Compare commits
38 Commits
9f25f29b7f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 8e86e6d5c0 | |||
| 72e664f714 | |||
| 81b04530ef | |||
| 23483ad9c5 | |||
| 44d176e42e | |||
| dc78650fe3 | |||
| 07667cc544 | |||
| ad6528c34e | |||
| 355d24312b | |||
| c9243f5a15 | |||
| bda2104146 | |||
| 8b8fbc5f2c | |||
| 6a459ccece | |||
| 537ea08bd6 | |||
| 947063118c | |||
| cab8c749d4 | |||
| b6f03f64aa | |||
| 8b25be4723 | |||
| 9b368f9b7a | |||
| 22d3e25fe2 | |||
| 288527aa18 | |||
| 576ef42c43 | |||
| 872535d17d | |||
| f4b13e6018 | |||
| c31c474ed8 | |||
| f081b5a529 | |||
| 2dc3e0ffee | |||
| 2a40ca53b2 | |||
| 19723f30fb | |||
| c05558b606 | |||
| 794322d346 | |||
| 9511d67c15 | |||
| 9937c6fd7e | |||
| b738f04b7a | |||
| e6a373f016 | |||
| d91ab10a07 | |||
| 596c8f6ee3 | |||
| 74b0939614 |
@@ -27,7 +27,11 @@ ohnehin ab, sobald dort Bestellungen liegen.
|
|||||||
acht nichts mehr geht.
|
acht nichts mehr geht.
|
||||||
- [ ] **Was passiert mit shop.hhonig.de?** Abschalten, weiterleiten oder als
|
- [ ] **Was passiert mit shop.hhonig.de?** Abschalten, weiterleiten oder als
|
||||||
Archiv für die alten Rechnungen stehen lassen. Die Aufbewahrungspflicht
|
Archiv für die alten Rechnungen stehen lassen. Die Aufbewahrungspflicht
|
||||||
für Rechnungen beträgt zehn Jahre.
|
für Rechnungen beträgt zehn Jahre. Die Weiterleitung ist gebaut
|
||||||
|
(`frontend/src/middleware.ts`): Zeigt shop.hhonig.de per DNS und
|
||||||
|
Proxy-Host auf den neuen Server, geht jede Adresse per 301 auf
|
||||||
|
place4bees.com. Die Rechnungen müssen dann vorher aus Shopify gesichert
|
||||||
|
sein.
|
||||||
- [ ] **Was passiert mit den Kundenkonten des alten Shops?** Passwörter
|
- [ ] **Was passiert mit den Kundenkonten des alten Shops?** Passwörter
|
||||||
lassen sich nicht übernehmen. Und: Verkäufer war die Imkerei Björn
|
lassen sich nicht übernehmen. Und: Verkäufer war die Imkerei Björn
|
||||||
Schumann, künftig ist es die PLACE4BEES GmbH — ein anderer
|
Schumann, künftig ist es die PLACE4BEES GmbH — ein anderer
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ Die Zuordnung passiert in `frontend/src/lib/sections.ts` (`resolveSection`, `isB
|
|||||||
## SEO-Konzept
|
## SEO-Konzept
|
||||||
|
|
||||||
- **Canonical-Konsolidierung:** Da dieselben Inhalte technisch auf zwei Domains erreichbar sind, zeigt jede Seite ihren `<link rel="canonical">` fest auf `https://place4bees.com/<pfad>` (in `Layout.astro`), unabhängig davon, über welche Domain sie aufgerufen wurde. Damit bündelt Google die Rankings auf einer Domain, statt sie zwischen hhonig.de und place4bees.com aufzuteilen. hhonig.de bleibt für Bestandsbesucher/Backlinks nutzbar, ohne hart per 301 umgeleitet zu werden.
|
- **Canonical-Konsolidierung:** Da dieselben Inhalte technisch auf zwei Domains erreichbar sind, zeigt jede Seite ihren `<link rel="canonical">` fest auf `https://place4bees.com/<pfad>` (in `Layout.astro`), unabhängig davon, über welche Domain sie aufgerufen wurde. Damit bündelt Google die Rankings auf einer Domain, statt sie zwischen hhonig.de und place4bees.com aufzuteilen. hhonig.de bleibt für Bestandsbesucher/Backlinks nutzbar, ohne hart per 301 umgeleitet zu werden.
|
||||||
- **Wichtig vor Go-Live:** Bestehende URLs von hhonig.de, shop.hhonig.de und place4bees.com erfassen und auf die neuen Pfade (`/`, `/shop`, `/business`, …) mappen – als 301-Redirects dort, wo sich die URL-Struktur ändert.
|
- **301-Weiterleitungen alter Adressen:** erledigt in `frontend/src/middleware.ts` (26.10.2026). Alle 59 Adressen aus den Sitemaps von hhonig.de, shop.hhonig.de und place4bees.com landen auf einer Seite des neuen Shops; Shopify-Produkte `/products/<handle>` gehen auf `/shop/<handle>`, shop.hhonig.de komplett auf place4bees.com.
|
||||||
- Google Search Console für beide Domains einrichten/aktualisieren, aktualisierte Sitemap einreichen.
|
- Google Search Console für beide Domains einrichten/aktualisieren, aktualisierte Sitemap einreichen.
|
||||||
- Produktseiten sollten vor Launch noch strukturierte Daten (schema.org `Product`) bekommen; der Privatkunden-Bereich zusätzlich `LocalBusiness`.
|
- Produktseiten sollten vor Launch noch strukturierte Daten (schema.org `Product`) bekommen; der Privatkunden-Bereich zusätzlich `LocalBusiness`.
|
||||||
|
|
||||||
@@ -220,5 +220,5 @@ Audit-Ergebnis vor dieser Änderung: Impressum, Datenschutzerklärung, AGB und W
|
|||||||
7. Produktions-Deployment: Reverse-Proxy/Server so einrichten, dass beide Domains (hhonig.de, place4bees.com) auf dieselbe Astro-Instanz zeigen (Host-Header muss unverändert durchgereicht werden) und 301-Redirect-Mapping für geänderte Alt-URLs erstellen.
|
7. Produktions-Deployment: Reverse-Proxy/Server so einrichten, dass beide Domains (hhonig.de, place4bees.com) auf dieselbe Astro-Instanz zeigen (Host-Header muss unverändert durchgereicht werden) und 301-Redirect-Mapping für geänderte Alt-URLs erstellen.
|
||||||
8. Redis-gestützte Event-Bus/Cache-Module für Produktionsbetrieb ergänzen (aktuell nutzt Medusa lokal In-Memory-Fallback).
|
8. Redis-gestützte Event-Bus/Cache-Module für Produktionsbetrieb ergänzen (aktuell nutzt Medusa lokal In-Memory-Fallback).
|
||||||
9. **Rechtstexte von einer Anwältin/einem Anwalt prüfen lassen** (siehe eigener Abschnitt unten) – erst danach den gelben Entwurf-Hinweis auf den 4 Rechtsseiten entfernen und live schalten.
|
9. **Rechtstexte von einer Anwältin/einem Anwalt prüfen lassen** (siehe eigener Abschnitt unten) – erst danach den gelben Entwurf-Hinweis auf den 4 Rechtsseiten entfernen und live schalten.
|
||||||
10. Passwort-vergessen-Flow für Kundenkonten ergänzen (Medusa unterstützt das über `/auth/customer/emailpass/reset-password`, im Frontend noch nicht angebunden).
|
10. ~~Passwort-vergessen-Flow für Kundenkonten ergänzen~~ – erledigt (26.10.2026): `/konto/passwort-vergessen` und `/konto/passwort-neu`, dazu die Bestätigung der Mailadresse, nach der Gastbestellungen ins Konto übernommen werden.
|
||||||
11. Echte Produktfotos für Presshonig, Kornblumenhonig und Geschenkgutschein ergänzen (aktuell Platzhalter im Shop, da für diese 3 Produkte bei der Migration kein Bild übernommen wurde).
|
11. Echte Produktfotos für Presshonig, Kornblumenhonig und Geschenkgutschein ergänzen (aktuell Platzhalter im Shop, da für diese 3 Produkte bei der Migration kein Bild übernommen wurde).
|
||||||
|
|||||||
@@ -46,16 +46,23 @@ Hermes gibt die HSI-Schnittstellendoku nur an Vertragskunden heraus. Ohne die
|
|||||||
Unterlagen lässt sich nichts schreiben, das mehr als geraten wäre. Sobald die
|
Unterlagen lässt sich nichts schreiben, das mehr als geraten wäre. Sobald die
|
||||||
Doku da ist, sagen Sie Bescheid.
|
Doku da ist, sagen Sie Bescheid.
|
||||||
|
|
||||||
### Mollie — Code fertig, ungetestet
|
### Mollie — im Testmodus durchgespielt (26.10.2026)
|
||||||
|
|
||||||
- `MOLLIE_API_KEY` — erst `test_…`, später `live_…`
|
Läuft für Abos und für normale Bestellungen ("Online bezahlen" an der
|
||||||
- Im Mollie-Dashboard freischalten: **SEPA-Lastschrift, Kreditkarte, PayPal**
|
Kasse). Getestet: Kauf, Abbruch, Teilerstattung im Admin, Storno mit
|
||||||
|
Resterstattung, Folgezahlung, gescheiterte Folgezahlung (nachgestellt).
|
||||||
|
|
||||||
|
- `MOLLIE_API_KEY` — jetzt `test_…`, zum Livegang `live_…`
|
||||||
|
- Im Mollie-Dashboard noch freischalten: **PayPal, SEPA-Lastschrift**. Dann
|
||||||
|
den Text der Zahlart in `src/api/store/payment-methods/route.ts` ergänzen.
|
||||||
- Webhook-URL muss von außen erreichbar sein: `https://<domain>/hooks/mollie`
|
- Webhook-URL muss von außen erreichbar sein: `https://<domain>/hooks/mollie`
|
||||||
(lokal geht das nur über einen Tunnel, z. B. ngrok)
|
(lokal über einen Tunnel, z. B. cloudflared)
|
||||||
|
|
||||||
Achtung: Mollie ist **kein** registriertes Medusa-Payment-Modul, sondern wird
|
Mollie ist **kein** Medusa-Zahlungsanbieter, sondern wird direkt über
|
||||||
direkt über `src/lib/mollie.ts` angesprochen. Registriert sind aktuell nur
|
`src/lib/mollie.ts` angesprochen. In Medusa laufen die Zahlungen über den
|
||||||
PayPal und PayPal-Card.
|
manuellen Anbieter; die Mollie-Zahlung steht als `mollie_payment_id` an der
|
||||||
|
Bestellung. Erstattungen im Admin (auch per Storno) gehen automatisch an
|
||||||
|
Mollie (`src/lib/mollie-erstattung.ts`).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -76,12 +83,20 @@ PayPal und PayPal-Card.
|
|||||||
am 16.9.2026 aus dem alten Shopify-Shop übernommen worden
|
am 16.9.2026 aus dem alten Shopify-Shop übernommen worden
|
||||||
(`src/scripts/import-hhonig-inhalte.ts`). Das sind Bruttogewichte inkl.
|
(`src/scripts/import-hhonig-inhalte.ts`). Das sind Bruttogewichte inkl.
|
||||||
Glas, also das, was DHL braucht.
|
Glas, also das, was DHL braucht.
|
||||||
- [ ] **Fünf Varianten haben weiterhin kein Versandgewicht**, weil es im alten
|
- [x] ~~Buchweizenhonig ohne Versandgewicht~~ — am 26.10.2026 auf 400 g / 100 g
|
||||||
Shop keine Vorlage gab: Buchweizenhonig (250 g und 50 g), Bienenpatenschaft
|
gesetzt wie alle anderen Honige, ebenso das Honig-Abo (400 / 700 g).
|
||||||
und der Schnupperkurs (2 Varianten). Beim Buchweizenhonig wären 400 g und
|
Der Schnupperkurs verschickt nichts.
|
||||||
100 g plausibel, das ist der Wert aller anderen Honige — bitte bestätigen,
|
- [x] ~~**Bienenpatenschaft: Was geht beim Kauf raus?**~~ Geklärt (27.10.2026):
|
||||||
geraten habe ich ihn nicht eingetragen. Ob Patenschaft und Kurs überhaupt
|
Beim Kauf geht nur die Urkunde per Brief raus, die 4 Honiggläser à 250 g
|
||||||
ein Gewicht brauchen, hängt daran, ob etwas verschickt wird.
|
(2 Sommer, 2 Frühjahr) folgen im Okt/Nov in einem Paket — beides von Hand.
|
||||||
|
Deshalb ist der Patenschaft das Versandprofil entfernt
|
||||||
|
(`requires_shipping = false`, wie beim Gutschein): keine DHL-Versandart an
|
||||||
|
der Kasse, kein automatisches Label. Die Honigsendung im Herbst legt ihr
|
||||||
|
im Admin von Hand an. Gesetzt über `setup-sponsorship.ts`.
|
||||||
|
- [ ] **Schnupperkurs: neue Termine.** Der Termin 25.04.2026 ist entfernt,
|
||||||
|
buchbar ist nur noch der Kurs-Gutschein ("Neue Termine folgen in Kürze").
|
||||||
|
- [ ] **Honigseife Lavendel**: Sorte angelegt (3,50 €), aber ohne eigenes
|
||||||
|
Foto.
|
||||||
- [ ] **7 neue Partner ohne Koordinate**: Ahrens Hausverwaltung, BRUHN,
|
- [ ] **7 neue Partner ohne Koordinate**: Ahrens Hausverwaltung, BRUHN,
|
||||||
E-Center Schleswig, intersoft consulting, JUFA Hotels, P+R, Radkultur
|
E-Center Schleswig, intersoft consulting, JUFA Hotels, P+R, Radkultur
|
||||||
Hamburg. Sie stehen in der Logo-Wand, aber nicht auf der Karte.
|
Hamburg. Sie stehen in der Logo-Wand, aber nicht auf der Karte.
|
||||||
@@ -143,6 +158,16 @@ Zur Information, hier ist nichts offen:
|
|||||||
Live-Seite hat sie nicht, und im Ergebnis sah sie wie ein Darstellungsfehler
|
Live-Seite hat sie nicht, und im Ergebnis sah sie wie ein Darstellungsfehler
|
||||||
aus.
|
aus.
|
||||||
|
|
||||||
|
## Entschieden
|
||||||
|
|
||||||
|
- **Kauf auf Rechnung: Versand von Hand** (26.10.2026). Bei Online-Zahlung
|
||||||
|
entsteht das Label automatisch, sobald Mollie bestätigt. Bei Rechnung
|
||||||
|
nicht: Die Bestellung wird im Admin von Hand verpackt ("Fulfill items"),
|
||||||
|
damit vor dem Versand ein Mensch draufschaut. Die Zahlung bucht ihr im
|
||||||
|
Admin ("Capture payment"), wenn die Überweisung da ist.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 6. Aufräumen
|
## 6. Aufräumen
|
||||||
|
|
||||||
- [ ] **Sendcloud-Modul ist noch in `medusa-config.ts` registriert** (Zeile ~114,
|
- [ ] **Sendcloud-Modul ist noch in `medusa-config.ts` registriert** (Zeile ~114,
|
||||||
|
|||||||
@@ -20,6 +20,40 @@ const sendcloudEnabled = Boolean(
|
|||||||
// Entwicklung ohne Zugangsdaten und niemand bekommt Testmails.
|
// Entwicklung ohne Zugangsdaten und niemand bekommt Testmails.
|
||||||
const smtpEnabled = Boolean(process.env.SMTP_HOST && process.env.MAIL_FROM)
|
const smtpEnabled = Boolean(process.env.SMTP_HOST && process.env.MAIL_FROM)
|
||||||
|
|
||||||
|
// Ohne diese Module hält Medusa Ereignisse, Workflows und Sperren nur im
|
||||||
|
// Speicher: Wer beim Neustart gerade in der Schlange steht (Bestellmail,
|
||||||
|
// Versandlabel nach Zahlungseingang), ist weg, und Medusa warnt beim Start
|
||||||
|
// "Local Event Bus installed. This is not recommended for production."
|
||||||
|
// Mit Redis überleben sie Neustarts. Bewusst ohne das Caching-Modul: Webhook
|
||||||
|
// und Erstattungsabgleich lesen direkt nach dem Schreiben und brauchen den
|
||||||
|
// frischen Stand.
|
||||||
|
const redisUrl = process.env.REDIS_URL
|
||||||
|
const redisModules = redisUrl
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/event-bus-redis",
|
||||||
|
options: { redisUrl },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/workflow-engine-redis",
|
||||||
|
options: { redis: { redisUrl } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/locking",
|
||||||
|
options: {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/locking-redis",
|
||||||
|
id: "locking-redis",
|
||||||
|
is_default: true,
|
||||||
|
options: { redisUrl },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []
|
||||||
|
|
||||||
module.exports = defineConfig({
|
module.exports = defineConfig({
|
||||||
projectConfig: {
|
projectConfig: {
|
||||||
databaseUrl: process.env.DATABASE_URL,
|
databaseUrl: process.env.DATABASE_URL,
|
||||||
@@ -52,16 +86,23 @@ module.exports = defineConfig({
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
modules: [
|
modules: [
|
||||||
|
...redisModules,
|
||||||
{
|
{
|
||||||
// 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: {
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
resolve: "@medusajs/file-local",
|
// Wie @medusajs/file-local, nur mit Adressen ohne Domain —
|
||||||
|
// siehe src/modules/file-relative.
|
||||||
|
resolve: "./src/modules/file-relative",
|
||||||
id: "local",
|
id: "local",
|
||||||
options: {
|
options: {
|
||||||
// Bewusst ohne Domain: Die Adresse landet so in der Datenbank,
|
// Bewusst ohne Domain: Die Adresse landet so in der Datenbank,
|
||||||
|
|||||||
@@ -23,16 +23,17 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@easypayment/medusa-payment-paypal": "^0.9.29",
|
"@easypayment/medusa-payment-paypal": "^0.9.29",
|
||||||
"@medusajs/admin-sdk": "2.17.0",
|
"@medusajs/admin-sdk": "2.17.2",
|
||||||
"@medusajs/admin-shared": "2.17.0",
|
"@medusajs/admin-shared": "2.17.2",
|
||||||
"@medusajs/caching": "2.17.0",
|
"@medusajs/caching": "2.17.2",
|
||||||
"@medusajs/cli": "2.17.0",
|
"@medusajs/cli": "2.17.2",
|
||||||
"@medusajs/dashboard": "2.17.0",
|
"@medusajs/dashboard": "2.17.2",
|
||||||
"@medusajs/draft-order": "2.17.0",
|
"@medusajs/draft-order": "2.17.2",
|
||||||
"@medusajs/framework": "2.17.0",
|
"@medusajs/file-local": "2.17.2",
|
||||||
"@medusajs/loyalty-plugin": "2.17.0",
|
"@medusajs/framework": "2.17.2",
|
||||||
"@medusajs/medusa": "2.17.0",
|
"@medusajs/loyalty-plugin": "2.17.2",
|
||||||
"@medusajs/ui": "4.1.15",
|
"@medusajs/medusa": "2.17.2",
|
||||||
|
"@medusajs/ui": "4.1.19",
|
||||||
"@mollie/api-client": "^4.6.0",
|
"@mollie/api-client": "^4.6.0",
|
||||||
"@tanstack/react-query": "5.64.2",
|
"@tanstack/react-query": "5.64.2",
|
||||||
"@types/nodemailer": "^8.0.1",
|
"@types/nodemailer": "^8.0.1",
|
||||||
@@ -45,7 +46,7 @@
|
|||||||
"zod": "4.2.0"
|
"zod": "4.2.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@medusajs/test-utils": "2.17.0",
|
"@medusajs/test-utils": "2.17.2",
|
||||||
"@swc/core": "^1.7.28",
|
"@swc/core": "^1.7.28",
|
||||||
"@swc/jest": "^0.2.36",
|
"@swc/jest": "^0.2.36",
|
||||||
"@types/jest": "^29.5.13",
|
"@types/jest": "^29.5.13",
|
||||||
|
|||||||
@@ -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,110 @@
|
|||||||
|
import { defineWidgetConfig } from "@medusajs/admin-sdk";
|
||||||
|
import { Button, Container, Heading, Input, Label, Text, toast } from "@medusajs/ui";
|
||||||
|
import type { DetailWidgetProps, AdminOrder } from "@medusajs/framework/types";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
// Urkunde zur Bienenpatenschaft: Name kommt aus der Bestellung, Nummer und
|
||||||
|
// Standort kann der Imker vor dem Drucken eintragen. Das Widget erscheint nur
|
||||||
|
// bei Bestellungen, die eine Patenschaft enthalten.
|
||||||
|
const OrderUrkundeWidget = ({ data: order }: DetailWidgetProps<AdminOrder>) => {
|
||||||
|
const paten = (order.items ?? [])
|
||||||
|
.map((i: any) => String(i?.metadata?.sponsorship_name ?? "").trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
const [nummer, setNummer] = useState("");
|
||||||
|
const [standort, setStandort] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
if (!paten.length) return null;
|
||||||
|
|
||||||
|
const url = () => {
|
||||||
|
const p = new URLSearchParams();
|
||||||
|
if (nummer.trim()) p.set("nummer", nummer.trim());
|
||||||
|
if (standort.trim()) p.set("standort", standort.trim());
|
||||||
|
const qs = p.toString();
|
||||||
|
return `/admin/orders/${order.id}/urkunde${qs ? `?${qs}` : ""}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ladePdf = async () => {
|
||||||
|
const res = await fetch(url(), { credentials: "include" });
|
||||||
|
if (!res.ok) throw new Error(`Urkunde konnte nicht erzeugt werden (${res.status}).`);
|
||||||
|
return res.blob();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDownload = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const blob = await ladePdf();
|
||||||
|
const href = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = href;
|
||||||
|
link.download = `urkunde-${paten[0].replace(/[^a-zA-Z0-9]+/g, "-").toLowerCase()}.pdf`;
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
URL.revokeObjectURL(href);
|
||||||
|
} catch (err) {
|
||||||
|
toast.error("Fehler", { description: err instanceof Error ? err.message : "Unbekannter Fehler." });
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePrint = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const blob = await ladePdf();
|
||||||
|
const href = URL.createObjectURL(blob);
|
||||||
|
const fenster = window.open(href, "_blank");
|
||||||
|
if (fenster) {
|
||||||
|
fenster.addEventListener("load", () => fenster.print());
|
||||||
|
}
|
||||||
|
// URL bleibt bis zum Schließen des Tabs gültig; nicht sofort widerrufen.
|
||||||
|
} catch (err) {
|
||||||
|
toast.error("Fehler", { description: err instanceof Error ? err.message : "Unbekannter Fehler." });
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container className="divide-y p-0">
|
||||||
|
<div className="flex items-center justify-between px-6 py-4">
|
||||||
|
<Heading level="h2">Urkunde Patenschaft</Heading>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-4 px-6 py-4">
|
||||||
|
<div>
|
||||||
|
<Text size="small" className="text-ui-fg-subtle">
|
||||||
|
Name auf der Urkunde: <span className="text-ui-fg-base font-medium">{paten.join(", ")}</span>
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<Label size="xsmall">Patenschaftsnummer (optional)</Label>
|
||||||
|
<Input size="small" value={nummer} onChange={(e) => setNummer(e.target.value)} placeholder="z. B. P-2026-077" />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<Label size="xsmall">Standort des Volkes (optional)</Label>
|
||||||
|
<Input size="small" value={standort} onChange={(e) => setStandort(e.target.value)} placeholder="z. B. Hamburg, Isestraße" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="primary" size="small" isLoading={loading} onClick={handlePrint}>
|
||||||
|
Drucken
|
||||||
|
</Button>
|
||||||
|
<Button variant="secondary" size="small" isLoading={loading} onClick={handleDownload}>
|
||||||
|
Als PDF herunterladen
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Text size="xsmall" className="text-ui-fg-muted">
|
||||||
|
Nummer und Standort leer lassen → auf der Urkunde steht eine Linie zum Eintragen von Hand.
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const config = defineWidgetConfig({
|
||||||
|
zone: "order.details.side.after",
|
||||||
|
});
|
||||||
|
|
||||||
|
export default OrderUrkundeWidget;
|
||||||
@@ -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,8 @@
|
|||||||
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { handleUrkundeRequest } from "../../../../../lib/urkunde-handler";
|
||||||
|
|
||||||
|
// GET /admin/orders/:id/urkunde — Patenschafts-Urkunde als PDF zum Ausdrucken
|
||||||
|
// aus dem Admin heraus (Admin-Auth wie jede andere /admin-Route).
|
||||||
|
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
await handleUrkundeRequest(req, res);
|
||||||
|
}
|
||||||
@@ -1,16 +1,15 @@
|
|||||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
import {
|
|
||||||
completeCartWorkflow,
|
|
||||||
createPaymentCollectionForCartWorkflow,
|
|
||||||
createPaymentSessionsWorkflow,
|
|
||||||
capturePaymentWorkflow,
|
|
||||||
} from "@medusajs/core-flows";
|
|
||||||
import { getPayment, findValidMandate } from "../../../lib/mollie";
|
import { getPayment, findValidMandate } from "../../../lib/mollie";
|
||||||
|
import { createSubscriptionsFromOrder } from "../../../lib/subscription-from-order";
|
||||||
import {
|
import {
|
||||||
createSubscriptionsFromOrder,
|
bezahltenWarenkorbAbschliessen,
|
||||||
SUBSCRIPTION_CART_FIELDS,
|
bestellungsZahlungErfassen,
|
||||||
} from "../../../lib/subscription-from-order";
|
mollieZahlungMerken,
|
||||||
import { SUBSCRIPTION_MODULE } from "../../../modules/subscription";
|
} from "../../../lib/mollie-bestellung";
|
||||||
|
import { aboAbbuchungGescheitert } from "../../../lib/abo-zahlung";
|
||||||
|
|
||||||
|
/** Endgültig gescheitert — "open" und "pending" können noch klappen. */
|
||||||
|
const GESCHEITERT = ["failed", "canceled", "expired"];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mollie-Webhook.
|
* Mollie-Webhook.
|
||||||
@@ -18,10 +17,12 @@ import { SUBSCRIPTION_MODULE } from "../../../modules/subscription";
|
|||||||
* Mollie schickt nur die Zahlungs-ID; den Zustand holen wir selbst ab, damit
|
* Mollie schickt nur die Zahlungs-ID; den Zustand holen wir selbst ab, damit
|
||||||
* ein gefälschter Aufruf nichts auslösen kann.
|
* ein gefälschter Aufruf nichts auslösen kann.
|
||||||
*
|
*
|
||||||
* Zwei Fälle:
|
* Drei Fälle:
|
||||||
* - Erstzahlung eines Abos ("first"): Warenkorb abschließen, Abo anlegen
|
* - Erstzahlung eines Abos ("first"): Warenkorb abschließen, Abo anlegen
|
||||||
* - Folgezahlung ("recurring"): nur die Zahlung der Bestellung erfassen,
|
* - normale Bestellung ("oneoff"): Warenkorb abschließen
|
||||||
* wodurch der Label-Subscriber greift
|
* - Folgezahlung eines Abos ("recurring"): Zahlung der schon angelegten
|
||||||
|
* Bestellung erfassen, wodurch der Label-Subscriber greift — oder, wenn
|
||||||
|
* die Abbuchung scheitert, Lieferung stornieren und Kunden informieren
|
||||||
*
|
*
|
||||||
* Mollie ruft den Webhook mehrfach auf. Alles hier muss also mehrfach
|
* Mollie ruft den Webhook mehrfach auf. Alles hier muss also mehrfach
|
||||||
* ausführbar sein, ohne doppelte Bestellungen oder Abos zu erzeugen.
|
* ausführbar sein, ohne doppelte Bestellungen oder Abos zu erzeugen.
|
||||||
@@ -41,113 +42,82 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|||||||
try {
|
try {
|
||||||
const payment: any = await getPayment(paymentId);
|
const payment: any = await getPayment(paymentId);
|
||||||
logger.info(`[mollie] ${paymentId}: ${payment.status} (${payment.sequenceType})`);
|
logger.info(`[mollie] ${paymentId}: ${payment.status} (${payment.sequenceType})`);
|
||||||
|
const meta = payment.metadata ?? {};
|
||||||
|
|
||||||
|
if (payment.sequenceType === "recurring") {
|
||||||
|
if (payment.status === "paid" && meta.order_id) {
|
||||||
|
await mollieZahlungMerken(req.scope, meta.order_id, payment.id);
|
||||||
|
await bestellungsZahlungErfassen(req.scope, meta.order_id, logger);
|
||||||
|
} else if (GESCHEITERT.includes(payment.status)) {
|
||||||
|
await aboAbbuchungGescheitert(req.scope, payment, logger);
|
||||||
|
}
|
||||||
|
return res.status(200).send("ok");
|
||||||
|
}
|
||||||
|
|
||||||
if (payment.status !== "paid") {
|
if (payment.status !== "paid") {
|
||||||
return res.status(200).send("ok");
|
return res.status(200).send("ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
const meta = payment.metadata ?? {};
|
// --- Normale Bestellung ---
|
||||||
|
if (payment.sequenceType === "oneoff") {
|
||||||
if (payment.sequenceType === "recurring") {
|
const ergebnis = await bezahltenWarenkorbAbschliessen(req.scope, payment, logger);
|
||||||
await captureOrderPayment(req.scope, query, meta.order_id, logger);
|
if (ergebnis?.neu) {
|
||||||
|
logger.info(`[mollie] Bestellung zu Warenkorb ${meta.cart_id} angelegt.`);
|
||||||
|
}
|
||||||
|
await bestellungsZahlungErfassen(req.scope, ergebnis?.orderId, logger);
|
||||||
return res.status(200).send("ok");
|
return res.status(200).send("ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Erstzahlung: Warenkorb abschließen und Abo anlegen ---
|
// --- Erstzahlung: Warenkorb abschließen und Abo anlegen ---
|
||||||
const cartId = meta.cart_id;
|
const mandateId = payment.mandateId ?? (await findValidMandate(payment.customerId));
|
||||||
if (!cartId) {
|
|
||||||
logger.warn(`[mollie] ${paymentId}: keine cart_id in den Metadaten.`);
|
|
||||||
return res.status(200).send("ok");
|
|
||||||
}
|
|
||||||
|
|
||||||
const { data: carts } = await query.graph({
|
|
||||||
entity: "cart",
|
|
||||||
fields: [
|
|
||||||
...SUBSCRIPTION_CART_FIELDS,
|
|
||||||
"completed_at",
|
|
||||||
"payment_collection.id",
|
|
||||||
"payment_collection.payment_sessions.id",
|
|
||||||
],
|
|
||||||
filters: { id: cartId },
|
|
||||||
});
|
|
||||||
const cart: any = carts?.[0];
|
|
||||||
if (!cart) {
|
|
||||||
logger.warn(`[mollie] Warenkorb ${cartId} nicht gefunden.`);
|
|
||||||
return res.status(200).send("ok");
|
|
||||||
}
|
|
||||||
if (cart.completed_at) {
|
|
||||||
logger.info(`[mollie] Warenkorb ${cartId} war schon abgeschlossen, nichts zu tun.`);
|
|
||||||
return res.status(200).send("ok");
|
|
||||||
}
|
|
||||||
|
|
||||||
const mandateId =
|
|
||||||
payment.mandateId ?? (await findValidMandate(payment.customerId));
|
|
||||||
if (!mandateId) {
|
if (!mandateId) {
|
||||||
logger.error(
|
logger.error(`[mollie] ${paymentId}: bezahlt, aber kein gültiges Mandat — ohne Mandat kein Abo.`);
|
||||||
`[mollie] ${paymentId}: bezahlt, aber kein gültiges Mandat — ohne Mandat kein Abo.`
|
|
||||||
);
|
|
||||||
return res.status(200).send("ok");
|
return res.status(200).send("ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ein früherer Aufruf kann Sammlung und Sitzung schon angelegt haben und
|
const ergebnis = await bezahltenWarenkorbAbschliessen(req.scope, payment, logger);
|
||||||
// erst danach gescheitert sein — dann weiterverwenden statt neu anlegen.
|
if (!ergebnis) return res.status(200).send("ok");
|
||||||
let collectionId = cart.payment_collection?.id;
|
|
||||||
if (!collectionId) {
|
if (ergebnis.neu) {
|
||||||
const { result: sammlung } = await createPaymentCollectionForCartWorkflow(req.scope).run({
|
const { data: orders } = await query.graph({
|
||||||
input: { cart_id: cartId },
|
entity: "order",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"display_id",
|
||||||
|
"email",
|
||||||
|
"customer_id",
|
||||||
|
"region_id",
|
||||||
|
"currency_code",
|
||||||
|
"sales_channel_id",
|
||||||
|
"shipping_address.*",
|
||||||
|
"shipping_methods.shipping_option_id",
|
||||||
|
"items.id",
|
||||||
|
"items.quantity",
|
||||||
|
"items.metadata",
|
||||||
|
"items.variant_id",
|
||||||
|
"items.variant.id",
|
||||||
|
"items.variant.metadata",
|
||||||
|
"items.variant.product.metadata",
|
||||||
|
],
|
||||||
|
filters: { id: ergebnis.orderId },
|
||||||
});
|
});
|
||||||
collectionId = (sammlung as any).id;
|
const order: any = orders?.[0];
|
||||||
}
|
|
||||||
// Ohne Zahlungssitzung lässt sich der Warenkorb nicht abschließen. Wie im
|
const subscriptions = await createSubscriptionsFromOrder({
|
||||||
// Abo-Job über den manuellen Anbieter: Das Geld hat Mollie schon.
|
container: req.scope,
|
||||||
if (!cart.payment_collection?.payment_sessions?.length) {
|
order,
|
||||||
await createPaymentSessionsWorkflow(req.scope).run({
|
mollieCustomerId: payment.customerId,
|
||||||
input: { payment_collection_id: collectionId, provider_id: "pp_system_default" },
|
mollieMandateId: mandateId,
|
||||||
|
paymentMethod: payment.method,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
`[mollie] Bestellung ${order.display_id} angelegt, ${subscriptions.length} Abo(s): ` +
|
||||||
|
subscriptions.map((s: any) => `${s.id} (${s.interval}, ${s.size})`).join(", ")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const { result: completed } = await completeCartWorkflow(req.scope).run({
|
|
||||||
input: { id: cartId },
|
|
||||||
});
|
|
||||||
const orderId = (completed as any)?.id;
|
|
||||||
|
|
||||||
const { data: orders } = await query.graph({
|
await bestellungsZahlungErfassen(req.scope, ergebnis.orderId, logger);
|
||||||
entity: "order",
|
|
||||||
fields: [
|
|
||||||
"id",
|
|
||||||
"display_id",
|
|
||||||
"email",
|
|
||||||
"customer_id",
|
|
||||||
"region_id",
|
|
||||||
"currency_code",
|
|
||||||
"sales_channel_id",
|
|
||||||
"shipping_address.*",
|
|
||||||
"shipping_methods.shipping_option_id",
|
|
||||||
"items.id",
|
|
||||||
"items.quantity",
|
|
||||||
"items.metadata",
|
|
||||||
"items.variant_id",
|
|
||||||
"items.variant.id",
|
|
||||||
"items.variant.metadata",
|
|
||||||
"items.variant.product.metadata",
|
|
||||||
],
|
|
||||||
filters: { id: orderId },
|
|
||||||
});
|
|
||||||
const order: any = orders?.[0];
|
|
||||||
|
|
||||||
const subscriptions = await createSubscriptionsFromOrder({
|
|
||||||
container: req.scope,
|
|
||||||
order,
|
|
||||||
mollieCustomerId: payment.customerId,
|
|
||||||
mollieMandateId: mandateId,
|
|
||||||
paymentMethod: payment.method,
|
|
||||||
});
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
`[mollie] Bestellung ${order.display_id} angelegt, ${subscriptions.length} Abo(s): ` +
|
|
||||||
subscriptions.map((s: any) => `${s.id} (${s.interval}, ${s.size})`).join(", ")
|
|
||||||
);
|
|
||||||
|
|
||||||
await captureOrderPayment(req.scope, query, orderId, logger);
|
|
||||||
res.status(200).send("ok");
|
res.status(200).send("ok");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(
|
logger.error(
|
||||||
@@ -162,30 +132,3 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|||||||
res.status(200).send("ok");
|
res.status(200).send("ok");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Erfasst die Zahlung der Bestellung in Medusa. Das löst `payment.captured`
|
|
||||||
* aus, worauf der Subscriber das Versandlabel erzeugt.
|
|
||||||
*/
|
|
||||||
async function captureOrderPayment(scope: any, query: any, orderId: string | undefined, logger: any) {
|
|
||||||
if (!orderId) return;
|
|
||||||
const { data: orders } = await query.graph({
|
|
||||||
entity: "order",
|
|
||||||
fields: [
|
|
||||||
"id",
|
|
||||||
"display_id",
|
|
||||||
"payment_collections.payments.id",
|
|
||||||
"payment_collections.payments.amount",
|
|
||||||
"payment_collections.payments.captured_at",
|
|
||||||
],
|
|
||||||
filters: { id: orderId },
|
|
||||||
});
|
|
||||||
const payments = orders?.[0]?.payment_collections?.flatMap((c: any) => c.payments ?? []) ?? [];
|
|
||||||
for (const payment of payments) {
|
|
||||||
if (payment.captured_at) continue;
|
|
||||||
await capturePaymentWorkflow(scope).run({
|
|
||||||
input: { payment_id: payment.id, amount: payment.amount },
|
|
||||||
});
|
|
||||||
logger.info(`[mollie] Zahlung ${payment.id} erfasst — Label wird erzeugt.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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 })),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils";
|
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils";
|
||||||
|
import { getOrderDetailWorkflow } from "@medusajs/core-flows";
|
||||||
|
|
||||||
// Matches Medusa's own "ALL /store/customers/me*" middleware, so this route
|
// Matches Medusa's own "ALL /store/customers/me*" middleware, so this route
|
||||||
// is already protected by customer bearer/session auth before it runs —
|
// is already protected by customer bearer/session auth before it runs —
|
||||||
@@ -52,7 +53,6 @@ export async function GET(req: AuthenticatedMedusaRequest, res: MedusaResponse)
|
|||||||
entity: "order",
|
entity: "order",
|
||||||
filters: { id: order.id },
|
filters: { id: order.id },
|
||||||
fields: [
|
fields: [
|
||||||
"fulfillment_status",
|
|
||||||
"fulfillments.packed_at",
|
"fulfillments.packed_at",
|
||||||
"fulfillments.shipped_at",
|
"fulfillments.shipped_at",
|
||||||
"fulfillments.delivered_at",
|
"fulfillments.delivered_at",
|
||||||
@@ -63,6 +63,13 @@ export async function GET(req: AuthenticatedMedusaRequest, res: MedusaResponse)
|
|||||||
});
|
});
|
||||||
const fulfillmentData = data[0] as any;
|
const fulfillmentData = data[0] as any;
|
||||||
|
|
||||||
|
// fulfillment_status ist kein gespeichertes Feld: Medusa berechnet ihn
|
||||||
|
// erst im Bestell-Workflow aus den Sendungen. Über query.graph kam er
|
||||||
|
// leer zurück, und die Fortschrittsanzeige blieb immer auf "Bestellt".
|
||||||
|
const { result: detail } = await getOrderDetailWorkflow(req.scope).run({
|
||||||
|
input: { order_id: order.id, fields: ["id", "fulfillment_status"] },
|
||||||
|
});
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
order: {
|
order: {
|
||||||
id: order.id,
|
id: order.id,
|
||||||
@@ -75,7 +82,7 @@ export async function GET(req: AuthenticatedMedusaRequest, res: MedusaResponse)
|
|||||||
item_total: itemTotal,
|
item_total: itemTotal,
|
||||||
shipping_total: shippingTotal,
|
shipping_total: shippingTotal,
|
||||||
total: Math.round((itemTotal + shippingTotal) * 100) / 100,
|
total: Math.round((itemTotal + shippingTotal) * 100) / 100,
|
||||||
fulfillment_status: fulfillmentData?.fulfillment_status ?? "not_fulfilled",
|
fulfillment_status: (detail as any)?.fulfillment_status ?? "not_fulfilled",
|
||||||
fulfillments: (fulfillmentData?.fulfillments ?? []).map((f: any) => ({
|
fulfillments: (fulfillmentData?.fulfillments ?? []).map((f: any) => ({
|
||||||
packed_at: f.packed_at,
|
packed_at: f.packed_at,
|
||||||
shipped_at: f.shipped_at,
|
shipped_at: f.shipped_at,
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { requestVerificationWorkflow } from "@medusajs/core-flows";
|
||||||
|
import {
|
||||||
|
EMAIL_VERIFICATION,
|
||||||
|
istEmailBestaetigt,
|
||||||
|
normalisiereEmail,
|
||||||
|
uebernimmGastbestellungen,
|
||||||
|
} from "../../../../../lib/gastbestellungen";
|
||||||
|
|
||||||
|
/** Frühestens nach dieser Zeit lässt sich ein neuer Link anfordern. */
|
||||||
|
const SPERRE_MS = 60_000;
|
||||||
|
|
||||||
|
async function kundeLaden(req: AuthenticatedMedusaRequest) {
|
||||||
|
const customers: any = req.scope.resolve(Modules.CUSTOMER);
|
||||||
|
return customers.retrieveCustomer(req.auth_context.actor_id, { select: ["id", "email"] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stand der Mailbestätigung. Ist die Adresse bestätigt, werden dabei
|
||||||
|
* Gastbestellungen und Gast-Abos mit derselben Adresse ins Konto übernommen —
|
||||||
|
* bei jedem Aufruf, damit auch spätere Gastbestellungen ankommen.
|
||||||
|
*
|
||||||
|
* Liegt unter /customers/me* und ist damit schon von Medusa geschützt.
|
||||||
|
*/
|
||||||
|
export async function GET(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
|
||||||
|
const kunde = await kundeLaden(req);
|
||||||
|
const bestaetigt = await istEmailBestaetigt(req.scope, req.auth_context.auth_identity_id, kunde.email);
|
||||||
|
if (!bestaetigt) {
|
||||||
|
return res.json({ verified: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const uebernommen = await uebernimmGastbestellungen(req.scope, kunde);
|
||||||
|
if (uebernommen.bestellungen || uebernommen.abos) {
|
||||||
|
req.scope
|
||||||
|
.resolve("logger")
|
||||||
|
.info(
|
||||||
|
`[konto] ${kunde.id}: ${uebernommen.bestellungen} Gastbestellung(en), ${uebernommen.abos} Abo(s) übernommen.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
res.json({ verified: true, uebernommen });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schickt einen Bestätigungslink an die Adresse des Kontos. Die Adresse kommt
|
||||||
|
* bewusst aus dem Konto, nicht aus der Anfrage: sonst ließen sich Mails an
|
||||||
|
* beliebige Adressen auslösen.
|
||||||
|
*/
|
||||||
|
export async function POST(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
|
||||||
|
const kunde = await kundeLaden(req);
|
||||||
|
const authIdentityId = req.auth_context.auth_identity_id;
|
||||||
|
const email = normalisiereEmail(kunde.email);
|
||||||
|
|
||||||
|
const auth: any = req.scope.resolve(Modules.AUTH);
|
||||||
|
const [vorhanden] = await auth.listAuthVerifications(
|
||||||
|
{ auth_identity_id: authIdentityId, entity_type: EMAIL_VERIFICATION.entity_type, entity_id: email },
|
||||||
|
{ take: 1 }
|
||||||
|
);
|
||||||
|
if (vorhanden?.verified_at) {
|
||||||
|
return res.json({ verified: true });
|
||||||
|
}
|
||||||
|
if (vorhanden && Date.now() - new Date(vorhanden.requested_at).getTime() < SPERRE_MS) {
|
||||||
|
return res.status(429).json({ message: "Bitte warten Sie eine Minute, bevor Sie einen neuen Link anfordern." });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Der Link selbst geht über den Subscriber auf auth.verification_requested.
|
||||||
|
await requestVerificationWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
auth_identity_id: authIdentityId,
|
||||||
|
entity_id: email,
|
||||||
|
entity_type: EMAIL_VERIFICATION.entity_type,
|
||||||
|
code_provider: EMAIL_VERIFICATION.code_provider,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
res.status(201).json({ verified: false, sent: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { updateCartWorkflow } from "@medusajs/core-flows";
|
||||||
|
import { createOneOffPayment, isMollieConfigured } from "../../../../lib/mollie";
|
||||||
|
import { hasSubscriptionLines, SUBSCRIPTION_CART_FIELDS } from "../../../../lib/subscription-from-order";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Startet die Online-Zahlung einer normalen Bestellung bei Mollie.
|
||||||
|
*
|
||||||
|
* Wie beim Abo wird der Warenkorb hier NICHT abgeschlossen. Das macht der
|
||||||
|
* Webhook, sobald Mollie die Zahlung bestätigt — bricht jemand bei Mollie ab,
|
||||||
|
* entsteht keine unbezahlte Bestellung. Adresse und Versandart setzt die
|
||||||
|
* Kasse vorher wie bei jeder anderen Zahlart.
|
||||||
|
*/
|
||||||
|
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
const query = req.scope.resolve("query");
|
||||||
|
const cartId = (req.body as { cart_id?: string })?.cart_id;
|
||||||
|
|
||||||
|
if (!isMollieConfigured()) {
|
||||||
|
return res.status(503).json({ message: "Online-Zahlung ist gerade nicht verfügbar." });
|
||||||
|
}
|
||||||
|
if (!cartId) {
|
||||||
|
return res.status(400).json({ message: "cart_id fehlt." });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data: carts } = await query.graph({
|
||||||
|
entity: "cart",
|
||||||
|
fields: [
|
||||||
|
...SUBSCRIPTION_CART_FIELDS,
|
||||||
|
"completed_at",
|
||||||
|
"metadata",
|
||||||
|
"total",
|
||||||
|
// Ohne Preise der Posten und Versandarten rechnet Medusa total = 0.
|
||||||
|
"items.*",
|
||||||
|
"shipping_methods.*",
|
||||||
|
],
|
||||||
|
filters: { id: cartId },
|
||||||
|
});
|
||||||
|
const cart: any = carts?.[0];
|
||||||
|
if (!cart || cart.completed_at) {
|
||||||
|
return res.status(404).json({ message: "Warenkorb nicht gefunden." });
|
||||||
|
}
|
||||||
|
if (hasSubscriptionLines(cart)) {
|
||||||
|
return res.status(400).json({ message: "Ein Abo läuft über die Abo-Kasse." });
|
||||||
|
}
|
||||||
|
if (!cart.email || !cart.shipping_address) {
|
||||||
|
return res.status(400).json({ message: "E-Mail-Adresse und Lieferadresse fehlen." });
|
||||||
|
}
|
||||||
|
const betrag = Math.round(Number(cart.total) * 100) / 100;
|
||||||
|
if (!(betrag > 0)) {
|
||||||
|
return res.status(400).json({ message: "Es ist nichts zu bezahlen." });
|
||||||
|
}
|
||||||
|
|
||||||
|
const storefront = process.env.STOREFRONT_URL ?? "http://localhost:4321";
|
||||||
|
const payment = await createOneOffPayment({
|
||||||
|
amount: betrag,
|
||||||
|
currency: String(cart.currency_code ?? "eur").toUpperCase(),
|
||||||
|
description: "place4bees Bestellung",
|
||||||
|
redirectUrl: `${storefront}/bestellung/zahlung?cart=${cart.id}`,
|
||||||
|
webhookUrl: process.env.MOLLIE_WEBHOOK_URL,
|
||||||
|
// Der Webhook findet den Warenkorb nur hierüber wieder.
|
||||||
|
metadata: { cart_id: cart.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Für die Rückkehrseite: woran sie erkennt, ob die Zahlung abgebrochen wurde.
|
||||||
|
await updateCartWorkflow(req.scope).run({
|
||||||
|
input: { id: cart.id, metadata: { ...(cart.metadata ?? {}), mollie_payment_id: payment.id } } as any,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({ checkout_url: payment.getCheckoutUrl?.() ?? (payment as any)._links?.checkout?.href });
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : "Online-Zahlung konnte nicht gestartet werden.";
|
||||||
|
req.scope.resolve("logger").error(`[mollie-kasse] ${message}`);
|
||||||
|
res.status(400).json({ message: "Online-Zahlung konnte nicht gestartet werden. Bitte versuchen Sie es erneut." });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { getPayment } from "../../../../lib/mollie";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stand einer Online-Zahlung für die Rückkehrseite.
|
||||||
|
*
|
||||||
|
* abgeschlossen — der Webhook hat die Bestellung angelegt
|
||||||
|
* wartet — Mollie hat noch nicht bestätigt (bei Überweisung dauert
|
||||||
|
* das Tage)
|
||||||
|
* abgebrochen — die Zahlung ist gescheitert oder wurde abgebrochen; der
|
||||||
|
* Warenkorb ist noch da und kann neu bezahlt werden
|
||||||
|
*/
|
||||||
|
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
const query = req.scope.resolve("query");
|
||||||
|
const cartId = req.query.cart_id as string | undefined;
|
||||||
|
if (!cartId) return res.status(400).json({ message: "cart_id fehlt." });
|
||||||
|
|
||||||
|
const { data: carts } = await query.graph({
|
||||||
|
entity: "cart",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"completed_at",
|
||||||
|
"metadata",
|
||||||
|
"order.id",
|
||||||
|
"order.display_id",
|
||||||
|
"order.email",
|
||||||
|
// Für die Dankeseite (Kaufmeldung an Analytics, nur mit Einwilligung).
|
||||||
|
"order.total",
|
||||||
|
"order.shipping_total",
|
||||||
|
"order.tax_total",
|
||||||
|
"order.currency_code",
|
||||||
|
"order.items.title",
|
||||||
|
"order.items.variant_id",
|
||||||
|
"order.items.unit_price",
|
||||||
|
"order.items.quantity",
|
||||||
|
],
|
||||||
|
filters: { id: cartId },
|
||||||
|
});
|
||||||
|
const cart: any = carts?.[0];
|
||||||
|
if (!cart) return res.status(404).json({ message: "Warenkorb nicht gefunden." });
|
||||||
|
|
||||||
|
if (cart.completed_at && cart.order) {
|
||||||
|
return res.json({
|
||||||
|
status: "abgeschlossen",
|
||||||
|
order: {
|
||||||
|
id: cart.order.id,
|
||||||
|
display_id: cart.order.display_id,
|
||||||
|
email: cart.order.email,
|
||||||
|
total: Number(cart.order.total ?? 0),
|
||||||
|
shipping_total: Number(cart.order.shipping_total ?? 0),
|
||||||
|
tax_total: Number(cart.order.tax_total ?? 0),
|
||||||
|
currency_code: cart.order.currency_code,
|
||||||
|
items: (cart.order.items ?? []).map((i: any) => ({
|
||||||
|
title: i.title,
|
||||||
|
variant_id: i.variant_id,
|
||||||
|
unit_price: Number(i.unit_price ?? 0),
|
||||||
|
quantity: Number(i.quantity ?? 1),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const molliePaymentId = cart.metadata?.mollie_payment_id;
|
||||||
|
if (!molliePaymentId) return res.json({ status: "abgebrochen" });
|
||||||
|
const payment: any = await getPayment(molliePaymentId);
|
||||||
|
res.json({ status: ["failed", "canceled", "expired"].includes(payment.status) ? "abgebrochen" : "wartet" });
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { isMollieConfigured } from "../../../lib/mollie";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Die Zahlungsarten, die der Shop anbieten darf.
|
* Die Zahlungsarten, die der Shop anbieten darf.
|
||||||
@@ -61,10 +62,28 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
|||||||
.map((provider: any) => provider.id)
|
.map((provider: any) => provider.id)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Mollie ist kein Medusa-Zahlungsanbieter an der Region, sondern läuft über
|
||||||
|
// /store/mollie/checkout — deshalb hier gesondert und nur mit Schlüssel.
|
||||||
|
const online = isMollieConfigured()
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: "mollie",
|
||||||
|
label: "Online bezahlen",
|
||||||
|
description:
|
||||||
|
// Nur nennen, was Mollie an der Kasse tatsächlich anbietet (Stand
|
||||||
|
// 26.10.2026). Klarna ist im Profil freigeschaltet, erscheint aber
|
||||||
|
// nicht: Es braucht die einzelnen Bestellposten, die eine einfache
|
||||||
|
// Zahlung nicht mitschickt. Kommt PayPal dazu, hier ergänzen.
|
||||||
|
"Kreditkarte, Sofortüberweisung oder Überweisung — die Auswahl folgt auf der sicheren Seite unseres Zahlungsdienstleisters Mollie.",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
payment_methods: ZAHLUNGSARTEN.filter(
|
payment_methods: [
|
||||||
(art) => art.bereit && anDerRegion.has(art.id)
|
...online,
|
||||||
).map(({ bereit, ...rest }) => rest),
|
...ZAHLUNGSARTEN.filter((art) => art.bereit && anDerRegion.has(art.id)).map(({ bereit, ...rest }) => rest),
|
||||||
|
],
|
||||||
// Für die Einrichtung sichtbar: was angeschlossen, aber noch nicht
|
// Für die Einrichtung sichtbar: was angeschlossen, aber noch nicht
|
||||||
// fertig ist. Der Shop zeigt das nicht an.
|
// fertig ist. Der Shop zeigt das nicht an.
|
||||||
not_ready: ZAHLUNGSARTEN.filter((art) => !art.bereit).map((art) => art.id),
|
not_ready: ZAHLUNGSARTEN.filter((art) => !art.bereit).map((art) => art.id),
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { cancelOrderWorkflow } from "@medusajs/core-flows";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { aboZahlungFehlgeschlagenMail } from "./order-emails";
|
||||||
|
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
||||||
|
|
||||||
|
/** Nach so vielen gescheiterten Abbuchungen wird das Abo pausiert. */
|
||||||
|
const MAX_FEHLVERSUCHE = 3;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Die Abbuchung für eine Abo-Lieferung ist gescheitert. Der Abo-Job hat die
|
||||||
|
* Bestellung schon angelegt — sie wird storniert, damit keine unbezahlte
|
||||||
|
* Lieferung im Admin liegt. Das Abo versucht es in drei Tagen erneut und
|
||||||
|
* pausiert nach dem dritten Fehlversuch. Der Kunde bekommt jedes Mal Bescheid.
|
||||||
|
*/
|
||||||
|
export async function aboAbbuchungGescheitert(scope: any, payment: any, logger: any) {
|
||||||
|
const { order_id: orderId, subscription_id: aboId } = payment.metadata ?? {};
|
||||||
|
if (!orderId || !aboId) return;
|
||||||
|
|
||||||
|
const orders: any = scope.resolve(Modules.ORDER);
|
||||||
|
const order = await orders.retrieveOrder(orderId, {
|
||||||
|
select: ["id", "display_id", "status", "metadata"],
|
||||||
|
relations: ["shipping_address"],
|
||||||
|
});
|
||||||
|
// Mollie meldet denselben Zustand mehrfach — nur einmal verarbeiten.
|
||||||
|
if (order.metadata?.mollie_fehlgeschlagen === payment.id) return;
|
||||||
|
|
||||||
|
await orders.updateOrders(orderId, {
|
||||||
|
// storno_grund sagt dem Storno-Subscriber, dass hier eine eigene Mail
|
||||||
|
// rausgeht und keine zweite nötig ist.
|
||||||
|
metadata: { ...(order.metadata ?? {}), mollie_fehlgeschlagen: payment.id, storno_grund: "abo_abbuchung" },
|
||||||
|
});
|
||||||
|
if (order.status !== "canceled") {
|
||||||
|
await cancelOrderWorkflow(scope).run({ input: { order_id: orderId } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const subscriptions: any = scope.resolve(SUBSCRIPTION_MODULE);
|
||||||
|
const [abo] = await subscriptions.listSubscriptions({ id: aboId });
|
||||||
|
if (!abo) return;
|
||||||
|
const versuche = (abo.failed_attempts ?? 0) + 1;
|
||||||
|
const pausiert = versuche >= MAX_FEHLVERSUCHE;
|
||||||
|
await subscriptions.updateSubscriptions({
|
||||||
|
id: abo.id,
|
||||||
|
failed_attempts: versuche,
|
||||||
|
last_error: `Abbuchung ${payment.id}: ${payment.status}`,
|
||||||
|
...(pausiert
|
||||||
|
? { status: "paused", paused_at: new Date() }
|
||||||
|
: { next_order_at: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000) }),
|
||||||
|
});
|
||||||
|
logger.warn(
|
||||||
|
`[mollie] Abo ${abo.id}: Abbuchung ${payment.id} ${payment.status}, Bestellung ${order.display_id} storniert` +
|
||||||
|
(pausiert ? ", Abo pausiert." : `, neuer Versuch in 3 Tagen (Versuch ${versuche}).`)
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const storefront = process.env.STOREFRONT_URL ?? "http://localhost:4321";
|
||||||
|
const rhythmus: Record<string, string> = {
|
||||||
|
monthly: "monatlich",
|
||||||
|
quarterly: "vierteljährlich",
|
||||||
|
biannual: "halbjährlich",
|
||||||
|
};
|
||||||
|
await scope.resolve(Modules.NOTIFICATION).createNotifications({
|
||||||
|
to: abo.email,
|
||||||
|
channel: "email",
|
||||||
|
template: pausiert ? "subscription-paused" : "subscription-payment-failed",
|
||||||
|
content: aboZahlungFehlgeschlagenMail({
|
||||||
|
shipping_address: order.shipping_address ?? null,
|
||||||
|
beschreibung: `${abo.size}, ${rhythmus[abo.interval] ?? abo.interval}`,
|
||||||
|
pausiert,
|
||||||
|
kontoLink: `${storefront}/konto/abos`,
|
||||||
|
}),
|
||||||
|
data: { subscription_id: abo.id, order_id: orderId },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
`[mail] Hinweis zur gescheiterten Abbuchung für ${abo.id} nicht verschickt: ${
|
||||||
|
error instanceof Error ? error.message : String(error)
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import { createHash, randomBytes } from "node:crypto";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { createCustomerAccountWorkflow } from "@medusajs/core-flows";
|
||||||
|
import { b2b, Eingabefehler } from "./b2b";
|
||||||
|
import { firmenEinladungMail, firmenZugangMail } from "./order-emails";
|
||||||
|
|
||||||
|
/** So lange gilt eine Einladung. */
|
||||||
|
const GUELTIG_TAGE = 14;
|
||||||
|
|
||||||
|
export const tokenHash = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||||
|
|
||||||
|
const storefront = () => process.env.STOREFRONT_URL ?? "http://localhost:4321";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schickt die Mail und wirft, wenn sie nicht wirklich rausgeht. Ohne
|
||||||
|
* Mailserver schreibt Medusa sie nur ins Log und meldet trotzdem Erfolg —
|
||||||
|
* im Admin stünde dann "Eingeladen", obwohl nie etwas ankommt.
|
||||||
|
*/
|
||||||
|
async function mailen(scope: any, an: string, vorlage: string, inhalt: { subject: string; html: string; text: string }) {
|
||||||
|
if (!process.env.SMTP_HOST || !process.env.MAIL_FROM) {
|
||||||
|
throw new Eingabefehler(
|
||||||
|
"Auf diesem System ist kein Mailserver eingerichtet (SMTP_HOST / MAIL_FROM fehlen). Die Einladung wurde nicht verschickt."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const notification: any = scope.resolve(Modules.NOTIFICATION);
|
||||||
|
try {
|
||||||
|
await notification.createNotifications({ to: an, channel: "email", template: vorlage, content: inhalt });
|
||||||
|
} catch (e) {
|
||||||
|
const grund = e instanceof Error ? e.message.split("\n").pop() : String(e);
|
||||||
|
throw new Eingabefehler(`Die Mail ließ sich nicht verschicken: ${grund}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lädt einen Ansprechpartner ins Firmenportal ein.
|
||||||
|
*
|
||||||
|
* Hat die Adresse schon ein Kundenkonto, wird es direkt verbunden — ein
|
||||||
|
* zweites Konto mit derselben Adresse ließe Medusa nicht zu. Sonst geht ein
|
||||||
|
* Link raus, über den das Passwort festgelegt wird; erst dann entsteht das
|
||||||
|
* Konto.
|
||||||
|
*/
|
||||||
|
export async function einladen(scope: any, kontaktId: string): Promise<"linked" | "invited"> {
|
||||||
|
const service = b2b(scope);
|
||||||
|
const kontakt = await service.retrieveContact(kontaktId, { relations: ["company"] });
|
||||||
|
if (kontakt.customer_id) throw new Eingabefehler("Dieser Ansprechpartner hat schon Zugang.");
|
||||||
|
|
||||||
|
const customerModule: any = scope.resolve(Modules.CUSTOMER);
|
||||||
|
const [kunde] = await customerModule.listCustomers({ email: kontakt.email, has_account: true }, { take: 1 });
|
||||||
|
const jetzt = new Date();
|
||||||
|
|
||||||
|
if (kunde) {
|
||||||
|
const [vergeben] = await service.listContacts({ customer_id: kunde.id }, { take: 1, relations: ["company"] });
|
||||||
|
if (vergeben) throw new Eingabefehler(`Dieses Konto gehört schon zu „${vergeben.company?.name}“.`);
|
||||||
|
await mailen(
|
||||||
|
scope,
|
||||||
|
kontakt.email,
|
||||||
|
"b2b-access",
|
||||||
|
firmenZugangMail({
|
||||||
|
firma: kontakt.company.name,
|
||||||
|
vorname: kontakt.first_name,
|
||||||
|
link: `${storefront()}/konto/anmelden?redirect=/konto/firma`,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
await service.updateContacts({
|
||||||
|
id: kontakt.id,
|
||||||
|
customer_id: kunde.id,
|
||||||
|
invited_at: jetzt,
|
||||||
|
accepted_at: jetzt,
|
||||||
|
invite_token_hash: null,
|
||||||
|
invite_expires_at: null,
|
||||||
|
});
|
||||||
|
return "linked";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Erst die Mail, dann speichern: Kommt sie nicht raus, bleibt der Status,
|
||||||
|
// wie er war, statt "Eingeladen" zu behaupten.
|
||||||
|
const token = randomBytes(32).toString("base64url");
|
||||||
|
await mailen(
|
||||||
|
scope,
|
||||||
|
kontakt.email,
|
||||||
|
"b2b-invite",
|
||||||
|
firmenEinladungMail({
|
||||||
|
firma: kontakt.company.name,
|
||||||
|
vorname: kontakt.first_name,
|
||||||
|
link: `${storefront()}/konto/einladung?token=${encodeURIComponent(token)}`,
|
||||||
|
tage: GUELTIG_TAGE,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
await service.updateContacts({
|
||||||
|
id: kontakt.id,
|
||||||
|
invite_token_hash: tokenHash(token),
|
||||||
|
invite_expires_at: new Date(jetzt.getTime() + GUELTIG_TAGE * 86400000),
|
||||||
|
invited_at: jetzt,
|
||||||
|
});
|
||||||
|
return "invited";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ansprechpartner zu einem gültigen Einladungslink, sonst `null`. */
|
||||||
|
export async function kontaktZumToken(scope: any, token: string) {
|
||||||
|
if (!token) return null;
|
||||||
|
const [kontakt] = await b2b(scope).listContacts(
|
||||||
|
{ invite_token_hash: tokenHash(token) },
|
||||||
|
{ take: 1, relations: ["company"] }
|
||||||
|
);
|
||||||
|
if (!kontakt || kontakt.customer_id) return null;
|
||||||
|
if (!kontakt.invite_expires_at || new Date(kontakt.invite_expires_at) <= new Date()) return null;
|
||||||
|
return kontakt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Löst die Einladung ein: Konto mit Passwort anlegen und verbinden. */
|
||||||
|
export async function einladungAnnehmen(scope: any, token: string, passwort: string) {
|
||||||
|
const kontakt = await kontaktZumToken(scope, token);
|
||||||
|
if (!kontakt) throw new Eingabefehler("Dieser Link ist abgelaufen oder ungültig.");
|
||||||
|
if (passwort.length < 8) throw new Eingabefehler("Das Passwort braucht mindestens 8 Zeichen.");
|
||||||
|
|
||||||
|
const auth: any = scope.resolve(Modules.AUTH);
|
||||||
|
const { success, authIdentity } = await auth.register("emailpass", {
|
||||||
|
body: { email: kontakt.email, password: passwort },
|
||||||
|
});
|
||||||
|
if (!success || !authIdentity) {
|
||||||
|
throw new Eingabefehler(
|
||||||
|
"Für diese Adresse gibt es schon ein Konto. Bitte melden Sie sich damit an und geben Sie uns kurz Bescheid — wir schalten den Zugang dann frei."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { result: kunde } = await createCustomerAccountWorkflow(scope).run({
|
||||||
|
input: {
|
||||||
|
authIdentityId: authIdentity.id,
|
||||||
|
customerData: {
|
||||||
|
email: kontakt.email,
|
||||||
|
first_name: kontakt.first_name ?? undefined,
|
||||||
|
last_name: kontakt.last_name ?? undefined,
|
||||||
|
phone: kontakt.phone ?? undefined,
|
||||||
|
company_name: kontakt.company?.name ?? undefined,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await b2b(scope).updateContacts({
|
||||||
|
id: kontakt.id,
|
||||||
|
customer_id: kunde.id,
|
||||||
|
accepted_at: new Date(),
|
||||||
|
invite_token_hash: null,
|
||||||
|
invite_expires_at: null,
|
||||||
|
});
|
||||||
|
return { email: kontakt.email as string };
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { FARBE, RAHMEN, STIL } from "./order-emails";
|
||||||
/**
|
/**
|
||||||
* Die Mail, die eine Anfrage aus einem Kontaktformular auslöst.
|
* Die Mail, die eine Anfrage aus einem Kontaktformular auslöst.
|
||||||
*
|
*
|
||||||
@@ -34,28 +35,23 @@ export function anfrageMail(anfrage: Anfrage) {
|
|||||||
...(seite ? [["Seite", seite] as [string, string]] : []),
|
...(seite ? [["Seite", seite] as [string, string]] : []),
|
||||||
];
|
];
|
||||||
|
|
||||||
const html = `<!doctype html>
|
const html = RAHMEN(`
|
||||||
<html lang="de"><head><meta charset="utf-8" /></head>
|
<h1 style="${STIL.h1}">Neue Anfrage über ${entschaerfen(quelle)}</h1>
|
||||||
<body style="margin:0;background:#f6f5f1;padding:24px;font-family:Arial,Helvetica,sans-serif;color:#1a1a1a;font-size:15px;line-height:1.55">
|
<table role="presentation" style="width:100%;border-collapse:collapse;margin:16px 0 0">
|
||||||
<div style="max-width:600px;margin:0 auto;background:#ffffff;padding:32px">
|
|
||||||
<h1 style="margin:0 0 20px;font-size:20px">Neue Anfrage über ${entschaerfen(quelle)}</h1>
|
|
||||||
<table style="width:100%;border-collapse:collapse">
|
|
||||||
${zeilen
|
${zeilen
|
||||||
.map(
|
.map(
|
||||||
([k, v]) => `<tr>
|
([k, v]) => `<tr>
|
||||||
<td style="padding:6px 12px 6px 0;color:#6b6b66;white-space:nowrap;vertical-align:top">${entschaerfen(k)}</td>
|
<td style="padding:6px 12px 6px 0;color:${FARBE.text};white-space:nowrap;vertical-align:top">${entschaerfen(k)}</td>
|
||||||
<td style="padding:6px 0">${entschaerfen(String(v))}</td>
|
<td style="padding:6px 0">${entschaerfen(String(v))}</td>
|
||||||
</tr>`
|
</tr>`
|
||||||
)
|
)
|
||||||
.join("")}
|
.join("")}
|
||||||
</table>
|
</table>
|
||||||
<h2 style="margin:24px 0 8px;font-size:16px">Nachricht</h2>
|
<h2 style="${STIL.h2}">Nachricht</h2>
|
||||||
<p style="margin:0;white-space:pre-wrap">${entschaerfen(nachricht)}</p>
|
<p style="margin:0;white-space:pre-wrap">${entschaerfen(nachricht)}</p>
|
||||||
<p style="margin:28px 0 0;padding-top:16px;border-top:1px solid #dcdcd8;color:#6b6b66;font-size:13px">
|
<p style="margin:28px 0 0;padding-top:16px;border-top:1px solid ${FARBE.linie};color:${FARBE.text};font-size:13px">
|
||||||
Antworten geht direkt an ${entschaerfen(email)}.
|
Antworten geht direkt an ${entschaerfen(email)}.
|
||||||
</p>
|
</p>`);
|
||||||
</div>
|
|
||||||
</body></html>`;
|
|
||||||
|
|
||||||
const text = [
|
const text = [
|
||||||
`Neue Anfrage über ${quelle}`,
|
`Neue Anfrage über ${quelle}`,
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
||||||
|
|
||||||
|
/** So steht die Bestätigung der Mailadresse im Auth-Modul. */
|
||||||
|
export const EMAIL_VERIFICATION = { entity_type: "email", code_provider: "token" } as const;
|
||||||
|
|
||||||
|
export function normalisiereEmail(email: string): string {
|
||||||
|
return email.trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ob die Adresse dieses Kontos bestätigt ist — über Medusas eingebaute
|
||||||
|
* Verifizierung (auth_verification), nicht über ein eigenes Feld.
|
||||||
|
*/
|
||||||
|
export async function istEmailBestaetigt(
|
||||||
|
container: any,
|
||||||
|
authIdentityId: string,
|
||||||
|
email: string
|
||||||
|
): Promise<boolean> {
|
||||||
|
const auth: any = container.resolve(Modules.AUTH);
|
||||||
|
const [eintrag] = await auth.listAuthVerifications(
|
||||||
|
{
|
||||||
|
auth_identity_id: authIdentityId,
|
||||||
|
entity_type: EMAIL_VERIFICATION.entity_type,
|
||||||
|
entity_id: normalisiereEmail(email),
|
||||||
|
},
|
||||||
|
{ take: 1 }
|
||||||
|
);
|
||||||
|
return Boolean(eintrag?.verified_at);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hängt Gastbestellungen und Gast-Abos mit derselben Mailadresse an das
|
||||||
|
* Konto. Nur aufrufen, wenn die Adresse bestätigt ist — sonst könnte sich
|
||||||
|
* jeder mit einer fremden Adresse registrieren und deren Bestellungen sehen.
|
||||||
|
*
|
||||||
|
* Mehrfach aufrufbar: Was schon am Konto hängt, wird nicht mehr gefunden.
|
||||||
|
*/
|
||||||
|
export async function uebernimmGastbestellungen(
|
||||||
|
container: any,
|
||||||
|
kunde: { id: string; email: string }
|
||||||
|
): Promise<{ bestellungen: number; abos: number }> {
|
||||||
|
const customers: any = container.resolve(Modules.CUSTOMER);
|
||||||
|
const orders: any = container.resolve(Modules.ORDER);
|
||||||
|
const subscriptions: any = container.resolve(SUBSCRIPTION_MODULE);
|
||||||
|
|
||||||
|
const email = normalisiereEmail(kunde.email);
|
||||||
|
// ilike wegen Groß-/Kleinschreibung; "_" in Adressen ist dort ein
|
||||||
|
// Platzhalter, deshalb danach noch exakt vergleichen.
|
||||||
|
const gaeste = (
|
||||||
|
await customers.listCustomers({ has_account: false, email: { $ilike: email } }, { select: ["id", "email"] })
|
||||||
|
).filter((c: any) => c.email && normalisiereEmail(c.email) === email);
|
||||||
|
const gastIds = gaeste.map((c: any) => c.id);
|
||||||
|
if (!gastIds.length) return { bestellungen: 0, abos: 0 };
|
||||||
|
|
||||||
|
const offen = await orders.listOrders({ customer_id: gastIds }, { select: ["id"] });
|
||||||
|
if (offen.length) {
|
||||||
|
await orders.updateOrders(offen.map((o: any) => ({ id: o.id, customer_id: kunde.id })));
|
||||||
|
}
|
||||||
|
|
||||||
|
const abos = await subscriptions.listSubscriptions({ customer_id: gastIds });
|
||||||
|
for (const abo of abos) {
|
||||||
|
await subscriptions.updateSubscriptions({ id: abo.id, customer_id: kunde.id });
|
||||||
|
}
|
||||||
|
|
||||||
|
return { bestellungen: offen.length, abos: abos.length };
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
||||||
|
import { geschenkAnkuendigung, patenschaftAnkuendigung } from "./order-emails";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ankündigungen an Beschenkte — Geschenk-Abo und Bienenpatenschaft.
|
||||||
|
*
|
||||||
|
* Sie gehen an eine Adresse, die der Käufer frei einträgt. Deshalb erst,
|
||||||
|
* wenn die Bestellung bezahlt ist: Sonst ließe sich über einen Kauf auf
|
||||||
|
* Rechnung kostenlos eine echte place4bees-Mail an jede beliebige Adresse
|
||||||
|
* auslösen. Aufgerufen bei order.placed (online bezahlt oder per Gutschein
|
||||||
|
* gedeckt) und bei payment.captured (Rechnung, sobald im Admin gebucht).
|
||||||
|
*
|
||||||
|
* Doppelte Mails verhindert der idempotency_key: Laufen beide Ereignisse
|
||||||
|
* gleichzeitig, verschickt das Benachrichtigungsmodul trotzdem nur einmal.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const RHYTHMUS: Record<string, string> = {
|
||||||
|
monthly: "monatlich",
|
||||||
|
quarterly: "vierteljährlich",
|
||||||
|
biannual: "halbjährlich",
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bezahlt heißt: eine Zahlung ist erfasst — oder es gibt gar keine
|
||||||
|
* Zahlungssammlung, weil ein Gutschein den ganzen Betrag gedeckt hat.
|
||||||
|
*/
|
||||||
|
export async function istBezahlt(container: any, orderId: string): Promise<boolean> {
|
||||||
|
const { data: orders } = await container.resolve("query").graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: ["id", "payment_collections.id", "payment_collections.payments.captured_at"],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const sammlungen = orders?.[0]?.payment_collections ?? [];
|
||||||
|
if (!sammlungen.length) return true;
|
||||||
|
return sammlungen.some((c: any) => (c.payments ?? []).some((p: any) => p.captured_at));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kündigt die verschenkten Abos einer bezahlten Bestellung an. */
|
||||||
|
export async function geschenkAbosAnkuendigen(container: any, orderId: string, logger: any) {
|
||||||
|
const { data: orders } = await container.resolve("query").graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: ["id", "display_id", "items.id"],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order = orders?.[0];
|
||||||
|
const postenIds = (order?.items ?? []).map((i: any) => i.id);
|
||||||
|
if (!postenIds.length) return;
|
||||||
|
|
||||||
|
const service: any = container.resolve(SUBSCRIPTION_MODULE);
|
||||||
|
const offen = (await service.listSubscriptions({ source_line_item_id: postenIds })).filter(
|
||||||
|
(abo: any) => abo.prepaid && abo.gift_recipient_email && !abo.gift_announced_at
|
||||||
|
);
|
||||||
|
if (!offen.length) return;
|
||||||
|
if (!(await istBezahlt(container, orderId))) {
|
||||||
|
logger.info(`[geschenk] Bestellung ${order.display_id}: Ankündigung wartet auf den Zahlungseingang.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const notification: any = container.resolve(Modules.NOTIFICATION);
|
||||||
|
for (const abo of offen) {
|
||||||
|
// Die erste Lieferung geht mit dieser Bestellung raus, deshalb ist die
|
||||||
|
// Gesamtzahl eine mehr als die verbleibenden.
|
||||||
|
const gesamt = (abo.remaining_deliveries ?? 0) + 1;
|
||||||
|
await notification.createNotifications({
|
||||||
|
to: abo.gift_recipient_email,
|
||||||
|
channel: "email",
|
||||||
|
template: "gift-announcement",
|
||||||
|
content: geschenkAnkuendigung({
|
||||||
|
empfaengerName: abo.gift_recipient_name,
|
||||||
|
schenkerName: abo.gift_sender_name ?? null,
|
||||||
|
lieferungen: gesamt,
|
||||||
|
rhythmus: RHYTHMUS[abo.interval] ?? abo.interval,
|
||||||
|
groesse: abo.size,
|
||||||
|
}),
|
||||||
|
idempotency_key: `geschenk-abo-ankuendigung-${abo.id}`,
|
||||||
|
data: { subscription_id: abo.id, order_id: orderId },
|
||||||
|
});
|
||||||
|
await service.updateSubscriptions({ id: abo.id, gift_announced_at: new Date() } as any);
|
||||||
|
logger.info(
|
||||||
|
`[geschenk] Abo ${abo.id} aus Bestellung ${order.display_id}: ${gesamt} Lieferungen, ` +
|
||||||
|
`Ankündigung an ${abo.gift_recipient_email}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kündigt verschenkte Patenschaften einer bezahlten Bestellung an. */
|
||||||
|
export async function patenschaftenAnkuendigen(container: any, orderId: string, logger: any) {
|
||||||
|
const { data: orders } = await container.resolve("query").graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: ["id", "display_id", "items.id", "items.metadata"],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order = orders?.[0];
|
||||||
|
if (!order) return;
|
||||||
|
|
||||||
|
// Auf die Felder herunterbrechen, die gebraucht werden — die Metadaten
|
||||||
|
// sind für den Übersetzer beliebig, hier soll es eindeutig sein.
|
||||||
|
const geschenke = (order.items ?? [])
|
||||||
|
.map((item: any) => ({
|
||||||
|
id: String(item?.id ?? ""),
|
||||||
|
name: String(item?.metadata?.sponsorship_name ?? ""),
|
||||||
|
email: String(item?.metadata?.sponsorship_recipient_email ?? ""),
|
||||||
|
von: item?.metadata?.sponsorship_sender_name ? String(item.metadata.sponsorship_sender_name) : null,
|
||||||
|
istGeschenk: item?.metadata?.sponsorship_gift === true,
|
||||||
|
}))
|
||||||
|
.filter((g: any) => g.istGeschenk && g.name && g.email);
|
||||||
|
if (!geschenke.length) return;
|
||||||
|
if (!(await istBezahlt(container, orderId))) {
|
||||||
|
logger.info(`[patenschaft] Bestellung ${order.display_id}: Ankündigung wartet auf den Zahlungseingang.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const notification: any = container.resolve(Modules.NOTIFICATION);
|
||||||
|
for (const item of geschenke) {
|
||||||
|
const erzeugt = await notification.createNotifications({
|
||||||
|
to: item.email,
|
||||||
|
channel: "email",
|
||||||
|
template: "sponsorship-announcement",
|
||||||
|
content: patenschaftAnkuendigung({ name: item.name, schenkerName: item.von }),
|
||||||
|
// Je Bestellposten genau eine Ankündigung.
|
||||||
|
idempotency_key: `patenschaft-ankuendigung-${item.id}`,
|
||||||
|
data: { order_id: order.id, line_item_id: item.id },
|
||||||
|
});
|
||||||
|
// Das Modul gibt nichts zurück, wenn es unter diesem Schlüssel schon
|
||||||
|
// verschickt hat. Das Protokoll soll keinen Versand behaupten, der
|
||||||
|
// gar nicht stattgefunden hat.
|
||||||
|
const verschickt = Array.isArray(erzeugt) ? erzeugt.length > 0 : Boolean(erzeugt);
|
||||||
|
logger.info(
|
||||||
|
verschickt
|
||||||
|
? `[patenschaft] Ankündigung zu Bestellung ${order.display_id} an ${item.email} (auf ${item.name}).`
|
||||||
|
: `[patenschaft] Ankündigung zu Bestellung ${order.display_id} war schon verschickt, übersprungen.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import {
|
||||||
|
capturePaymentWorkflow,
|
||||||
|
completeCartWorkflow,
|
||||||
|
createPaymentCollectionForCartWorkflow,
|
||||||
|
createPaymentSessionsWorkflow,
|
||||||
|
} from "@medusajs/core-flows";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { SUBSCRIPTION_CART_FIELDS } from "./subscription-from-order";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schließt einen Warenkorb ab, den der Kunde bei Mollie bezahlt hat — für
|
||||||
|
* Abo-Erstzahlung und normale Bestellung gleich.
|
||||||
|
*
|
||||||
|
* Das Geld liegt schon bei Mollie. In Medusa läuft die Zahlung deshalb über
|
||||||
|
* den manuellen Anbieter; die Mollie-Zahlung steht als `mollie_payment_id`
|
||||||
|
* an der Bestellung, damit Erstattungen sie finden.
|
||||||
|
*
|
||||||
|
* Mehrfach aufrufbar: Ist der Warenkorb schon abgeschlossen, kommt die
|
||||||
|
* vorhandene Bestellung mit `neu: false` zurück — so legt ein wiederholter
|
||||||
|
* Webhook kein zweites Abo an.
|
||||||
|
*
|
||||||
|
* Gibt `null` zurück, wenn nicht abgeschlossen werden darf — dann steht der
|
||||||
|
* Grund im Log.
|
||||||
|
*/
|
||||||
|
export async function bezahltenWarenkorbAbschliessen(
|
||||||
|
scope: any,
|
||||||
|
payment: any,
|
||||||
|
logger: any
|
||||||
|
): Promise<{ orderId: string; neu: boolean } | null> {
|
||||||
|
const query = scope.resolve("query");
|
||||||
|
const cartId = payment.metadata?.cart_id;
|
||||||
|
if (!cartId) {
|
||||||
|
logger.warn(`[mollie] ${payment.id}: keine cart_id in den Metadaten.`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data: carts } = await query.graph({
|
||||||
|
entity: "cart",
|
||||||
|
fields: [
|
||||||
|
...SUBSCRIPTION_CART_FIELDS,
|
||||||
|
"completed_at",
|
||||||
|
"total",
|
||||||
|
// Ohne Preise der Posten und Versandarten rechnet Medusa total = 0.
|
||||||
|
"items.*",
|
||||||
|
"shipping_methods.*",
|
||||||
|
"payment_collection.id",
|
||||||
|
"payment_collection.payment_sessions.id",
|
||||||
|
"order.id",
|
||||||
|
],
|
||||||
|
filters: { id: cartId },
|
||||||
|
});
|
||||||
|
const cart: any = carts?.[0];
|
||||||
|
if (!cart) {
|
||||||
|
logger.warn(`[mollie] Warenkorb ${cartId} nicht gefunden.`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (cart.completed_at) {
|
||||||
|
logger.info(`[mollie] Warenkorb ${cartId} war schon abgeschlossen.`);
|
||||||
|
return cart.order?.id ? { orderId: cart.order.id, neu: false } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Der Warenkorb ließe sich nach dem Anlegen der Zahlung noch ändern. Passt
|
||||||
|
// der bezahlte Betrag nicht mehr, wird nichts abgeschlossen — sonst gäbe es
|
||||||
|
// Ware, die niemand bezahlt hat.
|
||||||
|
const bezahlt = Number(payment.amount?.value);
|
||||||
|
const soll = Math.round(Number(cart.total) * 100) / 100;
|
||||||
|
if (Math.abs(bezahlt - soll) > 0.005) {
|
||||||
|
logger.error(
|
||||||
|
`[mollie] ${payment.id}: bezahlt ${bezahlt.toFixed(2)} €, Warenkorb ${cartId} steht bei ${soll.toFixed(2)} € — ` +
|
||||||
|
"nicht abgeschlossen. Bitte prüfen und den Betrag bei Mollie erstatten."
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ein früherer Aufruf kann Sammlung und Sitzung schon angelegt haben und
|
||||||
|
// erst danach gescheitert sein — dann weiterverwenden statt neu anlegen.
|
||||||
|
let collectionId = cart.payment_collection?.id;
|
||||||
|
if (!collectionId) {
|
||||||
|
const { result: sammlung } = await createPaymentCollectionForCartWorkflow(scope).run({
|
||||||
|
input: { cart_id: cartId },
|
||||||
|
});
|
||||||
|
collectionId = (sammlung as any).id;
|
||||||
|
}
|
||||||
|
if (!cart.payment_collection?.payment_sessions?.length) {
|
||||||
|
await createPaymentSessionsWorkflow(scope).run({
|
||||||
|
input: { payment_collection_id: collectionId, provider_id: "pp_system_default" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const { result: bestellung } = await completeCartWorkflow(scope).run({ input: { id: cartId } });
|
||||||
|
const orderId = (bestellung as any)?.id;
|
||||||
|
await mollieZahlungMerken(scope, orderId, payment.id);
|
||||||
|
return { orderId, neu: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hält die Mollie-Zahlung an der Bestellung fest — für spätere Erstattungen. */
|
||||||
|
export async function mollieZahlungMerken(scope: any, orderId: string, molliePaymentId: string) {
|
||||||
|
const orders: any = scope.resolve(Modules.ORDER);
|
||||||
|
const order = await orders.retrieveOrder(orderId, { select: ["id", "metadata"] });
|
||||||
|
if (order.metadata?.mollie_payment_id === molliePaymentId) return;
|
||||||
|
await orders.updateOrders(orderId, {
|
||||||
|
metadata: { ...(order.metadata ?? {}), mollie_payment_id: molliePaymentId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erfasst die Zahlung der Bestellung in Medusa. Das löst `payment.captured`
|
||||||
|
* aus, worauf der Subscriber das Versandlabel erzeugt.
|
||||||
|
*/
|
||||||
|
export async function bestellungsZahlungErfassen(scope: any, orderId: string | undefined, logger: any) {
|
||||||
|
if (!orderId) return;
|
||||||
|
const query = scope.resolve("query");
|
||||||
|
const { data: orders } = await query.graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"payment_collections.payments.id",
|
||||||
|
"payment_collections.payments.amount",
|
||||||
|
"payment_collections.payments.captured_at",
|
||||||
|
],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const zahlungen = orders?.[0]?.payment_collections?.flatMap((c: any) => c.payments ?? []) ?? [];
|
||||||
|
for (const zahlung of zahlungen) {
|
||||||
|
if (zahlung.captured_at) continue;
|
||||||
|
await capturePaymentWorkflow(scope).run({
|
||||||
|
input: { payment_id: zahlung.id, amount: zahlung.amount },
|
||||||
|
});
|
||||||
|
logger.info(`[mollie] Zahlung ${zahlung.id} erfasst — Label wird erzeugt.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { getPayment, isMollieConfigured, refundMolliePayment } from "./mollie";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bringt Mollie auf den Stand der Erstattungen in Medusa.
|
||||||
|
*
|
||||||
|
* Medusa bucht Erstattungen nur — bezahlt wurde aber bei Mollie, also muss
|
||||||
|
* das Geld auch dort zurück. Verglichen wird die Summe aller Erstattungen in
|
||||||
|
* Medusa mit dem, was Mollie schon zurückgezahlt hat; erstattet wird nur die
|
||||||
|
* Differenz. So ist es egal, ob die Erstattung über "Refund" im Admin kam
|
||||||
|
* (payment.refunded) oder über ein Storno (dort löst Medusa kein Ereignis
|
||||||
|
* pro Zahlung aus), und ein doppelter Aufruf erstattet nichts doppelt.
|
||||||
|
*
|
||||||
|
* Gibt den bei Mollie neu erstatteten Betrag zurück, 0 wenn nichts zu tun war.
|
||||||
|
*/
|
||||||
|
export async function erstattungenMitMollieAbgleichen(scope: any, orderId: string, logger: any): Promise<number> {
|
||||||
|
const query = scope.resolve("query");
|
||||||
|
const { data: orders } = await query.graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"display_id",
|
||||||
|
"currency_code",
|
||||||
|
"metadata",
|
||||||
|
"payment_collections.payments.refunds.amount",
|
||||||
|
],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order: any = orders?.[0];
|
||||||
|
const molliePaymentId = order?.metadata?.mollie_payment_id;
|
||||||
|
if (!molliePaymentId) return 0; // nicht über Mollie bezahlt, z. B. Rechnung
|
||||||
|
if (!isMollieConfigured()) {
|
||||||
|
logger.error(`[erstattung] Bestellung ${order.display_id}: MOLLIE_API_KEY fehlt — bitte bei Mollie von Hand erstatten.`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const inMedusa = (order.payment_collections ?? [])
|
||||||
|
.flatMap((c: any) => c.payments ?? [])
|
||||||
|
.flatMap((p: any) => p.refunds ?? [])
|
||||||
|
.reduce((summe: number, r: any) => summe + Number(r.amount ?? 0), 0);
|
||||||
|
|
||||||
|
// Nicht amountRefunded: Eine gerade angelegte Erstattung steht dort erst,
|
||||||
|
// wenn Mollie sie ausgeführt hat — bis dahin würde ein zweiter Aufruf sie
|
||||||
|
// doppelt anlegen. amountRemaining sinkt dagegen sofort.
|
||||||
|
const mollie: any = await getPayment(molliePaymentId);
|
||||||
|
const beiMollie = Number(mollie.amount?.value ?? 0) - Number(mollie.amountRemaining?.value ?? mollie.amount?.value ?? 0);
|
||||||
|
const offen = Math.round((inMedusa - beiMollie) * 100) / 100;
|
||||||
|
if (offen <= 0) return 0;
|
||||||
|
|
||||||
|
await refundMolliePayment({
|
||||||
|
paymentId: molliePaymentId,
|
||||||
|
amount: offen,
|
||||||
|
currency: String(order.currency_code ?? "eur").toUpperCase(),
|
||||||
|
description: `place4bees Erstattung Bestellung ${order.display_id}`,
|
||||||
|
});
|
||||||
|
logger.info(`[erstattung] Bestellung ${order.display_id}: ${offen.toFixed(2)} € bei Mollie erstattet (${molliePaymentId}).`);
|
||||||
|
return offen;
|
||||||
|
}
|
||||||
@@ -123,3 +123,38 @@ export async function chargeRecurring(params: {
|
|||||||
export async function getPayment(paymentId: string) {
|
export async function getPayment(paymentId: string) {
|
||||||
return getMollie().payments.get(paymentId);
|
return getMollie().payments.get(paymentId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Einmalige Zahlung für eine normale Bestellung. Ohne Kunde und Mandat —
|
||||||
|
* die Zahlart wählt der Kunde auf Mollies Seite.
|
||||||
|
*/
|
||||||
|
export async function createOneOffPayment(params: {
|
||||||
|
amount: number;
|
||||||
|
description: string;
|
||||||
|
redirectUrl: string;
|
||||||
|
webhookUrl?: string;
|
||||||
|
metadata?: Record<string, unknown>;
|
||||||
|
currency?: string;
|
||||||
|
}) {
|
||||||
|
return getMollie().payments.create({
|
||||||
|
amount: money(params.amount, params.currency ?? "EUR"),
|
||||||
|
description: params.description,
|
||||||
|
redirectUrl: params.redirectUrl,
|
||||||
|
...(params.webhookUrl ? { webhookUrl: params.webhookUrl } : {}),
|
||||||
|
metadata: params.metadata as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Erstattet einen Betrag auf das Zahlungsmittel, mit dem gezahlt wurde. */
|
||||||
|
export async function refundMolliePayment(params: {
|
||||||
|
paymentId: string;
|
||||||
|
amount: number;
|
||||||
|
description: string;
|
||||||
|
currency?: string;
|
||||||
|
}) {
|
||||||
|
return getMollie().paymentRefunds.create({
|
||||||
|
paymentId: params.paymentId,
|
||||||
|
amount: money(params.amount, params.currency ?? "EUR"),
|
||||||
|
description: params.description,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,6 +10,8 @@
|
|||||||
* Feldauswahl abweichende Werte (siehe Kommentar in invoice-handler.ts).
|
* Feldauswahl abweichende Werte (siehe Kommentar in invoice-handler.ts).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { MAIL_LOGO_CID } from "./mail-logo";
|
||||||
|
|
||||||
const SHOP = {
|
const SHOP = {
|
||||||
name: "PLACE4BEES GmbH",
|
name: "PLACE4BEES GmbH",
|
||||||
web: "www.place4bees.com",
|
web: "www.place4bees.com",
|
||||||
@@ -57,10 +59,15 @@ function runden(zahl: number): number {
|
|||||||
|
|
||||||
/** Anrede ohne Geschlechtsannahme: der Vorname allein reicht und liegt vor. */
|
/** Anrede ohne Geschlechtsannahme: der Vorname allein reicht und liegt vor. */
|
||||||
function anrede(adresse: Record<string, any> | null): string {
|
function anrede(adresse: Record<string, any> | null): string {
|
||||||
const name = [adresse?.first_name, adresse?.last_name].filter(Boolean).join(" ");
|
const name = kundenname([adresse?.first_name, adresse?.last_name].filter(Boolean).join(" "));
|
||||||
return name ? `Hallo ${name},` : "Hallo,";
|
return name ? `Hallo ${name},` : "Hallo,";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Die Anrede für den HTML-Teil: Der Name stammt aus der Kundeneingabe. */
|
||||||
|
function anredeHtml(adresse: Record<string, any> | null): string {
|
||||||
|
return html(anrede(adresse));
|
||||||
|
}
|
||||||
|
|
||||||
function summen(bestellung: MailBestellung) {
|
function summen(bestellung: MailBestellung) {
|
||||||
const posten = bestellung.items.map((item) => ({
|
const posten = bestellung.items.map((item) => ({
|
||||||
...item,
|
...item,
|
||||||
@@ -84,6 +91,15 @@ function html(text: string): string {
|
|||||||
.replace(/"/g, """);
|
.replace(/"/g, """);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Name, den eine Kundin eingegeben hat — gekürzt, damit niemand ganze Absätze
|
||||||
|
* in eine Mail schmuggelt, die wir an Dritte schicken. Im HTML-Teil zusätzlich
|
||||||
|
* mit html() maskieren.
|
||||||
|
*/
|
||||||
|
function kundenname(wert: unknown): string {
|
||||||
|
return String(wert ?? "").trim().slice(0, 80);
|
||||||
|
}
|
||||||
|
|
||||||
function adressblock(adresse: Record<string, any> | null): string[] {
|
function adressblock(adresse: Record<string, any> | null): string[] {
|
||||||
if (!adresse) return [];
|
if (!adresse) return [];
|
||||||
return [
|
return [
|
||||||
@@ -96,15 +112,64 @@ function adressblock(adresse: Record<string, any> | null): string[] {
|
|||||||
].filter(Boolean) as string[];
|
].filter(Boolean) as string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const RAHMEN = (inhalt: string) => `<!doctype html>
|
/*
|
||||||
<html lang="de"><head><meta charset="utf-8" /></head>
|
* Gestaltung wie die Webseite: Farben aus frontend/src/styles/global.css,
|
||||||
<body style="margin:0;background:#f6f5f1;padding:24px;font-family:Arial,Helvetica,sans-serif;color:#1a1a1a;font-size:15px;line-height:1.55">
|
* Überschriften in Bebas Neue, Fließtext in Open Sans. Programme ohne
|
||||||
<div style="max-width:600px;margin:0 auto;background:#ffffff;padding:32px">
|
* Webfonts (z. B. Gmail) fallen auf Arial zurück.
|
||||||
|
*
|
||||||
|
* Tabellen statt div/flex, alle Stile inline: so stellen auch Outlook und
|
||||||
|
* Gmail die Mail richtig dar.
|
||||||
|
*/
|
||||||
|
export const FARBE = {
|
||||||
|
honig: "#f8ac11",
|
||||||
|
honigTinte: "#8a5e05",
|
||||||
|
honigHell: "#fdf3dc",
|
||||||
|
tinte: "#212326",
|
||||||
|
text: "#5b6068",
|
||||||
|
textLeise: "#8b9099",
|
||||||
|
linie: "#e3e5e9",
|
||||||
|
flaeche: "#f2f3f5",
|
||||||
|
};
|
||||||
|
const SCHRIFT = "'Open Sans',Arial,Helvetica,sans-serif";
|
||||||
|
const DISPLAY = "'Bebas Neue','Arial Narrow',Arial,Helvetica,sans-serif";
|
||||||
|
|
||||||
|
/** Stile, die in allen Vorlagen gleich aussehen sollen. */
|
||||||
|
export const STIL = {
|
||||||
|
h1: `margin:0 0 6px;font-family:${DISPLAY};font-weight:normal;font-size:36px;line-height:1.1;letter-spacing:0.5px;text-transform:uppercase;color:${FARBE.tinte}`,
|
||||||
|
h2: `margin:28px 0 8px;font-family:${DISPLAY};font-weight:normal;font-size:22px;line-height:1.2;letter-spacing:0.5px;text-transform:uppercase;color:${FARBE.tinte}`,
|
||||||
|
kasten: `margin:20px 0 0;padding:14px 16px;background:${FARBE.honigHell};border-left:3px solid ${FARBE.honig};border-radius:4px`,
|
||||||
|
link: `color:${FARBE.honigTinte};text-decoration:underline`,
|
||||||
|
knopf: `display:inline-block;background:${FARBE.honig};color:${FARBE.tinte};text-decoration:none;font-weight:bold;padding:13px 26px;border-radius:6px`,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const RAHMEN = (inhalt: string) => `<!doctype html>
|
||||||
|
<html lang="de"><head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Open+Sans:wght@400;700&display=swap" rel="stylesheet" />
|
||||||
|
</head>
|
||||||
|
<body style="margin:0;padding:0;background:${FARBE.flaeche}">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${FARBE.flaeche}">
|
||||||
|
<tr><td align="center" style="padding:28px 12px">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px;background:#ffffff;border-radius:10px;overflow:hidden">
|
||||||
|
<tr><td align="center" style="padding:28px 24px 22px">
|
||||||
|
<img src="cid:${MAIL_LOGO_CID}" width="140" height="110" alt="place4bees — Hamburger Stadtimkerei" style="display:block;border:0" />
|
||||||
|
</td></tr>
|
||||||
|
<tr><td align="center" style="background:${FARBE.honig};padding:9px 16px;font-family:${SCHRIFT};font-size:11px;font-weight:bold;letter-spacing:1.6px;text-transform:uppercase;color:${FARBE.tinte}">
|
||||||
|
Direkt vom Imker · handabgefüllt in Hamburg
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding:36px 36px 32px;font-family:${SCHRIFT};font-size:15px;line-height:1.6;color:${FARBE.tinte}">
|
||||||
${inhalt}
|
${inhalt}
|
||||||
<p style="margin:32px 0 0;padding-top:20px;border-top:1px solid #dcdcd8;color:#6b6b66;font-size:13px">
|
</td></tr>
|
||||||
${SHOP.name} · ${SHOP.web} · <a href="mailto:${SHOP.email}" style="color:#8a5e05">${SHOP.email}</a>
|
<tr><td style="background:${FARBE.tinte};padding:24px 36px;font-family:${SCHRIFT};font-size:12px;line-height:1.7;color:#c9ccd1">
|
||||||
</p>
|
<span style="font-family:${DISPLAY};font-size:18px;letter-spacing:1px;color:#ffffff">PLACE<span style="color:${FARBE.honig}">4</span>BEES</span><br />
|
||||||
</div>
|
${SHOP.name} · Hamburger Stadtimkerei<br />
|
||||||
|
<a href="https://${SHOP.web}" style="color:#ffffff;text-decoration:none">${SHOP.web}</a> ·
|
||||||
|
<a href="mailto:${SHOP.email}" style="color:#ffffff;text-decoration:none">${SHOP.email}</a>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
</body></html>`;
|
</body></html>`;
|
||||||
|
|
||||||
function postenTabelle(bestellung: MailBestellung): string {
|
function postenTabelle(bestellung: MailBestellung): string {
|
||||||
@@ -113,12 +178,12 @@ function postenTabelle(bestellung: MailBestellung): string {
|
|||||||
const zeilen = posten
|
const zeilen = posten
|
||||||
.map(
|
.map(
|
||||||
(p) => `<tr>
|
(p) => `<tr>
|
||||||
<td style="padding:8px 0;border-bottom:1px solid #eeeeea">${p.quantity} × ${p.title}${
|
<td style="padding:8px 0;border-bottom:1px solid ${FARBE.linie}">${p.quantity} × ${p.title}${
|
||||||
p.hinweis
|
p.hinweis
|
||||||
? `<br /><span style="color:#6b6b66;font-size:13px">${p.hinweis}</span>`
|
? `<br /><span style="color:${FARBE.text};font-size:13px">${html(kundenname(p.hinweis))}</span>`
|
||||||
: ""
|
: ""
|
||||||
}</td>
|
}</td>
|
||||||
<td style="padding:8px 0;border-bottom:1px solid #eeeeea;text-align:right;white-space:nowrap">${euro(p.gesamt, w)}</td>
|
<td style="padding:8px 0;border-bottom:1px solid ${FARBE.linie};text-align:right;white-space:nowrap">${euro(p.gesamt, w)}</td>
|
||||||
</tr>`
|
</tr>`
|
||||||
)
|
)
|
||||||
.join("");
|
.join("");
|
||||||
@@ -131,8 +196,8 @@ function postenTabelle(bestellung: MailBestellung): string {
|
|||||||
: ""
|
: ""
|
||||||
}
|
}
|
||||||
<tr>
|
<tr>
|
||||||
<td style="padding:10px 0 0;border-top:1px solid #dcdcd8;font-weight:bold">Gesamt</td>
|
<td style="padding:10px 0 0;border-top:1px solid ${FARBE.linie};font-weight:bold">Gesamt</td>
|
||||||
<td style="padding:10px 0 0;border-top:1px solid #dcdcd8;text-align:right;font-weight:bold">${euro(gesamt, w)}</td>
|
<td style="padding:10px 0 0;border-top:1px solid ${FARBE.linie};text-align:right;font-weight:bold">${euro(gesamt, w)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
${
|
${
|
||||||
abzug > 0
|
abzug > 0
|
||||||
@@ -148,7 +213,7 @@ function postenTabelle(bestellung: MailBestellung): string {
|
|||||||
: ""
|
: ""
|
||||||
}
|
}
|
||||||
</table>
|
</table>
|
||||||
<p style="margin:10px 0 0;color:#6b6b66;font-size:13px">Alle Preise inklusive Umsatzsteuer.</p>`;
|
<p style="margin:10px 0 0;color:${FARBE.text};font-size:13px">Alle Preise inklusive Umsatzsteuer.</p>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -192,18 +257,18 @@ export function bestellbestaetigung(bestellung: MailBestellung) {
|
|||||||
: einleitungZeilen.join("\n ");
|
: einleitungZeilen.join("\n ");
|
||||||
|
|
||||||
const html = RAHMEN(`
|
const html = RAHMEN(`
|
||||||
<h1 style="margin:0 0 4px;font-size:22px">${ueberschrift}</h1>
|
<h1 style="${STIL.h1}">${ueberschrift}</h1>
|
||||||
<p style="margin:0;color:#6b6b66">Bestellnummer ${bestellung.display_id}</p>
|
<p style="margin:0;color:${FARBE.text}">Bestellnummer ${bestellung.display_id}</p>
|
||||||
<p style="margin:24px 0 0">${anrede(bestellung.shipping_address)}</p>
|
<p style="margin:24px 0 0">${anredeHtml(bestellung.shipping_address)}</p>
|
||||||
<p style="margin:12px 0 0">${einleitung}</p>
|
<p style="margin:12px 0 0">${einleitung}</p>
|
||||||
${postenTabelle(bestellung)}
|
${postenTabelle(bestellung)}
|
||||||
${
|
${
|
||||||
adresse.length
|
adresse.length
|
||||||
? `<h2 style="margin:28px 0 6px;font-size:16px">${nurDigital ? "Rechnungsadresse" : "Lieferadresse"}</h2>
|
? `<h2 style="${STIL.h2}">${nurDigital ? "Rechnungsadresse" : "Lieferadresse"}</h2>
|
||||||
<p style="margin:0;color:#4a4a45">${adresse.join("<br />")}</p>`
|
<p style="margin:0;color:${FARBE.text}">${adresse.join("<br />")}</p>`
|
||||||
: ""
|
: ""
|
||||||
}
|
}
|
||||||
<p style="margin:28px 0 0;color:#6b6b66;font-size:13px">
|
<p style="margin:28px 0 0;color:${FARBE.text};font-size:13px">
|
||||||
Diese E-Mail bestätigt den Eingang Ihrer Bestellung. Die Rechnung liegt
|
Diese E-Mail bestätigt den Eingang Ihrer Bestellung. Die Rechnung liegt
|
||||||
als PDF bei. Ihr Widerrufsrecht und die Bedingungen finden Sie unter
|
als PDF bei. Ihr Widerrufsrecht und die Bedingungen finden Sie unter
|
||||||
${SHOP.web}.
|
${SHOP.web}.
|
||||||
@@ -262,7 +327,7 @@ export function versandnachricht(bestellung: MailBestellung, sendungen: Sendung[
|
|||||||
(s) => `<li style="margin:0 0 6px">
|
(s) => `<li style="margin:0 0 6px">
|
||||||
<strong>${s.tracking_number}</strong>${
|
<strong>${s.tracking_number}</strong>${
|
||||||
s.tracking_url
|
s.tracking_url
|
||||||
? ` — <a href="${s.tracking_url}" style="color:#8a5e05">Sendung verfolgen</a>`
|
? ` — <a href="${s.tracking_url}" style="${STIL.link}">Sendung verfolgen</a>`
|
||||||
: ""
|
: ""
|
||||||
}
|
}
|
||||||
</li>`
|
</li>`
|
||||||
@@ -270,15 +335,15 @@ export function versandnachricht(bestellung: MailBestellung, sendungen: Sendung[
|
|||||||
.join("");
|
.join("");
|
||||||
|
|
||||||
const html = RAHMEN(`
|
const html = RAHMEN(`
|
||||||
<h1 style="margin:0 0 4px;font-size:22px">Ihre Bestellung ist unterwegs</h1>
|
<h1 style="${STIL.h1}">Ihre Bestellung ist unterwegs</h1>
|
||||||
<p style="margin:0;color:#6b6b66">Bestellnummer ${bestellung.display_id}</p>
|
<p style="margin:0;color:${FARBE.text}">Bestellnummer ${bestellung.display_id}</p>
|
||||||
<p style="margin:24px 0 0">${anrede(bestellung.shipping_address)}</p>
|
<p style="margin:24px 0 0">${anredeHtml(bestellung.shipping_address)}</p>
|
||||||
<p style="margin:12px 0 0">
|
<p style="margin:12px 0 0">
|
||||||
wir haben Ihr Paket verpackt und ${versandart ? `mit ${versandart} ` : ""}auf den Weg gebracht.
|
wir haben Ihr Paket verpackt und ${versandart ? `mit ${versandart} ` : ""}auf den Weg gebracht.
|
||||||
</p>
|
</p>
|
||||||
<h2 style="margin:24px 0 8px;font-size:16px">Sendungsnummer</h2>
|
<h2 style="${STIL.h2}">Sendungsnummer</h2>
|
||||||
<ul style="margin:0;padding-left:18px">${nummern}</ul>
|
<ul style="margin:0;padding-left:18px">${nummern}</ul>
|
||||||
<p style="margin:16px 0 0;padding:12px 14px;background:#faf6ec">
|
<p style="${STIL.kasten}">
|
||||||
<strong>Stand:</strong> Sendung angemeldet — das Paket ist beim
|
<strong>Stand:</strong> Sendung angemeldet — das Paket ist beim
|
||||||
Versanddienstleister eingebucht. Bis zur ersten Statusmeldung in der
|
Versanddienstleister eingebucht. Bis zur ersten Statusmeldung in der
|
||||||
Verfolgung können einige Stunden vergehen.
|
Verfolgung können einige Stunden vergehen.
|
||||||
@@ -323,21 +388,23 @@ export type GeschenkAbo = {
|
|||||||
|
|
||||||
/** Ankündigung an den Beschenkten, sobald das Geschenk gekauft ist. */
|
/** Ankündigung an den Beschenkten, sobald das Geschenk gekauft ist. */
|
||||||
export function geschenkAnkuendigung(abo: GeschenkAbo) {
|
export function geschenkAnkuendigung(abo: GeschenkAbo) {
|
||||||
const von = abo.schenkerName ? `${abo.schenkerName} schenkt Ihnen` : "Jemand schenkt Ihnen";
|
const empfaenger = kundenname(abo.empfaengerName);
|
||||||
|
const schenker = kundenname(abo.schenkerName);
|
||||||
|
const von = schenker ? `${schenker} schenkt Ihnen` : "Jemand schenkt Ihnen";
|
||||||
const umfang = `${abo.lieferungen} Lieferungen, ${abo.rhythmus}${abo.groesse ? `, je ${abo.groesse}` : ""}`;
|
const umfang = `${abo.lieferungen} Lieferungen, ${abo.rhythmus}${abo.groesse ? `, je ${abo.groesse}` : ""}`;
|
||||||
|
|
||||||
const html = RAHMEN(`
|
const htmlInhalt = RAHMEN(`
|
||||||
<h1 style="margin:0 0 4px;font-size:22px">Für Sie: ein Honig-Abo</h1>
|
<h1 style="${STIL.h1}">Für Sie: ein Honig-Abo</h1>
|
||||||
<p style="margin:24px 0 0">Hallo ${abo.empfaengerName},</p>
|
<p style="margin:24px 0 0">Hallo ${html(empfaenger)},</p>
|
||||||
<p style="margin:12px 0 0">
|
<p style="margin:12px 0 0">
|
||||||
${von} ein Honig-Abo von place4bees — ${umfang}. Der Honig kommt aus
|
${html(von)} ein Honig-Abo von place4bees — ${umfang}. Der Honig kommt aus
|
||||||
unseren eigenen Völkern, von Hand abgefüllt in Hamburg.
|
unseren eigenen Völkern, von Hand abgefüllt in Hamburg.
|
||||||
</p>
|
</p>
|
||||||
<p style="margin:16px 0 0">
|
<p style="margin:16px 0 0">
|
||||||
Sie müssen nichts tun. Die erste Sendung ist schon unterwegs, und zu
|
Sie müssen nichts tun. Die erste Sendung ist schon unterwegs, und zu
|
||||||
jedem weiteren Paket schicken wir Ihnen die Sendungsnummer.
|
jedem weiteren Paket schicken wir Ihnen die Sendungsnummer.
|
||||||
</p>
|
</p>
|
||||||
<p style="margin:24px 0 0;color:#6b6b66;font-size:13px">
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">
|
||||||
Stimmt die Lieferadresse nicht oder passt der Zeitpunkt nicht?
|
Stimmt die Lieferadresse nicht oder passt der Zeitpunkt nicht?
|
||||||
Schreiben Sie uns einfach.
|
Schreiben Sie uns einfach.
|
||||||
</p>`);
|
</p>`);
|
||||||
@@ -345,7 +412,7 @@ export function geschenkAnkuendigung(abo: GeschenkAbo) {
|
|||||||
const text = [
|
const text = [
|
||||||
"Für Sie: ein Honig-Abo",
|
"Für Sie: ein Honig-Abo",
|
||||||
"",
|
"",
|
||||||
`Hallo ${abo.empfaengerName},`,
|
`Hallo ${empfaenger},`,
|
||||||
"",
|
"",
|
||||||
`${von} ein Honig-Abo von place4bees — ${umfang}.`,
|
`${von} ein Honig-Abo von place4bees — ${umfang}.`,
|
||||||
"Der Honig kommt aus unseren eigenen Völkern, von Hand abgefüllt in Hamburg.",
|
"Der Honig kommt aus unseren eigenen Völkern, von Hand abgefüllt in Hamburg.",
|
||||||
@@ -356,7 +423,7 @@ export function geschenkAnkuendigung(abo: GeschenkAbo) {
|
|||||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
].join("\n");
|
].join("\n");
|
||||||
|
|
||||||
return { subject: "Für Sie: ein Honig-Abo von place4bees", html, text };
|
return { subject: "Für Sie: ein Honig-Abo von place4bees", html: htmlInhalt, text };
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Kuendigung = {
|
export type Kuendigung = {
|
||||||
@@ -392,7 +459,7 @@ export function kuendigungsbestaetigung(k: Kuendigung) {
|
|||||||
if (k.grund) zeilen.push(["Grund", k.grund]);
|
if (k.grund) zeilen.push(["Grund", k.grund]);
|
||||||
|
|
||||||
const htmlInhalt = RAHMEN(`
|
const htmlInhalt = RAHMEN(`
|
||||||
<h1 style="margin:0 0 4px;font-size:22px">Ihre Kündigung ist eingegangen</h1>
|
<h1 style="${STIL.h1}">Ihre Kündigung ist eingegangen</h1>
|
||||||
<p style="margin:24px 0 0">Hallo,</p>
|
<p style="margin:24px 0 0">Hallo,</p>
|
||||||
<p style="margin:12px 0 0">
|
<p style="margin:12px 0 0">
|
||||||
hiermit bestätigen wir den Eingang Ihrer Kündigung. Ihr Abo endet
|
hiermit bestätigen wir den Eingang Ihrer Kündigung. Ihr Abo endet
|
||||||
@@ -402,13 +469,13 @@ export function kuendigungsbestaetigung(k: Kuendigung) {
|
|||||||
${zeilen
|
${zeilen
|
||||||
.map(
|
.map(
|
||||||
([feld, wert]) => `<tr>
|
([feld, wert]) => `<tr>
|
||||||
<td style="padding:6px 12px 6px 0;color:#6b6b66;vertical-align:top;white-space:nowrap">${feld}</td>
|
<td style="padding:6px 12px 6px 0;color:${FARBE.text};vertical-align:top;white-space:nowrap">${feld}</td>
|
||||||
<td style="padding:6px 0">${html(wert)}</td>
|
<td style="padding:6px 0">${html(wert)}</td>
|
||||||
</tr>`
|
</tr>`
|
||||||
)
|
)
|
||||||
.join("")}
|
.join("")}
|
||||||
</table>
|
</table>
|
||||||
<p style="margin:24px 0 0;color:#6b6b66;font-size:13px">
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">
|
||||||
Bewahren Sie diese E-Mail als Nachweis auf. War die Kündigung ein
|
Bewahren Sie diese E-Mail als Nachweis auf. War die Kündigung ein
|
||||||
Versehen? Schreiben Sie uns einfach.
|
Versehen? Schreiben Sie uns einfach.
|
||||||
</p>`);
|
</p>`);
|
||||||
@@ -431,6 +498,249 @@ export function kuendigungsbestaetigung(k: Kuendigung) {
|
|||||||
return { subject: "Bestätigung Ihrer Kündigung – place4bees Honig-Abo", html: htmlInhalt, text };
|
return { subject: "Bestätigung Ihrer Kündigung – place4bees Honig-Abo", html: htmlInhalt, text };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Eine Mail mit genau einem Knopf — für Bestätigungs- und Zurücksetzen-Links. */
|
||||||
|
function linkMail(k: { titel: string; absatz: string; knopf: string; link: string; hinweis: string }) {
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">${k.titel}</h1>
|
||||||
|
<p style="margin:24px 0 0">Hallo,</p>
|
||||||
|
<p style="margin:12px 0 0">${k.absatz}</p>
|
||||||
|
<p style="margin:24px 0 0">
|
||||||
|
<a href="${html(k.link)}" style="${STIL.knopf}">${k.knopf}</a>
|
||||||
|
</p>
|
||||||
|
<p style="margin:16px 0 0;color:${FARBE.text};font-size:13px">
|
||||||
|
Der Link gilt 15 Minuten. Funktioniert der Knopf nicht, kopieren Sie
|
||||||
|
diese Adresse in Ihren Browser:<br />
|
||||||
|
<span style="word-break:break-all">${html(k.link)}</span>
|
||||||
|
</p>
|
||||||
|
<p style="margin:16px 0 0;color:${FARBE.text};font-size:13px">${k.hinweis}</p>`);
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
k.titel,
|
||||||
|
"",
|
||||||
|
"Hallo,",
|
||||||
|
"",
|
||||||
|
k.absatz,
|
||||||
|
"",
|
||||||
|
k.link,
|
||||||
|
"",
|
||||||
|
"Der Link gilt 15 Minuten.",
|
||||||
|
k.hinweis,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
return { html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bestätigung der Mailadresse nach der Registrierung. */
|
||||||
|
export function emailBestaetigenMail(link: string) {
|
||||||
|
return {
|
||||||
|
subject: "Bitte bestätigen Sie Ihre E-Mail-Adresse – place4bees",
|
||||||
|
...linkMail({
|
||||||
|
titel: "E-Mail-Adresse bestätigen",
|
||||||
|
absatz:
|
||||||
|
"bitte bestätigen Sie, dass diese Adresse zu Ihrem place4bees-Konto gehört. Danach sehen Sie dort auch Bestellungen und Abos, die Sie ohne Anmeldung mit dieser Adresse abgeschlossen haben.",
|
||||||
|
knopf: "Adresse bestätigen",
|
||||||
|
link,
|
||||||
|
hinweis: "Sie haben kein Konto angelegt? Dann können Sie diese E-Mail ignorieren.",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Link zum Zurücksetzen des Passworts. */
|
||||||
|
export function passwortZuruecksetzenMail(link: string) {
|
||||||
|
return {
|
||||||
|
subject: "Passwort zurücksetzen – place4bees",
|
||||||
|
...linkMail({
|
||||||
|
titel: "Neues Passwort festlegen",
|
||||||
|
absatz: "für Ihr place4bees-Konto wurde ein neues Passwort angefordert. Über diesen Link legen Sie es fest.",
|
||||||
|
knopf: "Neues Passwort festlegen",
|
||||||
|
link,
|
||||||
|
hinweis: "Sie haben nichts angefordert? Dann ignorieren Sie diese E-Mail — Ihr Passwort bleibt unverändert.",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Einladung ins Firmenportal. Gilt länger als die Konto-Links: Wer
|
||||||
|
* eingeladen wird, liest die Mail nicht unbedingt sofort.
|
||||||
|
*/
|
||||||
|
export function firmenEinladungMail(e: { firma: string; vorname?: string | null; link: string; tage: number }) {
|
||||||
|
const anredeText = e.vorname ? `Hallo ${e.vorname},` : "Hallo,";
|
||||||
|
const absatz = `für ${e.firma} haben wir Ihnen einen Zugang zum place4bees-Firmenportal eingerichtet. Dort sehen Sie Ihre Bienenpatenschaften, Lieferungen, Neuigkeiten von Ihren Völkern und alle Dokumente. Legen Sie über diesen Link Ihr Passwort fest.`;
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">Ihr Zugang zum Firmenportal</h1>
|
||||||
|
<p style="margin:24px 0 0">${html(anredeText)}</p>
|
||||||
|
<p style="margin:12px 0 0">${html(absatz)}</p>
|
||||||
|
<p style="margin:24px 0 0">
|
||||||
|
<a href="${html(e.link)}" style="${STIL.knopf}">Passwort festlegen</a>
|
||||||
|
</p>
|
||||||
|
<p style="margin:16px 0 0;color:${FARBE.text};font-size:13px">
|
||||||
|
Der Link gilt ${e.tage} Tage. Funktioniert der Knopf nicht, kopieren Sie
|
||||||
|
diese Adresse in Ihren Browser:<br />
|
||||||
|
<span style="word-break:break-all">${html(e.link)}</span>
|
||||||
|
</p>`);
|
||||||
|
const text = [
|
||||||
|
"Ihr Zugang zum Firmenportal",
|
||||||
|
"",
|
||||||
|
anredeText,
|
||||||
|
"",
|
||||||
|
absatz,
|
||||||
|
"",
|
||||||
|
e.link,
|
||||||
|
"",
|
||||||
|
`Der Link gilt ${e.tage} Tage.`,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
return { subject: `Ihr Zugang zum Firmenportal – ${SHOP.name}`, html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Für Eingeladene, die schon ein Kundenkonto haben: Zugang ist sofort frei. */
|
||||||
|
export function firmenZugangMail(e: { firma: string; vorname?: string | null; link: string }) {
|
||||||
|
const anredeText = e.vorname ? `Hallo ${e.vorname},` : "Hallo,";
|
||||||
|
const absatz = `Ihr bestehendes place4bees-Konto ist jetzt mit ${e.firma} verbunden. Nach der Anmeldung finden Sie im Firmenportal Ihre Bienenpatenschaften, Lieferungen, Neuigkeiten und Dokumente.`;
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">Firmenportal freigeschaltet</h1>
|
||||||
|
<p style="margin:24px 0 0">${html(anredeText)}</p>
|
||||||
|
<p style="margin:12px 0 0">${html(absatz)}</p>
|
||||||
|
<p style="margin:24px 0 0">
|
||||||
|
<a href="${html(e.link)}" style="${STIL.knopf}">Zum Firmenportal</a>
|
||||||
|
</p>`);
|
||||||
|
const text = [
|
||||||
|
"Firmenportal freigeschaltet",
|
||||||
|
"",
|
||||||
|
anredeText,
|
||||||
|
"",
|
||||||
|
absatz,
|
||||||
|
"",
|
||||||
|
e.link,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
return { subject: `Firmenportal freigeschaltet – ${SHOP.name}`, html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Schlusszeile für Mails, auf die man eine Rückfrage haben könnte. */
|
||||||
|
const RUECKFRAGE = `Fragen? Schreiben Sie uns an ${SHOP.email}.`;
|
||||||
|
|
||||||
|
/** Storno einer Bestellung. `erstattet` ist der Betrag, der zurückgeht. */
|
||||||
|
export function stornoMail(s: {
|
||||||
|
display_id: number | string;
|
||||||
|
shipping_address: Record<string, any> | null;
|
||||||
|
erstattet: number;
|
||||||
|
waehrung: string;
|
||||||
|
}) {
|
||||||
|
const geld =
|
||||||
|
s.erstattet > 0
|
||||||
|
? `Den bereits gezahlten Betrag von ${euro(s.erstattet, s.waehrung)} erstatten wir auf das Zahlungsmittel, mit dem Sie bezahlt haben. Je nach Bank dauert die Gutschrift einige Tage.`
|
||||||
|
: "Sie müssen nichts bezahlen.";
|
||||||
|
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">Bestellung storniert</h1>
|
||||||
|
<p style="margin:0;color:${FARBE.text}">Bestellnummer ${s.display_id}</p>
|
||||||
|
<p style="margin:24px 0 0">${anredeHtml(s.shipping_address)}</p>
|
||||||
|
<p style="margin:12px 0 0">wir haben Ihre Bestellung ${s.display_id} storniert. Sie wird nicht verschickt.</p>
|
||||||
|
<p style="${STIL.kasten}">${geld}</p>
|
||||||
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">${RUECKFRAGE}</p>`);
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`Bestellung ${s.display_id} storniert`,
|
||||||
|
"",
|
||||||
|
anrede(s.shipping_address),
|
||||||
|
"",
|
||||||
|
`wir haben Ihre Bestellung ${s.display_id} storniert. Sie wird nicht verschickt.`,
|
||||||
|
"",
|
||||||
|
geld,
|
||||||
|
"",
|
||||||
|
RUECKFRAGE,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
return { subject: `Ihre Bestellung ${s.display_id} wurde storniert`, html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Erstattung eines Betrags zu einer Bestellung. */
|
||||||
|
export function erstattungMail(e: {
|
||||||
|
display_id: number | string;
|
||||||
|
shipping_address: Record<string, any> | null;
|
||||||
|
betrag: number;
|
||||||
|
waehrung: string;
|
||||||
|
}) {
|
||||||
|
const betrag = euro(e.betrag, e.waehrung);
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">Geld ist unterwegs</h1>
|
||||||
|
<p style="margin:0;color:${FARBE.text}">Bestellnummer ${e.display_id}</p>
|
||||||
|
<p style="margin:24px 0 0">${anredeHtml(e.shipping_address)}</p>
|
||||||
|
<p style="margin:12px 0 0">
|
||||||
|
wir haben Ihnen zu Ihrer Bestellung ${e.display_id} <strong>${betrag}</strong> erstattet —
|
||||||
|
auf das Zahlungsmittel, mit dem Sie bezahlt haben.
|
||||||
|
</p>
|
||||||
|
<p style="${STIL.kasten}">Je nach Bank und Zahlart dauert es einige Tage, bis die Gutschrift auf Ihrem Konto erscheint.</p>
|
||||||
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">${RUECKFRAGE}</p>`);
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`Erstattung zu Bestellung ${e.display_id}`,
|
||||||
|
"",
|
||||||
|
anrede(e.shipping_address),
|
||||||
|
"",
|
||||||
|
`wir haben Ihnen zu Ihrer Bestellung ${e.display_id} ${betrag} erstattet —`,
|
||||||
|
"auf das Zahlungsmittel, mit dem Sie bezahlt haben.",
|
||||||
|
"Je nach Bank und Zahlart dauert es einige Tage, bis die Gutschrift erscheint.",
|
||||||
|
"",
|
||||||
|
RUECKFRAGE,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
return { subject: `Erstattung zu Ihrer Bestellung ${e.display_id}`, html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abbuchung für eine Abo-Lieferung ist fehlgeschlagen. Nach mehreren
|
||||||
|
* Fehlversuchen ist das Abo pausiert — dann sagt die Mail das.
|
||||||
|
*/
|
||||||
|
export function aboZahlungFehlgeschlagenMail(a: {
|
||||||
|
shipping_address: Record<string, any> | null;
|
||||||
|
beschreibung: string;
|
||||||
|
pausiert: boolean;
|
||||||
|
kontoLink: string;
|
||||||
|
}) {
|
||||||
|
const titel = a.pausiert ? "Ihr Abo ist pausiert" : "Abbuchung hat nicht geklappt";
|
||||||
|
const absatz = a.pausiert
|
||||||
|
? `die Abbuchung für Ihr Honig-Abo (${a.beschreibung}) ist mehrmals fehlgeschlagen. Wir haben das Abo deshalb pausiert — es wird nichts geliefert und nichts abgebucht.`
|
||||||
|
: `die Abbuchung für die nächste Lieferung Ihres Honig-Abos (${a.beschreibung}) ist fehlgeschlagen. Die Lieferung geht deshalb noch nicht raus. In drei Tagen versuchen wir es erneut.`;
|
||||||
|
const hinweis = a.pausiert
|
||||||
|
? "Sobald Ihr Zahlungsmittel wieder funktioniert, können Sie das Abo im Kundenkonto fortsetzen."
|
||||||
|
: "Bitte prüfen Sie, ob Ihr Zahlungsmittel noch gültig und das Konto gedeckt ist.";
|
||||||
|
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">${titel}</h1>
|
||||||
|
<p style="margin:24px 0 0">${anredeHtml(a.shipping_address)}</p>
|
||||||
|
<p style="margin:12px 0 0">${absatz}</p>
|
||||||
|
<p style="${STIL.kasten}">${hinweis}</p>
|
||||||
|
<p style="margin:24px 0 0"><a href="${html(a.kontoLink)}" style="${STIL.knopf}">Abo im Kundenkonto ansehen</a></p>
|
||||||
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">${RUECKFRAGE}</p>`);
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
titel,
|
||||||
|
"",
|
||||||
|
anrede(a.shipping_address),
|
||||||
|
"",
|
||||||
|
absatz,
|
||||||
|
"",
|
||||||
|
hinweis,
|
||||||
|
a.kontoLink,
|
||||||
|
"",
|
||||||
|
RUECKFRAGE,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
return { subject: `${titel} – place4bees Honig-Abo`, html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
/** Versandnachricht an den Beschenkten — dieselbe Sendung, ohne Beträge. */
|
/** Versandnachricht an den Beschenkten — dieselbe Sendung, ohne Beträge. */
|
||||||
export function geschenkVersandnachricht(
|
export function geschenkVersandnachricht(
|
||||||
empfaengerName: string,
|
empfaengerName: string,
|
||||||
@@ -441,7 +751,7 @@ export function geschenkVersandnachricht(
|
|||||||
const nummern = sendungen
|
const nummern = sendungen
|
||||||
.map(
|
.map(
|
||||||
(s) => `<li style="margin:0 0 6px"><strong>${s.tracking_number}</strong>${
|
(s) => `<li style="margin:0 0 6px"><strong>${s.tracking_number}</strong>${
|
||||||
s.tracking_url ? ` — <a href="${s.tracking_url}" style="color:#8a5e05">Sendung verfolgen</a>` : ""
|
s.tracking_url ? ` — <a href="${s.tracking_url}" style="${STIL.link}">Sendung verfolgen</a>` : ""
|
||||||
}</li>`
|
}</li>`
|
||||||
)
|
)
|
||||||
.join("");
|
.join("");
|
||||||
@@ -451,17 +761,17 @@ export function geschenkVersandnachricht(
|
|||||||
? `Danach kommen noch ${verbleibend} weitere Lieferungen.`
|
? `Danach kommen noch ${verbleibend} weitere Lieferungen.`
|
||||||
: "Das war die letzte Lieferung Ihres Abos.";
|
: "Das war die letzte Lieferung Ihres Abos.";
|
||||||
|
|
||||||
const html = RAHMEN(`
|
const htmlInhalt = RAHMEN(`
|
||||||
<h1 style="margin:0 0 4px;font-size:22px">Ihr Honig ist unterwegs</h1>
|
<h1 style="${STIL.h1}">Ihr Honig ist unterwegs</h1>
|
||||||
<p style="margin:24px 0 0">Hallo ${empfaengerName},</p>
|
<p style="margin:24px 0 0">Hallo ${html(kundenname(empfaengerName))},</p>
|
||||||
<p style="margin:12px 0 0">die nächste Lieferung Ihres Honig-Abos ist auf dem Weg.</p>
|
<p style="margin:12px 0 0">die nächste Lieferung Ihres Honig-Abos ist auf dem Weg.</p>
|
||||||
<h2 style="margin:24px 0 8px;font-size:16px">Im Paket</h2>
|
<h2 style="${STIL.h2}">Im Paket</h2>
|
||||||
<ul style="margin:0;padding-left:18px">
|
<ul style="margin:0;padding-left:18px">
|
||||||
${posten.map((p) => `<li style="margin:0 0 4px">${p.quantity} × ${p.title}</li>`).join("")}
|
${posten.map((p) => `<li style="margin:0 0 4px">${p.quantity} × ${p.title}</li>`).join("")}
|
||||||
</ul>
|
</ul>
|
||||||
<h2 style="margin:24px 0 8px;font-size:16px">Sendungsnummer</h2>
|
<h2 style="${STIL.h2}">Sendungsnummer</h2>
|
||||||
<ul style="margin:0;padding-left:18px">${nummern}</ul>
|
<ul style="margin:0;padding-left:18px">${nummern}</ul>
|
||||||
<p style="margin:16px 0 0;padding:12px 14px;background:#faf6ec">
|
<p style="${STIL.kasten}">
|
||||||
<strong>Stand:</strong> Sendung angemeldet — das Paket ist beim
|
<strong>Stand:</strong> Sendung angemeldet — das Paket ist beim
|
||||||
Versanddienstleister eingebucht. ${rest}
|
Versanddienstleister eingebucht. ${rest}
|
||||||
</p>`);
|
</p>`);
|
||||||
@@ -469,7 +779,7 @@ export function geschenkVersandnachricht(
|
|||||||
const text = [
|
const text = [
|
||||||
"Ihr Honig ist unterwegs",
|
"Ihr Honig ist unterwegs",
|
||||||
"",
|
"",
|
||||||
`Hallo ${empfaengerName},`,
|
`Hallo ${kundenname(empfaengerName)},`,
|
||||||
"",
|
"",
|
||||||
"die nächste Lieferung Ihres Honig-Abos ist auf dem Weg.",
|
"die nächste Lieferung Ihres Honig-Abos ist auf dem Weg.",
|
||||||
"",
|
"",
|
||||||
@@ -484,7 +794,7 @@ export function geschenkVersandnachricht(
|
|||||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
].join("\n");
|
].join("\n");
|
||||||
|
|
||||||
return { subject: "Ihr Honig ist unterwegs", html, text };
|
return { subject: "Ihr Honig ist unterwegs", html: htmlInhalt, text };
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --- Bienenpatenschaft ----------------------------------------------------
|
/* --- Bienenpatenschaft ----------------------------------------------------
|
||||||
@@ -501,9 +811,9 @@ export type PatenschaftGeschenk = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function patenschaftAnkuendigung(geschenk: PatenschaftGeschenk) {
|
export function patenschaftAnkuendigung(geschenk: PatenschaftGeschenk) {
|
||||||
const von = geschenk.schenkerName
|
const name = kundenname(geschenk.name);
|
||||||
? `${geschenk.schenkerName} schenkt Ihnen`
|
const schenker = kundenname(geschenk.schenkerName);
|
||||||
: "Jemand schenkt Ihnen";
|
const von = schenker ? `${schenker} schenkt Ihnen` : "Jemand schenkt Ihnen";
|
||||||
|
|
||||||
// Die Leistungen stehen so in der Produktbeschreibung — hier nichts
|
// Die Leistungen stehen so in der Produktbeschreibung — hier nichts
|
||||||
// dazuerfinden, was der Shop nicht verspricht.
|
// dazuerfinden, was der Shop nicht verspricht.
|
||||||
@@ -514,29 +824,29 @@ export function patenschaftAnkuendigung(geschenk: PatenschaftGeschenk) {
|
|||||||
"Bilder und Nachrichten vom Volk, dreimal im Jahr per E-Mail",
|
"Bilder und Nachrichten vom Volk, dreimal im Jahr per E-Mail",
|
||||||
];
|
];
|
||||||
|
|
||||||
const html = RAHMEN(`
|
const htmlInhalt = RAHMEN(`
|
||||||
<h1 style="margin:0 0 4px;font-size:22px">Für Sie: eine Bienenpatenschaft</h1>
|
<h1 style="${STIL.h1}">Für Sie: eine Bienenpatenschaft</h1>
|
||||||
<p style="margin:24px 0 0">Hallo ${geschenk.name},</p>
|
<p style="margin:24px 0 0">Hallo ${html(name)},</p>
|
||||||
<p style="margin:12px 0 0">
|
<p style="margin:12px 0 0">
|
||||||
${von} eine Bienenpatenschaft bei place4bees. Ein Volk in Hamburg trägt
|
${html(von)} eine Bienenpatenschaft bei place4bees. Ein Volk in Hamburg trägt
|
||||||
von jetzt an Ihren Namen — auf der Urkunde und auf dem Etikett der Gläser.
|
von jetzt an Ihren Namen — auf der Urkunde und auf dem Etikett der Gläser.
|
||||||
</p>
|
</p>
|
||||||
<h2 style="margin:24px 0 8px;font-size:16px">Was dazugehört</h2>
|
<h2 style="${STIL.h2}">Was dazugehört</h2>
|
||||||
<ul style="margin:0;padding-left:18px">
|
<ul style="margin:0;padding-left:18px">
|
||||||
${leistungen.map((l) => `<li style="margin:0 0 5px">${l}</li>`).join("")}
|
${leistungen.map((l) => `<li style="margin:0 0 5px">${l}</li>`).join("")}
|
||||||
</ul>
|
</ul>
|
||||||
<p style="margin:20px 0 0;padding:12px 14px;background:#faf6ec">
|
<p style="${STIL.kasten}">
|
||||||
Geerntet wird zweimal im Jahr. Ihren eigenen Honig bekommen Sie am Ende
|
Geerntet wird zweimal im Jahr. Ihren eigenen Honig bekommen Sie am Ende
|
||||||
der Bienensaison, im Oktober oder November.
|
der Bienensaison, im Oktober oder November.
|
||||||
</p>
|
</p>
|
||||||
<p style="margin:24px 0 0;color:#6b6b66;font-size:13px">
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">
|
||||||
Sie müssen nichts tun. Fragen beantworten wir gern — einfach antworten.
|
Sie müssen nichts tun. Fragen beantworten wir gern — einfach antworten.
|
||||||
</p>`);
|
</p>`);
|
||||||
|
|
||||||
const text = [
|
const text = [
|
||||||
"Für Sie: eine Bienenpatenschaft",
|
"Für Sie: eine Bienenpatenschaft",
|
||||||
"",
|
"",
|
||||||
`Hallo ${geschenk.name},`,
|
`Hallo ${name},`,
|
||||||
"",
|
"",
|
||||||
`${von} eine Bienenpatenschaft bei place4bees. Ein Volk in Hamburg trägt`,
|
`${von} eine Bienenpatenschaft bei place4bees. Ein Volk in Hamburg trägt`,
|
||||||
"von jetzt an Ihren Namen — auf der Urkunde und auf dem Etikett der Gläser.",
|
"von jetzt an Ihren Namen — auf der Urkunde und auf dem Etikett der Gläser.",
|
||||||
@@ -550,7 +860,7 @@ export function patenschaftAnkuendigung(geschenk: PatenschaftGeschenk) {
|
|||||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
].join("\n");
|
].join("\n");
|
||||||
|
|
||||||
return { subject: "Für Sie: eine Bienenpatenschaft bei place4bees", html, text };
|
return { subject: "Für Sie: eine Bienenpatenschaft bei place4bees", html: htmlInhalt, text };
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --- Geschenkgutschein ----------------------------------------------------
|
/* --- Geschenkgutschein ----------------------------------------------------
|
||||||
@@ -574,9 +884,9 @@ export type GutscheinInhalt = {
|
|||||||
/** Der Gutschein selbst — an den Beschenkten oder an den Käufer. */
|
/** Der Gutschein selbst — an den Beschenkten oder an den Käufer. */
|
||||||
export function gutscheinMail(g: GutscheinInhalt) {
|
export function gutscheinMail(g: GutscheinInhalt) {
|
||||||
const betrag = euro(g.betrag, g.waehrung);
|
const betrag = euro(g.betrag, g.waehrung);
|
||||||
const hallo = g.empfaengerName ? `Hallo ${g.empfaengerName},` : "Hallo,";
|
const hallo = g.empfaengerName ? `Hallo ${kundenname(g.empfaengerName)},` : "Hallo,";
|
||||||
const einleitung = g.geschenk
|
const einleitung = g.geschenk
|
||||||
? `${g.schenkerName ? `${g.schenkerName} schenkt` : "Jemand schenkt"} Ihnen einen Gutschein über ${betrag} für den Honig-Shop von place4bees.`
|
? `${g.schenkerName ? `${kundenname(g.schenkerName)} schenkt` : "Jemand schenkt"} Ihnen einen Gutschein über ${betrag} für den Honig-Shop von place4bees.`
|
||||||
: `hier ist Ihr Gutschein über ${betrag} für den Honig-Shop von place4bees.`;
|
: `hier ist Ihr Gutschein über ${betrag} für den Honig-Shop von place4bees.`;
|
||||||
const einloesen = [
|
const einloesen = [
|
||||||
"Wählen Sie im Shop aus, was Ihnen gefällt, und geben Sie den Code an der Kasse unter „Gutschein einlösen“ ein.",
|
"Wählen Sie im Shop aus, was Ihnen gefällt, und geben Sie den Code an der Kasse unter „Gutschein einlösen“ ein.",
|
||||||
@@ -584,23 +894,23 @@ export function gutscheinMail(g: GutscheinInhalt) {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const inhalt = RAHMEN(`
|
const inhalt = RAHMEN(`
|
||||||
<h1 style="margin:0 0 4px;font-size:22px">${g.geschenk ? "Für Sie: ein Gutschein" : "Ihr Gutschein"}</h1>
|
<h1 style="${STIL.h1}">${g.geschenk ? "Für Sie: ein Gutschein" : "Ihr Gutschein"}</h1>
|
||||||
<p style="margin:24px 0 0">${html(hallo)}</p>
|
<p style="margin:24px 0 0">${html(hallo)}</p>
|
||||||
<p style="margin:12px 0 0">${html(einleitung)}</p>
|
<p style="margin:12px 0 0">${html(einleitung)}</p>
|
||||||
${
|
${
|
||||||
g.nachricht
|
g.nachricht
|
||||||
? `<p style="margin:16px 0 0;padding:12px 14px;background:#faf6ec;white-space:pre-line">${html(g.nachricht)}</p>`
|
? `<p style="${STIL.kasten};white-space:pre-line">${html(g.nachricht)}</p>`
|
||||||
: ""
|
: ""
|
||||||
}
|
}
|
||||||
<div style="margin:24px 0 0;padding:20px;border:2px dashed #f8ac11;text-align:center">
|
<div style="margin:24px 0 0;padding:20px;border:2px dashed #f8ac11;text-align:center">
|
||||||
<p style="margin:0;color:#6b6b66;font-size:13px">Gutscheincode</p>
|
<p style="margin:0;color:${FARBE.text};font-size:13px">Gutscheincode</p>
|
||||||
<p style="margin:6px 0 0;font-family:'Courier New',Courier,monospace;font-size:24px;font-weight:bold;letter-spacing:2px">${html(g.code)}</p>
|
<p style="margin:6px 0 0;font-family:'Courier New',Courier,monospace;font-size:24px;font-weight:bold;letter-spacing:2px">${html(g.code)}</p>
|
||||||
<p style="margin:6px 0 0;font-size:16px">Wert: ${betrag}</p>
|
<p style="margin:6px 0 0;font-size:16px">Wert: ${betrag}</p>
|
||||||
</div>
|
</div>
|
||||||
<h2 style="margin:24px 0 8px;font-size:16px">So lösen Sie ihn ein</h2>
|
<h2 style="${STIL.h2}">So lösen Sie ihn ein</h2>
|
||||||
${einloesen.map((satz) => `<p style="margin:0 0 8px">${satz}</p>`).join("")}
|
${einloesen.map((satz) => `<p style="margin:0 0 8px">${satz}</p>`).join("")}
|
||||||
<p style="margin:16px 0 0"><a href="https://${SHOP.web}/shop" style="color:#8a5e05">Zum Shop</a></p>
|
<p style="margin:16px 0 0"><a href="https://${SHOP.web}/shop" style="${STIL.link}">Zum Shop</a></p>
|
||||||
<p style="margin:24px 0 0;color:#6b6b66;font-size:13px">
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">
|
||||||
Bewahren Sie diese E-Mail gut auf: Wer den Code kennt, kann das Guthaben
|
Bewahren Sie diese E-Mail gut auf: Wer den Code kennt, kann das Guthaben
|
||||||
einlösen. Eine Barauszahlung ist nicht möglich.
|
einlösen. Eine Barauszahlung ist nicht möglich.
|
||||||
</p>`);
|
</p>`);
|
||||||
@@ -652,7 +962,7 @@ export function gutscheinVersendetMail(g: GutscheinVersendet) {
|
|||||||
const hallo = g.kaeuferName ? `Hallo ${g.kaeuferName},` : "Hallo,";
|
const hallo = g.kaeuferName ? `Hallo ${g.kaeuferName},` : "Hallo,";
|
||||||
|
|
||||||
const inhalt = RAHMEN(`
|
const inhalt = RAHMEN(`
|
||||||
<h1 style="margin:0 0 4px;font-size:22px">Ihr Gutschein ist verschickt</h1>
|
<h1 style="${STIL.h1}">Ihr Gutschein ist verschickt</h1>
|
||||||
<p style="margin:24px 0 0">${html(hallo)}</p>
|
<p style="margin:24px 0 0">${html(hallo)}</p>
|
||||||
<p style="margin:12px 0 0">
|
<p style="margin:12px 0 0">
|
||||||
Ihre Zahlung ist eingegangen. Den Gutschein über ${betrag} haben wir eben
|
Ihre Zahlung ist eingegangen. Den Gutschein über ${betrag} haben wir eben
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { renderUrkundePdf } from "./urkunde";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liest aus einer Bestellung die Paten-Namen der Patenschafts-Posten.
|
||||||
|
* Jeder Posten einer Bienenpatenschaft trägt in den Metadaten
|
||||||
|
* `sponsorship_name` — den Namen, der auf die Urkunde soll (ob für einen
|
||||||
|
* selbst oder verschenkt, das Feld ist an der Kasse immer Pflicht).
|
||||||
|
*/
|
||||||
|
export async function findeSponsorPosten(
|
||||||
|
container: any,
|
||||||
|
orderId: string
|
||||||
|
): Promise<{ id: string; name: string }[]> {
|
||||||
|
const { data: orders } = await container.resolve("query").graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: ["id", "items.id", "items.metadata"],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order = orders?.[0];
|
||||||
|
if (!order) return [];
|
||||||
|
|
||||||
|
return (order.items ?? [])
|
||||||
|
.map((item: any) => ({
|
||||||
|
id: String(item?.id ?? ""),
|
||||||
|
name: String(item?.metadata?.sponsorship_name ?? "").trim(),
|
||||||
|
}))
|
||||||
|
.filter((p: any) => p.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /admin/orders/:id/urkunde — liefert die Patenschafts-Urkunde als PDF
|
||||||
|
// zum Ausdrucken. Der Name kommt aus der Bestellung; Nummer und Standort
|
||||||
|
// können über ?nummer= und ?standort= mitgegeben werden (sonst steht eine
|
||||||
|
// Linie zum Eintragen von Hand da). Mit ?name= lässt sich der Name überschreiben.
|
||||||
|
export async function handleUrkundeRequest(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
const posten = await findeSponsorPosten(req.scope, req.params.id);
|
||||||
|
const q = req.query as Record<string, string | undefined>;
|
||||||
|
|
||||||
|
const name = (q.name && q.name.trim()) || posten[0]?.name;
|
||||||
|
if (!name) {
|
||||||
|
res.status(404).json({ message: "Keine Patenschaft in dieser Bestellung gefunden." });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pdf = await renderUrkundePdf({
|
||||||
|
name,
|
||||||
|
nummer: q.nummer?.trim() || null,
|
||||||
|
standort: q.standort?.trim() || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const dateiName = `urkunde-${name.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase() || "patenschaft"}.pdf`;
|
||||||
|
res.setHeader("Content-Type", "application/pdf");
|
||||||
|
res.setHeader("Content-Disposition", `inline; filename="${dateiName}"`);
|
||||||
|
res.send(pdf);
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import PDFDocument from "pdfkit";
|
||||||
|
import path from "node:path";
|
||||||
|
import fs from "node:fs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Urkunde zur Bienenpatenschaft als PDF — im place4bees-Design (Hamburger
|
||||||
|
* Stadtimkerei), modern und zum Ausdrucken. Der Name des Paten wird aus der
|
||||||
|
* Bestellung übernommen; Nummer und Standort können mitgegeben oder leer
|
||||||
|
* gelassen werden (dann steht eine Linie zum Eintragen von Hand da).
|
||||||
|
*
|
||||||
|
* Gestaltung wie Website und Mails: Bebas Neue als Display-Schrift,
|
||||||
|
* Honiggelb #f8ac11, dunkle Tinte. Erzeugt mit pdfkit wie die Rechnung.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const LOGO_PATH = path.join(__dirname, "../assets/place4bees-logo.png");
|
||||||
|
const BEBAS_PATH = path.join(__dirname, "../assets/BebasNeue-Regular.ttf");
|
||||||
|
|
||||||
|
const C = {
|
||||||
|
honey: "#f8ac11",
|
||||||
|
honeyInk: "#8a5e05",
|
||||||
|
honeyTint: "#fdf3dc",
|
||||||
|
ink: "#212326",
|
||||||
|
text: "#5b6068",
|
||||||
|
muted: "#8b9099",
|
||||||
|
line: "#e3e5e9",
|
||||||
|
};
|
||||||
|
|
||||||
|
const COMPANY = {
|
||||||
|
name: "PLACE4BEES GmbH",
|
||||||
|
brand: "Hamburger Stadtimkerei",
|
||||||
|
addressLine: "Isestraße 109",
|
||||||
|
cityLine: "20149 Hamburg",
|
||||||
|
web: "www.place4bees.com",
|
||||||
|
email: "kontakt@place4bees.com",
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UrkundeDaten = {
|
||||||
|
name: string;
|
||||||
|
nummer?: string | null;
|
||||||
|
standort?: string | null;
|
||||||
|
datum?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
const PAGE_W = 595.28; // A4
|
||||||
|
const MARGIN = 56;
|
||||||
|
const INNER = PAGE_W - MARGIN * 2;
|
||||||
|
|
||||||
|
export function renderUrkundePdf(daten: UrkundeDaten): Promise<Buffer> {
|
||||||
|
// Unterer Rand klein, damit Fußzeile und Honigbalken nicht auf eine zweite
|
||||||
|
// Seite rutschen (pdfkit bricht sonst um, sobald Text unter den Rand geht).
|
||||||
|
const doc = new PDFDocument({ size: "A4", margins: { top: MARGIN, bottom: 24, left: MARGIN, right: MARGIN } });
|
||||||
|
|
||||||
|
const hatBebas = fs.existsSync(BEBAS_PATH);
|
||||||
|
if (hatBebas) doc.registerFont("Bebas", BEBAS_PATH);
|
||||||
|
const DISPLAY = hatBebas ? "Bebas" : "Helvetica-Bold";
|
||||||
|
|
||||||
|
const teile: Buffer[] = [];
|
||||||
|
const fertig = new Promise<Buffer>((resolve) => {
|
||||||
|
doc.on("data", (d: Buffer) => teile.push(d));
|
||||||
|
doc.on("end", () => resolve(Buffer.concat(teile)));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Rahmen: dünne Linie innen, oben und unten ein Honigbalken.
|
||||||
|
doc.save();
|
||||||
|
doc.rect(0, 0, PAGE_W, 10).fill(C.honey);
|
||||||
|
doc.rect(0, 831.89, PAGE_W, 10).fill(C.honey);
|
||||||
|
doc.lineWidth(0.8).strokeColor(C.line).rect(MARGIN - 18, MARGIN - 18, PAGE_W - (MARGIN - 18) * 2, 841.89 - (MARGIN - 18) * 2).stroke();
|
||||||
|
doc.restore();
|
||||||
|
|
||||||
|
// Logo zentriert.
|
||||||
|
const logoW = 150;
|
||||||
|
if (fs.existsSync(LOGO_PATH)) {
|
||||||
|
doc.image(LOGO_PATH, (PAGE_W - logoW) / 2, 64, { width: logoW });
|
||||||
|
}
|
||||||
|
|
||||||
|
let y = 212;
|
||||||
|
|
||||||
|
// Haupttitel.
|
||||||
|
doc.font(DISPLAY).fontSize(44).fillColor(C.ink);
|
||||||
|
doc.text("BIENENPATENSCHAFT", MARGIN, y, { width: INNER, align: "center", characterSpacing: 1 });
|
||||||
|
y += 54;
|
||||||
|
|
||||||
|
// Honig-Trennlinie mittig.
|
||||||
|
doc.save().lineWidth(2).strokeColor(C.honey)
|
||||||
|
.moveTo(PAGE_W / 2 - 40, y).lineTo(PAGE_W / 2 + 40, y).stroke().restore();
|
||||||
|
y += 24;
|
||||||
|
|
||||||
|
doc.font("Helvetica").fontSize(11).fillColor(C.honeyInk);
|
||||||
|
doc.text("URKUNDE ZUR BESTÄTIGUNG EINER PATENSCHAFT FÜR EIN BIENENVOLK", MARGIN, y, {
|
||||||
|
width: INNER, align: "center", characterSpacing: 0.5,
|
||||||
|
});
|
||||||
|
y += 46;
|
||||||
|
|
||||||
|
// "Für" + Name.
|
||||||
|
doc.font("Helvetica").fontSize(12).fillColor(C.text);
|
||||||
|
doc.text("Diese Urkunde wird ausgestellt für", MARGIN, y, { width: INNER, align: "center" });
|
||||||
|
y += 26;
|
||||||
|
|
||||||
|
doc.font(DISPLAY).fontSize(34).fillColor(C.honeyInk);
|
||||||
|
doc.text((daten.name || "—").toUpperCase(), MARGIN, y, { width: INNER, align: "center", characterSpacing: 1 });
|
||||||
|
y += 54;
|
||||||
|
|
||||||
|
// Bestätigungstext.
|
||||||
|
doc.font("Helvetica").fontSize(12).fillColor(C.text);
|
||||||
|
doc.text(
|
||||||
|
"Mit Ihrer Patenschaft übernehmen Sie Verantwortung für ein Bienenvolk unserer " +
|
||||||
|
"Hamburger Stadtimkerei und leisten einen wertvollen Beitrag zum Erhalt der Honigbiene " +
|
||||||
|
"und zur Bestäubung von Wild- und Nutzpflanzen. Ihr Engagement stärkt die Artenvielfalt " +
|
||||||
|
"mitten in der Stadt.",
|
||||||
|
MARGIN + 40, y,
|
||||||
|
{ width: INNER - 80, align: "center", lineGap: 3 }
|
||||||
|
);
|
||||||
|
y += 86;
|
||||||
|
|
||||||
|
// Angaben: Nummer & Standort in einem dezenten Kasten.
|
||||||
|
const boxH = 64;
|
||||||
|
doc.save().roundedRect(MARGIN + 40, y, INNER - 80, boxH, 8).fill(C.honeyTint).restore();
|
||||||
|
const feld = (label: string, wert: string | null | undefined, zeileY: number) => {
|
||||||
|
doc.font("Helvetica").fontSize(10).fillColor(C.honeyInk).text(label, MARGIN + 60, zeileY, { continued: false });
|
||||||
|
const wertX = MARGIN + 180;
|
||||||
|
const wertW = INNER - 80 - (180 - 40) - 20;
|
||||||
|
if (wert && wert.trim()) {
|
||||||
|
doc.font("Helvetica-Bold").fontSize(12).fillColor(C.ink).text(wert.trim(), wertX, zeileY - 1, { width: wertW });
|
||||||
|
} else {
|
||||||
|
doc.save().lineWidth(0.8).strokeColor(C.honey)
|
||||||
|
.moveTo(wertX, zeileY + 11).lineTo(wertX + wertW, zeileY + 11).stroke().restore();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
feld("Patenschaftsnummer", daten.nummer, y + 16);
|
||||||
|
feld("Standort des Volkes", daten.standort, y + 40);
|
||||||
|
y += boxH + 48;
|
||||||
|
|
||||||
|
// Unterschrift / Aussteller.
|
||||||
|
const sigW = 220;
|
||||||
|
const sigX = (PAGE_W - sigW) / 2;
|
||||||
|
doc.save().lineWidth(0.8).strokeColor(C.ink).moveTo(sigX, y).lineTo(sigX + sigW, y).stroke().restore();
|
||||||
|
y += 8;
|
||||||
|
doc.font(DISPLAY).fontSize(16).fillColor(C.ink)
|
||||||
|
.text("IHRE HAMBURGER STADTIMKEREI", MARGIN, y, { width: INNER, align: "center", characterSpacing: 0.5 });
|
||||||
|
y += 20;
|
||||||
|
const datum = (daten.datum ?? new Date()).toLocaleDateString("de-DE", { day: "2-digit", month: "long", year: "numeric" });
|
||||||
|
doc.font("Helvetica").fontSize(10).fillColor(C.muted)
|
||||||
|
.text(`${COMPANY.name} · Hamburg · ${datum}`, MARGIN, y, { width: INNER, align: "center" });
|
||||||
|
|
||||||
|
// Fußzeile.
|
||||||
|
doc.font("Helvetica").fontSize(9).fillColor(C.muted)
|
||||||
|
.text(`${COMPANY.name} · ${COMPANY.addressLine} · ${COMPANY.cityLine} · ${COMPANY.web} · ${COMPANY.email}`,
|
||||||
|
MARGIN, 795, { width: INNER, align: "center" });
|
||||||
|
|
||||||
|
doc.end();
|
||||||
|
return fertig;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import honigEssig from "../scripts/set-honig-essig";
|
||||||
|
|
||||||
|
/** Läuft einmal beim Deploy (medusa db:migrate). */
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await honigEssig({ container });
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import honigtexte from "../scripts/set-honigtexte";
|
||||||
|
|
||||||
|
/** Läuft einmal beim Deploy (medusa db:migrate). */
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await honigtexte({ container });
|
||||||
|
}
|
||||||
@@ -37,6 +37,17 @@ export default async function initial_data_seed({
|
|||||||
|
|
||||||
const countries = ["gb", "de", "dk", "se", "fr", "es", "it"];
|
const countries = ["gb", "de", "dk", "se", "fr", "es", "it"];
|
||||||
|
|
||||||
|
// Medusa merkt sich Migrationsskripte samt Dateiendung. Lokal ist dieses
|
||||||
|
// als .ts eingetragen, im gebauten Image heißt es .js und gilt dort als neu.
|
||||||
|
// Auf einem schon eingerichteten System würde es dann alles noch einmal
|
||||||
|
// anlegen und an den vorhandenen Regionen scheitern — nachdem es schon
|
||||||
|
// einen zweiten Verkaufskanal und API-Schlüssel erzeugt hat.
|
||||||
|
const { data: regionen } = await query.graph({ entity: "region", fields: ["id"] });
|
||||||
|
if (regionen.length) {
|
||||||
|
logger.info("Grunddaten schon vorhanden, nichts zu tun.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
logger.info("Seeding store data...");
|
logger.info("Seeding store data...");
|
||||||
const {
|
const {
|
||||||
result: [defaultSalesChannel],
|
result: [defaultSalesChannel],
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* Bringt die neuen Kerzen und den Honiglöffel auf jedes System.
|
||||||
|
*
|
||||||
|
* Medusa führt Dateien in diesem Ordner bei `medusa db:migrate` genau einmal
|
||||||
|
* aus — auf Test und Produktion erledigt das der migrate-Dienst beim
|
||||||
|
* Ausrollen. Die eigentliche Arbeit steht im Skript, das sich lokal auch von
|
||||||
|
* Hand wiederholen lässt.
|
||||||
|
*/
|
||||||
|
import kerzen from "../scripts/set-kerzenbilder";
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await kerzen({ container });
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import neueHonigbilder from "../scripts/set-neue-honigbilder";
|
||||||
|
|
||||||
|
/** Läuft einmal beim Deploy (medusa db:migrate), wie die Kerzenbilder. */
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await neueHonigbilder({ container });
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import shopFeinschliff from "../scripts/set-shop-feinschliff";
|
||||||
|
|
||||||
|
/** Läuft einmal beim Deploy (medusa db:migrate), wie die Honigbilder. */
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await shopFeinschliff({ container });
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { kategorienSortieren } from "../scripts/set-shop-feinschliff";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reihenfolge der Kategorien noch einmal setzen: Auf dem Testsystem lief
|
||||||
|
* shop-feinschliff mit der älteren Reihenfolge (Kerzen vor den Lebensmitteln).
|
||||||
|
*/
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await kategorienSortieren(container);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import snackbilder from "../scripts/set-snackbilder";
|
||||||
|
|
||||||
|
/** Läuft einmal beim Deploy (medusa db:migrate). */
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await snackbilder({ container });
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import snacksTexte from "../scripts/set-snacks-texte";
|
||||||
|
|
||||||
|
/** Läuft einmal beim Deploy (medusa db:migrate). */
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await snacksTexte({ container });
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import texteNachtrag from "../scripts/set-texte-nachtrag";
|
||||||
|
|
||||||
|
/** Läuft einmal beim Deploy (medusa db:migrate). */
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
await texteNachtrag({ container });
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Module } from "@medusajs/framework/utils";
|
||||||
|
import B2bModuleService from "./service";
|
||||||
|
|
||||||
|
export const B2B_MODULE = "b2b";
|
||||||
|
|
||||||
|
export default Module(B2B_MODULE, {
|
||||||
|
service: B2bModuleService,
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { AbstractNotificationProviderService, MedusaError } from "@medusajs/framework/utils";
|
import { AbstractNotificationProviderService, MedusaError } from "@medusajs/framework/utils";
|
||||||
import type { ProviderSendNotificationDTO } from "@medusajs/framework/types";
|
import type { ProviderSendNotificationDTO } from "@medusajs/framework/types";
|
||||||
import nodemailer, { type Transporter } from "nodemailer";
|
import nodemailer, { type Transporter } from "nodemailer";
|
||||||
|
import { MAIL_LOGO_CID, MAIL_LOGO_PNG_BASE64 } from "../../lib/mail-logo";
|
||||||
|
|
||||||
type Options = {
|
type Options = {
|
||||||
host: string;
|
host: string;
|
||||||
@@ -79,11 +80,25 @@ class EmailNotificationService extends AbstractNotificationProviderService {
|
|||||||
subject: umgeleitet ? `[TEST an ${notification.to}] ${content.subject}` : content.subject,
|
subject: umgeleitet ? `[TEST an ${notification.to}] ${content.subject}` : content.subject,
|
||||||
text: content.text,
|
text: content.text,
|
||||||
html: content.html,
|
html: content.html,
|
||||||
attachments: (notification.attachments ?? []).map((anhang: any) => ({
|
attachments: [
|
||||||
filename: anhang.filename,
|
...(notification.attachments ?? []).map((anhang: any) => ({
|
||||||
content: Buffer.from(anhang.content, "base64"),
|
filename: anhang.filename,
|
||||||
contentType: anhang.content_type,
|
content: Buffer.from(anhang.content, "base64"),
|
||||||
})),
|
contentType: anhang.content_type,
|
||||||
|
})),
|
||||||
|
// Der Rahmen aller Mails verweist auf das Logo per CID. Hier
|
||||||
|
// angehängt, damit nicht jeder Subscriber daran denken muss.
|
||||||
|
...(content.html?.includes(`cid:${MAIL_LOGO_CID}`)
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
filename: "place4bees.png",
|
||||||
|
content: Buffer.from(MAIL_LOGO_PNG_BASE64, "base64"),
|
||||||
|
contentType: "image/png",
|
||||||
|
cid: MAIL_LOGO_CID,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
this.logger_.info(
|
this.logger_.info(
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
||||||
|
import { LocalFileService } from "@medusajs/file-local";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lokale Dateiablage mit Adressen ohne Domain (/static/…).
|
||||||
|
*
|
||||||
|
* Der Standardanbieter baut die Adresse mit `new URL(backend_url)` und
|
||||||
|
* scheitert an einem relativen Pfad mit "Invalid URL" — jeder Upload brach
|
||||||
|
* ab, auch Produktbilder im Admin. Hier entsteht die Adresse ohne URL-Objekt;
|
||||||
|
* alles andere bleibt beim Original.
|
||||||
|
*/
|
||||||
|
class RelativeLocalFileService extends LocalFileService {
|
||||||
|
static identifier = "localfs-relative";
|
||||||
|
|
||||||
|
constructor(deps: any, options: any) {
|
||||||
|
super(deps, options);
|
||||||
|
const basis = String(options?.backend_url ?? "/static").replace(/\/+$/, "");
|
||||||
|
(this as any).getUploadFileUrl = (fileKey: string) =>
|
||||||
|
`${basis}/${fileKey.split("/").map(encodeURIComponent).join("/")}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ModuleProvider(Modules.FILE, {
|
||||||
|
services: [RelativeLocalFileService],
|
||||||
|
});
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import {
|
||||||
|
createProductVariantsWorkflow,
|
||||||
|
deleteProductVariantsWorkflow,
|
||||||
|
updateProductOptionsWorkflow,
|
||||||
|
updateProductsWorkflow,
|
||||||
|
updateProductVariantsWorkflow,
|
||||||
|
} from "@medusajs/core-flows";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lücken gegenüber der Preisliste 9/2026 schließen.
|
||||||
|
*
|
||||||
|
* - Sonnenblumenhonig steht dort auch mit 50 g (2,80 €), im Shop gab es nur
|
||||||
|
* 250 g.
|
||||||
|
* - Versandgewichte, die fehlten: Buchweizenhonig und Honig-Abo. Es sind
|
||||||
|
* dieselben Gläser wie bei allen anderen Honigen, also dieselben
|
||||||
|
* Bruttogewichte (50 g → 100 g, 250 g → 400 g, 500 g → 700 g).
|
||||||
|
*
|
||||||
|
* - Schnupperkurs: Der einzige Termin (25.04.2026) war vorbei und
|
||||||
|
* ausgebucht, ließ sich aber noch buchen. Er fliegt raus, buchbar bleibt
|
||||||
|
* der Kurs-Gutschein.
|
||||||
|
* - Alte Honigseife: eigener Name neben der neuen Honig-Seife, dazu die
|
||||||
|
* Sorte Lavendel, die in der Beschreibung stand, aber fehlte.
|
||||||
|
*
|
||||||
|
* Mehrfach ausführbar: legt nichts doppelt an, setzt dieselben Werte.
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/ergaenzungen-2026.ts
|
||||||
|
*/
|
||||||
|
|
||||||
|
const BRUTTO: Record<string, number> = { "50 Gramm": 100, "250 Gramm": 400, "500 Gramm": 700 };
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
const query = container.resolve("query");
|
||||||
|
|
||||||
|
const { data: produkte } = await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"handle",
|
||||||
|
"options.id",
|
||||||
|
"options.title",
|
||||||
|
"options.values.id",
|
||||||
|
"options.values.value",
|
||||||
|
"variants.id",
|
||||||
|
"variants.title",
|
||||||
|
"variants.weight",
|
||||||
|
"variants.metadata",
|
||||||
|
"description",
|
||||||
|
],
|
||||||
|
filters: {
|
||||||
|
handle: [
|
||||||
|
"sonnenblumenhonig-aus-der-harzregion",
|
||||||
|
"buchweizenhonig-aus-der-oder-spree-region",
|
||||||
|
"honig-abo",
|
||||||
|
"schnupperkurs",
|
||||||
|
"seife-aus-unserem-honig",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const nach = new Map(produkte.map((p: any) => [p.handle, p]));
|
||||||
|
|
||||||
|
// --- Sonnenblumenhonig 50 g ---------------------------------------------
|
||||||
|
const sonne: any = nach.get("sonnenblumenhonig-aus-der-harzregion");
|
||||||
|
if (!sonne) {
|
||||||
|
logger.warn("[ergaenzung] Sonnenblumenhonig nicht gefunden.");
|
||||||
|
} else if (sonne.variants.some((v: any) => v.title === "50 Gramm")) {
|
||||||
|
logger.info("[ergaenzung] Sonnenblumenhonig 50 g gibt es schon.");
|
||||||
|
} else {
|
||||||
|
const option = sonne.options[0];
|
||||||
|
const werte = option.values.map((v: any) => v.value);
|
||||||
|
if (!werte.includes("50 Gramm")) {
|
||||||
|
await updateProductOptionsWorkflow(container).run({
|
||||||
|
input: { selector: { id: option.id }, update: { values: ["50 Gramm", ...werte] } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await createProductVariantsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
product_variants: [
|
||||||
|
{
|
||||||
|
product_id: sonne.id,
|
||||||
|
title: "50 Gramm",
|
||||||
|
options: { [option.title]: "50 Gramm" },
|
||||||
|
prices: [{ amount: 2.8, currency_code: "eur" }],
|
||||||
|
weight: BRUTTO["50 Gramm"],
|
||||||
|
manage_inventory: false,
|
||||||
|
metadata: { net_weight_grams: 50 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
logger.info("[ergaenzung] Sonnenblumenhonig 50 g angelegt (2,80 €).");
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Fehlende Versandgewichte -------------------------------------------
|
||||||
|
for (const handle of ["buchweizenhonig-aus-der-oder-spree-region", "honig-abo"]) {
|
||||||
|
const produkt: any = nach.get(handle);
|
||||||
|
for (const variante of produkt?.variants ?? []) {
|
||||||
|
// Beim Abo heißt die Variante "250 Gramm / Monatlich".
|
||||||
|
const groesse = Object.keys(BRUTTO).find((g) => variante.title.startsWith(g));
|
||||||
|
if (!groesse || variante.weight) continue;
|
||||||
|
await updateProductVariantsWorkflow(container).run({
|
||||||
|
input: { selector: { id: variante.id }, update: { weight: BRUTTO[groesse] } },
|
||||||
|
});
|
||||||
|
logger.info(`[ergaenzung] ${handle} / ${variante.title}: ${BRUTTO[groesse]} g`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Schnupperkurs: abgelaufenen Termin entfernen -------------------------
|
||||||
|
const kurs: any = nach.get("schnupperkurs");
|
||||||
|
const alterTermin = kurs?.variants.find((v: any) => v.title.startsWith("25.04.2026"));
|
||||||
|
if (alterTermin) {
|
||||||
|
await deleteProductVariantsWorkflow(container).run({ input: { ids: [alterTermin.id] } });
|
||||||
|
logger.info("[ergaenzung] Schnupperkurs: Termin 25.04.2026 entfernt.");
|
||||||
|
}
|
||||||
|
// Steht über mehrere Zeilen verteilt in der Beschreibung.
|
||||||
|
const alterText = /Termine:\s*Samstag 25\.04\.2026[^\n]*?ausgebucht/;
|
||||||
|
if (kurs?.description && alterText.test(kurs.description)) {
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
selector: { id: kurs.id },
|
||||||
|
update: { description: kurs.description.replace(alterText, "Termine: Neue Termine folgen in Kürze.") },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
logger.info("[ergaenzung] Schnupperkurs: Beschreibung ohne alten Termin.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Alte Honigseife: Name und Sorte Lavendel ---------------------------
|
||||||
|
const seife: any = nach.get("seife-aus-unserem-honig");
|
||||||
|
if (seife) {
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: { selector: { id: seife.id }, update: { title: "Honigseife Lavendel, Gelee Royal & Propolis" } },
|
||||||
|
});
|
||||||
|
if (!seife.variants.some((v: any) => v.title.startsWith("Lavendel"))) {
|
||||||
|
// Die Option ist "exklusiv" (Medusa 2.16+): Ein Wert muss zusätzlich
|
||||||
|
// mit dem Produkt verknüpft sein, sonst lehnt Medusa die Variante ab.
|
||||||
|
const option = seife.options[0];
|
||||||
|
const vorhanden = option.values.find((v: any) => v.value === "Lavendel");
|
||||||
|
await container.resolve(Modules.PRODUCT).updateProductOptionValuesOnProduct({
|
||||||
|
product_id: seife.id,
|
||||||
|
product_option_id: option.id,
|
||||||
|
add: [vorhanden ? vorhanden.id : { value: "Lavendel" }],
|
||||||
|
});
|
||||||
|
await createProductVariantsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
product_variants: [
|
||||||
|
{
|
||||||
|
product_id: seife.id,
|
||||||
|
title: "Lavendel",
|
||||||
|
options: { [option.title]: "Lavendel" },
|
||||||
|
prices: [{ amount: 3.5, currency_code: "eur" }],
|
||||||
|
weight: 100,
|
||||||
|
manage_inventory: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
logger.info("[ergaenzung] Honigseife: Sorte Lavendel angelegt (3,50 €).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
/**
|
||||||
|
* Alle Mails, die der Shop verschicken kann (18), mit Beispieldaten — um nach
|
||||||
|
* einer Änderung an Text oder Gestaltung alles auf einmal anzusehen.
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/mail-muster.ts
|
||||||
|
* schreibt HTML-Vorschauen nach VORSCHAU_DIR (Standard: Temp-Ordner)
|
||||||
|
* SENDEN=1 MUSTER_AN=shop@place4bees.com npx medusa exec ./src/scripts/mail-muster.ts
|
||||||
|
* verschickt alle Muster an diese Adresse
|
||||||
|
*
|
||||||
|
* Die Rechnung als PDF-Anhang fehlt in den Mustern, sie hängt an einer
|
||||||
|
* echten Bestellung.
|
||||||
|
*/
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import * as os from "os";
|
||||||
|
import * as path from "path";
|
||||||
|
import {
|
||||||
|
bestellbestaetigung,
|
||||||
|
versandnachricht,
|
||||||
|
geschenkAnkuendigung,
|
||||||
|
geschenkVersandnachricht,
|
||||||
|
patenschaftAnkuendigung,
|
||||||
|
gutscheinMail,
|
||||||
|
gutscheinVersendetMail,
|
||||||
|
kuendigungsbestaetigung,
|
||||||
|
emailBestaetigenMail,
|
||||||
|
passwortZuruecksetzenMail,
|
||||||
|
stornoMail,
|
||||||
|
erstattungMail,
|
||||||
|
aboZahlungFehlgeschlagenMail,
|
||||||
|
} from "../lib/order-emails";
|
||||||
|
import { anfrageMail } from "../lib/contact-email";
|
||||||
|
import { MAIL_LOGO_PNG_BASE64 } from "../lib/mail-logo";
|
||||||
|
|
||||||
|
const adresse = {
|
||||||
|
first_name: "Erika",
|
||||||
|
last_name: "Mustermann",
|
||||||
|
address_1: "Musterstraße 12",
|
||||||
|
postal_code: "20095",
|
||||||
|
city: "Hamburg",
|
||||||
|
country_code: "de",
|
||||||
|
};
|
||||||
|
const basis = {
|
||||||
|
display_id: 1042,
|
||||||
|
email: "erika@example.com",
|
||||||
|
created_at: new Date(),
|
||||||
|
currency_code: "eur",
|
||||||
|
shipping_address: adresse,
|
||||||
|
shipping_methods: [{ name: "DHL Paket", amount: 5.49 }],
|
||||||
|
};
|
||||||
|
const sendung = [{ tracking_number: "00340434333010200291286", tracking_url: "https://www.dhl.de/de/privatkunden/pakete-empfangen/verfolgen.html" }];
|
||||||
|
|
||||||
|
const muster: [string, { subject: string; html: string; text: string }][] = [
|
||||||
|
["Bestellbestätigung", bestellbestaetigung({
|
||||||
|
...basis,
|
||||||
|
items: [
|
||||||
|
{ title: "Lindenhonig aus Hamburg – cremig, 250 g", quantity: 2, unit_price: 6.9 },
|
||||||
|
{ title: "Bienenpatenschaft", quantity: 1, unit_price: 49, hinweis: "Urkunde und Etikett auf: Familie Mustermann" },
|
||||||
|
],
|
||||||
|
gutscheine: [{ code: "P4B-…-7K2Q", betrag: 10 }],
|
||||||
|
})],
|
||||||
|
["Bestellbestätigung Abo-Lieferung", bestellbestaetigung({
|
||||||
|
...basis,
|
||||||
|
aus_abo: true,
|
||||||
|
items: [{ title: "Frühlingsblütenhonig aus Hamburg – cremig, 250 g", quantity: 1, unit_price: 6.9 }],
|
||||||
|
})],
|
||||||
|
["Bestellbestätigung nur Gutschein", bestellbestaetigung({
|
||||||
|
...basis,
|
||||||
|
shipping_methods: [],
|
||||||
|
items: [{ title: "Geschenkgutschein 25 €", quantity: 1, unit_price: 25, digital: true }],
|
||||||
|
})],
|
||||||
|
["Versandnachricht", versandnachricht(
|
||||||
|
{ ...basis, items: [{ title: "Lindenhonig aus Hamburg – cremig, 250 g", quantity: 2, unit_price: 6.9 }] },
|
||||||
|
sendung
|
||||||
|
)],
|
||||||
|
["Geschenk-Abo: Ankündigung an Beschenkte", geschenkAnkuendigung({
|
||||||
|
empfaengerName: "Max Beispiel", schenkerName: "Erika", lieferungen: 6, rhythmus: "monatlich", groesse: "250 Gramm",
|
||||||
|
})],
|
||||||
|
["Geschenk-Abo: Versandnachricht an Beschenkte", geschenkVersandnachricht(
|
||||||
|
"Max Beispiel",
|
||||||
|
[{ title: "Heidehonig aus der Lüneburger Heide, 250 g", quantity: 1, unit_price: 0 }],
|
||||||
|
sendung,
|
||||||
|
4
|
||||||
|
)],
|
||||||
|
["Patenschaft: Ankündigung", patenschaftAnkuendigung({ name: "Familie Mustermann", schenkerName: "Erika" })],
|
||||||
|
["Gutschein (für sich selbst)", gutscheinMail({
|
||||||
|
code: "P4B-ABCD-EFGH-7K2Q", betrag: 25, waehrung: "eur", empfaengerName: "Erika Mustermann",
|
||||||
|
schenkerName: null, nachricht: null, geschenk: false,
|
||||||
|
})],
|
||||||
|
["Gutschein (als Geschenk)", gutscheinMail({
|
||||||
|
code: "P4B-WXYZ-1234-9M3P", betrag: 50, waehrung: "eur", empfaengerName: "Max Beispiel",
|
||||||
|
schenkerName: "Erika", nachricht: "Alles Gute zum Geburtstag!\nLass es dir schmecken.", geschenk: true,
|
||||||
|
})],
|
||||||
|
["Gutschein verschickt (an Käuferin)", gutscheinVersendetMail({
|
||||||
|
code: "P4B-WXYZ-1234-9M3P", betrag: 50, waehrung: "eur", empfaengerEmail: "max@example.com",
|
||||||
|
empfaengerName: "Max Beispiel", kaeuferName: "Erika Mustermann",
|
||||||
|
})],
|
||||||
|
["Kündigungsbestätigung", kuendigungsbestaetigung({
|
||||||
|
aboId: "sub_01M5VQ7H8DG80ZTY4CF08ECTDM", art: "Ordentliche Kündigung", eingegangen: new Date(),
|
||||||
|
rhythmus: "monatlich", groesse: "250 Gramm", name: "Erika Mustermann", grund: "Zu viel Honig im Schrank",
|
||||||
|
})],
|
||||||
|
["E-Mail bestätigen", emailBestaetigenMail("https://place4bees.com/konto/bestaetigen?code=MUSTER")],
|
||||||
|
["Passwort zurücksetzen", passwortZuruecksetzenMail("https://place4bees.com/konto/passwort-neu?token=MUSTER")],
|
||||||
|
["Storno", stornoMail({ display_id: 1042, shipping_address: adresse, erstattet: 58.29, waehrung: "eur" })],
|
||||||
|
["Erstattung", erstattungMail({ display_id: 1042, shipping_address: adresse, betrag: 6.9, waehrung: "eur" })],
|
||||||
|
["Abo: Abbuchung fehlgeschlagen", aboZahlungFehlgeschlagenMail({
|
||||||
|
shipping_address: adresse, beschreibung: "250 Gramm, monatlich", pausiert: false,
|
||||||
|
kontoLink: "https://place4bees.com/konto/abos",
|
||||||
|
})],
|
||||||
|
["Abo: pausiert nach Fehlversuchen", aboZahlungFehlgeschlagenMail({
|
||||||
|
shipping_address: adresse, beschreibung: "250 Gramm, monatlich", pausiert: true,
|
||||||
|
kontoLink: "https://place4bees.com/konto/abos",
|
||||||
|
})],
|
||||||
|
["Kontaktanfrage (intern)", anfrageMail({
|
||||||
|
name: "Erika Mustermann", email: "erika@example.com", quelle: "Ihr Projekt", seite: "/business/kontakt",
|
||||||
|
nachricht: "Hallo,\nwir würden gern zwei Bienenvölker auf unserem Firmendach aufstellen. Wie läuft das ab?\n\nViele Grüße",
|
||||||
|
})],
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
const senden = process.env.SENDEN === "1";
|
||||||
|
const an = process.env.MUSTER_AN ?? "shop@place4bees.com";
|
||||||
|
const dir = process.env.VORSCHAU_DIR ?? path.join(os.tmpdir(), "mail-muster");
|
||||||
|
if (!senden) fs.mkdirSync(dir, { recursive: true });
|
||||||
|
|
||||||
|
for (const [i, [name, mail]] of muster.entries()) {
|
||||||
|
const nr = String(i + 1).padStart(2, "0");
|
||||||
|
if (!senden) {
|
||||||
|
// In der Vorschau das Logo direkt einbetten, das CID gibt es nur in der Mail.
|
||||||
|
const vorschau = mail.html.replace("cid:p4b-logo", `data:image/png;base64,${MAIL_LOGO_PNG_BASE64}`);
|
||||||
|
fs.writeFileSync(path.join(dir, `${nr}.html`), vorschau);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await container.resolve(Modules.NOTIFICATION).createNotifications({
|
||||||
|
to: an,
|
||||||
|
channel: "email",
|
||||||
|
template: `muster-${nr}`,
|
||||||
|
content: { ...mail, subject: `[Muster ${nr}/${muster.length}] ${name} — ${mail.subject}` },
|
||||||
|
});
|
||||||
|
logger.info(`MUSTER ${nr} verschickt: ${name}`);
|
||||||
|
}
|
||||||
|
if (!senden) {
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(dir, "index.html"),
|
||||||
|
`<meta charset="utf-8"><body style="font-family:sans-serif;padding:20px">` +
|
||||||
|
muster.map(([name], i) => `<p><a href="${String(i + 1).padStart(2, "0")}.html">${i + 1}. ${name}</a></p>`).join("")
|
||||||
|
);
|
||||||
|
console.log(`VORSCHAU ${muster.length} Mails in ${dir}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Neue Produkttexte für Snacks, Balsamico und Seife (Etiketten 2026).
|
||||||
|
*
|
||||||
|
* Titel, Claim (subtitle) und die kleine Zeile über dem Titel
|
||||||
|
* (metadata.label). Die Beschreibungen der Snacks bleiben unangetastet —
|
||||||
|
* dort stehen Zutaten und Nährwerte, die für Lebensmittel Pflicht sind.
|
||||||
|
*
|
||||||
|
* Mehrfach ausführbar: setzt jedes Mal dieselben Werte.
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/produkttexte-2026.ts
|
||||||
|
*/
|
||||||
|
|
||||||
|
const SNACK = "Honig. Aber Anders.";
|
||||||
|
|
||||||
|
const BALSAMICO = `Essigspezialität verfeinert mit 50 % Hamburger Stadthonig.
|
||||||
|
|
||||||
|
Zu Beginn wird der Honig zusammen mit lebendigem Wasser und gentechnikfreier Hefe vergoren. Im Anschluss fermentiert der entstandene Honigwein über mehrere Monate zu feinstem Honigessig. Heraus kommt ein traditioneller Gärungsessig, fruchtig-spritzig im Aroma mit einer dezenten Honignote.
|
||||||
|
|
||||||
|
Unsere Empfehlung:
|
||||||
|
• zum Verfeinern von Vinaigrette und Dressing
|
||||||
|
• zum Marinieren von Fisch und Fleisch vor dem Grillen oder Schmoren
|
||||||
|
• zum Marinieren von Gemüse nach dem Garen
|
||||||
|
|
||||||
|
Inhalt: 250 ml`;
|
||||||
|
|
||||||
|
const SEIFE = `Sanfte Pflege mit Hamburger Stadthonig.
|
||||||
|
|
||||||
|
Pflegeseife mit Milch und Honig aus unserer Imkerei. Honig spendet Feuchtigkeit, Milch macht den Schaum weich und mild — angenehm für trockene Haut und für jeden Tag.`;
|
||||||
|
|
||||||
|
const TEXTE: { handle: string; title: string; subtitle: string; label?: string; description?: string }[] = [
|
||||||
|
{ handle: "honig-lakritze", title: "Honig-Lakritz", subtitle: "Lakritz trifft Honig.", label: SNACK },
|
||||||
|
{ handle: "honig-bonbons", title: "Honig-Bonbons", subtitle: "Honig für unterwegs.", label: SNACK },
|
||||||
|
{ handle: "gummibarchen", title: "Honig-Doppelbärchen", subtitle: "Bärenstark mit Honig.", label: SNACK },
|
||||||
|
{ handle: "honigwaffeln", title: "Honig-Waffeln", subtitle: "Kleine Honigpause.", label: SNACK },
|
||||||
|
{ handle: "balsamico-essig", title: "Honig-Balsamico", subtitle: "Süße trifft Säure.", description: BALSAMICO },
|
||||||
|
{ handle: "pflegeseife-milch-honig", title: "Honig-Seife", subtitle: "Ein Stück Honigliebe.", description: SEIFE },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
const query = container.resolve("query");
|
||||||
|
|
||||||
|
const { data: produkte } = await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: ["id", "handle", "metadata"],
|
||||||
|
filters: { handle: TEXTE.map((t) => t.handle) },
|
||||||
|
});
|
||||||
|
const nachHandle = new Map(produkte.map((p: any) => [p.handle, p]));
|
||||||
|
|
||||||
|
for (const text of TEXTE) {
|
||||||
|
const produkt: any = nachHandle.get(text.handle);
|
||||||
|
if (!produkt) {
|
||||||
|
logger.warn(`[texte] ${text.handle} nicht gefunden — übersprungen.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
selector: { id: produkt.id },
|
||||||
|
update: {
|
||||||
|
title: text.title,
|
||||||
|
subtitle: text.subtitle,
|
||||||
|
...(text.description ? { description: text.description } : {}),
|
||||||
|
metadata: { ...(produkt.metadata ?? {}), ...(text.label ? { label: text.label } : {}) },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
logger.info(`[texte] ${text.handle}: „${text.title}“ — ${text.subtitle}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
/**
|
||||||
|
* Honig-Balsamico-Essig, 0,25 l, in der Kategorie "Feinkost".
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/set-honig-essig.ts
|
||||||
|
*
|
||||||
|
* Vorerst ohne Bild, Preis 12,90 €. Texte, Zutaten und Nährwerte vom
|
||||||
|
* Team, die Beschreibung vom Etikett.
|
||||||
|
* Der Grundpreis kommt über `net_volume_ml` und steht dann je Liter.
|
||||||
|
*
|
||||||
|
* Das Versandgewicht (550 g) ist geschätzt — Flasche plus Inhalt. Im Admin
|
||||||
|
* unter Variante → Gewicht korrigieren, sobald gewogen.
|
||||||
|
*
|
||||||
|
* Wiederholbar: legt nur an, was fehlt, und setzt sonst die Zielwerte.
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
createProductCategoriesWorkflow,
|
||||||
|
createProductsWorkflow,
|
||||||
|
updateProductsWorkflow,
|
||||||
|
updateProductVariantsWorkflow,
|
||||||
|
} from "@medusajs/core-flows";
|
||||||
|
|
||||||
|
const HANDLE = "honig-balsamico-essig";
|
||||||
|
const TITEL = "Honig-Balsamico-Essig";
|
||||||
|
const KATEGORIE = { name: "Feinkost", handle: "feinkost" };
|
||||||
|
const PREIS = 12.9;
|
||||||
|
const VARIANTE = {
|
||||||
|
title: "0,25 l",
|
||||||
|
weight: 550,
|
||||||
|
metadata: { net_volume_ml: 250 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const BESCHREIBUNG = [
|
||||||
|
"Zu Beginn wird der Honig zusammen mit lebendigem Wasser und gentechnikfreier Hefe vergoren. Im Anschluss fermentiert der entstandene Honigwein über mehrere Monate zu feinstem Honigessig. Heraus kommt ein traditioneller Gärungsessig, fruchtig-spritzig im Aroma mit einer dezenten Honignote.",
|
||||||
|
"Genussempfehlung: Zum Verfeinern von Vinaigrette und Dressing, zum Marinieren von Fisch und Fleisch vor dem Grillen oder Schmoren oder zum Marinieren von Gemüse nach dem Garen.",
|
||||||
|
"Zutaten: Honig 50 %, Honig-Gärungsessig (Wasser, Honig).",
|
||||||
|
"Essigzubereitung, enthält 2,9 % Säure. Inhalt: 0,25 l.",
|
||||||
|
"Ablagerungen sind möglich, da Naturprodukt. Bitte kühl und dunkel lagern.",
|
||||||
|
"Nährwerte je 100 ml: Brennwert 807 kJ / 193 kcal · Kohlenhydrate 46,0 g, davon Zucker 46,0 g. Enthält geringfügige Mengen an Fett, gesättigten Fettsäuren, Eiweiß und Salz.",
|
||||||
|
].join("\n\n");
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
let { data: kategorien } = await query.graph({
|
||||||
|
entity: "product_category",
|
||||||
|
fields: ["id", "handle", "rank"],
|
||||||
|
filters: { handle: KATEGORIE.handle },
|
||||||
|
});
|
||||||
|
if (!kategorien?.[0]) {
|
||||||
|
const { result } = await createProductCategoriesWorkflow(container).run({
|
||||||
|
input: { product_categories: [{ ...KATEGORIE, is_active: true }] },
|
||||||
|
});
|
||||||
|
kategorien = result as any;
|
||||||
|
logger.info(`Kategorie "${KATEGORIE.name}" angelegt.`);
|
||||||
|
}
|
||||||
|
const kategorieId = kategorien[0].id;
|
||||||
|
|
||||||
|
const lesen = async () =>
|
||||||
|
(
|
||||||
|
await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: ["id", "metadata", "variants.id"],
|
||||||
|
filters: { handle: HANDLE },
|
||||||
|
})
|
||||||
|
).data?.[0];
|
||||||
|
|
||||||
|
let produkt = await lesen();
|
||||||
|
if (!produkt) {
|
||||||
|
// Jeweils der älteste, wie in set-kerzenbilder.ts.
|
||||||
|
const { data: profile } = await query.graph({
|
||||||
|
entity: "shipping_profile",
|
||||||
|
fields: ["id"],
|
||||||
|
pagination: { order: { created_at: "ASC" } },
|
||||||
|
});
|
||||||
|
const { data: kanaele } = await query.graph({
|
||||||
|
entity: "sales_channel",
|
||||||
|
fields: ["id"],
|
||||||
|
pagination: { order: { created_at: "ASC" } },
|
||||||
|
});
|
||||||
|
await createProductsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
products: [
|
||||||
|
{
|
||||||
|
title: TITEL,
|
||||||
|
handle: HANDLE,
|
||||||
|
status: "published" as any,
|
||||||
|
description: BESCHREIBUNG,
|
||||||
|
shipping_profile_id: profile?.[0]?.id,
|
||||||
|
sales_channels: kanaele?.[0] ? [{ id: kanaele[0].id }] : undefined,
|
||||||
|
category_ids: [kategorieId],
|
||||||
|
metadata: { category: KATEGORIE.name, delivery_time: "2-3 Werktage" },
|
||||||
|
options: [{ title: "Inhalt", values: [VARIANTE.title] }],
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
...VARIANTE,
|
||||||
|
options: { Inhalt: VARIANTE.title },
|
||||||
|
manage_inventory: false,
|
||||||
|
prices: [{ amount: PREIS, currency_code: "eur" }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} as any,
|
||||||
|
});
|
||||||
|
logger.info(`"${TITEL}" angelegt.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
selector: { id: produkt.id },
|
||||||
|
update: {
|
||||||
|
title: TITEL,
|
||||||
|
description: BESCHREIBUNG,
|
||||||
|
category_ids: [kategorieId],
|
||||||
|
metadata: { ...(produkt.metadata ?? {}), category: KATEGORIE.name },
|
||||||
|
},
|
||||||
|
} as any,
|
||||||
|
});
|
||||||
|
for (const v of produkt.variants ?? []) {
|
||||||
|
await updateProductVariantsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
selector: { id: v.id },
|
||||||
|
update: { ...VARIANTE, prices: [{ amount: PREIS, currency_code: "eur" }] },
|
||||||
|
} as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
logger.info(`"${TITEL}" aktualisiert.`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
/**
|
||||||
|
* Neue Beschreibungen für die Honigsorten (Texte vom Team, November 2026).
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/set-honigtexte.ts
|
||||||
|
*
|
||||||
|
* Gefunden wird über ein Stichwort im Titel, nicht über den Handle: einige
|
||||||
|
* Handles stammen aus kopierten Produkten und passen nicht zur Sorte
|
||||||
|
* (der Kornblumenhonig heißt dort "heidehonig-…-kopie").
|
||||||
|
*
|
||||||
|
* Buchweizenhonig und das Probierset bleiben, wie sie sind.
|
||||||
|
* Wiederholbar: setzt nur Zielwerte.
|
||||||
|
*/
|
||||||
|
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||||
|
|
||||||
|
const TEXTE: { stichwort: string; text: string }[] = [
|
||||||
|
{
|
||||||
|
stichwort: "presshonig",
|
||||||
|
text: "Traditionelles Handwerk im Glas: Unser Traditionshonig wird durch das Pressen der Honigwaben gewonnen. Diese ursprüngliche Art der Honigernte macht ihn zu einer besonderen Entdeckung für Honigliebhaber – zum puren Genießen oder auf einer frischen Scheibe Brot.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "waldhonig",
|
||||||
|
text: "Dunkel, kräftig und malzig-würzig: Waldhonig verdankt seinen besonderen Charakter vor allem dem Honigtau der Bäume. Seine intensive Aromatik passt wunderbar zu rustikalem Brot, kräftigem Käse und herzhaften Dressings.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "kornblumenhonig",
|
||||||
|
text: "Kleine blaue Blüte, ausdrucksstarker Honig: Kornblumenhonig überrascht mit einem kräftigen, blumig-würzigen Aroma und einer leicht herben Note. Für alle, die gern neue Honigsorten entdecken – besonders lecker auf kräftigem Brot oder zu Käse.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "himbeerblütenhonig",
|
||||||
|
text: "Die Himbeere kann mehr als süße Früchte: Aus dem Nektar ihrer Blüten entsteht ein feiner Honig mit blumigem Aroma und zartfruchtigen Nuancen. Eine besondere Sorte für dein Frühstück – köstlich zu Naturjoghurt, frischen Beeren oder auf einem warmen Croissant.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "heidehonig",
|
||||||
|
text: "Kräftig, würzig und mit einer feinherben Note: Heidehonig ist ein Genuss für alle, die ausdrucksstarke Aromen lieben. Sein intensiver Geschmack passt besonders gut zu dunklem Brot, gereiftem Käse oder als besondere Zutat in der Küche.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "rapshonig",
|
||||||
|
text: "Hell, mild und angenehm sanft: Rapshonig ist ein Klassiker für alle, die einen dezenten Honiggeschmack mögen. Seine zurückhaltende Süße passt wunderbar auf frisches Brot und lässt auch im Quark oder Müsli den anderen Zutaten Raum.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "sonnenblumenhonig",
|
||||||
|
text: "Ein sonniger Genussmoment: Sonnenblumenhonig verbindet eine aromatische Süße mit einer feinfrischen Note. Sein warmer, goldgelber Farbton macht schon beim Öffnen Lust aufs Probieren – auf dem Frühstücksbrot, im Joghurt oder zu einem warmen Pfannkuchen.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "akazienhonig",
|
||||||
|
text: "Zart, mild und feinblumig: Unser Akazienhonig ist ideal für alle, die eine zurückhaltende Süße lieben. Er passt wunderbar in Joghurt, zu frischem Obst oder zum Süßen von Tee, ohne andere Aromen zu überdecken.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "lindenhonig",
|
||||||
|
text: "So schmeckt der Sommer unter Hamburgs Linden: Unser Lindenhonig begeistert mit einem markanten, würzigen Aroma und einer feinfrischen, leicht minzigen Note. Ein Honig mit Charakter, der auf kräftigem Brot ebenso gut schmeckt wie zu Käse.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "frühlingsblütenhonig",
|
||||||
|
text: "Hamburger Frühling im Glas: Unser Frühlingshonig vereint die Blütenvielfalt der ersten warmen Tage mit einer milden, blumigen Süße. Ein Stück Frühling für deinen Frühstückstisch – auf frischen Brötchen, im Joghurt oder einfach pur.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stichwort: "sommerblütenhonig",
|
||||||
|
text: "Hamburger Sommer im Glas: Die Blütenvielfalt der warmen Jahreszeit verleiht unserem Sommerblütenhonig seinen aromatischen Charakter. Jede Ernte erzählt ein wenig anders vom Sommer – köstlich auf dem Frühstücksbrot, zu Joghurt oder als süße Note im Dressing.",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
const { data: produkte } = await query.graph({ entity: "product", fields: ["id", "title"] });
|
||||||
|
|
||||||
|
for (const { stichwort, text } of TEXTE) {
|
||||||
|
// "Presshonig Hamburger Sommerblüte" enthält kein "sommerblütenhonig",
|
||||||
|
// trotzdem nur genau ein Treffer je Sorte zulassen.
|
||||||
|
const treffer = produkte.filter((p: any) => p.title.toLowerCase().includes(stichwort));
|
||||||
|
if (treffer.length !== 1) {
|
||||||
|
logger.warn(`${stichwort}: ${treffer.length} Treffer, übersprungen.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: { selector: { id: treffer[0].id }, update: { description: text } } as any,
|
||||||
|
});
|
||||||
|
logger.info(`${treffer[0].title}: Text aktualisiert.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
/**
|
||||||
|
* Hängt die neuen Fotos an die Kerzen und den Honiglöffel.
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/set-kerzenbilder.ts
|
||||||
|
*
|
||||||
|
* Die vier Kerzen aus der Preisliste 9/2026 (setup-neu-2026.ts) bekommen
|
||||||
|
* ihre Bilder, einen stimmigen Namen und eine kurze Beschreibung und werden
|
||||||
|
* sichtbar.
|
||||||
|
*
|
||||||
|
* Sie lösen die alten Kerzen ab: Das Produkt "Bienenwachskerzen" (Bienenkorb,
|
||||||
|
* Wabenkerze, klassisch) wird Entwurf. Nicht gelöscht — Bestellungen und
|
||||||
|
* Varianten bleiben erhalten, im Admin lässt es sich wieder einschalten.
|
||||||
|
*
|
||||||
|
* Drei weitere Kerzen stehen nicht in der Preisliste. Ihre Preise sind an
|
||||||
|
* die vorhandenen Formen angelehnt und im Admin änderbar. Der Honiglöffel
|
||||||
|
* (Handle "honigdipper") steht in der eigenen Kategorie "Zubehör".
|
||||||
|
*
|
||||||
|
* Jede Kerze gibt es in zwei Farben, Honiggelb und Elfenbeinweiß. Die Farbe
|
||||||
|
* ist eine Variante (Option "Farbe"), damit sie in der Bestellung steht.
|
||||||
|
*
|
||||||
|
* Der Adventskranz wird nicht verkauft. Seine Bilder stehen in der Galerie
|
||||||
|
* der Rillenkerze, denn auf ihm stecken genau diese Kerzen.
|
||||||
|
*
|
||||||
|
* Vorn steht das schlichte Bild mit heller und dunkler Kerze gemeinsam, danach
|
||||||
|
* das weihnachtliche Paar. Das erste Bild ist zugleich das Hauptbild im
|
||||||
|
* Raster. Adressen ohne Domain, damit dieselben Daten im Heimnetz, auf dem
|
||||||
|
* Testsystem und in der Produktion stimmen.
|
||||||
|
*
|
||||||
|
* Auf Test und Produktion läuft das Skript beim Ausrollen von selbst, über
|
||||||
|
* src/migration-scripts/kerzen-und-honigloeffel.ts.
|
||||||
|
*
|
||||||
|
* Wiederholbar: Vorhandenes wird aktualisiert, nicht doppelt angelegt.
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
createAndLinkProductOptionsToProductWorkflow,
|
||||||
|
createProductCategoriesWorkflow,
|
||||||
|
createProductVariantsWorkflow,
|
||||||
|
createProductsWorkflow,
|
||||||
|
updateProductOptionsWorkflow,
|
||||||
|
updateProductOptionValuesWorkflow,
|
||||||
|
updateProductsWorkflow,
|
||||||
|
updateProductVariantsWorkflow,
|
||||||
|
} from "@medusajs/core-flows";
|
||||||
|
|
||||||
|
/** Nicht mehr im Shop: die abgelösten Kerzen aus der Shopify-Übernahme und
|
||||||
|
* der Adventskranz, der nur noch als Bild bei der Rillenkerze steht. */
|
||||||
|
const NICHT_IM_SHOP = ["bienenwachskerzen", "adventskranz"];
|
||||||
|
|
||||||
|
/** Die beiden Farben jeder Kerze; die erste ist vorausgewählt. */
|
||||||
|
const FARBEN = ["Honiggelb", "Elfenbeinweiß"];
|
||||||
|
|
||||||
|
/** Die Bilder liefert das Frontend aus (frontend/public/images/produkte).
|
||||||
|
* So kommen sie mit dem Frontend-Image auf jedes System, ohne Kopieren in
|
||||||
|
* das Upload-Volume des Backends. */
|
||||||
|
const BILDPFAD = "/images/produkte";
|
||||||
|
|
||||||
|
const PLATZHALTER = /\n*⚠️ Platzhalter:.*$/s;
|
||||||
|
|
||||||
|
/** Alle Kerzen sind handgemacht aus reinem Bienenwachs; der Titel sagt es
|
||||||
|
* im Muster der Honige ("Akazienhonig aus … - flüssig"). */
|
||||||
|
const PRODUKTE: {
|
||||||
|
handle: string;
|
||||||
|
titel: string;
|
||||||
|
kategorie: string;
|
||||||
|
/** Erstes Bild = Hauptbild: helle und dunkle Kerze gemeinsam, schlicht. */
|
||||||
|
aufnahmen: string[];
|
||||||
|
/** Nur für sichtbare Produkte, ersetzt den Platzhaltertext. */
|
||||||
|
beschreibung?: string;
|
||||||
|
/** Euro; gilt für alle Varianten. */
|
||||||
|
preis?: number;
|
||||||
|
/** Kerze in Honiggelb und Elfenbeinweiß. */
|
||||||
|
farben?: boolean;
|
||||||
|
sichtbar?: boolean;
|
||||||
|
}[] = [
|
||||||
|
// Schon vorhanden. Die Handles bleiben, damit Adressen stabil sind.
|
||||||
|
{
|
||||||
|
handle: "bubble-kerze",
|
||||||
|
titel: "Bubble-Würfel aus Bienenwachs - handgemacht",
|
||||||
|
kategorie: "Bienenprodukte",
|
||||||
|
aufnahmen: ["duo", "weihnacht"],
|
||||||
|
beschreibung: "Würfelkerze aus kleinen Wachskugeln, ca. 180 g. Handgemacht aus reinem Bienenwachs.",
|
||||||
|
preis: 9.9,
|
||||||
|
sichtbar: true,
|
||||||
|
farben: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
handle: "regenbogen",
|
||||||
|
titel: "Regenbogenkerze aus Bienenwachs - handgemacht",
|
||||||
|
kategorie: "Bienenprodukte",
|
||||||
|
aufnahmen: ["duo", "weihnacht"],
|
||||||
|
beschreibung: "Kerze in Bogenform mit feinen Rillen. Handgemacht aus reinem Bienenwachs.",
|
||||||
|
preis: 7.9,
|
||||||
|
sichtbar: true,
|
||||||
|
farben: true,
|
||||||
|
},
|
||||||
|
// Eierform 1 ist die facettierte Tropfenform, Eierform 2 die gerippte Kugel.
|
||||||
|
{
|
||||||
|
handle: "eierform-1",
|
||||||
|
titel: "Tropfenkerze aus Bienenwachs - handgemacht",
|
||||||
|
kategorie: "Bienenprodukte",
|
||||||
|
aufnahmen: ["duo", "weihnacht"],
|
||||||
|
beschreibung: "Facettierte Kerze in Tropfenform. Handgemacht aus reinem Bienenwachs.",
|
||||||
|
preis: 5.5,
|
||||||
|
sichtbar: true,
|
||||||
|
farben: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
handle: "eierform-2",
|
||||||
|
titel: "Lampionkerze aus Bienenwachs - handgemacht",
|
||||||
|
kategorie: "Bienenprodukte",
|
||||||
|
aufnahmen: ["duo", "weihnacht"],
|
||||||
|
beschreibung: "Runde, gerippte Kerze in Lampionform. Handgemacht aus reinem Bienenwachs.",
|
||||||
|
preis: 5.5,
|
||||||
|
sichtbar: true,
|
||||||
|
farben: true,
|
||||||
|
},
|
||||||
|
// Nicht in der Preisliste; Preise angelehnt an die vorhandenen Formen.
|
||||||
|
{
|
||||||
|
handle: "bubble-stumpenkerze",
|
||||||
|
titel: "Bubble-Stumpenkerze aus Bienenwachs - handgemacht",
|
||||||
|
kategorie: "Bienenprodukte",
|
||||||
|
aufnahmen: ["duo", "weihnacht"],
|
||||||
|
beschreibung: "Stumpenkerze mit Noppen-Oberfläche. Handgemacht aus reinem Bienenwachs.",
|
||||||
|
preis: 9.9,
|
||||||
|
sichtbar: true,
|
||||||
|
farben: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
handle: "geriffelte-stumpenkerze",
|
||||||
|
titel: "Rillenkerze aus Bienenwachs - handgemacht",
|
||||||
|
kategorie: "Bienenprodukte",
|
||||||
|
aufnahmen: ["duo", "weihnacht", "adventskranz-gold", "adventskranz-elfenbein"],
|
||||||
|
beschreibung: "Stumpenkerze mit feinen Rillen und spitzer Krone. Handgemacht aus reinem Bienenwachs.",
|
||||||
|
preis: 7.9,
|
||||||
|
sichtbar: true,
|
||||||
|
farben: true,
|
||||||
|
},
|
||||||
|
// Von den Tannen gibt es nur weihnachtliche Paare.
|
||||||
|
{
|
||||||
|
handle: "bienenwachs-tannenbaum",
|
||||||
|
titel: "Tannenbaumkerze aus Bienenwachs - handgemacht",
|
||||||
|
kategorie: "Bienenprodukte",
|
||||||
|
aufnahmen: ["studio", "tafel", "sideboard"],
|
||||||
|
beschreibung: "Kerze in Tannenbaumform für die Weihnachtszeit. Handgemacht aus reinem Bienenwachs.",
|
||||||
|
preis: 5.5,
|
||||||
|
sichtbar: true,
|
||||||
|
farben: true,
|
||||||
|
},
|
||||||
|
// Keine Kerze: eigene Kategorie, ohne Farbwahl.
|
||||||
|
{
|
||||||
|
handle: "honigdipper",
|
||||||
|
titel: "Honiglöffel aus Holz",
|
||||||
|
kategorie: "Zubehör",
|
||||||
|
aufnahmen: ["studio", "wabe", "fruehstueck", "akazie"],
|
||||||
|
beschreibung:
|
||||||
|
"Für deinen süßen Genussmoment: Mit unserem Honiglöffel bringst du deinen Lieblingshonig auf Brot, in den Tee oder über dein Frühstück. Ein praktischer Begleiter für jeden Honigfan und eine schöne Ergänzung zum verschenkten Honigglas.",
|
||||||
|
preis: 5.9,
|
||||||
|
sichtbar: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
let { data: kategorien } = await query.graph({
|
||||||
|
entity: "product_category",
|
||||||
|
fields: ["id", "name", "rank"],
|
||||||
|
});
|
||||||
|
// Fehlende Kategorien (z. B. "Zubehör") hinten anhängen.
|
||||||
|
for (const name of new Set(PRODUKTE.map((p) => p.kategorie))) {
|
||||||
|
if ((kategorien ?? []).some((c: any) => c.name === name)) continue;
|
||||||
|
const rang = Math.max(0, ...(kategorien ?? []).map((c: any) => c.rank ?? 0)) + 1;
|
||||||
|
const handle = name.toLowerCase().replace("ö", "oe").replace(/[^a-z0-9]+/g, "-");
|
||||||
|
const { result } = await createProductCategoriesWorkflow(container).run({
|
||||||
|
input: { product_categories: [{ name, handle, is_active: true, rank: rang }] },
|
||||||
|
});
|
||||||
|
kategorien = [...(kategorien ?? []), (result as any)[0]];
|
||||||
|
logger.info(`Kategorie "${name}" angelegt.`);
|
||||||
|
}
|
||||||
|
// Jeweils der älteste: Auf dem Testsystem kann ein abgebrochener Seed-Lauf
|
||||||
|
// einen zweiten "Default Sales Channel" hinterlassen haben.
|
||||||
|
const { data: profile } = await query.graph({
|
||||||
|
entity: "shipping_profile",
|
||||||
|
fields: ["id"],
|
||||||
|
pagination: { order: { created_at: "ASC" } },
|
||||||
|
});
|
||||||
|
const { data: kanaele } = await query.graph({
|
||||||
|
entity: "sales_channel",
|
||||||
|
fields: ["id"],
|
||||||
|
pagination: { order: { created_at: "ASC" } },
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const p of PRODUKTE) {
|
||||||
|
const bilder = p.aufnahmen.map((a) => `${BILDPFAD}/produkt-${a}-${p.handle}.jpg`);
|
||||||
|
const kategorie = (kategorien ?? []).find((c: any) => c.name === p.kategorie);
|
||||||
|
const lesen = async () =>
|
||||||
|
(
|
||||||
|
await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: ["id", "title", "status", "description", "metadata", "variants.id"],
|
||||||
|
filters: { handle: p.handle },
|
||||||
|
})
|
||||||
|
).data?.[0];
|
||||||
|
|
||||||
|
// Fehlt das Produkt (etwa auf einem frischen System), zuerst als Entwurf
|
||||||
|
// anlegen; danach geht es für alle gleich weiter.
|
||||||
|
let produkt = await lesen();
|
||||||
|
if (!produkt) {
|
||||||
|
await createProductsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
products: [
|
||||||
|
{
|
||||||
|
title: p.titel,
|
||||||
|
handle: p.handle,
|
||||||
|
status: "draft" as any,
|
||||||
|
description:
|
||||||
|
`${p.titel}.\n\n` +
|
||||||
|
"⚠️ Platzhalter: Beschreibung, Maße, Preis und Gewicht fehlen noch.",
|
||||||
|
shipping_profile_id: profile?.[0]?.id,
|
||||||
|
sales_channels: kanaele?.[0] ? [{ id: kanaele[0].id }] : undefined,
|
||||||
|
metadata: { category: p.kategorie, delivery_time: "2-3 Werktage" },
|
||||||
|
...(kategorie ? { category_ids: [kategorie.id] } : {}),
|
||||||
|
options: [{ title: "Ausführung", values: ["Standard"] }],
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
title: "Standard",
|
||||||
|
options: { "Ausführung": "Standard" },
|
||||||
|
manage_inventory: false,
|
||||||
|
prices: p.preis !== undefined ? [{ amount: p.preis, currency_code: "eur" }] : [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
logger.info(`"${p.titel}" angelegt.`);
|
||||||
|
produkt = await lesen();
|
||||||
|
}
|
||||||
|
|
||||||
|
const update: any = {
|
||||||
|
title: p.titel,
|
||||||
|
category_ids: kategorie ? [kategorie.id] : undefined,
|
||||||
|
metadata: { ...(produkt.metadata ?? {}), category: p.kategorie },
|
||||||
|
thumbnail: bilder[0],
|
||||||
|
images: bilder.map((url: string) => ({ url })),
|
||||||
|
};
|
||||||
|
if (p.sichtbar) {
|
||||||
|
update.status = "published";
|
||||||
|
update.description = p.beschreibung ?? (produkt.description ?? "").replace(PLATZHALTER, "");
|
||||||
|
}
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: { selector: { id: produkt.id }, update } as any,
|
||||||
|
});
|
||||||
|
if (p.preis !== undefined) {
|
||||||
|
for (const v of produkt.variants ?? []) {
|
||||||
|
await updateProductVariantsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
selector: { id: v.id },
|
||||||
|
update: { prices: [{ amount: p.preis, currency_code: "eur" }] },
|
||||||
|
} as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (p.farben) await farbenSetzen(container, produkt.id, p.preis);
|
||||||
|
logger.info(`"${p.titel}": ${bilder.length} Bilder (${update.status ?? produkt.status}).`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const handle of NICHT_IM_SHOP) {
|
||||||
|
const { data: alt } = await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: ["id", "title", "status"],
|
||||||
|
filters: { handle },
|
||||||
|
});
|
||||||
|
if (alt?.[0] && alt[0].status !== "draft") {
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: { selector: { id: alt[0].id }, update: { status: "draft" } } as any,
|
||||||
|
});
|
||||||
|
logger.info(`"${alt[0].title}" ist jetzt Entwurf und nicht mehr im Shop.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Macht aus der Option "Ausführung: Standard" die Option "Farbe" mit beiden
|
||||||
|
* Farben. Umbenennen statt ersetzen: Medusa lässt eine Option nicht los,
|
||||||
|
* solange Varianten an ihr hängen. Die vorhandene Variante wird Honiggelb
|
||||||
|
* (Bestellungen bleiben an ihr), Elfenbeinweiß kommt mit demselben Preis dazu.
|
||||||
|
*/
|
||||||
|
async function farbenSetzen(container: any, produktId: string, preis?: number) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const lesen = async () =>
|
||||||
|
(
|
||||||
|
await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"options.id",
|
||||||
|
"options.title",
|
||||||
|
"options.values.id",
|
||||||
|
"options.values.value",
|
||||||
|
"variants.id",
|
||||||
|
"variants.title",
|
||||||
|
"variants.prices.amount",
|
||||||
|
"variants.prices.currency_code",
|
||||||
|
],
|
||||||
|
filters: { id: produktId },
|
||||||
|
})
|
||||||
|
).data[0];
|
||||||
|
|
||||||
|
let produkt = await lesen();
|
||||||
|
const option = produkt.options.find((o: any) => ["Ausführung", "Farbe"].includes(o.title));
|
||||||
|
if (!option) throw new Error(`Produkt ${produktId}: keine Option "Ausführung" oder "Farbe".`);
|
||||||
|
|
||||||
|
if (option.title !== "Farbe") {
|
||||||
|
await updateProductOptionsWorkflow(container).run({
|
||||||
|
input: { selector: { id: option.id }, update: { title: "Farbe" } } as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const standard = option.values.find((v: any) => v.value === "Standard");
|
||||||
|
if (standard) {
|
||||||
|
await updateProductOptionValuesWorkflow(container).run({
|
||||||
|
input: { id: standard.id, update: { value: FARBEN[0] } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
produkt = await lesen();
|
||||||
|
const werte = produkt.options.find((o: any) => o.id === option.id).values.map((v: any) => v.value);
|
||||||
|
const fehlend = FARBEN.filter((f) => !werte.includes(f));
|
||||||
|
if (fehlend.length) {
|
||||||
|
await createAndLinkProductOptionsToProductWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
product_id: produktId,
|
||||||
|
update: [{ product_option_id: option.id, add: fehlend.map((value) => ({ value })) }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const betrag =
|
||||||
|
preis ?? produkt.variants[0]?.prices?.find((x: any) => x.currency_code === "eur")?.amount;
|
||||||
|
|
||||||
|
const standardVariante = produkt.variants.find((v: any) => !FARBEN.includes(v.title));
|
||||||
|
if (standardVariante) {
|
||||||
|
await updateProductVariantsWorkflow(container).run({
|
||||||
|
input: { selector: { id: standardVariante.id }, update: { title: FARBEN[0] } } as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Die alte Standard-Variante heißt nach dem Umbenennen Honiggelb.
|
||||||
|
const vorhanden = produkt.variants.map((v: any) =>
|
||||||
|
FARBEN.includes(v.title) ? v.title : FARBEN[0]
|
||||||
|
);
|
||||||
|
for (const farbe of FARBEN.filter((f) => !vorhanden.includes(f))) {
|
||||||
|
await createProductVariantsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
product_variants: [
|
||||||
|
{
|
||||||
|
product_id: produktId,
|
||||||
|
title: farbe,
|
||||||
|
options: { Farbe: farbe },
|
||||||
|
manage_inventory: false,
|
||||||
|
prices: [{ amount: betrag, currency_code: "eur" }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
} as any);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* Fotos für Lindenhonig, Sommerblütenhonig und Sonnenblumenhonig.
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/set-neue-honigbilder.ts
|
||||||
|
*
|
||||||
|
* Nur die Frühstücks- und die Outdoor-Aufnahme, ohne Studio. Die Frühstücks-
|
||||||
|
* aufnahme wird das Hauptbild. Vorhandene Bilder bleiben dahinter erhalten.
|
||||||
|
*
|
||||||
|
* Die Dateien liegen im Frontend (public/images/produkte) und kommen mit dem
|
||||||
|
* Frontend-Image mit — wie die Kerzenbilder.
|
||||||
|
*
|
||||||
|
* Wiederholbar: Was schon dran ist, wird nicht doppelt angehängt.
|
||||||
|
*/
|
||||||
|
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||||
|
|
||||||
|
const SORTEN = [
|
||||||
|
{ datei: "linde", handle: "lindenhonig-aus-hamburg" },
|
||||||
|
{ datei: "sommer", handle: "sommerblutenhonig-aus-hamburg" },
|
||||||
|
{ datei: "sonnenblume", handle: "sonnenblumenhonig-aus-der-harzregion" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const PFAD = (aufnahme: string, sorte: string) => `/images/produkte/produkt-${aufnahme}-${sorte}-250g.jpg`;
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
for (const sorte of SORTEN) {
|
||||||
|
const { data } = await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: ["id", "title", "images.url", "images.rank"],
|
||||||
|
filters: { handle: sorte.handle },
|
||||||
|
});
|
||||||
|
const produkt = data?.[0];
|
||||||
|
if (!produkt) {
|
||||||
|
logger.warn(`Kein Produkt mit Handle ${sorte.handle}.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const neu = [PFAD("fruehstueck", sorte.datei), PFAD("outdoor", sorte.datei)];
|
||||||
|
const bisher = [...(produkt.images ?? [])]
|
||||||
|
.sort((a: any, b: any) => (a.rank ?? 0) - (b.rank ?? 0))
|
||||||
|
.map((i: any) => i.url)
|
||||||
|
.filter((url: string) => !neu.includes(url));
|
||||||
|
const bilder = [...neu, ...bisher];
|
||||||
|
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
selector: { id: produkt.id },
|
||||||
|
update: { thumbnail: neu[0], images: bilder.map((url) => ({ url })) },
|
||||||
|
} as any,
|
||||||
|
});
|
||||||
|
logger.info(`${produkt.title}: ${bilder.length} Bilder, Hauptbild Frühstück.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
/**
|
||||||
|
* Feinschliff im Shop nach der Durchsicht vom November 2026.
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/set-shop-feinschliff.ts
|
||||||
|
*
|
||||||
|
* - Reihenfolge der Kategorien: erst alles zum Essen, dann Wachs, Kerzen,
|
||||||
|
* Pflege und Zubehör, dann Gutschein,
|
||||||
|
* Patenschaft, Kurs und Abo.
|
||||||
|
* - Text der eigenen Honig-Seife mit Zutatenliste (INCI, bei Kosmetik
|
||||||
|
* Pflicht). Der offene Hinweis dazu am Produkt fällt weg.
|
||||||
|
* - Honiglöffel ("Honigheber") kostet 5,90 €.
|
||||||
|
* - Die zugekaufte Honigseife (Lavendel, Gelee Royal, Propolis) wird nicht
|
||||||
|
* mehr verkauft: Entwurf statt löschen, Bestellungen bleiben erhalten.
|
||||||
|
*
|
||||||
|
* Wiederholbar: setzt nur Zielwerte.
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
updateProductCategoriesWorkflow,
|
||||||
|
updateProductsWorkflow,
|
||||||
|
updateProductVariantsWorkflow,
|
||||||
|
} from "@medusajs/core-flows";
|
||||||
|
|
||||||
|
const REIHENFOLGE = [
|
||||||
|
// Erst alles zum Essen, dann Wachs und Kerzen.
|
||||||
|
"honig",
|
||||||
|
"süßigkeiten-mit-honig",
|
||||||
|
"feinkost",
|
||||||
|
"bienenprodukte",
|
||||||
|
"pflegeprodukte",
|
||||||
|
"zubehoer",
|
||||||
|
"geschenkgutschein",
|
||||||
|
"bienenpatenschaften",
|
||||||
|
"kurse",
|
||||||
|
"abo",
|
||||||
|
];
|
||||||
|
|
||||||
|
const SEIFE = {
|
||||||
|
handle: "pflegeseife-milch-honig",
|
||||||
|
subtitle: "Handgemachte Pflegeseife mit Hamburger Stadthonig.",
|
||||||
|
description: [
|
||||||
|
"Handgemacht, Stück für Stück – mit Honig aus unserer eigenen Hamburger Imkerei.",
|
||||||
|
"Ein Stück Hamburg für deine tägliche Pflege: Unsere Seife mit eigenem Hamburger Stadthonig verbindet Ziegenmilch, Sheabutter, Kokosöl und Jojobaöl mit Calendula. Dazu ein angenehm weicher, frischer Duft – für eine kleine Auszeit am Waschbecken.",
|
||||||
|
"Von Hand hergestellt in Zusammenarbeit mit der Manufaktur Meerseifen Timmendorf.",
|
||||||
|
"Inhaltsstoffe: Aqua (Wasser), Butyrospermum Parkii Butter (Shea Butter), Cocos Nucifera Oil (Kokosnußöl), Brassica Napus Seed Oil (Rapsöl), Oryza Sativa Germ Oil (Reiskeimöl), Sodium Hydroxide (Natriumhydroxid), Simmondsia Chinensis Seed Oil (Jojobaöl mit Calendulablütenauszug), Parfum (ätherisches Öl) Citrus Sinensis Peel Oil, Mel (Honig), Caprae Lac (Ziegenmilch), Maris Sal (Meersalz), CI77492 (Eisenoxid, gelb), Limonene.",
|
||||||
|
"Frischgewicht: 100 g",
|
||||||
|
].join("\n\n"),
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Kategorien in REIHENFOLGE bringen. Auch einzeln nutzbar (shop-reihenfolge). */
|
||||||
|
export async function kategorienSortieren(container: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
const { data: kategorien } = await query.graph({
|
||||||
|
entity: "product_category",
|
||||||
|
fields: ["id", "handle", "rank", "parent_category_id"],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Der Reihe nach auf Platz 0, 1, 2 … setzen. Medusa schiebt die übrigen
|
||||||
|
// Geschwister dabei weiter, am Ende stimmt die Reihenfolge.
|
||||||
|
let platz = 0;
|
||||||
|
for (const handle of REIHENFOLGE) {
|
||||||
|
const kategorie = kategorien.find((k: any) => k.handle === handle && !k.parent_category_id);
|
||||||
|
if (!kategorie) {
|
||||||
|
logger.warn(`Keine Kategorie ${handle}.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (kategorie.rank !== platz) {
|
||||||
|
await updateProductCategoriesWorkflow(container).run({
|
||||||
|
input: { selector: { id: kategorie.id }, update: { rank: platz } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
platz++;
|
||||||
|
}
|
||||||
|
logger.info("Kategorien neu sortiert.");
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
await kategorienSortieren(container);
|
||||||
|
|
||||||
|
const { data: produkte } = await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: ["id"],
|
||||||
|
filters: { handle: SEIFE.handle },
|
||||||
|
});
|
||||||
|
if (produkte?.[0]) {
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
selector: { id: produkte[0].id },
|
||||||
|
update: {
|
||||||
|
subtitle: SEIFE.subtitle,
|
||||||
|
description: SEIFE.description,
|
||||||
|
// Leerer Wert entfernt den Schlüssel.
|
||||||
|
metadata: { offen: "" },
|
||||||
|
},
|
||||||
|
} as any,
|
||||||
|
});
|
||||||
|
logger.info("Text der Honig-Seife aktualisiert.");
|
||||||
|
} else {
|
||||||
|
logger.warn(`Kein Produkt mit Handle ${SEIFE.handle}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data: loeffel } = await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: ["id", "variants.id"],
|
||||||
|
filters: { handle: "honigdipper" },
|
||||||
|
});
|
||||||
|
for (const v of loeffel?.[0]?.variants ?? []) {
|
||||||
|
await updateProductVariantsWorkflow(container).run({
|
||||||
|
input: { selector: { id: v.id }, update: { prices: [{ amount: 5.9, currency_code: "eur" }] } } as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (loeffel?.[0]) logger.info("Honiglöffel: 5,90 €.");
|
||||||
|
|
||||||
|
const { data: alteSeife } = await query.graph({
|
||||||
|
entity: "product",
|
||||||
|
fields: ["id", "status"],
|
||||||
|
filters: { handle: "seife-aus-unserem-honig" },
|
||||||
|
});
|
||||||
|
if (alteSeife?.[0] && alteSeife[0].status !== "draft") {
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: { selector: { id: alteSeife[0].id }, update: { status: "draft" } } as any,
|
||||||
|
});
|
||||||
|
logger.info("Zugekaufte Honigseife ist jetzt Entwurf und nicht mehr im Shop.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
/**
|
||||||
|
* Neue Fotos für Honig-Doppelbärchen, Honigwaffeln, Honig-Lakritz und Honig-Bonbons.
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/set-snackbilder.ts
|
||||||
|
*
|
||||||
|
* Ersetzt die bisherigen Bilder ganz. Hauptbild ist die Packung auf
|
||||||
|
* Elfenbein, dahinter die Szenen mit Packung und der Teller.
|
||||||
|
* Die Dateien liegen im Frontend (public/images/produkte).
|
||||||
|
*
|
||||||
|
* Wiederholbar.
|
||||||
|
*/
|
||||||
|
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||||
|
|
||||||
|
const SNACKS = [
|
||||||
|
{ handle: "gummibarchen", datei: "doppelbaerchen", szenen: ["wohnzimmer"] },
|
||||||
|
{ handle: "honigwaffeln", datei: "honigwaffeln", szenen: ["tisch"] },
|
||||||
|
{ handle: "honig-lakritze", datei: "honig-lakritz", szenen: ["wohnzimmer"] },
|
||||||
|
{ handle: "honig-bonbons", datei: "honig-bonbons", szenen: ["tisch", "unterwegs"] },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
for (const snack of SNACKS) {
|
||||||
|
const { data } = await query.graph({ entity: "product", fields: ["id", "title"], filters: { handle: snack.handle } });
|
||||||
|
const produkt = data?.[0];
|
||||||
|
if (!produkt) {
|
||||||
|
logger.warn(`Kein Produkt mit Handle ${snack.handle}.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const bilder = ["studio", ...snack.szenen, "teller"].map((a) => `/images/produkte/produkt-${a}-${snack.datei}.jpg`);
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: {
|
||||||
|
selector: { id: produkt.id },
|
||||||
|
update: { thumbnail: bilder[0], images: bilder.map((url) => ({ url })) },
|
||||||
|
} as any,
|
||||||
|
});
|
||||||
|
logger.info(`${produkt.title}: ${bilder.length} neue Bilder.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/**
|
||||||
|
* Zutaten und Nährwerte der Honig-Süßigkeiten (Angaben vom Team, November 2026).
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/set-snacks-texte.ts
|
||||||
|
*
|
||||||
|
* Allergene stehen in GROSSBUCHSTABEN: Die LMIV verlangt sie in der
|
||||||
|
* Zutatenliste hervorgehoben, auch im Onlineshop, und die Beschreibung ist
|
||||||
|
* reiner Text ohne Fettdruck.
|
||||||
|
*
|
||||||
|
* Wiederholbar: setzt nur Zielwerte.
|
||||||
|
*/
|
||||||
|
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||||
|
|
||||||
|
const absatz = (...teile: string[]) => teile.join("\n\n");
|
||||||
|
const naehrwerte = (zeilen: [string, string][]) =>
|
||||||
|
["Nährwerte pro 100 g:", ...zeilen.map(([name, wert]) => `${name}: ${wert}`)].join("\n");
|
||||||
|
|
||||||
|
const TEXTE: Record<string, string> = {
|
||||||
|
"honig-lakritze": absatz(
|
||||||
|
"Die Honig-Lakritze zeichnen sich durch ihre Bienenkorbform und den leicht würzigen Geschmack aus.",
|
||||||
|
"Inhalt: 100 g",
|
||||||
|
"Zutaten: Zucker, Glukosesirup, modifizierte Kartoffelstärke, Rohrzuckermelasse, WEIZENSTÄRKE, Honig (8 %), Süßholzwurzelextrakt (1,6 %), Salmiaksalz, Wasser, Kokosöl, Überzugsmittel (E901).",
|
||||||
|
naehrwerte([
|
||||||
|
["Energie", "1457 kJ / 343 kcal"],
|
||||||
|
["Fett", "0,3 g"],
|
||||||
|
["• davon gesättigte Fettsäuren", "0,2 g"],
|
||||||
|
["Kohlenhydrate", "84,7 g"],
|
||||||
|
["• davon Zucker", "57,6 g"],
|
||||||
|
["Eiweiß", "0,3 g"],
|
||||||
|
["Salz", "0,21 g"],
|
||||||
|
])
|
||||||
|
),
|
||||||
|
gummibarchen: absatz(
|
||||||
|
"Die Honig-Doppelbärchen gehören wegen ihres fruchtig-frischen Geschmacks zu den beliebtesten Honig-Süßigkeiten – mit Honig und Vitaminen.",
|
||||||
|
"Inhalt: 100 g",
|
||||||
|
"Zutaten: Glucosesirup; Zucker; Gelatine (Schwein); Honig 5 %; Säuerungsmittel: Citronensäure; Fruchtsaftkonzentrate (Maracuja, Zitrone, Kirsche); Vitamine: Vitamin E, Niacin, Vitamin B6, Thiamin; pflanzliches Öl (Kokosnuss, Rapssamen); Überzugsmittel: Bienenwachs (weiß), Carnaubawachs; Aromen; Farbstoff: Beta-Carotin.",
|
||||||
|
"Kann Spuren von GLUTEN und MILCH enthalten.",
|
||||||
|
naehrwerte([
|
||||||
|
["Energie", "1453 kJ / 342 kcal"],
|
||||||
|
["Fett", "0,2 g"],
|
||||||
|
["• davon gesättigte Fettsäuren", "0,2 g"],
|
||||||
|
["Kohlenhydrate", "77 g"],
|
||||||
|
["• davon Zucker", "56 g"],
|
||||||
|
["Eiweiß", "6,9 g"],
|
||||||
|
["Salz", "0,10 g"],
|
||||||
|
["Vitamin E", "35 mg ≈ 292 %*"],
|
||||||
|
["Vitamin B6", "1,8 mg ≈ 129 %*"],
|
||||||
|
["Thiamin", "1,5 mg ≈ 136 %*"],
|
||||||
|
["Niacin", "17 mg ≈ 106 %*"],
|
||||||
|
["Biotin", "400 µg ≈ 800 %*"],
|
||||||
|
]) + "\n* % der Referenzmenge für die tägliche Zufuhr von Vitaminen"
|
||||||
|
),
|
||||||
|
honigwaffeln: absatz(
|
||||||
|
"Unsere Honigwaffeln mit Rahmbutter, Honig, Vanille und Zimt gehören zu den meistverkauften Süßigkeiten mit Honig – und das nicht ohne Grund: Geschmack und Konsistenz sind einfach klasse.",
|
||||||
|
"Inhalt: 90 g",
|
||||||
|
"Zutaten: WEIZENMEHL, 32 % Sirup (Glucose-Fructose-Sirup, Zucker, 11 % BUTTER, 10 % Honig, Stärke, Emulgator: Sonnenblumenlecithin), 14 % BUTTERREINFETT (Carotin), Zucker, Glucose-Fructose-Sirup, EIER aus Freilandhaltung, Backtriebmittel (Natriumcarbonat, Ammoniumcarbonat), Salz, Stärke, Emulgator: Sonnenblumenlecithin, Zimt.",
|
||||||
|
"Kann Spuren von ERDNÜSSEN und NÜSSEN (MANDELN) enthalten.",
|
||||||
|
naehrwerte([
|
||||||
|
["Energie", "1978 kJ / 468 kcal"],
|
||||||
|
["Fett", "18 g"],
|
||||||
|
["• davon gesättigte Fettsäuren", "12 g"],
|
||||||
|
["Kohlenhydrate", "71 g"],
|
||||||
|
["• davon Zucker", "36 g"],
|
||||||
|
["Eiweiß", "5 g"],
|
||||||
|
["Salz", "0,38 g"],
|
||||||
|
])
|
||||||
|
),
|
||||||
|
"honig-bonbons": absatz(
|
||||||
|
"Die Honigbienen-Bonbons sind ungefüllt und perfekt für den kleinen Snack zwischendurch. Optisch machen sie auch was her: Auf beiden Seiten ist eine Bienenkönigin eingearbeitet.",
|
||||||
|
"Inhalt: 100 g",
|
||||||
|
"Zutaten: Zucker, Glukosesirup, Honig (6,5 %).",
|
||||||
|
naehrwerte([
|
||||||
|
["Energie", "1655 kJ / 389 kcal"],
|
||||||
|
["Fett", "0,1 g"],
|
||||||
|
["• davon gesättigte Fettsäuren", "< 0,1 g"],
|
||||||
|
["Kohlenhydrate", "96,1 g"],
|
||||||
|
["• davon Zucker", "64,0 g"],
|
||||||
|
["Eiweiß", "0,1 g"],
|
||||||
|
["Salz", "0,0 g"],
|
||||||
|
])
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
for (const [handle, text] of Object.entries(TEXTE)) {
|
||||||
|
const { data } = await query.graph({ entity: "product", fields: ["id", "title"], filters: { handle } });
|
||||||
|
if (!data?.[0]) {
|
||||||
|
logger.warn(`Kein Produkt mit Handle ${handle}.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: { selector: { id: data[0].id }, update: { description: text } } as any,
|
||||||
|
});
|
||||||
|
logger.info(`${data[0].title}: Text aktualisiert.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/**
|
||||||
|
* Nachtrag zu den Produkttexten (November 2026): Honiglöffel und
|
||||||
|
* Honig-Balsamico-Essig mit den Texten vom Team.
|
||||||
|
*
|
||||||
|
* npx medusa exec ./src/scripts/set-texte-nachtrag.ts
|
||||||
|
*
|
||||||
|
* Eigenes Skript, weil die vorherigen Migrationsskripte auf dem Testsystem
|
||||||
|
* schon gelaufen sein können und dann nicht noch einmal laufen.
|
||||||
|
* Wiederholbar.
|
||||||
|
*/
|
||||||
|
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||||
|
import honigEssig from "./set-honig-essig";
|
||||||
|
|
||||||
|
const LOEFFEL =
|
||||||
|
"Für deinen süßen Genussmoment: Mit unserem Honiglöffel bringst du deinen Lieblingshonig auf Brot, in den Tee oder über dein Frühstück. Ein praktischer Begleiter für jeden Honigfan und eine schöne Ergänzung zum verschenkten Honigglas.";
|
||||||
|
|
||||||
|
export default async function ({ container }: any) {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
|
||||||
|
const { data } = await query.graph({ entity: "product", fields: ["id"], filters: { handle: "honigdipper" } });
|
||||||
|
if (data?.[0]) {
|
||||||
|
await updateProductsWorkflow(container).run({
|
||||||
|
input: { selector: { id: data[0].id }, update: { description: LOEFFEL } } as any,
|
||||||
|
});
|
||||||
|
logger.info("Honiglöffel: Text aktualisiert.");
|
||||||
|
}
|
||||||
|
|
||||||
|
await honigEssig({ container });
|
||||||
|
}
|
||||||
@@ -12,6 +12,12 @@
|
|||||||
* die Angaben werden jetzt direkt am Produkt erfragt. Der Satz wird
|
* die Angaben werden jetzt direkt am Produkt erfragt. Der Satz wird
|
||||||
* deshalb entfernt, damit die Beschreibung nicht etwas verlangt, was
|
* deshalb entfernt, damit die Beschreibung nicht etwas verlangt, was
|
||||||
* der Bestellvorgang schon erledigt.
|
* der Bestellvorgang schon erledigt.
|
||||||
|
* 3. Versandprofil entfernen → der Posten braucht keinen Versand
|
||||||
|
* (`requires_shipping = false`, wie beim Gutschein). Beim Kauf geht nur
|
||||||
|
* die Urkunde per Brief raus; die vier Honiggläser folgen im
|
||||||
|
* Oktober/November in einem Paket. Beides wird im Admin von Hand
|
||||||
|
* verschickt, deshalb soll der Shop kein automatisches DHL-Label
|
||||||
|
* erzeugen und an der Kasse keine Versandart verlangen.
|
||||||
*
|
*
|
||||||
* Wiederholbar: was schon stimmt, bleibt unangetastet.
|
* Wiederholbar: was schon stimmt, bleibt unangetastet.
|
||||||
*/
|
*/
|
||||||
@@ -27,7 +33,7 @@ export default async function ({ container }: any) {
|
|||||||
|
|
||||||
const { data: produkte } = await query.graph({
|
const { data: produkte } = await query.graph({
|
||||||
entity: "product",
|
entity: "product",
|
||||||
fields: ["id", "title", "description", "metadata", "categories.name"],
|
fields: ["id", "title", "description", "metadata", "categories.name", "shipping_profile.id"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const paten = (produkte ?? []).filter(
|
const paten = (produkte ?? []).filter(
|
||||||
@@ -53,6 +59,12 @@ export default async function ({ container }: any) {
|
|||||||
update.description = beschreibung.replace(ALTER_HINWEIS, "").trimEnd();
|
update.description = beschreibung.replace(ALTER_HINWEIS, "").trimEnd();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Versandprofil entfernen: Urkunde (Brief) und Honig (Okt/Nov) gehen von
|
||||||
|
// Hand raus, kein automatisches DHL-Label, keine Versandart an der Kasse.
|
||||||
|
if (p.shipping_profile?.id) {
|
||||||
|
update.shipping_profile_id = null;
|
||||||
|
}
|
||||||
|
|
||||||
if (!Object.keys(update).length) {
|
if (!Object.keys(update).length) {
|
||||||
logger.info(` "${p.title}" ist bereits eingerichtet.`);
|
logger.info(` "${p.title}" ist bereits eingerichtet.`);
|
||||||
continue;
|
continue;
|
||||||
@@ -65,6 +77,7 @@ export default async function ({ container }: any) {
|
|||||||
` "${p.title}": ${[
|
` "${p.title}": ${[
|
||||||
update.metadata ? "als Patenschaft markiert" : null,
|
update.metadata ? "als Patenschaft markiert" : null,
|
||||||
update.description ? "Hinweis auf das Warenkorb-Feld entfernt" : null,
|
update.description ? "Hinweis auf das Warenkorb-Feld entfernt" : null,
|
||||||
|
"shipping_profile_id" in update ? "Versandprofil entfernt" : null,
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(", ")}.`
|
.join(", ")}.`
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||||
|
import { PaymentEvents } from "@medusajs/framework/utils";
|
||||||
|
import { bestellungZurZahlung } from "../lib/fulfill-order";
|
||||||
|
import { geschenkAbosAnkuendigen, patenschaftenAnkuendigen } from "../lib/geschenk-ankuendigung";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holt die Ankündigungen an Beschenkte nach, sobald eine Zahlung erfasst
|
||||||
|
* ist — bei Kauf auf Rechnung, wenn im Admin die Zahlung gebucht wird.
|
||||||
|
* Bereits Verschicktes überspringen die beiden Funktionen.
|
||||||
|
*/
|
||||||
|
export default async function geschenkeNachZahlung({ event, container }: SubscriberArgs<{ id: string }>) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
try {
|
||||||
|
const orderId = await bestellungZurZahlung(container, event.data.id);
|
||||||
|
if (!orderId) return;
|
||||||
|
await geschenkAbosAnkuendigen(container, orderId, logger);
|
||||||
|
await patenschaftenAnkuendigen(container, orderId, logger);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
`[geschenk] Ankündigung nach Zahlung ${event.data.id} fehlgeschlagen: ${
|
||||||
|
error instanceof Error ? error.message : String(error)
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config: SubscriberConfig = {
|
||||||
|
event: PaymentEvents.CAPTURED,
|
||||||
|
};
|
||||||
@@ -1,19 +1,10 @@
|
|||||||
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||||
import { Modules } from "@medusajs/framework/utils";
|
|
||||||
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
|
||||||
import { createGiftSubscriptionsFromOrder, SUBSCRIPTION_CART_FIELDS } from "../lib/subscription-from-order";
|
import { createGiftSubscriptionsFromOrder, SUBSCRIPTION_CART_FIELDS } from "../lib/subscription-from-order";
|
||||||
import { geschenkAnkuendigung } from "../lib/order-emails";
|
import { geschenkAbosAnkuendigen } from "../lib/geschenk-ankuendigung";
|
||||||
|
|
||||||
/** Für die Ankündigung lesbar machen, was im Modell technisch heißt. */
|
|
||||||
const RHYTHMUS: Record<string, string> = {
|
|
||||||
monthly: "monatlich",
|
|
||||||
quarterly: "vierteljährlich",
|
|
||||||
biannual: "halbjährlich",
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Legt aus einer bezahlten Bestellung die verschenkten Abos an und kündigt
|
* Legt aus einer Bestellung die verschenkten Abos an und kündigt sie beim
|
||||||
* sie beim Beschenkten an.
|
* Beschenkten an — die Ankündigung erst, wenn die Bestellung bezahlt ist.
|
||||||
*
|
*
|
||||||
* Hängt an `order.placed` und nicht am Zahlungseingang: das Geschenk läuft
|
* Hängt an `order.placed` und nicht am Zahlungseingang: das Geschenk läuft
|
||||||
* über die normale Kasse, und dort gilt die Bestellung als Abschluss.
|
* über die normale Kasse, und dort gilt die Bestellung als Abschluss.
|
||||||
@@ -53,35 +44,10 @@ export default async function giftSubscription({
|
|||||||
const angelegt = await createGiftSubscriptionsFromOrder({ container, order });
|
const angelegt = await createGiftSubscriptionsFromOrder({ container, order });
|
||||||
if (!angelegt.length) return;
|
if (!angelegt.length) return;
|
||||||
|
|
||||||
const notification: any = container.resolve(Modules.NOTIFICATION);
|
logger.info(`[geschenk] Bestellung ${order.display_id}: ${angelegt.length} Geschenk-Abo(s) angelegt.`);
|
||||||
const service: any = container.resolve(SUBSCRIPTION_MODULE);
|
// Angekündigt wird erst, wenn bezahlt ist — sonst wartet die Mail auf
|
||||||
|
// payment.captured (siehe geschenke-nach-zahlung.ts).
|
||||||
for (const abo of angelegt) {
|
await geschenkAbosAnkuendigen(container, order.id, logger);
|
||||||
// Die erste Lieferung geht mit dieser Bestellung raus, deshalb ist die
|
|
||||||
// Gesamtzahl eine mehr als die verbleibenden.
|
|
||||||
const gesamt = (abo.remaining_deliveries ?? 0) + 1;
|
|
||||||
const inhalt = geschenkAnkuendigung({
|
|
||||||
empfaengerName: abo.gift_recipient_name,
|
|
||||||
schenkerName: abo.gift_sender_name ?? null,
|
|
||||||
lieferungen: gesamt,
|
|
||||||
rhythmus: RHYTHMUS[abo.interval] ?? abo.interval,
|
|
||||||
groesse: abo.size,
|
|
||||||
});
|
|
||||||
|
|
||||||
await notification.createNotifications({
|
|
||||||
to: abo.gift_recipient_email,
|
|
||||||
channel: "email",
|
|
||||||
template: "gift-announcement",
|
|
||||||
content: inhalt,
|
|
||||||
data: { subscription_id: abo.id, order_id: order.id },
|
|
||||||
});
|
|
||||||
|
|
||||||
await service.updateSubscriptions({ id: abo.id, gift_announced_at: new Date() } as any);
|
|
||||||
logger.info(
|
|
||||||
`[geschenk] Abo ${abo.id} aus Bestellung ${order.display_id} angelegt, ` +
|
|
||||||
`${gesamt} Lieferungen, Ankündigung an ${abo.gift_recipient_email}.`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(
|
logger.error(
|
||||||
`[geschenk] Bestellung ${orderId} konnte nicht in ein Abo überführt werden: ${
|
`[geschenk] Bestellung ${orderId} konnte nicht in ein Abo überführt werden: ${
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { emailBestaetigenMail, passwortZuruecksetzenMail } from "../lib/order-emails";
|
||||||
|
import { EMAIL_VERIFICATION, normalisiereEmail } from "../lib/gastbestellungen";
|
||||||
|
|
||||||
|
type Daten = {
|
||||||
|
// auth.verification_requested
|
||||||
|
auth_identity_id?: string;
|
||||||
|
entity_id?: string;
|
||||||
|
entity_type?: string;
|
||||||
|
code?: string;
|
||||||
|
// auth.password_reset
|
||||||
|
actor_type?: string;
|
||||||
|
token?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mails rund ums Kundenkonto: Bestätigung der Mailadresse und Passwort
|
||||||
|
* zurücksetzen. Beide Abläufe sind in Medusa eingebaut, nur der Versand
|
||||||
|
* fehlt — Medusa löst ein Ereignis mit dem Code aus und überlässt die Mail
|
||||||
|
* dem Shop.
|
||||||
|
*/
|
||||||
|
export default async function kontoEmails({ event, container }: SubscriberArgs<Daten>) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
const storefront = process.env.STOREFRONT_URL ?? "http://localhost:4321";
|
||||||
|
const daten = event.data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let an: string | null = null;
|
||||||
|
let inhalt: { subject: string; html: string; text: string } | null = null;
|
||||||
|
let vorlage = "";
|
||||||
|
|
||||||
|
if (event.name === "auth.verification_requested") {
|
||||||
|
// Ohne Code war die Adresse schon bestätigt — nichts zu schicken.
|
||||||
|
if (daten.entity_type !== EMAIL_VERIFICATION.entity_type || !daten.code || !daten.entity_id) return;
|
||||||
|
|
||||||
|
// Nur an die Adresse des eigenen Kontos. Medusas offene Route
|
||||||
|
// /auth/verification/request nimmt jede Adresse an; ohne diese Prüfung
|
||||||
|
// ließe sich darüber Post an Fremde auslösen.
|
||||||
|
const auth: any = container.resolve(Modules.AUTH);
|
||||||
|
const identitaet = await auth.retrieveAuthIdentity(daten.auth_identity_id);
|
||||||
|
const kundeId = identitaet?.app_metadata?.customer_id;
|
||||||
|
if (!kundeId) return;
|
||||||
|
const kunde = await container.resolve<any>(Modules.CUSTOMER).retrieveCustomer(kundeId, { select: ["email"] });
|
||||||
|
if (normalisiereEmail(kunde.email) !== normalisiereEmail(daten.entity_id)) {
|
||||||
|
logger.warn(`[mail] Bestätigung für fremde Adresse bei ${kundeId} verworfen.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
an = kunde.email;
|
||||||
|
vorlage = "email-verification";
|
||||||
|
inhalt = emailBestaetigenMail(`${storefront}/konto/bestaetigen?code=${encodeURIComponent(daten.code)}`);
|
||||||
|
} else if (event.name === "auth.password_reset") {
|
||||||
|
// Admin-Konten setzen ihr Passwort über die Admin-Oberfläche zurück.
|
||||||
|
if (daten.actor_type !== "customer" || !daten.token || !daten.entity_id) return;
|
||||||
|
an = daten.entity_id;
|
||||||
|
vorlage = "password-reset";
|
||||||
|
inhalt = passwortZuruecksetzenMail(`${storefront}/konto/passwort-neu?token=${encodeURIComponent(daten.token)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!an || !inhalt) return;
|
||||||
|
const notification: any = container.resolve(Modules.NOTIFICATION);
|
||||||
|
await notification.createNotifications({ to: an, channel: "email", template: vorlage, content: inhalt });
|
||||||
|
logger.info(`[mail] ${vorlage} an ${an}.`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
`[mail] ${event.name} fehlgeschlagen: ${error instanceof Error ? error.message : String(error)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config: SubscriberConfig = {
|
||||||
|
event: ["auth.verification_requested", "auth.password_reset"],
|
||||||
|
};
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { stornoMail } from "../lib/order-emails";
|
||||||
|
import { erstattungenMitMollieAbgleichen } from "../lib/mollie-erstattung";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Storno einer Bestellung: Geld bei Mollie zurück und Kunde informieren.
|
||||||
|
*
|
||||||
|
* Beim Storno erstattet Medusa erfasste Zahlungen selbst, löst dabei aber
|
||||||
|
* kein payment.refunded aus — deshalb wird hier mit Mollie abgeglichen.
|
||||||
|
*
|
||||||
|
* Keine Mail, wenn die Bestellung wegen einer gescheiterten Abo-Abbuchung
|
||||||
|
* storniert wurde: Dazu geht schon eine eigene Mail raus.
|
||||||
|
*/
|
||||||
|
export default async function orderCanceledEmail({ event, container }: SubscriberArgs<{ id: string }>) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
const orderId = event.data.id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const erstattetBeiMollie = await erstattungenMitMollieAbgleichen(container, orderId, logger);
|
||||||
|
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const { data: orders } = await query.graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"display_id",
|
||||||
|
"email",
|
||||||
|
"currency_code",
|
||||||
|
"metadata",
|
||||||
|
"shipping_address.*",
|
||||||
|
"payment_collections.payments.refunds.amount",
|
||||||
|
],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order: any = orders?.[0];
|
||||||
|
if (!order?.email || order.metadata?.storno_grund === "abo_abbuchung") return;
|
||||||
|
|
||||||
|
// Alles, was zu dieser Bestellung erstattet ist — auch per Rechnung
|
||||||
|
// bezahltes, das im Admin als erstattet verbucht wurde.
|
||||||
|
const erstattet = (order.payment_collections ?? [])
|
||||||
|
.flatMap((c: any) => c.payments ?? [])
|
||||||
|
.flatMap((p: any) => p.refunds ?? [])
|
||||||
|
.reduce((summe: number, r: any) => summe + Number(r.amount ?? 0), 0);
|
||||||
|
|
||||||
|
await container.resolve<any>(Modules.NOTIFICATION).createNotifications({
|
||||||
|
to: order.email,
|
||||||
|
channel: "email",
|
||||||
|
template: "order-canceled",
|
||||||
|
content: stornoMail({
|
||||||
|
display_id: order.display_id,
|
||||||
|
shipping_address: order.shipping_address ?? null,
|
||||||
|
erstattet: Math.max(erstattet, erstattetBeiMollie),
|
||||||
|
waehrung: order.currency_code,
|
||||||
|
}),
|
||||||
|
data: { order_id: order.id, display_id: order.display_id },
|
||||||
|
});
|
||||||
|
logger.info(`[mail] Stornomail ${order.display_id} an ${order.email}.`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
`[storno] Bestellung ${orderId}: ${error instanceof Error ? error.message : (error as any)?.message ?? String(error)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config: SubscriberConfig = {
|
||||||
|
event: "order.canceled",
|
||||||
|
};
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { erstattungMail } from "../lib/order-emails";
|
||||||
|
import { erstattungenMitMollieAbgleichen } from "../lib/mollie-erstattung";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erstattung über "Refund" im Admin: Geld bei Mollie zurück und Kunde
|
||||||
|
* informieren — mit dem Betrag genau dieser Erstattung.
|
||||||
|
*/
|
||||||
|
export default async function paymentRefundedEmail({ event, container }: SubscriberArgs<{ id: string }>) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
const paymentId = event.data.id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const { data: zahlungen } = await query.graph({
|
||||||
|
entity: "payment",
|
||||||
|
fields: ["id", "currency_code", "refunds.amount", "refunds.created_at", "payment_collection.order.id"],
|
||||||
|
filters: { id: paymentId },
|
||||||
|
});
|
||||||
|
const zahlung: any = zahlungen?.[0];
|
||||||
|
const orderId = zahlung?.payment_collection?.order?.id;
|
||||||
|
if (!orderId) {
|
||||||
|
logger.warn(`[erstattung] Zahlung ${paymentId} gehört zu keiner Bestellung.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await erstattungenMitMollieAbgleichen(container, orderId, logger);
|
||||||
|
|
||||||
|
const letzte = [...(zahlung.refunds ?? [])].sort(
|
||||||
|
(a: any, b: any) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
|
||||||
|
)[0];
|
||||||
|
if (!letzte) return;
|
||||||
|
|
||||||
|
const { data: orders } = await query.graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: ["id", "display_id", "email", "shipping_address.*"],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order: any = orders?.[0];
|
||||||
|
if (!order?.email) return;
|
||||||
|
|
||||||
|
await container.resolve<any>(Modules.NOTIFICATION).createNotifications({
|
||||||
|
to: order.email,
|
||||||
|
channel: "email",
|
||||||
|
template: "payment-refunded",
|
||||||
|
content: erstattungMail({
|
||||||
|
display_id: order.display_id,
|
||||||
|
shipping_address: order.shipping_address ?? null,
|
||||||
|
betrag: Number(letzte.amount),
|
||||||
|
waehrung: zahlung.currency_code,
|
||||||
|
}),
|
||||||
|
data: { order_id: order.id, payment_id: paymentId },
|
||||||
|
});
|
||||||
|
logger.info(`[mail] Erstattungsmail ${order.display_id} an ${order.email} (${Number(letzte.amount).toFixed(2)} €).`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
`[erstattung] Zahlung ${paymentId}: ${error instanceof Error ? error.message : (error as any)?.message ?? String(error)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config: SubscriberConfig = {
|
||||||
|
event: "payment.refunded",
|
||||||
|
};
|
||||||
@@ -1,83 +1,20 @@
|
|||||||
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||||
import { Modules } from "@medusajs/framework/utils";
|
import { patenschaftenAnkuendigen } from "../lib/geschenk-ankuendigung";
|
||||||
import { patenschaftAnkuendigung } from "../lib/order-emails";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Kündigt eine verschenkte Bienenpatenschaft beim Beschenkten an.
|
* Kündigt eine verschenkte Bienenpatenschaft beim Beschenkten an.
|
||||||
*
|
*
|
||||||
* Ohne sie erführe er bis zur Ernte im Herbst nichts von seinem Geschenk.
|
* Ohne sie erführe er bis zur Ernte im Herbst nichts von seinem Geschenk.
|
||||||
* Die Mail nennt keine Beträge — bezahlt hat jemand anderes.
|
* Verschickt wird erst, wenn die Bestellung bezahlt ist; bei Kauf auf
|
||||||
*
|
* Rechnung holt geschenke-nach-zahlung.ts die Ankündigung nach.
|
||||||
* Doppelte Nachrichten verhindert der `idempotency_key`: das
|
|
||||||
* Benachrichtigungsmodul überspringt, was unter diesem Schlüssel schon
|
|
||||||
* erfolgreich verschickt wurde, versucht einen Fehlschlag aber erneut.
|
|
||||||
*/
|
*/
|
||||||
export default async function sponsorshipAnnouncement({
|
export default async function sponsorshipAnnouncement({ event, container }: SubscriberArgs<{ id: string }>) {
|
||||||
event,
|
|
||||||
container,
|
|
||||||
}: SubscriberArgs<{ id: string }>) {
|
|
||||||
const logger = container.resolve("logger");
|
const logger = container.resolve("logger");
|
||||||
const query = container.resolve("query");
|
|
||||||
const orderId = event.data.id;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { data: orders } = await query.graph({
|
await patenschaftenAnkuendigen(container, event.data.id, logger);
|
||||||
entity: "order",
|
|
||||||
fields: ["id", "display_id", "items.id", "items.metadata"],
|
|
||||||
filters: { id: orderId },
|
|
||||||
});
|
|
||||||
const order = orders?.[0];
|
|
||||||
if (!order) return;
|
|
||||||
|
|
||||||
// Auf die Felder herunterbrechen, die gebraucht werden — die Metadaten
|
|
||||||
// sind für den Übersetzer beliebig, hier soll es eindeutig sein.
|
|
||||||
const geschenke = (order.items ?? [])
|
|
||||||
.map((item: any) => ({
|
|
||||||
id: String(item?.id ?? ""),
|
|
||||||
name: String(item?.metadata?.sponsorship_name ?? ""),
|
|
||||||
email: String(item?.metadata?.sponsorship_recipient_email ?? ""),
|
|
||||||
von: item?.metadata?.sponsorship_sender_name
|
|
||||||
? String(item.metadata.sponsorship_sender_name)
|
|
||||||
: null,
|
|
||||||
istGeschenk: item?.metadata?.sponsorship_gift === true,
|
|
||||||
}))
|
|
||||||
.filter((g) => g.istGeschenk && g.name && g.email);
|
|
||||||
|
|
||||||
if (!geschenke.length) return;
|
|
||||||
|
|
||||||
const notification: any = container.resolve(Modules.NOTIFICATION);
|
|
||||||
|
|
||||||
for (const item of geschenke) {
|
|
||||||
const inhalt = patenschaftAnkuendigung({
|
|
||||||
name: item.name,
|
|
||||||
schenkerName: item.von,
|
|
||||||
});
|
|
||||||
|
|
||||||
const erzeugt = await notification.createNotifications({
|
|
||||||
to: item.email,
|
|
||||||
channel: "email",
|
|
||||||
template: "sponsorship-announcement",
|
|
||||||
content: inhalt,
|
|
||||||
// Je Bestellposten genau eine Ankündigung.
|
|
||||||
idempotency_key: `patenschaft-ankuendigung-${item.id}`,
|
|
||||||
data: { order_id: order.id, line_item_id: item.id },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Das Modul gibt nichts zurück, wenn es unter diesem Schlüssel schon
|
|
||||||
// verschickt hat. Das Protokoll soll keinen Versand behaupten, der
|
|
||||||
// gar nicht stattgefunden hat.
|
|
||||||
const verschickt = Array.isArray(erzeugt) ? erzeugt.length > 0 : Boolean(erzeugt);
|
|
||||||
logger.info(
|
|
||||||
verschickt
|
|
||||||
? `[patenschaft] Ankündigung zu Bestellung ${order.display_id} an ` +
|
|
||||||
`${item.email} (auf ${item.name}).`
|
|
||||||
: `[patenschaft] Ankündigung zu Bestellung ${order.display_id} war schon ` +
|
|
||||||
`verschickt, übersprungen.`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(
|
logger.error(
|
||||||
`[patenschaft] Ankündigung für ${orderId} fehlgeschlagen: ${
|
`[patenschaft] Ankündigung für ${event.data.id} fehlgeschlagen: ${
|
||||||
error instanceof Error ? error.message : String(error)
|
error instanceof Error ? error.message : String(error)
|
||||||
}`
|
}`
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -106,7 +106,10 @@ services:
|
|||||||
# Frontend und Backend teilen sich die Domain. Ohne diese beiden schickt
|
# Frontend und Backend teilen sich die Domain. Ohne diese beiden schickt
|
||||||
# Mollie den Kunden nach localhost zurück und meldet die Zahlung nie.
|
# Mollie den Kunden nach localhost zurück und meldet die Zahlung nie.
|
||||||
MOLLIE_WEBHOOK_URL: ${MEDUSA_BACKEND_URL}/hooks/mollie
|
MOLLIE_WEBHOOK_URL: ${MEDUSA_BACKEND_URL}/hooks/mollie
|
||||||
STOREFRONT_URL: ${MEDUSA_BACKEND_URL}
|
# Adresse des Shops für Links in Mails (Einladung, Passwort, Bestätigung).
|
||||||
|
# Ohne eigenen Wert die Backend-Adresse — passt nur, wenn beide unter
|
||||||
|
# einer Domain laufen. Im Testsystem auf https://test.place4bees.com setzen.
|
||||||
|
STOREFRONT_URL: ${STOREFRONT_URL:-${MEDUSA_BACKEND_URL}}
|
||||||
SMTP_HOST: ${SMTP_HOST:-}
|
SMTP_HOST: ${SMTP_HOST:-}
|
||||||
SMTP_PORT: ${SMTP_PORT:-}
|
SMTP_PORT: ${SMTP_PORT:-}
|
||||||
SMTP_USER: ${SMTP_USER:-}
|
SMTP_USER: ${SMTP_USER:-}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export default defineConfig({
|
|||||||
server: {
|
server: {
|
||||||
// Lets us test host-based behavior (hhonig.de vs. place4bees.com) locally
|
// Lets us test host-based behavior (hhonig.de vs. place4bees.com) locally
|
||||||
// by sending a custom Host header against the dev server.
|
// by sending a custom Host header against the dev server.
|
||||||
allowedHosts: ['hhonig.de', 'place4bees.com'],
|
allowedHosts: ['hhonig.de', 'place4bees.com', 'shop.hhonig.de'],
|
||||||
// Produktbilder stehen in der Datenbank als /static/… ohne Domain, damit
|
// Produktbilder stehen in der Datenbank als /static/… ohne Domain, damit
|
||||||
// sie in jeder Umgebung stimmen. Im Betrieb löst der Reverse Proxy das
|
// sie in jeder Umgebung stimmen. Im Betrieb löst der Reverse Proxy das
|
||||||
// auf; hier in der Entwicklung übernimmt das dieser Eintrag.
|
// auf; hier in der Entwicklung übernimmt das dieser Eintrag.
|
||||||
|
|||||||
|
After Width: | Height: | Size: 314 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 265 KiB |
|
After Width: | Height: | Size: 258 KiB |
|
After Width: | Height: | Size: 170 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 105 KiB |
|
After Width: | Height: | Size: 104 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 171 KiB |