Compare commits

...

23 Commits

Author SHA1 Message Date
torbinus 8e86e6d5c0 Neue Fotos für Doppelbärchen, Waffeln, Lakritz und Bonbons
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:33:14 +01:00
torbinus 72e664f714 Shop-Reihenfolge als eigenes Migrationsskript nachziehen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:24:52 +01:00
torbinus 81b04530ef Shop: Wachs und Kerzen nach den Lebensmitteln
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:19:06 +01:00
torbinus 23483ad9c5 Zugekaufte Honigseife nicht mehr im Shop (Entwurf)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:15:48 +01:00
torbinus 44d176e42e Highlights: Zwischentitel größer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:06:20 +01:00
torbinus dc78650fe3 Automaten: Hinweis zur Standortabfrage und klarere Meldung ohne Ortungsdienste
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:03:08 +01:00
torbinus 07667cc544 Automaten: Nächsten Automaten über den Standort im Browser finden
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:01:34 +01:00
torbinus ad6528c34e Automaten: Beispielfoto eines Automaten im Seitenkopf
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:59:14 +01:00
torbinus 355d24312b Automaten: Überschrift und Text in festen Zeilen statt zufälliger Umbrüche
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:55:00 +01:00
torbinus c9243f5a15 Mittendrin und Highlights: Fotos so verteilt, dass keins doppelt auf einer Seite steht
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:40:57 +01:00
torbinus bda2104146 Honig-Süßigkeiten: Zutaten und Nährwerte vom Team, Allergene hervorgehoben
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:36:58 +01:00
torbinus 8b8fbc5f2c Mittendrin und Highlights: echtes Foto neben dem Text statt Text auf Stockfoto
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:36:12 +01:00
torbinus 6a459ccece Kontakt: Porträt kleiner und mittig neben dem Formular
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:27:21 +01:00
torbinus 537ea08bd6 Kontakt: Ansprechpartnerin statt gezeichneter Deutschlandkarte
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:24:31 +01:00
torbinus 947063118c Unternehmenslogo auf den Business-Seiten, Texte für Honiglöffel und Essig
- Business-Seiten zeigen das Logo "modern beekeeping" statt des
  Produktlogos "Hamburger Stadtimkerei"
- Honiglöffel und Honig-Balsamico-Essig mit den Texten vom Team,
  per eigenem Migrationsskript

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:52:48 +01:00
torbinus cab8c749d4 Shop-Feinschliff: neue Honigtexte, Seife, Essig, Reihenfolge
- Kategorien: erst alle Produkte, dann Gutschein, Patenschaft, Kurs, Abo
- Gutschein und Kurs ohne Versand-, Lieferzeit- und Abfüllhinweise
- Neue Beschreibungen für elf Honigsorten, Subline für Himbeerblüte
- Honig-Seife: handgemacht im Untertitel, Text mit INCI-Liste
- Shop-Raster zeigt den Untertitel auch bei Nicht-Honig-Produkten
- Honig-Balsamico-Essig 0,25 l für 12,90 €, Grundpreis je Liter
- Honiglöffel 5,90 €
- Automaten: neuer Titel und Text

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:39:36 +01:00
torbinus b6f03f64aa Shop-Adresse für Links in Mails getrennt einstellbar
STOREFRONT_URL kam bisher immer aus MEDUSA_BACKEND_URL. Auf dem Testsystem
zeigten Einladungs- und Passwort-Links dadurch auf das Backend (:9001).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 13:10:25 +01:00
torbinus 8b25be4723 Einladung ins Firmenportal gilt erst als verschickt, wenn die Mail raus ist
Ohne Mailserver schrieb Medusa die Mail nur ins Log, im Admin stand
trotzdem "Eingeladen".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:54:13 +01:00
torbinus 9b368f9b7a Firmenkunden-CRM mit B2B-Patenschaften und Firmenportal
Admin: Firmen mit Vertriebsstufe und Wiedervorlage, Ansprechpartner mit
Einladung ins Portal, B2B-Patenschaften mit Lieferungen und Neuigkeiten,
private Dokumente, Notizen und Anfragen.
Portal unter /konto/firma: Patenschaften, Lieferungen, Neuigkeiten,
Dokument-Download und Anfrageformular.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:11:03 +01:00
torbinus 22d3e25fe2 Neue Fotos für Linden-, Sommerblüten- und Sonnenblumenhonig
Frühstücks- und Outdoor-Aufnahme, ohne Studio; Frühstück ist das Hauptbild.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:11:02 +01:00
torbinus 288527aa18 Datei-Uploads funktionieren wieder mit Adressen ohne Domain
Der lokale Dateianbieter baut die Adresse mit new URL(backend_url) und
scheiterte an "/static" mit "Invalid URL" – jeder Upload brach ab,
auch Produktbilder im Admin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:11:02 +01:00
torbinus 576ef42c43 Seed-Skript läuft im gebauten Image nicht noch einmal
Medusa merkt sich Migrationsskripte samt Dateiendung. Lokal steht
initial-data-seed.ts als erledigt, im Image heißt die Datei .js und galt als
neu. Sie scheiterte dann an den vorhandenen Regionen, brach die Migration ab,
bevor das Kerzenskript drankam, und hinterließ einen zweiten Verkaufskanal
samt API-Schlüssel. Jetzt tut sie nichts, sobald es eine Region gibt.

Das Kerzenskript nimmt für neue Produkte den ältesten Verkaufskanal, damit
ein solcher doppelter Kanal nicht stört.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:35:49 +01:00
torbinus 872535d17d Neue Bienenwachskerzen mit Farbwahl, Honiglöffel unter Zubehör
Sieben handgemachte Kerzen lösen die alten aus der Shopify-Übernahme ab:
Bubble-Würfel, Regenbogen-, Tropfen-, Lampion-, Bubble-Stumpen-, Rillen-
und Tannenbaumkerze. Jede gibt es in Honiggelb und Elfenbeinweiß, als
Variante, damit die Farbe in der Bestellung steht; über der Auswahl steht
"Farbe" statt "Variante". Hauptbild ist jeweils das schlichte Paar aus
heller und dunkler Kerze, dazu das weihnachtliche.

Der Adventskranz wird nicht verkauft, seine Bilder stehen bei der
Rillenkerze. Das alte Produkt "Bienenwachskerzen" ist Entwurf, nicht
gelöscht. Der Honiglöffel steht in der neuen Kategorie "Zubehör".

