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>
This commit is contained in:
torbinus
2026-11-05 12:11:03 +01:00
parent 22d3e25fe2
commit 9b368f9b7a
37 changed files with 4727 additions and 0 deletions
+4
View File
@@ -91,6 +91,10 @@ module.exports = defineConfig({
// Honig-Abos: eigenes Modell, weil Medusa keine Abos kennt. // Honig-Abos: eigenes Modell, weil Medusa keine Abos kennt.
resolve: "./src/modules/subscription", resolve: "./src/modules/subscription",
}, },
{
// Firmenkunden (CRM) mit eigenen B2B-Patenschaften und Firmenportal.
resolve: "./src/modules/b2b",
},
{ {
resolve: "@medusajs/medusa/file", resolve: "@medusajs/medusa/file",
options: { options: {
+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,130 @@
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";
async function mailen(scope: any, an: string, vorlage: string, inhalt: { subject: string; html: string; text: string }) {
const notification: any = scope.resolve(Modules.NOTIFICATION);
await notification.createNotifications({ to: an, channel: "email", template: vorlage, content: inhalt });
}
/**
* 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 service.updateContacts({
id: kontakt.id,
customer_id: kunde.id,
invited_at: jetzt,
accepted_at: jetzt,
invite_token_hash: null,
invite_expires_at: null,
});
await mailen(
scope,
kontakt.email,
"b2b-access",
firmenZugangMail({
firma: kontakt.company.name,
vorname: kontakt.first_name,
link: `${storefront()}/konto/anmelden?redirect=/konto/firma`,
})
);
return "linked";
}
const token = randomBytes(32).toString("base64url");
await service.updateContacts({
id: kontakt.id,
invite_token_hash: tokenHash(token),
invite_expires_at: new Date(jetzt.getTime() + GUELTIG_TAGE * 86400000),
invited_at: jetzt,
});
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,
})
);
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. */ /** Schlusszeile für Mails, auf die man eine Rückfrage haben könnte. */
const RUECKFRAGE = `Fragen? Schreiben Sie uns an ${SHOP.email}.`; const RUECKFRAGE = `Fragen? Schreiben Sie uns an ${SHOP.email}.`;
@@ -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;
+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),
});
}
+81
View File
@@ -0,0 +1,81 @@
---
import Layout from "../../layouts/Layout.astro";
import { getInvite } from "../../lib/b2b";
export const prerender = false;
const token = Astro.url.searchParams.get("token") ?? "";
const einladung = token ? await getInvite(token) : null;
---
<Layout title="Firmenportal – Zugang einrichten" description="Legen Sie Ihr Passwort für das place4bees-Firmenportal fest.">
<section class="honeycomb-bg pt-24 pb-[var(--section-y)] sm:pt-28">
<div class="mx-auto max-w-[30rem] px-[var(--gutter)]">
<span class="section-label">Firmenportal</span>
<h1 class="mt-5">Zugang einrichten</h1>
{einladung ? (
<form id="invite-form" class="surface mt-10 grid gap-5 p-7 shadow-xs sm:p-8" data-token={token} data-email={einladung.email}>
<p class="text-brand-text">
{einladung.first_name ? `Hallo ${einladung.first_name}, l` : "L"}egen Sie Ihr Passwort für den Zugang von
<strong class="text-brand-ink">{einladung.company}</strong> fest.
</p>
<div>
<label class="field-label" for="invite-email">E-Mail</label>
<input id="invite-email" class="field" type="email" value={einladung.email} disabled autocomplete="username" />
</div>
<div>
<label class="field-label" for="invite-password">Passwort (mindestens 8 Zeichen)</label>
<input id="invite-password" class="field" type="password" name="password" required minlength="8" autocomplete="new-password" />
</div>
<p id="invite-status" role="alert" class="hidden text-sm text-[#b4453a]"></p>
<button type="submit" class="btn btn-primary mt-1 w-full disabled:pointer-events-none disabled:opacity-55">
Zugang einrichten
</button>
</form>
) : (
<div class="surface mt-10 p-7 shadow-xs sm:p-8">
<p class="text-brand-text">
Dieser Link ist abgelaufen oder wurde schon benutzt. Haben Sie Ihr Passwort bereits festgelegt, melden Sie sich
einfach an. Sonst schicken wir Ihnen gern eine neue Einladung: kontakt@place4bees.com.
</p>
<a href="/konto/anmelden?redirect=/konto/firma" class="btn btn-primary mt-6 w-full">Zur Anmeldung</a>
</div>
)}
</div>
</section>
</Layout>
<script>
import { acceptInvite } from "../../lib/b2b";
import { loginCustomer } from "../../lib/auth";
import { setCustomerTokenClient } from "../../lib/customerCookie";
document.addEventListener("astro:page-load", () => {
const form = document.getElementById("invite-form") as HTMLFormElement | null;
const status = document.getElementById("invite-status");
if (!form) return;
const token = form.dataset.token ?? "";
// Das Token nicht im Verlauf stehen lassen.
history.replaceState(history.state, "", window.location.pathname);
form.addEventListener("submit", async (event) => {
event.preventDefault();
const button = form.querySelector("button[type=submit]") as HTMLButtonElement;
button.disabled = true;
status?.classList.add("hidden");
const passwort = String(new FormData(form).get("password"));
try {
const { email } = await acceptInvite(token, passwort);
setCustomerTokenClient(await loginCustomer(email, passwort));
window.location.href = "/konto/firma";
} catch (err) {
if (status) {
status.textContent = err instanceof Error ? err.message : "Das hat nicht geklappt.";
status.classList.remove("hidden");
}
button.disabled = false;
}
});
});
</script>
@@ -0,0 +1,28 @@
import type { APIRoute } from "astro";
import { medusaConfig } from "../../../../lib/medusa";
export const prerender = false;
/**
* Dokument-Download fürs Firmenportal. Ein Link im Browser kann kein
* Bearer-Token mitschicken; deshalb holt diese Route die Datei mit dem
* Token aus dem Cookie und reicht sie durch.
*/
export const GET: APIRoute = async ({ params, cookies, redirect }) => {
const token = cookies.get("customer_jwt")?.value;
if (!token) return redirect(`/konto/anmelden?redirect=/konto/firma`);
const { url, key } = medusaConfig();
const res = await fetch(`${url}/store/customers/me/b2b/documents/${encodeURIComponent(params.id ?? "")}`, {
headers: { Authorization: `Bearer ${token}`, "x-publishable-api-key": key },
});
if (!res.ok) return new Response("Dokument nicht gefunden.", { status: res.status === 401 ? 401 : 404 });
return new Response(res.body, {
headers: {
"Content-Type": res.headers.get("Content-Type") ?? "application/octet-stream",
"Content-Disposition": res.headers.get("Content-Disposition") ?? "attachment",
"Cache-Control": "private, no-store",
},
});
};
+273
View File
@@ -0,0 +1,273 @@
---
import Layout from "../../../layouts/Layout.astro";
import {
ANFRAGE_ARTEN,
DOKUMENT_ARTEN,
getMyCompany,
LIEFER_STATUS,
PATEN_STATUS,
type B2bPortal,
} from "../../../lib/b2b";
export const prerender = false;
const token = Astro.cookies.get("customer_jwt")?.value;
if (!token) {
return Astro.redirect("/konto/anmelden?redirect=/konto/firma");
}
let portal: B2bPortal | null;
try {
portal = await getMyCompany(token);
} catch {
Astro.cookies.delete("customer_jwt", { path: "/" });
return Astro.redirect("/konto/anmelden?redirect=/konto/firma");
}
// Kein Firmenkunde: Das normale Konto ist der richtige Ort.
if (!portal) return Astro.redirect("/konto");
const datum = (wert: string | null | undefined) =>
wert ? new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(new Date(wert)) : null;
const euro = (wert: number | null) =>
wert === null || wert === undefined
? null
: new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(Number(wert));
const laufend = portal.sponsorships.filter((p) => p.status === "active" || p.status === "renewal");
const voelker = laufend.reduce((summe, p) => summe + p.colonies, 0);
const titelZu = new Map(portal.sponsorships.map((p) => [p.id, p.title]));
---
<Layout title="Firmenportal" description="Ihre Bienenpatenschaften bei place4bees im Überblick.">
<section class="honeycomb-bg pt-24 pb-[var(--section-y)] sm:pt-28">
<div class="mx-auto max-w-[60rem] px-[var(--gutter)]">
<a href="/konto" class="text-sm text-brand-text hover:text-brand-ink">← Mein Konto</a>
<span class="section-label mt-6 block">Firmenportal</span>
<h1 class="mt-5">{portal.company.name}</h1>
<p class="mt-2.5 text-brand-text">
{laufend.length > 0
? `${laufend.length} laufende Patenschaft${laufend.length > 1 ? "en" : ""} mit ${voelker} ${voelker === 1 ? "Bienenvolk" : "Bienenvölkern"}`
: "Zurzeit keine laufende Patenschaft"}
</p>
<h2 class="mt-16 text-h3">Ihre Bienenpatenschaften</h2>
{portal.sponsorships.length === 0 && (
<div class="surface mt-6 px-8 py-12 text-center shadow-xs">
<p class="text-brand-text">Sobald Ihre Patenschaft eingerichtet ist, finden Sie sie hier.</p>
</div>
)}
<div class="mt-6 grid gap-6">
{portal.sponsorships.map((p) => (
<article class="surface p-6 shadow-xs sm:p-8">
<div class="flex flex-wrap items-start justify-between gap-4">
<div>
<h3 class="text-xl font-medium text-brand-ink">{p.title}</h3>
<p class="mt-1 text-sm text-brand-text-muted">
{[
`${p.colonies} ${p.colonies === 1 ? "Bienenvolk" : "Bienenvölker"}`,
p.location,
datum(p.start_date) && `${datum(p.start_date)} – ${datum(p.end_date) ?? "offen"}`,
]
.filter(Boolean)
.join(" · ")}
</p>
</div>
<span
class:list={[
"rounded-[6px] px-3 py-1.5 text-xs font-medium",
p.status === "renewal" ? "bg-brand-primary text-brand-ink" : "bg-brand-surface-sunk text-brand-text",
]}
>
{PATEN_STATUS[p.status] ?? p.status}
</span>
</div>
{euro(p.price) && <p class="mt-3 text-sm text-brand-text">Preis: {euro(p.price)} netto für die Laufzeit</p>}
<div class="mt-8 grid gap-8 md:grid-cols-[1fr_1.4fr]">
<div>
<h4 class="text-sm font-medium uppercase tracking-wide text-brand-text-muted">Lieferungen</h4>
{p.deliveries.length === 0 ? (
<p class="mt-3 text-sm text-brand-text">Noch keine Lieferungen geplant.</p>
) : (
<ul class="mt-3 grid gap-3">
{p.deliveries.map((l) => (
<li class="border-l-2 border-brand-primary pl-4">
<p class="font-medium text-brand-ink">{l.title}</p>
<p class="text-sm text-brand-text">
{[
l.quantity,
l.status === "planned"
? datum(l.planned_at) && `geplant ${datum(l.planned_at)}`
: `${LIEFER_STATUS[l.status]}${datum(l.shipped_at) ? ` am ${datum(l.shipped_at)}` : ""}`,
]
.filter(Boolean)
.join(" · ") || LIEFER_STATUS[l.status]}
</p>
{l.tracking_number && <p class="text-sm text-brand-text-muted">Sendungsnummer {l.tracking_number}</p>}
</li>
))}
</ul>
)}
</div>
<div>
<h4 class="text-sm font-medium uppercase tracking-wide text-brand-text-muted">Neuigkeiten von Ihren Völkern</h4>
{p.reports.length === 0 ? (
<p class="mt-3 text-sm text-brand-text">Bald berichten wir hier, wie es Ihren Bienen geht.</p>
) : (
<div class="mt-3 grid gap-6">
{p.reports.map((r) => (
<div>
<p class="text-sm text-brand-text-muted">{datum(r.published_at)}</p>
<p class="font-medium text-brand-ink">{r.title}</p>
{r.body && <p class="mt-1.5 whitespace-pre-line text-sm leading-relaxed text-brand-text">{r.body}</p>}
{r.images.length > 0 && (
<div class="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-3">
{r.images.map((bild) => (
<a href={bild} target="_blank" rel="noopener">
<img src={bild} alt="" loading="lazy" class="aspect-square w-full rounded-[8px] object-cover" />
</a>
))}
</div>
)}
</div>
))}
</div>
)}
</div>
</div>
</article>
))}
</div>
<h2 class="mt-16 text-h3">Dokumente</h2>
{portal.documents.length === 0 ? (
<p class="mt-4 text-brand-text">Noch keine Dokumente hinterlegt.</p>
) : (
<ul class="mt-6 grid gap-3">
{portal.documents.map((d) => (
<li>
<a
href={`/konto/firma/dokument/${d.id}`}
class="group card-interactive flex flex-wrap items-center justify-between gap-x-6 gap-y-2 p-5"
>
<div>
<p class="font-medium text-brand-ink">{d.title}</p>
<p class="mt-1 text-sm text-brand-text-muted">
{[DOKUMENT_ARTEN[d.kind], d.sponsorship_id && titelZu.get(d.sponsorship_id), datum(d.created_at)]
.filter(Boolean)
.join(" · ")}
</p>
</div>
<span class="text-sm font-medium text-brand-primary">Herunterladen</span>
</a>
</li>
))}
</ul>
)}
<h2 class="mt-16 text-h3">Anfrage an uns</h2>
<p class="mt-2 text-brand-text">Mehr Völker, eine weitere Patenschaft oder eine Frage? Wir melden uns schnellstmöglich.</p>
<form id="anfrage-form" class="surface mt-6 grid gap-5 p-7 shadow-xs sm:p-8">
<div class="grid gap-5 sm:grid-cols-2">
<div>
<label class="field-label" for="anfrage-art">Worum geht es?</label>
<select id="anfrage-art" name="kind" class="field" required>
<option value="more">Mehr Völker für eine bestehende Patenschaft</option>
<option value="new">Neue Patenschaft</option>
<option value="other">Sonstiges</option>
</select>
</div>
<div>
<label class="field-label" for="anfrage-voelker">Anzahl Völker (optional)</label>
<input id="anfrage-voelker" name="colonies" class="field" type="number" min="1" max="1000" />
</div>
</div>
<div>
<label class="field-label" for="anfrage-text">Nachricht</label>
<textarea id="anfrage-text" name="message" class="field min-h-28" maxlength="5000"></textarea>
</div>
<p id="anfrage-status" role="status" class="hidden text-sm"></p>
<div>
<button type="submit" class="btn btn-primary disabled:pointer-events-none disabled:opacity-55">Anfrage senden</button>
</div>
</form>
{portal.inquiries.length > 0 && (
<ul class="mt-6 grid gap-2 text-sm text-brand-text">
{portal.inquiries.map((a) => (
<li>
{datum(a.created_at)} · {ANFRAGE_ARTEN[a.kind] ?? a.kind}
{a.colonies ? ` (${a.colonies} Völker)` : ""} ·{" "}
<span class="font-medium">{a.status === "open" ? "in Bearbeitung" : "erledigt"}</span>
</li>
))}
</ul>
)}
<h2 class="mt-16 text-h3">Ihre Firma bei uns</h2>
<div class="mt-6 grid gap-6 sm:grid-cols-2">
<div class="surface p-6 shadow-xs">
<p class="font-medium text-brand-ink">{portal.company.name}</p>
<p class="mt-1 text-sm leading-relaxed text-brand-text">
{portal.company.street}
{portal.company.street && <br />}
{[portal.company.postal_code, portal.company.city].filter(Boolean).join(" ")}
</p>
{portal.company.vat_id && <p class="mt-2 text-sm text-brand-text-muted">USt-IdNr. {portal.company.vat_id}</p>}
</div>
<div class="surface p-6 shadow-xs">
<p class="font-medium text-brand-ink">Ansprechpartner</p>
<ul class="mt-2 grid gap-1.5 text-sm text-brand-text">
{portal.contacts.map((k) => (
<li>
{k.name || k.email}
{k.role && <span class="text-brand-text-muted"> · {k.role}</span>}
</li>
))}
</ul>
<p class="mt-3 text-sm text-brand-text-muted">
Änderungen oder weitere Zugänge? Schreiben Sie uns an{" "}
<a href="mailto:kontakt@place4bees.com" class="underline">kontakt@place4bees.com</a>.
</p>
</div>
</div>
</div>
</section>
</Layout>
<script>
import { createInquiry } from "../../../lib/b2b";
import { getCustomerTokenClient } from "../../../lib/customerCookie";
document.addEventListener("astro:page-load", () => {
const form = document.getElementById("anfrage-form") as HTMLFormElement | null;
const status = document.getElementById("anfrage-status");
form?.addEventListener("submit", async (event) => {
event.preventDefault();
const token = getCustomerTokenClient();
if (!token || !status) return;
const button = form.querySelector("button[type=submit]") as HTMLButtonElement;
button.disabled = true;
const daten = new FormData(form);
const voelker = String(daten.get("colonies") ?? "").trim();
try {
await createInquiry(token, {
kind: String(daten.get("kind")),
colonies: voelker ? Number(voelker) : null,
message: String(daten.get("message") ?? ""),
});
form.reset();
status.textContent = "Danke! Ihre Anfrage ist bei uns angekommen.";
status.className = "text-sm text-brand-ink";
} catch (err) {
status.textContent = err instanceof Error ? err.message : "Das hat nicht geklappt.";
status.className = "text-sm text-[#b4453a]";
}
button.disabled = false;
});
});
</script>
+15
View File
@@ -1,6 +1,7 @@
--- ---
import Layout from "../../layouts/Layout.astro"; import Layout from "../../layouts/Layout.astro";
import { getCustomerMe, getEmailVerification, listMyOrders } from "../../lib/auth"; import { getCustomerMe, getEmailVerification, listMyOrders } from "../../lib/auth";
import { getMyCompany } from "../../lib/b2b";
export const prerender = false; export const prerender = false;
@@ -24,6 +25,10 @@ try {
return Astro.redirect("/konto/anmelden?redirect=/konto"); return Astro.redirect("/konto/anmelden?redirect=/konto");
} }
// Firmenkunden bekommen einen Weg ins Firmenportal. Fehler hier sollen das
// normale Konto nicht blockieren.
const firma = await getMyCompany(token).catch(() => null);
const STATUS_LABELS: Record<string, string> = { const STATUS_LABELS: Record<string, string> = {
pending: "In Bearbeitung", pending: "In Bearbeitung",
completed: "Abgeschlossen", completed: "Abgeschlossen",
@@ -79,6 +84,16 @@ function statusLabel(order: { status: string; fulfillment_status?: string }): st
</div> </div>
)} )}
{firma && (
<a href="/konto/firma" class="group card-interactive mt-10 flex flex-wrap items-center justify-between gap-4 p-6 sm:p-7">
<div>
<p class="font-medium text-brand-ink">Firmenportal {firma.company.name}</p>
<p class="mt-1 text-sm text-brand-text">Bienenpatenschaften, Lieferungen, Neuigkeiten und Dokumente</p>
</div>
<span class="text-sm font-medium text-brand-primary">Öffnen →</span>
</a>
)}
<h2 class="mt-16 text-h3">Meine Bestellungen</h2> <h2 class="mt-16 text-h3">Meine Bestellungen</h2>
{orders.length === 0 && ( {orders.length === 0 && (