Die Bilder liefert das Frontend aus, so kommen sie mit dem Image auf jedes
System, ohne Kopieren ins Upload-Volume. Die Daten bringt ein
Migrationsskript mit, das der migrate-Dienst beim Ausrollen einmal ausführt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:04:31 +01:00
117 changed files with 6132 additions and 112 deletions
+7 -1
View File
@@ -91,12 +91,18 @@ module.exports = defineConfig({
// Honig-Abos: eigenes Modell, weil Medusa keine Abos kennt.
resolve: "./src/modules/subscription",
},
{
// Firmenkunden (CRM) mit eigenen B2B-Patenschaften und Firmenportal.
resolve: "./src/modules/b2b",
},
{
resolve: "@medusajs/medusa/file",
options: {
providers: [
{
resolve: "@medusajs/file-local",
// Wie @medusajs/file-local, nur mit Adressen ohne Domain —
// siehe src/modules/file-relative.
resolve: "./src/modules/file-relative",
id: "local",
options: {
// Bewusst ohne Domain: Die Adresse landet so in der Datenbank,
+1
View File
@@ -29,6 +29,7 @@
"@medusajs/cli": "2.17.2",
"@medusajs/dashboard": "2.17.2",
"@medusajs/draft-order": "2.17.2",
"@medusajs/file-local": "2.17.2",
"@medusajs/framework": "2.17.2",
"@medusajs/loyalty-plugin": "2.17.2",
"@medusajs/medusa": "2.17.2",
+219
View File
@@ -0,0 +1,219 @@
import { Button, Drawer, Input, Label, Select, Switch, Textarea, toast } from "@medusajs/ui";
import { useEffect, useState } from "react";
/** Gemeinsames für die Firmenkunden-Seiten im Admin. */
/** Zu einer Admin-Seite wechseln, z. B. gehe("/firmenkunden"). */
export function gehe(pfad: string) {
window.location.assign(`/app${pfad}`);
}
export async function api<T = any>(pfad: string, init?: { method?: string; body?: unknown }): Promise<T> {
const res = await fetch(`/admin/b2b${pfad}`, {
method: init?.method ?? "GET",
credentials: "include",
headers: init?.body !== undefined ? { "Content-Type": "application/json" } : undefined,
body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,
});
const json = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(json?.message ?? `Fehler ${res.status}`);
return json;
}
/** Führt eine Aktion aus und meldet Fehler als Toast. Gibt `true` bei Erfolg. */
export async function versuche(aktion: () => Promise<unknown>, erfolg?: string): Promise<boolean> {
try {
await aktion();
if (erfolg) toast.success(erfolg);
return true;
} catch (e) {
toast.error("Fehler", { description: e instanceof Error ? e.message : "Unbekannter Fehler." });
return false;
}
}
export const STUFEN: Record<string, { label: string; farbe: "grey" | "blue" | "green" | "red" | "orange" }> = {
lead: { label: "Interessent", farbe: "blue" },
offer: { label: "Angebot", farbe: "orange" },
customer: { label: "Kunde", farbe: "green" },
inactive: { label: "Inaktiv", farbe: "grey" },
};
export const PATEN_STATUS: Record<string, { label: string; farbe: "grey" | "blue" | "green" | "red" | "orange" }> = {
requested: { label: "Angefragt", farbe: "blue" },
offer: { label: "Angebot", farbe: "orange" },
active: { label: "Aktiv", farbe: "green" },
renewal: { label: "Verlängerung fällig", farbe: "red" },
ended: { label: "Beendet", farbe: "grey" },
};
export const LIEFER_STATUS: Record<string, string> = {
planned: "Geplant",
shipped: "Versendet",
delivered: "Zugestellt",
};
export const DOKUMENT_ARTEN: Record<string, string> = {
contract: "Vertrag",
certificate: "Urkunde",
invoice: "Rechnung",
offer: "Angebot",
other: "Sonstiges",
};
export const ANFRAGE_ARTEN: Record<string, string> = {
new: "Neue Patenschaft",
more: "Mehr Völker",
other: "Sonstiges",
};
export const ZUGANG: Record<string, { label: string; farbe: "grey" | "blue" | "green" | "red" | "orange" }> = {
active: { label: "Login aktiv", farbe: "green" },
invited: { label: "Eingeladen", farbe: "orange" },
expired: { label: "Einladung abgelaufen", farbe: "red" },
none: { label: "Kein Login", farbe: "grey" },
};
export const datum = (wert?: string | null) =>
wert ? new Date(wert).toLocaleDateString("de-DE", { dateStyle: "medium" }) : "–";
export const euro = (wert?: number | string | null) =>
wert === null || wert === undefined || wert === ""
? "–"
: Number(wert).toLocaleString("de-DE", { style: "currency", currency: "EUR" });
/** Datei → Base64 ohne den "data:…;base64,"-Vorspann. */
export function alsBase64(datei: File): Promise<string> {
return new Promise((resolve, reject) => {
const leser = new FileReader();
leser.onload = () => resolve(String(leser.result).split(",")[1] ?? "");
leser.onerror = () => reject(leser.error);
leser.readAsDataURL(datei);
});
}
export type Feld = {
key: string;
label: string;
art?: "text" | "textarea" | "date" | "number" | "select" | "switch" | "email";
optionen?: Record<string, string>;
pflicht?: boolean;
hinweis?: string;
};
/** Wert aus der API für ein Formularfeld aufbereiten. */
function anfangswert(feld: Feld, wert: any): any {
if (feld.art === "switch") return Boolean(wert);
if (wert === null || wert === undefined) return "";
if (feld.art === "date") return String(wert).slice(0, 10);
return String(wert);
}
/**
* Seitenleiste mit Formular. Ein Formular für alles: Firma, Ansprechpartner,
* Patenschaft, Lieferung … — nur die Felder unterscheiden sich.
*/
export function FormularDrawer(props: {
offen: boolean;
titel: string;
felder: Feld[];
werte?: Record<string, any>;
onClose: () => void;
onSave: (daten: Record<string, any>) => Promise<boolean>;
zusatz?: React.ReactNode;
}) {
const [daten, setDaten] = useState<Record<string, any>>({});
const [speichert, setSpeichert] = useState(false);
useEffect(() => {
if (props.offen) {
setDaten(Object.fromEntries(props.felder.map((f) => [f.key, anfangswert(f, props.werte?.[f.key])])));
}
}, [props.offen]);
const speichern = async () => {
setSpeichert(true);
const ok = await props.onSave(daten);
setSpeichert(false);
if (ok) props.onClose();
};
return (
<Drawer open={props.offen} onOpenChange={(o) => !o && props.onClose()}>
<Drawer.Content>
<Drawer.Header>
<Drawer.Title>{props.titel}</Drawer.Title>
</Drawer.Header>
<Drawer.Body className="flex flex-col gap-4 overflow-y-auto">
{props.felder.map((f) => (
<div key={f.key} className="flex flex-col gap-1.5">
<Label htmlFor={`f-${f.key}`}>
{f.label}
{f.pflicht ? " *" : ""}
</Label>
{f.art === "textarea" ? (
<Textarea
id={`f-${f.key}`}
rows={5}
value={daten[f.key] ?? ""}
onChange={(e) => setDaten({ ...daten, [f.key]: e.target.value })}
/>
) : f.art === "select" ? (
<Select value={daten[f.key] ?? ""} onValueChange={(v) => setDaten({ ...daten, [f.key]: v })}>
<Select.Trigger id={`f-${f.key}`}>
<Select.Value placeholder="Bitte wählen" />
</Select.Trigger>
<Select.Content>
{Object.entries(f.optionen ?? {}).map(([wert, label]) => (
<Select.Item key={wert} value={wert}>
{label}
</Select.Item>
))}
</Select.Content>
</Select>
) : f.art === "switch" ? (
<Switch
id={`f-${f.key}`}
checked={Boolean(daten[f.key])}
onCheckedChange={(v) => setDaten({ ...daten, [f.key]: v })}
/>
) : (
<Input
id={`f-${f.key}`}
type={f.art === "date" ? "date" : f.art === "number" ? "number" : f.art === "email" ? "email" : "text"}
value={daten[f.key] ?? ""}
onChange={(e) => setDaten({ ...daten, [f.key]: e.target.value })}
/>
)}
{f.hinweis && <span className="text-ui-fg-subtle txt-small">{f.hinweis}</span>}
</div>
))}
{props.zusatz}
</Drawer.Body>
<Drawer.Footer>
<Button variant="secondary" onClick={props.onClose}>
Abbrechen
</Button>
<Button onClick={speichern} isLoading={speichert}>
Speichern
</Button>
</Drawer.Footer>
</Drawer.Content>
</Drawer>
);
}
export const FIRMEN_FELDER: Feld[] = [
{ key: "name", label: "Firmenname", pflicht: true },
{ key: "stage", label: "Stufe", art: "select", optionen: Object.fromEntries(Object.entries(STUFEN).map(([k, v]) => [k, v.label])) },
{ key: "follow_up_at", label: "Wiedervorlage", art: "date" },
{ key: "source", label: "Herkunft", hinweis: "z. B. Messe, Empfehlung, Website" },
{ key: "street", label: "Straße und Hausnummer" },
{ key: "postal_code", label: "PLZ" },
{ key: "city", label: "Ort" },
{ key: "country", label: "Land", hinweis: "Ländercode, z. B. DE" },
{ key: "vat_id", label: "USt-IdNr." },
{ key: "email", label: "E-Mail (allgemein)", art: "email" },
{ key: "phone", label: "Telefon" },
{ key: "website", label: "Website" },
];
@@ -0,0 +1,703 @@
import { Badge, Button, Container, Heading, Label, Table, Text, Textarea, usePrompt } from "@medusajs/ui";
import { useEffect, useState } from "react";
import {
alsBase64,
ANFRAGE_ARTEN,
api,
datum,
DOKUMENT_ARTEN,
euro,
type Feld,
FIRMEN_FELDER,
FormularDrawer,
gehe,
LIEFER_STATUS,
PATEN_STATUS,
STUFEN,
versuche,
ZUGANG,
} from "../../../lib/b2b";
const KONTAKT_FELDER: Feld[] = [
{ key: "first_name", label: "Vorname" },
{ key: "last_name", label: "Nachname" },
{ key: "email", label: "E-Mail", art: "email", pflicht: true, hinweis: "Mit dieser Adresse meldet sich der Ansprechpartner im Portal an." },
{ key: "phone", label: "Telefon" },
{ key: "role", label: "Funktion" },
];
const PATEN_FELDER: Feld[] = [
{ key: "title", label: "Bezeichnung", pflicht: true, hinweis: "Sieht der Kunde, z. B. „2 Völker am Standort Hafencity“" },
{ key: "status", label: "Status", art: "select", optionen: Object.fromEntries(Object.entries(PATEN_STATUS).map(([k, v]) => [k, v.label])), hinweis: "„Angefragt“ ist im Portal noch nicht sichtbar." },
{ key: "colonies", label: "Anzahl Völker", art: "number" },
{ key: "location", label: "Standort" },
{ key: "start_date", label: "Beginn", art: "date" },
{ key: "end_date", label: "Ende", art: "date" },
{ key: "price", label: "Preis netto (€) für die Laufzeit", art: "number" },
{ key: "internal_note", label: "Interne Bemerkung", art: "textarea", hinweis: "Nur im Admin sichtbar." },
];
const LIEFER_FELDER: Feld[] = [
{ key: "title", label: "Was", pflicht: true, hinweis: "z. B. Honiglieferung Herbst" },
{ key: "quantity", label: "Menge", hinweis: "z. B. 120 Gläser à 250 g" },
{ key: "status", label: "Status", art: "select", optionen: LIEFER_STATUS },
{ key: "planned_at", label: "Geplant für", art: "date" },
{ key: "shipped_at", label: "Versendet am", art: "date" },
{ key: "tracking_number", label: "Sendungsnummer" },
];
const BERICHT_FELDER: Feld[] = [
{ key: "title", label: "Überschrift", pflicht: true },
{ key: "published_at", label: "Datum", art: "date", pflicht: true, hinweis: "Liegt das Datum in der Zukunft, erscheint der Bericht erst dann." },
{ key: "body", label: "Text", art: "textarea" },
];
type Formular = {
titel: string;
felder: Feld[];
werte?: Record<string, any>;
speichern: (daten: Record<string, any>) => Promise<unknown>;
erfolg: string;
art?: "bericht" | "dokument";
};
const heuteIso = () => new Date().toISOString().slice(0, 10);
const Abschnitt = (p: { titel: string; aktion?: React.ReactNode; children: React.ReactNode }) => (
<div className="px-6 py-5">
<div className="mb-3 flex items-center justify-between">
<Heading level="h2">{p.titel}</Heading>
{p.aktion}
</div>
{p.children}
</div>
);
const FirmaPage = () => {
// Die ID aus der Adresse statt über react-router: Im Projekt liegen zwei
// Versionen davon, und die Hooks finden dann den Router des Dashboards nicht.
const id = decodeURIComponent(window.location.pathname.split("/").filter(Boolean).pop() ?? "");
const fragen = usePrompt();
const [firma, setFirma] = useState<any>(null);
const [formular, setFormular] = useState<Formular | null>(null);
const [bilder, setBilder] = useState<string[]>([]);
const [datei, setDatei] = useState<File | null>(null);
const [laedtHoch, setLaedtHoch] = useState(false);
const [notiz, setNotiz] = useState("");
const laden = () =>
versuche(async () => {
const json = await api(`/companies/${id}`);
setFirma(json.company);
});
useEffect(() => {
laden();
}, [id]);
if (!firma) return <Container className="px-6 py-4">Lädt …</Container>;
const oeffnen = (f: Formular) => {
setBilder(f.werte?.images ?? []);
setDatei(null);
setFormular(f);
};
const loeschen = async (titel: string, pfad: string) => {
const ok = await fragen({ title: titel, description: "Das lässt sich nicht rückgängig machen.", confirmText: "Löschen", cancelText: "Abbrechen" });
if (ok && (await versuche(() => api(pfad, { method: "DELETE" }), "Gelöscht"))) laden();
};
const aendern = (pfad: string, body: Record<string, unknown>, erfolg?: string) =>
versuche(() => api(pfad, { method: "POST", body }), erfolg).then((ok) => ok && laden());
const bilderHochladen = async (dateien: FileList | null) => {
if (!dateien?.length) return;
setLaedtHoch(true);
await versuche(async () => {
const neu: string[] = [];
for (const d of Array.from(dateien)) {
const json = await api("/images", { method: "POST", body: { mime_type: d.type, content: await alsBase64(d) } });
neu.push(json.url);
}
setBilder((alt) => [...alt, ...neu]);
});
setLaedtHoch(false);
};
const stufe = STUFEN[firma.stage];
const offeneAnfragen = firma.inquiries.filter((a: any) => a.status === "open");
const patenOptionen = Object.fromEntries([["none", "Keine bestimmte"], ...firma.sponsorships.map((p: any) => [p.id, p.title])]);
return (
<div className="flex flex-col gap-3">
<Container className="divide-y p-0">
<div className="flex flex-wrap items-start justify-between gap-3 px-6 py-4">
<div>
<Button size="small" variant="transparent" className="-ml-2 mb-1" onClick={() => gehe("/firmenkunden")}>
← Firmenkunden
</Button>
<div className="flex items-center gap-2">
<Heading level="h1">{firma.name}</Heading>
<Badge color={stufe?.farbe}>{stufe?.label ?? firma.stage}</Badge>
</div>
</div>
<div className="flex gap-2">
<Button
size="small"
variant="secondary"
onClick={() =>
oeffnen({
titel: "Firma bearbeiten",
felder: FIRMEN_FELDER,
werte: firma,
speichern: (d) => api(`/companies/${id}`, { method: "POST", body: d }),
erfolg: "Gespeichert",
})
}
>
Bearbeiten
</Button>
<Button
size="small"
variant="danger"
onClick={async () => {
const ok = await fragen({
title: `${firma.name} löschen?`,
description: "Ansprechpartner, Patenschaften, Dokumente und Notizen werden mitgelöscht. Kundenkonten bleiben bestehen.",
confirmText: "Löschen",
cancelText: "Abbrechen",
});
if (ok && (await versuche(() => api(`/companies/${id}`, { method: "DELETE" }), "Firma gelöscht"))) gehe("/firmenkunden");
}}
>
Löschen
</Button>
</div>
</div>
<div className="grid grid-cols-2 gap-x-8 gap-y-2 px-6 py-4 md:grid-cols-4">
{[
["Adresse", [firma.street, [firma.postal_code, firma.city].filter(Boolean).join(" "), firma.country].filter(Boolean).join(", ")],
["USt-IdNr.", firma.vat_id],
["E-Mail", firma.email],
["Telefon", firma.phone],
["Website", firma.website],
["Herkunft", firma.source],
["Wiedervorlage", firma.follow_up_at ? datum(firma.follow_up_at) : null],
["Angelegt", datum(firma.created_at)],
].map(([label, wert]) => (
<div key={label as string}>
<Text size="xsmall" className="text-ui-fg-subtle">
{label}
</Text>
<Text size="small">{wert || "–"}</Text>
</div>
))}
</div>
</Container>
{offeneAnfragen.length > 0 && (
<Container className="p-0">
<Abschnitt titel="Offene Anfragen aus dem Portal">
<div className="flex flex-col gap-3">
{offeneAnfragen.map((a: any) => (
<div key={a.id} className="bg-ui-bg-subtle flex flex-wrap items-start justify-between gap-3 rounded-lg p-4">
<div>
<Text size="small" weight="plus">
{ANFRAGE_ARTEN[a.kind]}
{a.colonies ? ` · ${a.colonies} Völker` : ""} · {datum(a.created_at)}
</Text>
{a.message && <Text size="small" className="mt-1 whitespace-pre-wrap">{a.message}</Text>}
</div>
<div className="flex gap-2">
{a.kind !== "other" && (
<Button
size="small"
variant="secondary"
onClick={() =>
oeffnen({
titel: "Patenschaft aus Anfrage anlegen",
felder: PATEN_FELDER,
werte: { status: "offer", colonies: a.colonies ?? 1, title: `${a.colonies ?? 1} ${(a.colonies ?? 1) > 1 ? "Bienenvölker" : "Bienenvolk"}` },
speichern: async (d) => {
await api("/sponsorships", { method: "POST", body: { ...d, company_id: id } });
await api(`/inquiries/${a.id}`, { method: "POST", body: { status: "done" } });
},
erfolg: "Patenschaft angelegt, Anfrage erledigt",
})
}
>
Patenschaft anlegen
</Button>
)}
<Button size="small" variant="secondary" onClick={() => aendern(`/inquiries/${a.id}`, { status: "done" }, "Erledigt")}>
Erledigt
</Button>
</div>
</div>
))}
</div>
</Abschnitt>
</Container>
)}
<Container className="p-0">
<Abschnitt
titel="Ansprechpartner"
aktion={
<Button
size="small"
variant="secondary"
onClick={() =>
oeffnen({
titel: "Ansprechpartner hinzufügen",
felder: KONTAKT_FELDER,
speichern: (d) => api("/contacts", { method: "POST", body: { ...d, company_id: id } }),
erfolg: "Hinzugefügt",
})
}
>
Hinzufügen
</Button>
}
>
{firma.contacts.length === 0 ? (
<Text size="small" className="text-ui-fg-subtle">
Noch keine Ansprechpartner.
</Text>
) : (
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Kontakt</Table.HeaderCell>
<Table.HeaderCell>Portal</Table.HeaderCell>
<Table.HeaderCell />
</Table.Row>
</Table.Header>
<Table.Body>
{firma.contacts.map((k: any) => (
<Table.Row key={k.id}>
<Table.Cell>
<div>{[k.first_name, k.last_name].filter(Boolean).join(" ") || "–"}</div>
{k.role && <div className="text-ui-fg-subtle txt-small">{k.role}</div>}
</Table.Cell>
<Table.Cell>
<div>{k.email}</div>
{k.phone && <div className="text-ui-fg-subtle txt-small">{k.phone}</div>}
</Table.Cell>
<Table.Cell>
<Badge size="2xsmall" color={ZUGANG[k.access].farbe}>
{ZUGANG[k.access].label}
</Badge>
</Table.Cell>
<Table.Cell>
<div className="flex justify-end gap-2">
{k.access !== "active" && (
<Button
size="small"
variant="secondary"
onClick={() =>
versuche(async () => {
const json = await api(`/contacts/${k.id}/invite`, { method: "POST" });
await laden();
return json;
}, k.access === "none" ? "Einladung verschickt" : "Einladung erneut verschickt")
}
>
{k.access === "none" ? "Einladen" : "Erneut einladen"}
</Button>
)}
<Button
size="small"
variant="secondary"
onClick={() =>
oeffnen({
titel: "Ansprechpartner bearbeiten",
felder: KONTAKT_FELDER,
werte: k,
speichern: (d) => api(`/contacts/${k.id}`, { method: "POST", body: d }),
erfolg: "Gespeichert",
})
}
>
Bearbeiten
</Button>
<Button size="small" variant="transparent" onClick={() => loeschen("Ansprechpartner entfernen?", `/contacts/${k.id}`)}>
Entfernen
</Button>
</div>
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
)}
</Abschnitt>
</Container>
<Container className="p-0">
<Abschnitt
titel="B2B-Patenschaften"
aktion={
<Button
size="small"
variant="secondary"
onClick={() =>
oeffnen({
titel: "Patenschaft anlegen",
felder: PATEN_FELDER,
werte: { status: "offer", colonies: 1 },
speichern: (d) => api("/sponsorships", { method: "POST", body: { ...d, company_id: id } }),
erfolg: "Patenschaft angelegt",
})
}
>
Anlegen
</Button>
}
>
{firma.sponsorships.length === 0 && (
<Text size="small" className="text-ui-fg-subtle">
Noch keine Patenschaften.
</Text>
)}
<div className="flex flex-col gap-4">
{firma.sponsorships.map((p: any) => (
<div key={p.id} className="shadow-elevation-card-rest rounded-lg">
<div className="flex flex-wrap items-start justify-between gap-3 p-4">
<div>
<div className="flex items-center gap-2">
<Text weight="plus">{p.title}</Text>
<Badge size="2xsmall" color={PATEN_STATUS[p.status]?.farbe}>
{PATEN_STATUS[p.status]?.label}
</Badge>
</div>
<Text size="small" className="text-ui-fg-subtle mt-1">
{p.colonies} {p.colonies === 1 ? "Volk" : "Völker"}
{p.location ? ` · ${p.location}` : ""} · {datum(p.start_date)} – {datum(p.end_date)} · {euro(p.price)} netto
</Text>
{p.internal_note && (
<Text size="small" className="text-ui-fg-subtle mt-1 whitespace-pre-wrap italic">
{p.internal_note}
</Text>
)}
</div>
<div className="flex gap-2">
<Button
size="small"
variant="secondary"
onClick={() =>
oeffnen({
titel: "Patenschaft bearbeiten",
felder: PATEN_FELDER,
werte: p,
speichern: (d) => api(`/sponsorships/${p.id}`, { method: "POST", body: d }),
erfolg: "Gespeichert",
})
}
>
Bearbeiten
</Button>
<Button size="small" variant="transparent" onClick={() => loeschen("Patenschaft löschen?", `/sponsorships/${p.id}`)}>
Löschen
</Button>
</div>
</div>
<div className="border-ui-border-base grid gap-4 border-t p-4 md:grid-cols-2">
<div>
<div className="mb-2 flex items-center justify-between">
<Text size="small" weight="plus">
Lieferungen
</Text>
<Button
size="small"
variant="transparent"
onClick={() =>
oeffnen({
titel: "Lieferung hinzufügen",
felder: LIEFER_FELDER,
werte: { status: "planned" },
speichern: (d) => api("/deliveries", { method: "POST", body: { ...d, sponsorship_id: p.id } }),
erfolg: "Lieferung angelegt",
})
}
>
+ Lieferung
</Button>
</div>
{p.deliveries.length === 0 && <Text size="small" className="text-ui-fg-subtle">Keine.</Text>}
{p.deliveries.map((l: any) => (
<div key={l.id} className="flex items-center justify-between gap-2 py-1">
<Text size="small">
{l.title}
{l.quantity ? ` · ${l.quantity}` : ""}
<span className="text-ui-fg-subtle">
{" "}
· {LIEFER_STATUS[l.status]} {l.status === "planned" ? datum(l.planned_at) : datum(l.shipped_at)}
</span>
</Text>
<div className="flex shrink-0 gap-1">
<Button
size="small"
variant="transparent"
onClick={() =>
oeffnen({
titel: "Lieferung bearbeiten",
felder: LIEFER_FELDER,
werte: l,
speichern: (d) => api(`/deliveries/${l.id}`, { method: "POST", body: d }),
erfolg: "Gespeichert",
})
}
>
Bearbeiten
</Button>
<Button size="small" variant="transparent" onClick={() => loeschen("Lieferung löschen?", `/deliveries/${l.id}`)}>
×
</Button>
</div>
</div>
))}
</div>
<div>
<div className="mb-2 flex items-center justify-between">
<Text size="small" weight="plus">
Neuigkeiten vom Volk
</Text>
<Button
size="small"
variant="transparent"
onClick={() =>
oeffnen({
titel: "Neuigkeit schreiben",
felder: BERICHT_FELDER,
werte: { published_at: heuteIso() },
speichern: (d) => api("/reports", { method: "POST", body: { ...d, sponsorship_id: p.id } }),
erfolg: "Neuigkeit veröffentlicht",
art: "bericht",
})
}
>
+ Neuigkeit
</Button>
</div>
{p.reports.length === 0 && <Text size="small" className="text-ui-fg-subtle">Keine.</Text>}
{p.reports.map((r: any) => (
<div key={r.id} className="flex items-center justify-between gap-2 py-1">
<Text size="small">
{r.title}
<span className="text-ui-fg-subtle">
{" "}
· {datum(r.published_at)}
{r.images?.length ? ` · ${r.images.length} Foto${r.images.length > 1 ? "s" : ""}` : ""}
</span>
</Text>
<div className="flex shrink-0 gap-1">
<Button
size="small"
variant="transparent"
onClick={() =>
oeffnen({
titel: "Neuigkeit bearbeiten",
felder: BERICHT_FELDER,
werte: r,
speichern: (d) => api(`/reports/${r.id}`, { method: "POST", body: d }),
erfolg: "Gespeichert",
art: "bericht",
})
}
>
Bearbeiten
</Button>
<Button size="small" variant="transparent" onClick={() => loeschen("Neuigkeit löschen?", `/reports/${r.id}`)}>
×
</Button>
</div>
</div>
))}
</div>
</div>
</div>
))}
</div>
</Abschnitt>
</Container>
<Container className="p-0">
<Abschnitt
titel="Dokumente"
aktion={
<Button
size="small"
variant="secondary"
onClick={() =>
oeffnen({
titel: "Dokument hochladen",
felder: [
{ key: "title", label: "Titel", pflicht: true },
{ key: "kind", label: "Art", art: "select", optionen: DOKUMENT_ARTEN },
{ key: "sponsorship_id", label: "Gehört zu Patenschaft", art: "select", optionen: patenOptionen },
{ key: "visible", label: "Im Portal sichtbar", art: "switch" },
],
werte: { kind: "contract", visible: true, sponsorship_id: "none" },
speichern: async () => undefined,
erfolg: "Hochgeladen",
art: "dokument",
})
}
>
Hochladen
</Button>
}
>
{firma.documents.length === 0 ? (
<Text size="small" className="text-ui-fg-subtle">
Noch keine Dokumente.
</Text>
) : (
<Table>
<Table.Body>
{firma.documents.map((d: any) => (
<Table.Row key={d.id}>
<Table.Cell>
<a className="text-ui-fg-interactive hover:underline" href={`/admin/b2b/documents/${d.id}/download`}>
{d.title}
</a>
<div className="text-ui-fg-subtle txt-small">{d.file_name}</div>
</Table.Cell>
<Table.Cell>{DOKUMENT_ARTEN[d.kind]}</Table.Cell>
<Table.Cell>{datum(d.created_at)}</Table.Cell>
<Table.Cell>
<Badge size="2xsmall" color={d.visible ? "green" : "grey"}>
{d.visible ? "Im Portal" : "Nur intern"}
</Badge>
</Table.Cell>
<Table.Cell>
<div className="flex justify-end gap-1">
<Button size="small" variant="transparent" onClick={() => aendern(`/documents/${d.id}`, { visible: !d.visible })}>
{d.visible ? "Verbergen" : "Freigeben"}
</Button>
<Button size="small" variant="transparent" onClick={() => loeschen("Dokument löschen?", `/documents/${d.id}`)}>
Löschen
</Button>
</div>
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
)}
</Abschnitt>
</Container>
<Container className="p-0">
<Abschnitt titel="Notizen">
<div className="flex flex-col gap-2">
<Textarea rows={3} placeholder="Telefonat, Treffen, Absprache …" value={notiz} onChange={(e) => setNotiz(e.target.value)} />
<div>
<Button
size="small"
variant="secondary"
disabled={!notiz.trim()}
onClick={async () => {
if (await versuche(() => api("/notes", { method: "POST", body: { body: notiz, company_id: id } }))) {
setNotiz("");
laden();
}
}}
>
Notiz speichern
</Button>
</div>
</div>
<div className="mt-4 flex flex-col gap-3">
{firma.notes.map((n: any) => (
<div key={n.id} className="border-ui-border-base border-l-2 pl-3">
<Text size="xsmall" className="text-ui-fg-subtle">
{new Date(n.created_at).toLocaleString("de-DE", { dateStyle: "medium", timeStyle: "short" })}
{n.author ? ` · ${n.author}` : ""}
<button className="ml-2 hover:underline" onClick={() => loeschen("Notiz löschen?", `/notes/${n.id}`)}>
löschen
</button>
</Text>
<Text size="small" className="whitespace-pre-wrap">
{n.body}
</Text>
</div>
))}
</div>
{firma.inquiries.some((a: any) => a.status === "done") && (
<Text size="xsmall" className="text-ui-fg-subtle mt-4">
Erledigte Anfragen:{" "}
{firma.inquiries
.filter((a: any) => a.status === "done")
.map((a: any) => `${ANFRAGE_ARTEN[a.kind]} (${datum(a.created_at)})`)
.join(", ")}
</Text>
)}
</Abschnitt>
</Container>
<FormularDrawer
offen={Boolean(formular)}
titel={formular?.titel ?? ""}
felder={formular?.felder ?? []}
werte={formular?.werte}
onClose={() => setFormular(null)}
onSave={(daten) =>
versuche(async () => {
if (!formular) return;
if (formular.art === "dokument") {
if (!datei) throw new Error("Bitte eine Datei wählen.");
await api(`/companies/${id}/documents`, {
method: "POST",
body: { ...daten, sponsorship_id: daten.sponsorship_id === "none" ? null : daten.sponsorship_id, file_name: datei.name, mime_type: datei.type, content: await alsBase64(datei) },
});
} else if (formular.art === "bericht") {
await formular.speichern({ ...daten, images: bilder });
} else {
await formular.speichern(daten);
}
await laden();
}, formular?.erfolg)
}
zusatz={
formular?.art === "bericht" ? (
<div className="flex flex-col gap-1.5">
<Label>Fotos</Label>
<input type="file" accept="image/jpeg,image/png,image/webp" multiple onChange={(e) => bilderHochladen(e.target.files)} />
{laedtHoch && <Text size="small">Lädt hoch …</Text>}
<div className="mt-2 grid grid-cols-3 gap-2">
{bilder.map((url) => (
<div key={url} className="relative">
<img src={url} className="aspect-square w-full rounded object-cover" />
<button
type="button"
className="bg-ui-bg-base absolute right-1 top-1 rounded px-1.5 text-xs shadow"
onClick={() => setBilder(bilder.filter((b) => b !== url))}
>
×
</button>
</div>
))}
</div>
</div>
) : formular?.art === "dokument" ? (
<div className="flex flex-col gap-1.5">
<Label>Datei *</Label>
<input type="file" accept=".pdf,.jpg,.jpeg,.png,.docx,.xlsx" onChange={(e) => setDatei(e.target.files?.[0] ?? null)} />
<Text size="small" className="text-ui-fg-subtle">
PDF, JPG, PNG, Word oder Excel, bis 18 MB.
</Text>
</div>
) : null
}
/>
</div>
);
};
export default FirmaPage;
@@ -0,0 +1,149 @@
import { defineRouteConfig } from "@medusajs/admin-sdk";
import { Buildings } from "@medusajs/icons";
import { Badge, Button, Container, Heading, Input, Table, Text } from "@medusajs/ui";
import { useEffect, useMemo, useState } from "react";
import { api, datum, FIRMEN_FELDER, FormularDrawer, gehe, STUFEN, versuche } from "../../lib/b2b";
type Firma = {
id: string;
name: string;
city: string | null;
stage: string;
follow_up_at: string | null;
contacts: number;
logins: number;
colonies: number;
sponsorships: number;
open_inquiries: number;
};
const FirmenkundenPage = () => {
const [firmen, setFirmen] = useState<Firma[] | null>(null);
const [filter, setFilter] = useState<string>("alle");
const [suche, setSuche] = useState("");
const [neu, setNeu] = useState(false);
const laden = () =>
versuche(async () => {
const json = await api<{ companies: Firma[] }>("/companies");
setFirmen(json.companies);
});
useEffect(() => {
laden();
}, []);
const heute = new Date();
const sichtbar = useMemo(() => {
const liste = (firmen ?? []).filter(
(f) =>
(filter === "alle" || f.stage === filter) &&
(!suche || `${f.name} ${f.city ?? ""}`.toLowerCase().includes(suche.toLowerCase()))
);
// Fällige Wiedervorlagen und offene Anfragen zuerst — das ist die Arbeit von heute.
const dringend = (f: Firma) =>
f.open_inquiries > 0 || (f.follow_up_at && new Date(f.follow_up_at) <= heute) ? 0 : 1;
return liste.sort((a, b) => dringend(a) - dringend(b) || a.name.localeCompare(b.name, "de"));
}, [firmen, filter, suche]);
const anzahl = (stufe: string) => (firmen ?? []).filter((f) => f.stage === stufe).length;
return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
<div>
<Heading level="h1">Firmenkunden</Heading>
<Text className="text-ui-fg-subtle mt-1" size="small">
Interessenten, Kunden und ihre B2B-Patenschaften.
</Text>
</div>
<Button size="small" onClick={() => setNeu(true)}>
Firma anlegen
</Button>
</div>
<div className="flex flex-wrap items-center gap-2 px-6 py-3">
{[["alle", `Alle (${firmen?.length ?? 0})`], ...Object.entries(STUFEN).map(([k, v]) => [k, `${v.label} (${anzahl(k)})`])].map(
([wert, label]) => (
<Button key={wert} size="small" variant={filter === wert ? "primary" : "secondary"} onClick={() => setFilter(wert)}>
{label}
</Button>
)
)}
<div className="ml-auto w-64">
<Input size="small" type="search" placeholder="Suchen" value={suche} onChange={(e) => setSuche(e.target.value)} />
</div>
</div>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Firma</Table.HeaderCell>
<Table.HeaderCell>Stufe</Table.HeaderCell>
<Table.HeaderCell>Völker aktiv</Table.HeaderCell>
<Table.HeaderCell>Ansprechpartner</Table.HeaderCell>
<Table.HeaderCell>Wiedervorlage</Table.HeaderCell>
<Table.HeaderCell>Offen</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{sichtbar.map((f) => {
const faellig = f.follow_up_at && new Date(f.follow_up_at) <= heute;
return (
<Table.Row key={f.id} className="cursor-pointer" onClick={() => gehe(`/firmenkunden/${f.id}`)}>
<Table.Cell>
<div className="font-medium">{f.name}</div>
{f.city && <div className="text-ui-fg-subtle txt-small">{f.city}</div>}
</Table.Cell>
<Table.Cell>
<Badge size="2xsmall" color={STUFEN[f.stage]?.farbe}>
{STUFEN[f.stage]?.label ?? f.stage}
</Badge>
</Table.Cell>
<Table.Cell>{f.colonies || "–"}</Table.Cell>
<Table.Cell>
{f.contacts}
{f.logins > 0 && <span className="text-ui-fg-subtle"> ({f.logins} mit Login)</span>}
</Table.Cell>
<Table.Cell className={faellig ? "text-ui-fg-error font-medium" : ""}>{datum(f.follow_up_at)}</Table.Cell>
<Table.Cell>
{f.open_inquiries > 0 && (
<Badge size="2xsmall" color="red">
{f.open_inquiries} Anfrage{f.open_inquiries > 1 ? "n" : ""}
</Badge>
)}
</Table.Cell>
</Table.Row>
);
})}
{firmen && sichtbar.length === 0 && (
<Table.Row>
<Table.Cell className="text-ui-fg-subtle">Keine Firmen gefunden.</Table.Cell>
</Table.Row>
)}
</Table.Body>
</Table>
<FormularDrawer
offen={neu}
titel="Firma anlegen"
felder={FIRMEN_FELDER}
werte={{ stage: "lead", country: "DE" }}
onClose={() => setNeu(false)}
onSave={(daten) =>
versuche(async () => {
const json = await api("/companies", { method: "POST", body: daten });
gehe(`/firmenkunden/${json.company.id}`);
}, "Firma angelegt")
}
/>
</Container>
);
};
export const config = defineRouteConfig({
label: "Firmenkunden",
icon: Buildings,
});
export default FirmenkundenPage;
@@ -0,0 +1,41 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { Modules } from "@medusajs/framework/utils";
import { b2b, Eingabefehler, ENTITAETEN, kontaktOhneGeheimnis, pruefe } from "../../../../../lib/b2b";
export async function POST(req: MedusaRequest, res: MedusaResponse) {
const art = ENTITAETEN[req.params.entity];
if (!art) return void res.status(404).json({ message: "Unbekannt." });
try {
const daten = pruefe((req.body ?? {}) as Record<string, unknown>, art.felder, "aendern");
const service = b2b(req.scope);
if (req.params.entity === "contacts" && "email" in daten) {
// Mit Login hängt die Adresse am Kundenkonto; geändert wird sie dort.
const kontakt = await service.retrieveContact(req.params.id);
if (kontakt.customer_id && kontakt.email !== daten.email) {
throw new Eingabefehler("Die Adresse eines Ansprechpartners mit Login lässt sich hier nicht ändern.");
}
}
let neu = await service[`update${art.plural}`]({ id: req.params.id, ...daten });
if (req.params.entity === "contacts") neu = kontaktOhneGeheimnis(neu);
if (req.params.entity === "documents") delete neu.file_key;
res.json({ [art.name.toLowerCase()]: neu });
} catch (e) {
if (e instanceof Eingabefehler) return void res.status(400).json({ message: e.message });
throw e;
}
}
/** Löschen. Ein Ansprechpartner verliert damit den Portalzugang, sein Kundenkonto bleibt. */
export async function DELETE(req: MedusaRequest, res: MedusaResponse) {
const art = ENTITAETEN[req.params.entity];
if (!art) return void res.status(404).json({ message: "Unbekannt." });
const service = b2b(req.scope);
if (req.params.entity === "documents") {
const dokument = await service.retrieveDocument(req.params.id);
await service.deleteDocuments(req.params.id);
await (req.scope.resolve(Modules.FILE) as any).deleteFiles(dokument.file_key).catch(() => undefined);
} else {
await service[`delete${art.plural}`](req.params.id);
}
res.json({ id: req.params.id, deleted: true });
}
@@ -0,0 +1,32 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { b2b, Eingabefehler, ENTITAETEN, kontaktOhneGeheimnis, pruefe } from "../../../../lib/b2b";
/**
* Unterobjekt anlegen: Ansprechpartner, Patenschaft, Lieferung, Bericht,
* Notiz. Die Firma bzw. Patenschaft kommt als `company_id` /
* `sponsorship_id` im Body.
*/
export async function POST(req: MedusaRequest, res: MedusaResponse) {
const art = ENTITAETEN[req.params.entity];
if (!art?.parent) return void res.status(404).json({ message: "Unbekannt." });
const body = (req.body ?? {}) as Record<string, unknown>;
try {
const service = b2b(req.scope);
const parentId = String(body[art.parent] ?? "");
if (art.parent === "company_id") await service.retrieveCompany(parentId);
else await service.retrieveSponsorship(parentId);
const daten = pruefe(body, art.felder, "anlegen");
if (req.params.entity === "notes") {
// Wer die Notiz geschrieben hat, steht später im Verlauf.
const userId = (req as any).auth_context?.actor_id;
const user = userId ? await (req.scope.resolve("user") as any).retrieveUser(userId).catch(() => null) : null;
daten.author = user ? [user.first_name, user.last_name].filter(Boolean).join(" ") || user.email : null;
}
const neu = await service[`create${art.plural}`]({ ...daten, [art.parent]: parentId });
res.json({ [art.name.toLowerCase()]: req.params.entity === "contacts" ? kontaktOhneGeheimnis(neu) : neu });
} catch (e) {
if (e instanceof Eingabefehler) return void res.status(400).json({ message: e.message });
throw e;
}
}
@@ -0,0 +1,25 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { b2b, dateiAblegen, Eingabefehler, ENTITAETEN, pruefe, sichererDateiname } from "../../../../../../lib/b2b";
/** Dokument hochladen: { title, kind, visible, sponsorship_id, file_name, mime_type, content (Base64) }. */
export async function POST(req: MedusaRequest, res: MedusaResponse) {
const body = (req.body ?? {}) as Record<string, unknown>;
try {
const service = b2b(req.scope);
await service.retrieveCompany(req.params.id);
const daten = pruefe(body, ENTITAETEN.documents.felder, "anlegen");
const datei = await dateiAblegen(req.scope, body, "dokument");
const dokument = await service.createDocuments({
...daten,
company_id: req.params.id,
file_key: datei.key,
file_name: sichererDateiname(body.file_name, `dokument${datei.mime === "application/pdf" ? ".pdf" : ""}`),
mime_type: datei.mime,
});
const { file_key: _k, ...ohneSchluessel } = dokument;
res.json({ document: ohneSchluessel });
} catch (e) {
if (e instanceof Eingabefehler) return void res.status(400).json({ message: e.message });
throw e;
}
}
@@ -0,0 +1,59 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { Modules } from "@medusajs/framework/utils";
import { b2b, COMPANY_FELDER, Eingabefehler, kontaktOhneGeheimnis, pruefe } from "../../../../../lib/b2b";
const neuesteZuerst = (a: any, b: any) => +new Date(b.created_at) - +new Date(a.created_at);
/** Eine Firma mit allem, was dazugehört. */
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const firma = await b2b(req.scope).retrieveCompany(req.params.id, {
relations: [
"contacts",
"sponsorships",
"sponsorships.deliveries",
"sponsorships.reports",
"documents",
"notes",
"inquiries",
],
});
res.json({
company: {
...firma,
contacts: firma.contacts.map(kontaktOhneGeheimnis),
sponsorships: firma.sponsorships.sort(neuesteZuerst).map((p: any) => ({
...p,
deliveries: p.deliveries.sort(
(a: any, b: any) => +new Date(a.planned_at ?? a.created_at) - +new Date(b.planned_at ?? b.created_at)
),
reports: p.reports.sort((a: any, b: any) => +new Date(b.published_at) - +new Date(a.published_at)),
})),
documents: firma.documents.sort(neuesteZuerst).map(({ file_key: _k, ...d }: any) => d),
notes: firma.notes.sort(neuesteZuerst),
inquiries: firma.inquiries.sort(neuesteZuerst),
},
});
}
export async function POST(req: MedusaRequest, res: MedusaResponse) {
try {
const daten = pruefe((req.body ?? {}) as Record<string, unknown>, COMPANY_FELDER, "aendern");
const firma = await b2b(req.scope).updateCompanies({ id: req.params.id, ...daten });
res.json({ company: firma });
} catch (e) {
if (e instanceof Eingabefehler) return void res.status(400).json({ message: e.message });
throw e;
}
}
/** Firma samt allem löschen, auch die Dateien. Kundenkonten bleiben. */
export async function DELETE(req: MedusaRequest, res: MedusaResponse) {
const service = b2b(req.scope);
const firma = await service.retrieveCompany(req.params.id, { relations: ["documents"] });
const schluessel = firma.documents.map((d: any) => d.file_key);
await service.deleteCompanies(req.params.id);
if (schluessel.length) {
await (req.scope.resolve(Modules.FILE) as any).deleteFiles(schluessel).catch(() => undefined);
}
res.json({ id: req.params.id, deleted: true });
}
@@ -0,0 +1,38 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { b2b, COMPANY_FELDER, Eingabefehler, pruefe } from "../../../../lib/b2b";
/** Alle Firmen mit Zahlen für die Liste. */
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const service = b2b(req.scope);
const firmen = await service.listCompanies(
{},
{ relations: ["contacts", "sponsorships", "inquiries"], order: { name: "ASC" } }
);
res.json({
companies: firmen.map((f: any) => ({
id: f.id,
name: f.name,
city: f.city,
stage: f.stage,
follow_up_at: f.follow_up_at,
contacts: f.contacts.length,
logins: f.contacts.filter((k: any) => k.customer_id).length,
colonies: f.sponsorships
.filter((p: any) => p.status === "active" || p.status === "renewal")
.reduce((s: number, p: any) => s + (p.colonies ?? 0), 0),
sponsorships: f.sponsorships.length,
open_inquiries: f.inquiries.filter((a: any) => a.status === "open").length,
})),
});
}
export async function POST(req: MedusaRequest, res: MedusaResponse) {
try {
const daten = pruefe((req.body ?? {}) as Record<string, unknown>, COMPANY_FELDER, "anlegen");
const firma = await b2b(req.scope).createCompanies(daten);
res.json({ company: firma });
} catch (e) {
if (e instanceof Eingabefehler) return void res.status(400).json({ message: e.message });
throw e;
}
}
@@ -0,0 +1,14 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { Eingabefehler } from "../../../../../../lib/b2b";
import { einladen } from "../../../../../../lib/b2b-einladung";
/** Einladung ins Firmenportal schicken (auch erneut, wenn abgelaufen). */
export async function POST(req: MedusaRequest, res: MedusaResponse) {
try {
const ergebnis = await einladen(req.scope, req.params.id);
res.json({ result: ergebnis });
} catch (e) {
if (e instanceof Eingabefehler) return void res.status(400).json({ message: e.message });
throw e;
}
}
@@ -0,0 +1,7 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { b2b, dokumentSenden } from "../../../../../../lib/b2b";
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const dokument = await b2b(req.scope).retrieveDocument(req.params.id);
await dokumentSenden(req.scope, res, dokument);
}
@@ -0,0 +1,13 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { dateiAblegen, Eingabefehler } from "../../../../lib/b2b";
/** Foto für einen Bericht hochladen: { mime_type, content (Base64) } → { url }. */
export async function POST(req: MedusaRequest, res: MedusaResponse) {
try {
const datei = await dateiAblegen(req.scope, (req.body ?? {}) as Record<string, unknown>, "bild");
res.json({ url: datei.url });
} catch (e) {
if (e instanceof Eingabefehler) return void res.status(400).json({ message: e.message });
throw e;
}
}
@@ -0,0 +1,12 @@
import { defineMiddlewares } from "@medusajs/framework/http";
/**
* Datei-Uploads der Firmenkunden kommen als Base64 im JSON. Medusas
* Standardgrenze reicht dafür nicht.
*/
export default defineMiddlewares({
routes: [
{ matcher: "/admin/b2b/companies/:id/documents", methods: ["POST"], bodyParser: { sizeLimit: "25mb" } },
{ matcher: "/admin/b2b/images", methods: ["POST"], bodyParser: { sizeLimit: "25mb" } },
],
});
@@ -0,0 +1,24 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { Eingabefehler } from "../../../../lib/b2b";
import { einladungAnnehmen, kontaktZumToken } from "../../../../lib/b2b-einladung";
/**
* Einladung ins Firmenportal. Öffentlich: Wer den Link hat, ist berechtigt.
* Das Token ist 32 zufällige Bytes, Raten lohnt nicht.
*/
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const kontakt = await kontaktZumToken(req.scope, String(req.query.token ?? ""));
if (!kontakt) return void res.status(404).json({ message: "Dieser Link ist abgelaufen oder ungültig." });
res.json({ email: kontakt.email, first_name: kontakt.first_name, company: kontakt.company?.name });
}
export async function POST(req: MedusaRequest, res: MedusaResponse) {
const body = (req.body ?? {}) as Record<string, unknown>;
try {
const ergebnis = await einladungAnnehmen(req.scope, String(body.token ?? ""), String(body.password ?? ""));
res.json(ergebnis);
} catch (e) {
if (e instanceof Eingabefehler) return void res.status(400).json({ message: e.message });
throw e;
}
}
@@ -0,0 +1,12 @@
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { b2b, dokumentSenden, firmaDesKunden } from "../../../../../../../lib/b2b";
/** Download eines Dokuments — nur der eigenen Firma und nur freigegebene. */
export async function GET(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
const zuordnung = await firmaDesKunden(req.scope, req.auth_context.actor_id);
const [dokument] = zuordnung
? await b2b(req.scope).listDocuments({ id: req.params.id, company_id: zuordnung.firma.id, visible: true }, { take: 1 })
: [];
if (!dokument) return void res.status(404).json({ message: "Nicht gefunden." });
await dokumentSenden(req.scope, res, dokument);
}
@@ -0,0 +1,61 @@
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { Modules } from "@medusajs/framework/utils";
import { b2b, firmaDesKunden } from "../../../../../../lib/b2b";
import { anfrageMail } from "../../../../../../lib/contact-email";
const EMPFAENGER = "kontakt@place4bees.com";
const ARTEN: Record<string, string> = {
new: "Neue Patenschaft",
more: "Mehr Völker",
other: "Sonstiges",
};
/** Anfrage aus dem Firmenportal: landet im Admin und als Mail beim Shop. */
export async function POST(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
const zuordnung = await firmaDesKunden(req.scope, req.auth_context.actor_id);
if (!zuordnung) return void res.status(404).json({ message: "Kein Firmenkonto." });
const body = (req.body ?? {}) as Record<string, unknown>;
const kind = String(body.kind ?? "");
const message = String(body.message ?? "").trim();
const colonies = body.colonies === undefined || body.colonies === "" || body.colonies === null ? null : Number(body.colonies);
if (!ARTEN[kind]) return void res.status(400).json({ message: "Bitte wählen Sie, worum es geht." });
if (colonies !== null && (!Number.isInteger(colonies) || colonies < 1 || colonies > 1000)) {
return void res.status(400).json({ message: "Bitte eine Anzahl Völker zwischen 1 und 1000 angeben." });
}
if (message.length > 5000) return void res.status(400).json({ message: "Die Nachricht ist zu lang." });
if (kind === "other" && message.length < 5) return void res.status(400).json({ message: "Bitte schreiben Sie uns kurz, worum es geht." });
const { kontakt, firma } = zuordnung;
const anfrage = await b2b(req.scope).createInquiries({
company_id: firma.id,
contact_id: kontakt.id,
kind,
colonies,
message: message || null,
});
const logger = req.scope.resolve("logger");
try {
const name = [kontakt.first_name, kontakt.last_name].filter(Boolean).join(" ") || kontakt.email;
const inhalt = anfrageMail({
name: `${name} (${firma.name})`,
email: kontakt.email,
nachricht: [`${ARTEN[kind]}${colonies ? `: ${colonies} Völker` : ""}`, message].filter(Boolean).join("\n\n"),
quelle: "Firmenportal",
});
await (req.scope.resolve(Modules.NOTIFICATION) as any).createNotifications({
to: EMPFAENGER,
channel: "email",
template: "b2b-inquiry",
content: inhalt,
data: { reply_to: kontakt.email },
});
} catch (error) {
// Die Anfrage ist gespeichert und im Admin sichtbar; die Mail ist nur Bequemlichkeit.
logger.error(`[b2b] Anfrage-Mail fehlgeschlagen: ${error instanceof Error ? error.message : String(error)}`);
}
res.json({ inquiry: { id: anfrage.id } });
}
@@ -0,0 +1,74 @@
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
import { firmaDesKunden, b2b } from "../../../../../lib/b2b";
/**
* Firmenportal: alles, was der angemeldete Ansprechpartner sehen darf.
* Interne Notizen, interne Dokumente und die interne Bemerkung an der
* Patenschaft bleiben draußen. Kein Firmenkunde → 404.
*/
export async function GET(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
const zuordnung = await firmaDesKunden(req.scope, req.auth_context.actor_id);
if (!zuordnung) return void res.status(404).json({ message: "Kein Firmenkonto." });
const firma = await b2b(req.scope).retrieveCompany(zuordnung.firma.id, {
relations: ["contacts", "sponsorships", "sponsorships.deliveries", "sponsorships.reports", "documents", "inquiries"],
});
const datum = (d: any) => +new Date(d ?? 0);
res.json({
company: {
name: firma.name,
street: firma.street,
postal_code: firma.postal_code,
city: firma.city,
vat_id: firma.vat_id,
},
contacts: firma.contacts.map((k: any) => ({
name: [k.first_name, k.last_name].filter(Boolean).join(" "),
email: k.email,
role: k.role,
has_login: Boolean(k.customer_id),
})),
sponsorships: firma.sponsorships
.filter((p: any) => p.status !== "requested")
.sort((a: any, b: any) => datum(b.start_date ?? b.created_at) - datum(a.start_date ?? a.created_at))
.map((p: any) => ({
id: p.id,
title: p.title,
colonies: p.colonies,
location: p.location,
start_date: p.start_date,
end_date: p.end_date,
price: p.price,
status: p.status,
deliveries: p.deliveries
.sort((a: any, b: any) => datum(a.planned_at ?? a.created_at) - datum(b.planned_at ?? b.created_at))
.map((l: any) => ({
title: l.title,
quantity: l.quantity,
planned_at: l.planned_at,
shipped_at: l.shipped_at,
tracking_number: l.tracking_number,
status: l.status,
})),
reports: p.reports
.filter((r: any) => datum(r.published_at) <= Date.now())
.sort((a: any, b: any) => datum(b.published_at) - datum(a.published_at))
.map((r: any) => ({ id: r.id, title: r.title, body: r.body, images: r.images ?? [], published_at: r.published_at })),
})),
documents: firma.documents
.filter((d: any) => d.visible)
.sort((a: any, b: any) => datum(b.created_at) - datum(a.created_at))
.map((d: any) => ({
id: d.id,
title: d.title,
kind: d.kind,
file_name: d.file_name,
sponsorship_id: d.sponsorship_id,
created_at: d.created_at,
})),
inquiries: firma.inquiries
.sort((a: any, b: any) => datum(b.created_at) - datum(a.created_at))
.map((a: any) => ({ kind: a.kind, colonies: a.colonies, message: a.message, status: a.status, created_at: a.created_at })),
});
}
@@ -0,0 +1,147 @@
import { createHash, randomBytes } from "node:crypto";
import { Modules } from "@medusajs/framework/utils";
import { createCustomerAccountWorkflow } from "@medusajs/core-flows";
import { b2b, Eingabefehler } from "./b2b";
import { firmenEinladungMail, firmenZugangMail } from "./order-emails";
/** So lange gilt eine Einladung. */
const GUELTIG_TAGE = 14;
export const tokenHash = (token: string) => createHash("sha256").update(token).digest("hex");
const storefront = () => process.env.STOREFRONT_URL ?? "http://localhost:4321";
/**
* Schickt die Mail und wirft, wenn sie nicht wirklich rausgeht. Ohne
* Mailserver schreibt Medusa sie nur ins Log und meldet trotzdem Erfolg —
* im Admin stünde dann "Eingeladen", obwohl nie etwas ankommt.
*/
async function mailen(scope: any, an: string, vorlage: string, inhalt: { subject: string; html: string; text: string }) {
if (!process.env.SMTP_HOST || !process.env.MAIL_FROM) {
throw new Eingabefehler(
"Auf diesem System ist kein Mailserver eingerichtet (SMTP_HOST / MAIL_FROM fehlen). Die Einladung wurde nicht verschickt."
);
}
const notification: any = scope.resolve(Modules.NOTIFICATION);
try {
await notification.createNotifications({ to: an, channel: "email", template: vorlage, content: inhalt });
} catch (e) {
const grund = e instanceof Error ? e.message.split("\n").pop() : String(e);
throw new Eingabefehler(`Die Mail ließ sich nicht verschicken: ${grund}`);
}
}
/**
* Lädt einen Ansprechpartner ins Firmenportal ein.
*
* Hat die Adresse schon ein Kundenkonto, wird es direkt verbunden — ein
* zweites Konto mit derselben Adresse ließe Medusa nicht zu. Sonst geht ein
* Link raus, über den das Passwort festgelegt wird; erst dann entsteht das
* Konto.
*/
export async function einladen(scope: any, kontaktId: string): Promise<"linked" | "invited"> {
const service = b2b(scope);
const kontakt = await service.retrieveContact(kontaktId, { relations: ["company"] });
if (kontakt.customer_id) throw new Eingabefehler("Dieser Ansprechpartner hat schon Zugang.");
const customerModule: any = scope.resolve(Modules.CUSTOMER);
const [kunde] = await customerModule.listCustomers({ email: kontakt.email, has_account: true }, { take: 1 });
const jetzt = new Date();
if (kunde) {
const [vergeben] = await service.listContacts({ customer_id: kunde.id }, { take: 1, relations: ["company"] });
if (vergeben) throw new Eingabefehler(`Dieses Konto gehört schon zu „${vergeben.company?.name}“.`);
await mailen(
scope,
kontakt.email,
"b2b-access",
firmenZugangMail({
firma: kontakt.company.name,
vorname: kontakt.first_name,
link: `${storefront()}/konto/anmelden?redirect=/konto/firma`,
})
);
await service.updateContacts({
id: kontakt.id,
customer_id: kunde.id,
invited_at: jetzt,
accepted_at: jetzt,
invite_token_hash: null,
invite_expires_at: null,
});
return "linked";
}
// Erst die Mail, dann speichern: Kommt sie nicht raus, bleibt der Status,
// wie er war, statt "Eingeladen" zu behaupten.
const token = randomBytes(32).toString("base64url");
await mailen(
scope,
kontakt.email,
"b2b-invite",
firmenEinladungMail({
firma: kontakt.company.name,
vorname: kontakt.first_name,
link: `${storefront()}/konto/einladung?token=${encodeURIComponent(token)}`,
tage: GUELTIG_TAGE,
})
);
await service.updateContacts({
id: kontakt.id,
invite_token_hash: tokenHash(token),
invite_expires_at: new Date(jetzt.getTime() + GUELTIG_TAGE * 86400000),
invited_at: jetzt,
});
return "invited";
}
/** Ansprechpartner zu einem gültigen Einladungslink, sonst `null`. */
export async function kontaktZumToken(scope: any, token: string) {
if (!token) return null;
const [kontakt] = await b2b(scope).listContacts(
{ invite_token_hash: tokenHash(token) },
{ take: 1, relations: ["company"] }
);
if (!kontakt || kontakt.customer_id) return null;
if (!kontakt.invite_expires_at || new Date(kontakt.invite_expires_at) <= new Date()) return null;
return kontakt;
}
/** Löst die Einladung ein: Konto mit Passwort anlegen und verbinden. */
export async function einladungAnnehmen(scope: any, token: string, passwort: string) {
const kontakt = await kontaktZumToken(scope, token);
if (!kontakt) throw new Eingabefehler("Dieser Link ist abgelaufen oder ungültig.");
if (passwort.length < 8) throw new Eingabefehler("Das Passwort braucht mindestens 8 Zeichen.");
const auth: any = scope.resolve(Modules.AUTH);
const { success, authIdentity } = await auth.register("emailpass", {
body: { email: kontakt.email, password: passwort },
});
if (!success || !authIdentity) {
throw new Eingabefehler(
"Für diese Adresse gibt es schon ein Konto. Bitte melden Sie sich damit an und geben Sie uns kurz Bescheid — wir schalten den Zugang dann frei."
);
}
const { result: kunde } = await createCustomerAccountWorkflow(scope).run({
input: {
authIdentityId: authIdentity.id,
customerData: {
email: kontakt.email,
first_name: kontakt.first_name ?? undefined,
last_name: kontakt.last_name ?? undefined,
phone: kontakt.phone ?? undefined,
company_name: kontakt.company?.name ?? undefined,
},
},
});
await b2b(scope).updateContacts({
id: kontakt.id,
customer_id: kunde.id,
accepted_at: new Date(),
invite_token_hash: null,
invite_expires_at: null,
});
return { email: kontakt.email as string };
}
+276
View File
@@ -0,0 +1,276 @@
import { randomUUID } from "node:crypto";
import path from "node:path";
import { Modules } from "@medusajs/framework/utils";
import { B2B_MODULE } from "../modules/b2b";
/**
* Gemeinsames für die Firmenkunden: welche Felder der Admin ändern darf,
* wie sie geprüft werden, und wer im Portal was sehen darf.
*/
type Feldart =
| "text"
| "email"
| "int"
| "number"
| "date"
| "bool"
| "images"
| readonly string[];
type Feld = { art: Feldart; pflicht?: boolean };
const t = (pflicht = false): Feld => ({ art: "text", pflicht });
export const COMPANY_FELDER: Record<string, Feld> = {
name: t(true),
street: t(),
postal_code: t(),
city: t(),
country: t(),
vat_id: t(),
email: { art: "email" },
phone: t(),
website: t(),
stage: { art: ["lead", "offer", "customer", "inactive"] },
follow_up_at: { art: "date" },
source: t(),
};
/**
* Die Unterobjekte einer Firma. `parent` ist das Feld, über das sie beim
* Anlegen an Firma oder Patenschaft hängen; ohne `parent` lassen sie sich
* über die allgemeine Route nur ändern, nicht anlegen.
*/
export const ENTITAETEN: Record<
string,
{ name: string; plural: string; parent?: "company_id" | "sponsorship_id"; felder: Record<string, Feld> }
> = {
contacts: {
name: "Contact",
plural: "Contacts",
parent: "company_id",
felder: {
first_name: t(),
last_name: t(),
email: { art: "email", pflicht: true },
phone: t(),
role: t(),
},
},
sponsorships: {
name: "Sponsorship",
plural: "Sponsorships",
parent: "company_id",
felder: {
title: t(true),
colonies: { art: "int" },
location: t(),
start_date: { art: "date" },
end_date: { art: "date" },
price: { art: "number" },
status: { art: ["requested", "offer", "active", "renewal", "ended"] },
internal_note: t(),
},
},
deliveries: {
name: "Delivery",
plural: "Deliveries",
parent: "sponsorship_id",
felder: {
title: t(true),
quantity: t(),
planned_at: { art: "date" },
shipped_at: { art: "date" },
tracking_number: t(),
status: { art: ["planned", "shipped", "delivered"] },
},
},
reports: {
name: "Report",
plural: "Reports",
parent: "sponsorship_id",
felder: {
title: t(true),
body: t(),
images: { art: "images" },
published_at: { art: "date", pflicht: true },
},
},
notes: {
name: "Note",
plural: "Notes",
parent: "company_id",
felder: { body: t(true) },
},
inquiries: {
name: "Inquiry",
plural: "Inquiries",
felder: { status: { art: ["open", "done"] } },
},
documents: {
name: "Document",
plural: "Documents",
felder: {
title: t(true),
kind: { art: ["contract", "certificate", "invoice", "offer", "other"] },
visible: { art: "bool" },
sponsorship_id: t(),
},
},
};
export class Eingabefehler extends Error {}
const MAIL = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;
/**
* Prüft die Eingabe gegen die erlaubten Felder. Unbekannte Felder fallen
* weg. Beim Anlegen müssen Pflichtfelder da sein, beim Ändern nur dann
* gültig, wenn sie mitkommen.
*/
export function pruefe(
body: Record<string, unknown>,
felder: Record<string, Feld>,
modus: "anlegen" | "aendern"
): Record<string, unknown> {
const daten: Record<string, unknown> = {};
for (const [schluessel, feld] of Object.entries(felder)) {
if (!(schluessel in body)) {
if (modus === "anlegen" && feld.pflicht) throw new Eingabefehler(`Feld „${schluessel}“ fehlt.`);
continue;
}
const roh = body[schluessel];
const leer = roh === null || roh === undefined || (typeof roh === "string" && roh.trim() === "");
if (leer) {
if (feld.pflicht) throw new Eingabefehler(`Feld „${schluessel}“ darf nicht leer sein.`);
daten[schluessel] = feld.art === "bool" ? false : null;
continue;
}
const art = feld.art;
if (Array.isArray(art)) {
if (!art.includes(String(roh))) throw new Eingabefehler(`Ungültiger Wert für „${schluessel}“.`);
daten[schluessel] = String(roh);
} else if (art === "text") {
const text = String(roh).trim();
if (text.length > 10000) throw new Eingabefehler(`„${schluessel}“ ist zu lang.`);
daten[schluessel] = text;
} else if (art === "email") {
const mail = String(roh).trim().toLowerCase();
if (!MAIL.test(mail)) throw new Eingabefehler("Bitte eine gültige E-Mail-Adresse angeben.");
daten[schluessel] = mail;
} else if (art === "int") {
const zahl = Number(roh);
if (!Number.isInteger(zahl) || zahl < 0) throw new Eingabefehler(`„${schluessel}“ muss eine ganze Zahl sein.`);
daten[schluessel] = zahl;
} else if (art === "number") {
// "1.490,00" wie im Deutschen, aber auch "1490.5" aus Zahlenfeldern.
const text = String(roh).trim();
const zahl = Number(text.includes(",") ? text.replace(/\./g, "").replace(",", ".") : text);
if (!Number.isFinite(zahl) || zahl < 0) throw new Eingabefehler(`„${schluessel}“ muss eine Zahl sein.`);
daten[schluessel] = zahl;
} else if (art === "date") {
const datum = new Date(String(roh));
if (Number.isNaN(datum.getTime())) throw new Eingabefehler(`„${schluessel}“ ist kein Datum.`);
daten[schluessel] = datum;
} else if (art === "bool") {
daten[schluessel] = roh === true || roh === "true";
} else if (art === "images") {
// Nur Bilder, die über den eigenen Upload kamen — keine fremden Adressen.
if (!Array.isArray(roh) || roh.length > 30 || !roh.every((u) => typeof u === "string" && u.startsWith("/static/"))) {
throw new Eingabefehler("Ungültige Bildliste.");
}
daten[schluessel] = roh;
}
}
return daten;
}
/** Das Modul, getypt so lose wie im Rest des Projekts. */
export function b2b(scope: { resolve: (key: string) => any }): any {
return scope.resolve(B2B_MODULE);
}
/** Zugang eines Ansprechpartners, für die Anzeige im Admin. */
export function zugang(kontakt: any): "active" | "invited" | "expired" | "none" {
if (kontakt.customer_id) return "active";
if (kontakt.invite_token_hash && kontakt.invite_expires_at) {
return new Date(kontakt.invite_expires_at) > new Date() ? "invited" : "expired";
}
return "none";
}
/** Ansprechpartner ohne den Einladungshash. */
export function kontaktOhneGeheimnis(kontakt: any) {
const { invite_token_hash: _hash, ...rest } = kontakt;
return { ...rest, access: zugang(kontakt) };
}
/** Firma des angemeldeten Kunden, oder `null`, wenn er kein Firmenkunde ist. */
export async function firmaDesKunden(scope: any, customerId: string) {
const service = b2b(scope);
const [kontakt] = await service.listContacts({ customer_id: customerId }, { take: 1, relations: ["company"] });
return kontakt ? { kontakt, firma: kontakt.company } : null;
}
/** Erlaubte Dateien für Dokumente. */
const DOKUMENT_TYPEN: Record<string, string> = {
"application/pdf": ".pdf",
"image/jpeg": ".jpg",
"image/png": ".png",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
};
const BILD_TYPEN: Record<string, string> = {
"image/jpeg": ".jpg",
"image/png": ".png",
"image/webp": ".webp",
};
/**
* Legt eine Datei im Dateimodul ab. Der Name ist zufällig: Auch private
* Dateien landen beim lokalen Anbieter unter /static, eine erratbare
* Adresse wäre also eine offene Tür.
*/
export async function dateiAblegen(
scope: any,
datei: { mime_type?: unknown; content?: unknown },
art: "dokument" | "bild"
) {
const typen = art === "dokument" ? DOKUMENT_TYPEN : BILD_TYPEN;
const mime = String(datei.mime_type ?? "");
const endung = typen[mime];
if (!endung) throw new Eingabefehler("Dieser Dateityp ist nicht erlaubt.");
const inhalt = String(datei.content ?? "");
if (!inhalt) throw new Eingabefehler("Die Datei ist leer.");
const fileModule: any = scope.resolve(Modules.FILE);
const ergebnis = await fileModule.createFiles({
filename: `${randomUUID()}${endung}`,
mimeType: mime,
content: inhalt,
access: art === "dokument" ? "private" : "public",
});
return { key: ergebnis.id as string, url: ergebnis.url as string, mime };
}
/** Dateiname für den Download, ohne Pfadteile. */
export function sichererDateiname(name: unknown, fallback: string): string {
const basis = path.basename(String(name ?? "")).replace(/[^\p{L}\p{N} ._-]/gu, "").trim();
return basis.slice(0, 120) || fallback;
}
/** Schickt ein Dokument als Download. */
export async function dokumentSenden(scope: any, res: any, dokument: any) {
const fileModule: any = scope.resolve(Modules.FILE);
const inhalt: Buffer = await fileModule.getAsBuffer(dokument.file_key);
res.setHeader("Content-Type", dokument.mime_type);
res.setHeader(
"Content-Disposition",
`attachment; filename*=UTF-8''${encodeURIComponent(dokument.file_name)}`
);
res.setHeader("Cache-Control", "private, no-store");
res.send(inhalt);
}
@@ -561,6 +561,66 @@ export function passwortZuruecksetzenMail(link: string) {
};
}
/**
* Einladung ins Firmenportal. Gilt länger als die Konto-Links: Wer
* eingeladen wird, liest die Mail nicht unbedingt sofort.
*/
export function firmenEinladungMail(e: { firma: string; vorname?: string | null; link: string; tage: number }) {
const anredeText = e.vorname ? `Hallo ${e.vorname},` : "Hallo,";
const absatz = `für ${e.firma} haben wir Ihnen einen Zugang zum place4bees-Firmenportal eingerichtet. Dort sehen Sie Ihre Bienenpatenschaften, Lieferungen, Neuigkeiten von Ihren Völkern und alle Dokumente. Legen Sie über diesen Link Ihr Passwort fest.`;
const htmlInhalt = RAHMEN(`
<h1 style="${STIL.h1}">Ihr Zugang zum Firmenportal</h1>
<p style="margin:24px 0 0">${html(anredeText)}</p>
<p style="margin:12px 0 0">${html(absatz)}</p>
<p style="margin:24px 0 0">
<a href="${html(e.link)}" style="${STIL.knopf}">Passwort festlegen</a>
</p>
<p style="margin:16px 0 0;color:${FARBE.text};font-size:13px">
Der Link gilt ${e.tage} Tage. Funktioniert der Knopf nicht, kopieren Sie
diese Adresse in Ihren Browser:<br />
<span style="word-break:break-all">${html(e.link)}</span>
</p>`);
const text = [
"Ihr Zugang zum Firmenportal",
"",
anredeText,
"",
absatz,
"",
e.link,
"",
`Der Link gilt ${e.tage} Tage.`,
"",
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
].join("\n");
return { subject: `Ihr Zugang zum Firmenportal – ${SHOP.name}`, html: htmlInhalt, text };
}
/** Für Eingeladene, die schon ein Kundenkonto haben: Zugang ist sofort frei. */
export function firmenZugangMail(e: { firma: string; vorname?: string | null; link: string }) {
const anredeText = e.vorname ? `Hallo ${e.vorname},` : "Hallo,";
const absatz = `Ihr bestehendes place4bees-Konto ist jetzt mit ${e.firma} verbunden. Nach der Anmeldung finden Sie im Firmenportal Ihre Bienenpatenschaften, Lieferungen, Neuigkeiten und Dokumente.`;
const htmlInhalt = RAHMEN(`
<h1 style="${STIL.h1}">Firmenportal freigeschaltet</h1>
<p style="margin:24px 0 0">${html(anredeText)}</p>
<p style="margin:12px 0 0">${html(absatz)}</p>
<p style="margin:24px 0 0">
<a href="${html(e.link)}" style="${STIL.knopf}">Zum Firmenportal</a>
</p>`);
const text = [
"Firmenportal freigeschaltet",
"",
anredeText,
"",
absatz,
"",
e.link,
"",
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
].join("\n");
return { subject: `Firmenportal freigeschaltet – ${SHOP.name}`, html: htmlInhalt, text };
}
/** Schlusszeile für Mails, auf die man eine Rückfrage haben könnte. */
const RUECKFRAGE = `Fragen? Schreiben Sie uns an ${SHOP.email}.`;
@@ -0,0 +1,6 @@
import honigEssig from "../scripts/set-honig-essig";
/** Läuft einmal beim Deploy (medusa db:migrate). */
export default async function ({ container }: any) {
await honigEssig({ container });
}
@@ -0,0 +1,6 @@
import honigtexte from "../scripts/set-honigtexte";
/** Läuft einmal beim Deploy (medusa db:migrate). */
export default async function ({ container }: any) {
await honigtexte({ container });
}
@@ -37,6 +37,17 @@ export default async function initial_data_seed({
const countries = ["gb", "de", "dk", "se", "fr", "es", "it"];
// Medusa merkt sich Migrationsskripte samt Dateiendung. Lokal ist dieses
// als .ts eingetragen, im gebauten Image heißt es .js und gilt dort als neu.
// Auf einem schon eingerichteten System würde es dann alles noch einmal
// anlegen und an den vorhandenen Regionen scheitern — nachdem es schon
// einen zweiten Verkaufskanal und API-Schlüssel erzeugt hat.
const { data: regionen } = await query.graph({ entity: "region", fields: ["id"] });
if (regionen.length) {
logger.info("Grunddaten schon vorhanden, nichts zu tun.");
return;
}
logger.info("Seeding store data...");
const {
result: [defaultSalesChannel],
@@ -0,0 +1,13 @@
/**
* Bringt die neuen Kerzen und den Honiglöffel auf jedes System.
*
* Medusa führt Dateien in diesem Ordner bei `medusa db:migrate` genau einmal
* aus — auf Test und Produktion erledigt das der migrate-Dienst beim
* Ausrollen. Die eigentliche Arbeit steht im Skript, das sich lokal auch von
* Hand wiederholen lässt.
*/
import kerzen from "../scripts/set-kerzenbilder";
export default async function ({ container }: any) {
await kerzen({ container });
}
@@ -0,0 +1,6 @@
import neueHonigbilder from "../scripts/set-neue-honigbilder";
/** Läuft einmal beim Deploy (medusa db:migrate), wie die Kerzenbilder. */
export default async function ({ container }: any) {
await neueHonigbilder({ container });
}
@@ -0,0 +1,6 @@
import shopFeinschliff from "../scripts/set-shop-feinschliff";
/** Läuft einmal beim Deploy (medusa db:migrate), wie die Honigbilder. */
export default async function ({ container }: any) {
await shopFeinschliff({ container });
}
@@ -0,0 +1,9 @@
import { kategorienSortieren } from "../scripts/set-shop-feinschliff";
/**
* Reihenfolge der Kategorien noch einmal setzen: Auf dem Testsystem lief
* shop-feinschliff mit der älteren Reihenfolge (Kerzen vor den Lebensmitteln).
*/
export default async function ({ container }: any) {
await kategorienSortieren(container);
}
@@ -0,0 +1,6 @@
import snackbilder from "../scripts/set-snackbilder";
/** Läuft einmal beim Deploy (medusa db:migrate). */
export default async function ({ container }: any) {
await snackbilder({ container });
}
@@ -0,0 +1,6 @@
import snacksTexte from "../scripts/set-snacks-texte";
/** Läuft einmal beim Deploy (medusa db:migrate). */
export default async function ({ container }: any) {
await snacksTexte({ container });
}
@@ -0,0 +1,6 @@
import texteNachtrag from "../scripts/set-texte-nachtrag";
/** Läuft einmal beim Deploy (medusa db:migrate). */
export default async function ({ container }: any) {
await texteNachtrag({ container });
}
@@ -0,0 +1,8 @@
import { Module } from "@medusajs/framework/utils";
import B2bModuleService from "./service";
export const B2B_MODULE = "b2b";
export default Module(B2B_MODULE, {
service: B2bModuleService,
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,86 @@
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
export class Migration20261105104333 extends Migration {
override async up(): Promise<void> {
this.addSql(`create table if not exists "b2b_company" ("id" text not null, "name" text not null, "street" text null, "postal_code" text null, "city" text null, "country" text not null default 'DE', "vat_id" text null, "email" text null, "phone" text null, "website" text null, "stage" text check ("stage" in ('lead', 'offer', 'customer', 'inactive')) not null default 'lead', "follow_up_at" timestamptz null, "source" text null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "b2b_company_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_company_deleted_at" ON "b2b_company" ("deleted_at") WHERE deleted_at IS NULL;`);
this.addSql(`create table if not exists "b2b_contact" ("id" text not null, "company_id" text not null, "first_name" text null, "last_name" text null, "email" text not null, "phone" text null, "role" text null, "customer_id" text null, "invite_token_hash" text null, "invite_expires_at" timestamptz null, "invited_at" timestamptz null, "accepted_at" timestamptz null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "b2b_contact_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_contact_company_id" ON "b2b_contact" ("company_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_contact_deleted_at" ON "b2b_contact" ("deleted_at") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_contact_customer_id" ON "b2b_contact" ("customer_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_contact_invite_token_hash" ON "b2b_contact" ("invite_token_hash") WHERE deleted_at IS NULL;`);
this.addSql(`create table if not exists "b2b_document" ("id" text not null, "company_id" text not null, "sponsorship_id" text null, "title" text not null, "kind" text check ("kind" in ('contract', 'certificate', 'invoice', 'offer', 'other')) not null default 'other', "file_key" text not null, "file_name" text not null, "mime_type" text not null, "visible" boolean not null default true, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "b2b_document_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_document_company_id" ON "b2b_document" ("company_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_document_deleted_at" ON "b2b_document" ("deleted_at") WHERE deleted_at IS NULL;`);
this.addSql(`create table if not exists "b2b_inquiry" ("id" text not null, "company_id" text not null, "contact_id" text null, "kind" text check ("kind" in ('new', 'more', 'other')) not null default 'new', "colonies" integer null, "message" text null, "status" text check ("status" in ('open', 'done')) not null default 'open', "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "b2b_inquiry_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_inquiry_company_id" ON "b2b_inquiry" ("company_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_inquiry_deleted_at" ON "b2b_inquiry" ("deleted_at") WHERE deleted_at IS NULL;`);
this.addSql(`create table if not exists "b2b_note" ("id" text not null, "company_id" text not null, "body" text not null, "author" text null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "b2b_note_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_note_company_id" ON "b2b_note" ("company_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_note_deleted_at" ON "b2b_note" ("deleted_at") WHERE deleted_at IS NULL;`);
this.addSql(`create table if not exists "b2b_sponsorship" ("id" text not null, "company_id" text not null, "title" text not null, "colonies" integer not null default 1, "location" text null, "start_date" timestamptz null, "end_date" timestamptz null, "price" numeric null, "status" text check ("status" in ('requested', 'offer', 'active', 'renewal', 'ended')) not null default 'requested', "internal_note" text null, "raw_price" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "b2b_sponsorship_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_sponsorship_company_id" ON "b2b_sponsorship" ("company_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_sponsorship_deleted_at" ON "b2b_sponsorship" ("deleted_at") WHERE deleted_at IS NULL;`);
this.addSql(`create table if not exists "b2b_report" ("id" text not null, "sponsorship_id" text not null, "title" text not null, "body" text null, "images" jsonb null, "published_at" timestamptz not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "b2b_report_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_report_sponsorship_id" ON "b2b_report" ("sponsorship_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_report_deleted_at" ON "b2b_report" ("deleted_at") WHERE deleted_at IS NULL;`);
this.addSql(`create table if not exists "b2b_delivery" ("id" text not null, "sponsorship_id" text not null, "title" text not null, "quantity" text null, "planned_at" timestamptz null, "shipped_at" timestamptz null, "tracking_number" text null, "status" text check ("status" in ('planned', 'shipped', 'delivered')) not null default 'planned', "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "b2b_delivery_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_delivery_sponsorship_id" ON "b2b_delivery" ("sponsorship_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_b2b_delivery_deleted_at" ON "b2b_delivery" ("deleted_at") WHERE deleted_at IS NULL;`);
this.addSql(`alter table if exists "b2b_contact" add constraint "b2b_contact_company_id_foreign" foreign key ("company_id") references "b2b_company" ("id") on update cascade on delete cascade;`);
this.addSql(`alter table if exists "b2b_document" add constraint "b2b_document_company_id_foreign" foreign key ("company_id") references "b2b_company" ("id") on update cascade on delete cascade;`);
this.addSql(`alter table if exists "b2b_inquiry" add constraint "b2b_inquiry_company_id_foreign" foreign key ("company_id") references "b2b_company" ("id") on update cascade on delete cascade;`);
this.addSql(`alter table if exists "b2b_note" add constraint "b2b_note_company_id_foreign" foreign key ("company_id") references "b2b_company" ("id") on update cascade on delete cascade;`);
this.addSql(`alter table if exists "b2b_sponsorship" add constraint "b2b_sponsorship_company_id_foreign" foreign key ("company_id") references "b2b_company" ("id") on update cascade on delete cascade;`);
this.addSql(`alter table if exists "b2b_report" add constraint "b2b_report_sponsorship_id_foreign" foreign key ("sponsorship_id") references "b2b_sponsorship" ("id") on update cascade on delete cascade;`);
this.addSql(`alter table if exists "b2b_delivery" add constraint "b2b_delivery_sponsorship_id_foreign" foreign key ("sponsorship_id") references "b2b_sponsorship" ("id") on update cascade on delete cascade;`);
}
override async down(): Promise<void> {
this.addSql(`alter table if exists "b2b_contact" drop constraint if exists "b2b_contact_company_id_foreign";`);
this.addSql(`alter table if exists "b2b_document" drop constraint if exists "b2b_document_company_id_foreign";`);
this.addSql(`alter table if exists "b2b_inquiry" drop constraint if exists "b2b_inquiry_company_id_foreign";`);
this.addSql(`alter table if exists "b2b_note" drop constraint if exists "b2b_note_company_id_foreign";`);
this.addSql(`alter table if exists "b2b_sponsorship" drop constraint if exists "b2b_sponsorship_company_id_foreign";`);
this.addSql(`alter table if exists "b2b_report" drop constraint if exists "b2b_report_sponsorship_id_foreign";`);
this.addSql(`alter table if exists "b2b_delivery" drop constraint if exists "b2b_delivery_sponsorship_id_foreign";`);
this.addSql(`drop table if exists "b2b_company" cascade;`);
this.addSql(`drop table if exists "b2b_contact" cascade;`);
this.addSql(`drop table if exists "b2b_document" cascade;`);
this.addSql(`drop table if exists "b2b_inquiry" cascade;`);
this.addSql(`drop table if exists "b2b_note" cascade;`);
this.addSql(`drop table if exists "b2b_sponsorship" cascade;`);
this.addSql(`drop table if exists "b2b_report" cascade;`);
this.addSql(`drop table if exists "b2b_delivery" cascade;`);
}
}
@@ -0,0 +1,43 @@
import { model } from "@medusajs/framework/utils";
import Contact from "./contact";
import Sponsorship from "./sponsorship";
import Document from "./document";
import Note from "./note";
import Inquiry from "./inquiry";
/**
* Ein Firmenkunde oder Interessent.
*
* Die Stufe ist die Vertriebs-Pipeline: Interessent → Angebot → Kunde.
* Bewusst getrennt von den Medusa-Kunden: Eine Firma hat mehrere
* Ansprechpartner, und nur die haben (vielleicht) ein Kundenkonto.
*/
const Company = model
.define("b2b_company", {
id: model.id({ prefix: "firma" }).primaryKey(),
name: model.text().searchable(),
street: model.text().nullable(),
postal_code: model.text().nullable(),
city: model.text().nullable(),
country: model.text().default("DE"),
vat_id: model.text().nullable(),
email: model.text().nullable(),
phone: model.text().nullable(),
website: model.text().nullable(),
stage: model.enum(["lead", "offer", "customer", "inactive"]).default("lead"),
/** Wann wieder nachfassen. Die Liste im Admin sortiert Fällige nach oben. */
follow_up_at: model.dateTime().nullable(),
/** Woher der Kontakt kam, Freitext (Messe, Empfehlung, Website …). */
source: model.text().nullable(),
contacts: model.hasMany(() => Contact, { mappedBy: "company" }),
sponsorships: model.hasMany(() => Sponsorship, { mappedBy: "company" }),
documents: model.hasMany(() => Document, { mappedBy: "company" }),
notes: model.hasMany(() => Note, { mappedBy: "company" }),
inquiries: model.hasMany(() => Inquiry, { mappedBy: "company" }),
})
.cascades({ delete: ["contacts", "sponsorships", "documents", "notes", "inquiries"] });
export default Company;
@@ -0,0 +1,29 @@
import { model } from "@medusajs/framework/utils";
import Company from "./company";
/**
* Ansprechpartner einer Firma. Mit `customer_id` wird daraus ein Login
* fürs Firmenportal — gesetzt erst, wenn die Einladung angenommen ist.
*/
const Contact = model
.define("b2b_contact", {
id: model.id({ prefix: "fkontakt" }).primaryKey(),
company: model.belongsTo(() => Company, { mappedBy: "contacts" }),
first_name: model.text().nullable(),
last_name: model.text().nullable(),
email: model.text(),
phone: model.text().nullable(),
/** Funktion in der Firma, z. B. "Office Management". */
role: model.text().nullable(),
customer_id: model.text().nullable(),
/** Nur der Hash steht in der Datenbank, der Link selbst nur in der Mail. */
invite_token_hash: model.text().nullable(),
invite_expires_at: model.dateTime().nullable(),
invited_at: model.dateTime().nullable(),
accepted_at: model.dateTime().nullable(),
})
.indexes([{ on: ["customer_id"] }, { on: ["invite_token_hash"] }]);
export default Contact;
@@ -0,0 +1,18 @@
import { model } from "@medusajs/framework/utils";
import Sponsorship from "./sponsorship";
/** Was zu einer Patenschaft verschickt wird: Honig, Werbemittel, Urkunde. */
const Delivery = model.define("b2b_delivery", {
id: model.id({ prefix: "fliefer" }).primaryKey(),
sponsorship: model.belongsTo(() => Sponsorship, { mappedBy: "deliveries" }),
title: model.text(),
/** Freitext, z. B. "120 Gläser à 250 g". */
quantity: model.text().nullable(),
planned_at: model.dateTime().nullable(),
shipped_at: model.dateTime().nullable(),
tracking_number: model.text().nullable(),
status: model.enum(["planned", "shipped", "delivered"]).default("planned"),
});
export default Delivery;
@@ -0,0 +1,25 @@
import { model } from "@medusajs/framework/utils";
import Company from "./company";
/**
* Datei für eine Firma: Vertrag, Urkunde, Rechnung …
*
* Liegt privat im Dateimodul. Ausgeliefert wird nur über eine Route, die
* prüft, wer fragt — nie über eine öffentliche Adresse.
*/
const Document = model.define("b2b_document", {
id: model.id({ prefix: "fdok" }).primaryKey(),
company: model.belongsTo(() => Company, { mappedBy: "documents" }),
/** Optional: gehört zu einer bestimmten Patenschaft. */
sponsorship_id: model.text().nullable(),
title: model.text(),
kind: model.enum(["contract", "certificate", "invoice", "offer", "other"]).default("other"),
file_key: model.text(),
file_name: model.text(),
mime_type: model.text(),
/** Aus, wenn das Dokument nur intern sein soll. */
visible: model.boolean().default(true),
});
export default Document;
@@ -0,0 +1,16 @@
import { model } from "@medusajs/framework/utils";
import Company from "./company";
/** Anfrage eines Firmenkunden aus dem Portal. */
const Inquiry = model.define("b2b_inquiry", {
id: model.id({ prefix: "fanfrage" }).primaryKey(),
company: model.belongsTo(() => Company, { mappedBy: "inquiries" }),
contact_id: model.text().nullable(),
kind: model.enum(["new", "more", "other"]).default("new"),
colonies: model.number().nullable(),
message: model.text().nullable(),
status: model.enum(["open", "done"]).default("open"),
});
export default Inquiry;
@@ -0,0 +1,12 @@
import { model } from "@medusajs/framework/utils";
import Company from "./company";
/** Interne Notiz zum Kundenkontakt (Telefonat, Treffen …). Nie im Portal. */
const Note = model.define("b2b_note", {
id: model.id({ prefix: "fnotiz" }).primaryKey(),
company: model.belongsTo(() => Company, { mappedBy: "notes" }),
body: model.text(),
author: model.text().nullable(),
});
export default Note;
@@ -0,0 +1,16 @@
import { model } from "@medusajs/framework/utils";
import Sponsorship from "./sponsorship";
/** Neuigkeit vom Volk: Text mit Fotos, im Portal für den Kunden sichtbar. */
const Report = model.define("b2b_report", {
id: model.id({ prefix: "fbericht" }).primaryKey(),
sponsorship: model.belongsTo(() => Sponsorship, { mappedBy: "reports" }),
title: model.text(),
body: model.text().nullable(),
/** Bildadressen (/static/…), in der Reihenfolge der Anzeige. */
images: model.json().nullable(),
published_at: model.dateTime(),
});
export default Report;
@@ -0,0 +1,31 @@
import { model } from "@medusajs/framework/utils";
import Company from "./company";
import Delivery from "./delivery";
import Report from "./report";
/**
* Eine B2B-Bienenpatenschaft. Hat nichts mit der Patenschaft aus dem Shop
* zu tun: Das hier ist ein Vertrag mit einer Firma, ohne Medusa-Bestellung.
*/
const Sponsorship = model
.define("b2b_sponsorship", {
id: model.id({ prefix: "fpaten" }).primaryKey(),
company: model.belongsTo(() => Company, { mappedBy: "sponsorships" }),
title: model.text(),
colonies: model.number().default(1),
location: model.text().nullable(),
start_date: model.dateTime().nullable(),
end_date: model.dateTime().nullable(),
/** Netto in Euro für die Laufzeit. */
price: model.bigNumber().nullable(),
status: model.enum(["requested", "offer", "active", "renewal", "ended"]).default("requested"),
/** Sieht der Kunde nicht. */
internal_note: model.text().nullable(),
deliveries: model.hasMany(() => Delivery, { mappedBy: "sponsorship" }),
reports: model.hasMany(() => Report, { mappedBy: "sponsorship" }),
})
.cascades({ delete: ["deliveries", "reports"] });
export default Sponsorship;
@@ -0,0 +1,22 @@
import { MedusaService } from "@medusajs/framework/utils";
import Company from "./models/company";
import Contact from "./models/contact";
import Sponsorship from "./models/sponsorship";
import Delivery from "./models/delivery";
import Report from "./models/report";
import Document from "./models/document";
import Note from "./models/note";
import Inquiry from "./models/inquiry";
class B2bModuleService extends MedusaService({
Company,
Contact,
Sponsorship,
Delivery,
Report,
Document,
Note,
Inquiry,
}) {}
export default B2bModuleService;
@@ -0,0 +1,25 @@
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
import { LocalFileService } from "@medusajs/file-local";
/**
* Lokale Dateiablage mit Adressen ohne Domain (/static/…).
*
* Der Standardanbieter baut die Adresse mit `new URL(backend_url)` und
* scheitert an einem relativen Pfad mit "Invalid URL" — jeder Upload brach
* ab, auch Produktbilder im Admin. Hier entsteht die Adresse ohne URL-Objekt;
* alles andere bleibt beim Original.
*/
class RelativeLocalFileService extends LocalFileService {
static identifier = "localfs-relative";
constructor(deps: any, options: any) {
super(deps, options);
const basis = String(options?.backend_url ?? "/static").replace(/\/+$/, "");
(this as any).getUploadFileUrl = (fileKey: string) =>
`${basis}/${fileKey.split("/").map(encodeURIComponent).join("/")}`;
}
}
export default ModuleProvider(Modules.FILE, {
services: [RelativeLocalFileService],
});
@@ -0,0 +1,130 @@
/**
* Honig-Balsamico-Essig, 0,25 l, in der Kategorie "Feinkost".
*
* npx medusa exec ./src/scripts/set-honig-essig.ts
*
* Vorerst ohne Bild, Preis 12,90 €. Texte, Zutaten und Nährwerte vom
* Team, die Beschreibung vom Etikett.
* Der Grundpreis kommt über `net_volume_ml` und steht dann je Liter.
*
* Das Versandgewicht (550 g) ist geschätzt — Flasche plus Inhalt. Im Admin
* unter Variante → Gewicht korrigieren, sobald gewogen.
*
* Wiederholbar: legt nur an, was fehlt, und setzt sonst die Zielwerte.
*/
import {
createProductCategoriesWorkflow,
createProductsWorkflow,
updateProductsWorkflow,
updateProductVariantsWorkflow,
} from "@medusajs/core-flows";
const HANDLE = "honig-balsamico-essig";
const TITEL = "Honig-Balsamico-Essig";
const KATEGORIE = { name: "Feinkost", handle: "feinkost" };
const PREIS = 12.9;
const VARIANTE = {
title: "0,25 l",
weight: 550,
metadata: { net_volume_ml: 250 },
};
const BESCHREIBUNG = [
"Zu Beginn wird der Honig zusammen mit lebendigem Wasser und gentechnikfreier Hefe vergoren. Im Anschluss fermentiert der entstandene Honigwein über mehrere Monate zu feinstem Honigessig. Heraus kommt ein traditioneller Gärungsessig, fruchtig-spritzig im Aroma mit einer dezenten Honignote.",
"Genussempfehlung: Zum Verfeinern von Vinaigrette und Dressing, zum Marinieren von Fisch und Fleisch vor dem Grillen oder Schmoren oder zum Marinieren von Gemüse nach dem Garen.",
"Zutaten: Honig 50 %, Honig-Gärungsessig (Wasser, Honig).",
"Essigzubereitung, enthält 2,9 % Säure. Inhalt: 0,25 l.",
"Ablagerungen sind möglich, da Naturprodukt. Bitte kühl und dunkel lagern.",
"Nährwerte je 100 ml: Brennwert 807 kJ / 193 kcal · Kohlenhydrate 46,0 g, davon Zucker 46,0 g. Enthält geringfügige Mengen an Fett, gesättigten Fettsäuren, Eiweiß und Salz.",
].join("\n\n");
export default async function ({ container }: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
let { data: kategorien } = await query.graph({
entity: "product_category",
fields: ["id", "handle", "rank"],
filters: { handle: KATEGORIE.handle },
});
if (!kategorien?.[0]) {
const { result } = await createProductCategoriesWorkflow(container).run({
input: { product_categories: [{ ...KATEGORIE, is_active: true }] },
});
kategorien = result as any;
logger.info(`Kategorie "${KATEGORIE.name}" angelegt.`);
}
const kategorieId = kategorien[0].id;
const lesen = async () =>
(
await query.graph({
entity: "product",
fields: ["id", "metadata", "variants.id"],
filters: { handle: HANDLE },
})
).data?.[0];
let produkt = await lesen();
if (!produkt) {
// Jeweils der älteste, wie in set-kerzenbilder.ts.
const { data: profile } = await query.graph({
entity: "shipping_profile",
fields: ["id"],
pagination: { order: { created_at: "ASC" } },
});
const { data: kanaele } = await query.graph({
entity: "sales_channel",
fields: ["id"],
pagination: { order: { created_at: "ASC" } },
});
await createProductsWorkflow(container).run({
input: {
products: [
{
title: TITEL,
handle: HANDLE,
status: "published" as any,
description: BESCHREIBUNG,
shipping_profile_id: profile?.[0]?.id,
sales_channels: kanaele?.[0] ? [{ id: kanaele[0].id }] : undefined,
category_ids: [kategorieId],
metadata: { category: KATEGORIE.name, delivery_time: "2-3 Werktage" },
options: [{ title: "Inhalt", values: [VARIANTE.title] }],
variants: [
{
...VARIANTE,
options: { Inhalt: VARIANTE.title },
manage_inventory: false,
prices: [{ amount: PREIS, currency_code: "eur" }],
},
],
},
],
} as any,
});
logger.info(`"${TITEL}" angelegt.`);
return;
}
await updateProductsWorkflow(container).run({
input: {
selector: { id: produkt.id },
update: {
title: TITEL,
description: BESCHREIBUNG,
category_ids: [kategorieId],
metadata: { ...(produkt.metadata ?? {}), category: KATEGORIE.name },
},
} as any,
});
for (const v of produkt.variants ?? []) {
await updateProductVariantsWorkflow(container).run({
input: {
selector: { id: v.id },
update: { ...VARIANTE, prices: [{ amount: PREIS, currency_code: "eur" }] },
} as any,
});
}
logger.info(`"${TITEL}" aktualisiert.`);
}
@@ -0,0 +1,81 @@
/**
* Neue Beschreibungen für die Honigsorten (Texte vom Team, November 2026).
*
* npx medusa exec ./src/scripts/set-honigtexte.ts
*
* Gefunden wird über ein Stichwort im Titel, nicht über den Handle: einige
* Handles stammen aus kopierten Produkten und passen nicht zur Sorte
* (der Kornblumenhonig heißt dort "heidehonig-…-kopie").
*
* Buchweizenhonig und das Probierset bleiben, wie sie sind.
* Wiederholbar: setzt nur Zielwerte.
*/
import { updateProductsWorkflow } from "@medusajs/core-flows";
const TEXTE: { stichwort: string; text: string }[] = [
{
stichwort: "presshonig",
text: "Traditionelles Handwerk im Glas: Unser Traditionshonig wird durch das Pressen der Honigwaben gewonnen. Diese ursprüngliche Art der Honigernte macht ihn zu einer besonderen Entdeckung für Honigliebhaber – zum puren Genießen oder auf einer frischen Scheibe Brot.",
},
{
stichwort: "waldhonig",
text: "Dunkel, kräftig und malzig-würzig: Waldhonig verdankt seinen besonderen Charakter vor allem dem Honigtau der Bäume. Seine intensive Aromatik passt wunderbar zu rustikalem Brot, kräftigem Käse und herzhaften Dressings.",
},
{
stichwort: "kornblumenhonig",
text: "Kleine blaue Blüte, ausdrucksstarker Honig: Kornblumenhonig überrascht mit einem kräftigen, blumig-würzigen Aroma und einer leicht herben Note. Für alle, die gern neue Honigsorten entdecken – besonders lecker auf kräftigem Brot oder zu Käse.",
},
{
stichwort: "himbeerblütenhonig",
text: "Die Himbeere kann mehr als süße Früchte: Aus dem Nektar ihrer Blüten entsteht ein feiner Honig mit blumigem Aroma und zartfruchtigen Nuancen. Eine besondere Sorte für dein Frühstück – köstlich zu Naturjoghurt, frischen Beeren oder auf einem warmen Croissant.",
},
{
stichwort: "heidehonig",
text: "Kräftig, würzig und mit einer feinherben Note: Heidehonig ist ein Genuss für alle, die ausdrucksstarke Aromen lieben. Sein intensiver Geschmack passt besonders gut zu dunklem Brot, gereiftem Käse oder als besondere Zutat in der Küche.",
},
{
stichwort: "rapshonig",
text: "Hell, mild und angenehm sanft: Rapshonig ist ein Klassiker für alle, die einen dezenten Honiggeschmack mögen. Seine zurückhaltende Süße passt wunderbar auf frisches Brot und lässt auch im Quark oder Müsli den anderen Zutaten Raum.",
},
{
stichwort: "sonnenblumenhonig",
text: "Ein sonniger Genussmoment: Sonnenblumenhonig verbindet eine aromatische Süße mit einer feinfrischen Note. Sein warmer, goldgelber Farbton macht schon beim Öffnen Lust aufs Probieren – auf dem Frühstücksbrot, im Joghurt oder zu einem warmen Pfannkuchen.",
},
{
stichwort: "akazienhonig",
text: "Zart, mild und feinblumig: Unser Akazienhonig ist ideal für alle, die eine zurückhaltende Süße lieben. Er passt wunderbar in Joghurt, zu frischem Obst oder zum Süßen von Tee, ohne andere Aromen zu überdecken.",
},
{
stichwort: "lindenhonig",
text: "So schmeckt der Sommer unter Hamburgs Linden: Unser Lindenhonig begeistert mit einem markanten, würzigen Aroma und einer feinfrischen, leicht minzigen Note. Ein Honig mit Charakter, der auf kräftigem Brot ebenso gut schmeckt wie zu Käse.",
},
{
stichwort: "frühlingsblütenhonig",
text: "Hamburger Frühling im Glas: Unser Frühlingshonig vereint die Blütenvielfalt der ersten warmen Tage mit einer milden, blumigen Süße. Ein Stück Frühling für deinen Frühstückstisch – auf frischen Brötchen, im Joghurt oder einfach pur.",
},
{
stichwort: "sommerblütenhonig",
text: "Hamburger Sommer im Glas: Die Blütenvielfalt der warmen Jahreszeit verleiht unserem Sommerblütenhonig seinen aromatischen Charakter. Jede Ernte erzählt ein wenig anders vom Sommer – köstlich auf dem Frühstücksbrot, zu Joghurt oder als süße Note im Dressing.",
},
];
export default async function ({ container }: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
const { data: produkte } = await query.graph({ entity: "product", fields: ["id", "title"] });
for (const { stichwort, text } of TEXTE) {
// "Presshonig Hamburger Sommerblüte" enthält kein "sommerblütenhonig",
// trotzdem nur genau ein Treffer je Sorte zulassen.
const treffer = produkte.filter((p: any) => p.title.toLowerCase().includes(stichwort));
if (treffer.length !== 1) {
logger.warn(`${stichwort}: ${treffer.length} Treffer, übersprungen.`);
continue;
}
await updateProductsWorkflow(container).run({
input: { selector: { id: treffer[0].id }, update: { description: text } } as any,
});
logger.info(`${treffer[0].title}: Text aktualisiert.`);
}
}
@@ -0,0 +1,366 @@
/**
* Hängt die neuen Fotos an die Kerzen und den Honiglöffel.
*
* npx medusa exec ./src/scripts/set-kerzenbilder.ts
*
* Die vier Kerzen aus der Preisliste 9/2026 (setup-neu-2026.ts) bekommen
* ihre Bilder, einen stimmigen Namen und eine kurze Beschreibung und werden
* sichtbar.
*
* Sie lösen die alten Kerzen ab: Das Produkt "Bienenwachskerzen" (Bienenkorb,
* Wabenkerze, klassisch) wird Entwurf. Nicht gelöscht — Bestellungen und
* Varianten bleiben erhalten, im Admin lässt es sich wieder einschalten.
*
* Drei weitere Kerzen stehen nicht in der Preisliste. Ihre Preise sind an
* die vorhandenen Formen angelehnt und im Admin änderbar. Der Honiglöffel
* (Handle "honigdipper") steht in der eigenen Kategorie "Zubehör".
*
* Jede Kerze gibt es in zwei Farben, Honiggelb und Elfenbeinweiß. Die Farbe
* ist eine Variante (Option "Farbe"), damit sie in der Bestellung steht.
*
* Der Adventskranz wird nicht verkauft. Seine Bilder stehen in der Galerie
* der Rillenkerze, denn auf ihm stecken genau diese Kerzen.
*
* Vorn steht das schlichte Bild mit heller und dunkler Kerze gemeinsam, danach
* das weihnachtliche Paar. Das erste Bild ist zugleich das Hauptbild im
* Raster. Adressen ohne Domain, damit dieselben Daten im Heimnetz, auf dem
* Testsystem und in der Produktion stimmen.
*
* Auf Test und Produktion läuft das Skript beim Ausrollen von selbst, über
* src/migration-scripts/kerzen-und-honigloeffel.ts.
*
* Wiederholbar: Vorhandenes wird aktualisiert, nicht doppelt angelegt.
*/
import {
createAndLinkProductOptionsToProductWorkflow,
createProductCategoriesWorkflow,
createProductVariantsWorkflow,
createProductsWorkflow,
updateProductOptionsWorkflow,
updateProductOptionValuesWorkflow,
updateProductsWorkflow,
updateProductVariantsWorkflow,
} from "@medusajs/core-flows";
/** Nicht mehr im Shop: die abgelösten Kerzen aus der Shopify-Übernahme und
* der Adventskranz, der nur noch als Bild bei der Rillenkerze steht. */
const NICHT_IM_SHOP = ["bienenwachskerzen", "adventskranz"];
/** Die beiden Farben jeder Kerze; die erste ist vorausgewählt. */
const FARBEN = ["Honiggelb", "Elfenbeinweiß"];
/** Die Bilder liefert das Frontend aus (frontend/public/images/produkte).
* So kommen sie mit dem Frontend-Image auf jedes System, ohne Kopieren in
* das Upload-Volume des Backends. */
const BILDPFAD = "/images/produkte";
const PLATZHALTER = /\n*⚠️ Platzhalter:.*$/s;
/** Alle Kerzen sind handgemacht aus reinem Bienenwachs; der Titel sagt es
* im Muster der Honige ("Akazienhonig aus … - flüssig"). */
const PRODUKTE: {
handle: string;
titel: string;
kategorie: string;
/** Erstes Bild = Hauptbild: helle und dunkle Kerze gemeinsam, schlicht. */
aufnahmen: string[];
/** Nur für sichtbare Produkte, ersetzt den Platzhaltertext. */
beschreibung?: string;
/** Euro; gilt für alle Varianten. */
preis?: number;
/** Kerze in Honiggelb und Elfenbeinweiß. */
farben?: boolean;
sichtbar?: boolean;
}[] = [
// Schon vorhanden. Die Handles bleiben, damit Adressen stabil sind.
{
handle: "bubble-kerze",
titel: "Bubble-Würfel aus Bienenwachs - handgemacht",
kategorie: "Bienenprodukte",
aufnahmen: ["duo", "weihnacht"],
beschreibung: "Würfelkerze aus kleinen Wachskugeln, ca. 180 g. Handgemacht aus reinem Bienenwachs.",
preis: 9.9,
sichtbar: true,
farben: true,
},
{
handle: "regenbogen",
titel: "Regenbogenkerze aus Bienenwachs - handgemacht",
kategorie: "Bienenprodukte",
aufnahmen: ["duo", "weihnacht"],
beschreibung: "Kerze in Bogenform mit feinen Rillen. Handgemacht aus reinem Bienenwachs.",
preis: 7.9,
sichtbar: true,
farben: true,
},
// Eierform 1 ist die facettierte Tropfenform, Eierform 2 die gerippte Kugel.
{
handle: "eierform-1",
titel: "Tropfenkerze aus Bienenwachs - handgemacht",
kategorie: "Bienenprodukte",
aufnahmen: ["duo", "weihnacht"],
beschreibung: "Facettierte Kerze in Tropfenform. Handgemacht aus reinem Bienenwachs.",
preis: 5.5,
sichtbar: true,
farben: true,
},
{
handle: "eierform-2",
titel: "Lampionkerze aus Bienenwachs - handgemacht",
kategorie: "Bienenprodukte",
aufnahmen: ["duo", "weihnacht"],
beschreibung: "Runde, gerippte Kerze in Lampionform. Handgemacht aus reinem Bienenwachs.",
preis: 5.5,
sichtbar: true,
farben: true,
},
// Nicht in der Preisliste; Preise angelehnt an die vorhandenen Formen.
{
handle: "bubble-stumpenkerze",
titel: "Bubble-Stumpenkerze aus Bienenwachs - handgemacht",
kategorie: "Bienenprodukte",
aufnahmen: ["duo", "weihnacht"],
beschreibung: "Stumpenkerze mit Noppen-Oberfläche. Handgemacht aus reinem Bienenwachs.",
preis: 9.9,
sichtbar: true,
farben: true,
},
{
handle: "geriffelte-stumpenkerze",
titel: "Rillenkerze aus Bienenwachs - handgemacht",
kategorie: "Bienenprodukte",
aufnahmen: ["duo", "weihnacht", "adventskranz-gold", "adventskranz-elfenbein"],
beschreibung: "Stumpenkerze mit feinen Rillen und spitzer Krone. Handgemacht aus reinem Bienenwachs.",
preis: 7.9,
sichtbar: true,
farben: true,
},
// Von den Tannen gibt es nur weihnachtliche Paare.
{
handle: "bienenwachs-tannenbaum",
titel: "Tannenbaumkerze aus Bienenwachs - handgemacht",
kategorie: "Bienenprodukte",
aufnahmen: ["studio", "tafel", "sideboard"],
beschreibung: "Kerze in Tannenbaumform für die Weihnachtszeit. Handgemacht aus reinem Bienenwachs.",
preis: 5.5,
sichtbar: true,
farben: true,
},
// Keine Kerze: eigene Kategorie, ohne Farbwahl.
{
handle: "honigdipper",
titel: "Honiglöffel aus Holz",
kategorie: "Zubehör",
aufnahmen: ["studio", "wabe", "fruehstueck", "akazie"],
beschreibung:
"Für deinen süßen Genussmoment: Mit unserem Honiglöffel bringst du deinen Lieblingshonig auf Brot, in den Tee oder über dein Frühstück. Ein praktischer Begleiter für jeden Honigfan und eine schöne Ergänzung zum verschenkten Honigglas.",
preis: 5.9,
sichtbar: true,
},
];
export default async function ({ container }: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
let { data: kategorien } = await query.graph({
entity: "product_category",
fields: ["id", "name", "rank"],
});
// Fehlende Kategorien (z. B. "Zubehör") hinten anhängen.
for (const name of new Set(PRODUKTE.map((p) => p.kategorie))) {
if ((kategorien ?? []).some((c: any) => c.name === name)) continue;
const rang = Math.max(0, ...(kategorien ?? []).map((c: any) => c.rank ?? 0)) + 1;
const handle = name.toLowerCase().replace("ö", "oe").replace(/[^a-z0-9]+/g, "-");
const { result } = await createProductCategoriesWorkflow(container).run({
input: { product_categories: [{ name, handle, is_active: true, rank: rang }] },
});
kategorien = [...(kategorien ?? []), (result as any)[0]];
logger.info(`Kategorie "${name}" angelegt.`);
}
// Jeweils der älteste: Auf dem Testsystem kann ein abgebrochener Seed-Lauf
// einen zweiten "Default Sales Channel" hinterlassen haben.
const { data: profile } = await query.graph({
entity: "shipping_profile",
fields: ["id"],
pagination: { order: { created_at: "ASC" } },
});
const { data: kanaele } = await query.graph({
entity: "sales_channel",
fields: ["id"],
pagination: { order: { created_at: "ASC" } },
});
for (const p of PRODUKTE) {
const bilder = p.aufnahmen.map((a) => `${BILDPFAD}/produkt-${a}-${p.handle}.jpg`);
const kategorie = (kategorien ?? []).find((c: any) => c.name === p.kategorie);
const lesen = async () =>
(
await query.graph({
entity: "product",
fields: ["id", "title", "status", "description", "metadata", "variants.id"],
filters: { handle: p.handle },
})
).data?.[0];
// Fehlt das Produkt (etwa auf einem frischen System), zuerst als Entwurf
// anlegen; danach geht es für alle gleich weiter.
let produkt = await lesen();
if (!produkt) {
await createProductsWorkflow(container).run({
input: {
products: [
{
title: p.titel,
handle: p.handle,
status: "draft" as any,
description:
`${p.titel}.\n\n` +
"⚠️ Platzhalter: Beschreibung, Maße, Preis und Gewicht fehlen noch.",
shipping_profile_id: profile?.[0]?.id,
sales_channels: kanaele?.[0] ? [{ id: kanaele[0].id }] : undefined,
metadata: { category: p.kategorie, delivery_time: "2-3 Werktage" },
...(kategorie ? { category_ids: [kategorie.id] } : {}),
options: [{ title: "Ausführung", values: ["Standard"] }],
variants: [
{
title: "Standard",
options: { "Ausführung": "Standard" },
manage_inventory: false,
prices: p.preis !== undefined ? [{ amount: p.preis, currency_code: "eur" }] : [],
},
],
},
],
},
});
logger.info(`"${p.titel}" angelegt.`);
produkt = await lesen();
}
const update: any = {
title: p.titel,
category_ids: kategorie ? [kategorie.id] : undefined,
metadata: { ...(produkt.metadata ?? {}), category: p.kategorie },
thumbnail: bilder[0],
images: bilder.map((url: string) => ({ url })),
};
if (p.sichtbar) {
update.status = "published";
update.description = p.beschreibung ?? (produkt.description ?? "").replace(PLATZHALTER, "");
}
await updateProductsWorkflow(container).run({
input: { selector: { id: produkt.id }, update } as any,
});
if (p.preis !== undefined) {
for (const v of produkt.variants ?? []) {
await updateProductVariantsWorkflow(container).run({
input: {
selector: { id: v.id },
update: { prices: [{ amount: p.preis, currency_code: "eur" }] },
} as any,
});
}
}
if (p.farben) await farbenSetzen(container, produkt.id, p.preis);
logger.info(`"${p.titel}": ${bilder.length} Bilder (${update.status ?? produkt.status}).`);
}
for (const handle of NICHT_IM_SHOP) {
const { data: alt } = await query.graph({
entity: "product",
fields: ["id", "title", "status"],
filters: { handle },
});
if (alt?.[0] && alt[0].status !== "draft") {
await updateProductsWorkflow(container).run({
input: { selector: { id: alt[0].id }, update: { status: "draft" } } as any,
});
logger.info(`"${alt[0].title}" ist jetzt Entwurf und nicht mehr im Shop.`);
}
}
}
/**
* Macht aus der Option "Ausführung: Standard" die Option "Farbe" mit beiden
* Farben. Umbenennen statt ersetzen: Medusa lässt eine Option nicht los,
* solange Varianten an ihr hängen. Die vorhandene Variante wird Honiggelb
* (Bestellungen bleiben an ihr), Elfenbeinweiß kommt mit demselben Preis dazu.
*/
async function farbenSetzen(container: any, produktId: string, preis?: number) {
const query = container.resolve("query");
const lesen = async () =>
(
await query.graph({
entity: "product",
fields: [
"id",
"options.id",
"options.title",
"options.values.id",
"options.values.value",
"variants.id",
"variants.title",
"variants.prices.amount",
"variants.prices.currency_code",
],
filters: { id: produktId },
})
).data[0];
let produkt = await lesen();
const option = produkt.options.find((o: any) => ["Ausführung", "Farbe"].includes(o.title));
if (!option) throw new Error(`Produkt ${produktId}: keine Option "Ausführung" oder "Farbe".`);
if (option.title !== "Farbe") {
await updateProductOptionsWorkflow(container).run({
input: { selector: { id: option.id }, update: { title: "Farbe" } } as any,
});
}
const standard = option.values.find((v: any) => v.value === "Standard");
if (standard) {
await updateProductOptionValuesWorkflow(container).run({
input: { id: standard.id, update: { value: FARBEN[0] } },
});
}
produkt = await lesen();
const werte = produkt.options.find((o: any) => o.id === option.id).values.map((v: any) => v.value);
const fehlend = FARBEN.filter((f) => !werte.includes(f));
if (fehlend.length) {
await createAndLinkProductOptionsToProductWorkflow(container).run({
input: {
product_id: produktId,
update: [{ product_option_id: option.id, add: fehlend.map((value) => ({ value })) }],
},
});
}
const betrag =
preis ?? produkt.variants[0]?.prices?.find((x: any) => x.currency_code === "eur")?.amount;
const standardVariante = produkt.variants.find((v: any) => !FARBEN.includes(v.title));
if (standardVariante) {
await updateProductVariantsWorkflow(container).run({
input: { selector: { id: standardVariante.id }, update: { title: FARBEN[0] } } as any,
});
}
// Die alte Standard-Variante heißt nach dem Umbenennen Honiggelb.
const vorhanden = produkt.variants.map((v: any) =>
FARBEN.includes(v.title) ? v.title : FARBEN[0]
);
for (const farbe of FARBEN.filter((f) => !vorhanden.includes(f))) {
await createProductVariantsWorkflow(container).run({
input: {
product_variants: [
{
product_id: produktId,
title: farbe,
options: { Farbe: farbe },
manage_inventory: false,
prices: [{ amount: betrag, currency_code: "eur" }],
},
],
},
} as any);
}
}
@@ -0,0 +1,55 @@
/**
* Fotos für Lindenhonig, Sommerblütenhonig und Sonnenblumenhonig.
*
* npx medusa exec ./src/scripts/set-neue-honigbilder.ts
*
* Nur die Frühstücks- und die Outdoor-Aufnahme, ohne Studio. Die Frühstücks-
* aufnahme wird das Hauptbild. Vorhandene Bilder bleiben dahinter erhalten.
*
* Die Dateien liegen im Frontend (public/images/produkte) und kommen mit dem
* Frontend-Image mit — wie die Kerzenbilder.
*
* Wiederholbar: Was schon dran ist, wird nicht doppelt angehängt.
*/
import { updateProductsWorkflow } from "@medusajs/core-flows";
const SORTEN = [
{ datei: "linde", handle: "lindenhonig-aus-hamburg" },
{ datei: "sommer", handle: "sommerblutenhonig-aus-hamburg" },
{ datei: "sonnenblume", handle: "sonnenblumenhonig-aus-der-harzregion" },
];
const PFAD = (aufnahme: string, sorte: string) => `/images/produkte/produkt-${aufnahme}-${sorte}-250g.jpg`;
export default async function ({ container }: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
for (const sorte of SORTEN) {
const { data } = await query.graph({
entity: "product",
fields: ["id", "title", "images.url", "images.rank"],
filters: { handle: sorte.handle },
});
const produkt = data?.[0];
if (!produkt) {
logger.warn(`Kein Produkt mit Handle ${sorte.handle}.`);
continue;
}
const neu = [PFAD("fruehstueck", sorte.datei), PFAD("outdoor", sorte.datei)];
const bisher = [...(produkt.images ?? [])]
.sort((a: any, b: any) => (a.rank ?? 0) - (b.rank ?? 0))
.map((i: any) => i.url)
.filter((url: string) => !neu.includes(url));
const bilder = [...neu, ...bisher];
await updateProductsWorkflow(container).run({
input: {
selector: { id: produkt.id },
update: { thumbnail: neu[0], images: bilder.map((url) => ({ url })) },
} as any,
});
logger.info(`${produkt.title}: ${bilder.length} Bilder, Hauptbild Frühstück.`);
}
}
@@ -0,0 +1,129 @@
/**
* Feinschliff im Shop nach der Durchsicht vom November 2026.
*
* npx medusa exec ./src/scripts/set-shop-feinschliff.ts
*
* - Reihenfolge der Kategorien: erst alles zum Essen, dann Wachs, Kerzen,
* Pflege und Zubehör, dann Gutschein,
* Patenschaft, Kurs und Abo.
* - Text der eigenen Honig-Seife mit Zutatenliste (INCI, bei Kosmetik
* Pflicht). Der offene Hinweis dazu am Produkt fällt weg.
* - Honiglöffel ("Honigheber") kostet 5,90 €.
* - Die zugekaufte Honigseife (Lavendel, Gelee Royal, Propolis) wird nicht
* mehr verkauft: Entwurf statt löschen, Bestellungen bleiben erhalten.
*
* Wiederholbar: setzt nur Zielwerte.
*/
import {
updateProductCategoriesWorkflow,
updateProductsWorkflow,
updateProductVariantsWorkflow,
} from "@medusajs/core-flows";
const REIHENFOLGE = [
// Erst alles zum Essen, dann Wachs und Kerzen.
"honig",
"süßigkeiten-mit-honig",
"feinkost",
"bienenprodukte",
"pflegeprodukte",
"zubehoer",
"geschenkgutschein",
"bienenpatenschaften",
"kurse",
"abo",
];
const SEIFE = {
handle: "pflegeseife-milch-honig",
subtitle: "Handgemachte Pflegeseife mit Hamburger Stadthonig.",
description: [
"Handgemacht, Stück für Stück – mit Honig aus unserer eigenen Hamburger Imkerei.",
"Ein Stück Hamburg für deine tägliche Pflege: Unsere Seife mit eigenem Hamburger Stadthonig verbindet Ziegenmilch, Sheabutter, Kokosöl und Jojobaöl mit Calendula. Dazu ein angenehm weicher, frischer Duft – für eine kleine Auszeit am Waschbecken.",
"Von Hand hergestellt in Zusammenarbeit mit der Manufaktur Meerseifen Timmendorf.",
"Inhaltsstoffe: Aqua (Wasser), Butyrospermum Parkii Butter (Shea Butter), Cocos Nucifera Oil (Kokosnußöl), Brassica Napus Seed Oil (Rapsöl), Oryza Sativa Germ Oil (Reiskeimöl), Sodium Hydroxide (Natriumhydroxid), Simmondsia Chinensis Seed Oil (Jojobaöl mit Calendulablütenauszug), Parfum (ätherisches Öl) Citrus Sinensis Peel Oil, Mel (Honig), Caprae Lac (Ziegenmilch), Maris Sal (Meersalz), CI77492 (Eisenoxid, gelb), Limonene.",
"Frischgewicht: 100 g",
].join("\n\n"),
};
/** Kategorien in REIHENFOLGE bringen. Auch einzeln nutzbar (shop-reihenfolge). */
export async function kategorienSortieren(container: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
const { data: kategorien } = await query.graph({
entity: "product_category",
fields: ["id", "handle", "rank", "parent_category_id"],
});
// Der Reihe nach auf Platz 0, 1, 2 … setzen. Medusa schiebt die übrigen
// Geschwister dabei weiter, am Ende stimmt die Reihenfolge.
let platz = 0;
for (const handle of REIHENFOLGE) {
const kategorie = kategorien.find((k: any) => k.handle === handle && !k.parent_category_id);
if (!kategorie) {
logger.warn(`Keine Kategorie ${handle}.`);
continue;
}
if (kategorie.rank !== platz) {
await updateProductCategoriesWorkflow(container).run({
input: { selector: { id: kategorie.id }, update: { rank: platz } },
});
}
platz++;
}
logger.info("Kategorien neu sortiert.");
}
export default async function ({ container }: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
await kategorienSortieren(container);
const { data: produkte } = await query.graph({
entity: "product",
fields: ["id"],
filters: { handle: SEIFE.handle },
});
if (produkte?.[0]) {
await updateProductsWorkflow(container).run({
input: {
selector: { id: produkte[0].id },
update: {
subtitle: SEIFE.subtitle,
description: SEIFE.description,
// Leerer Wert entfernt den Schlüssel.
metadata: { offen: "" },
},
} as any,
});
logger.info("Text der Honig-Seife aktualisiert.");
} else {
logger.warn(`Kein Produkt mit Handle ${SEIFE.handle}.`);
}
const { data: loeffel } = await query.graph({
entity: "product",
fields: ["id", "variants.id"],
filters: { handle: "honigdipper" },
});
for (const v of loeffel?.[0]?.variants ?? []) {
await updateProductVariantsWorkflow(container).run({
input: { selector: { id: v.id }, update: { prices: [{ amount: 5.9, currency_code: "eur" }] } } as any,
});
}
if (loeffel?.[0]) logger.info("Honiglöffel: 5,90 €.");
const { data: alteSeife } = await query.graph({
entity: "product",
fields: ["id", "status"],
filters: { handle: "seife-aus-unserem-honig" },
});
if (alteSeife?.[0] && alteSeife[0].status !== "draft") {
await updateProductsWorkflow(container).run({
input: { selector: { id: alteSeife[0].id }, update: { status: "draft" } } as any,
});
logger.info("Zugekaufte Honigseife ist jetzt Entwurf und nicht mehr im Shop.");
}
}
@@ -0,0 +1,41 @@
/**
* Neue Fotos für Honig-Doppelbärchen, Honigwaffeln, Honig-Lakritz und Honig-Bonbons.
*
* npx medusa exec ./src/scripts/set-snackbilder.ts
*
* Ersetzt die bisherigen Bilder ganz. Hauptbild ist die Packung auf
* Elfenbein, dahinter die Szenen mit Packung und der Teller.
* Die Dateien liegen im Frontend (public/images/produkte).
*
* Wiederholbar.
*/
import { updateProductsWorkflow } from "@medusajs/core-flows";
const SNACKS = [
{ handle: "gummibarchen", datei: "doppelbaerchen", szenen: ["wohnzimmer"] },
{ handle: "honigwaffeln", datei: "honigwaffeln", szenen: ["tisch"] },
{ handle: "honig-lakritze", datei: "honig-lakritz", szenen: ["wohnzimmer"] },
{ handle: "honig-bonbons", datei: "honig-bonbons", szenen: ["tisch", "unterwegs"] },
];
export default async function ({ container }: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
for (const snack of SNACKS) {
const { data } = await query.graph({ entity: "product", fields: ["id", "title"], filters: { handle: snack.handle } });
const produkt = data?.[0];
if (!produkt) {
logger.warn(`Kein Produkt mit Handle ${snack.handle}.`);
continue;
}
const bilder = ["studio", ...snack.szenen, "teller"].map((a) => `/images/produkte/produkt-${a}-${snack.datei}.jpg`);
await updateProductsWorkflow(container).run({
input: {
selector: { id: produkt.id },
update: { thumbnail: bilder[0], images: bilder.map((url) => ({ url })) },
} as any,
});
logger.info(`${produkt.title}: ${bilder.length} neue Bilder.`);
}
}
@@ -0,0 +1,99 @@
/**
* Zutaten und Nährwerte der Honig-Süßigkeiten (Angaben vom Team, November 2026).
*
* npx medusa exec ./src/scripts/set-snacks-texte.ts
*
* Allergene stehen in GROSSBUCHSTABEN: Die LMIV verlangt sie in der
* Zutatenliste hervorgehoben, auch im Onlineshop, und die Beschreibung ist
* reiner Text ohne Fettdruck.
*
* Wiederholbar: setzt nur Zielwerte.
*/
import { updateProductsWorkflow } from "@medusajs/core-flows";
const absatz = (...teile: string[]) => teile.join("\n\n");
const naehrwerte = (zeilen: [string, string][]) =>
["Nährwerte pro 100 g:", ...zeilen.map(([name, wert]) => `${name}: ${wert}`)].join("\n");
const TEXTE: Record<string, string> = {
"honig-lakritze": absatz(
"Die Honig-Lakritze zeichnen sich durch ihre Bienenkorbform und den leicht würzigen Geschmack aus.",
"Inhalt: 100 g",
"Zutaten: Zucker, Glukosesirup, modifizierte Kartoffelstärke, Rohrzuckermelasse, WEIZENSTÄRKE, Honig (8 %), Süßholzwurzelextrakt (1,6 %), Salmiaksalz, Wasser, Kokosöl, Überzugsmittel (E901).",
naehrwerte([
["Energie", "1457 kJ / 343 kcal"],
["Fett", "0,3 g"],
["• davon gesättigte Fettsäuren", "0,2 g"],
["Kohlenhydrate", "84,7 g"],
["• davon Zucker", "57,6 g"],
["Eiweiß", "0,3 g"],
["Salz", "0,21 g"],
])
),
gummibarchen: absatz(
"Die Honig-Doppelbärchen gehören wegen ihres fruchtig-frischen Geschmacks zu den beliebtesten Honig-Süßigkeiten – mit Honig und Vitaminen.",
"Inhalt: 100 g",
"Zutaten: Glucosesirup; Zucker; Gelatine (Schwein); Honig 5 %; Säuerungsmittel: Citronensäure; Fruchtsaftkonzentrate (Maracuja, Zitrone, Kirsche); Vitamine: Vitamin E, Niacin, Vitamin B6, Thiamin; pflanzliches Öl (Kokosnuss, Rapssamen); Überzugsmittel: Bienenwachs (weiß), Carnaubawachs; Aromen; Farbstoff: Beta-Carotin.",
"Kann Spuren von GLUTEN und MILCH enthalten.",
naehrwerte([
["Energie", "1453 kJ / 342 kcal"],
["Fett", "0,2 g"],
["• davon gesättigte Fettsäuren", "0,2 g"],
["Kohlenhydrate", "77 g"],
["• davon Zucker", "56 g"],
["Eiweiß", "6,9 g"],
["Salz", "0,10 g"],
["Vitamin E", "35 mg ≈ 292 %*"],
["Vitamin B6", "1,8 mg ≈ 129 %*"],
["Thiamin", "1,5 mg ≈ 136 %*"],
["Niacin", "17 mg ≈ 106 %*"],
["Biotin", "400 µg ≈ 800 %*"],
]) + "\n* % der Referenzmenge für die tägliche Zufuhr von Vitaminen"
),
honigwaffeln: absatz(
"Unsere Honigwaffeln mit Rahmbutter, Honig, Vanille und Zimt gehören zu den meistverkauften Süßigkeiten mit Honig – und das nicht ohne Grund: Geschmack und Konsistenz sind einfach klasse.",
"Inhalt: 90 g",
"Zutaten: WEIZENMEHL, 32 % Sirup (Glucose-Fructose-Sirup, Zucker, 11 % BUTTER, 10 % Honig, Stärke, Emulgator: Sonnenblumenlecithin), 14 % BUTTERREINFETT (Carotin), Zucker, Glucose-Fructose-Sirup, EIER aus Freilandhaltung, Backtriebmittel (Natriumcarbonat, Ammoniumcarbonat), Salz, Stärke, Emulgator: Sonnenblumenlecithin, Zimt.",
"Kann Spuren von ERDNÜSSEN und NÜSSEN (MANDELN) enthalten.",
naehrwerte([
["Energie", "1978 kJ / 468 kcal"],
["Fett", "18 g"],
["• davon gesättigte Fettsäuren", "12 g"],
["Kohlenhydrate", "71 g"],
["• davon Zucker", "36 g"],
["Eiweiß", "5 g"],
["Salz", "0,38 g"],
])
),
"honig-bonbons": absatz(
"Die Honigbienen-Bonbons sind ungefüllt und perfekt für den kleinen Snack zwischendurch. Optisch machen sie auch was her: Auf beiden Seiten ist eine Bienenkönigin eingearbeitet.",
"Inhalt: 100 g",
"Zutaten: Zucker, Glukosesirup, Honig (6,5 %).",
naehrwerte([
["Energie", "1655 kJ / 389 kcal"],
["Fett", "0,1 g"],
["• davon gesättigte Fettsäuren", "< 0,1 g"],
["Kohlenhydrate", "96,1 g"],
["• davon Zucker", "64,0 g"],
["Eiweiß", "0,1 g"],
["Salz", "0,0 g"],
])
),
};
export default async function ({ container }: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
for (const [handle, text] of Object.entries(TEXTE)) {
const { data } = await query.graph({ entity: "product", fields: ["id", "title"], filters: { handle } });
if (!data?.[0]) {
logger.warn(`Kein Produkt mit Handle ${handle}.`);
continue;
}
await updateProductsWorkflow(container).run({
input: { selector: { id: data[0].id }, update: { description: text } } as any,
});
logger.info(`${data[0].title}: Text aktualisiert.`);
}
}
@@ -0,0 +1,30 @@
/**
* Nachtrag zu den Produkttexten (November 2026): Honiglöffel und
* Honig-Balsamico-Essig mit den Texten vom Team.
*
* npx medusa exec ./src/scripts/set-texte-nachtrag.ts
*
* Eigenes Skript, weil die vorherigen Migrationsskripte auf dem Testsystem
* schon gelaufen sein können und dann nicht noch einmal laufen.
* Wiederholbar.
*/
import { updateProductsWorkflow } from "@medusajs/core-flows";
import honigEssig from "./set-honig-essig";
const LOEFFEL =
"Für deinen süßen Genussmoment: Mit unserem Honiglöffel bringst du deinen Lieblingshonig auf Brot, in den Tee oder über dein Frühstück. Ein praktischer Begleiter für jeden Honigfan und eine schöne Ergänzung zum verschenkten Honigglas.";
export default async function ({ container }: any) {
const query = container.resolve("query");
const logger = container.resolve("logger");
const { data } = await query.graph({ entity: "product", fields: ["id"], filters: { handle: "honigdipper" } });
if (data?.[0]) {
await updateProductsWorkflow(container).run({
input: { selector: { id: data[0].id }, update: { description: LOEFFEL } } as any,
});
logger.info("Honiglöffel: Text aktualisiert.");
}
await honigEssig({ container });
}
+1
View File
@@ -32,6 +32,7 @@
"@medusajs/cli": "2.17.2",
"@medusajs/dashboard": "2.17.2",
"@medusajs/draft-order": "2.17.2",
"@medusajs/file-local": "2.17.2",
"@medusajs/framework": "2.17.2",
"@medusajs/loyalty-plugin": "2.17.2",
"@medusajs/medusa": "2.17.2",
+4 -1
View File
@@ -106,7 +106,10 @@ services:
# Frontend und Backend teilen sich die Domain. Ohne diese beiden schickt
# Mollie den Kunden nach localhost zurück und meldet die Zahlung nie.
MOLLIE_WEBHOOK_URL: ${MEDUSA_BACKEND_URL}/hooks/mollie
STOREFRONT_URL: ${MEDUSA_BACKEND_URL}
# Adresse des Shops für Links in Mails (Einladung, Passwort, Bestätigung).
# Ohne eigenen Wert die Backend-Adresse — passt nur, wenn beide unter
# einer Domain laufen. Im Testsystem auf https://test.place4bees.com setzen.
STOREFRONT_URL: ${STOREFRONT_URL:-${MEDUSA_BACKEND_URL}}
SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-}
SMTP_USER: ${SMTP_USER:-}
Binary file not shown.

After

Width:  |  Height:  |  Size: 314 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 474 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 485 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 525 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 545 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 594 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 596 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 371 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 364 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 406 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 293 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 275 KiB

@@ -7,6 +7,8 @@ interface Variant {
interface Props {
variants: Variant[];
regionId: string;
/** Überschrift über der Variantenwahl, z. B. "Farbe" bei den Kerzen. */
variantLabel?: string;
/**
* Ob der Mengenwähler angezeigt wird. Beim Abo nicht: dort steht die Menge
* schon in der Sortenauswahl und steuert dort die Zahl der Gläser.
@@ -26,6 +28,7 @@ interface Props {
const {
variants,
regionId,
variantLabel = "Variante",
showQuantity = true,
giftSurchargeVariantId = null,
isSponsorship = false,
@@ -36,7 +39,7 @@ const {
<div>
{variants.length > 1 && (
<fieldset id="variant-picker" class="mb-7" aria-labelledby="variant-picker-label">
<p id="variant-picker-label" class="field-label">Variante</p>
<p id="variant-picker-label" class="field-label">{variantLabel}</p>
<div class="flex flex-wrap gap-2">
{variants.map((variant, index) => (
<label class="relative">
+31 -5
View File
@@ -1,16 +1,23 @@
---
interface Props {
label: string;
/** Ein Zeilenumbruch ("\n") setzt eine feste Zeile, z. B. bei zwei Sätzen. */
title: string;
lede?: string;
/** Optional photo used as a full-bleed backdrop instead of the textured
* cream ground. */
image?: string;
imageAlt?: string;
/** Optionales Foto rechts neben dem Text, auf hellem Grund (ab lg). */
sideImage?: string;
sideImageAlt?: string;
}
const { label, title, lede, image, imageAlt = "" } = Astro.props;
const { label, title, lede, image, imageAlt = "", sideImage, sideImageAlt = "" } = Astro.props;
const dark = Boolean(image);
// Mit festen Zeilen bestimmt der Text die Breite, nicht die 16ch-Grenze —
// sonst bricht jede Zeile noch einmal mittendrin um.
const titleLines = title.split("\n");
---
<!--
@@ -40,21 +47,40 @@ const dark = Boolean(image);
</div>
) : null}
<div class="relative mx-auto max-w-[84rem] px-[var(--gutter)] pt-36 pb-16 sm:pt-44 sm:pb-24">
<div
class:list={[
"relative mx-auto max-w-[84rem] px-[var(--gutter)] pt-36 pb-16 sm:pt-44 sm:pb-24",
sideImage && "grid items-center gap-12 lg:grid-cols-[1.2fr_1fr]",
]}
>
<div>
<span class:list={["reveal section-label", dark && "section-label-light"]}>{label}</span>
<h1
class:list={["reveal mt-6 max-w-[16ch]", dark ? "text-white" : "text-brand-ink"]}
class:list={[
"reveal mt-6",
titleLines.length > 1 ? "max-w-full" : "max-w-[16ch]",
dark ? "text-white" : "text-brand-ink",
]}
style="--delay: 0.08s"
>
{title}
{titleLines.length > 1 ? titleLines.map((zeile) => <span class="block">{zeile}</span>) : title}
</h1>
{lede && (
<p
class:list={["reveal lede mt-7", dark ? "text-white/70" : "text-brand-text"]}
class:list={["reveal lede mt-7 whitespace-pre-line", dark ? "text-white/70" : "text-brand-text"]}
style="--delay: 0.16s"
>
{lede}
</p>
)}
</div>
{sideImage && (
<img
src={sideImage}
alt={sideImageAlt}
class="reveal aspect-[4/5] w-full max-w-[26rem] justify-self-center rounded-[var(--radius-inner)] object-cover shadow-md lg:justify-self-end"
style="--delay: 0.2s"
/>
)}
</div>
</section>
@@ -71,7 +71,7 @@ const schritte = [
<!-- 2 · Logoband. Weiß, 15px oben und unten. -->
<section class="bg-white py-[15px]">
<div class="p4b-breite flex justify-center">
<img src="/images/newLogo.png" alt="place4bees – Hamburger Stadtimkerei" width="1890" height="1486" class="h-auto w-[220px]" />
<img src="/images/logo-modern-beekeeping.png" alt="PLACE4BEES – modern beekeeping, est. 2021" width="780" height="494" class="h-auto w-[260px]" />
</div>
</section>
@@ -130,24 +130,28 @@ const schritte = [
</div>
</section>
<!-- 5 · Mittendrin statt nur dabei. Hintergrundfoto, Text mittig. -->
<section
class="p4b-mittendrin flex min-h-[50vh] items-center py-10"
style="background-image: url('/images/p4b/unternehmensbienen-20-scaled.jpg')"
>
<div class="p4b-breite text-center">
<!-- 5 · Mittendrin statt nur dabei. Text links, echtes Foto rechts — wie
Abschnitt 3 und 4, statt Text auf einem Stockfoto. -->
<section class="grid min-h-[40vh] md:grid-cols-2">
<div class="p4b-spalte-text flex flex-col justify-center">
<h4 class="p4b-eyebrow">Mittendrin statt nur dabei!</h4>
<h2 class="p4b-h2 mt-2">Erlebbares Nachhaltigkeitsengagement</h2>
<p class="mt-4">Umweltschutz und Nachhaltigkeit sind Zeitgeist.</p>
<p class="mt-6">
Um so schöner und besonders spürbar ist Ihr Nachhaltigkeitsengagement, wenn Sie es direkt vor
Ort erleben<br />und aktiv mitgestalten können.
Umweltschutz und Nachhaltigkeit sind Zeitgeist. Umso schöner und spürbarer ist Ihr
Engagement, wenn Sie es direkt vor Ort erleben und aktiv mitgestalten können.
</p>
<p class="mt-6">
Mit einem Unternehmensbienen-Projekt ermöglichen Sie Ihrem Team naturnahe und spannende
Erlebnisse –<br />und das jeden Tag und direkt vor Ort.
Erlebnisse – jeden Tag und direkt vor Ort.
</p>
</div>
<div
class="p4b-spalte-bild min-h-[40vh]"
style="background-image: url('/images/p4b/philosophie-11.jpg')"
role="img"
aria-label="Eine Imkerin zeigt einem Kind eine Wabe mit Bienen"
>
</div>
</section>
<!-- 6 · Was uns antreibt. Karte mit Schatten, 60px Außenabstand. -->
+111
View File
@@ -0,0 +1,111 @@
import { medusaConfig, medusaFetch } from "./medusa";
/** Firmenportal: Daten des angemeldeten Firmenkunden. */
export interface B2bDelivery {
title: string;
quantity: string | null;
planned_at: string | null;
shipped_at: string | null;
tracking_number: string | null;
status: "planned" | "shipped" | "delivered";
}
export interface B2bReport {
id: string;
title: string;
body: string | null;
images: string[];
published_at: string;
}
export interface B2bSponsorship {
id: string;
title: string;
colonies: number;
location: string | null;
start_date: string | null;
end_date: string | null;
price: number | null;
status: "offer" | "active" | "renewal" | "ended";
deliveries: B2bDelivery[];
reports: B2bReport[];
}
export interface B2bDocument {
id: string;
title: string;
kind: "contract" | "certificate" | "invoice" | "offer" | "other";
file_name: string;
sponsorship_id: string | null;
created_at: string;
}
export interface B2bPortal {
company: { name: string; street: string | null; postal_code: string | null; city: string | null; vat_id: string | null };
contacts: { name: string; email: string; role: string | null; has_login: boolean }[];
sponsorships: B2bSponsorship[];
documents: B2bDocument[];
inquiries: { kind: string; colonies: number | null; message: string | null; status: "open" | "done"; created_at: string }[];
}
export const PATEN_STATUS: Record<string, string> = {
offer: "Angebot",
active: "Aktiv",
renewal: "Verlängerung steht an",
ended: "Beendet",
};
export const LIEFER_STATUS: Record<string, string> = {
planned: "Geplant",
shipped: "Versendet",
delivered: "Zugestellt",
};
export const DOKUMENT_ARTEN: Record<string, string> = {
contract: "Vertrag",
certificate: "Urkunde",
invoice: "Rechnung",
offer: "Angebot",
other: "Dokument",
};
export const ANFRAGE_ARTEN: Record<string, string> = {
new: "Neue Patenschaft",
more: "Mehr Völker",
other: "Sonstiges",
};
/** Portal-Daten, oder `null`, wenn das Konto zu keiner Firma gehört. */
export async function getMyCompany(token: string): Promise<B2bPortal | null> {
const { url, key } = medusaConfig();
const res = await fetch(`${url}/store/customers/me/b2b`, {
headers: { Authorization: `Bearer ${token}`, "x-publishable-api-key": key },
});
if (res.status === 404) return null;
if (!res.ok) throw new Error(`Firmenportal nicht ladbar (${res.status})`);
return res.json();
}
export async function getInvite(token: string): Promise<{ email: string; first_name: string | null; company: string } | null> {
try {
return await medusaFetch(`/store/b2b/invite?token=${encodeURIComponent(token)}`);
} catch {
return null;
}
}
export async function acceptInvite(token: string, password: string): Promise<{ email: string }> {
return medusaFetch("/store/b2b/invite", { method: "POST", body: JSON.stringify({ token, password }) });
}
export async function createInquiry(
token: string,
payload: { kind: string; colonies?: number | null; message?: string }
): Promise<void> {
await medusaFetch("/store/customers/me/b2b/inquiries", {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify(payload),
});
}

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