aktueller stand
@@ -2,6 +2,24 @@ import { loadEnv, defineConfig } from '@medusajs/framework/utils'
|
||||
|
||||
loadEnv(process.env.NODE_ENV || 'development', process.cwd())
|
||||
|
||||
// DHL braucht alle acht Werte; fehlt einer, wirft der Provider beim Start.
|
||||
const dhlEnabled = Boolean(
|
||||
process.env.DHL_API_KEY &&
|
||||
process.env.DHL_USERNAME &&
|
||||
process.env.DHL_PASSWORD &&
|
||||
process.env.DHL_BILLING_NUMBER &&
|
||||
process.env.DHL_SHIPPER_NAME &&
|
||||
process.env.DHL_SHIPPER_STREET &&
|
||||
process.env.DHL_SHIPPER_POSTAL_CODE &&
|
||||
process.env.DHL_SHIPPER_CITY
|
||||
)
|
||||
const sendcloudEnabled = Boolean(
|
||||
process.env.SENDCLOUD_PUBLIC_KEY && process.env.SENDCLOUD_SECRET_KEY
|
||||
)
|
||||
// Ohne Mailserver wird nicht verschickt, sondern protokolliert. So läuft die
|
||||
// Entwicklung ohne Zugangsdaten und niemand bekommt Testmails.
|
||||
const smtpEnabled = Boolean(process.env.SMTP_HOST && process.env.MAIL_FROM)
|
||||
|
||||
module.exports = defineConfig({
|
||||
projectConfig: {
|
||||
databaseUrl: process.env.DATABASE_URL,
|
||||
@@ -19,8 +37,18 @@ module.exports = defineConfig({
|
||||
resolve: "@easypayment/medusa-payment-paypal",
|
||||
options: {},
|
||||
},
|
||||
{
|
||||
// Geschenkgutscheine mit Restguthaben: Code, Guthabenkonto und die
|
||||
// Verrechnung im Warenkorb kommen aus dem offiziellen Plugin.
|
||||
resolve: "@medusajs/loyalty-plugin",
|
||||
options: {},
|
||||
},
|
||||
],
|
||||
modules: [
|
||||
{
|
||||
// Honig-Abos: eigenes Modell, weil Medusa keine Abos kennt.
|
||||
resolve: "./src/modules/subscription",
|
||||
},
|
||||
{
|
||||
resolve: "@medusajs/medusa/file",
|
||||
options: {
|
||||
@@ -35,6 +63,36 @@ module.exports = defineConfig({
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// Kundenmails: Bestellbestätigung und Versandnachricht. Genau ein
|
||||
// Anbieter je Kanal — zwei für "email" würde das Modul nicht auflösen.
|
||||
resolve: "@medusajs/medusa/notification",
|
||||
options: {
|
||||
providers: [
|
||||
smtpEnabled
|
||||
? {
|
||||
resolve: "./src/modules/email-notification",
|
||||
id: "email-smtp",
|
||||
options: {
|
||||
channels: ["email"],
|
||||
host: process.env.SMTP_HOST,
|
||||
port: Number(process.env.SMTP_PORT || 587),
|
||||
secure: process.env.SMTP_SECURE === "true",
|
||||
user: process.env.SMTP_USER,
|
||||
pass: process.env.SMTP_PASSWORD,
|
||||
from: process.env.MAIL_FROM,
|
||||
},
|
||||
}
|
||||
: {
|
||||
resolve: "@medusajs/notification-local",
|
||||
id: "local",
|
||||
options: {
|
||||
channels: ["email"],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
resolve: "@medusajs/medusa/payment",
|
||||
options: {
|
||||
@@ -56,5 +114,55 @@ module.exports = defineConfig({
|
||||
],
|
||||
},
|
||||
},
|
||||
// Carrier werden einzeln registriert, sobald ihre Zugangsdaten gesetzt
|
||||
// sind. Die Service-Konstruktoren werfen ohne Zugangsdaten — ohne diese
|
||||
// Bedingung käme der Server bei jedem ohne Vertrag nicht mehr hoch.
|
||||
...(dhlEnabled || sendcloudEnabled
|
||||
? [
|
||||
{
|
||||
resolve: "@medusajs/medusa/fulfillment",
|
||||
options: {
|
||||
providers: [
|
||||
...(dhlEnabled
|
||||
? [
|
||||
{
|
||||
resolve: "./src/modules/dhl-fulfillment",
|
||||
id: "dhl",
|
||||
options: {
|
||||
api_key: process.env.DHL_API_KEY,
|
||||
username: process.env.DHL_USERNAME,
|
||||
password: process.env.DHL_PASSWORD,
|
||||
billing_number: process.env.DHL_BILLING_NUMBER,
|
||||
shipper_name: process.env.DHL_SHIPPER_NAME,
|
||||
shipper_street: process.env.DHL_SHIPPER_STREET,
|
||||
shipper_postal_code: process.env.DHL_SHIPPER_POSTAL_CODE,
|
||||
shipper_city: process.env.DHL_SHIPPER_CITY,
|
||||
shipper_country: process.env.DHL_SHIPPER_COUNTRY,
|
||||
sandbox: process.env.DHL_SANDBOX === "true",
|
||||
// Solange gesetzt, prüft DHL die Daten nur und
|
||||
// erzeugt weder Label noch Portokosten.
|
||||
validate_only: process.env.DHL_VALIDATE_ONLY === "true",
|
||||
default_item_weight_g: Number(process.env.DHL_DEFAULT_ITEM_WEIGHT_G || 600),
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(sendcloudEnabled
|
||||
? [
|
||||
{
|
||||
resolve: "./src/modules/sendcloud-fulfillment",
|
||||
id: "sendcloud",
|
||||
options: {
|
||||
public_key: process.env.SENDCLOUD_PUBLIC_KEY,
|
||||
secret_key: process.env.SENDCLOUD_SECRET_KEY,
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
})
|
||||
|
||||
@@ -30,11 +30,18 @@
|
||||
"@medusajs/dashboard": "2.17.0",
|
||||
"@medusajs/draft-order": "2.17.0",
|
||||
"@medusajs/framework": "2.17.0",
|
||||
"@medusajs/loyalty-plugin": "2.17.0",
|
||||
"@medusajs/medusa": "2.17.0",
|
||||
"@medusajs/ui": "4.1.15",
|
||||
"@mollie/api-client": "^4.6.0",
|
||||
"@tanstack/react-query": "5.64.2",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"nodemailer": "^10.0.3",
|
||||
"onnxruntime-node": "^1.27.0",
|
||||
"pdfkit": "^0.19.1",
|
||||
"react-i18next": "13.5.0",
|
||||
"react-router-dom": "6.30.3",
|
||||
"sharp": "^0.35.3",
|
||||
"zod": "4.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -43,6 +50,7 @@
|
||||
"@swc/jest": "^0.2.36",
|
||||
"@types/jest": "^29.5.13",
|
||||
"@types/node": "^20.12.11",
|
||||
"@types/pdfkit": "^0.17.6",
|
||||
"@types/react": "^18.3.2",
|
||||
"@types/react-dom": "^18.2.25",
|
||||
"jest": "^29.7.0",
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { defineRouteConfig } from "@medusajs/admin-sdk";
|
||||
import { Badge, Button, Container, Heading, Input, Label, Text, toast } from "@medusajs/ui";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
type Data = {
|
||||
settings: { discount_percent: number; discount_label: string | null };
|
||||
sizes: { size: string; varieties: number }[];
|
||||
counts: { active: number; paused: number; canceled: number };
|
||||
};
|
||||
|
||||
const AboSettingsPage = () => {
|
||||
const [data, setData] = useState<Data | null>(null);
|
||||
const [percent, setPercent] = useState("0");
|
||||
const [label, setLabel] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const load = async () => {
|
||||
const res = await fetch("/admin/subscription-settings", { credentials: "include" });
|
||||
if (!res.ok) {
|
||||
toast.error("Fehler", { description: `Einstellungen nicht ladbar (${res.status}).` });
|
||||
return;
|
||||
}
|
||||
const json: Data = await res.json();
|
||||
setData(json);
|
||||
setPercent(String(json.settings.discount_percent));
|
||||
setLabel(json.settings.discount_label ?? "");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch("/admin/subscription-settings", {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
discount_percent: Number(percent),
|
||||
discount_label: label.trim() || null,
|
||||
}),
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) throw new Error(json?.message ?? "Speichern fehlgeschlagen.");
|
||||
toast.success("Gespeichert", {
|
||||
description: `Abo-Rabatt liegt bei ${json.settings.discount_percent} %.`,
|
||||
});
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error("Nicht gespeichert", {
|
||||
description: err instanceof Error ? err.message : "Unbekannter Fehler.",
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const parsed = Number(percent);
|
||||
const invalid = !Number.isInteger(parsed) || parsed < 0 || parsed > 100;
|
||||
|
||||
return (
|
||||
<Container className="divide-y p-0">
|
||||
<div className="px-6 py-4">
|
||||
<Heading level="h1">Honig-Abo</Heading>
|
||||
<Text className="text-ui-fg-subtle mt-1" size="small">
|
||||
Rabatt und Hinweistext für alle Abo-Lieferungen.
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 px-6 py-5">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="discount">Abo-Rabatt in Prozent</Label>
|
||||
<Input
|
||||
id="discount"
|
||||
type="number"
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
value={percent}
|
||||
onChange={(e) => setPercent(e.target.value)}
|
||||
className="max-w-32"
|
||||
/>
|
||||
<Text size="small" className={invalid ? "text-ui-fg-error" : "text-ui-fg-subtle"}>
|
||||
{invalid
|
||||
? "Ganze Zahl zwischen 0 und 100."
|
||||
: parsed === 0
|
||||
? "0 % — das Abo kostet dasselbe wie der Einzelkauf."
|
||||
: `Jede Lieferung ist ${parsed} % günstiger als der Einzelkauf.`}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="label">Hinweistext im Shop (optional)</Label>
|
||||
<Input
|
||||
id="label"
|
||||
value={label}
|
||||
placeholder="z. B. 10 % Abo-Rabatt auf jede Lieferung"
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
className="max-w-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button onClick={save} isLoading={saving} disabled={invalid}>
|
||||
Speichern
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-5">
|
||||
<Heading level="h2">Wählbare Größen</Heading>
|
||||
<Text size="small" className="text-ui-fg-subtle mt-1">
|
||||
Im Abo stehen nur diese Größen zur Auswahl. Die Zahl dahinter ist der Zufallspool.
|
||||
</Text>
|
||||
<div className="mt-3 flex gap-2">
|
||||
{data?.sizes.map((entry) => (
|
||||
<Badge key={entry.size} color={entry.varieties > 0 ? "grey" : "red"}>
|
||||
{entry.size} · {entry.varieties} Sorten
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-5">
|
||||
<Heading level="h2">Laufende Abos</Heading>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<Badge color="green">{data?.counts.active ?? 0} aktiv</Badge>
|
||||
<Badge color="orange">{data?.counts.paused ?? 0} pausiert</Badge>
|
||||
<Badge color="grey">{data?.counts.canceled ?? 0} gekündigt</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export const config = defineRouteConfig({
|
||||
label: "Honig-Abo",
|
||||
});
|
||||
|
||||
export default AboSettingsPage;
|
||||
@@ -0,0 +1,139 @@
|
||||
import { defineRouteConfig } from "@medusajs/admin-sdk";
|
||||
import { Badge, Button, Container, Heading, Input, Label, Text, toast } from "@medusajs/ui";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
type Versandart = {
|
||||
id: string;
|
||||
name: string;
|
||||
base_amount: number | null;
|
||||
free_shipping: boolean;
|
||||
};
|
||||
|
||||
type Data = {
|
||||
settings: { free_shipping_threshold: number | null };
|
||||
shipping_options: Versandart[];
|
||||
};
|
||||
|
||||
const VersandPage = () => {
|
||||
const [data, setData] = useState<Data | null>(null);
|
||||
const [schwelle, setSchwelle] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const load = async () => {
|
||||
const res = await fetch("/admin/shipping-settings", { credentials: "include" });
|
||||
if (!res.ok) {
|
||||
toast.error("Fehler", { description: `Einstellungen nicht ladbar (${res.status}).` });
|
||||
return;
|
||||
}
|
||||
const json: Data = await res.json();
|
||||
setData(json);
|
||||
setSchwelle(json.settings.free_shipping_threshold?.toString() ?? "");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
// Leeres Feld heißt: kein kostenfreier Versand. Der Shop schweigt dann dazu.
|
||||
const leer = schwelle.trim() === "";
|
||||
const parsed = Number(schwelle);
|
||||
const invalid = !leer && (!Number.isInteger(parsed) || parsed <= 0);
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch("/admin/shipping-settings", {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ free_shipping_threshold: leer ? null : parsed }),
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) throw new Error(json?.message ?? "Speichern fehlgeschlagen.");
|
||||
toast.success("Gespeichert", {
|
||||
description: json.settings.free_shipping_threshold
|
||||
? `Ab ${json.settings.free_shipping_threshold} € versandkostenfrei — ${json.geaendert} Versandart(en) angepasst.`
|
||||
: `Kein kostenfreier Versand — ${json.geaendert} Versandart(en) angepasst.`,
|
||||
});
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error("Nicht gespeichert", {
|
||||
description: err instanceof Error ? err.message : "Unbekannter Fehler.",
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Container className="divide-y p-0">
|
||||
<div className="px-6 py-4">
|
||||
<Heading level="h1">Versand</Heading>
|
||||
<Text className="text-ui-fg-subtle mt-1" size="small">
|
||||
Ab welchem Warenwert der Versand entfällt. Der Wert steht im Shop und
|
||||
liegt zugleich als Preis von 0 € an den Versandarten.
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 px-6 py-5">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="schwelle">Versandkostenfrei ab (Euro)</Label>
|
||||
<Input
|
||||
id="schwelle"
|
||||
type="number"
|
||||
min={1}
|
||||
step={1}
|
||||
value={schwelle}
|
||||
placeholder="leer = kein kostenfreier Versand"
|
||||
onChange={(e) => setSchwelle(e.target.value)}
|
||||
className="max-w-32"
|
||||
/>
|
||||
<Text size="small" className={invalid ? "text-ui-fg-error" : "text-ui-fg-subtle"}>
|
||||
{invalid
|
||||
? "Ganze Zahl in Euro, größer als 0."
|
||||
: leer
|
||||
? "Kein kostenfreier Versand — der Shop weist dann auch nicht darauf hin."
|
||||
: `Ab einem Warenwert von ${parsed} € kostet der Versand nichts.`}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button onClick={save} isLoading={saving} disabled={invalid}>
|
||||
Speichern
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-5">
|
||||
<Heading level="h2">Betroffene Versandarten</Heading>
|
||||
<Text size="small" className="text-ui-fg-subtle mt-1">
|
||||
Nur Versandarten mit festem Preis. Berechnete Preise kommen vom
|
||||
Versanddienstleister und lassen sich hier nicht auf 0 setzen. Eine
|
||||
neu angelegte Versandart übernimmt die Schwelle erst, wenn hier
|
||||
wieder gespeichert wird.
|
||||
</Text>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{data?.shipping_options.length ? (
|
||||
data.shipping_options.map((option) => (
|
||||
<Badge key={option.id} color={option.free_shipping ? "green" : "grey"}>
|
||||
{option.name}
|
||||
{option.base_amount != null ? ` · ${option.base_amount} €` : ""}
|
||||
{option.free_shipping ? " · Schwelle aktiv" : ""}
|
||||
</Badge>
|
||||
))
|
||||
) : (
|
||||
<Text size="small" className="text-ui-fg-subtle">
|
||||
Keine Versandart mit festem Preis gefunden.
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export const config = defineRouteConfig({
|
||||
label: "Versand",
|
||||
});
|
||||
|
||||
export default VersandPage;
|
||||
@@ -0,0 +1,52 @@
|
||||
import { defineWidgetConfig } from "@medusajs/admin-sdk";
|
||||
import { Button, Container, Heading, toast } from "@medusajs/ui";
|
||||
import type { DetailWidgetProps, AdminOrder } from "@medusajs/framework/types";
|
||||
import { useState } from "react";
|
||||
|
||||
const OrderInvoiceWidget = ({ data: order }: DetailWidgetProps<AdminOrder>) => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleDownload = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`/admin/orders/${order.id}/invoice`, {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Rechnung konnte nicht geladen werden (${res.status}).`);
|
||||
}
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = `rechnung-${order.display_id}.pdf`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
} 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">Rechnung</Heading>
|
||||
<Button variant="secondary" size="small" isLoading={loading} onClick={handleDownload}>
|
||||
Rechnung herunterladen
|
||||
</Button>
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export const config = defineWidgetConfig({
|
||||
zone: "order.details.side.after",
|
||||
});
|
||||
|
||||
export default OrderInvoiceWidget;
|
||||
@@ -0,0 +1,264 @@
|
||||
import { defineWidgetConfig } from "@medusajs/admin-sdk";
|
||||
import { Button, Container, Heading, Text, toast } from "@medusajs/ui";
|
||||
import type { DetailWidgetProps, AdminProduct } from "@medusajs/framework/types";
|
||||
import { useEffect, useState, type CSSProperties } from "react";
|
||||
|
||||
interface BackgroundPreset {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const COLOR_PRESETS = [
|
||||
{ label: "Honig-Orange", value: "#f8ac11" },
|
||||
{ label: "Weiß", value: "#ffffff" },
|
||||
{ label: "Hellgrau", value: "#f2f2ef" },
|
||||
{ label: "Dunkel", value: "#1a1a1a" },
|
||||
];
|
||||
|
||||
// Transparency checkerboard so the cutout preview is actually visible
|
||||
// against Medusa admin's own white panel background — inline style since
|
||||
// admin widgets only get whatever Tailwind classes Medusa's dashboard build
|
||||
// already includes, not arbitrary custom ones.
|
||||
const checkerboardStyle: CSSProperties = {
|
||||
backgroundImage:
|
||||
"linear-gradient(45deg, #ddd 25%, transparent 25%), linear-gradient(-45deg, #ddd 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ddd 75%), linear-gradient(-45deg, transparent 75%, #ddd 75%)",
|
||||
backgroundSize: "16px 16px",
|
||||
backgroundPosition: "0 0, 0 8px, 8px -8px, -8px 0px",
|
||||
};
|
||||
|
||||
const ProductBackgroundWidget = ({ data: product }: DetailWidgetProps<AdminProduct>) => {
|
||||
const images = product.images ?? [];
|
||||
const [selectedImageUrl, setSelectedImageUrl] = useState(images[0]?.url ?? "");
|
||||
const [cutoutUrl, setCutoutUrl] = useState<string | null>(null);
|
||||
const [removing, setRemoving] = useState(false);
|
||||
const [backgroundMode, setBackgroundMode] = useState<"color" | "image" | "preset">("color");
|
||||
const [color, setColor] = useState(COLOR_PRESETS[0].value);
|
||||
const [backgroundImageUrl, setBackgroundImageUrl] = useState("");
|
||||
const [presets, setPresets] = useState<BackgroundPreset[]>([]);
|
||||
const [selectedPreset, setSelectedPreset] = useState("");
|
||||
const [applying, setApplying] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/admin/background-presets", { credentials: "include" })
|
||||
.then((res) => res.json())
|
||||
.then((body) => setPresets(body.presets ?? []))
|
||||
.catch(() => setPresets([]));
|
||||
}, []);
|
||||
|
||||
if (images.length === 0) return null;
|
||||
|
||||
const handleRemoveBackground = async () => {
|
||||
if (!selectedImageUrl) return;
|
||||
setRemoving(true);
|
||||
setCutoutUrl(null);
|
||||
try {
|
||||
const res = await fetch(`/admin/products/${product.id}/remove-background`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ image_url: selectedImageUrl }),
|
||||
});
|
||||
if (!res.ok) throw new Error();
|
||||
const body = await res.json();
|
||||
setCutoutUrl(body.cutout_url as string);
|
||||
} catch {
|
||||
toast.error("Fehler", { description: "Hintergrund konnte nicht entfernt werden." });
|
||||
} finally {
|
||||
setRemoving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleApply = async () => {
|
||||
if (!cutoutUrl) return;
|
||||
if (backgroundMode === "image" && !backgroundImageUrl) return;
|
||||
if (backgroundMode === "preset" && !selectedPreset) return;
|
||||
setApplying(true);
|
||||
try {
|
||||
const backgroundPayload =
|
||||
backgroundMode === "color"
|
||||
? { color }
|
||||
: backgroundMode === "preset"
|
||||
? { background_preset: selectedPreset }
|
||||
: { background_image_url: backgroundImageUrl };
|
||||
const res = await fetch(`/admin/products/${product.id}/apply-background`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
cutout_url: cutoutUrl,
|
||||
...backgroundPayload,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error();
|
||||
toast.success("Gespeichert", { description: "Das neue Bild wurde zur Produktgalerie hinzugefügt." });
|
||||
setCutoutUrl(null);
|
||||
window.location.reload();
|
||||
} catch {
|
||||
toast.error("Fehler", { description: "Hintergrund konnte nicht übernommen werden." });
|
||||
} finally {
|
||||
setApplying(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Container className="divide-y p-0">
|
||||
<div className="px-6 py-4">
|
||||
<Heading level="h2">Hintergrund freistellen</Heading>
|
||||
<Text size="small" className="text-ui-fg-subtle mt-1">
|
||||
Bild auswählen, Hintergrund automatisch entfernen und durch eine Farbe oder ein anderes Bild ersetzen.
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div className="px-6 py-4 flex flex-col gap-4">
|
||||
<div>
|
||||
<Text size="small" weight="plus" className="mb-2">
|
||||
1. Bild auswählen
|
||||
</Text>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{images.map((image) => (
|
||||
<button
|
||||
key={image.id ?? image.url}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSelectedImageUrl(image.url);
|
||||
setCutoutUrl(null);
|
||||
}}
|
||||
style={{
|
||||
border: selectedImageUrl === image.url ? "2px solid #f8ac11" : "2px solid transparent",
|
||||
borderRadius: 8,
|
||||
padding: 2,
|
||||
cursor: "pointer",
|
||||
background: "none",
|
||||
}}
|
||||
>
|
||||
<img src={image.url} alt="" style={{ width: 64, height: 64, objectFit: "cover", borderRadius: 6 }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<Button className="mt-3" size="small" variant="secondary" isLoading={removing} onClick={handleRemoveBackground}>
|
||||
Hintergrund entfernen
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{cutoutUrl && (
|
||||
<div className="border-t border-ui-border-base pt-4">
|
||||
<Text size="small" weight="plus" className="mb-2">
|
||||
2. Vorschau & neuer Hintergrund
|
||||
</Text>
|
||||
<div style={{ ...checkerboardStyle, width: 160, height: 160, borderRadius: 8, overflow: "hidden" }}>
|
||||
<img src={cutoutUrl} alt="Freigestelltes Bild" style={{ width: "100%", height: "100%", objectFit: "contain" }} />
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex gap-2">
|
||||
<Button
|
||||
size="small"
|
||||
variant={backgroundMode === "color" ? "primary" : "secondary"}
|
||||
onClick={() => setBackgroundMode("color")}
|
||||
>
|
||||
Farbe
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
variant={backgroundMode === "image" ? "primary" : "secondary"}
|
||||
onClick={() => setBackgroundMode("image")}
|
||||
>
|
||||
Bild
|
||||
</Button>
|
||||
{presets.length > 0 && (
|
||||
<Button
|
||||
size="small"
|
||||
variant={backgroundMode === "preset" ? "primary" : "secondary"}
|
||||
onClick={() => setBackgroundMode("preset")}
|
||||
>
|
||||
Motiv
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{backgroundMode === "color" && (
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
{COLOR_PRESETS.map((preset) => (
|
||||
<button
|
||||
key={preset.value}
|
||||
type="button"
|
||||
title={preset.label}
|
||||
onClick={() => setColor(preset.value)}
|
||||
style={{
|
||||
width: 28,
|
||||
height: 28,
|
||||
borderRadius: "50%",
|
||||
background: preset.value,
|
||||
border: color === preset.value ? "2px solid #f8ac11" : "1px solid #ccc",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<input type="color" value={color} onChange={(e) => setColor(e.target.value)} style={{ width: 36, height: 28, padding: 0, border: "none" }} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{backgroundMode === "image" && (
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{images.map((image) => (
|
||||
<button
|
||||
key={image.id ?? image.url}
|
||||
type="button"
|
||||
onClick={() => setBackgroundImageUrl(image.url)}
|
||||
style={{
|
||||
border: backgroundImageUrl === image.url ? "2px solid #f8ac11" : "2px solid transparent",
|
||||
borderRadius: 8,
|
||||
padding: 2,
|
||||
cursor: "pointer",
|
||||
background: "none",
|
||||
}}
|
||||
>
|
||||
<img src={image.url} alt="" style={{ width: 64, height: 64, objectFit: "cover", borderRadius: 6 }} />
|
||||
</button>
|
||||
))}
|
||||
<Text size="small" className="text-ui-fg-subtle w-full">
|
||||
Um ein neues Hintergrundbild zu verwenden, es zuerst normal zur Produktgalerie hochladen.
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{backgroundMode === "preset" && (
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{presets.map((preset) => (
|
||||
<button
|
||||
key={preset.key}
|
||||
type="button"
|
||||
title={preset.label}
|
||||
onClick={() => setSelectedPreset(preset.key)}
|
||||
style={{
|
||||
border: selectedPreset === preset.key ? "2px solid #f8ac11" : "2px solid transparent",
|
||||
borderRadius: 8,
|
||||
padding: 2,
|
||||
cursor: "pointer",
|
||||
background: "none",
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={`/admin/background-presets/${preset.key}`}
|
||||
alt={preset.label}
|
||||
style={{ width: 64, height: 64, objectFit: "cover", borderRadius: 6 }}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button className="mt-4" size="small" isLoading={applying} onClick={handleApply}>
|
||||
Übernehmen & zur Galerie hinzufügen
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export const config = defineWidgetConfig({
|
||||
zone: "product.details.after",
|
||||
});
|
||||
|
||||
export default ProductBackgroundWidget;
|
||||
@@ -0,0 +1,17 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import fs from "node:fs";
|
||||
import { getPresetPath } from "../../../../lib/background-presets";
|
||||
|
||||
// Streams a preset's actual image bytes — used both as the <img> src for
|
||||
// the widget's thumbnail and as the source the apply-background route
|
||||
// reads from when a preset (rather than a color or uploaded image) is
|
||||
// chosen.
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
const filePath = getPresetPath(req.params.key);
|
||||
if (!filePath) {
|
||||
res.status(404).json({ message: "Unbekanntes Hintergrund-Motiv." });
|
||||
return;
|
||||
}
|
||||
res.setHeader("Content-Type", "image/jpeg");
|
||||
fs.createReadStream(filePath).pipe(res);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { BACKGROUND_PRESETS } from "../../../lib/background-presets";
|
||||
|
||||
// Lists the curated preset backgrounds for the widget's thumbnail picker —
|
||||
// the actual bytes are served per-key by the [key] route below.
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
res.json({
|
||||
presets: BACKGROUND_PRESETS.map((p) => ({ key: p.key, label: p.label })),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { handleInvoiceRequest } from "../../../../../lib/invoice-handler";
|
||||
|
||||
// GET /admin/orders/:id/invoice — lets the store owner download an order's
|
||||
// invoice as PDF from the admin dashboard (requires admin auth, same as any
|
||||
// other /admin route).
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
await handleInvoiceRequest(req, res);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import fs from "node:fs/promises";
|
||||
import { replaceBackground } from "../../../../../lib/background-removal";
|
||||
import { getPresetPath } from "../../../../../lib/background-presets";
|
||||
|
||||
interface ApplyBackgroundBody {
|
||||
cutout_url?: string;
|
||||
color?: string;
|
||||
background_image_url?: string;
|
||||
background_preset?: string;
|
||||
}
|
||||
|
||||
// Composites a cutout (from remove-background/route.ts) over a flat color,
|
||||
// another one of the product's own images, or a curated preset scene, then
|
||||
// appends the result to the product's image gallery — the original photo
|
||||
// is left untouched.
|
||||
export async function POST(req: MedusaRequest<ApplyBackgroundBody>, res: MedusaResponse) {
|
||||
const { cutout_url, color, background_image_url, background_preset } = req.body as ApplyBackgroundBody;
|
||||
if (!cutout_url || (!color && !background_image_url && !background_preset)) {
|
||||
res.status(400).json({ message: "cutout_url und eines von color, background_image_url oder background_preset sind erforderlich." });
|
||||
return;
|
||||
}
|
||||
|
||||
const cutoutRes = await fetch(cutout_url).catch(() => null);
|
||||
if (!cutoutRes || !cutoutRes.ok) {
|
||||
res.status(400).json({ message: "Freigestelltes Bild konnte nicht geladen werden." });
|
||||
return;
|
||||
}
|
||||
const cutoutBuffer = Buffer.from(await cutoutRes.arrayBuffer());
|
||||
|
||||
let backgroundImageBuffer: Buffer | undefined;
|
||||
if (background_preset) {
|
||||
const presetPath = getPresetPath(background_preset);
|
||||
if (!presetPath) {
|
||||
res.status(400).json({ message: "Unbekanntes Hintergrund-Motiv." });
|
||||
return;
|
||||
}
|
||||
backgroundImageBuffer = await fs.readFile(presetPath);
|
||||
} else if (background_image_url) {
|
||||
const bgRes = await fetch(background_image_url).catch(() => null);
|
||||
if (!bgRes || !bgRes.ok) {
|
||||
res.status(400).json({ message: "Hintergrundbild konnte nicht geladen werden." });
|
||||
return;
|
||||
}
|
||||
backgroundImageBuffer = Buffer.from(await bgRes.arrayBuffer());
|
||||
}
|
||||
|
||||
const finalImage = await replaceBackground(cutoutBuffer, { color, backgroundImage: backgroundImageBuffer });
|
||||
|
||||
const fileModuleService = req.scope.resolve(Modules.FILE);
|
||||
const file = await fileModuleService.createFiles({
|
||||
filename: `product-${Date.now()}.png`,
|
||||
mimeType: "image/png",
|
||||
content: finalImage.toString("base64"),
|
||||
access: "public",
|
||||
});
|
||||
|
||||
const productModuleService = req.scope.resolve(Modules.PRODUCT);
|
||||
const product = await productModuleService.retrieveProduct(req.params.id, { relations: ["images"] });
|
||||
const updatedImages = [...(product.images ?? []).map((img) => ({ url: img.url })), { url: file.url }];
|
||||
await productModuleService.updateProducts(req.params.id, { images: updatedImages });
|
||||
|
||||
res.json({ image: { url: file.url } });
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import { removeBackground } from "../../../../../lib/background-removal";
|
||||
|
||||
interface RemoveBackgroundBody {
|
||||
image_url?: string;
|
||||
}
|
||||
|
||||
// Takes one of the product's existing image URLs, cuts the subject out
|
||||
// (see lib/background-removal.ts) and stores the transparent-background
|
||||
// result as a new, standalone file — not yet attached to the product, so
|
||||
// the admin can preview it in the widget before deciding what background
|
||||
// to composite it onto next (see apply-background/route.ts).
|
||||
export async function POST(req: MedusaRequest<RemoveBackgroundBody>, res: MedusaResponse) {
|
||||
const { image_url } = req.body as RemoveBackgroundBody;
|
||||
if (!image_url) {
|
||||
res.status(400).json({ message: "image_url ist erforderlich." });
|
||||
return;
|
||||
}
|
||||
|
||||
const sourceRes = await fetch(image_url).catch(() => null);
|
||||
if (!sourceRes || !sourceRes.ok) {
|
||||
res.status(400).json({ message: "Bild konnte nicht geladen werden." });
|
||||
return;
|
||||
}
|
||||
const inputBuffer = Buffer.from(await sourceRes.arrayBuffer());
|
||||
|
||||
const cutout = await removeBackground(inputBuffer);
|
||||
|
||||
const fileModuleService = req.scope.resolve(Modules.FILE);
|
||||
const file = await fileModuleService.createFiles({
|
||||
filename: `cutout-${Date.now()}.png`,
|
||||
mimeType: "image/png",
|
||||
content: cutout.toString("base64"),
|
||||
access: "public",
|
||||
});
|
||||
|
||||
res.json({ cutout_url: file.url });
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { SUBSCRIPTION_MODULE } from "../../../modules/subscription";
|
||||
import { syncFreeShipping } from "../../../lib/free-shipping";
|
||||
|
||||
/** Versand-Einstellungen für die Admin-Oberfläche. */
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
const service: any = req.scope.resolve(SUBSCRIPTION_MODULE);
|
||||
const query = req.scope.resolve("query");
|
||||
|
||||
const settings = await service.getSettings();
|
||||
|
||||
// Damit auf der Seite steht, an welchen Versandarten die Schwelle hängt.
|
||||
const { data: options } = await query.graph({
|
||||
entity: "shipping_option",
|
||||
fields: ["id", "name", "price_type", "prices.amount", "prices.currency_code", "prices.price_rules.attribute"],
|
||||
});
|
||||
|
||||
res.json({
|
||||
settings: { free_shipping_threshold: settings.free_shipping_threshold },
|
||||
shipping_options: (options ?? [])
|
||||
.filter((option: any) => option.price_type === "flat")
|
||||
.map((option: any) => ({
|
||||
id: option.id,
|
||||
name: option.name,
|
||||
base_amount:
|
||||
(option.prices ?? []).find(
|
||||
(preis: any) => !(preis.price_rules ?? []).some((r: any) => r.attribute === "item_total")
|
||||
)?.amount ?? null,
|
||||
free_shipping: (option.prices ?? []).some((preis: any) =>
|
||||
(preis.price_rules ?? []).some((r: any) => r.attribute === "item_total")
|
||||
),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||
const service: any = req.scope.resolve(SUBSCRIPTION_MODULE);
|
||||
const body = req.body as { free_shipping_threshold?: number | null };
|
||||
|
||||
try {
|
||||
const settings = await service.updateSettings({
|
||||
free_shipping_threshold:
|
||||
body.free_shipping_threshold == null ? null : Number(body.free_shipping_threshold),
|
||||
});
|
||||
// Den Versandpreis sofort nachziehen: sonst verspricht der Shop eine
|
||||
// Schwelle, die an der Kasse nicht greift.
|
||||
const ergebnis = await syncFreeShipping(req.scope, settings.free_shipping_threshold);
|
||||
res.json({
|
||||
settings: { free_shipping_threshold: settings.free_shipping_threshold },
|
||||
...ergebnis,
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
message: error instanceof Error ? error.message : "Speichern fehlgeschlagen.",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { SUBSCRIPTION_MODULE } from "../../../modules/subscription";
|
||||
import { HONEY_SIZES, countVarietiesBySize } from "../../../lib/honey-picker";
|
||||
import { syncSubscriptionPromotion, SUBSCRIPTION_PROMO_CODE } from "../../../lib/subscription-promotion";
|
||||
|
||||
/** Aktuelle Abo-Einstellungen samt Kontext für die Admin-Oberfläche. */
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
const service: any = req.scope.resolve(SUBSCRIPTION_MODULE);
|
||||
const query = req.scope.resolve("query");
|
||||
|
||||
const settings = await service.getSettings();
|
||||
const varieties = await countVarietiesBySize(query);
|
||||
const subscriptions = await service.listSubscriptions({});
|
||||
|
||||
res.json({
|
||||
settings: {
|
||||
discount_percent: settings.discount_percent,
|
||||
discount_label: settings.discount_label,
|
||||
promo_code: SUBSCRIPTION_PROMO_CODE,
|
||||
},
|
||||
sizes: HONEY_SIZES.map((size) => ({ size, varieties: varieties[size] ?? 0 })),
|
||||
counts: {
|
||||
active: subscriptions.filter((s: any) => s.status === "active").length,
|
||||
paused: subscriptions.filter((s: any) => s.status === "paused").length,
|
||||
canceled: subscriptions.filter((s: any) => s.status === "canceled").length,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||
const service: any = req.scope.resolve(SUBSCRIPTION_MODULE);
|
||||
const body = req.body as { discount_percent?: number; discount_label?: string | null };
|
||||
|
||||
try {
|
||||
const settings = await service.updateSettings({
|
||||
discount_percent:
|
||||
body.discount_percent != null ? Number(body.discount_percent) : undefined,
|
||||
discount_label: body.discount_label,
|
||||
});
|
||||
// Rabatt-Engine nachziehen, sonst weicht der berechnete Betrag von der
|
||||
// Einstellung ab.
|
||||
await syncSubscriptionPromotion(req.scope, settings.discount_percent);
|
||||
res.json({
|
||||
settings: {
|
||||
discount_percent: settings.discount_percent,
|
||||
discount_label: settings.discount_label,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
message: error instanceof Error ? error.message : "Speichern fehlgeschlagen.",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import {
|
||||
completeCartWorkflow,
|
||||
createPaymentCollectionForCartWorkflow,
|
||||
capturePaymentWorkflow,
|
||||
} from "@medusajs/core-flows";
|
||||
import { getPayment, findValidMandate } from "../../../lib/mollie";
|
||||
import {
|
||||
createSubscriptionsFromOrder,
|
||||
SUBSCRIPTION_CART_FIELDS,
|
||||
} from "../../../lib/subscription-from-order";
|
||||
import { SUBSCRIPTION_MODULE } from "../../../modules/subscription";
|
||||
|
||||
/**
|
||||
* Mollie-Webhook.
|
||||
*
|
||||
* Mollie schickt nur die Zahlungs-ID; den Zustand holen wir selbst ab, damit
|
||||
* ein gefälschter Aufruf nichts auslösen kann.
|
||||
*
|
||||
* Zwei Fälle:
|
||||
* - Erstzahlung eines Abos ("first"): Warenkorb abschließen, Abo anlegen
|
||||
* - Folgezahlung ("recurring"): nur die Zahlung der Bestellung erfassen,
|
||||
* wodurch der Label-Subscriber greift
|
||||
*
|
||||
* Mollie ruft den Webhook mehrfach auf. Alles hier muss also mehrfach
|
||||
* ausführbar sein, ohne doppelte Bestellungen oder Abos zu erzeugen.
|
||||
*/
|
||||
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||
const logger = req.scope.resolve("logger");
|
||||
const query = req.scope.resolve("query");
|
||||
|
||||
// Mollie sendet formularkodiert: id=tr_xxx
|
||||
const paymentId = (req.body as any)?.id;
|
||||
if (!paymentId) {
|
||||
return res.status(400).send("id fehlt");
|
||||
}
|
||||
|
||||
// Mollie erwartet 200, sonst wird endlos wiederholt. Fehler werden
|
||||
// protokolliert, nicht als Fehlercode zurückgegeben.
|
||||
try {
|
||||
const payment: any = await getPayment(paymentId);
|
||||
logger.info(`[mollie] ${paymentId}: ${payment.status} (${payment.sequenceType})`);
|
||||
|
||||
if (payment.status !== "paid") {
|
||||
return res.status(200).send("ok");
|
||||
}
|
||||
|
||||
const meta = payment.metadata ?? {};
|
||||
|
||||
if (payment.sequenceType === "recurring") {
|
||||
await captureOrderPayment(req.scope, query, meta.order_id, logger);
|
||||
return res.status(200).send("ok");
|
||||
}
|
||||
|
||||
// --- Erstzahlung: Warenkorb abschließen und Abo anlegen ---
|
||||
const cartId = meta.cart_id;
|
||||
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"],
|
||||
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) {
|
||||
logger.error(
|
||||
`[mollie] ${paymentId}: bezahlt, aber kein gültiges Mandat — ohne Mandat kein Abo.`
|
||||
);
|
||||
return res.status(200).send("ok");
|
||||
}
|
||||
|
||||
await createPaymentCollectionForCartWorkflow(req.scope).run({
|
||||
input: { cart_id: cartId },
|
||||
});
|
||||
const { result: completed } = await completeCartWorkflow(req.scope).run({
|
||||
input: { id: cartId },
|
||||
});
|
||||
const orderId = (completed as any)?.id;
|
||||
|
||||
const { data: orders } = await query.graph({
|
||||
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");
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[mollie] Webhook ${paymentId} fehlgeschlagen: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
// Bewusst 200: sonst wiederholt Mollie endlos, obwohl der Fehler bei uns
|
||||
// liegt. Der Eintrag im Log ist der Aufhänger für die Nacharbeit.
|
||||
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,32 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { gutscheinGuthaben } from "../../../../../lib/gift-voucher";
|
||||
|
||||
/**
|
||||
* Guthaben der Gutscheine, die am Warenkorb hängen.
|
||||
*
|
||||
* Die Kasse braucht es, um den Abzug schon vor dem Abschluss richtig zu
|
||||
* zeigen: die Gutschrift am Warenkorb deckelt das Plugin auf den Betrag zum
|
||||
* Zeitpunkt des Einlösens — ohne Versand, den der Kunde erst danach wählt.
|
||||
*/
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
const query = req.scope.resolve("query");
|
||||
|
||||
const { data: carts } = await query.graph({
|
||||
entity: "cart",
|
||||
fields: ["id", "gift_cards.id", "gift_cards.code"],
|
||||
filters: { id: req.params.id },
|
||||
});
|
||||
const karten = ((carts?.[0] as any)?.gift_cards ?? []).filter(Boolean);
|
||||
|
||||
const guthaben = await gutscheinGuthaben(
|
||||
req.scope,
|
||||
karten.map((karte: any) => karte.id)
|
||||
);
|
||||
|
||||
res.json({
|
||||
gift_cards: karten.map((karte: any) => ({
|
||||
code: karte.code,
|
||||
balance: guthaben.get(karte.id) ?? 0,
|
||||
})),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { addShippingMethodToCartWorkflow } from "@medusajs/core-flows";
|
||||
import { setzeVersandpreis } from "../../../../../lib/free-shipping";
|
||||
|
||||
/**
|
||||
* Versandart setzen — mit dem Preis ohne Gutscheine im Warenwert.
|
||||
*
|
||||
* Ersatz für `POST /store/carts/:id/shipping-methods` an der Kasse: Medusa
|
||||
* rechnet dort mit dem vollen Warenwert, also mit Gutscheinen. Warum das
|
||||
* danach korrigiert werden muss, steht in lib/free-shipping.ts.
|
||||
*/
|
||||
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||
const { option_id } = (req.body ?? {}) as { option_id?: unknown };
|
||||
if (typeof option_id !== "string" || !option_id) {
|
||||
res.status(400).json({ message: "option_id fehlt." });
|
||||
return;
|
||||
}
|
||||
|
||||
await addShippingMethodToCartWorkflow(req.scope).run({
|
||||
input: { cart_id: req.params.id, options: [{ id: option_id }] },
|
||||
});
|
||||
await setzeVersandpreis(req.scope, req.params.id);
|
||||
|
||||
const query = req.scope.resolve("query");
|
||||
const { data: carts } = await query.graph({
|
||||
entity: "cart",
|
||||
fields: ["id", "total", "shipping_total", "credit_line_total"],
|
||||
filters: { id: req.params.id },
|
||||
});
|
||||
res.json({ cart: carts?.[0] ?? null });
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import { anfrageMail } from "../../../lib/contact-email";
|
||||
|
||||
/**
|
||||
* Anfragen aus den Kontaktformularen.
|
||||
*
|
||||
* Der Endpunkt verschickt Mails und ist öffentlich — er ist damit ein
|
||||
* mögliches Werkzeug für Fremde. Drei Bremsen dagegen:
|
||||
* - ein unsichtbares Feld, das nur Maschinen ausfüllen,
|
||||
* - Längen- und Formatgrenzen auf allen Feldern,
|
||||
* - eine Obergrenze je Absender-IP.
|
||||
* Nichts davon ist unüberwindbar, aber zusammen halten sie den Alltagsmüll
|
||||
* draußen, ohne dass jemand ein Rätsel lösen muss.
|
||||
*/
|
||||
|
||||
const EMPFAENGER = "kontakt@place4bees.com";
|
||||
|
||||
/** Erlaubte Herkünfte. Freitext hier würde im Betreff landen. */
|
||||
const QUELLEN: Record<string, string> = {
|
||||
kontakt: "Kontakt",
|
||||
"business-kontakt": "Kontakt (Unternehmen)",
|
||||
interesse: "Ihr Projekt",
|
||||
};
|
||||
|
||||
const GRENZE_PRO_IP = 5;
|
||||
const FENSTER_MS = 10 * 60 * 1000;
|
||||
const zaehler = new Map<string, number[]>();
|
||||
|
||||
function zuOft(ip: string): boolean {
|
||||
const jetzt = Date.now();
|
||||
const bisher = (zaehler.get(ip) ?? []).filter((t) => jetzt - t < FENSTER_MS);
|
||||
bisher.push(jetzt);
|
||||
zaehler.set(ip, bisher);
|
||||
// Der Speicher soll nicht unbegrenzt wachsen, wenn viele IPs anfragen.
|
||||
if (zaehler.size > 500) {
|
||||
for (const [k, v] of zaehler) {
|
||||
if (!v.some((t) => jetzt - t < FENSTER_MS)) zaehler.delete(k);
|
||||
}
|
||||
}
|
||||
return bisher.length > GRENZE_PRO_IP;
|
||||
}
|
||||
|
||||
const MAIL_MUSTER = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;
|
||||
|
||||
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||
const logger = req.scope.resolve("logger");
|
||||
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||
|
||||
// Das unsichtbare Feld. Wer es ausfüllt, bekommt ein freundliches OK und
|
||||
// sonst nichts — ein Fehler würde nur verraten, dass es die Falle gibt.
|
||||
if (typeof body.website === "string" && body.website.trim() !== "") {
|
||||
res.json({ ok: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const name = String(body.name ?? "").trim();
|
||||
const email = String(body.email ?? "").trim();
|
||||
const nachricht = String(body.nachricht ?? "").trim();
|
||||
const quelle = QUELLEN[String(body.quelle ?? "")] ?? null;
|
||||
const seite = typeof body.seite === "string" ? body.seite.slice(0, 200) : null;
|
||||
|
||||
const fehler: string[] = [];
|
||||
if (name.length < 2 || name.length > 120) fehler.push("Bitte geben Sie Ihren Namen an.");
|
||||
if (!MAIL_MUSTER.test(email) || email.length > 200) fehler.push("Bitte geben Sie eine gültige E-Mail-Adresse an.");
|
||||
if (nachricht.length < 10) fehler.push("Bitte schreiben Sie uns etwas mehr.");
|
||||
if (nachricht.length > 5000) fehler.push("Die Nachricht ist zu lang.");
|
||||
if (body.datenschutz !== true) fehler.push("Bitte stimmen Sie der Datenschutzerklärung zu.");
|
||||
if (!quelle) fehler.push("Unbekanntes Formular.");
|
||||
|
||||
if (fehler.length) {
|
||||
res.status(400).json({ message: fehler[0] });
|
||||
return;
|
||||
}
|
||||
|
||||
const ip = String(req.headers["x-forwarded-for"] ?? "").split(",")[0].trim() || req.ip || "unbekannt";
|
||||
if (zuOft(ip)) {
|
||||
res.status(429).json({
|
||||
message: "Es sind gerade viele Anfragen von Ihrem Anschluss gekommen. Bitte versuchen Sie es später noch einmal.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const inhalt = anfrageMail({ name, email, nachricht, quelle: quelle!, seite });
|
||||
const notification: any = req.scope.resolve(Modules.NOTIFICATION);
|
||||
await notification.createNotifications({
|
||||
to: EMPFAENGER,
|
||||
channel: "email",
|
||||
template: "kontaktanfrage",
|
||||
content: inhalt,
|
||||
// Antworten sollen bei der Absenderin landen, nicht beim Shop.
|
||||
data: { reply_to: email, quelle, seite },
|
||||
});
|
||||
|
||||
// Bewusst ohne Inhalt der Nachricht: das Protokoll ist kein Postfach.
|
||||
logger.info(`[kontakt] Anfrage über ${quelle} von ${email} weitergeleitet.`);
|
||||
res.json({ ok: true });
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[kontakt] Anfrage konnte nicht verschickt werden: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
res.status(500).json({
|
||||
message: "Die Nachricht konnte gerade nicht zugestellt werden. Bitte versuchen Sie es später noch einmal.",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils";
|
||||
|
||||
// Matches Medusa's own "ALL /store/customers/me*" middleware, so this route
|
||||
// is already protected by customer bearer/session auth before it runs —
|
||||
// req.auth_context.actor_id is guaranteed to be the requesting customer's id.
|
||||
export async function GET(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
|
||||
const customerId = req.auth_context.actor_id;
|
||||
|
||||
const orderModuleService = req.scope.resolve(Modules.ORDER);
|
||||
const order = await orderModuleService
|
||||
.retrieveOrder(req.params.id, { relations: ["items", "shipping_address", "shipping_methods"] })
|
||||
.catch(() => null);
|
||||
|
||||
if (!order || order.customer_id !== customerId) {
|
||||
res.status(404).json({ message: "Bestellung nicht gefunden." });
|
||||
return;
|
||||
}
|
||||
|
||||
const items = (order.items ?? []).map((item: any) => {
|
||||
const quantity = item.detail?.quantity ?? 1;
|
||||
const unitPrice = item.unit_price ?? 0;
|
||||
return {
|
||||
title: item.title,
|
||||
quantity,
|
||||
unit_price: unitPrice,
|
||||
total: Math.round(unitPrice * quantity * 100) / 100,
|
||||
product_id: item.product_id as string | null,
|
||||
};
|
||||
});
|
||||
|
||||
// Product thumbnails aren't part of the order's own data — order line
|
||||
// items only store product_id as a plain string, so look thumbnails up
|
||||
// the same way invoice-tax.ts resolves each item's tax category.
|
||||
const productIds = [...new Set(items.map((i) => i.product_id).filter((id): id is string => !!id))];
|
||||
const productModuleService = req.scope.resolve(Modules.PRODUCT);
|
||||
const products = productIds.length
|
||||
? await productModuleService.listProducts({ id: productIds }, { select: ["id", "thumbnail"] })
|
||||
: [];
|
||||
const thumbnailByProductId = new Map(products.map((p) => [p.id, p.thumbnail]));
|
||||
|
||||
const itemTotal = Math.round(items.reduce((sum, i) => sum + i.total, 0) * 100) / 100;
|
||||
const shippingTotal =
|
||||
Math.round((order.shipping_methods ?? []).reduce((sum: number, m: any) => sum + (m.amount ?? 0), 0) * 100) / 100;
|
||||
|
||||
// Fulfillment/tracking data lives in a separate module linked to the
|
||||
// order (not a native relation on the Order module's own tables), so it
|
||||
// has to be resolved through the remote query graph instead of
|
||||
// retrieveOrder's relations.
|
||||
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY);
|
||||
const { data } = await query.graph({
|
||||
entity: "order",
|
||||
filters: { id: order.id },
|
||||
fields: [
|
||||
"fulfillment_status",
|
||||
"fulfillments.packed_at",
|
||||
"fulfillments.shipped_at",
|
||||
"fulfillments.delivered_at",
|
||||
"fulfillments.canceled_at",
|
||||
"fulfillments.labels.tracking_number",
|
||||
"fulfillments.labels.tracking_url",
|
||||
],
|
||||
});
|
||||
const fulfillmentData = data[0] as any;
|
||||
|
||||
res.json({
|
||||
order: {
|
||||
id: order.id,
|
||||
display_id: order.display_id,
|
||||
email: order.email,
|
||||
created_at: order.created_at,
|
||||
currency_code: order.currency_code,
|
||||
items: items.map((item) => ({ ...item, thumbnail: item.product_id ? thumbnailByProductId.get(item.product_id) ?? null : null })),
|
||||
shipping_address: order.shipping_address,
|
||||
item_total: itemTotal,
|
||||
shipping_total: shippingTotal,
|
||||
total: Math.round((itemTotal + shippingTotal) * 100) / 100,
|
||||
fulfillment_status: fulfillmentData?.fulfillment_status ?? "not_fulfilled",
|
||||
fulfillments: (fulfillmentData?.fulfillments ?? []).map((f: any) => ({
|
||||
packed_at: f.packed_at,
|
||||
shipped_at: f.shipped_at,
|
||||
delivered_at: f.delivered_at,
|
||||
canceled_at: f.canceled_at,
|
||||
labels: (f.labels ?? []).map((l: any) => ({ tracking_number: l.tracking_number, tracking_url: l.tracking_url })),
|
||||
})),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { SUBSCRIPTION_MODULE } from "../../../../../../modules/subscription";
|
||||
import { HONEY_SIZES } from "../../../../../../lib/honey-picker";
|
||||
|
||||
/**
|
||||
* Ändert ein Abo: Menge, Größe, Sortenwahl, Zustand.
|
||||
*
|
||||
* `action` steuert den Zustandswechsel (pause | resume | cancel), die
|
||||
* übrigen Felder ändern den Inhalt. Beides in einer Route, damit die
|
||||
* Besitzprüfung nur an einer Stelle steht.
|
||||
*/
|
||||
export async function POST(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
|
||||
const customerId = req.auth_context.actor_id;
|
||||
const service: any = req.scope.resolve(SUBSCRIPTION_MODULE);
|
||||
const body = req.body as {
|
||||
action?: "pause" | "resume" | "cancel";
|
||||
quantity?: number;
|
||||
size?: string;
|
||||
selection?: "fixed" | "random";
|
||||
variant_id?: string | null;
|
||||
/** Eine Variante je Glas. Ersetzt variant_id, sobald gesetzt. */
|
||||
variant_ids?: string[] | null;
|
||||
cancel_reason?: string;
|
||||
};
|
||||
|
||||
const existing = await service.listSubscriptions({ id: req.params.id });
|
||||
const subscription = existing?.[0];
|
||||
// Bewusst dieselbe Antwort wie bei "gibt es nicht": ein fremdes Abo soll
|
||||
// sich nicht durch eine andere Fehlermeldung verraten.
|
||||
if (!subscription || subscription.customer_id !== customerId) {
|
||||
return res.status(404).json({ message: "Abo nicht gefunden." });
|
||||
}
|
||||
if (subscription.status === "canceled") {
|
||||
return res.status(400).json({ message: "Dieses Abo ist bereits gekündigt." });
|
||||
}
|
||||
|
||||
const update: Record<string, unknown> = { id: subscription.id };
|
||||
|
||||
switch (body.action) {
|
||||
case "pause":
|
||||
update.status = "paused";
|
||||
update.paused_at = new Date();
|
||||
break;
|
||||
case "resume":
|
||||
update.status = "active";
|
||||
update.paused_at = null;
|
||||
// Fehlversuche zurücksetzen: wurde wegen Zahlungsproblemen pausiert,
|
||||
// soll der nächste Lauf wieder regulär starten.
|
||||
update.failed_attempts = 0;
|
||||
update.last_error = null;
|
||||
// Nicht rückwirkend liefern, wenn der Termin während der Pause verstrich.
|
||||
if (new Date(subscription.next_order_at) < new Date()) {
|
||||
update.next_order_at = service.computeNextOrderDate(subscription.interval, new Date());
|
||||
}
|
||||
break;
|
||||
case "cancel":
|
||||
update.status = "canceled";
|
||||
update.canceled_at = new Date();
|
||||
if (body.cancel_reason) update.cancel_reason = String(body.cancel_reason).slice(0, 500);
|
||||
break;
|
||||
}
|
||||
|
||||
if (body.quantity != null) {
|
||||
const quantity = Number(body.quantity);
|
||||
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 12) {
|
||||
return res.status(400).json({ message: "Menge muss zwischen 1 und 12 liegen." });
|
||||
}
|
||||
update.quantity = quantity;
|
||||
}
|
||||
if (body.size != null) {
|
||||
if (!HONEY_SIZES.includes(body.size as any)) {
|
||||
return res.status(400).json({ message: `Größe muss ${HONEY_SIZES.join(" oder ")} sein.` });
|
||||
}
|
||||
update.size = body.size;
|
||||
}
|
||||
if (body.selection != null) {
|
||||
if (!["fixed", "random"].includes(body.selection)) {
|
||||
return res.status(400).json({ message: "Ungültige Sortenwahl." });
|
||||
}
|
||||
update.selection = body.selection;
|
||||
// Bei Zufall darf keine feste Sorte hängenbleiben, sonst liefert der Job
|
||||
// weiter dieselbe.
|
||||
update.variant_id = body.selection === "fixed" ? (body.variant_id ?? subscription.variant_id) : null;
|
||||
if (body.selection === "random") update.variant_ids = null;
|
||||
} else if (body.variant_id !== undefined) {
|
||||
update.variant_id = body.variant_id;
|
||||
}
|
||||
|
||||
// Die Liste hat Vorrang vor der Einzelangabe. `variant_id` bleibt auf dem
|
||||
// ersten Eintrag stehen, damit ältere Leser — und die Namensauflösung in
|
||||
// der Übersicht — weiter etwas Sinnvolles finden.
|
||||
if (body.variant_ids !== undefined && update.selection !== "random") {
|
||||
const list = body.variant_ids;
|
||||
if (list === null) {
|
||||
update.variant_ids = null;
|
||||
} else {
|
||||
if (!Array.isArray(list) || list.length < 1 || list.length > 12) {
|
||||
return res.status(400).json({ message: "Es braucht eine bis zwölf Sortenangaben." });
|
||||
}
|
||||
if (!list.every((id) => typeof id === "string" && id.length > 0)) {
|
||||
return res.status(400).json({ message: "Ungültige Sortenangabe." });
|
||||
}
|
||||
update.variant_ids = list;
|
||||
update.variant_id = list[0];
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await service.updateSubscriptions(update);
|
||||
const result = Array.isArray(updated) ? updated[0] : updated;
|
||||
|
||||
res.json({
|
||||
subscription: {
|
||||
id: result.id,
|
||||
status: result.status,
|
||||
interval: result.interval,
|
||||
size: result.size,
|
||||
quantity: result.quantity,
|
||||
selection: result.selection,
|
||||
variant_ids: result.variant_ids ?? [],
|
||||
next_order_at: result.next_order_at,
|
||||
canceled_at: result.canceled_at,
|
||||
paused_at: result.paused_at,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { SUBSCRIPTION_MODULE } from "../../../../../modules/subscription";
|
||||
import { HONEY_SIZES } from "../../../../../lib/honey-picker";
|
||||
import { varietyPerGlass } from "../../../../../lib/subscription-varieties";
|
||||
|
||||
/** Abos des angemeldeten Kunden. Die Route liegt unter /customers/me* und ist
|
||||
* dadurch schon von Medusas Middleware geschützt. */
|
||||
export async function GET(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
|
||||
const customerId = req.auth_context.actor_id;
|
||||
const service: any = req.scope.resolve(SUBSCRIPTION_MODULE);
|
||||
const query = req.scope.resolve("query");
|
||||
|
||||
const subscriptions = await service.listSubscriptions({ customer_id: customerId });
|
||||
|
||||
// Namen der festen Sorten nachschlagen, damit die Oberfläche keine
|
||||
// Varianten-IDs anzeigen muss. Bei fester Sorte steht je Glas eine
|
||||
// Variante — alle nachschlagen, nicht nur die erste.
|
||||
const perGlassBySubscription = new Map<string, string[]>(
|
||||
subscriptions.map((s: any) => [s.id, varietyPerGlass(s)])
|
||||
);
|
||||
const variantIds: string[] = subscriptions
|
||||
.flatMap((s: any) => [...(perGlassBySubscription.get(s.id) ?? []), s.variant_id, s.last_variant_id])
|
||||
.filter((id: unknown): id is string => typeof id === "string");
|
||||
const titleByVariant = new Map<string, string>();
|
||||
if (variantIds.length) {
|
||||
const { data } = await query.graph({
|
||||
entity: "variant",
|
||||
fields: ["id", "title", "product.title"],
|
||||
filters: { id: [...new Set(variantIds)] },
|
||||
});
|
||||
for (const variant of data ?? []) {
|
||||
titleByVariant.set(variant.id, variant.product?.title ?? variant.title);
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
subscriptions: subscriptions.map((s: any) => ({
|
||||
id: s.id,
|
||||
status: s.status,
|
||||
interval: s.interval,
|
||||
size: s.size,
|
||||
quantity: s.quantity,
|
||||
selection: s.selection,
|
||||
variety: s.variant_id ? (titleByVariant.get(s.variant_id) ?? null) : null,
|
||||
// Eine Variante je Glas, in der Reihenfolge der Auswahl, dazu die
|
||||
// Namen für die Anzeige.
|
||||
variant_ids: perGlassBySubscription.get(s.id) ?? [],
|
||||
varieties: (perGlassBySubscription.get(s.id) ?? []).map(
|
||||
(id: string) => titleByVariant.get(id) ?? null
|
||||
),
|
||||
last_variety: s.last_variant_id ? (titleByVariant.get(s.last_variant_id) ?? null) : null,
|
||||
next_order_at: s.next_order_at,
|
||||
last_order_at: s.last_order_at,
|
||||
canceled_at: s.canceled_at,
|
||||
paused_at: s.paused_at,
|
||||
payment_method: s.payment_method,
|
||||
})),
|
||||
sizes: HONEY_SIZES,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { handleInvoiceRequest } from "../../../../../lib/invoice-handler";
|
||||
|
||||
// GET /store/orders/:id/invoice — lets the customer download their own
|
||||
// invoice as PDF. Like Medusa's own GET /store/orders/:id, this only checks
|
||||
// for a valid publishable API key and trusts the (unguessable) order ID as
|
||||
// the access token, since our checkout flow doesn't require customer
|
||||
// accounts. Same trust model as the existing order-confirmation page.
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
await handleInvoiceRequest(req, res);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
|
||||
/**
|
||||
* Die Zahlungsarten, die der Shop anbieten darf.
|
||||
*
|
||||
* Medusas eigener Endpunkt `/store/payment-providers` liefert alles, was an
|
||||
* der Region hängt — auch Anbieter, für die es im Shop noch gar keinen
|
||||
* Bezahlablauf gibt. Ein Kunde, der so etwas auswählt, käme nicht durch.
|
||||
* Diese Route filtert deshalb auf die Anbieter, die der Shop tatsächlich
|
||||
* zu Ende führen kann, und gibt gleich die Beschriftung mit.
|
||||
*
|
||||
* Kommt eine Zahlungsart dazu, gehört sie hier eingetragen — und zwar erst
|
||||
* dann, wenn ihr Ablauf an der Kasse steht.
|
||||
*/
|
||||
type Zahlungsart = {
|
||||
id: string;
|
||||
label: string;
|
||||
description: string;
|
||||
/** Ob der Bezahlablauf an der Kasse fertig ist. */
|
||||
bereit: boolean;
|
||||
};
|
||||
|
||||
const ZAHLUNGSARTEN: Zahlungsart[] = [
|
||||
{
|
||||
id: "pp_system_default",
|
||||
label: "Rechnung",
|
||||
description: "Sie erhalten die Rechnung mit der Ware und zahlen danach per Überweisung.",
|
||||
bereit: true,
|
||||
},
|
||||
{
|
||||
id: "pp_paypal_paypal",
|
||||
label: "PayPal",
|
||||
description: "Zahlung über Ihr PayPal-Konto.",
|
||||
// Der Ablauf fehlt noch: das Plugin legt die PayPal-Bestellung nicht
|
||||
// serverseitig an, der Shop müsste sie über PayPals SDK erzeugen.
|
||||
// Solange das nicht steht, darf die Zahlungsart nicht wählbar sein.
|
||||
bereit: false,
|
||||
},
|
||||
{
|
||||
id: "pp_paypal_card_paypal_card",
|
||||
label: "Kreditkarte",
|
||||
description: "Visa, Mastercard und American Express.",
|
||||
bereit: false,
|
||||
},
|
||||
];
|
||||
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
const query = req.scope.resolve("query");
|
||||
const regionId = req.query.region_id as string | undefined;
|
||||
|
||||
const { data: regions } = await query.graph({
|
||||
entity: "region",
|
||||
fields: ["id", "payment_providers.id", "payment_providers.is_enabled"],
|
||||
...(regionId ? { filters: { id: regionId } } : {}),
|
||||
});
|
||||
|
||||
const region = regions?.[0];
|
||||
const anDerRegion = new Set(
|
||||
(region?.payment_providers ?? [])
|
||||
.filter((provider: any) => provider.is_enabled !== false)
|
||||
.map((provider: any) => provider.id)
|
||||
);
|
||||
|
||||
res.json({
|
||||
payment_methods: ZAHLUNGSARTEN.filter(
|
||||
(art) => art.bereit && anDerRegion.has(art.id)
|
||||
).map(({ bereit, ...rest }) => rest),
|
||||
// Für die Einrichtung sichtbar: was angeschlossen, aber noch nicht
|
||||
// fertig ist. Der Shop zeigt das nicht an.
|
||||
not_ready: ZAHLUNGSARTEN.filter((art) => !art.bereit).map((art) => art.id),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { SUBSCRIPTION_MODULE } from "../../../modules/subscription";
|
||||
|
||||
/**
|
||||
* Die Einstellungen, die der Shop anzeigen muss.
|
||||
*
|
||||
* Nur lesend und bewusst knapp: hier steht ausschließlich, was ohnehin auf
|
||||
* den Shop-Seiten sichtbar ist — die Schwelle für kostenfreien Versand und
|
||||
* die Versandarten, die der Shop tatsächlich anbietet. Beides kommt aus
|
||||
* denselben Daten, aus denen die Kasse rechnet; eine gepflegte Liste im
|
||||
* Frontend würde früher oder später davon abweichen.
|
||||
*/
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
const service: any = req.scope.resolve(SUBSCRIPTION_MODULE);
|
||||
const query = req.scope.resolve("query");
|
||||
|
||||
const settings = await service.getSettings();
|
||||
|
||||
const { data: options } = await query.graph({
|
||||
entity: "shipping_option",
|
||||
fields: [
|
||||
"id",
|
||||
"name",
|
||||
"price_type",
|
||||
"type.description",
|
||||
"rules.attribute",
|
||||
"rules.value",
|
||||
"prices.amount",
|
||||
"prices.currency_code",
|
||||
"prices.price_rules.attribute",
|
||||
],
|
||||
});
|
||||
|
||||
const imShop = (option: any) =>
|
||||
(option.rules ?? []).some(
|
||||
(regel: any) => regel.attribute === "enabled_in_store" && String(regel.value) === "true"
|
||||
);
|
||||
|
||||
res.json({
|
||||
free_shipping_threshold: settings.free_shipping_threshold,
|
||||
shipping_options: (options ?? [])
|
||||
.filter((option: any) => option.price_type === "flat" && imShop(option))
|
||||
.map((option: any) => {
|
||||
// Der Grundpreis ist der ohne Bedingung; der mit `item_total` ist
|
||||
// der Nullpreis oberhalb der Schwelle und gehört hier nicht hin.
|
||||
const grund = (option.prices ?? []).find(
|
||||
(preis: any) =>
|
||||
preis.currency_code === "eur" &&
|
||||
!(preis.price_rules ?? []).some((r: any) => r.attribute === "item_total")
|
||||
);
|
||||
return {
|
||||
id: option.id,
|
||||
name: option.name,
|
||||
description: option.type?.description ?? null,
|
||||
amount: grund?.amount ?? null,
|
||||
currency_code: grund?.currency_code ?? "eur",
|
||||
};
|
||||
})
|
||||
.filter((option: any) => option.amount != null)
|
||||
.sort((a: any, b: any) => a.amount - b.amount),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { SUBSCRIPTION_MODULE } from "../../../../modules/subscription";
|
||||
|
||||
/**
|
||||
* Kündigung ohne Anmeldung — § 312k BGB.
|
||||
*
|
||||
* Das Gesetz verlangt, dass Verbraucher einen online geschlossenen
|
||||
* Dauervertrag über eine Schaltfläche kündigen können, ohne sich anmelden zu
|
||||
* müssen. Deshalb liegt diese Route außerhalb von /customers/me und ist nicht
|
||||
* durch Kundenauth geschützt.
|
||||
*
|
||||
* Identifiziert wird über Abo-Nummer UND E-Mail: die E-Mail allein würde
|
||||
* genügen, um fremde Abos zu kündigen. Beides zusammen hat nur, wer die
|
||||
* Bestätigung zum Vertrag bekommen hat.
|
||||
*/
|
||||
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||
const service: any = req.scope.resolve(SUBSCRIPTION_MODULE);
|
||||
const logger = req.scope.resolve("logger");
|
||||
const body = req.body as {
|
||||
subscription_id?: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
kind?: string;
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
const id = String(body.subscription_id ?? "").trim();
|
||||
const email = String(body.email ?? "").trim().toLowerCase();
|
||||
if (!id || !email) {
|
||||
return res.status(400).json({ message: "Abo-Nummer und E-Mail-Adresse werden benötigt." });
|
||||
}
|
||||
|
||||
const found = await service.listSubscriptions({ id });
|
||||
const subscription = found?.[0];
|
||||
|
||||
// Gleiche Antwort bei falscher Nummer und falscher Adresse, damit sich
|
||||
// keine gültigen Abo-Nummern durchprobieren lassen.
|
||||
if (!subscription || String(subscription.email).toLowerCase() !== email) {
|
||||
logger.warn(`[kuendigung] Fehlversuch für "${id}"`);
|
||||
return res.status(404).json({
|
||||
message:
|
||||
"Zu diesen Angaben wurde kein Abo gefunden. Bitte prüfen Sie Abo-Nummer und E-Mail-Adresse.",
|
||||
});
|
||||
}
|
||||
|
||||
if (subscription.status === "canceled") {
|
||||
return res.json({
|
||||
already_canceled: true,
|
||||
canceled_at: subscription.canceled_at,
|
||||
message: "Dieses Abo war bereits gekündigt.",
|
||||
});
|
||||
}
|
||||
|
||||
const canceledAt = new Date();
|
||||
|
||||
// § 312k verlangt, dass der Verbraucher Art der Kündigung und seine
|
||||
// Identität angeben kann. Beides wird zum Nachweis mitgeschrieben.
|
||||
const kind = body.kind === "ausserordentlich" ? "Außerordentlich" : "Ordentlich";
|
||||
const note = [
|
||||
`${kind} über Kündigungsschaltfläche`,
|
||||
body.name ? `Name: ${String(body.name).slice(0, 120)}` : null,
|
||||
body.reason ? `Grund: ${String(body.reason).slice(0, 500)}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" — ");
|
||||
|
||||
await service.updateSubscriptions({
|
||||
id: subscription.id,
|
||||
status: "canceled",
|
||||
canceled_at: canceledAt,
|
||||
cancel_reason: note,
|
||||
});
|
||||
|
||||
logger.info(`[kuendigung] Abo ${subscription.id} gekündigt (${canceledAt.toISOString()}).`);
|
||||
|
||||
// § 312k Abs. 2 verlangt zusätzlich eine sofortige Bestätigung in Textform.
|
||||
// Solange kein Versandweg eingerichtet ist, bleibt das der offene Punkt —
|
||||
// siehe Hinweis in der Antwort.
|
||||
res.json({
|
||||
subscription_id: subscription.id,
|
||||
canceled_at: canceledAt.toISOString(),
|
||||
email: subscription.email,
|
||||
interval: subscription.interval,
|
||||
size: subscription.size,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { updateCartWorkflow, addShippingMethodToCartWorkflow } from "@medusajs/core-flows";
|
||||
import {
|
||||
extractSubscriptionLines,
|
||||
hasSubscriptionLines,
|
||||
SUBSCRIPTION_CART_FIELDS,
|
||||
} from "../../../../lib/subscription-from-order";
|
||||
import { ensureCustomer, createFirstPayment, isMollieConfigured } from "../../../../lib/mollie";
|
||||
import { setzeVersandpreis } from "../../../../lib/free-shipping";
|
||||
|
||||
/**
|
||||
* Startet die Abo-Kasse.
|
||||
*
|
||||
* Liegt ein Abo im Korb, kann nicht wie sonst abgeschlossen werden: es braucht
|
||||
* ein Mandat, und das entsteht nur über eine Erstzahlung bei Mollie mit
|
||||
* Weiterleitung. Der Warenkorb wird deshalb hier NICHT abgeschlossen — das
|
||||
* übernimmt der Webhook, sobald Mollie die Zahlung bestätigt. Bricht jemand
|
||||
* bei Mollie ab, entsteht keine Bestellung ohne Mandat.
|
||||
*/
|
||||
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||
const query = req.scope.resolve("query");
|
||||
const body = req.body as {
|
||||
cart_id?: string;
|
||||
email?: string;
|
||||
shipping_address?: Record<string, unknown>;
|
||||
shipping_option_id?: string;
|
||||
method?: string;
|
||||
};
|
||||
|
||||
if (!isMollieConfigured()) {
|
||||
return res.status(503).json({
|
||||
message: "Zahlungsanbieter ist nicht eingerichtet (MOLLIE_API_KEY fehlt).",
|
||||
});
|
||||
}
|
||||
if (!body.cart_id) {
|
||||
return res.status(400).json({ message: "cart_id fehlt." });
|
||||
}
|
||||
|
||||
try {
|
||||
// Adresse und Versandart wie im normalen Checkout setzen, bevor es zu
|
||||
// Mollie geht — danach ist der Korb nicht mehr änderbar.
|
||||
if (body.email || body.shipping_address) {
|
||||
await updateCartWorkflow(req.scope).run({
|
||||
input: {
|
||||
id: body.cart_id,
|
||||
...(body.email ? { email: body.email } : {}),
|
||||
...(body.shipping_address ? { shipping_address: body.shipping_address as any } : {}),
|
||||
} as any,
|
||||
});
|
||||
}
|
||||
if (body.shipping_option_id) {
|
||||
await addShippingMethodToCartWorkflow(req.scope).run({
|
||||
input: { cart_id: body.cart_id, options: [{ id: body.shipping_option_id }] },
|
||||
});
|
||||
// Gutscheine im Korb zählen nicht zur Versandkostenfreigrenze.
|
||||
await setzeVersandpreis(req.scope, body.cart_id);
|
||||
}
|
||||
|
||||
const { data: carts } = await query.graph({
|
||||
entity: "cart",
|
||||
fields: [...SUBSCRIPTION_CART_FIELDS, "total"],
|
||||
filters: { id: body.cart_id },
|
||||
});
|
||||
const cart: any = carts?.[0];
|
||||
if (!cart) return res.status(404).json({ message: "Warenkorb nicht gefunden." });
|
||||
if (!hasSubscriptionLines(cart)) {
|
||||
return res.status(400).json({ message: "Dieser Warenkorb enthält kein Abo." });
|
||||
}
|
||||
|
||||
// Wirft mit Klartext, wenn an einer Variante die Abo-Metadaten fehlen.
|
||||
const lines = extractSubscriptionLines(cart);
|
||||
|
||||
const email = cart.email ?? body.email;
|
||||
if (!email) return res.status(400).json({ message: "E-Mail-Adresse fehlt." });
|
||||
|
||||
const customerId = await ensureCustomer({
|
||||
email,
|
||||
name: [cart.shipping_address?.first_name, cart.shipping_address?.last_name]
|
||||
.filter(Boolean)
|
||||
.join(" "),
|
||||
});
|
||||
|
||||
const storefront = process.env.STOREFRONT_URL ?? "http://localhost:4321";
|
||||
const payment = await createFirstPayment({
|
||||
customerId,
|
||||
amount: Number(cart.total),
|
||||
currency: String(cart.currency_code ?? "eur").toUpperCase(),
|
||||
description: `place4bees Honig-Abo (${lines.map((l) => `${l.size}, ${l.interval}`).join("; ")})`,
|
||||
redirectUrl: `${storefront}/bestellung/abo?cart=${cart.id}`,
|
||||
webhookUrl: process.env.MOLLIE_WEBHOOK_URL,
|
||||
method: body.method,
|
||||
// Der Webhook findet den Warenkorb nur hierüber wieder.
|
||||
metadata: { cart_id: cart.id, mollie_customer_id: customerId },
|
||||
});
|
||||
|
||||
res.json({
|
||||
checkout_url: payment.getCheckoutUrl?.() ?? (payment as any)._links?.checkout?.href,
|
||||
payment_id: payment.id,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Abo-Kasse fehlgeschlagen.";
|
||||
req.scope.resolve("logger").error(`[abo-checkout] ${message}`);
|
||||
res.status(400).json({ message });
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 242 KiB |
|
After Width: | Height: | Size: 148 KiB |
@@ -0,0 +1,300 @@
|
||||
import type { MedusaContainer } from "@medusajs/framework/types";
|
||||
import {
|
||||
createCartWorkflow,
|
||||
addShippingMethodToCartWorkflow,
|
||||
createPaymentCollectionForCartWorkflow,
|
||||
createPaymentSessionsWorkflow,
|
||||
completeCartWorkflow,
|
||||
updateCartPromotionsWorkflow,
|
||||
} from "@medusajs/core-flows";
|
||||
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
||||
import { pickHoneyVariant } from "../lib/honey-picker";
|
||||
import { varietyPerGlass, groupByVariant } from "../lib/subscription-varieties";
|
||||
import { chargeRecurring, isMollieConfigured } from "../lib/mollie";
|
||||
import { SUBSCRIPTION_PROMO_CODE } from "../lib/subscription-promotion";
|
||||
import { ensureGiftPromotions, GIFT_ITEMS_CODE, GIFT_SHIPPING_CODE } from "../lib/gift-promotion";
|
||||
|
||||
/** Nach so vielen Fehlversuchen wird das Abo pausiert statt endlos zu wiederholen. */
|
||||
const MAX_FAILED_ATTEMPTS = 3;
|
||||
|
||||
/**
|
||||
* Lesbarer Text zu einem Fehler.
|
||||
*
|
||||
* Medusas Workflows werfen nicht immer `Error`, sondern auch Listen und
|
||||
* einfache Objekte — `String(fehler)` ergab dann "[object Object]" und das
|
||||
* Protokoll war wertlos.
|
||||
*/
|
||||
/**
|
||||
* Die Lieferadresse so, wie ein neuer Warenkorb sie annimmt.
|
||||
*
|
||||
* Im Abo liegt die Adresse so, wie sie an der Bestellung stand — mitsamt
|
||||
* ihrer ID. Gibt man die unverändert weiter, versucht Medusa eine Adresse
|
||||
* mit derselben ID anzulegen und bricht mit "already exists" ab. Es gehen
|
||||
* deshalb nur die Felder mit, die eine Anschrift ausmachen.
|
||||
*/
|
||||
const ADRESSFELDER = [
|
||||
"first_name",
|
||||
"last_name",
|
||||
"company",
|
||||
"address_1",
|
||||
"address_2",
|
||||
"city",
|
||||
"postal_code",
|
||||
"province",
|
||||
"country_code",
|
||||
"phone",
|
||||
] as const;
|
||||
|
||||
function adresseFuerWarenkorb(adresse: any): Record<string, any> | undefined {
|
||||
if (!adresse || typeof adresse !== "object") return undefined;
|
||||
const sauber: Record<string, any> = {};
|
||||
for (const feld of ADRESSFELDER) {
|
||||
const wert = adresse[feld];
|
||||
if (wert !== undefined && wert !== null && wert !== "") sauber[feld] = wert;
|
||||
}
|
||||
return Object.keys(sauber).length ? sauber : undefined;
|
||||
}
|
||||
|
||||
function fehlertext(fehler: unknown): string {
|
||||
if (fehler instanceof Error) return fehler.message;
|
||||
if (Array.isArray(fehler)) return fehler.map(fehlertext).join(" | ");
|
||||
if (fehler && typeof fehler === "object") {
|
||||
const o = fehler as Record<string, any>;
|
||||
if (typeof o.message === "string") return o.message;
|
||||
if (o.error) return fehlertext(o.error);
|
||||
try {
|
||||
return JSON.stringify(fehler);
|
||||
} catch {
|
||||
return Object.prototype.toString.call(fehler);
|
||||
}
|
||||
}
|
||||
return String(fehler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt die fälligen Abo-Bestellungen.
|
||||
*
|
||||
* Ablauf je Abo:
|
||||
* 1. Sorte bestimmen (fest oder Zufall ohne Wiederholung)
|
||||
* 2. Warenkorb bauen und abschließen -> Bestellung entsteht sofort
|
||||
* 3. Bei Mollie wiederkehrend abbuchen
|
||||
* 4. Der Mollie-Webhook erfasst die Zahlung, sobald sie eingeht
|
||||
* -> der Subscriber auto-fulfill-on-payment erzeugt das Label
|
||||
*
|
||||
* Die Bestellung entsteht bewusst VOR der Abbuchung: SEPA-Lastschrift
|
||||
* bestätigt erst nach Tagen. So sieht der Kunde die Bestellung sofort, und
|
||||
* das Label entsteht trotzdem erst mit dem Geldeingang.
|
||||
*/
|
||||
export default async function processSubscriptions(container: MedusaContainer) {
|
||||
const logger = container.resolve("logger");
|
||||
const query = container.resolve("query");
|
||||
const subscriptions: any = container.resolve(SUBSCRIPTION_MODULE);
|
||||
|
||||
let due = await subscriptions.listDue(new Date());
|
||||
|
||||
// Vorausbezahlte Geschenke brauchen kein Mollie — sie werden nie
|
||||
// abgebucht. Fehlt der Schlüssel, laufen deshalb nur sie weiter, statt
|
||||
// den ganzen Job stillzulegen.
|
||||
if (!isMollieConfigured()) {
|
||||
const abgebucht = due.filter((sub: any) => !sub.prepaid).length;
|
||||
due = due.filter((sub: any) => sub.prepaid);
|
||||
if (abgebucht) {
|
||||
logger.warn(
|
||||
`[abo] MOLLIE_API_KEY fehlt — ${abgebucht} abzubuchende(s) Abo(s) übersprungen.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!due.length) {
|
||||
logger.info("[abo] Keine fälligen Abos.");
|
||||
return;
|
||||
}
|
||||
logger.info(`[abo] ${due.length} fällige Abo(s).`);
|
||||
|
||||
// Die Nachlässe für Geschenke einmal je Lauf sicherstellen.
|
||||
if (due.some((sub: any) => sub.prepaid)) {
|
||||
await ensureGiftPromotions(container);
|
||||
}
|
||||
|
||||
for (const sub of due) {
|
||||
try {
|
||||
// Bei fester Sorte steht für jedes Glas eine Variante fest; gleiche
|
||||
// Sorten werden zu einem Posten zusammengefasst. Geprüft wird jede
|
||||
// Sorte einmal, nicht je Glas — sonst liefe dieselbe Abfrage mehrfach.
|
||||
const perGlass = varietyPerGlass(sub);
|
||||
let items: { variant_id: string; quantity: number }[];
|
||||
let lastVariantId: string;
|
||||
let delivered: string;
|
||||
|
||||
if (perGlass.length) {
|
||||
items = groupByVariant(perGlass);
|
||||
const checked = await Promise.all(
|
||||
items.map((item) =>
|
||||
pickHoneyVariant({ query, fixedVariantId: item.variant_id, size: sub.size })
|
||||
)
|
||||
);
|
||||
delivered = checked
|
||||
.map((variant, index) => `${items[index].quantity}× ${variant.productTitle} – ${variant.title}`)
|
||||
.join(", ");
|
||||
lastVariantId = items[0].variant_id;
|
||||
} else {
|
||||
const picked = await pickHoneyVariant({
|
||||
query,
|
||||
excludeVariantId: sub.last_variant_id,
|
||||
size: sub.size,
|
||||
});
|
||||
items = [{ variant_id: picked.variantId, quantity: sub.quantity }];
|
||||
delivered = `${sub.quantity}× ${picked.productTitle} – ${picked.title}`;
|
||||
lastVariantId = picked.variantId;
|
||||
}
|
||||
|
||||
const { result: cart } = await createCartWorkflow(container).run({
|
||||
input: {
|
||||
region_id: sub.region_id,
|
||||
email: sub.email,
|
||||
currency_code: sub.currency_code,
|
||||
customer_id: sub.customer_id ?? undefined,
|
||||
sales_channel_id: sub.sales_channel_id ?? undefined,
|
||||
shipping_address: adresseFuerWarenkorb(sub.shipping_address),
|
||||
items,
|
||||
metadata: { subscription_id: sub.id },
|
||||
} as any,
|
||||
});
|
||||
|
||||
// Abo-Rabatt anwenden, falls im Admin eingestellt. Läuft über die
|
||||
// Rabatt-Engine, damit Steuer und Summen stimmen.
|
||||
if (sub.shipping_option_id) {
|
||||
await addShippingMethodToCartWorkflow(container).run({
|
||||
input: { cart_id: (cart as any).id, options: [{ id: sub.shipping_option_id }] },
|
||||
});
|
||||
}
|
||||
|
||||
// Erst jetzt, mit Versandart im Warenkorb: ein Versandnachlass kann
|
||||
// sonst nichts finden, worauf er wirken soll.
|
||||
const settings = await subscriptions.getSettings();
|
||||
// Beim Geschenk ist alles bezahlt: Ware und Versand gehen auf 0, ein
|
||||
// Abo-Rabatt hätte darauf keine Wirkung mehr.
|
||||
const codes = sub.prepaid
|
||||
? [GIFT_ITEMS_CODE, GIFT_SHIPPING_CODE]
|
||||
: (settings?.discount_percent ?? 0) > 0
|
||||
? [SUBSCRIPTION_PROMO_CODE]
|
||||
: [];
|
||||
if (codes.length) {
|
||||
await updateCartPromotionsWorkflow(container).run({
|
||||
input: { cart_id: (cart as any).id, promo_codes: codes, action: "add" },
|
||||
} as any);
|
||||
}
|
||||
|
||||
|
||||
const { result: sammlung } = await createPaymentCollectionForCartWorkflow(container).run({
|
||||
input: { cart_id: (cart as any).id },
|
||||
});
|
||||
|
||||
// Ohne Zahlungssitzung lässt sich der Warenkorb nicht abschließen.
|
||||
// Sie läuft über den manuellen Anbieter — beim Geschenk ist der Betrag
|
||||
// ohnehin 0, beim laufenden Abo bucht Mollie außerhalb von Medusa ab
|
||||
// und der Webhook trägt die Zahlung nach.
|
||||
await createPaymentSessionsWorkflow(container).run({
|
||||
input: {
|
||||
payment_collection_id: (sammlung as any).id,
|
||||
provider_id: "pp_system_default",
|
||||
},
|
||||
});
|
||||
|
||||
const { result: completed } = await completeCartWorkflow(container).run({
|
||||
input: { id: (cart as any).id },
|
||||
});
|
||||
const orderId = (completed as any)?.id;
|
||||
|
||||
// Betrag aus der fertigen Bestellung, nicht aus dem Warenkorb: erst
|
||||
// dort stehen Steuer und Versand endgültig fest.
|
||||
const { data: orders } = await query.graph({
|
||||
entity: "order",
|
||||
fields: ["id", "display_id", "total", "currency_code"],
|
||||
filters: { id: orderId },
|
||||
});
|
||||
const order = orders?.[0];
|
||||
|
||||
if (sub.prepaid) {
|
||||
// Nichts abzubuchen. Damit trotzdem ein Label entsteht, muss die
|
||||
// Zahlung als erledigt gelten — der Nachlass hat den Betrag auf 0
|
||||
// gesetzt, es gibt also nichts einzuziehen.
|
||||
const verbleibend = Math.max(0, (sub.remaining_deliveries ?? 1) - 1);
|
||||
const beendet = verbleibend === 0;
|
||||
|
||||
await subscriptions.updateSubscriptions({
|
||||
id: sub.id,
|
||||
last_order_at: new Date(),
|
||||
last_variant_id: lastVariantId,
|
||||
remaining_deliveries: verbleibend,
|
||||
failed_attempts: 0,
|
||||
last_error: null,
|
||||
...(beendet
|
||||
? {
|
||||
status: "canceled",
|
||||
canceled_at: new Date(),
|
||||
cancel_reason: "Laufzeit des Geschenk-Abos beendet",
|
||||
}
|
||||
: {
|
||||
next_order_at: subscriptions.computeNextOrderDate(sub.interval, new Date()),
|
||||
}),
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`[abo] ${sub.id}: Geschenk-Lieferung ${order.display_id} angelegt, ${delivered}, ` +
|
||||
(beendet ? "letzte Lieferung." : `noch ${verbleibend} Lieferung(en).`)
|
||||
);
|
||||
} else {
|
||||
const payment = await chargeRecurring({
|
||||
customerId: sub.mollie_customer_id,
|
||||
mandateId: sub.mollie_mandate_id,
|
||||
amount: Number(order.total),
|
||||
currency: String(order.currency_code ?? "eur").toUpperCase(),
|
||||
description: `place4bees Honig-Abo – Bestellung ${order.display_id}`,
|
||||
webhookUrl: process.env.MOLLIE_WEBHOOK_URL,
|
||||
metadata: { subscription_id: sub.id, order_id: orderId },
|
||||
});
|
||||
|
||||
await subscriptions.updateSubscriptions({
|
||||
id: sub.id,
|
||||
last_order_at: new Date(),
|
||||
last_variant_id: lastVariantId,
|
||||
next_order_at: subscriptions.computeNextOrderDate(sub.interval, new Date()),
|
||||
failed_attempts: 0,
|
||||
last_error: null,
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`[abo] ${sub.id}: Bestellung ${order.display_id} angelegt, ${delivered}, ` +
|
||||
`Mollie-Zahlung ${payment.id} (${payment.status}). Label folgt mit dem Zahlungseingang.`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
const message = fehlertext(error);
|
||||
const attempts = (sub.failed_attempts ?? 0) + 1;
|
||||
const pause = attempts >= MAX_FAILED_ATTEMPTS;
|
||||
|
||||
await subscriptions.updateSubscriptions({
|
||||
id: sub.id,
|
||||
failed_attempts: attempts,
|
||||
last_error: message.slice(0, 500),
|
||||
...(pause
|
||||
? { status: "paused", paused_at: new Date() }
|
||||
: // In drei Tagen erneut versuchen, nicht im nächsten Lauf.
|
||||
{ next_order_at: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000) }),
|
||||
});
|
||||
|
||||
logger.error(
|
||||
`[abo] ${sub.id}: Versuch ${attempts} fehlgeschlagen — ${message}` +
|
||||
(pause ? " Abo pausiert, Kunde informieren." : "")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const config = {
|
||||
name: "process-subscriptions",
|
||||
// Täglich um 06:00. Fällige Abos werden dabei nachgeholt, ein verpasster
|
||||
// Lauf verliert also nichts.
|
||||
schedule: "0 6 * * *",
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import path from "node:path";
|
||||
|
||||
// Curated background photos bundled with the app (copied from the
|
||||
// storefront's own asset library) so admins can composite a product cutout
|
||||
// onto a real on-brand scene with one click, instead of only a flat color
|
||||
// or a photo they've already uploaded to that specific product.
|
||||
export const BACKGROUND_PRESETS = [
|
||||
{ key: "bienenstock", label: "Bienenstock", file: "bienenstock.jpg" },
|
||||
{ key: "biene-bluete", label: "Biene auf Blüte", file: "biene-bluete.jpg" },
|
||||
] as const;
|
||||
|
||||
export type BackgroundPresetKey = (typeof BACKGROUND_PRESETS)[number]["key"];
|
||||
|
||||
export function getPresetPath(key: string): string | null {
|
||||
const preset = BACKGROUND_PRESETS.find((p) => p.key === key);
|
||||
if (!preset) return null;
|
||||
return path.join(__dirname, "../assets/backgrounds", preset.file);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import sharp from "sharp";
|
||||
import * as ort from "onnxruntime-node";
|
||||
import path from "node:path";
|
||||
|
||||
// IS-Net (general-use) salient-object-detection model, sourced from
|
||||
// danielgatis/rembg's GitHub release (MIT-licensed project), which in turn
|
||||
// re-exports the original IS-Net model from https://github.com/xuebinqin/DIS
|
||||
// (Apache-2.0 licensed, ECCV 2022 "Highly Accurate Dichotomous Image
|
||||
// Segmentation" paper) as ONNX. Deliberately NOT using IMG.LY's
|
||||
// background-removal models, which are AGPL-licensed — this one has a clean
|
||||
// permissive lineage end to end, safe to self-host in a commercial product.
|
||||
// Noticeably sharper edges than the smaller U2NetP model previously used
|
||||
// here, at the cost of a much bigger model file (~179MB) and slower
|
||||
// inference (seconds, not milliseconds) — acceptable for an admin-triggered
|
||||
// one-off action, not something you'd want on every storefront page load.
|
||||
const MODEL_PATH = path.join(__dirname, "../assets/isnet-general-use.onnx");
|
||||
const MODEL_SIZE = 1024;
|
||||
// NOT ImageNet normalization (that's what U2Net used) — IS-Net was trained
|
||||
// with a flat 0.5 mean / 1.0 std per channel. Even rembg's own reference
|
||||
// implementation had this wrong (used ImageNet values) until a March 2025
|
||||
// fix; get it wrong and the mask silently degrades instead of erroring.
|
||||
const MEAN = [0.5, 0.5, 0.5];
|
||||
const STD = [1.0, 1.0, 1.0];
|
||||
|
||||
let sessionPromise: Promise<ort.InferenceSession> | null = null;
|
||||
function getSession(): Promise<ort.InferenceSession> {
|
||||
if (!sessionPromise) {
|
||||
sessionPromise = ort.InferenceSession.create(MODEL_PATH);
|
||||
}
|
||||
return sessionPromise;
|
||||
}
|
||||
|
||||
async function computeMask(inputBuffer: Buffer): Promise<{ mask: Buffer; width: number; height: number }> {
|
||||
const image = sharp(inputBuffer).rotate(); // rotate() applies EXIF orientation before we read metadata/dimensions
|
||||
const { width, height } = await image.metadata();
|
||||
if (!width || !height) throw new Error("Could not read image dimensions.");
|
||||
|
||||
const { data: rgb } = await image
|
||||
.clone()
|
||||
.resize(MODEL_SIZE, MODEL_SIZE, { fit: "fill" })
|
||||
.removeAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
|
||||
// Interleaved HWC uint8 (RGBRGB...) -> planar CHW float32, normalized.
|
||||
const chw = new Float32Array(3 * MODEL_SIZE * MODEL_SIZE);
|
||||
const plane = MODEL_SIZE * MODEL_SIZE;
|
||||
for (let i = 0; i < plane; i++) {
|
||||
for (let c = 0; c < 3; c++) {
|
||||
const value = rgb[i * 3 + c] / 255;
|
||||
chw[c * plane + i] = (value - MEAN[c]) / STD[c];
|
||||
}
|
||||
}
|
||||
|
||||
const session = await getSession();
|
||||
const inputName = session.inputNames[0];
|
||||
const outputName = session.outputNames[0];
|
||||
const tensor = new ort.Tensor("float32", chw, [1, 3, MODEL_SIZE, MODEL_SIZE]);
|
||||
const results = await session.run({ [inputName]: tensor });
|
||||
const output = results[outputName].data as Float32Array;
|
||||
|
||||
// Min-max stretch across the full output range — the raw saliency map is
|
||||
// often low-contrast, so without this the cutout mask comes out washed out
|
||||
// (semi-transparent everywhere) instead of a clean crisp edge.
|
||||
let min = Infinity;
|
||||
let max = -Infinity;
|
||||
for (const v of output) {
|
||||
if (v < min) min = v;
|
||||
if (v > max) max = v;
|
||||
}
|
||||
const range = max - min || 1;
|
||||
|
||||
const maskSmall = Buffer.alloc(plane);
|
||||
for (let i = 0; i < plane; i++) {
|
||||
maskSmall[i] = Math.round(((output[i] - min) / range) * 255);
|
||||
}
|
||||
|
||||
// Scale the mask back up to the source image's own resolution so the
|
||||
// alpha channel we join in later lines up pixel-for-pixel with it.
|
||||
// Two gotchas that both silently corrupt this without erroring:
|
||||
// - Must stay .raw() — otherwise sharp PNG-encodes the output, and those
|
||||
// encoded bytes get misread as raw pixels downstream.
|
||||
// - resize() on a single-channel raw buffer upconverts it to 3 channels
|
||||
// internally (buffer ends up exactly 3x the expected length) unless we
|
||||
// explicitly extract a single channel back out afterwards.
|
||||
const maskFull = await sharp(maskSmall, { raw: { width: MODEL_SIZE, height: MODEL_SIZE, channels: 1 } })
|
||||
.resize(width, height, { fit: "fill" })
|
||||
.extractChannel(0)
|
||||
.raw()
|
||||
.toBuffer();
|
||||
|
||||
return { mask: maskFull, width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Cuts the subject out of `inputBuffer` and returns a transparent-background
|
||||
* PNG. The mask is a saliency prediction, not a hard-edged trace, so results
|
||||
* are best on a single clear subject against a fairly uniform background
|
||||
* (typical product-on-a-table photography) rather than busy scenes.
|
||||
*/
|
||||
export async function removeBackground(inputBuffer: Buffer): Promise<Buffer> {
|
||||
const { mask, width, height } = await computeMask(inputBuffer);
|
||||
|
||||
const rgbBuffer = await sharp(inputBuffer).rotate().resize(width, height, { fit: "fill" }).removeAlpha().raw().toBuffer();
|
||||
|
||||
return sharp(rgbBuffer, { raw: { width, height, channels: 3 } })
|
||||
.joinChannel(mask, { raw: { width, height, channels: 1 } })
|
||||
.png()
|
||||
.toBuffer();
|
||||
}
|
||||
|
||||
interface ReplaceBackgroundOptions {
|
||||
/** Hex color (e.g. "#f8ac11") to use as a flat backdrop. */
|
||||
color?: string;
|
||||
/** Raw bytes of a background image to place behind the cutout instead. */
|
||||
backgroundImage?: Buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Composites an already-transparent cutout (as produced by
|
||||
* removeBackground) over a new flat color or background image.
|
||||
*/
|
||||
export async function replaceBackground(cutoutBuffer: Buffer, options: ReplaceBackgroundOptions): Promise<Buffer> {
|
||||
const { width, height } = await sharp(cutoutBuffer).metadata();
|
||||
if (!width || !height) throw new Error("Could not read cutout dimensions.");
|
||||
|
||||
const backdrop = options.backgroundImage
|
||||
? await sharp(options.backgroundImage).resize(width, height, { fit: "cover" }).toBuffer()
|
||||
: await sharp({
|
||||
create: { width, height, channels: 3, background: options.color ?? "#ffffff" },
|
||||
})
|
||||
.png()
|
||||
.toBuffer();
|
||||
|
||||
return sharp(backdrop)
|
||||
.composite([{ input: cutoutBuffer }])
|
||||
.png()
|
||||
.toBuffer();
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Die Mail, die eine Anfrage aus einem Kontaktformular auslöst.
|
||||
*
|
||||
* Sie geht an den Shop, nicht an die Kundin — deshalb steht hier alles, was
|
||||
* zum Antworten nötig ist, und nichts zum Schmücken. Die Absenderadresse
|
||||
* reist als Reply-To mit, damit eine Antwort direkt bei ihr landet.
|
||||
*/
|
||||
|
||||
export type Anfrage = {
|
||||
name: string;
|
||||
email: string;
|
||||
nachricht: string;
|
||||
/** Woher die Anfrage kam, z. B. "Kontakt" oder "Ihr Projekt". */
|
||||
quelle: string;
|
||||
/** Die Seite, auf der das Formular stand. */
|
||||
seite?: string | null;
|
||||
};
|
||||
|
||||
function entschaerfen(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
export function anfrageMail(anfrage: Anfrage) {
|
||||
const { name, email, nachricht, quelle, seite } = anfrage;
|
||||
|
||||
const zeilen = [
|
||||
["Name", name],
|
||||
["E-Mail", email],
|
||||
["Formular", quelle],
|
||||
...(seite ? [["Seite", seite] as [string, string]] : []),
|
||||
];
|
||||
|
||||
const html = `<!doctype html>
|
||||
<html lang="de"><head><meta charset="utf-8" /></head>
|
||||
<body style="margin:0;background:#f6f5f1;padding:24px;font-family:Arial,Helvetica,sans-serif;color:#1a1a1a;font-size:15px;line-height:1.55">
|
||||
<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
|
||||
.map(
|
||||
([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 0">${entschaerfen(String(v))}</td>
|
||||
</tr>`
|
||||
)
|
||||
.join("")}
|
||||
</table>
|
||||
<h2 style="margin:24px 0 8px;font-size:16px">Nachricht</h2>
|
||||
<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">
|
||||
Antworten geht direkt an ${entschaerfen(email)}.
|
||||
</p>
|
||||
</div>
|
||||
</body></html>`;
|
||||
|
||||
const text = [
|
||||
`Neue Anfrage über ${quelle}`,
|
||||
"",
|
||||
...zeilen.map(([k, v]) => `${k}: ${v}`),
|
||||
"",
|
||||
"Nachricht:",
|
||||
nachricht,
|
||||
"",
|
||||
`Antworten geht direkt an ${email}.`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
subject: `Anfrage über ${quelle}: ${name}`,
|
||||
html,
|
||||
text,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { listShippingOptionsForCartWorkflow, updateShippingOptionsWorkflow } from "@medusajs/core-flows";
|
||||
import { refreshCartGiftCardsWorkflow } from "@medusajs/loyalty-plugin/workflows";
|
||||
|
||||
/**
|
||||
* Kostenfreier Versand ab einem Warenwert.
|
||||
*
|
||||
* Medusa kann das selbst: an einem Versandpreis darf genau eine Bedingung
|
||||
* auf `item_total` hängen. Statt eigener Rechnerei bekommt deshalb jeder
|
||||
* Euro-Preis einer Versandart mit festem Preis einen zweiten Preis von 0 €,
|
||||
* der ab der Schwelle greift. Zwischensumme, Steuer und Rechnung stimmen
|
||||
* damit ohne Zutun.
|
||||
*
|
||||
* Die Schwelle selbst steht in den Shop-Einstellungen — eine Stelle, aus der
|
||||
* sowohl der Hinweis im Shop als auch dieser Preis folgt.
|
||||
*/
|
||||
|
||||
/** Preise mit Schwellenbedingung sind unsere Zutat und werden neu gesetzt. */
|
||||
function istSchwellenpreis(preis: any): boolean {
|
||||
return (preis.price_rules ?? []).some((regel: any) => regel.attribute === "item_total");
|
||||
}
|
||||
|
||||
function regelWert(preis: any, attribut: string): string | null {
|
||||
const regel = (preis.price_rules ?? []).find((r: any) => r.attribute === attribut);
|
||||
return regel ? String(regel.value) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Preis so, wie er wieder gespeichert werden muss.
|
||||
*
|
||||
* Das Setzen der Preise ersetzt die bisherigen vollständig. Ein Preis, der
|
||||
* an einer Region hängt, muss deshalb als `region_id` zurückgeschrieben
|
||||
* werden — schickt man ihn als bloße Währung, verliert die Versandart ihn.
|
||||
*/
|
||||
function alsEingabe(preis: any): { amount: number; currency_code?: string; region_id?: string } {
|
||||
const region = regelWert(preis, "region_id");
|
||||
return region
|
||||
? { region_id: region, amount: preis.amount }
|
||||
: { currency_code: preis.currency_code, amount: preis.amount };
|
||||
}
|
||||
|
||||
export async function syncFreeShipping(container: any, thresholdEuro: number | null) {
|
||||
const query = container.resolve("query");
|
||||
|
||||
const { data: regions } = await query.graph({
|
||||
entity: "region",
|
||||
fields: ["id", "currency_code"],
|
||||
});
|
||||
const waehrungJeRegion = new Map<string, string>(
|
||||
(regions ?? []).map((region: any) => [region.id, region.currency_code])
|
||||
);
|
||||
|
||||
const { data: options } = await query.graph({
|
||||
entity: "shipping_option",
|
||||
fields: [
|
||||
"id",
|
||||
"name",
|
||||
"price_type",
|
||||
"rules.attribute",
|
||||
"rules.value",
|
||||
"prices.amount",
|
||||
"prices.currency_code",
|
||||
"prices.price_rules.attribute",
|
||||
"prices.price_rules.operator",
|
||||
"prices.price_rules.value",
|
||||
],
|
||||
});
|
||||
|
||||
// "Versandkostenfrei ab 60 €" ist ein Versprechen an Kunden und gilt
|
||||
// deshalb genau an den Versandarten, die der Shop anbietet. Was nur im
|
||||
// Admin wählbar ist — etwa Hermes für interne Bestellungen — behält seinen
|
||||
// Preis; dort entscheidet ohnehin ein Mensch. Ausgeblendete Versandarten
|
||||
// werden mitgeführt, damit ein früher gesetzter Schwellenpreis wieder
|
||||
// verschwindet, sobald sie aus dem Shop genommen werden.
|
||||
const imShop = (option: any) =>
|
||||
(option.rules ?? []).some(
|
||||
(regel: any) => regel.attribute === "enabled_in_store" && String(regel.value) === "true"
|
||||
);
|
||||
|
||||
const flache = (options ?? []).filter((option: any) => option.price_type === "flat");
|
||||
const betroffen = flache.filter(imShop);
|
||||
const updates: any[] = [];
|
||||
|
||||
for (const option of flache) {
|
||||
const schwelleFuerDiese = imShop(option) ? thresholdEuro : null;
|
||||
const alle = option.prices ?? [];
|
||||
const grundpreise = alle.filter((preis: any) => !istSchwellenpreis(preis));
|
||||
const vorhandene = alle.filter(istSchwellenpreis);
|
||||
|
||||
// Die Schwelle ist ein Eurobetrag und gilt deshalb nur für Euro-Preise.
|
||||
// Ein Dollarpreis bekäme sonst stillschweigend die Schwelle 60 USD.
|
||||
const inEuro = grundpreise.filter((preis: any) => {
|
||||
const region = regelWert(preis, "region_id");
|
||||
const waehrung = region ? waehrungJeRegion.get(region) : preis.currency_code;
|
||||
return waehrung?.toLowerCase() === "eur";
|
||||
});
|
||||
|
||||
const schwelleJetzt = vorhandene.length
|
||||
? Number(regelWert(vorhandene[0], "item_total"))
|
||||
: null;
|
||||
const sollAnzahl = schwelleFuerDiese == null ? 0 : inEuro.length;
|
||||
|
||||
// Nichts tun, wenn schon genau das dransteht, was drastehen soll.
|
||||
if (vorhandene.length === sollAnzahl && schwelleJetzt === (schwelleFuerDiese ?? null)) continue;
|
||||
|
||||
// Ohne Grundpreis wäre der Versand nach dem Schreiben immer kostenlos.
|
||||
// Lieber diese Versandart auslassen als sie zu verschenken.
|
||||
if (!grundpreise.length) continue;
|
||||
|
||||
const prices = [
|
||||
...grundpreise.map(alsEingabe),
|
||||
...(schwelleFuerDiese == null
|
||||
? []
|
||||
: inEuro.map((preis: any) => ({
|
||||
...alsEingabe(preis),
|
||||
amount: 0,
|
||||
rules: [{ attribute: "item_total", operator: "gte", value: schwelleFuerDiese }],
|
||||
}))),
|
||||
];
|
||||
|
||||
updates.push({ id: option.id, prices });
|
||||
}
|
||||
|
||||
if (!updates.length) return { geaendert: 0, versandarten: betroffen.length };
|
||||
|
||||
await updateShippingOptionsWorkflow(container).run({ input: updates as any });
|
||||
return { geaendert: updates.length, versandarten: betroffen.length };
|
||||
}
|
||||
|
||||
/*
|
||||
* --- Gutscheine zählen nicht zur Schwelle ------------------------------------
|
||||
*
|
||||
* Die Bedingung am Versandpreis hört auf Medusas `item_total`, und darin
|
||||
* steckt jeder Posten — auch ein Geschenkgutschein. Wer einen 50-€-Gutschein
|
||||
* und ein Glas Honig kauft, bekäme so den Versand geschenkt.
|
||||
*
|
||||
* Medusa lässt den Warenwert an einer Stelle überschreiben: beim Auflisten
|
||||
* der Versandarten (Hook in src/workflows/hooks/free-shipping.ts). Beim
|
||||
* Hinzufügen der Versandart rechnet es aber mit dem vollen `item_total` und
|
||||
* bietet dort keinen Eingriff. Deshalb schreibt `setzeVersandpreis` den Preis
|
||||
* danach so fest, wie ihn die Auflistung ergibt — aufgerufen direkt vor dem
|
||||
* Bezahlen (Kasse und Abo-Kasse).
|
||||
*/
|
||||
|
||||
/** Warenwert, der für die Versandkostenfreigrenze zählt: ohne Posten ohne Versand. */
|
||||
export async function warenwertFuerVersand(container: any, cartId: string): Promise<number> {
|
||||
const query = container.resolve("query");
|
||||
const { data: carts } = await query.graph({
|
||||
entity: "cart",
|
||||
// Medusa rechnet `item_total` nur aus, wenn Posten samt Steuer- und
|
||||
// Rabattzeilen mitkommen; sonst steht dort 0.
|
||||
fields: ["id", "item_total", "items.*", "items.tax_lines.*", "items.adjustments.*"],
|
||||
filters: { id: cartId },
|
||||
});
|
||||
const cart = carts?.[0] as any;
|
||||
if (!cart) return 0;
|
||||
|
||||
const ohneVersand = (cart.items ?? [])
|
||||
.filter((item: any) => item?.requires_shipping === false)
|
||||
.reduce((summe: number, item: any) => summe + Number(item.total ?? 0), 0);
|
||||
|
||||
return Math.round((Number(cart.item_total ?? 0) - ohneVersand) * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt die Versandpreise des Warenkorbs auf den Wert, den die Auflistung
|
||||
* mit dem Warenwert ohne Gutscheine ergibt.
|
||||
*
|
||||
* Ändert sich dabei ein Betrag, wird die Gutschrift eingelöster Gutscheine
|
||||
* neu berechnet — sie ist auf den Gesamtbetrag gedeckelt.
|
||||
*/
|
||||
export async function setzeVersandpreis(container: any, cartId: string) {
|
||||
const query = container.resolve("query");
|
||||
const cartModule: any = container.resolve("cart");
|
||||
|
||||
const { data: carts } = await query.graph({
|
||||
entity: "cart",
|
||||
fields: ["id", "shipping_methods.id", "shipping_methods.amount", "shipping_methods.shipping_option_id", "gift_cards.id"],
|
||||
filters: { id: cartId },
|
||||
});
|
||||
const cart = carts?.[0] as any;
|
||||
const methoden = (cart?.shipping_methods ?? []).filter((m: any) => m?.shipping_option_id);
|
||||
if (!methoden.length) return;
|
||||
|
||||
const { result: optionen } = await listShippingOptionsForCartWorkflow(container).run({
|
||||
input: { cart_id: cartId, option_ids: methoden.map((m: any) => m.shipping_option_id) },
|
||||
});
|
||||
const preisJeOption = new Map(
|
||||
(optionen as any[]).map((option) => [option.id, Number(option.amount)])
|
||||
);
|
||||
|
||||
let geaendert = false;
|
||||
for (const methode of methoden) {
|
||||
const soll = preisJeOption.get(methode.shipping_option_id);
|
||||
if (soll == null || Number.isNaN(soll) || soll === Number(methode.amount)) continue;
|
||||
await cartModule.updateShippingMethods([{ id: methode.id, amount: soll }]);
|
||||
geaendert = true;
|
||||
}
|
||||
|
||||
if (geaendert && (cart.gift_cards ?? []).length) {
|
||||
await refreshCartGiftCardsWorkflow(container).run({ input: { cart_id: cartId } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { createOrderFulfillmentWorkflow } from "@medusajs/core-flows";
|
||||
|
||||
/**
|
||||
* Bestellung zu einer Zahlung.
|
||||
*
|
||||
* Zahlung -> Payment-Collection -> Bestellung. Der Umweg ist nötig, weil
|
||||
* sich über zwei Relationen hinweg nicht filtern lässt.
|
||||
*/
|
||||
export async function bestellungZurZahlung(container: any, paymentId: string): Promise<string | null> {
|
||||
const logger = container.resolve("logger");
|
||||
const query = container.resolve("query");
|
||||
|
||||
const { data: payments } = await query.graph({
|
||||
entity: "payment",
|
||||
fields: ["id", "payment_collection_id"],
|
||||
filters: { id: paymentId },
|
||||
});
|
||||
|
||||
const collectionId = payments?.[0]?.payment_collection_id;
|
||||
if (!collectionId) {
|
||||
logger.warn(`[auto-fulfill] Zahlung ${paymentId} hat keine Payment-Collection.`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const { data: collections } = await query.graph({
|
||||
entity: "payment_collection",
|
||||
fields: ["id", "order.id"],
|
||||
filters: { id: collectionId },
|
||||
});
|
||||
|
||||
const orderId = (collections?.[0] as any)?.order?.id;
|
||||
if (!orderId) {
|
||||
logger.warn(`[auto-fulfill] Payment-Collection ${collectionId} hängt an keiner Bestellung.`);
|
||||
return null;
|
||||
}
|
||||
return orderId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt die Fulfillment für alle offenen Posten an, die verschickt werden.
|
||||
*
|
||||
* Das Label entsteht dabei im Fulfillment-Provider der gewählten Versandart
|
||||
* (siehe src/modules/*-fulfillment). Posten ohne Versand — der
|
||||
* Geschenkgutschein — bleiben außen vor: sie kommen per E-Mail.
|
||||
*/
|
||||
export async function erfuelleBestellung(container: any, orderId: string) {
|
||||
const logger = container.resolve("logger");
|
||||
const query = container.resolve("query");
|
||||
|
||||
// Bestellung direkt abfragen: über zwei Relationen hinweg kamen die
|
||||
// Mengen nicht mit, wodurch jede Position als "nichts offen" galt.
|
||||
const { data: fullOrders } = await query.graph({
|
||||
entity: "order",
|
||||
fields: [
|
||||
"id",
|
||||
"display_id",
|
||||
"status",
|
||||
"items.id",
|
||||
"items.requires_shipping",
|
||||
// Menge und bereits erfüllte Menge liegen beide auf `detail`.
|
||||
// `items.quantity` liefert die Query nicht mit.
|
||||
"items.detail.quantity",
|
||||
"items.detail.fulfilled_quantity",
|
||||
"fulfillments.id",
|
||||
],
|
||||
filters: { id: orderId },
|
||||
});
|
||||
|
||||
const order = fullOrders?.[0] as any;
|
||||
if (!order) {
|
||||
logger.warn(`[auto-fulfill] Bestellung ${orderId} nicht gefunden.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (order.status === "canceled") {
|
||||
logger.info(`[auto-fulfill] Bestellung ${order.display_id} ist storniert, kein Label.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Mehrfache Zahlungen (Teilzahlung, erneuter Capture) dürfen nicht zu
|
||||
// mehreren Labels führen.
|
||||
if (order.fulfillments?.length) {
|
||||
logger.info(
|
||||
`[auto-fulfill] Bestellung ${order.display_id} hat bereits ${order.fulfillments.length} Fulfillment(s), übersprungen.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const items = (order.items ?? [])
|
||||
.filter((item: any) => item.requires_shipping !== false)
|
||||
.map((item: any) => ({
|
||||
id: item.id,
|
||||
quantity: (item.detail?.quantity ?? 0) - (item.detail?.fulfilled_quantity ?? 0),
|
||||
}))
|
||||
.filter((item: any) => item.quantity > 0);
|
||||
|
||||
if (items.length === 0) {
|
||||
logger.info(`[auto-fulfill] Bestellung ${order.display_id}: nichts zu verschicken.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const { result } = await createOrderFulfillmentWorkflow(container).run({
|
||||
input: { order_id: order.id, items },
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`[auto-fulfill] Bestellung ${order.display_id}: Fulfillment ${(result as any)?.id} angelegt, ${items.length} Position(en).`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { createPromotionsWorkflow } from "@medusajs/core-flows";
|
||||
|
||||
/**
|
||||
* Nachlieferungen eines Geschenk-Abos auf 0 € stellen.
|
||||
*
|
||||
* Der Käufer hat alle Lieferungen auf einmal bezahlt. Die Folgebestellungen
|
||||
* dürfen deshalb nichts mehr kosten — weder Ware noch Versand. Statt die
|
||||
* Beträge selbst zu rechnen, laufen beide über Medusas Rabatt-Engine: nur so
|
||||
* stimmen Zwischensumme, Steuer und Rechnung, und die Bestellung sieht im
|
||||
* Admin nachvollziehbar aus.
|
||||
*
|
||||
* Zwei Codes, weil eine Promotion genau ein Ziel hat.
|
||||
*/
|
||||
export const GIFT_ITEMS_CODE = "GESCHENK-ABO";
|
||||
export const GIFT_SHIPPING_CODE = "GESCHENK-VERSAND";
|
||||
|
||||
async function ensure(container: any, code: string, targetType: "items" | "shipping_methods") {
|
||||
const query = container.resolve("query");
|
||||
const { data } = await query.graph({
|
||||
entity: "promotion",
|
||||
fields: ["id", "code"],
|
||||
filters: { code },
|
||||
});
|
||||
if (data?.[0]) return data[0];
|
||||
|
||||
const { result } = await createPromotionsWorkflow(container).run({
|
||||
input: {
|
||||
promotionsData: [
|
||||
{
|
||||
code,
|
||||
type: "standard",
|
||||
status: "active",
|
||||
// Bewusst nicht automatisch: der Nachlass gilt nur für die
|
||||
// Lieferungen eines bezahlten Geschenks, nicht für jeden Warenkorb.
|
||||
is_automatic: false,
|
||||
application_method: {
|
||||
type: "percentage",
|
||||
target_type: targetType,
|
||||
allocation: targetType === "items" ? "each" : "across",
|
||||
value: 100,
|
||||
...(targetType === "items" ? { max_quantity: 100 } : {}),
|
||||
},
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
});
|
||||
return Array.isArray(result) ? result[0] : result;
|
||||
}
|
||||
|
||||
/** Legt beide Codes an, falls sie fehlen. Wiederholbar. */
|
||||
export async function ensureGiftPromotions(container: any) {
|
||||
await ensure(container, GIFT_ITEMS_CODE, "items");
|
||||
await ensure(container, GIFT_SHIPPING_CODE, "shipping_methods");
|
||||
return [GIFT_ITEMS_CODE, GIFT_SHIPPING_CODE];
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Verschenkte Abos.
|
||||
*
|
||||
* Ein Geschenk läuft über eine feste Zahl von Lieferungen und ist beim Kauf
|
||||
* vollständig bezahlt. Deshalb bekommt der Warenkorb die Gläser aller
|
||||
* Lieferungen auf einmal — der Käufer zahlt einmal, die Ware verteilt der
|
||||
* Job später auf die einzelnen Termine.
|
||||
*/
|
||||
|
||||
/** Wählbare Laufzeiten in Lieferungen. */
|
||||
export const GIFT_TERMS = [3, 6, 12] as const;
|
||||
|
||||
export type GiftDetails = {
|
||||
deliveries: number;
|
||||
recipientName: string;
|
||||
recipientEmail: string;
|
||||
senderName: string | null;
|
||||
};
|
||||
|
||||
const MAIL_MUSTER = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;
|
||||
|
||||
/**
|
||||
* Liest die Geschenkangaben aus den Metadaten eines Warenkorb-Postens.
|
||||
*
|
||||
* Gibt `null` zurück, wenn es kein Geschenk ist. Wirft, wenn es eines sein
|
||||
* soll, aber die Angaben nicht taugen — ein Geschenk ohne Empfängeradresse
|
||||
* käme nie an.
|
||||
*/
|
||||
export function giftFromMetadata(metadata: Record<string, any> | null | undefined): GiftDetails | null {
|
||||
if (!metadata || metadata.subscription_gift !== true) return null;
|
||||
|
||||
const deliveries = Number(metadata.subscription_deliveries);
|
||||
if (!GIFT_TERMS.includes(deliveries as any)) {
|
||||
throw new Error(
|
||||
`Ungültige Laufzeit für ein Geschenk-Abo: ${metadata.subscription_deliveries}. ` +
|
||||
`Erlaubt sind ${GIFT_TERMS.join(", ")} Lieferungen.`
|
||||
);
|
||||
}
|
||||
|
||||
const recipientName = String(metadata.gift_recipient_name ?? "").trim();
|
||||
const recipientEmail = String(metadata.gift_recipient_email ?? "").trim();
|
||||
if (recipientName.length < 2) throw new Error("Das Geschenk-Abo hat keinen Empfängernamen.");
|
||||
if (!MAIL_MUSTER.test(recipientEmail)) {
|
||||
throw new Error("Das Geschenk-Abo hat keine gültige E-Mail-Adresse des Empfängers.");
|
||||
}
|
||||
|
||||
const senderName = String(metadata.gift_sender_name ?? "").trim();
|
||||
|
||||
return {
|
||||
deliveries,
|
||||
recipientName,
|
||||
recipientEmail,
|
||||
senderName: senderName.length ? senderName : null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import crypto from "crypto";
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import { createGiftCardsWorkflow } from "@medusajs/loyalty-plugin/workflows";
|
||||
import { gutscheinMail, gutscheinVersendetMail } from "./order-emails";
|
||||
|
||||
/**
|
||||
* Geschenkgutscheine: ausgeben nach Zahlung, Guthaben lesen, eingelöste
|
||||
* Gutscheine einer Bestellung auflisten.
|
||||
*
|
||||
* Code, Guthabenkonto und die Verrechnung im Warenkorb kommen aus dem
|
||||
* Loyalty-Plugin (`@medusajs/loyalty-plugin`). Hier steht nur, was der Shop
|
||||
* darüber hinaus braucht: der Zeitpunkt der Ausgabe und die E-Mails.
|
||||
*/
|
||||
|
||||
/** Ohne 0/O und 1/I — der Code wird abgetippt. */
|
||||
const ZEICHEN = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
|
||||
/**
|
||||
* Ein Gutscheincode wie `P4B-7KQM-X2HD-9RTW`.
|
||||
*
|
||||
* Eigene Erzeugung statt der des Plugins: dort wiederholen sich ab dem
|
||||
* elften Zeichen die Zufallsbytes. Zwölf echte Zufallszeichen ergeben
|
||||
* 60 Bit — nicht zu erraten, auch nicht über die öffentliche Abfrage.
|
||||
*/
|
||||
export function erzeugeGutscheinCode(): string {
|
||||
const zeichen = Array.from({ length: 12 }, () => ZEICHEN[crypto.randomInt(ZEICHEN.length)]);
|
||||
return ["P4B", zeichen.slice(0, 4), zeichen.slice(4, 8), zeichen.slice(8)]
|
||||
.map((teil) => (Array.isArray(teil) ? teil.join("") : teil))
|
||||
.join("-");
|
||||
}
|
||||
|
||||
/** Was der Kunde am Posten zum Gutschein angegeben hat. */
|
||||
type GutscheinAngaben = {
|
||||
geschenk: boolean;
|
||||
empfaengerName: string | null;
|
||||
empfaengerEmail: string | null;
|
||||
schenkerName: string | null;
|
||||
nachricht: string | null;
|
||||
};
|
||||
|
||||
function angabenAusMetadaten(metadata: any): GutscheinAngaben {
|
||||
const text = (wert: unknown) => (typeof wert === "string" && wert.trim() ? wert.trim() : null);
|
||||
const geschenk = metadata?.voucher_gift === true && Boolean(text(metadata?.voucher_recipient_email));
|
||||
return {
|
||||
geschenk,
|
||||
empfaengerName: geschenk ? text(metadata?.voucher_recipient_name) : null,
|
||||
empfaengerEmail: geschenk ? text(metadata?.voucher_recipient_email) : null,
|
||||
schenkerName: geschenk ? text(metadata?.voucher_sender_name) : null,
|
||||
nachricht: geschenk ? text(metadata?.voucher_message) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt für die bezahlten Gutschein-Posten einer Bestellung je Stück einen
|
||||
* Gutschein an und verschickt ihn.
|
||||
*
|
||||
* Wiederholbar: je Posten entstehen höchstens so viele Gutscheine, wie er
|
||||
* Stück hat. Eine zweite Zahlung oder ein erneutes Ereignis legt nichts
|
||||
* doppelt an; die Mails schützt zusätzlich der `idempotency_key`.
|
||||
*/
|
||||
export async function gibGutscheineAus(container: any, orderId: string) {
|
||||
const logger = container.resolve("logger");
|
||||
const query = container.resolve("query");
|
||||
|
||||
const { data: orders } = await query.graph({
|
||||
entity: "order",
|
||||
fields: [
|
||||
"id",
|
||||
"display_id",
|
||||
"email",
|
||||
"status",
|
||||
"currency_code",
|
||||
"shipping_address.first_name",
|
||||
"shipping_address.last_name",
|
||||
"items.id",
|
||||
"items.title",
|
||||
"items.unit_price",
|
||||
"items.metadata",
|
||||
"items.detail.quantity",
|
||||
"items.product.metadata",
|
||||
],
|
||||
filters: { id: orderId },
|
||||
});
|
||||
const order = orders?.[0] as any;
|
||||
if (!order) return;
|
||||
|
||||
const posten = (order.items ?? []).filter((item: any) => item?.product?.metadata?.gift_voucher === true);
|
||||
if (!posten.length) return;
|
||||
|
||||
if (order.status === "canceled") {
|
||||
logger.info(`[gutschein] Bestellung ${order.display_id} ist storniert, kein Gutschein.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const notification: any = container.resolve(Modules.NOTIFICATION);
|
||||
const kaeuferName =
|
||||
[order.shipping_address?.first_name, order.shipping_address?.last_name].filter(Boolean).join(" ") || null;
|
||||
|
||||
for (const item of posten) {
|
||||
const menge = Number(item.detail?.quantity ?? 1);
|
||||
const wert = Number(item.unit_price ?? 0);
|
||||
const angaben = angabenAusMetadaten(item.metadata);
|
||||
|
||||
const { data: vorhandene } = await query.graph({
|
||||
entity: "gift_card",
|
||||
fields: ["id", "code", "value"],
|
||||
filters: { line_item_id: item.id },
|
||||
});
|
||||
const gutscheine: { id: string; code: string; value: number }[] = [...(vorhandene ?? [])];
|
||||
|
||||
for (let i = gutscheine.length; i < menge; i++) {
|
||||
const { result } = await createGiftCardsWorkflow(container).run({
|
||||
input: [
|
||||
{
|
||||
code: erzeugeGutscheinCode(),
|
||||
value: wert,
|
||||
currency_code: order.currency_code,
|
||||
line_item_id: item.id,
|
||||
// Unbefristet: das Plugin prüft beim Einlösen ohnehin kein Ablaufdatum.
|
||||
expires_at: null,
|
||||
// Anonym — eingelöst wird über den Code, nicht über ein Kundenkonto.
|
||||
customer_id: null,
|
||||
reference: "order",
|
||||
reference_id: order.id,
|
||||
metadata: {
|
||||
display_id: order.display_id,
|
||||
...(angaben.geschenk ? { recipient_email: angaben.empfaengerEmail } : {}),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
gutscheine.push(...(result as any[]));
|
||||
}
|
||||
|
||||
for (const gutschein of gutscheine) {
|
||||
const betrag = Number(gutschein.value);
|
||||
const an = angaben.geschenk ? angaben.empfaengerEmail! : order.email;
|
||||
if (!an) {
|
||||
logger.warn(`[gutschein] ${gutschein.code}: keine E-Mail-Adresse, nicht verschickt.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await notification.createNotifications({
|
||||
to: an,
|
||||
channel: "email",
|
||||
template: "gift-voucher",
|
||||
content: gutscheinMail({
|
||||
code: gutschein.code,
|
||||
betrag,
|
||||
waehrung: order.currency_code,
|
||||
empfaengerName: angaben.geschenk ? angaben.empfaengerName : kaeuferName,
|
||||
schenkerName: angaben.geschenk ? angaben.schenkerName ?? kaeuferName : null,
|
||||
nachricht: angaben.nachricht,
|
||||
geschenk: angaben.geschenk,
|
||||
}),
|
||||
idempotency_key: `gutschein-${gutschein.id}`,
|
||||
data: { order_id: order.id, gift_card_id: gutschein.id },
|
||||
});
|
||||
|
||||
// Beim Geschenk erfährt der Käufer, dass es angekommen ist — mit dem
|
||||
// Code, falls die Adresse des Beschenkten nicht stimmt.
|
||||
if (angaben.geschenk && order.email) {
|
||||
await notification.createNotifications({
|
||||
to: order.email,
|
||||
channel: "email",
|
||||
template: "gift-voucher-sent",
|
||||
content: gutscheinVersendetMail({
|
||||
code: gutschein.code,
|
||||
betrag,
|
||||
waehrung: order.currency_code,
|
||||
empfaengerEmail: angaben.empfaengerEmail!,
|
||||
empfaengerName: angaben.empfaengerName,
|
||||
kaeuferName,
|
||||
}),
|
||||
idempotency_key: `gutschein-versendet-${gutschein.id}`,
|
||||
data: { order_id: order.id, gift_card_id: gutschein.id },
|
||||
});
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`[gutschein] Bestellung ${order.display_id}: ${gutschein.code} über ${betrag} ` +
|
||||
`${String(order.currency_code).toUpperCase()} an ${an}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Das aktuelle Guthaben der Gutscheine, nach Gutschein-ID. */
|
||||
export async function gutscheinGuthaben(
|
||||
container: any,
|
||||
giftCardIds: string[]
|
||||
): Promise<Map<string, number>> {
|
||||
const guthaben = new Map<string, number>();
|
||||
if (!giftCardIds.length) return guthaben;
|
||||
|
||||
const query = container.resolve("query");
|
||||
const storeCredit: any = container.resolve("store_credit");
|
||||
|
||||
const { data: konten } = await query.graph({
|
||||
entity: "gift_card_store_credit_account",
|
||||
fields: ["gift_card_id", "store_credit_account_id"],
|
||||
filters: { gift_card_id: giftCardIds },
|
||||
});
|
||||
|
||||
for (const konto of konten ?? []) {
|
||||
const stand = await storeCredit.retrieveAccountStats({ account_id: konto.store_credit_account_id });
|
||||
guthaben.set(konto.gift_card_id, Number(stand.balance ?? 0));
|
||||
}
|
||||
return guthaben;
|
||||
}
|
||||
|
||||
export type EingeloesterGutschein = { code: string; betrag: number };
|
||||
|
||||
/** Die Gutscheine, mit denen eine Bestellung (teilweise) bezahlt wurde. */
|
||||
export async function eingeloesteGutscheine(
|
||||
container: any,
|
||||
orderId: string
|
||||
): Promise<EingeloesterGutschein[]> {
|
||||
const query = container.resolve("query");
|
||||
|
||||
const { data: orders } = await query.graph({
|
||||
entity: "order",
|
||||
fields: ["id", "credit_lines.amount", "credit_lines.reference", "credit_lines.reference_id"],
|
||||
filters: { id: orderId },
|
||||
});
|
||||
const zeilen = ((orders?.[0] as any)?.credit_lines ?? []).filter(
|
||||
(zeile: any) => zeile?.reference === "gift-card"
|
||||
);
|
||||
if (!zeilen.length) return [];
|
||||
|
||||
const { data: karten } = await query.graph({
|
||||
entity: "gift_card",
|
||||
fields: ["id", "code"],
|
||||
filters: { id: zeilen.map((zeile: any) => zeile.reference_id) },
|
||||
});
|
||||
const codes = new Map((karten ?? []).map((karte: any) => [karte.id, karte.code]));
|
||||
|
||||
return zeilen.map((zeile: any) => ({
|
||||
code: String(codes.get(zeile.reference_id) ?? "Gutschein"),
|
||||
betrag: Math.round(Number(zeile.amount ?? 0) * 100) / 100,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Für Mail und Rechnung: nur das Ende des Codes, der Rest bleibt privat. */
|
||||
export function gekuerzterCode(code: string): string {
|
||||
return code.length > 4 ? `…${code.slice(-4)}` : code;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Wählt die Sorte für die nächste Abo-Lieferung.
|
||||
*
|
||||
* Bei "random" wird aus der Kategorie Honig gezogen, wobei die zuletzt
|
||||
* gelieferte Sorte ausgeschlossen wird — sonst käme zufällig zweimal
|
||||
* hintereinander dasselbe, was sich für den Kunden nach Fehler anfühlt.
|
||||
*/
|
||||
|
||||
const HONEY_CATEGORY = "Honig";
|
||||
|
||||
export type PickedVariant = { variantId: string; title: string; productTitle: string };
|
||||
|
||||
/**
|
||||
* Glasgrößen, die im Abo wählbar sind.
|
||||
*
|
||||
* Bewusst ohne "50 Gramm": die Größe existiert im Katalog (11 Sorten), ist
|
||||
* als Abo aber nicht gewollt. Entspricht sonst den Variantentiteln.
|
||||
* Die Probiersets ("Süß", "Kräftig", …) liegen zwar auch in der Kategorie
|
||||
* Honig, tragen aber keine Größe und fallen durch die Filterung heraus.
|
||||
*/
|
||||
export const HONEY_SIZES = ["250 Gramm", "500 Gramm"] as const;
|
||||
export type HoneySize = (typeof HONEY_SIZES)[number];
|
||||
|
||||
/** Wie viele Sorten es in einer Größe gibt — für die Anzeige im Shop. */
|
||||
export async function countVarietiesBySize(query: any): Promise<Record<string, number>> {
|
||||
const { data: variants } = await query.graph({
|
||||
entity: "variant",
|
||||
fields: ["id", "title", "product.id", "product.status", "product.categories.name"],
|
||||
});
|
||||
const counts: Record<string, Set<string>> = {};
|
||||
for (const variant of variants ?? []) {
|
||||
if (variant.product?.status !== "published") continue;
|
||||
if (!(variant.product?.categories ?? []).some((c: any) => c.name === HONEY_CATEGORY)) continue;
|
||||
if (!HONEY_SIZES.includes(variant.title)) continue;
|
||||
(counts[variant.title] ??= new Set()).add(variant.product.id);
|
||||
}
|
||||
return Object.fromEntries(Object.entries(counts).map(([size, ids]) => [size, ids.size]));
|
||||
}
|
||||
|
||||
export async function pickHoneyVariant(params: {
|
||||
query: any;
|
||||
/** Bei "fixed" wird diese Variante genommen. */
|
||||
fixedVariantId?: string | null;
|
||||
/** Zuletzt geliefert; wird bei "random" ausgeschlossen. */
|
||||
excludeVariantId?: string | null;
|
||||
/** Glasgröße, z. B. "250 Gramm". Schränkt den Zufallspool ein. */
|
||||
size?: string | null;
|
||||
salesChannelId?: string | null;
|
||||
}): Promise<PickedVariant> {
|
||||
const { query, fixedVariantId, excludeVariantId, size } = params;
|
||||
|
||||
if (fixedVariantId) {
|
||||
const { data } = await query.graph({
|
||||
entity: "variant",
|
||||
fields: ["id", "title", "product.title", "product.status"],
|
||||
filters: { id: fixedVariantId },
|
||||
});
|
||||
const variant = data?.[0];
|
||||
if (!variant) throw new Error(`Variante ${fixedVariantId} existiert nicht mehr.`);
|
||||
if (variant.product?.status !== "published") {
|
||||
throw new Error(`Produkt zu Variante ${fixedVariantId} ist nicht veröffentlicht.`);
|
||||
}
|
||||
return { variantId: variant.id, title: variant.title, productTitle: variant.product?.title };
|
||||
}
|
||||
|
||||
const { data: variants } = await query.graph({
|
||||
entity: "variant",
|
||||
fields: [
|
||||
"id",
|
||||
"title",
|
||||
"manage_inventory",
|
||||
"inventory_quantity",
|
||||
"product.id",
|
||||
"product.title",
|
||||
"product.status",
|
||||
"product.categories.name",
|
||||
],
|
||||
});
|
||||
|
||||
const candidates = (variants ?? []).filter((variant: any) => {
|
||||
if (variant.product?.status !== "published") return false;
|
||||
const inHoney = (variant.product?.categories ?? []).some(
|
||||
(category: any) => category.name === HONEY_CATEGORY
|
||||
);
|
||||
if (!inHoney) return false;
|
||||
// Bestandsführung ist optional; nur wenn sie an ist, muss etwas da sein.
|
||||
if (variant.manage_inventory && (variant.inventory_quantity ?? 0) < 1) return false;
|
||||
// Größe eingrenzen. Ohne Angabe bleiben die Probiersets im Pool, die
|
||||
// keine Größe tragen — deshalb ist size in der Praxis immer gesetzt.
|
||||
if (size && variant.title !== size) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
if (candidates.length === 0) {
|
||||
throw new Error(
|
||||
size
|
||||
? `Keine lieferbare Honigsorte in der Größe "${size}" gefunden.`
|
||||
: `Keine lieferbare Sorte in der Kategorie "${HONEY_CATEGORY}" gefunden.`
|
||||
);
|
||||
}
|
||||
|
||||
// Auf Produktebene ausschließen, nicht auf Variantenebene: sonst kommt
|
||||
// derselbe Honig zweimal hintereinander, nur in anderer Glasgröße — das
|
||||
// liest sich für den Kunden als Wiederholung.
|
||||
const lastProductId = excludeVariantId
|
||||
? (variants ?? []).find((variant: any) => variant.id === excludeVariantId)?.product?.id
|
||||
: null;
|
||||
const filtered = lastProductId
|
||||
? candidates.filter((variant: any) => variant.product?.id !== lastProductId)
|
||||
: candidates;
|
||||
// Wenn dadurch nichts übrig bleibt (nur ein Produkt im Sortiment), lieber
|
||||
// wiederholen als nicht liefern.
|
||||
const pool = filtered.length > 0 ? filtered : candidates;
|
||||
|
||||
const chosen = pool[Math.floor(Math.random() * pool.length)];
|
||||
return {
|
||||
variantId: chosen.id,
|
||||
title: chosen.title,
|
||||
productTitle: chosen.product?.title,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import { generateInvoicePdf } from "./invoice-pdf";
|
||||
import { resolveTaxBreakdown } from "./invoice-tax";
|
||||
import { eingeloesteGutscheine, gekuerzterCode } from "./gift-voucher";
|
||||
|
||||
// We compute totals ourselves from raw unit_price/quantity/shipping amount
|
||||
// instead of relying on Medusa's query-graph computed total/subtotal fields,
|
||||
// which turned out to require field-selection combinations we couldn't get
|
||||
// to resolve reliably. Since our prices have no discounts/promotions, this
|
||||
// is a safe, simple multiplication rather than a re-implementation of a full
|
||||
// pricing engine.
|
||||
/**
|
||||
* Die Rechnungsdaten einer Bestellung.
|
||||
*
|
||||
* Aus dem Anfrage-Handler herausgelöst, weil die Bestellbestätigung
|
||||
* dieselbe Rechnung als Anhang braucht — zwei Rechenwege für einen Betrag
|
||||
* gehen früher oder später auseinander.
|
||||
*/
|
||||
export async function buildInvoiceOrder(container: any, orderId: string) {
|
||||
const orderModuleService = container.resolve(Modules.ORDER);
|
||||
const order = await orderModuleService
|
||||
.retrieveOrder(orderId, { relations: ["items", "shipping_address", "shipping_methods"] })
|
||||
.catch(() => null);
|
||||
|
||||
if (!order) return null;
|
||||
|
||||
const items = (order.items ?? []).map((item: any) => {
|
||||
const quantity = item.detail?.quantity ?? 1;
|
||||
const unitPrice = item.unit_price ?? 0;
|
||||
return {
|
||||
title: item.title,
|
||||
quantity,
|
||||
unit_price: unitPrice,
|
||||
total: Math.round(unitPrice * quantity * 100) / 100,
|
||||
product_id: item.product_id,
|
||||
};
|
||||
});
|
||||
|
||||
const itemSubtotal = Math.round(items.reduce((sum, i) => sum + i.total, 0) * 100) / 100;
|
||||
const shippingTotal = Math.round((order.shipping_methods ?? []).reduce((sum: number, m: any) => sum + (m.amount ?? 0), 0) * 100) / 100;
|
||||
const total = Math.round((itemSubtotal + shippingTotal) * 100) / 100;
|
||||
|
||||
const taxBreakdown = await resolveTaxBreakdown(container, items, shippingTotal);
|
||||
const taxTotal = Math.round(taxBreakdown.reduce((sum, b) => sum + b.tax, 0) * 100) / 100;
|
||||
|
||||
// Ein Gutschein ist ein Zahlungsmittel: die Umsatzsteuer bleibt auf dem
|
||||
// vollen Betrag, der Gutschein mindert nur, was noch zu zahlen ist.
|
||||
const gutscheine = (await eingeloesteGutscheine(container, order.id)).map((g) => ({
|
||||
code: gekuerzterCode(g.code),
|
||||
amount: g.betrag,
|
||||
}));
|
||||
const gutscheinTotal = Math.round(gutscheine.reduce((sum, g) => sum + g.amount, 0) * 100) / 100;
|
||||
|
||||
return {
|
||||
id: order.id,
|
||||
display_id: order.display_id,
|
||||
email: order.email ?? "",
|
||||
created_at: order.created_at,
|
||||
currency_code: order.currency_code,
|
||||
items,
|
||||
shipping_address: order.shipping_address,
|
||||
item_subtotal: itemSubtotal,
|
||||
item_total: itemSubtotal,
|
||||
shipping_total: shippingTotal,
|
||||
tax_total: taxTotal,
|
||||
total,
|
||||
tax_breakdown: taxBreakdown,
|
||||
gift_cards: gutscheine,
|
||||
amount_due: Math.round(Math.max(0, total - gutscheinTotal) * 100) / 100,
|
||||
};
|
||||
}
|
||||
|
||||
/** Die Rechnung als PDF im Speicher — für den Mailanhang. */
|
||||
export async function renderInvoicePdf(container: any, orderId: string): Promise<Buffer | null> {
|
||||
const order = await buildInvoiceOrder(container, orderId);
|
||||
if (!order) return null;
|
||||
|
||||
return await new Promise<Buffer>((resolve, reject) => {
|
||||
const teile: Buffer[] = [];
|
||||
const strom = generateInvoicePdf(order);
|
||||
strom.on("data", (teil: Buffer) => teile.push(teil));
|
||||
strom.on("end", () => resolve(Buffer.concat(teile)));
|
||||
strom.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleInvoiceRequest(req: MedusaRequest, res: MedusaResponse) {
|
||||
const order = await buildInvoiceOrder(req.scope, req.params.id);
|
||||
|
||||
if (!order) {
|
||||
res.status(404).json({ message: "Bestellung nicht gefunden." });
|
||||
return;
|
||||
}
|
||||
|
||||
res.setHeader("Content-Type", "application/pdf");
|
||||
res.setHeader("Content-Disposition", `inline; filename="rechnung-${order.display_id}.pdf"`);
|
||||
generateInvoicePdf(order).pipe(res);
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
import PDFDocument from "pdfkit";
|
||||
import type { PassThrough } from "node:stream";
|
||||
import path from "node:path";
|
||||
|
||||
// Real registration data — required on every German invoice by §14 UStG /
|
||||
// Impressumspflicht, so it's hardcoded here rather than left as a placeholder.
|
||||
const COMPANY = {
|
||||
name: "PLACE4BEES GmbH",
|
||||
addressLine: "Isestraße 109",
|
||||
cityLine: "20149 Hamburg",
|
||||
phone: "+49 173 269 89 51",
|
||||
email: "buchhaltung@place4bees.com",
|
||||
web: "www.place4bees.com",
|
||||
court: "Amtsgericht Hamburg",
|
||||
registryNumber: "173319",
|
||||
vatId: "DE350889068",
|
||||
taxNumber: "42/750/03722",
|
||||
management: "Daniela Zastrow und Björn Schumann",
|
||||
bankName: "Olinda",
|
||||
iban: "DE84 1001 0123 8938 3905 34",
|
||||
bic: "QNTODEB2XXX",
|
||||
};
|
||||
|
||||
const LOGO_PATH = path.join(__dirname, "../assets/place4bees-logo.png");
|
||||
|
||||
const COLORS = {
|
||||
text: "#1a1a1a",
|
||||
muted: "#6b6b66",
|
||||
rule: "#dcdcd8",
|
||||
shade: "#f2f2ef",
|
||||
shadeStrong: "#e6e6e1",
|
||||
};
|
||||
|
||||
const MARGIN_X = 50;
|
||||
const PAGE_RIGHT = 545; // A4 width (595.28) minus the 50pt right margin
|
||||
|
||||
function formatMoney(amount: number, currencyCode: string) {
|
||||
return new Intl.NumberFormat("de-DE", { style: "currency", currency: currencyCode.toUpperCase() }).format(amount);
|
||||
}
|
||||
|
||||
function formatDate(date: string | Date) {
|
||||
return new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(new Date(date));
|
||||
}
|
||||
|
||||
interface InvoiceItem {
|
||||
title: string;
|
||||
quantity: number;
|
||||
unit_price: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface InvoiceAddress {
|
||||
first_name?: string | null;
|
||||
last_name?: string | null;
|
||||
address_1?: string | null;
|
||||
postal_code?: string | null;
|
||||
city?: string | null;
|
||||
country_code?: string | null;
|
||||
}
|
||||
|
||||
export interface InvoiceOrder {
|
||||
id: string;
|
||||
display_id: number;
|
||||
email: string;
|
||||
created_at: string | Date;
|
||||
currency_code: string;
|
||||
items: InvoiceItem[];
|
||||
shipping_address?: InvoiceAddress | null;
|
||||
item_subtotal?: number;
|
||||
item_total: number;
|
||||
shipping_total: number;
|
||||
tax_total: number;
|
||||
total: number;
|
||||
tax_breakdown?: { rate: number; net: number; tax: number }[];
|
||||
/** Eingelöste Gutscheine, Code gekürzt. */
|
||||
gift_cards?: { code: string; amount: number }[];
|
||||
/** Gesamtbetrag abzüglich Gutscheine. */
|
||||
amount_due?: number;
|
||||
}
|
||||
|
||||
export function generateInvoicePdf(order: InvoiceOrder): PassThrough {
|
||||
// bufferPages lets us go back and stamp "Seite X von Y" on every page at
|
||||
// the very end, once we actually know how many pages the Widerrufsbelehrung
|
||||
// on page 2 ended up flowing across.
|
||||
const doc = new PDFDocument({
|
||||
size: "A4",
|
||||
margins: { top: MARGIN_X, bottom: 25, left: MARGIN_X, right: MARGIN_X },
|
||||
bufferPages: true,
|
||||
});
|
||||
const stream = doc as unknown as PassThrough;
|
||||
|
||||
const invoiceNumber = `RE-${order.display_id}`;
|
||||
const contentWidth = PAGE_RIGHT - MARGIN_X;
|
||||
|
||||
// --- Sender line + logo ---
|
||||
doc
|
||||
.fontSize(8)
|
||||
.font("Helvetica")
|
||||
.fillColor(COLORS.muted)
|
||||
.text(`${COMPANY.name} - ${COMPANY.addressLine} - ${COMPANY.cityLine}`, MARGIN_X, 50);
|
||||
|
||||
try {
|
||||
doc.image(LOGO_PATH, PAGE_RIGHT - 95, 38, { width: 95 });
|
||||
} catch {
|
||||
// Logo is optional decoration — the invoice is still legally complete without it.
|
||||
}
|
||||
|
||||
// --- Recipient address (left) + invoice meta (right) ---
|
||||
const blockTop = 118;
|
||||
const addr = order.shipping_address;
|
||||
let leftY = blockTop;
|
||||
doc.fontSize(10).font("Helvetica").fillColor(COLORS.text);
|
||||
if (addr) {
|
||||
doc.text(`${addr.first_name ?? ""} ${addr.last_name ?? ""}`.trim(), MARGIN_X, leftY);
|
||||
leftY += 14;
|
||||
if (addr.address_1) {
|
||||
doc.text(addr.address_1, MARGIN_X, leftY);
|
||||
leftY += 14;
|
||||
}
|
||||
doc.text(`${addr.postal_code ?? ""} ${addr.city ?? ""}`.trim(), MARGIN_X, leftY);
|
||||
leftY += 14;
|
||||
doc.text(addr.country_code?.toUpperCase() === "DE" ? "Deutschland" : addr.country_code ?? "", MARGIN_X, leftY);
|
||||
leftY += 14;
|
||||
}
|
||||
|
||||
const metaLabelX = 340;
|
||||
const metaValueWidth = PAGE_RIGHT - metaLabelX;
|
||||
let rightY = blockTop;
|
||||
const metaRow = (label: string, value: string) => {
|
||||
doc.font("Helvetica").fillColor(COLORS.muted).fontSize(9.5).text(label, metaLabelX, rightY);
|
||||
doc
|
||||
.font("Helvetica-Bold")
|
||||
.fillColor(COLORS.text)
|
||||
.fontSize(9.5)
|
||||
.text(value, metaLabelX, rightY, { width: metaValueWidth, align: "right" });
|
||||
rightY += 15;
|
||||
};
|
||||
metaRow("Rechnungs-Nr.", invoiceNumber);
|
||||
metaRow("Rechnungsdatum", formatDate(new Date()));
|
||||
metaRow("Bestelldatum", formatDate(order.created_at));
|
||||
|
||||
// --- Heading ---
|
||||
let y = Math.max(leftY, rightY) + 25;
|
||||
doc.font("Helvetica-Bold").fontSize(15).fillColor(COLORS.text).text(`Rechnung Nr. ${invoiceNumber}`, MARGIN_X, y);
|
||||
y += 22;
|
||||
doc
|
||||
.font("Helvetica")
|
||||
.fontSize(9.5)
|
||||
.fillColor(COLORS.muted)
|
||||
.text(`Rechnung zu Ihrer Bestellung Nr. ${order.display_id}`, MARGIN_X, y);
|
||||
y += 26;
|
||||
|
||||
// --- Line items table ---
|
||||
const col = { idx: MARGIN_X, label: MARGIN_X + 30, qty: 335, unit: 385, total: 460 };
|
||||
const rowHeight = 22;
|
||||
|
||||
const drawTableHeader = (top: number) => {
|
||||
doc.rect(MARGIN_X, top, contentWidth, rowHeight).fill(COLORS.shade);
|
||||
doc.fillColor(COLORS.text).font("Helvetica-Bold").fontSize(9);
|
||||
doc.text("Pos.", col.idx + 4, top + 7);
|
||||
doc.text("Beschreibung", col.label, top + 7);
|
||||
doc.text("Menge", col.qty, top + 7, { width: 45, align: "right" });
|
||||
doc.text("Einzelpreis", col.unit, top + 7, { width: 70, align: "right" });
|
||||
doc.text("Gesamtpreis", col.total, top + 7, { width: 81, align: "right" });
|
||||
return top + rowHeight;
|
||||
};
|
||||
|
||||
y = drawTableHeader(y);
|
||||
|
||||
type Row = { idx: number; label: string; qty: string; unit: string; total: string };
|
||||
const rows: Row[] = order.items.map((item, i) => ({
|
||||
idx: i + 1,
|
||||
label: item.title,
|
||||
qty: String(item.quantity),
|
||||
unit: formatMoney(item.unit_price, order.currency_code),
|
||||
total: formatMoney(item.total, order.currency_code),
|
||||
}));
|
||||
if (order.shipping_total > 0) {
|
||||
rows.push({
|
||||
idx: rows.length + 1,
|
||||
label: "Versandkosten",
|
||||
qty: "1",
|
||||
unit: formatMoney(order.shipping_total, order.currency_code),
|
||||
total: formatMoney(order.shipping_total, order.currency_code),
|
||||
});
|
||||
}
|
||||
|
||||
doc.font("Helvetica").fontSize(9.5);
|
||||
rows.forEach((row, i) => {
|
||||
if (i % 2 === 1) {
|
||||
doc.rect(MARGIN_X, y, contentWidth, rowHeight).fill("#f8f8f6");
|
||||
}
|
||||
doc.fillColor(COLORS.text);
|
||||
doc.text(String(row.idx) + ".", col.idx + 4, y + 6);
|
||||
doc.text(row.label, col.label, y + 6, { width: 295 });
|
||||
doc.text(row.qty, col.qty, y + 6, { width: 45, align: "right" });
|
||||
doc.text(row.unit, col.unit, y + 6, { width: 70, align: "right" });
|
||||
doc.text(row.total, col.total, y + 6, { width: 81, align: "right" });
|
||||
y += rowHeight;
|
||||
});
|
||||
|
||||
y += 12;
|
||||
|
||||
// --- Summary: net + tax per rate (§14 UStG requires both, not just the tax amount), then gross ---
|
||||
const summaryRows: { label: string; value: string; bold?: boolean }[] = [];
|
||||
if (order.tax_breakdown?.length) {
|
||||
for (const bracket of order.tax_breakdown) {
|
||||
summaryRows.push({
|
||||
label: `Gesamtbetrag netto (${bracket.rate}%)`,
|
||||
value: formatMoney(bracket.net, order.currency_code),
|
||||
});
|
||||
summaryRows.push({
|
||||
label: `zzgl. Umsatzsteuer ${bracket.rate}%`,
|
||||
value: formatMoney(bracket.tax, order.currency_code),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
summaryRows.push({ label: "Gesamtbetrag netto", value: formatMoney(order.total - order.tax_total, order.currency_code) });
|
||||
summaryRows.push({ label: "Umsatzsteuer", value: formatMoney(order.tax_total, order.currency_code) });
|
||||
}
|
||||
summaryRows.push({ label: "Gesamtbetrag brutto", value: formatMoney(order.total, order.currency_code), bold: true });
|
||||
const gutscheine = order.gift_cards ?? [];
|
||||
for (const gutschein of gutscheine) {
|
||||
summaryRows.push({
|
||||
label: `abzgl. Gutschein ${gutschein.code}`,
|
||||
value: `−${formatMoney(gutschein.amount, order.currency_code)}`,
|
||||
});
|
||||
}
|
||||
if (gutscheine.length) {
|
||||
summaryRows.push({
|
||||
label: "Zahlbetrag",
|
||||
value: formatMoney(order.amount_due ?? order.total, order.currency_code),
|
||||
bold: true,
|
||||
});
|
||||
}
|
||||
|
||||
summaryRows.forEach((row) => {
|
||||
doc.rect(MARGIN_X, y, contentWidth, rowHeight).fill(row.bold ? COLORS.shadeStrong : COLORS.shade);
|
||||
doc.fillColor(COLORS.text).font(row.bold ? "Helvetica-Bold" : "Helvetica").fontSize(row.bold ? 10 : 9.5);
|
||||
doc.text(row.label, col.label, y + 6);
|
||||
doc.text(row.value, col.total, y + 6, { width: 81, align: "right" });
|
||||
y += rowHeight;
|
||||
});
|
||||
|
||||
y += 24;
|
||||
|
||||
doc
|
||||
.font("Helvetica")
|
||||
.fontSize(9.5)
|
||||
.fillColor(COLORS.text)
|
||||
.text(
|
||||
gutscheine.length && (order.amount_due ?? order.total) <= 0
|
||||
? "Der Rechnungsbetrag ist vollständig mit Gutschein beglichen."
|
||||
: "Zahlungsziel innerhalb von 14 Tagen nach Erhalt der Ware.",
|
||||
MARGIN_X,
|
||||
y
|
||||
);
|
||||
y += 28;
|
||||
doc.text("Mit freundlichen Grüßen", MARGIN_X, y);
|
||||
y += 15;
|
||||
doc.text("Ihr Team von place4bees", MARGIN_X, y);
|
||||
|
||||
// --- Footer: address / contact / legal / bank, pinned to the bottom of the page ---
|
||||
// Each entry is pre-split into short lines that fit within a quarter-width
|
||||
// column at this font size — letting pdfkit auto-wrap instead would throw
|
||||
// off the fixed per-line row height below and push content onto a 2nd page.
|
||||
const footerTop = doc.page.height - 110;
|
||||
doc.moveTo(MARGIN_X, footerTop - 12).lineTo(PAGE_RIGHT, footerTop - 12).strokeColor(COLORS.rule).lineWidth(0.5).stroke();
|
||||
|
||||
const footerColWidth = contentWidth / 4;
|
||||
const footerCols = [MARGIN_X, MARGIN_X + footerColWidth, MARGIN_X + footerColWidth * 2, MARGIN_X + footerColWidth * 3];
|
||||
|
||||
doc.font("Helvetica").fontSize(7.5).fillColor(COLORS.muted);
|
||||
|
||||
const footerLines = (x: number, lines: string[]) => {
|
||||
let fy = footerTop;
|
||||
for (const line of lines) {
|
||||
doc.text(line, x, fy, { width: footerColWidth - 10 });
|
||||
fy += 10;
|
||||
}
|
||||
};
|
||||
|
||||
footerLines(footerCols[0], [COMPANY.name, COMPANY.addressLine, COMPANY.cityLine, "Deutschland"]);
|
||||
footerLines(footerCols[1], [`Tel. ${COMPANY.phone}`, "E-Mail", COMPANY.email, `Web ${COMPANY.web}`]);
|
||||
footerLines(footerCols[2], [
|
||||
COMPANY.court,
|
||||
`HR-Nr. ${COMPANY.registryNumber}`,
|
||||
`USt.-ID ${COMPANY.vatId}`,
|
||||
`Steuer-Nr. ${COMPANY.taxNumber}`,
|
||||
"Geschäftsführung:",
|
||||
"Daniela Zastrow,",
|
||||
"Björn Schumann",
|
||||
]);
|
||||
footerLines(footerCols[3], [`Bank ${COMPANY.bankName}`, "IBAN", COMPANY.iban, `BIC ${COMPANY.bic}`]);
|
||||
|
||||
// --- Page 2+: Widerrufsbelehrung (Art. 246a §1 Abs. 2 EGBGB requires this
|
||||
// be provided on a durable medium, at the latest at delivery — flowing
|
||||
// text rather than fixed positions since we don't know in advance how
|
||||
// many pages the legal text needs). ---
|
||||
doc.addPage();
|
||||
doc.font("Helvetica-Bold").fontSize(13).fillColor(COLORS.text).text("Widerrufsbelehrung", { width: contentWidth });
|
||||
doc.moveDown(1);
|
||||
|
||||
const heading = (text: string) => {
|
||||
doc.moveDown(0.8);
|
||||
doc.font("Helvetica-Bold").fontSize(10).fillColor(COLORS.text).text(text, { width: contentWidth });
|
||||
doc.moveDown(0.3);
|
||||
};
|
||||
const paragraph = (text: string) => {
|
||||
doc.font("Helvetica").fontSize(9).fillColor(COLORS.text).text(text, { width: contentWidth, align: "justify" });
|
||||
doc.moveDown(0.5);
|
||||
};
|
||||
|
||||
heading("Widerrufsrecht");
|
||||
paragraph("Sie haben das Recht, binnen vierzehn Tagen ohne Angabe von Gründen diesen Vertrag zu widerrufen.");
|
||||
paragraph(
|
||||
"Die Widerrufsfrist beträgt vierzehn Tage ab dem Tag, an dem Sie oder ein von Ihnen benannter Dritter, der nicht der Beförderer ist, die Waren in Besitz genommen haben bzw. hat. Haben Sie mehrere Waren einer einheitlichen Bestellung getrennt erhalten, beginnt die Frist mit Erhalt der letzten Ware."
|
||||
);
|
||||
paragraph(
|
||||
`Um Ihr Widerrufsrecht auszuüben, müssen Sie uns (${COMPANY.name}, ${COMPANY.addressLine}, ${COMPANY.cityLine}, Telefon: ${COMPANY.phone}, E-Mail: ${COMPANY.email}) mittels einer eindeutigen Erklärung (z.B. per Post versandter Brief oder E-Mail) über Ihren Entschluss, diesen Vertrag zu widerrufen, informieren. Sie können dafür das untenstehende Muster-Widerrufsformular verwenden, das jedoch nicht vorgeschrieben ist.`
|
||||
);
|
||||
paragraph("Zur Wahrung der Widerrufsfrist reicht es aus, dass Sie die Mitteilung über die Ausübung des Widerrufsrechts vor Ablauf der Widerrufsfrist absenden.");
|
||||
|
||||
heading("Folgen des Widerrufs");
|
||||
paragraph(
|
||||
"Wenn Sie diesen Vertrag widerrufen, haben wir Ihnen alle Zahlungen, die wir von Ihnen erhalten haben, einschließlich der Lieferkosten (mit Ausnahme der zusätzlichen Kosten, die sich daraus ergeben, dass Sie eine andere Art der Lieferung als die von uns angebotene, günstigste Standardlieferung gewählt haben), unverzüglich und spätestens binnen vierzehn Tagen ab dem Tag zurückzuzahlen, an dem die Mitteilung über Ihren Widerruf dieses Vertrags bei uns eingegangen ist. Für diese Rückzahlung verwenden wir dasselbe Zahlungsmittel, das Sie bei der ursprünglichen Transaktion eingesetzt haben, es sei denn, mit Ihnen wurde ausdrücklich etwas anderes vereinbart; in keinem Fall werden Ihnen wegen dieser Rückzahlung Entgelte berechnet."
|
||||
);
|
||||
paragraph(
|
||||
"Wir können die Rückzahlung verweigern, bis wir die Waren wieder zurückerhalten haben oder bis Sie den Nachweis erbracht haben, dass Sie die Waren zurückgesandt haben, je nachdem, welches der frühere Zeitpunkt ist."
|
||||
);
|
||||
paragraph(
|
||||
"Sie haben die Waren unverzüglich und in jedem Fall spätestens binnen vierzehn Tagen ab dem Tag, an dem Sie uns über den Widerruf dieses Vertrags unterrichten, an uns zurückzusenden oder zu übergeben. Die Frist ist gewahrt, wenn Sie die Waren vor Ablauf der Frist von vierzehn Tagen absenden. Sie tragen die unmittelbaren Kosten der Rücksendung der Waren. Sie müssen für einen etwaigen Wertverlust der Waren nur aufkommen, wenn dieser Wertverlust auf einen zur Prüfung der Beschaffenheit, Eigenschaften und Funktionsweise der Waren nicht notwendigen Umgang mit ihnen zurückzuführen ist."
|
||||
);
|
||||
|
||||
heading("Besonderheit bei Kursen und Veranstaltungen");
|
||||
paragraph(
|
||||
"Haben Sie einer Dienstleistung (z.B. Bienen-Schnupperkurs) ausdrücklich zugestimmt, dass wir mit der Ausführung vor Ablauf der Widerrufsfrist beginnen, und wurde die Dienstleistung vollständig erbracht, erlischt Ihr Widerrufsrecht gemäß § 356 Abs. 4 BGB mit vollständiger Erbringung der Dienstleistung."
|
||||
);
|
||||
|
||||
heading("Muster-Widerrufsformular");
|
||||
paragraph("(Wenn Sie den Vertrag widerrufen wollen, füllen Sie bitte dieses Formular aus und senden Sie es zurück.)");
|
||||
paragraph(`An ${COMPANY.name}, ${COMPANY.addressLine}, ${COMPANY.cityLine}, E-Mail: ${COMPANY.email}:`);
|
||||
paragraph(
|
||||
"Hiermit widerrufe(n) ich/wir (*) den von mir/uns (*) abgeschlossenen Vertrag über den Kauf der folgenden Waren (*)/die Erbringung der folgenden Dienstleistung (*)\n\n– Bestellt am (*)/erhalten am (*)\n– Name des/der Verbraucher(s)\n– Anschrift des/der Verbraucher(s)\n– Unterschrift des/der Verbraucher(s) (nur bei Mitteilung auf Papier)\n– Datum\n\n(*) Unzutreffendes streichen."
|
||||
);
|
||||
|
||||
// --- Page numbers, stamped last across every page now that the total is known ---
|
||||
const pageRange = doc.bufferedPageRange();
|
||||
for (let i = pageRange.start; i < pageRange.start + pageRange.count; i++) {
|
||||
doc.switchToPage(i);
|
||||
// Must stay within the document's own bottom margin (25pt) — placing
|
||||
// this any lower silently made pdfkit think the text overflowed the
|
||||
// page and auto-insert extra blank pages to fit it.
|
||||
doc
|
||||
.font("Helvetica")
|
||||
.fontSize(8)
|
||||
.fillColor(COLORS.muted)
|
||||
.text(`Seite ${i + 1} von ${pageRange.count}`, PAGE_RIGHT - 100, doc.page.height - 40, { width: 100, align: "right", lineBreak: false });
|
||||
}
|
||||
|
||||
doc.end();
|
||||
return stream;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import type { MedusaContainer } from "@medusajs/framework/types";
|
||||
|
||||
// Mirrors the tax setup we configured for the German tax region: Honig
|
||||
// (food) gets the reduced rate, everything else the standard rate. Order
|
||||
// line items don't reliably carry resolved tax_lines in our testing, so we
|
||||
// re-derive the rate from the product's own category instead of trusting
|
||||
// stored tax data.
|
||||
const REDUCED_RATE_CATEGORY = "Honig";
|
||||
const REDUCED_RATE = 7;
|
||||
const STANDARD_RATE = 19;
|
||||
|
||||
interface OrderItemLike {
|
||||
product_id?: string | null;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export async function resolveTaxBreakdown(
|
||||
container: MedusaContainer,
|
||||
items: OrderItemLike[],
|
||||
shippingTotal = 0
|
||||
): Promise<{ rate: number; net: number; tax: number }[]> {
|
||||
const productIds = [...new Set(items.map((i) => i.product_id).filter((id): id is string => !!id))];
|
||||
|
||||
const productModuleService = container.resolve(Modules.PRODUCT);
|
||||
const products = productIds.length
|
||||
? await productModuleService.listProducts({ id: productIds }, { select: ["id", "metadata"] })
|
||||
: [];
|
||||
const categoryByProductId = new Map(products.map((p) => [p.id, (p.metadata as any)?.category as string | undefined]));
|
||||
|
||||
// §14 UStG requires the net amount to be broken out per tax rate, not just
|
||||
// the tax amount, so we track both the gross total and the embedded tax
|
||||
// per bracket here.
|
||||
const grossByRate = new Map<number, number>();
|
||||
for (const item of items) {
|
||||
const category = item.product_id ? categoryByProductId.get(item.product_id) : undefined;
|
||||
const rate = category === REDUCED_RATE_CATEGORY ? REDUCED_RATE : STANDARD_RATE;
|
||||
grossByRate.set(rate, (grossByRate.get(rate) ?? 0) + item.total);
|
||||
}
|
||||
|
||||
// Shipping is a service, always taxed at the standard rate in our setup.
|
||||
if (shippingTotal) {
|
||||
grossByRate.set(STANDARD_RATE, (grossByRate.get(STANDARD_RATE) ?? 0) + shippingTotal);
|
||||
}
|
||||
|
||||
return [...grossByRate.entries()]
|
||||
.sort((a, b) => a[0] - b[0])
|
||||
.map(([rate, gross]) => {
|
||||
const net = gross / (1 + rate / 100);
|
||||
const tax = gross - net;
|
||||
return {
|
||||
rate,
|
||||
net: Math.round(net * 100) / 100,
|
||||
tax: Math.round(tax * 100) / 100,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import createMollieClient, { SequenceType } from "@mollie/api-client";
|
||||
import type { MollieClient } from "@mollie/api-client";
|
||||
|
||||
/**
|
||||
* Mollie-Anbindung für wiederkehrende Zahlungen.
|
||||
*
|
||||
* Ablauf laut Mollie:
|
||||
* 1. Kunde in Mollie anlegen -> customerId
|
||||
* 2. Erstzahlung mit sequenceType "first" -> Kunde erteilt das Mandat
|
||||
* 3. Folgezahlungen mit sequenceType "recurring" + mandateId, ohne Redirect
|
||||
*
|
||||
* Wählt der Kunde Karte oder PayPal, laufen die Folgezahlungen über dasselbe
|
||||
* Verfahren; bei allen anderen Verfahren über SEPA-Lastschrift. Dafür muss im
|
||||
* Mollie-Profil SEPA-Lastschrift oder Kreditkarte freigeschaltet sein.
|
||||
*
|
||||
* NICHT GETESTET: gegen die Mollie-Dokumentation geschrieben, aber ohne
|
||||
* echten API-Schlüssel nie ausgeführt. Vor dem Scharfschalten
|
||||
* `npx medusa exec ./src/scripts/check-subscriptions.ts` laufen lassen.
|
||||
*/
|
||||
|
||||
let client: MollieClient | null = null;
|
||||
|
||||
export function isMollieConfigured(): boolean {
|
||||
return Boolean(process.env.MOLLIE_API_KEY);
|
||||
}
|
||||
|
||||
export function getMollie(): MollieClient {
|
||||
if (!process.env.MOLLIE_API_KEY) {
|
||||
throw new Error("MOLLIE_API_KEY ist nicht gesetzt.");
|
||||
}
|
||||
if (!client) {
|
||||
client = createMollieClient({ apiKey: process.env.MOLLIE_API_KEY });
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
/** Beträge gehen bei Mollie als String mit zwei Nachkommastellen. */
|
||||
export function money(amount: number, currency = "EUR") {
|
||||
return { currency, value: amount.toFixed(2) };
|
||||
}
|
||||
|
||||
export async function ensureCustomer(params: {
|
||||
email: string;
|
||||
name?: string;
|
||||
existingId?: string | null;
|
||||
}): Promise<string> {
|
||||
const mollie = getMollie();
|
||||
if (params.existingId) {
|
||||
try {
|
||||
const existing = await mollie.customers.get(params.existingId);
|
||||
return existing.id;
|
||||
} catch {
|
||||
// Gelöscht oder aus einem anderen Konto — neu anlegen statt zu scheitern.
|
||||
}
|
||||
}
|
||||
const created = await mollie.customers.create({
|
||||
email: params.email,
|
||||
name: params.name || params.email,
|
||||
});
|
||||
return created.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstzahlung, die das Mandat erzeugt. Der Kunde wird zu Mollie geleitet und
|
||||
* kommt danach auf `redirectUrl` zurück.
|
||||
*/
|
||||
export async function createFirstPayment(params: {
|
||||
customerId: string;
|
||||
amount: number;
|
||||
description: string;
|
||||
redirectUrl: string;
|
||||
webhookUrl?: string;
|
||||
/** "creditcard" | "directdebit" | "paypal" — offen lassen für Mollies Auswahlseite. */
|
||||
method?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
currency?: string;
|
||||
}) {
|
||||
const mollie = getMollie();
|
||||
return mollie.payments.create({
|
||||
amount: money(params.amount, params.currency ?? "EUR"),
|
||||
description: params.description,
|
||||
redirectUrl: params.redirectUrl,
|
||||
...(params.webhookUrl ? { webhookUrl: params.webhookUrl } : {}),
|
||||
customerId: params.customerId,
|
||||
sequenceType: SequenceType.first,
|
||||
...(params.method ? { method: params.method as any } : {}),
|
||||
metadata: params.metadata as any,
|
||||
});
|
||||
}
|
||||
|
||||
/** Gültiges Mandat des Kunden suchen. */
|
||||
export async function findValidMandate(customerId: string): Promise<string | null> {
|
||||
const mollie = getMollie();
|
||||
const mandates = await mollie.customerMandates.page({ customerId });
|
||||
const valid = mandates.find((mandate: any) => mandate.status === "valid");
|
||||
return valid?.id ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folgezahlung ohne Zutun des Kunden. Braucht ein gültiges Mandat.
|
||||
*/
|
||||
export async function chargeRecurring(params: {
|
||||
customerId: string;
|
||||
mandateId: string;
|
||||
amount: number;
|
||||
description: string;
|
||||
webhookUrl?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
currency?: string;
|
||||
}) {
|
||||
const mollie = getMollie();
|
||||
return mollie.payments.create({
|
||||
amount: money(params.amount, params.currency ?? "EUR"),
|
||||
description: params.description,
|
||||
customerId: params.customerId,
|
||||
mandateId: params.mandateId,
|
||||
sequenceType: SequenceType.recurring,
|
||||
...(params.webhookUrl ? { webhookUrl: params.webhookUrl } : {}),
|
||||
metadata: params.metadata as any,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPayment(paymentId: string) {
|
||||
return getMollie().payments.get(paymentId);
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
/**
|
||||
* Texte der Kundenmails.
|
||||
*
|
||||
* Die Inhalte liegen bewusst hier und nicht als Vorlage bei einem
|
||||
* Dienstleister: die Bestellbestätigung ist nach § 312f BGB Vertragsinhalt
|
||||
* und muss dieselben Angaben tragen wie die Bestellung selbst.
|
||||
*
|
||||
* Die Summen werden wie in der Rechnung aus Einzelpreis und Menge gerechnet,
|
||||
* nicht aus Medusas berechneten Feldern — die liefern je nach angeforderter
|
||||
* Feldauswahl abweichende Werte (siehe Kommentar in invoice-handler.ts).
|
||||
*/
|
||||
|
||||
const SHOP = {
|
||||
name: "PLACE4BEES GmbH",
|
||||
web: "www.place4bees.com",
|
||||
email: "kontakt@place4bees.com",
|
||||
};
|
||||
|
||||
export type MailPosten = {
|
||||
title: string;
|
||||
quantity: number;
|
||||
unit_price: number;
|
||||
/**
|
||||
* Angaben, die der Kunde zu diesem Posten gemacht hat — bei der
|
||||
* Bienenpatenschaft der Name für Urkunde und Etikett. Sie stehen in der
|
||||
* Bestätigung, damit ein Tippfehler auffällt, bevor gedruckt wird.
|
||||
*/
|
||||
hinweis?: string | null;
|
||||
/** Kommt per E-Mail statt im Paket — beim Geschenkgutschein. */
|
||||
digital?: boolean;
|
||||
};
|
||||
|
||||
export type MailBestellung = {
|
||||
display_id: number | string;
|
||||
email: string;
|
||||
created_at: string | Date;
|
||||
currency_code: string;
|
||||
items: MailPosten[];
|
||||
shipping_methods: { name: string; amount: number }[];
|
||||
shipping_address: Record<string, any> | null;
|
||||
/** Gesetzt, wenn die Bestellung aus einem laufenden Abo stammt. */
|
||||
aus_abo?: boolean;
|
||||
/** Eingelöste Gutscheine; der Code steht nur gekürzt drin. */
|
||||
gutscheine?: { code: string; betrag: number }[];
|
||||
};
|
||||
|
||||
function euro(betrag: number, waehrung = "EUR"): string {
|
||||
return new Intl.NumberFormat("de-DE", {
|
||||
style: "currency",
|
||||
currency: waehrung.toUpperCase(),
|
||||
}).format(betrag);
|
||||
}
|
||||
|
||||
function runden(zahl: number): number {
|
||||
return Math.round(zahl * 100) / 100;
|
||||
}
|
||||
|
||||
/** Anrede ohne Geschlechtsannahme: der Vorname allein reicht und liegt vor. */
|
||||
function anrede(adresse: Record<string, any> | null): string {
|
||||
const name = [adresse?.first_name, adresse?.last_name].filter(Boolean).join(" ");
|
||||
return name ? `Hallo ${name},` : "Hallo,";
|
||||
}
|
||||
|
||||
function summen(bestellung: MailBestellung) {
|
||||
const posten = bestellung.items.map((item) => ({
|
||||
...item,
|
||||
gesamt: runden(item.unit_price * item.quantity),
|
||||
}));
|
||||
const ware = runden(posten.reduce((s, p) => s + p.gesamt, 0));
|
||||
const versand = runden(
|
||||
(bestellung.shipping_methods ?? []).reduce((s, m) => s + (m.amount ?? 0), 0)
|
||||
);
|
||||
const gesamt = runden(ware + versand);
|
||||
const abzug = runden((bestellung.gutscheine ?? []).reduce((s, g) => s + g.betrag, 0));
|
||||
return { posten, ware, versand, gesamt, abzug, zuZahlen: runden(Math.max(0, gesamt - abzug)) };
|
||||
}
|
||||
|
||||
/** Für Kundeneingaben im HTML-Teil der Mails. */
|
||||
function html(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function adressblock(adresse: Record<string, any> | null): string[] {
|
||||
if (!adresse) return [];
|
||||
return [
|
||||
[adresse.first_name, adresse.last_name].filter(Boolean).join(" "),
|
||||
adresse.company,
|
||||
adresse.address_1,
|
||||
adresse.address_2,
|
||||
[adresse.postal_code, adresse.city].filter(Boolean).join(" "),
|
||||
adresse.country_code ? String(adresse.country_code).toUpperCase() : null,
|
||||
].filter(Boolean) as string[];
|
||||
}
|
||||
|
||||
const RAHMEN = (inhalt: string) => `<!doctype html>
|
||||
<html lang="de"><head><meta charset="utf-8" /></head>
|
||||
<body style="margin:0;background:#f6f5f1;padding:24px;font-family:Arial,Helvetica,sans-serif;color:#1a1a1a;font-size:15px;line-height:1.55">
|
||||
<div style="max-width:600px;margin:0 auto;background:#ffffff;padding:32px">
|
||||
${inhalt}
|
||||
<p style="margin:32px 0 0;padding-top:20px;border-top:1px solid #dcdcd8;color:#6b6b66;font-size:13px">
|
||||
${SHOP.name} · ${SHOP.web} · <a href="mailto:${SHOP.email}" style="color:#8a5e05">${SHOP.email}</a>
|
||||
</p>
|
||||
</div>
|
||||
</body></html>`;
|
||||
|
||||
function postenTabelle(bestellung: MailBestellung): string {
|
||||
const { posten, ware, versand, gesamt, abzug, zuZahlen } = summen(bestellung);
|
||||
const w = bestellung.currency_code;
|
||||
const zeilen = posten
|
||||
.map(
|
||||
(p) => `<tr>
|
||||
<td style="padding:8px 0;border-bottom:1px solid #eeeeea">${p.quantity} × ${p.title}${
|
||||
p.hinweis
|
||||
? `<br /><span style="color:#6b6b66;font-size:13px">${p.hinweis}</span>`
|
||||
: ""
|
||||
}</td>
|
||||
<td style="padding:8px 0;border-bottom:1px solid #eeeeea;text-align:right;white-space:nowrap">${euro(p.gesamt, w)}</td>
|
||||
</tr>`
|
||||
)
|
||||
.join("");
|
||||
return `<table style="width:100%;border-collapse:collapse;margin:20px 0 0">
|
||||
${zeilen}
|
||||
<tr><td style="padding:8px 0">Zwischensumme</td><td style="padding:8px 0;text-align:right">${euro(ware, w)}</td></tr>
|
||||
${
|
||||
bestellung.shipping_methods?.length
|
||||
? `<tr><td style="padding:0 0 8px">Versand</td><td style="padding:0 0 8px;text-align:right">${euro(versand, w)}</td></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 #dcdcd8;text-align:right;font-weight:bold">${euro(gesamt, w)}</td>
|
||||
</tr>
|
||||
${
|
||||
abzug > 0
|
||||
? `${(bestellung.gutscheine ?? [])
|
||||
.map(
|
||||
(g) => `<tr><td style="padding:8px 0 0">Gutschein ${g.code}</td><td style="padding:8px 0 0;text-align:right">−${euro(g.betrag, w)}</td></tr>`
|
||||
)
|
||||
.join("")}
|
||||
<tr>
|
||||
<td style="padding:8px 0 0;font-weight:bold">Zu zahlen</td>
|
||||
<td style="padding:8px 0 0;text-align:right;font-weight:bold">${euro(zuZahlen, w)}</td>
|
||||
</tr>`
|
||||
: ""
|
||||
}
|
||||
</table>
|
||||
<p style="margin:10px 0 0;color:#6b6b66;font-size:13px">Alle Preise inklusive Umsatzsteuer.</p>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bestellbestätigung nach § 312f BGB.
|
||||
*
|
||||
* Bei einer Abo-Lieferung ändert sich der Ton: niemand hat gerade bestellt,
|
||||
* die Lieferung kommt aus einer Abmachung von früher. Der Rest — Posten,
|
||||
* Summen, Rechnung im Anhang — bleibt gleich, denn jede Lieferung ist ein
|
||||
* eigener Umsatz und braucht ihre eigene Bestätigung.
|
||||
*/
|
||||
export function bestellbestaetigung(bestellung: MailBestellung) {
|
||||
const abo = Boolean(bestellung.aus_abo);
|
||||
const { posten, ware, versand, gesamt, abzug, zuZahlen } = summen(bestellung);
|
||||
const w = bestellung.currency_code;
|
||||
const adresse = adressblock(bestellung.shipping_address);
|
||||
|
||||
// Ein Gutschein kommt per E-Mail. Liegt nur er im Warenkorb, gibt es kein
|
||||
// Paket und keine Sendungsnummer.
|
||||
const nurDigital = bestellung.items.length > 0 && bestellung.items.every((item) => item.digital);
|
||||
const mitGutschein = bestellung.items.some((item) => item.digital);
|
||||
|
||||
const ueberschrift = abo ? "Ihre nächste Abo-Lieferung" : "Danke für Ihre Bestellung";
|
||||
const einleitungZeilen = abo
|
||||
? [
|
||||
"Ihr Honig-Abo ist wieder dran — wir packen die Lieferung gerade.",
|
||||
"Sobald das Paket unterwegs ist, schicken wir Ihnen die Sendungsnummer.",
|
||||
]
|
||||
: nurDigital
|
||||
? [
|
||||
"wir haben Ihre Bestellung erhalten. Der Gutschein kommt per E-Mail,",
|
||||
"sobald die Zahlung bei uns eingegangen ist.",
|
||||
]
|
||||
: [
|
||||
"wir haben Ihre Bestellung erhalten und bereiten sie vor.",
|
||||
"Sobald das Paket unterwegs ist, schicken wir Ihnen die Sendungsnummer.",
|
||||
...(mitGutschein ? ["Der Gutschein kommt per E-Mail, sobald die Zahlung eingegangen ist."] : []),
|
||||
];
|
||||
const einleitung = abo
|
||||
? `${einleitungZeilen.join("\n ")}
|
||||
Die Rechnung zu dieser Lieferung liegt bei.`
|
||||
: einleitungZeilen.join("\n ");
|
||||
|
||||
const html = RAHMEN(`
|
||||
<h1 style="margin:0 0 4px;font-size:22px">${ueberschrift}</h1>
|
||||
<p style="margin:0;color:#6b6b66">Bestellnummer ${bestellung.display_id}</p>
|
||||
<p style="margin:24px 0 0">${anrede(bestellung.shipping_address)}</p>
|
||||
<p style="margin:12px 0 0">${einleitung}</p>
|
||||
${postenTabelle(bestellung)}
|
||||
${
|
||||
adresse.length
|
||||
? `<h2 style="margin:28px 0 6px;font-size:16px">${nurDigital ? "Rechnungsadresse" : "Lieferadresse"}</h2>
|
||||
<p style="margin:0;color:#4a4a45">${adresse.join("<br />")}</p>`
|
||||
: ""
|
||||
}
|
||||
<p style="margin:28px 0 0;color:#6b6b66;font-size:13px">
|
||||
Diese E-Mail bestätigt den Eingang Ihrer Bestellung. Die Rechnung liegt
|
||||
als PDF bei. Ihr Widerrufsrecht und die Bedingungen finden Sie unter
|
||||
${SHOP.web}.
|
||||
</p>`);
|
||||
|
||||
const text = [
|
||||
`${ueberschrift} — Bestellnummer ${bestellung.display_id}`,
|
||||
"",
|
||||
anrede(bestellung.shipping_address),
|
||||
"",
|
||||
...einleitungZeilen,
|
||||
"",
|
||||
...posten.flatMap((p) => [
|
||||
` ${p.quantity} × ${p.title} ${euro(p.gesamt, w)}`,
|
||||
...(p.hinweis ? [` ${p.hinweis}`] : []),
|
||||
]),
|
||||
` Zwischensumme ${euro(ware, w)}`,
|
||||
...(bestellung.shipping_methods?.length ? [` Versand ${euro(versand, w)}`] : []),
|
||||
` Gesamt ${euro(gesamt, w)}`,
|
||||
...(abzug > 0
|
||||
? [
|
||||
...(bestellung.gutscheine ?? []).map((g) => ` Gutschein ${g.code} −${euro(g.betrag, w)}`),
|
||||
` Zu zahlen ${euro(zuZahlen, w)}`,
|
||||
]
|
||||
: []),
|
||||
" Alle Preise inklusive Umsatzsteuer.",
|
||||
"",
|
||||
"Die Rechnung liegt dieser E-Mail als PDF bei.",
|
||||
"",
|
||||
...(adresse.length
|
||||
? [nurDigital ? "Rechnungsadresse:" : "Lieferadresse:", ...adresse.map((z) => " " + z), ""]
|
||||
: []),
|
||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
subject: abo
|
||||
? `Ihre Abo-Lieferung ${bestellung.display_id} von place4bees`
|
||||
: `Ihre Bestellung ${bestellung.display_id} bei place4bees`,
|
||||
html,
|
||||
text,
|
||||
};
|
||||
}
|
||||
|
||||
export type Sendung = {
|
||||
tracking_number: string;
|
||||
tracking_url?: string | null;
|
||||
};
|
||||
|
||||
/** Versandnachricht mit Sendungsnummer und Stand der Sendung. */
|
||||
export function versandnachricht(bestellung: MailBestellung, sendungen: Sendung[]) {
|
||||
const versandart = (bestellung.shipping_methods ?? [])[0]?.name ?? null;
|
||||
|
||||
const nummern = sendungen
|
||||
.map(
|
||||
(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>`
|
||||
: ""
|
||||
}
|
||||
</li>`
|
||||
)
|
||||
.join("");
|
||||
|
||||
const html = RAHMEN(`
|
||||
<h1 style="margin:0 0 4px;font-size:22px">Ihre Bestellung ist unterwegs</h1>
|
||||
<p style="margin:0;color:#6b6b66">Bestellnummer ${bestellung.display_id}</p>
|
||||
<p style="margin:24px 0 0">${anrede(bestellung.shipping_address)}</p>
|
||||
<p style="margin:12px 0 0">
|
||||
wir haben Ihr Paket verpackt und ${versandart ? `mit ${versandart} ` : ""}auf den Weg gebracht.
|
||||
</p>
|
||||
<h2 style="margin:24px 0 8px;font-size:16px">Sendungsnummer</h2>
|
||||
<ul style="margin:0;padding-left:18px">${nummern}</ul>
|
||||
<p style="margin:16px 0 0;padding:12px 14px;background:#faf6ec">
|
||||
<strong>Stand:</strong> Sendung angemeldet — das Paket ist beim
|
||||
Versanddienstleister eingebucht. Bis zur ersten Statusmeldung in der
|
||||
Verfolgung können einige Stunden vergehen.
|
||||
</p>
|
||||
${postenTabelle(bestellung)}`);
|
||||
|
||||
const text = [
|
||||
`Ihre Bestellung ${bestellung.display_id} ist unterwegs`,
|
||||
"",
|
||||
anrede(bestellung.shipping_address),
|
||||
"",
|
||||
`wir haben Ihr Paket verpackt und ${versandart ? `mit ${versandart} ` : ""}auf den Weg gebracht.`,
|
||||
"",
|
||||
"Sendungsnummer:",
|
||||
...sendungen.map((s) => ` ${s.tracking_number}${s.tracking_url ? ` — ${s.tracking_url}` : ""}`),
|
||||
"",
|
||||
"Stand: Sendung angemeldet — das Paket ist beim Versanddienstleister",
|
||||
"eingebucht. Bis zur ersten Statusmeldung können einige Stunden vergehen.",
|
||||
"",
|
||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||
].join("\n");
|
||||
|
||||
return { subject: `Ihre Bestellung ${bestellung.display_id} ist unterwegs`, html, text };
|
||||
}
|
||||
|
||||
/* --- Geschenk-Abo ---------------------------------------------------------
|
||||
* Der Beschenkte hat nichts gekauft. Seine Mails nennen deshalb Sorte,
|
||||
* Menge und Sendungsnummer, aber keine Beträge — Preise und Rechnung gehen
|
||||
* ausschließlich an den Käufer.
|
||||
*/
|
||||
|
||||
export type GeschenkAbo = {
|
||||
empfaengerName: string;
|
||||
/** Wer schenkt. `null`, wenn niemand genannt wurde. */
|
||||
schenkerName: string | null;
|
||||
/** Gesamtzahl der Lieferungen. */
|
||||
lieferungen: number;
|
||||
/** "monatlich", "vierteljährlich", "halbjährlich". */
|
||||
rhythmus: string;
|
||||
groesse?: string | null;
|
||||
};
|
||||
|
||||
/** Ankündigung an den Beschenkten, sobald das Geschenk gekauft ist. */
|
||||
export function geschenkAnkuendigung(abo: GeschenkAbo) {
|
||||
const von = abo.schenkerName ? `${abo.schenkerName} schenkt Ihnen` : "Jemand schenkt Ihnen";
|
||||
const umfang = `${abo.lieferungen} Lieferungen, ${abo.rhythmus}${abo.groesse ? `, je ${abo.groesse}` : ""}`;
|
||||
|
||||
const html = RAHMEN(`
|
||||
<h1 style="margin:0 0 4px;font-size:22px">Für Sie: ein Honig-Abo</h1>
|
||||
<p style="margin:24px 0 0">Hallo ${abo.empfaengerName},</p>
|
||||
<p style="margin:12px 0 0">
|
||||
${von} ein Honig-Abo von place4bees — ${umfang}. Der Honig kommt aus
|
||||
unseren eigenen Völkern, von Hand abgefüllt in Hamburg.
|
||||
</p>
|
||||
<p style="margin:16px 0 0">
|
||||
Sie müssen nichts tun. Die erste Sendung ist schon unterwegs, und zu
|
||||
jedem weiteren Paket schicken wir Ihnen die Sendungsnummer.
|
||||
</p>
|
||||
<p style="margin:24px 0 0;color:#6b6b66;font-size:13px">
|
||||
Stimmt die Lieferadresse nicht oder passt der Zeitpunkt nicht?
|
||||
Schreiben Sie uns einfach.
|
||||
</p>`);
|
||||
|
||||
const text = [
|
||||
"Für Sie: ein Honig-Abo",
|
||||
"",
|
||||
`Hallo ${abo.empfaengerName},`,
|
||||
"",
|
||||
`${von} ein Honig-Abo von place4bees — ${umfang}.`,
|
||||
"Der Honig kommt aus unseren eigenen Völkern, von Hand abgefüllt in Hamburg.",
|
||||
"",
|
||||
"Sie müssen nichts tun. Die erste Sendung ist schon unterwegs, und zu",
|
||||
"jedem weiteren Paket schicken wir Ihnen die Sendungsnummer.",
|
||||
"",
|
||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||
].join("\n");
|
||||
|
||||
return { subject: "Für Sie: ein Honig-Abo von place4bees", html, text };
|
||||
}
|
||||
|
||||
/** Versandnachricht an den Beschenkten — dieselbe Sendung, ohne Beträge. */
|
||||
export function geschenkVersandnachricht(
|
||||
empfaengerName: string,
|
||||
posten: MailPosten[],
|
||||
sendungen: Sendung[],
|
||||
verbleibend: number
|
||||
) {
|
||||
const nummern = sendungen
|
||||
.map(
|
||||
(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>` : ""
|
||||
}</li>`
|
||||
)
|
||||
.join("");
|
||||
|
||||
const rest =
|
||||
verbleibend > 0
|
||||
? `Danach kommen noch ${verbleibend} weitere Lieferungen.`
|
||||
: "Das war die letzte Lieferung Ihres Abos.";
|
||||
|
||||
const html = RAHMEN(`
|
||||
<h1 style="margin:0 0 4px;font-size:22px">Ihr Honig ist unterwegs</h1>
|
||||
<p style="margin:24px 0 0">Hallo ${empfaengerName},</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>
|
||||
<ul style="margin:0;padding-left:18px">
|
||||
${posten.map((p) => `<li style="margin:0 0 4px">${p.quantity} × ${p.title}</li>`).join("")}
|
||||
</ul>
|
||||
<h2 style="margin:24px 0 8px;font-size:16px">Sendungsnummer</h2>
|
||||
<ul style="margin:0;padding-left:18px">${nummern}</ul>
|
||||
<p style="margin:16px 0 0;padding:12px 14px;background:#faf6ec">
|
||||
<strong>Stand:</strong> Sendung angemeldet — das Paket ist beim
|
||||
Versanddienstleister eingebucht. ${rest}
|
||||
</p>`);
|
||||
|
||||
const text = [
|
||||
"Ihr Honig ist unterwegs",
|
||||
"",
|
||||
`Hallo ${empfaengerName},`,
|
||||
"",
|
||||
"die nächste Lieferung Ihres Honig-Abos ist auf dem Weg.",
|
||||
"",
|
||||
"Im Paket:",
|
||||
...posten.map((p) => ` ${p.quantity} × ${p.title}`),
|
||||
"",
|
||||
"Sendungsnummer:",
|
||||
...sendungen.map((s) => ` ${s.tracking_number}${s.tracking_url ? ` — ${s.tracking_url}` : ""}`),
|
||||
"",
|
||||
`Stand: Sendung angemeldet. ${rest}`,
|
||||
"",
|
||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||
].join("\n");
|
||||
|
||||
return { subject: "Ihr Honig ist unterwegs", html, text };
|
||||
}
|
||||
|
||||
/* --- Bienenpatenschaft ----------------------------------------------------
|
||||
* Wird eine Patenschaft verschenkt, erfährt der Beschenkte sonst bis zur
|
||||
* Ernte im Herbst nichts davon. Die Ankündigung nennt deshalb, was ihn
|
||||
* erwartet und wann — aber keine Beträge: bezahlt hat jemand anderes.
|
||||
*/
|
||||
|
||||
export type PatenschaftGeschenk = {
|
||||
/** Name auf Urkunde und Etikett. */
|
||||
name: string;
|
||||
/** Wer schenkt. `null`, wenn niemand genannt wurde. */
|
||||
schenkerName: string | null;
|
||||
};
|
||||
|
||||
export function patenschaftAnkuendigung(geschenk: PatenschaftGeschenk) {
|
||||
const von = geschenk.schenkerName
|
||||
? `${geschenk.schenkerName} schenkt Ihnen`
|
||||
: "Jemand schenkt Ihnen";
|
||||
|
||||
// Die Leistungen stehen so in der Produktbeschreibung — hier nichts
|
||||
// dazuerfinden, was der Shop nicht verspricht.
|
||||
const leistungen = [
|
||||
"eine hochwertige Urkunde über die Patenschaft",
|
||||
"die Patenschaft für ein Jahr",
|
||||
"vier Honiggläser mit persönlichem Etikett, mit Honig aus Ihrem Bienenvolk",
|
||||
"Bilder und Nachrichten vom Volk, dreimal im Jahr per E-Mail",
|
||||
];
|
||||
|
||||
const html = RAHMEN(`
|
||||
<h1 style="margin:0 0 4px;font-size:22px">Für Sie: eine Bienenpatenschaft</h1>
|
||||
<p style="margin:24px 0 0">Hallo ${geschenk.name},</p>
|
||||
<p style="margin:12px 0 0">
|
||||
${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.
|
||||
</p>
|
||||
<h2 style="margin:24px 0 8px;font-size:16px">Was dazugehört</h2>
|
||||
<ul style="margin:0;padding-left:18px">
|
||||
${leistungen.map((l) => `<li style="margin:0 0 5px">${l}</li>`).join("")}
|
||||
</ul>
|
||||
<p style="margin:20px 0 0;padding:12px 14px;background:#faf6ec">
|
||||
Geerntet wird zweimal im Jahr. Ihren eigenen Honig bekommen Sie am Ende
|
||||
der Bienensaison, im Oktober oder November.
|
||||
</p>
|
||||
<p style="margin:24px 0 0;color:#6b6b66;font-size:13px">
|
||||
Sie müssen nichts tun. Fragen beantworten wir gern — einfach antworten.
|
||||
</p>`);
|
||||
|
||||
const text = [
|
||||
"Für Sie: eine Bienenpatenschaft",
|
||||
"",
|
||||
`Hallo ${geschenk.name},`,
|
||||
"",
|
||||
`${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.",
|
||||
"",
|
||||
"Was dazugehört:",
|
||||
...leistungen.map((l) => ` - ${l}`),
|
||||
"",
|
||||
"Geerntet wird zweimal im Jahr. Ihren eigenen Honig bekommen Sie am Ende",
|
||||
"der Bienensaison, im Oktober oder November.",
|
||||
"",
|
||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||
].join("\n");
|
||||
|
||||
return { subject: "Für Sie: eine Bienenpatenschaft bei place4bees", html, text };
|
||||
}
|
||||
|
||||
/* --- Geschenkgutschein ----------------------------------------------------
|
||||
* Der Code ist das Geld. Er steht groß in der Mail, dazu, wie man ihn
|
||||
* einlöst — und dass ein Rest nicht verfällt, sondern auf dem Code bleibt.
|
||||
*/
|
||||
|
||||
export type GutscheinInhalt = {
|
||||
code: string;
|
||||
betrag: number;
|
||||
waehrung: string;
|
||||
/** Anrede. Beim Geschenk der Beschenkte, sonst der Käufer. */
|
||||
empfaengerName: string | null;
|
||||
/** Nur beim Geschenk: wer schenkt. */
|
||||
schenkerName: string | null;
|
||||
/** Persönliche Nachricht des Schenkenden, falls angegeben. */
|
||||
nachricht: string | null;
|
||||
geschenk: boolean;
|
||||
};
|
||||
|
||||
/** Der Gutschein selbst — an den Beschenkten oder an den Käufer. */
|
||||
export function gutscheinMail(g: GutscheinInhalt) {
|
||||
const betrag = euro(g.betrag, g.waehrung);
|
||||
const hallo = g.empfaengerName ? `Hallo ${g.empfaengerName},` : "Hallo,";
|
||||
const einleitung = g.geschenk
|
||||
? `${g.schenkerName ? `${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.`;
|
||||
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.",
|
||||
"Sie müssen nicht alles auf einmal ausgeben: Was übrig bleibt, bleibt als Guthaben auf dem Code und lässt sich beim nächsten Einkauf einlösen.",
|
||||
];
|
||||
|
||||
const inhalt = RAHMEN(`
|
||||
<h1 style="margin:0 0 4px;font-size:22px">${g.geschenk ? "Für Sie: ein Gutschein" : "Ihr Gutschein"}</h1>
|
||||
<p style="margin:24px 0 0">${html(hallo)}</p>
|
||||
<p style="margin:12px 0 0">${html(einleitung)}</p>
|
||||
${
|
||||
g.nachricht
|
||||
? `<p style="margin:16px 0 0;padding:12px 14px;background:#faf6ec;white-space:pre-line">${html(g.nachricht)}</p>`
|
||||
: ""
|
||||
}
|
||||
<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: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>
|
||||
</div>
|
||||
<h2 style="margin:24px 0 8px;font-size:16px">So lösen Sie ihn ein</h2>
|
||||
${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:24px 0 0;color:#6b6b66;font-size:13px">
|
||||
Bewahren Sie diese E-Mail gut auf: Wer den Code kennt, kann das Guthaben
|
||||
einlösen. Eine Barauszahlung ist nicht möglich.
|
||||
</p>`);
|
||||
|
||||
const text = [
|
||||
g.geschenk ? "Für Sie: ein Gutschein" : "Ihr Gutschein",
|
||||
"",
|
||||
hallo,
|
||||
"",
|
||||
einleitung,
|
||||
...(g.nachricht ? ["", g.nachricht] : []),
|
||||
"",
|
||||
`Gutscheincode: ${g.code}`,
|
||||
`Wert: ${betrag}`,
|
||||
"",
|
||||
"So lösen Sie ihn ein:",
|
||||
...einloesen,
|
||||
"",
|
||||
`Zum Shop: https://${SHOP.web}/shop`,
|
||||
"",
|
||||
"Bewahren Sie diese E-Mail gut auf: Wer den Code kennt, kann das Guthaben",
|
||||
"einlösen. Eine Barauszahlung ist nicht möglich.",
|
||||
"",
|
||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
subject: g.geschenk
|
||||
? `Für Sie: ein Gutschein über ${betrag} von place4bees`
|
||||
: `Ihr Gutschein über ${betrag} von place4bees`,
|
||||
html: inhalt,
|
||||
text,
|
||||
};
|
||||
}
|
||||
|
||||
export type GutscheinVersendet = {
|
||||
code: string;
|
||||
betrag: number;
|
||||
waehrung: string;
|
||||
empfaengerEmail: string;
|
||||
empfaengerName: string | null;
|
||||
kaeuferName: string | null;
|
||||
};
|
||||
|
||||
/** Bestätigung an den Käufer, dass der verschenkte Gutschein raus ist. */
|
||||
export function gutscheinVersendetMail(g: GutscheinVersendet) {
|
||||
const betrag = euro(g.betrag, g.waehrung);
|
||||
const an = g.empfaengerName ? `${g.empfaengerName} (${g.empfaengerEmail})` : g.empfaengerEmail;
|
||||
const hallo = g.kaeuferName ? `Hallo ${g.kaeuferName},` : "Hallo,";
|
||||
|
||||
const inhalt = RAHMEN(`
|
||||
<h1 style="margin:0 0 4px;font-size:22px">Ihr Gutschein ist verschickt</h1>
|
||||
<p style="margin:24px 0 0">${html(hallo)}</p>
|
||||
<p style="margin:12px 0 0">
|
||||
Ihre Zahlung ist eingegangen. Den Gutschein über ${betrag} haben wir eben
|
||||
an ${html(an)} geschickt.
|
||||
</p>
|
||||
<p style="margin:16px 0 0">
|
||||
Zur Sicherheit der Code auch für Sie: <strong style="font-family:'Courier New',Courier,monospace">${html(g.code)}</strong>.
|
||||
Sollte die Mail nicht ankommen, können Sie ihn einfach weitergeben.
|
||||
</p>`);
|
||||
|
||||
const text = [
|
||||
"Ihr Gutschein ist verschickt",
|
||||
"",
|
||||
hallo,
|
||||
"",
|
||||
`Ihre Zahlung ist eingegangen. Den Gutschein über ${betrag} haben wir eben an ${an} geschickt.`,
|
||||
"",
|
||||
`Zur Sicherheit der Code auch für Sie: ${g.code}`,
|
||||
"Sollte die Mail nicht ankommen, können Sie ihn einfach weitergeben.",
|
||||
"",
|
||||
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||
].join("\n");
|
||||
|
||||
return { subject: `Ihr Gutschein über ${betrag} ist verschickt`, html: inhalt, text };
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
||||
import { varietyIdsFromMetadata } from "./subscription-varieties";
|
||||
import { giftFromMetadata, type GiftDetails } from "./gift-subscription";
|
||||
|
||||
/**
|
||||
* Erkennt Abo-Posten und legt daraus Abos an.
|
||||
*
|
||||
* Ein Posten gilt als Abo, wenn sein Produkt `metadata.subscription` trägt.
|
||||
* Intervall und Größe stehen als Metadaten an der Variante, damit hier keine
|
||||
* deutschen Beschriftungen geparst werden müssen.
|
||||
*/
|
||||
|
||||
export type SubscriptionLine = {
|
||||
lineItemId: string;
|
||||
variantId: string;
|
||||
quantity: number;
|
||||
interval: string;
|
||||
size: string;
|
||||
selection: "fixed" | "random";
|
||||
/** Nur bei fester Sorte: die Variante der gewünschten Honigsorte. */
|
||||
fixedVariantId: string | null;
|
||||
/**
|
||||
* Nur bei fester Sorte: eine Variante je Glas. Leer, wenn der Posten noch
|
||||
* die alte Form mit einer Sorte für alle Gläser trägt.
|
||||
*/
|
||||
fixedVariantIds: string[];
|
||||
/**
|
||||
* Nur beim Geschenk: Laufzeit und Empfänger. Die Menge des Postens ist
|
||||
* dann Gläser × Lieferungen — bezahlt wird alles auf einmal.
|
||||
*/
|
||||
gift: GiftDetails | null;
|
||||
};
|
||||
|
||||
const CART_FIELDS = [
|
||||
"id",
|
||||
"email",
|
||||
"region_id",
|
||||
"currency_code",
|
||||
"customer_id",
|
||||
"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.id",
|
||||
"items.variant.product.metadata",
|
||||
];
|
||||
|
||||
export const SUBSCRIPTION_CART_FIELDS = CART_FIELDS;
|
||||
|
||||
/** Abo-Posten eines Warenkorbs oder einer Bestellung herauslesen. */
|
||||
export function extractSubscriptionLines(container: { items?: any[] }): SubscriptionLine[] {
|
||||
const lines: SubscriptionLine[] = [];
|
||||
for (const item of container.items ?? []) {
|
||||
const product = item.variant?.product;
|
||||
if (!product?.metadata?.subscription) continue;
|
||||
|
||||
const interval = item.variant?.metadata?.subscription_interval;
|
||||
const size = item.variant?.metadata?.subscription_size;
|
||||
if (!interval || !size) {
|
||||
throw new Error(
|
||||
`Abo-Posten ${item.id} hat keine Intervall-/Größenangabe an der Variante. ` +
|
||||
"Wurde das Produkt von Hand angelegt statt über setup-subscription-product?"
|
||||
);
|
||||
}
|
||||
|
||||
const selection = item.metadata?.subscription_selection === "fixed" ? "fixed" : "random";
|
||||
const fixedVariantIds = selection === "fixed" ? varietyIdsFromMetadata(item.metadata) : [];
|
||||
const gift = giftFromMetadata(item.metadata);
|
||||
|
||||
// Beim Geschenk stehen im Posten die Gläser aller Lieferungen. Je
|
||||
// Lieferung gehen davon nur `quantity / deliveries` Gläser raus.
|
||||
const quantity = item.quantity ?? 1;
|
||||
const glaeserJeLieferung = gift ? Math.max(1, Math.round(quantity / gift.deliveries)) : quantity;
|
||||
|
||||
lines.push({
|
||||
lineItemId: item.id,
|
||||
variantId: item.variant_id ?? item.variant?.id,
|
||||
quantity: glaeserJeLieferung,
|
||||
gift,
|
||||
interval,
|
||||
size,
|
||||
selection,
|
||||
// Erster Eintrag der Liste, sonst die alte Einzelangabe: das Feld
|
||||
// bleibt für Abos gültig, bei denen alle Gläser dieselbe Sorte haben.
|
||||
fixedVariantId:
|
||||
selection === "fixed"
|
||||
? (fixedVariantIds[0] ?? item.metadata?.subscription_variant_id ?? null)
|
||||
: null,
|
||||
fixedVariantIds,
|
||||
});
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function hasSubscriptionLines(container: { items?: any[] }): boolean {
|
||||
return (container.items ?? []).some((item: any) => item.variant?.product?.metadata?.subscription);
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt für jeden Abo-Posten einer abgeschlossenen Bestellung ein Abo an.
|
||||
*
|
||||
* Der erste Termin liegt ein Intervall in der Zukunft: die erste Lieferung
|
||||
* ist ja gerade die Bestellung selbst.
|
||||
*/
|
||||
export async function createSubscriptionsFromOrder(params: {
|
||||
container: any;
|
||||
order: any;
|
||||
mollieCustomerId: string;
|
||||
mollieMandateId: string;
|
||||
paymentMethod?: string | null;
|
||||
}) {
|
||||
const { container, order, mollieCustomerId, mollieMandateId, paymentMethod } = params;
|
||||
const service: any = container.resolve(SUBSCRIPTION_MODULE);
|
||||
|
||||
const lines = extractSubscriptionLines(order);
|
||||
const created: any[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
const subscription = await service.createSubscriptions({
|
||||
customer_id: order.customer_id ?? null,
|
||||
email: order.email,
|
||||
selection: line.selection,
|
||||
variant_id: line.fixedVariantId,
|
||||
variant_ids: line.fixedVariantIds.length ? line.fixedVariantIds : null,
|
||||
// Zählt als bereits geliefert, damit die nächste Zufallssorte eine
|
||||
// andere ist als die aus dieser ersten Lieferung.
|
||||
last_variant_id: line.fixedVariantId,
|
||||
size: line.size,
|
||||
quantity: line.quantity,
|
||||
interval: line.interval,
|
||||
// Beim Geschenk zählt die erste Lieferung schon mit: sie geht mit der
|
||||
// Bestellung raus, es bleiben also eine weniger als gekauft.
|
||||
prepaid: Boolean(line.gift),
|
||||
remaining_deliveries: line.gift ? line.gift.deliveries - 1 : null,
|
||||
gift_recipient_name: line.gift?.recipientName ?? null,
|
||||
gift_recipient_email: line.gift?.recipientEmail ?? null,
|
||||
gift_sender_name: line.gift?.senderName ?? null,
|
||||
next_order_at: service.computeNextOrderDate(line.interval, new Date()),
|
||||
last_order_at: new Date(),
|
||||
status: "active",
|
||||
mollie_customer_id: mollieCustomerId,
|
||||
mollie_mandate_id: mollieMandateId,
|
||||
payment_method: paymentMethod ?? null,
|
||||
shipping_address: order.shipping_address ?? null,
|
||||
shipping_option_id: order.shipping_methods?.[0]?.shipping_option_id ?? null,
|
||||
region_id: order.region_id,
|
||||
currency_code: order.currency_code ?? "eur",
|
||||
sales_channel_id: order.sales_channel_id ?? null,
|
||||
});
|
||||
created.push(Array.isArray(subscription) ? subscription[0] : subscription);
|
||||
}
|
||||
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt die Abos für verschenkte Lieferungen einer Bestellung an.
|
||||
*
|
||||
* Getrennt von `createSubscriptionsFromOrder`, weil hier alles fehlt, was
|
||||
* ein laufendes Abo braucht: kein Mandat, keine Abbuchung, kein Mollie. Ein
|
||||
* Geschenk ist bezahlt, wenn die Bestellung bezahlt ist.
|
||||
*
|
||||
* Wird über `order.placed` ausgelöst und muss deshalb erkennen, was schon
|
||||
* angelegt wurde — dieselbe Bestellung darf nicht zweimal zu Abos führen.
|
||||
*/
|
||||
export async function createGiftSubscriptionsFromOrder(params: {
|
||||
container: any;
|
||||
order: any;
|
||||
}) {
|
||||
const { container, order } = params;
|
||||
const service: any = container.resolve(SUBSCRIPTION_MODULE);
|
||||
|
||||
const geschenke = extractSubscriptionLines(order).filter((line) => line.gift);
|
||||
if (!geschenke.length) return [];
|
||||
|
||||
const created: any[] = [];
|
||||
for (const line of geschenke) {
|
||||
// Schutz gegen doppelte Anlage: der Posten der Bestellung ist eindeutig.
|
||||
const schon = await service.listSubscriptions({ source_line_item_id: line.lineItemId });
|
||||
if (schon?.length) continue;
|
||||
|
||||
const subscription = await service.createSubscriptions({
|
||||
customer_id: order.customer_id ?? null,
|
||||
email: order.email,
|
||||
source_line_item_id: line.lineItemId,
|
||||
selection: line.selection,
|
||||
variant_id: line.fixedVariantId,
|
||||
variant_ids: line.fixedVariantIds.length ? line.fixedVariantIds : null,
|
||||
last_variant_id: line.fixedVariantId,
|
||||
size: line.size,
|
||||
quantity: line.quantity,
|
||||
interval: line.interval,
|
||||
prepaid: true,
|
||||
remaining_deliveries: line.gift!.deliveries - 1,
|
||||
gift_recipient_name: line.gift!.recipientName,
|
||||
gift_recipient_email: line.gift!.recipientEmail,
|
||||
gift_sender_name: line.gift!.senderName,
|
||||
next_order_at: service.computeNextOrderDate(line.interval, new Date()),
|
||||
last_order_at: new Date(),
|
||||
status: "active",
|
||||
shipping_address: order.shipping_address ?? null,
|
||||
shipping_option_id: order.shipping_methods?.[0]?.shipping_option_id ?? null,
|
||||
region_id: order.region_id,
|
||||
currency_code: order.currency_code ?? "eur",
|
||||
sales_channel_id: order.sales_channel_id ?? null,
|
||||
});
|
||||
created.push(Array.isArray(subscription) ? subscription[0] : subscription);
|
||||
}
|
||||
|
||||
return created;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { createPromotionsWorkflow, updatePromotionsWorkflow } from "@medusajs/core-flows";
|
||||
|
||||
/**
|
||||
* Der Abo-Rabatt läuft über Medusas eigene Rabatt-Engine statt über eigene
|
||||
* Rechnerei: nur so stimmen Zwischensumme, Steuer und Gesamtbetrag, und der
|
||||
* Rabatt taucht auf Rechnung und im Admin auf.
|
||||
*
|
||||
* Es gibt genau eine Promotion mit diesem Code. Die Einstellungsseite hält
|
||||
* sie mit dem eingestellten Prozentsatz im Gleichstand.
|
||||
*/
|
||||
export const SUBSCRIPTION_PROMO_CODE = "ABO-RABATT";
|
||||
|
||||
export async function syncSubscriptionPromotion(container: any, percent: number) {
|
||||
const query = container.resolve("query");
|
||||
|
||||
const { data: existing } = await query.graph({
|
||||
entity: "promotion",
|
||||
fields: ["id", "code", "status", "application_method.id", "application_method.value"],
|
||||
filters: { code: SUBSCRIPTION_PROMO_CODE },
|
||||
});
|
||||
const promotion = existing?.[0];
|
||||
|
||||
// 0 % bedeutet: kein Rabatt. Die Promotion wird stillgelegt statt gelöscht,
|
||||
// damit bereits damit erstellte Bestellungen ihre Historie behalten.
|
||||
const status = percent > 0 ? "active" : "inactive";
|
||||
|
||||
if (!promotion) {
|
||||
if (percent <= 0) return null;
|
||||
const { result } = await createPromotionsWorkflow(container).run({
|
||||
input: {
|
||||
promotionsData: [
|
||||
{
|
||||
code: SUBSCRIPTION_PROMO_CODE,
|
||||
type: "standard",
|
||||
status: "active",
|
||||
// Bewusst nicht automatisch: der Rabatt soll nur bei
|
||||
// Abo-Bestellungen greifen, nicht bei jedem Warenkorb.
|
||||
is_automatic: false,
|
||||
application_method: {
|
||||
type: "percentage",
|
||||
target_type: "items",
|
||||
allocation: "each",
|
||||
value: percent,
|
||||
max_quantity: 100,
|
||||
},
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
});
|
||||
return Array.isArray(result) ? result[0] : result;
|
||||
}
|
||||
|
||||
// Bei 0 % nur stilllegen: Medusas Rabatt-Validierung lässt den Wert 0
|
||||
// nicht zu ("value should be a percentage number between 0 and 100"), der
|
||||
// alte Prozentsatz bleibt deshalb stehen und die Promotion wird inaktiv.
|
||||
const { result } = await updatePromotionsWorkflow(container).run({
|
||||
input: {
|
||||
promotionsData: [
|
||||
{
|
||||
id: promotion.id,
|
||||
status,
|
||||
...(percent > 0 && promotion.application_method?.id
|
||||
? {
|
||||
application_method: {
|
||||
id: promotion.application_method.id,
|
||||
value: percent,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
});
|
||||
return Array.isArray(result) ? result[0] : result;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Die Sorten eines Abos — eine je Glas.
|
||||
*
|
||||
* Ein Abo mit fester Sorte darf über mehrere Gläser verschiedene Sorten
|
||||
* haben. Gespeichert ist das als Liste an `variant_ids`; ältere Abos kennen
|
||||
* nur ein einzelnes `variant_id` für alle Gläser.
|
||||
*
|
||||
* Damit beides an einer Stelle zusammenläuft und nirgends sonst über die
|
||||
* Form nachgedacht werden muss, geht jeder Lesezugriff über diese Datei.
|
||||
*/
|
||||
|
||||
export type SubscriptionVarietySource = {
|
||||
selection?: string | null;
|
||||
variant_id?: string | null;
|
||||
variant_ids?: unknown;
|
||||
quantity?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Eine Variantenkennung je Glas, immer `quantity` Einträge lang.
|
||||
*
|
||||
* Leer bei Überraschungshonig und dann, wenn gar keine Sorte hinterlegt ist.
|
||||
* Ist die Liste kürzer als die Menge — etwa weil das Abo aus der Zeit vor
|
||||
* der Sortenwahl je Glas stammt oder weil die Menge später erhöht wurde —,
|
||||
* füllen die letzte Sorte der Liste beziehungsweise `variant_id` den Rest.
|
||||
*/
|
||||
export function varietyPerGlass(subscription: SubscriptionVarietySource): string[] {
|
||||
if (subscription.selection !== "fixed") return [];
|
||||
|
||||
const quantity = Math.max(1, Math.trunc(Number(subscription.quantity ?? 1)) || 1);
|
||||
const stored = Array.isArray(subscription.variant_ids)
|
||||
? subscription.variant_ids.filter((id): id is string => typeof id === "string" && id.length > 0)
|
||||
: [];
|
||||
|
||||
const fallback = stored[stored.length - 1] ?? subscription.variant_id ?? null;
|
||||
if (!fallback) return [];
|
||||
|
||||
return Array.from({ length: quantity }, (_, index) => stored[index] ?? fallback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gleiche Sorten zu einem Posten zusammenfassen.
|
||||
*
|
||||
* Zwei Gläser Lindenhonig sind ein Warenkorbposten mit Menge 2, nicht zwei
|
||||
* Posten — sonst legt Medusa sie ohnehin zusammen und die Reihenfolge der
|
||||
* Bestellung sähe zufällig aus.
|
||||
*/
|
||||
export function groupByVariant(variantIds: string[]): { variant_id: string; quantity: number }[] {
|
||||
const counts = new Map<string, number>();
|
||||
for (const id of variantIds) counts.set(id, (counts.get(id) ?? 0) + 1);
|
||||
return [...counts].map(([variant_id, quantity]) => ({ variant_id, quantity }));
|
||||
}
|
||||
|
||||
/** Liest die Sortenliste aus den Metadaten eines Warenkorb- oder Bestellpostens. */
|
||||
export function varietyIdsFromMetadata(metadata: unknown): string[] {
|
||||
const raw = (metadata as Record<string, unknown> | null | undefined)?.subscription_variant_ids;
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.filter((id): id is string => typeof id === "string" && id.length > 0);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
||||
import DhlFulfillmentService from "./service";
|
||||
|
||||
export default ModuleProvider(Modules.FULFILLMENT, {
|
||||
services: [DhlFulfillmentService],
|
||||
});
|
||||
@@ -0,0 +1,323 @@
|
||||
import { AbstractFulfillmentProviderService } from "@medusajs/framework/utils";
|
||||
import type {
|
||||
CalculatedShippingOptionPrice,
|
||||
CreateFulfillmentResult,
|
||||
FulfillmentItemDTO,
|
||||
FulfillmentOption,
|
||||
FulfillmentOrderDTO,
|
||||
} from "@medusajs/framework/types";
|
||||
|
||||
type Options = {
|
||||
/** API-Key der App im DHL-Entwicklerportal. */
|
||||
api_key: string;
|
||||
/** Benutzer des Geschäftskundenportals mit Recht "Versenden". */
|
||||
username: string;
|
||||
password: string;
|
||||
/** 14-stellige Abrechnungsnummer: EKP + Verfahren + Teilnahme. */
|
||||
billing_number: string;
|
||||
/** Absenderadresse, erscheint auf dem Label. */
|
||||
shipper_name: string;
|
||||
shipper_street: string;
|
||||
shipper_postal_code: string;
|
||||
shipper_city: string;
|
||||
/** ISO 3166-1 alpha-3, DHL erwartet drei Buchstaben. */
|
||||
shipper_country?: string;
|
||||
sandbox?: boolean;
|
||||
/**
|
||||
* Wenn gesetzt, wird nur `?validate=true` aufgerufen: DHL prüft die Daten
|
||||
* und meldet Fehler, erzeugt aber kein Label und zieht kein Porto.
|
||||
* Für die Inbetriebnahme gedacht.
|
||||
*/
|
||||
validate_only?: boolean;
|
||||
/** Fallback, wenn an der Variante kein Versandgewicht hinterlegt ist. */
|
||||
default_item_weight_g?: number;
|
||||
};
|
||||
|
||||
const LIVE_URL = "https://api-eu.dhl.com/parcel/de/shipping/v2";
|
||||
const SANDBOX_URL = "https://api-sandbox.dhl.com/parcel/de/shipping/v2";
|
||||
|
||||
/**
|
||||
* Produkte für den Versand innerhalb Deutschlands.
|
||||
*
|
||||
* ACHTUNG: Warenpost (V62WP) hat DHL zum 31.05.2026 eingestellt, Nachfolger
|
||||
* ist V62KP (DHL Kleinpaket). Ältere Anleitungen im Netz nennen noch V62WP —
|
||||
* damit schlägt die Erstellung fehl.
|
||||
*/
|
||||
const PRODUCTS: { code: string; label: string }[] = [
|
||||
{ code: "V01PAK", label: "DHL Paket" },
|
||||
{ code: "V62KP", label: "DHL Kleinpaket" },
|
||||
{ code: "V53WPAK", label: "DHL Paket International" },
|
||||
{ code: "V54EPAK", label: "DHL Europaket" },
|
||||
{ code: "V66WPI", label: "Warenpost International" },
|
||||
];
|
||||
|
||||
/**
|
||||
* DHL "Paket DE Versenden" v2 (REST).
|
||||
*
|
||||
* Doku: https://developer.dhl.com/api-reference/parcel-de-shipping-post-parcel-germany-v2
|
||||
*
|
||||
* NICHT GETESTET: geschrieben gegen die öffentliche Spezifikation, aber ohne
|
||||
* echte Zugangsdaten nie ausgeführt. Vor dem Produktivbetrieb einmal
|
||||
* `npx medusa exec ./src/scripts/check-carriers.ts` laufen lassen — das prüft
|
||||
* die Zugangsdaten und schickt eine Testsendung mit `?validate=true` los,
|
||||
* also ohne Label und ohne Porto.
|
||||
*/
|
||||
class DhlFulfillmentService extends AbstractFulfillmentProviderService {
|
||||
static identifier = "dhl";
|
||||
|
||||
private options_: Options;
|
||||
private container_: any;
|
||||
private baseUrl_: string;
|
||||
private authHeader_: string;
|
||||
|
||||
constructor(container: unknown, options: Options) {
|
||||
super();
|
||||
const missing = [
|
||||
"api_key",
|
||||
"username",
|
||||
"password",
|
||||
"billing_number",
|
||||
"shipper_name",
|
||||
"shipper_street",
|
||||
"shipper_postal_code",
|
||||
"shipper_city",
|
||||
].filter((key) => !options?.[key as keyof Options]);
|
||||
if (missing.length) {
|
||||
throw new Error(`DHL fulfillment provider: fehlende Optionen: ${missing.join(", ")}`);
|
||||
}
|
||||
this.options_ = options;
|
||||
this.container_ = container;
|
||||
this.baseUrl_ = options.sandbox ? SANDBOX_URL : LIVE_URL;
|
||||
// DHL führt Basic Auth als "deprecated", es funktioniert aber weiterhin.
|
||||
// Auf OAuth2 (ROPC) umstellen, sobald echte Zugangsdaten zum Testen da
|
||||
// sind — ungetestet umzubauen wäre der schlechtere Tausch.
|
||||
this.authHeader_ = `Basic ${Buffer.from(`${options.username}:${options.password}`).toString("base64")}`;
|
||||
}
|
||||
|
||||
private async request(path: string, init?: RequestInit) {
|
||||
const res = await fetch(`${this.baseUrl_}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: this.authHeader_,
|
||||
"dhl-api-key": this.options_.api_key,
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
throw new Error(`DHL-Anfrage fehlgeschlagen: ${path} (${res.status}) ${JSON.stringify(body)}`);
|
||||
}
|
||||
return body as any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Versandgewicht in Gramm.
|
||||
*
|
||||
* Quelle ist `product_variant.weight` (Medusas Versandgewicht). Achtung:
|
||||
* das Metadatenfeld `net_weight_grams` ist die Füllmenge für den
|
||||
* Grundpreis und NICHT das Versandgewicht — ein 250-g-Glas wiegt
|
||||
* versandfertig deutlich mehr.
|
||||
*/
|
||||
private async resolveWeightGrams(
|
||||
items: Partial<Omit<FulfillmentItemDTO, "fulfillment">>[]
|
||||
): Promise<number> {
|
||||
const fallback = this.options_.default_item_weight_g ?? 600;
|
||||
let total = 0;
|
||||
try {
|
||||
const query = this.container_?.query ?? this.container_?.resolve?.("query");
|
||||
const variantIds = items
|
||||
.map((item: any) => item.variant_id ?? item.line_item?.variant_id)
|
||||
.filter(Boolean);
|
||||
|
||||
const weights = new Map<string, number>();
|
||||
if (query && variantIds.length) {
|
||||
const { data } = await query.graph({
|
||||
entity: "variant",
|
||||
fields: ["id", "weight"],
|
||||
filters: { id: variantIds },
|
||||
});
|
||||
for (const variant of data ?? []) {
|
||||
if (variant.weight) weights.set(variant.id, Number(variant.weight));
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of items as any[]) {
|
||||
const qty = item.quantity ?? 1;
|
||||
const id = item.variant_id ?? item.line_item?.variant_id;
|
||||
total += qty * (weights.get(id) ?? fallback);
|
||||
}
|
||||
} catch {
|
||||
total = items.reduce((sum, item: any) => sum + (item.quantity ?? 1) * fallback, 0);
|
||||
}
|
||||
// DHL nimmt kein Paket mit 0 g an.
|
||||
return Math.max(total, 100);
|
||||
}
|
||||
|
||||
async getFulfillmentOptions(): Promise<FulfillmentOption[]> {
|
||||
return PRODUCTS.map((product) => ({
|
||||
id: product.code,
|
||||
name: `DHL – ${product.label}`,
|
||||
}));
|
||||
}
|
||||
|
||||
async validateFulfillmentData(
|
||||
optionData: Record<string, unknown>,
|
||||
data: Record<string, unknown>
|
||||
): Promise<any> {
|
||||
const product = (optionData.id as string) ?? (data.dhl_product as string);
|
||||
if (!PRODUCTS.some((p) => p.code === product)) {
|
||||
throw new Error(
|
||||
`Unbekanntes DHL-Produkt "${product}". Erlaubt: ${PRODUCTS.map((p) => p.code).join(", ")}`
|
||||
);
|
||||
}
|
||||
return { ...data, dhl_product: product };
|
||||
}
|
||||
|
||||
async validateOption(): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
async canCalculate(): Promise<boolean> {
|
||||
return false;
|
||||
}
|
||||
|
||||
async calculatePrice(): Promise<CalculatedShippingOptionPrice> {
|
||||
throw new Error("DHL-Provider berechnet keine dynamischen Preise.");
|
||||
}
|
||||
|
||||
/** Baut den Sendungsdatensatz. Öffentlich, damit das Prüfskript ihn nutzen kann. */
|
||||
buildShipment(params: {
|
||||
product: string;
|
||||
weightGrams: number;
|
||||
reference: string;
|
||||
consignee: Record<string, any>;
|
||||
}) {
|
||||
const o = this.options_;
|
||||
return {
|
||||
product: params.product,
|
||||
billingNumber: o.billing_number,
|
||||
refNo: params.reference.slice(0, 35),
|
||||
shipper: {
|
||||
name1: o.shipper_name,
|
||||
addressStreet: o.shipper_street,
|
||||
postalCode: o.shipper_postal_code,
|
||||
city: o.shipper_city,
|
||||
country: (o.shipper_country ?? "DEU").toUpperCase(),
|
||||
},
|
||||
consignee: {
|
||||
name1: `${params.consignee.first_name ?? ""} ${params.consignee.last_name ?? ""}`.trim(),
|
||||
addressStreet: params.consignee.address_1,
|
||||
additionalAddressInformation1: params.consignee.address_2 || undefined,
|
||||
postalCode: params.consignee.postal_code,
|
||||
city: params.consignee.city,
|
||||
country: (params.consignee.country_code ?? "de").toUpperCase() === "DE"
|
||||
? "DEU"
|
||||
: String(params.consignee.country_code).toUpperCase(),
|
||||
email: params.consignee.email || undefined,
|
||||
},
|
||||
details: {
|
||||
weight: { uom: "g", value: params.weightGrams },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async createFulfillment(
|
||||
data: Record<string, unknown>,
|
||||
items: Partial<Omit<FulfillmentItemDTO, "fulfillment">>[],
|
||||
order: Partial<FulfillmentOrderDTO> | undefined,
|
||||
fulfillment: Record<string, unknown>
|
||||
): Promise<CreateFulfillmentResult> {
|
||||
const address = (order as any)?.shipping_address ?? {};
|
||||
const product = (data.dhl_product as string) ?? PRODUCTS[0].code;
|
||||
const weightGrams = await this.resolveWeightGrams(items);
|
||||
|
||||
const payload = {
|
||||
profile: "STANDARD",
|
||||
shipments: [
|
||||
this.buildShipment({
|
||||
product,
|
||||
weightGrams,
|
||||
reference: String((order as any)?.display_id ?? (order as any)?.id ?? ""),
|
||||
consignee: { ...address, email: (order as any)?.email },
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
const query = this.options_.validate_only
|
||||
? "?validate=true&includeDocs=include"
|
||||
: "?includeDocs=include";
|
||||
const body = await this.request(`/orders${query}`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
// Die Feldnamen weichen zwischen Doku-Ständen ab, deshalb mehrere
|
||||
// Varianten prüfen statt auf eine zu setzen.
|
||||
const item = body?.items?.[0] ?? {};
|
||||
const shipmentNo = item.shipmentNo ?? item.shipmentNumber ?? body?.shipmentNumber;
|
||||
const labelUrl = item.label?.url ?? item.labelUrl ?? "";
|
||||
const labelB64 = item.label?.b64 ?? item.label?.data;
|
||||
|
||||
if (!shipmentNo && !this.options_.validate_only) {
|
||||
throw new Error(`DHL lieferte keine Sendungsnummer: ${JSON.stringify(body).slice(0, 500)}`);
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
...(fulfillment.data as object | undefined),
|
||||
dhl_shipment_no: shipmentNo,
|
||||
dhl_product: product,
|
||||
dhl_weight_g: weightGrams,
|
||||
// Wenn DHL das Label eingebettet liefert, hier ablegen — sonst
|
||||
// ginge es beim nächsten Aufruf verloren.
|
||||
...(labelB64 ? { dhl_label_b64: labelB64 } : {}),
|
||||
...(this.options_.validate_only ? { dhl_validate_only: true } : {}),
|
||||
},
|
||||
labels: shipmentNo
|
||||
? [
|
||||
{
|
||||
tracking_number: shipmentNo,
|
||||
tracking_url: `https://www.dhl.de/de/privatkunden/pakete-empfangen/verfolgen.html?piececode=${shipmentNo}`,
|
||||
label_url: labelUrl,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
async cancelFulfillment(data: Record<string, unknown>): Promise<any> {
|
||||
const shipmentNo = data.dhl_shipment_no as string | undefined;
|
||||
if (!shipmentNo || data.dhl_validate_only) return {};
|
||||
await this.request(`/orders?shipment=${encodeURIComponent(shipmentNo)}&profile=STANDARD`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
async getFulfillmentDocuments(): Promise<never[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async createReturnFulfillment(fulfillment: Record<string, unknown>): Promise<CreateFulfillmentResult> {
|
||||
// Retourenlabel läuft über den Service "Retoure" im selben Aufruf.
|
||||
// Erst umsetzen, wenn es fachlich gebraucht wird.
|
||||
return { data: { ...(fulfillment.data as object | undefined) }, labels: [] };
|
||||
}
|
||||
|
||||
async getReturnDocuments(): Promise<never[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getShipmentDocuments(): Promise<never[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async retrieveDocuments(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export default DhlFulfillmentService;
|
||||
export { PRODUCTS as DHL_PRODUCTS };
|
||||
@@ -0,0 +1,6 @@
|
||||
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
||||
import EmailNotificationService from "./service";
|
||||
|
||||
export default ModuleProvider(Modules.NOTIFICATION, {
|
||||
services: [EmailNotificationService],
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { AbstractNotificationProviderService, MedusaError } from "@medusajs/framework/utils";
|
||||
import type { ProviderSendNotificationDTO } from "@medusajs/framework/types";
|
||||
import nodemailer, { type Transporter } from "nodemailer";
|
||||
|
||||
type Options = {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
from: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* E-Mail-Versand über SMTP.
|
||||
*
|
||||
* Bewusst SMTP und keine Vorlagen bei einem Dienstleister: Bestellbestätigung
|
||||
* und Versandnachricht sind Vertragsinhalt (§ 312f BGB) und gehören damit ins
|
||||
* Projekt, wo sie versioniert sind und mit dem Shop zusammen geprüft werden.
|
||||
*
|
||||
* Der Absender kommt aus der Konfiguration, der Inhalt fertig aus dem
|
||||
* Subscriber — dieser Dienst formuliert nichts, er versendet nur.
|
||||
*/
|
||||
class EmailNotificationService extends AbstractNotificationProviderService {
|
||||
static identifier = "email-smtp";
|
||||
|
||||
private transporter_: Transporter;
|
||||
private options_: Options;
|
||||
private logger_: any;
|
||||
|
||||
constructor({ logger }: { logger: any }, options: Options) {
|
||||
super();
|
||||
if (!options?.host || !options?.from) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_ARGUMENT,
|
||||
"E-Mail-Versand braucht mindestens SMTP_HOST und MAIL_FROM."
|
||||
);
|
||||
}
|
||||
this.options_ = options;
|
||||
this.logger_ = logger;
|
||||
this.transporter_ = nodemailer.createTransport({
|
||||
host: options.host,
|
||||
port: options.port,
|
||||
secure: options.secure,
|
||||
...(options.user ? { auth: { user: options.user, pass: options.pass } } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async send(notification: ProviderSendNotificationDTO) {
|
||||
if (!notification?.to) {
|
||||
throw new MedusaError(MedusaError.Types.INVALID_DATA, "Keine Empfängeradresse.");
|
||||
}
|
||||
|
||||
const content = notification.content ?? {};
|
||||
if (!content.subject || (!content.html && !content.text)) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_DATA,
|
||||
`Nachricht "${notification.template}" hat keinen Betreff oder keinen Inhalt.`
|
||||
);
|
||||
}
|
||||
|
||||
// Reply-To reist in `data`, weil das Benachrichtigungsmodell dafür kein
|
||||
// eigenes Feld hat. Eine Kontaktanfrage soll so beantwortet werden
|
||||
// können, ohne die Adresse aus dem Text zu kopieren.
|
||||
const antwortAn = (notification.data as any)?.reply_to;
|
||||
|
||||
const info = await this.transporter_.sendMail({
|
||||
from: notification.from || this.options_.from,
|
||||
...(typeof antwortAn === "string" && antwortAn ? { replyTo: antwortAn } : {}),
|
||||
to: notification.to,
|
||||
subject: content.subject,
|
||||
text: content.text,
|
||||
html: content.html,
|
||||
attachments: (notification.attachments ?? []).map((anhang: any) => ({
|
||||
filename: anhang.filename,
|
||||
content: Buffer.from(anhang.content, "base64"),
|
||||
contentType: anhang.content_type,
|
||||
})),
|
||||
});
|
||||
|
||||
this.logger_.info(`[mail] "${notification.template}" an ${notification.to} verschickt (${info.messageId}).`);
|
||||
return { id: info.messageId };
|
||||
}
|
||||
}
|
||||
|
||||
export default EmailNotificationService;
|
||||
@@ -0,0 +1,6 @@
|
||||
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
||||
import SendcloudFulfillmentService from "./service";
|
||||
|
||||
export default ModuleProvider(Modules.FULFILLMENT, {
|
||||
services: [SendcloudFulfillmentService],
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { AbstractFulfillmentProviderService } from "@medusajs/framework/utils";
|
||||
import type {
|
||||
CalculatedShippingOptionPrice,
|
||||
CreateFulfillmentResult,
|
||||
FulfillmentItemDTO,
|
||||
FulfillmentOption,
|
||||
FulfillmentOrderDTO,
|
||||
} from "@medusajs/framework/types";
|
||||
|
||||
type Options = {
|
||||
public_key: string;
|
||||
secret_key: string;
|
||||
};
|
||||
|
||||
const SENDCLOUD_API_URL = "https://panel.sendcloud.sc/api/v2";
|
||||
|
||||
/**
|
||||
* Self-built Sendcloud integration (instead of the early-stage community
|
||||
* plugin) so a single account covers DHL/DPD/GLS/Hermes label creation and
|
||||
* tracking for German shipments.
|
||||
*
|
||||
* IMPORTANT: this has only been written against Sendcloud's documented v2
|
||||
* REST API — it hasn't been exercised against a real account yet (none
|
||||
* existed when this was built). Before relying on it, create a Sendcloud
|
||||
* account, put the API credentials in .env (SENDCLOUD_PUBLIC_KEY /
|
||||
* SENDCLOUD_SECRET_KEY), and do a real end-to-end test order; double-check
|
||||
* the request/response shape against https://api.sendcloud.dev at that
|
||||
* point in case anything has changed since this was written.
|
||||
*/
|
||||
class SendcloudFulfillmentService extends AbstractFulfillmentProviderService {
|
||||
static identifier = "sendcloud";
|
||||
|
||||
private authHeader: string;
|
||||
|
||||
constructor(_container: unknown, options: Options) {
|
||||
super();
|
||||
if (!options?.public_key || !options?.secret_key) {
|
||||
throw new Error("Sendcloud fulfillment provider requires public_key and secret_key options.");
|
||||
}
|
||||
this.authHeader = `Basic ${Buffer.from(`${options.public_key}:${options.secret_key}`).toString("base64")}`;
|
||||
}
|
||||
|
||||
private async sendcloudFetch(path: string, init?: RequestInit) {
|
||||
const res = await fetch(`${SENDCLOUD_API_URL}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: this.authHeader,
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
throw new Error(`Sendcloud request failed: ${path} (${res.status}) ${JSON.stringify(body)}`);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
async getFulfillmentOptions(): Promise<FulfillmentOption[]> {
|
||||
const { shipping_methods } = await this.sendcloudFetch("/shipping_methods");
|
||||
return (shipping_methods ?? []).map((method: any) => ({
|
||||
id: String(method.id),
|
||||
name: `${method.carrier} – ${method.name}`,
|
||||
}));
|
||||
}
|
||||
|
||||
async validateFulfillmentData(
|
||||
optionData: Record<string, unknown>,
|
||||
data: Record<string, unknown>
|
||||
): Promise<any> {
|
||||
return { ...data, sendcloud_shipping_method_id: optionData.id };
|
||||
}
|
||||
|
||||
async validateOption(): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
async canCalculate(): Promise<boolean> {
|
||||
return false;
|
||||
}
|
||||
|
||||
async calculatePrice(): Promise<CalculatedShippingOptionPrice> {
|
||||
throw new Error("Sendcloud provider does not support dynamic price calculation yet.");
|
||||
}
|
||||
|
||||
async createFulfillment(
|
||||
data: Record<string, unknown>,
|
||||
items: Partial<Omit<FulfillmentItemDTO, "fulfillment">>[],
|
||||
order: Partial<FulfillmentOrderDTO> | undefined,
|
||||
fulfillment: Record<string, unknown>
|
||||
): Promise<CreateFulfillmentResult> {
|
||||
const address = (order as any)?.shipping_address ?? {};
|
||||
const totalWeightKg = items.reduce((sum, item) => sum + (item.quantity ?? 1) * 0.5, 0) || 1;
|
||||
|
||||
const { parcel } = await this.sendcloudFetch("/parcels", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
parcel: {
|
||||
name: `${address.first_name ?? ""} ${address.last_name ?? ""}`.trim(),
|
||||
address: address.address_1,
|
||||
city: address.city,
|
||||
postal_code: address.postal_code,
|
||||
country: address.country_code?.toUpperCase(),
|
||||
email: (order as any)?.email,
|
||||
order_number: String((order as any)?.display_id ?? ""),
|
||||
weight: totalWeightKg.toFixed(2),
|
||||
request_label: true,
|
||||
shipment: { id: Number(data.sendcloud_shipping_method_id) },
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
data: {
|
||||
...(fulfillment.data as object | undefined),
|
||||
sendcloud_parcel_id: parcel.id,
|
||||
},
|
||||
labels: [
|
||||
{
|
||||
tracking_number: parcel.tracking_number,
|
||||
tracking_url: parcel.tracking_url,
|
||||
label_url: parcel.label?.label_printer?.[0] ?? parcel.label?.normal_printer?.[0] ?? "",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async cancelFulfillment(data: Record<string, unknown>): Promise<any> {
|
||||
const parcelId = data.sendcloud_parcel_id;
|
||||
if (!parcelId) return {};
|
||||
await this.sendcloudFetch(`/parcels/${parcelId}/cancel`, { method: "POST" });
|
||||
return {};
|
||||
}
|
||||
|
||||
async getFulfillmentDocuments(data: Record<string, unknown>): Promise<never[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async createReturnFulfillment(fulfillment: Record<string, unknown>): Promise<CreateFulfillmentResult> {
|
||||
// Return-label creation would follow the same /parcels call with the
|
||||
// sender/recipient reversed. Not implemented yet — add when needed.
|
||||
return { data: { ...(fulfillment.data as object | undefined) }, labels: [] };
|
||||
}
|
||||
|
||||
async getReturnDocuments(): Promise<never[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getShipmentDocuments(): Promise<never[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async retrieveDocuments(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export default SendcloudFulfillmentService;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Module } from "@medusajs/framework/utils";
|
||||
import SubscriptionModuleService from "./service";
|
||||
|
||||
export const SUBSCRIPTION_MODULE = "subscription";
|
||||
|
||||
export default Module(SUBSCRIPTION_MODULE, {
|
||||
service: SubscriptionModuleService,
|
||||
});
|
||||
@@ -0,0 +1,642 @@
|
||||
{
|
||||
"namespaces": [
|
||||
"public"
|
||||
],
|
||||
"name": "public",
|
||||
"tables": [
|
||||
{
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": true,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"customer_id": {
|
||||
"name": "customer_id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"email": {
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"selection": {
|
||||
"name": "selection",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "'fixed'",
|
||||
"comment": null,
|
||||
"enumItems": [
|
||||
"fixed",
|
||||
"random"
|
||||
],
|
||||
"mappedType": "enum"
|
||||
},
|
||||
"variant_id": {
|
||||
"name": "variant_id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"last_variant_id": {
|
||||
"name": "last_variant_id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"size": {
|
||||
"name": "size",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"quantity": {
|
||||
"name": "quantity",
|
||||
"type": "integer",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "1",
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "integer"
|
||||
},
|
||||
"interval": {
|
||||
"name": "interval",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [
|
||||
"monthly",
|
||||
"quarterly",
|
||||
"biannual"
|
||||
],
|
||||
"mappedType": "enum"
|
||||
},
|
||||
"next_order_at": {
|
||||
"name": "next_order_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"last_order_at": {
|
||||
"name": "last_order_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "'active'",
|
||||
"comment": null,
|
||||
"enumItems": [
|
||||
"active",
|
||||
"paused",
|
||||
"canceled"
|
||||
],
|
||||
"mappedType": "enum"
|
||||
},
|
||||
"paused_at": {
|
||||
"name": "paused_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"canceled_at": {
|
||||
"name": "canceled_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"cancel_reason": {
|
||||
"name": "cancel_reason",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"mollie_customer_id": {
|
||||
"name": "mollie_customer_id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"mollie_mandate_id": {
|
||||
"name": "mollie_mandate_id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"payment_method": {
|
||||
"name": "payment_method",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"shipping_address": {
|
||||
"name": "shipping_address",
|
||||
"type": "jsonb",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "json"
|
||||
},
|
||||
"shipping_option_id": {
|
||||
"name": "shipping_option_id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"region_id": {
|
||||
"name": "region_id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"currency_code": {
|
||||
"name": "currency_code",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "'eur'",
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"sales_channel_id": {
|
||||
"name": "sales_channel_id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"failed_attempts": {
|
||||
"name": "failed_attempts",
|
||||
"type": "integer",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "0",
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "integer"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "last_error",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "now()",
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "now()",
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"deleted_at": {
|
||||
"name": "deleted_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
}
|
||||
},
|
||||
"name": "subscription",
|
||||
"schema": "public",
|
||||
"indexes": [
|
||||
{
|
||||
"keyName": "IDX_subscription_deleted_at",
|
||||
"columnNames": [],
|
||||
"composite": false,
|
||||
"constraint": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_subscription_deleted_at\" ON \"subscription\" (\"deleted_at\") WHERE deleted_at IS NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "IDX_subscription_status_next_order_at",
|
||||
"columnNames": [],
|
||||
"composite": false,
|
||||
"constraint": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_subscription_status_next_order_at\" ON \"subscription\" (\"status\", \"next_order_at\") WHERE deleted_at IS NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "IDX_subscription_customer_id",
|
||||
"columnNames": [],
|
||||
"composite": false,
|
||||
"constraint": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_subscription_customer_id\" ON \"subscription\" (\"customer_id\") WHERE deleted_at IS NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "subscription_pkey",
|
||||
"columnNames": [
|
||||
"id"
|
||||
],
|
||||
"composite": false,
|
||||
"constraint": true,
|
||||
"primary": true,
|
||||
"unique": true
|
||||
}
|
||||
],
|
||||
"checks": [],
|
||||
"foreignKeys": {},
|
||||
"nativeEnums": {}
|
||||
},
|
||||
{
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": true,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"discount_percent": {
|
||||
"name": "discount_percent",
|
||||
"type": "integer",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "0",
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "integer"
|
||||
},
|
||||
"discount_label": {
|
||||
"name": "discount_label",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": null,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "text"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "now()",
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": "now()",
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"deleted_at": {
|
||||
"name": "deleted_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"unique": false,
|
||||
"length": 6,
|
||||
"precision": null,
|
||||
"scale": null,
|
||||
"default": null,
|
||||
"comment": null,
|
||||
"enumItems": [],
|
||||
"mappedType": "datetime"
|
||||
}
|
||||
},
|
||||
"name": "subscription_setting",
|
||||
"schema": "public",
|
||||
"indexes": [
|
||||
{
|
||||
"keyName": "IDX_subscription_setting_deleted_at",
|
||||
"columnNames": [],
|
||||
"composite": false,
|
||||
"constraint": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_subscription_setting_deleted_at\" ON \"subscription_setting\" (\"deleted_at\") WHERE deleted_at IS NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "subscription_setting_pkey",
|
||||
"columnNames": [
|
||||
"id"
|
||||
],
|
||||
"composite": false,
|
||||
"constraint": true,
|
||||
"primary": true,
|
||||
"unique": true
|
||||
}
|
||||
],
|
||||
"checks": [],
|
||||
"foreignKeys": {},
|
||||
"nativeEnums": {}
|
||||
}
|
||||
],
|
||||
"nativeEnums": {}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
|
||||
|
||||
export class Migration20260902111832 extends Migration {
|
||||
|
||||
override async up(): Promise<void> {
|
||||
this.addSql(`create table if not exists "subscription" ("id" text not null, "customer_id" text null, "email" text not null, "selection" text check ("selection" in ('fixed', 'random')) not null default 'fixed', "variant_id" text null, "last_variant_id" text null, "quantity" integer not null default 1, "interval" text check ("interval" in ('monthly', 'quarterly', 'biannual')) not null, "next_order_at" timestamptz not null, "last_order_at" timestamptz null, "status" text check ("status" in ('active', 'paused', 'canceled')) not null default 'active', "paused_at" timestamptz null, "canceled_at" timestamptz null, "cancel_reason" text null, "mollie_customer_id" text null, "mollie_mandate_id" text null, "payment_method" text null, "shipping_address" jsonb null, "shipping_option_id" text null, "region_id" text null, "currency_code" text not null default 'eur', "sales_channel_id" text null, "failed_attempts" integer not null default 0, "last_error" text null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "subscription_pkey" primary key ("id"));`);
|
||||
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_subscription_deleted_at" ON "subscription" ("deleted_at") WHERE deleted_at IS NULL;`);
|
||||
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_subscription_status_next_order_at" ON "subscription" ("status", "next_order_at") WHERE deleted_at IS NULL;`);
|
||||
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_subscription_customer_id" ON "subscription" ("customer_id") WHERE deleted_at IS NULL;`);
|
||||
}
|
||||
|
||||
override async down(): Promise<void> {
|
||||
this.addSql(`drop table if exists "subscription" cascade;`);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
|
||||
|
||||
export class Migration20260902112429 extends Migration {
|
||||
|
||||
override async up(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "size" text null;`);
|
||||
}
|
||||
|
||||
override async down(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription" drop column if exists "size";`);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
|
||||
|
||||
export class Migration20260902112828 extends Migration {
|
||||
|
||||
override async up(): Promise<void> {
|
||||
this.addSql(`create table if not exists "subscription_setting" ("id" text not null, "discount_percent" integer not null default 0, "discount_label" text null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "subscription_setting_pkey" primary key ("id"));`);
|
||||
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_subscription_setting_deleted_at" ON "subscription_setting" ("deleted_at") WHERE deleted_at IS NULL;`);
|
||||
}
|
||||
|
||||
override async down(): Promise<void> {
|
||||
this.addSql(`drop table if exists "subscription_setting" cascade;`);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
|
||||
|
||||
/**
|
||||
* Sortenwahl je Glas.
|
||||
*
|
||||
* Bewusst ohne Backfill: bestehende Abos behalten ihr einzelnes
|
||||
* `variant_id`, und `varietyPerGlass()` füllt daraus die Liste auf. Sie
|
||||
* bedeuten damit weiterhin genau das, was sie vorher bedeutet haben.
|
||||
*/
|
||||
export class Migration20260904120000 extends Migration {
|
||||
|
||||
override async up(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "variant_ids" jsonb null;`);
|
||||
}
|
||||
|
||||
override async down(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription" drop column if exists "variant_ids";`);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
|
||||
|
||||
/**
|
||||
* Schwelle für kostenfreien Versand.
|
||||
*
|
||||
* `null` als Ausgangswert, damit der Shop nach der Migration nichts
|
||||
* verspricht, was noch niemand eingestellt hat.
|
||||
*/
|
||||
export class Migration20260910100000 extends Migration {
|
||||
|
||||
override async up(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription_setting" add column if not exists "free_shipping_threshold" integer null;`);
|
||||
}
|
||||
|
||||
override async down(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription_setting" drop column if exists "free_shipping_threshold";`);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
|
||||
|
||||
/**
|
||||
* Verschenkte Abos.
|
||||
*
|
||||
* Bestehende Abos bleiben unbefristet und nicht vorausbezahlt — genau das,
|
||||
* was sie bisher schon waren. Deshalb kein Backfill.
|
||||
*/
|
||||
export class Migration20260910140000 extends Migration {
|
||||
|
||||
override async up(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "prepaid" boolean not null default false;`);
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "remaining_deliveries" integer null;`);
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "gift_recipient_name" text null;`);
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "gift_recipient_email" text null;`);
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "gift_sender_name" text null;`);
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "gift_announced_at" timestamptz null;`);
|
||||
}
|
||||
|
||||
override async down(): Promise<void> {
|
||||
for (const spalte of [
|
||||
"prepaid",
|
||||
"remaining_deliveries",
|
||||
"gift_recipient_name",
|
||||
"gift_recipient_email",
|
||||
"gift_sender_name",
|
||||
"gift_announced_at",
|
||||
]) {
|
||||
this.addSql(`alter table if exists "subscription" drop column if exists "${spalte}";`);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
|
||||
|
||||
/**
|
||||
* Herkunft eines Abos.
|
||||
*
|
||||
* Eigene Migration, weil die vorige zu diesem Zeitpunkt schon gelaufen war —
|
||||
* Medusa führt eine erledigte Migration nicht erneut aus, nachgetragene
|
||||
* Zeilen darin bleiben also wirkungslos.
|
||||
*/
|
||||
export class Migration20260910150000 extends Migration {
|
||||
|
||||
override async up(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription" add column if not exists "source_line_item_id" text null;`);
|
||||
}
|
||||
|
||||
override async down(): Promise<void> {
|
||||
this.addSql(`alter table if exists "subscription" drop column if exists "source_line_item_id";`);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { model } from "@medusajs/framework/utils";
|
||||
|
||||
/**
|
||||
* Einstellungen des Shops, im Admin pflegbar.
|
||||
*
|
||||
* Genau eine Zeile mit fester ID "default" — ein eigenes Modell statt einer
|
||||
* Umgebungsvariable, weil die Werte ohne Deployment änderbar sein sollen.
|
||||
*
|
||||
* Der Tabellenname stammt noch aus der Zeit, als hier nur Abo-Werte standen.
|
||||
* Umbenennen hieße die Zeile umziehen, ohne dass sich etwas ändert — deshalb
|
||||
* bleibt er, und die Zeile trägt inzwischen auch shopweite Einstellungen.
|
||||
*/
|
||||
const SubscriptionSetting = model.define("subscription_setting", {
|
||||
id: model.id({ prefix: "subset" }).primaryKey(),
|
||||
|
||||
/**
|
||||
* Abo-Rabatt in Prozent auf den regulären Glaspreis, 0 bis 100.
|
||||
* 0 bedeutet: Abo kostet dasselbe wie der Einzelkauf.
|
||||
*/
|
||||
discount_percent: model.number().default(0),
|
||||
|
||||
/** Sichtbarer Hinweis im Shop, z. B. "10 % Abo-Rabatt auf jede Lieferung". */
|
||||
discount_label: model.text().nullable(),
|
||||
|
||||
/**
|
||||
* Ab welchem Warenwert der Versand entfällt, in ganzen Euro.
|
||||
* `null` heißt: kein kostenfreier Versand, und der Shop sagt auch nichts
|
||||
* dergleichen.
|
||||
*
|
||||
* Ganze Euro, weil die Spalte ganzzahlig ist. Schwellen sind in der Praxis
|
||||
* runde Beträge (49, 60, 75); für 59,90 wäre eine eigene Spalte in Cent
|
||||
* nötig, die sich sonst nirgends im Projekt findet.
|
||||
*/
|
||||
free_shipping_threshold: model.number().nullable(),
|
||||
});
|
||||
|
||||
export default SubscriptionSetting;
|
||||
@@ -0,0 +1,123 @@
|
||||
import { model } from "@medusajs/framework/utils";
|
||||
|
||||
/**
|
||||
* Ein Honig-Abo.
|
||||
*
|
||||
* Bewusst eigenständig statt über wiederkehrende Bestellungen abgebildet:
|
||||
* Medusa kennt keine Abos, und der Zustand (nächster Termin, Mandat,
|
||||
* zuletzt gelieferte Sorte) gehört an eine Stelle.
|
||||
*/
|
||||
const Subscription = model.define("subscription", {
|
||||
id: model.id({ prefix: "sub" }).primaryKey(),
|
||||
|
||||
// --- Wer ---
|
||||
customer_id: model.text().nullable(),
|
||||
email: model.text(),
|
||||
|
||||
// --- Was ---
|
||||
/** "fixed" = feste Sorte, "random" = Überraschungshonig */
|
||||
selection: model.enum(["fixed", "random"]).default("fixed"),
|
||||
/**
|
||||
* Nur bei selection = fixed gesetzt.
|
||||
*
|
||||
* Bleibt neben `variant_ids` bestehen: Abos aus der Zeit vor der
|
||||
* Sortenwahl je Glas kennen nur dieses Feld, und es ist weiterhin die
|
||||
* Sorte, die für alle Gläser gilt, wenn keine Liste hinterlegt ist.
|
||||
*/
|
||||
variant_id: model.text().nullable(),
|
||||
/**
|
||||
* Bei fester Sorte eine Variante je Glas, in der Reihenfolge der Auswahl —
|
||||
* damit ein Abo über drei Gläser auch drei verschiedene Sorten haben kann.
|
||||
*
|
||||
* Kürzer als `quantity` oder gar nicht gesetzt heißt: der Rest läuft auf
|
||||
* `variant_id`. Gelesen wird das ausschließlich über
|
||||
* `varietyPerGlass()` in src/lib/subscription-varieties.ts.
|
||||
*/
|
||||
variant_ids: model.json().nullable(),
|
||||
/**
|
||||
* Zuletzt gelieferte Variante. Verhindert bei "random", dass zweimal
|
||||
* hintereinander dieselbe Sorte kommt.
|
||||
*/
|
||||
last_variant_id: model.text().nullable(),
|
||||
/**
|
||||
* Glasgröße als Variantentitel, z. B. "250 Gramm".
|
||||
*
|
||||
* Gilt für beide Auswahlarten: bei "random" wird der Zufallspool darauf
|
||||
* eingeschränkt, bei "fixed" steckt sie ohnehin schon in der Variante.
|
||||
* Bewusst Text statt Aufzählung — kommt eine neue Größe ins Sortiment,
|
||||
* braucht es keine Migration.
|
||||
*/
|
||||
size: model.text().nullable(),
|
||||
|
||||
/** Gläser je Lieferung. */
|
||||
quantity: model.number().default(1),
|
||||
|
||||
// --- Wann ---
|
||||
interval: model.enum(["monthly", "quarterly", "biannual"]),
|
||||
next_order_at: model.dateTime(),
|
||||
last_order_at: model.dateTime().nullable(),
|
||||
|
||||
// --- Zustand ---
|
||||
status: model.enum(["active", "paused", "canceled"]).default("active"),
|
||||
paused_at: model.dateTime().nullable(),
|
||||
canceled_at: model.dateTime().nullable(),
|
||||
/** Grund der Kündigung, für Auswertung. Freitext des Kunden. */
|
||||
cancel_reason: model.text().nullable(),
|
||||
|
||||
// --- Zahlung (Mollie) ---
|
||||
mollie_customer_id: model.text().nullable(),
|
||||
mollie_mandate_id: model.text().nullable(),
|
||||
/** "creditcard", "directdebit" oder "paypal" — womit abgebucht wird. */
|
||||
payment_method: model.text().nullable(),
|
||||
|
||||
// --- Versand und Preis ---
|
||||
shipping_address: model.json().nullable(),
|
||||
shipping_option_id: model.text().nullable(),
|
||||
region_id: model.text().nullable(),
|
||||
currency_code: model.text().default("eur"),
|
||||
sales_channel_id: model.text().nullable(),
|
||||
|
||||
/* --- Geschenk-Abo -----------------------------------------------------
|
||||
* Ein verschenktes Abo läuft nicht endlos, sondern über eine feste Zahl
|
||||
* von Lieferungen, und ist im Voraus bezahlt. Es wird deshalb nie
|
||||
* abgebucht — `prepaid` schaltet den Zahlungsteil des Jobs ab.
|
||||
*/
|
||||
|
||||
/** Wahr, wenn das Abo bereits vollständig bezahlt ist. */
|
||||
prepaid: model.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Wie viele Lieferungen noch ausstehen. `null` heißt: unbefristet.
|
||||
* Bei 0 endet das Abo von selbst.
|
||||
*/
|
||||
remaining_deliveries: model.number().nullable(),
|
||||
|
||||
/** Wer beschenkt wird. Leer, wenn das Abo für den Besteller selbst ist. */
|
||||
gift_recipient_name: model.text().nullable(),
|
||||
gift_recipient_email: model.text().nullable(),
|
||||
/** Wer schenkt — steht in der Ankündigung an den Beschenkten. */
|
||||
gift_sender_name: model.text().nullable(),
|
||||
/** Ob die Ankündigung an den Beschenkten schon raus ist. */
|
||||
gift_announced_at: model.dateTime().nullable(),
|
||||
|
||||
/**
|
||||
* Der Bestellposten, aus dem dieses Abo entstanden ist. Verhindert, dass
|
||||
* dieselbe Bestellung zweimal zu Abos führt — `order.placed` kann sich
|
||||
* wiederholen.
|
||||
*/
|
||||
source_line_item_id: model.text().nullable(),
|
||||
|
||||
/**
|
||||
* Zählt fehlgeschlagene Abbuchungen. Nach mehreren Versuchen wird das Abo
|
||||
* pausiert, statt endlos weiterzuversuchen.
|
||||
*/
|
||||
failed_attempts: model.number().default(0),
|
||||
last_error: model.text().nullable(),
|
||||
})
|
||||
.indexes([
|
||||
// Der Tagesjob sucht genau danach.
|
||||
{ on: ["status", "next_order_at"] },
|
||||
{ on: ["customer_id"] },
|
||||
]);
|
||||
|
||||
export default Subscription;
|
||||
@@ -0,0 +1,97 @@
|
||||
import { MedusaService } from "@medusajs/framework/utils";
|
||||
import Subscription from "./models/subscription";
|
||||
import SubscriptionSetting from "./models/subscription-setting";
|
||||
|
||||
/** Monatsschritte je Intervall. */
|
||||
const INTERVAL_MONTHS: Record<string, number> = {
|
||||
monthly: 1,
|
||||
quarterly: 3,
|
||||
biannual: 6,
|
||||
};
|
||||
|
||||
/** Feste ID der einen Einstellungszeile. */
|
||||
const SETTINGS_ID = "subset_default";
|
||||
|
||||
class SubscriptionModuleService extends MedusaService({ Subscription, SubscriptionSetting }) {
|
||||
/**
|
||||
* Nächster Liefertermin ab einem Stichtag.
|
||||
*
|
||||
* Rechnet in Monaten, nicht in Tagen: "alle 3 Monate" soll am gleichen
|
||||
* Kalendertag landen. Der 31. wird dabei auf den letzten Tag des Zielmonats
|
||||
* gezogen, sonst würde der 31. Januar auf den 3. März rutschen.
|
||||
*/
|
||||
computeNextOrderDate(interval: string, from: Date = new Date()): Date {
|
||||
const months = INTERVAL_MONTHS[interval];
|
||||
if (!months) throw new Error(`Unbekanntes Intervall: ${interval}`);
|
||||
|
||||
const day = from.getDate();
|
||||
const next = new Date(from);
|
||||
next.setDate(1);
|
||||
next.setMonth(next.getMonth() + months);
|
||||
const lastDayOfTarget = new Date(next.getFullYear(), next.getMonth() + 1, 0).getDate();
|
||||
next.setDate(Math.min(day, lastDayOfTarget));
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Einstellungen lesen. Legt beim ersten Aufruf die Standardzeile an, damit
|
||||
* weder Admin noch Job einen Sonderfall für "noch nichts gespeichert"
|
||||
* behandeln müssen.
|
||||
*/
|
||||
async getSettings() {
|
||||
const existing = await this.listSubscriptionSettings({ id: SETTINGS_ID } as any);
|
||||
if (existing?.length) return existing[0];
|
||||
const created = await this.createSubscriptionSettings({
|
||||
id: SETTINGS_ID,
|
||||
discount_percent: 0,
|
||||
discount_label: null,
|
||||
free_shipping_threshold: null,
|
||||
} as any);
|
||||
return Array.isArray(created) ? created[0] : created;
|
||||
}
|
||||
|
||||
async updateSettings(input: {
|
||||
discount_percent?: number;
|
||||
discount_label?: string | null;
|
||||
free_shipping_threshold?: number | null;
|
||||
}) {
|
||||
await this.getSettings();
|
||||
const percent = input.discount_percent;
|
||||
if (percent != null) {
|
||||
// Die Spalte ist ganzzahlig; Nachkommastellen würden stillschweigend
|
||||
// abgeschnitten. Deshalb hier ablehnen statt still zu runden.
|
||||
if (!Number.isInteger(percent) || percent < 0 || percent > 100) {
|
||||
throw new Error("Rabatt muss eine ganze Zahl zwischen 0 und 100 sein.");
|
||||
}
|
||||
}
|
||||
const threshold = input.free_shipping_threshold;
|
||||
if (threshold != null) {
|
||||
// Gleiche Begründung wie oben: ganze Euro, sonst wird stillschweigend
|
||||
// abgeschnitten und der Shop verspricht eine andere Schwelle, als am
|
||||
// Versandpreis hinterlegt ist.
|
||||
if (!Number.isInteger(threshold) || threshold <= 0) {
|
||||
throw new Error("Die Schwelle muss eine ganze Zahl in Euro sein, größer als 0.");
|
||||
}
|
||||
}
|
||||
const updated = await this.updateSubscriptionSettings({
|
||||
id: SETTINGS_ID,
|
||||
...(percent != null ? { discount_percent: percent } : {}),
|
||||
...(input.discount_label !== undefined ? { discount_label: input.discount_label } : {}),
|
||||
...(input.free_shipping_threshold !== undefined
|
||||
? { free_shipping_threshold: threshold }
|
||||
: {}),
|
||||
} as any);
|
||||
return Array.isArray(updated) ? updated[0] : updated;
|
||||
}
|
||||
|
||||
/** Abos, die heute fällig sind. */
|
||||
async listDue(now: Date = new Date()) {
|
||||
return this.listSubscriptions({
|
||||
status: "active",
|
||||
next_order_at: { $lte: now },
|
||||
} as any);
|
||||
}
|
||||
}
|
||||
|
||||
export default SubscriptionModuleService;
|
||||
export { INTERVAL_MONTHS };
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Inbetriebnahme-Prüfung für die Versandanbindung.
|
||||
*
|
||||
* npx medusa exec ./src/scripts/check-carriers.ts
|
||||
*
|
||||
* Prüft, welche Carrier konfiguriert sind, schickt bei DHL eine Testsendung
|
||||
* mit `?validate=true` (DHL prüft nur die Daten, erzeugt KEIN Label und zieht
|
||||
* KEIN Porto) und meldet Lücken in den Stammdaten.
|
||||
*
|
||||
* Gedacht für den Moment, in dem die Zugangsdaten ankommen: einmal laufen
|
||||
* lassen, bevor irgendetwas scharf geschaltet wird.
|
||||
*/
|
||||
|
||||
const REQUIRED_DHL = [
|
||||
"DHL_API_KEY",
|
||||
"DHL_USERNAME",
|
||||
"DHL_PASSWORD",
|
||||
"DHL_BILLING_NUMBER",
|
||||
"DHL_SHIPPER_NAME",
|
||||
"DHL_SHIPPER_STREET",
|
||||
"DHL_SHIPPER_POSTAL_CODE",
|
||||
"DHL_SHIPPER_CITY",
|
||||
];
|
||||
|
||||
function line(char = "-") {
|
||||
console.log(char.repeat(64));
|
||||
}
|
||||
|
||||
async function checkDhl() {
|
||||
console.log("\nDHL Paket DE Versenden v2");
|
||||
line();
|
||||
const missing = REQUIRED_DHL.filter((key) => !process.env[key]);
|
||||
if (missing.length) {
|
||||
console.log(" nicht konfiguriert. Fehlende Werte:");
|
||||
missing.forEach((key) => console.log(` - ${key}`));
|
||||
return;
|
||||
}
|
||||
|
||||
const sandbox = process.env.DHL_SANDBOX === "true";
|
||||
const base = sandbox
|
||||
? "https://api-sandbox.dhl.com/parcel/de/shipping/v2"
|
||||
: "https://api-eu.dhl.com/parcel/de/shipping/v2";
|
||||
console.log(` Umgebung: ${sandbox ? "Sandbox" : "PRODUKTION"}`);
|
||||
console.log(` Nur prüfen: ${process.env.DHL_VALIDATE_ONLY === "true" ? "ja" : "NEIN – Labels werden erzeugt"}`);
|
||||
console.log(` Abrechnungsnr: ${process.env.DHL_BILLING_NUMBER} (${String(process.env.DHL_BILLING_NUMBER).length} Zeichen, erwartet 14)`);
|
||||
|
||||
const payload = {
|
||||
profile: "STANDARD",
|
||||
shipments: [
|
||||
{
|
||||
product: "V01PAK",
|
||||
billingNumber: process.env.DHL_BILLING_NUMBER,
|
||||
refNo: "pruefung-inbetriebnahme",
|
||||
shipper: {
|
||||
name1: process.env.DHL_SHIPPER_NAME,
|
||||
addressStreet: process.env.DHL_SHIPPER_STREET,
|
||||
postalCode: process.env.DHL_SHIPPER_POSTAL_CODE,
|
||||
city: process.env.DHL_SHIPPER_CITY,
|
||||
country: (process.env.DHL_SHIPPER_COUNTRY ?? "DEU").toUpperCase(),
|
||||
},
|
||||
consignee: {
|
||||
name1: "Testempfaenger",
|
||||
addressStreet: "Isestr. 109",
|
||||
postalCode: "20149",
|
||||
city: "Hamburg",
|
||||
country: "DEU",
|
||||
},
|
||||
details: { weight: { uom: "g", value: 600 } },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch(`${base}/orders?validate=true`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Basic ${Buffer.from(`${process.env.DHL_USERNAME}:${process.env.DHL_PASSWORD}`).toString("base64")}`,
|
||||
"dhl-api-key": process.env.DHL_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const body: any = await res.json().catch(() => ({}));
|
||||
|
||||
if (res.ok) {
|
||||
console.log(` Prüfaufruf: OK (HTTP ${res.status}) – Zugangsdaten und Adressdaten akzeptiert`);
|
||||
const status = body?.status ?? body?.items?.[0]?.sstatus;
|
||||
if (status) console.log(` DHL-Meldung: ${JSON.stringify(status).slice(0, 200)}`);
|
||||
} else {
|
||||
console.log(` Prüfaufruf: FEHLER (HTTP ${res.status})`);
|
||||
console.log(` Antwort: ${JSON.stringify(body).slice(0, 600)}`);
|
||||
if (res.status === 401) console.log(" Hinweis: Benutzer/Passwort oder API-Key falsch.");
|
||||
if (res.status === 403) console.log(" Hinweis: Benutzer hat vermutlich kein Recht \"Versenden\".");
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(` Prüfaufruf: nicht erreichbar – ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function checkOthers() {
|
||||
console.log("\nWeitere Carrier");
|
||||
line();
|
||||
const sendcloud = process.env.SENDCLOUD_PUBLIC_KEY && process.env.SENDCLOUD_SECRET_KEY;
|
||||
console.log(` Sendcloud: ${sendcloud ? "konfiguriert" : "nicht konfiguriert"}`);
|
||||
console.log(" Internetmarke: Modul noch nicht gebaut (1C4A/SOAP, braucht Portokasse,");
|
||||
console.log(" Partner-ID und SCHLUESSEL_DPWN_MARKTPLATZ von der DPAG)");
|
||||
console.log(" Hermes: Modul nicht baubar – keine öffentliche Doku. Erst nach");
|
||||
console.log(" Vertrag und beantragtem Entwicklerzugang (HSI).");
|
||||
}
|
||||
|
||||
export default async function ({ container }: any) {
|
||||
const query = container.resolve("query");
|
||||
|
||||
console.log("");
|
||||
line("=");
|
||||
console.log(" Versandanbindung – Inbetriebnahme-Prüfung");
|
||||
line("=");
|
||||
|
||||
await checkDhl();
|
||||
checkOthers();
|
||||
|
||||
console.log("\nVersandarten im Shop");
|
||||
line();
|
||||
const { data: options } = await query.graph({
|
||||
entity: "shipping_option",
|
||||
fields: ["id", "name", "provider_id", "data"],
|
||||
});
|
||||
if (!options?.length) {
|
||||
console.log(" keine angelegt");
|
||||
}
|
||||
for (const option of options ?? []) {
|
||||
const product = (option.data as any)?.dhl_product ?? "–";
|
||||
console.log(` ${option.name.padEnd(22)} Provider: ${String(option.provider_id).padEnd(16)} Produkt: ${product}`);
|
||||
}
|
||||
const manual = (options ?? []).filter((o: any) => o.provider_id === "manual_manual");
|
||||
if (manual.length) {
|
||||
console.log(`\n ${manual.length} Versandart(en) laufen noch über "manual_manual" –`);
|
||||
console.log(" dabei entsteht eine Fulfillment, aber KEIN Label.");
|
||||
console.log(" Anlegen der Carrier-Versandarten: src/scripts/setup-shipping-options.ts");
|
||||
}
|
||||
|
||||
console.log("\nVersandgewichte der Varianten");
|
||||
line();
|
||||
const { data: variants } = await query.graph({
|
||||
entity: "variant",
|
||||
fields: ["id", "title", "weight", "product.title"],
|
||||
});
|
||||
const withWeight = (variants ?? []).filter((v: any) => v.weight);
|
||||
console.log(` ${withWeight.length} von ${variants?.length ?? 0} Varianten haben ein Versandgewicht.`);
|
||||
if (withWeight.length < (variants?.length ?? 0)) {
|
||||
console.log(" Für die übrigen greift DHL_DEFAULT_ITEM_WEIGHT_G " +
|
||||
`(${process.env.DHL_DEFAULT_ITEM_WEIGHT_G ?? 600} g).`);
|
||||
console.log(" Achtung: das Metadatenfeld net_weight_grams ist die Füllmenge für");
|
||||
console.log(" den Grundpreis, NICHT das Versandgewicht. Gewichte im Admin unter");
|
||||
console.log(" Produkt -> Variante -> Versand eintragen.");
|
||||
}
|
||||
|
||||
console.log("");
|
||||
line("=");
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Übernimmt Beschreibungstexte und Versandgewichte aus dem alten Shopify-Shop
|
||||
* shop.hhonig.de in die Produkte dieses Shops.
|
||||
*
|
||||
* Abgleich ansehen, nichts ändern:
|
||||
* HHONIG_JSON=/pfad/hhonig-products.json \
|
||||
* npx medusa exec ./src/scripts/import-hhonig-inhalte.ts
|
||||
*
|
||||
* Wirklich schreiben:
|
||||
* HHONIG_WRITE=1 HHONIG_JSON=/pfad/hhonig-products.json \
|
||||
* npx medusa exec ./src/scripts/import-hhonig-inhalte.ts
|
||||
*
|
||||
* Die JSON-Datei kommt von `curl https://shop.hhonig.de/products.json?limit=250`.
|
||||
*
|
||||
* Es wird nur gefüllt, was hier leer ist — vorhandene Texte und Gewichte
|
||||
* bleiben unangetastet. Das Skript ist wiederholbar.
|
||||
*
|
||||
* Zum Gewicht: Shopify führt pro Variante `grams`. Das ist das Versandgewicht
|
||||
* inklusive Glas (250-g-Honig wiegt dort 400 g), also genau das, was DHL für
|
||||
* das Label braucht. Das Füllgewicht steckt hier in
|
||||
* `variant.metadata.net_weight_grams` und wird nicht angefasst.
|
||||
*/
|
||||
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||
import { readFileSync } from "fs";
|
||||
|
||||
type ShopifyVariante = { title: string; grams: number | null };
|
||||
type ShopifyProdukt = { title: string; handle: string; body_html: string; variants: ShopifyVariante[] };
|
||||
|
||||
/** HTML zu Fließtext: Absätze bleiben als Leerzeile erhalten. */
|
||||
function alsText(html: string): string {
|
||||
return html
|
||||
.replace(/<br\s*\/?>/gi, "\n")
|
||||
.replace(/<\/(p|div|li|h[1-6])>/gi, "\n\n")
|
||||
.replace(/<li[^>]*>/gi, "• ")
|
||||
.replace(/<[^>]+>/g, "")
|
||||
.replace(/ /g, " ")
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'|’/g, "'")
|
||||
.replace(/ä/g, "ä").replace(/ö/g, "ö").replace(/ü/g, "ü")
|
||||
.replace(/Ä/g, "Ä").replace(/Ö/g, "Ö").replace(/Ü/g, "Ü")
|
||||
.replace(/ß/g, "ß")
|
||||
.replace(/[ \t]+/g, " ")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Für den Vergleich: Kleinschreibung, nur Buchstaben und Ziffern. */
|
||||
function schluessel(s: string): string {
|
||||
return s.toLowerCase().replace(/ß/g, "ss").replace(/[^a-z0-9äöü]/g, "");
|
||||
}
|
||||
|
||||
export default async function ({ container }: any) {
|
||||
const query = container.resolve("query");
|
||||
const logger = container.resolve("logger");
|
||||
|
||||
const pfad = process.env.HHONIG_JSON;
|
||||
if (!pfad) {
|
||||
logger.error("HHONIG_JSON fehlt — Pfad zur products.json des alten Shops angeben.");
|
||||
return;
|
||||
}
|
||||
const schreiben = process.env.HHONIG_WRITE === "1";
|
||||
const alt: ShopifyProdukt[] = JSON.parse(readFileSync(pfad, "utf-8")).products;
|
||||
|
||||
const { data: neu } = await query.graph({
|
||||
entity: "product",
|
||||
fields: ["id", "title", "handle", "description", "variants.id", "variants.title", "variants.weight"],
|
||||
});
|
||||
|
||||
const altNachTitel = new Map(alt.map((p) => [schluessel(p.title), p]));
|
||||
const altNachHandle = new Map(alt.map((p) => [p.handle, p]));
|
||||
const getroffen = new Set<string>();
|
||||
|
||||
let textFehlt = 0;
|
||||
let gewichtFehlt = 0;
|
||||
const ohneVorlage: string[] = [];
|
||||
|
||||
for (const produkt of neu) {
|
||||
const vorlage =
|
||||
altNachHandle.get(produkt.handle) ??
|
||||
altNachTitel.get(schluessel(produkt.title)) ??
|
||||
alt.find((p) => schluessel(p.title).startsWith(schluessel(produkt.title).slice(0, 18)));
|
||||
|
||||
if (!vorlage) {
|
||||
ohneVorlage.push(produkt.title);
|
||||
continue;
|
||||
}
|
||||
getroffen.add(vorlage.handle);
|
||||
|
||||
const neuerText = !produkt.description && alsText(vorlage.body_html) ? alsText(vorlage.body_html) : null;
|
||||
|
||||
const gewichte = (produkt.variants ?? [])
|
||||
.map((v: any) => {
|
||||
if (v.weight) return null;
|
||||
const q = vorlage.variants.find((x) => schluessel(x.title) === schluessel(v.title));
|
||||
return q?.grams ? { id: v.id, title: v.title, weight: q.grams } : null;
|
||||
})
|
||||
.filter(Boolean) as { id: string; title: string; weight: number }[];
|
||||
|
||||
if (!neuerText && !gewichte.length) continue;
|
||||
|
||||
if (neuerText) textFehlt++;
|
||||
gewichtFehlt += gewichte.length;
|
||||
|
||||
logger.info(
|
||||
`${produkt.title}` +
|
||||
(neuerText ? ` | Text: ${neuerText.length} Zeichen` : "") +
|
||||
(gewichte.length ? ` | Gewicht: ${gewichte.map((g) => `${g.title} = ${g.weight} g`).join(", ")}` : "")
|
||||
);
|
||||
|
||||
if (schreiben) {
|
||||
await updateProductsWorkflow(container).run({
|
||||
input: {
|
||||
selector: { id: produkt.id },
|
||||
update: {
|
||||
...(neuerText ? { description: neuerText } : {}),
|
||||
...(gewichte.length
|
||||
? { variants: gewichte.map((g) => ({ id: g.id, weight: g.weight })) }
|
||||
: {}),
|
||||
},
|
||||
} as any,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const fehlend = alt.filter((p) => !getroffen.has(p.handle)).map((p) => p.title);
|
||||
|
||||
logger.info("—".repeat(60));
|
||||
logger.info(`${schreiben ? "Geschrieben" : "Offen (nichts geändert)"}: ${textFehlt} Beschreibungen, ${gewichtFehlt} Versandgewichte.`);
|
||||
if (ohneVorlage.length) logger.info(`Ohne Vorlage im alten Shop (${ohneVorlage.length}): ${ohneVorlage.join(", ")}`);
|
||||
if (fehlend.length) logger.info(`Im alten Shop, hier nicht zugeordnet (${fehlend.length}): ${fehlend.join(", ")}`);
|
||||
if (!schreiben) logger.info("Zum Schreiben: HHONIG_WRITE=1 voranstellen.");
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Hängt die gebauten Kacheln an die Produkte, von denen es kein Foto gibt:
|
||||
* Gutschein und Honig-Abo.
|
||||
*
|
||||
* npx medusa exec ./src/scripts/set-platzhalter-bilder.ts
|
||||
*
|
||||
* Die Bilder liegen im Frontend unter `public/images/shop/`. Der Pfad wird
|
||||
* bewusst relativ gespeichert, damit er unter jeder Domain stimmt.
|
||||
*
|
||||
* Wiederholbar: Ein vorhandenes Bild wird nicht überschrieben.
|
||||
*/
|
||||
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||
|
||||
const KACHELN: Record<string, string> = {
|
||||
geschenkgutschein: "/images/shop/gutschein.svg",
|
||||
"honig-abo": "/images/shop/honig-abo.svg",
|
||||
};
|
||||
|
||||
export default async function ({ container }: any) {
|
||||
const query = container.resolve("query");
|
||||
const logger = container.resolve("logger");
|
||||
|
||||
for (const [handle, pfad] of Object.entries(KACHELN)) {
|
||||
const { data } = await query.graph({
|
||||
entity: "product",
|
||||
fields: ["id", "title", "thumbnail"],
|
||||
filters: { handle },
|
||||
});
|
||||
const produkt = data?.[0];
|
||||
|
||||
if (!produkt) {
|
||||
logger.error(`Kein Produkt mit dem Handle "${handle}".`);
|
||||
continue;
|
||||
}
|
||||
if (produkt.thumbnail) {
|
||||
logger.info(`${produkt.title}: hat schon ein Bild (${produkt.thumbnail}) — nichts geändert.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await updateProductsWorkflow(container).run({
|
||||
input: { selector: { id: produkt.id }, update: { thumbnail: pfad } } as any,
|
||||
});
|
||||
logger.info(`${produkt.title}: Kachel gesetzt → ${pfad}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Richtet den Versandanteil für verschenkte Abos ein.
|
||||
*
|
||||
* npx medusa exec ./src/scripts/setup-gift-shipping.ts
|
||||
*
|
||||
* Hintergrund: eine Bestellung in Medusa trägt genau einen Versandposten.
|
||||
* Ein Geschenk-Abo verursacht aber mehrere Pakete. Soll jedes davon seinen
|
||||
* Versand tragen, muss der Anteil für die weiteren Pakete beim Kauf als
|
||||
* eigener Posten mitverkauft werden — dafür ist dieser Artikel da.
|
||||
*
|
||||
* Eingestellt wird beides im Admin, ohne Deployment:
|
||||
* - AM ABO-PRODUKT, Metadaten: `gift_shipping` = "once" oder "per_delivery"
|
||||
* - AM ARTIKEL "Versandanteil": der Preis je weiterem Paket
|
||||
*
|
||||
* Das Skript ist wiederholbar und überschreibt keine Preise.
|
||||
*/
|
||||
import { createProductsWorkflow, updateProductsWorkflow } from "@medusajs/core-flows";
|
||||
import { ProductStatus } from "@medusajs/framework/utils";
|
||||
|
||||
export const GIFT_SHIPPING_HANDLE = "versandanteil-geschenk-abo";
|
||||
const SUBSCRIPTION_PRODUCT_HANDLE = "honig-abo";
|
||||
|
||||
export default async function ({ container }: any) {
|
||||
const query = container.resolve("query");
|
||||
const logger = container.resolve("logger");
|
||||
|
||||
// 1. Die Einstellung am Abo-Produkt anlegen, falls sie fehlt.
|
||||
const { data: abos } = await query.graph({
|
||||
entity: "product",
|
||||
fields: ["id", "title", "metadata"],
|
||||
filters: { handle: SUBSCRIPTION_PRODUCT_HANDLE },
|
||||
});
|
||||
const abo = abos?.[0];
|
||||
if (!abo) {
|
||||
logger.error(`Produkt "${SUBSCRIPTION_PRODUCT_HANDLE}" nicht gefunden.`);
|
||||
return;
|
||||
}
|
||||
if (!(abo.metadata ?? {}).gift_shipping) {
|
||||
await updateProductsWorkflow(container).run({
|
||||
input: {
|
||||
selector: { id: abo.id },
|
||||
update: { metadata: { ...(abo.metadata ?? {}), gift_shipping: "once" } },
|
||||
} as any,
|
||||
});
|
||||
logger.info('Abo-Produkt: gift_shipping = "once" gesetzt (Versand einmalig).');
|
||||
} else {
|
||||
logger.info(`Abo-Produkt: gift_shipping steht auf "${(abo.metadata as any).gift_shipping}".`);
|
||||
}
|
||||
|
||||
// 2. Den Artikel für den Versandanteil anlegen, falls er fehlt.
|
||||
const { data: vorhanden } = await query.graph({
|
||||
entity: "product",
|
||||
fields: ["id", "title", "variants.id", "variants.prices.amount"],
|
||||
filters: { handle: GIFT_SHIPPING_HANDLE },
|
||||
});
|
||||
if (vorhanden?.[0]) {
|
||||
const preis = vorhanden[0].variants?.[0]?.prices?.[0]?.amount;
|
||||
logger.info(`Artikel "Versandanteil" existiert bereits (${preis} EUR je weiterem Paket).`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Als Startwert der Preis der günstigsten Versandart, die der Shop
|
||||
// anbietet — im Admin jederzeit änderbar.
|
||||
const { data: optionen } = await query.graph({
|
||||
entity: "shipping_option",
|
||||
fields: ["id", "name", "price_type", "rules.attribute", "rules.value", "prices.amount", "prices.currency_code", "prices.price_rules.attribute"],
|
||||
});
|
||||
const imShop = (o: any) =>
|
||||
(o.rules ?? []).some((r: any) => r.attribute === "enabled_in_store" && String(r.value) === "true");
|
||||
const preise = (optionen ?? [])
|
||||
.filter((o: any) => o.price_type === "flat" && imShop(o))
|
||||
.flatMap((o: any) =>
|
||||
(o.prices ?? [])
|
||||
.filter((p: any) => p.currency_code === "eur" && !(p.price_rules ?? []).some((r: any) => r.attribute === "item_total"))
|
||||
.map((p: any) => Number(p.amount))
|
||||
)
|
||||
.filter((n: number) => n > 0);
|
||||
const startpreis = preise.length ? Math.min(...preise) : 4.99;
|
||||
|
||||
const { data: profiles } = await query.graph({ entity: "shipping_profile", fields: ["id"] });
|
||||
const { data: channels } = await query.graph({ entity: "sales_channel", fields: ["id"] });
|
||||
|
||||
await createProductsWorkflow(container).run({
|
||||
input: {
|
||||
products: [
|
||||
{
|
||||
title: "Versandanteil Geschenk-Abo",
|
||||
handle: GIFT_SHIPPING_HANDLE,
|
||||
status: ProductStatus.PUBLISHED,
|
||||
shipping_profile_id: profiles?.[0]?.id,
|
||||
sales_channels: channels?.map((c: any) => ({ id: c.id })),
|
||||
description:
|
||||
"Anteil an den Versandkosten für die weiteren Pakete eines verschenkten " +
|
||||
"Honig-Abos. Wird beim Kauf automatisch hinzugefügt und ist im Shop " +
|
||||
"nicht einzeln bestellbar.",
|
||||
// Der Shop blendet Artikel mit diesem Merkmal aus.
|
||||
metadata: { hidden: true, gift_shipping_surcharge: true },
|
||||
options: [{ title: "Art", values: ["Standard"] }],
|
||||
variants: [
|
||||
{
|
||||
title: "Versandanteil",
|
||||
sku: "GESCHENK-VERSANDANTEIL",
|
||||
// Kein Lagerartikel.
|
||||
manage_inventory: false,
|
||||
options: { Art: "Standard" },
|
||||
prices: [{ amount: startpreis, currency_code: "eur" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`Artikel "Versandanteil Geschenk-Abo" angelegt, ${startpreis} EUR je weiterem Paket ` +
|
||||
"(aus der günstigsten Versandart übernommen — im Admin anpassen)."
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Richtet den Geschenkgutschein als digitales Produkt ein.
|
||||
*
|
||||
* npx medusa exec ./src/scripts/setup-gift-voucher.ts
|
||||
*
|
||||
* Drei Dinge:
|
||||
* 1. `metadata.gift_voucher = true` — daran erkennen Shop und Backend den
|
||||
* Gutschein. Bewusst nicht `is_giftcard`: dann legte der Subscriber des
|
||||
* Loyalty-Plugins den Code schon bei `order.placed` an, also bei Kauf
|
||||
* auf Rechnung vor dem Zahlungseingang.
|
||||
* 2. Kein Versandprofil. Ohne Profil verlangt Medusa für den Posten keine
|
||||
* Versandart; der Gutschein kommt per E-Mail.
|
||||
* 3. Eine Beschreibung, falls noch keine da ist.
|
||||
*
|
||||
* Wiederholbar: was schon stimmt, bleibt unangetastet.
|
||||
*/
|
||||
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||
|
||||
const HANDLE = "geschenkgutschein";
|
||||
|
||||
const BESCHREIBUNG = [
|
||||
"Der Gutschein kommt nach Zahlungseingang per E-Mail — an Sie oder direkt an die Person, die Sie beschenken möchten.",
|
||||
"Er gilt für alles im Shop und muss nicht auf einmal eingelöst werden: Was übrig bleibt, bleibt als Guthaben auf dem Code.",
|
||||
].join("\n\n");
|
||||
|
||||
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", "description", "metadata", "shipping_profile.id"],
|
||||
filters: { handle: HANDLE },
|
||||
});
|
||||
|
||||
const produkt = produkte?.[0];
|
||||
if (!produkt) {
|
||||
logger.error(`Kein Produkt mit dem Handle "${HANDLE}" gefunden.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const update: Record<string, any> = {};
|
||||
|
||||
if (!produkt.metadata?.gift_voucher) {
|
||||
update.metadata = { ...(produkt.metadata ?? {}), gift_voucher: true };
|
||||
}
|
||||
if (produkt.shipping_profile?.id) {
|
||||
// `null` entfernt die Verknüpfung, ohne eine neue anzulegen.
|
||||
update.shipping_profile_id = null;
|
||||
}
|
||||
if (!String(produkt.description ?? "").trim()) {
|
||||
update.description = BESCHREIBUNG;
|
||||
}
|
||||
|
||||
if (!Object.keys(update).length) {
|
||||
logger.info(` "${produkt.title}" ist bereits eingerichtet.`);
|
||||
return;
|
||||
}
|
||||
|
||||
await updateProductsWorkflow(container).run({
|
||||
input: { selector: { id: produkt.id }, update } as any,
|
||||
});
|
||||
|
||||
logger.info(
|
||||
` "${produkt.title}": ${[
|
||||
update.metadata ? "als Gutschein markiert" : null,
|
||||
"shipping_profile_id" in update ? "Versandprofil entfernt" : null,
|
||||
update.description ? "Beschreibung ergänzt" : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(", ")}.`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* Richtet die Versandarten ein.
|
||||
*
|
||||
* npx medusa exec ./src/scripts/setup-shipping-options.ts
|
||||
*
|
||||
* Danach gilt:
|
||||
* - Im Webshop stehen nur die DHL-Versandarten zur Auswahl.
|
||||
* - Hermes steht weiterhin bereit, aber nur für Bestellungen, die im
|
||||
* Admin angelegt werden.
|
||||
* - Medusas mitgelieferte Versandarten ("Standard"/"Express") sind, falls
|
||||
* vorhanden, im Webshop ausgeblendet.
|
||||
*
|
||||
* Der Unterschied zwischen "Webshop" und "nur intern" ist Medusas eigene
|
||||
* Regel `enabled_in_store`. Der Shop fragt seine Versandarten mit
|
||||
* enabled_in_store=true ab; im Admin gilt die Einschränkung nicht.
|
||||
*
|
||||
* Das Skript ist wiederholbar: Vorhandenes wird angepasst, nicht doppelt
|
||||
* angelegt.
|
||||
*
|
||||
* ⚠️ Die Preise unten sind PLATZHALTER. Sie müssen zu euren Konditionen
|
||||
* passen — im Zweifel im Admin nachziehen.
|
||||
*/
|
||||
import { createShippingOptionsWorkflow, updateShippingOptionsWorkflow } from "@medusajs/core-flows";
|
||||
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
||||
import { syncFreeShipping } from "../lib/free-shipping";
|
||||
|
||||
type Vorgabe = {
|
||||
name: string;
|
||||
code: string;
|
||||
description: string;
|
||||
amount: number;
|
||||
/** true = im Webshop wählbar, false = nur im Admin. */
|
||||
imShop: boolean;
|
||||
/** Nur für DHL: welches Produkt gebucht wird, sobald der Provider läuft. */
|
||||
dhlProdukt?: string;
|
||||
/** Ob diese Versandart den DHL-Provider braucht. */
|
||||
brauchtDhl: boolean;
|
||||
};
|
||||
|
||||
const VORGABEN: Vorgabe[] = [
|
||||
{
|
||||
name: "DHL Paket",
|
||||
code: "dhl-paket",
|
||||
description: "Versand bis 31,5 kg innerhalb Deutschlands",
|
||||
amount: 5.49, // Platzhalter
|
||||
imShop: true,
|
||||
dhlProdukt: "V01PAK",
|
||||
brauchtDhl: true,
|
||||
},
|
||||
{
|
||||
name: "DHL Kleinpaket",
|
||||
code: "dhl-kleinpaket",
|
||||
// Nachfolger der zum 31.05.2026 eingestellten Warenpost (V62WP).
|
||||
description: "Kleine Sendungen bis 1 kg",
|
||||
amount: 3.99, // Platzhalter
|
||||
imShop: true,
|
||||
dhlProdukt: "V62KP",
|
||||
brauchtDhl: true,
|
||||
},
|
||||
{
|
||||
name: "Hermes Paket",
|
||||
code: "hermes-paket",
|
||||
description: "Nur für Bestellungen, die im Admin angelegt werden",
|
||||
amount: 4.95, // Platzhalter
|
||||
imShop: false,
|
||||
// Für Hermes gibt es kein eigenes Modul. Die Versandart läuft über den
|
||||
// manuellen Dienstleister: die Sendung wird von Hand bei Hermes
|
||||
// eingeliefert, Medusa erzeugt kein Label.
|
||||
brauchtDhl: false,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Medusas mitgelieferte Versandarten. In dieser Installation sind sie
|
||||
* gelöscht; in einer frisch aufgesetzten legt der Seed sie wieder an, und
|
||||
* dann sollen sie zumindest nicht im Shop auftauchen. Das Skript blendet
|
||||
* sie nur aus und löscht nichts — ein Löschen gehört in eine bewusste
|
||||
* Entscheidung, nicht in ein Einrichtungsskript.
|
||||
*/
|
||||
const AUS_DEM_SHOP_NEHMEN = ["Standard Shipping", "Express Shipping"];
|
||||
|
||||
const OPTION_FIELDS = [
|
||||
"id",
|
||||
"name",
|
||||
"provider_id",
|
||||
"price_type",
|
||||
"rules.id",
|
||||
"rules.attribute",
|
||||
"rules.operator",
|
||||
"rules.value",
|
||||
"prices.amount",
|
||||
"prices.currency_code",
|
||||
"prices.price_rules.attribute",
|
||||
];
|
||||
|
||||
function ladenRegel(option: any, attribut: string) {
|
||||
return (option.rules ?? []).find((r: any) => r.attribute === attribut);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Regeln einer Versandart mit einem geänderten Wert.
|
||||
*
|
||||
* Vollständig, weil das Schreiben die bisherigen Regeln ersetzt: schickt man
|
||||
* nur die eine geänderte, verliert die Versandart alle übrigen — etwa
|
||||
* `is_return`, ohne die sie auch als Rückversandart auftauchen kann.
|
||||
*/
|
||||
function regelnMit(option: any, attribut: string, wert: string) {
|
||||
return (option.rules ?? []).map((regel: any) => ({
|
||||
id: regel.id,
|
||||
attribute: regel.attribute,
|
||||
operator: regel.operator,
|
||||
value: regel.attribute === attribut ? wert : regel.value,
|
||||
}));
|
||||
}
|
||||
|
||||
export default async function ({ container }: any) {
|
||||
const query = container.resolve("query");
|
||||
const logger = container.resolve("logger");
|
||||
|
||||
const { data: providers } = await query.graph({
|
||||
entity: "fulfillment_provider",
|
||||
fields: ["id", "is_enabled"],
|
||||
});
|
||||
const dhl = (providers ?? []).find((p: any) => p.id.includes("dhl") && p.is_enabled);
|
||||
const manuell = (providers ?? []).find((p: any) => p.id === "manual_manual");
|
||||
|
||||
if (!manuell) {
|
||||
logger.error("Kein manueller Dienstleister gefunden — das sollte nicht vorkommen.");
|
||||
return;
|
||||
}
|
||||
if (!dhl) {
|
||||
logger.warn(
|
||||
"DHL-Provider ist nicht registriert (DHL_API_KEY / DHL_USERNAME / DHL_PASSWORD / " +
|
||||
"DHL_BILLING_NUMBER fehlen in der .env). Die DHL-Versandarten werden über den " +
|
||||
"manuellen Dienstleister angelegt: Preise und Auswahl stimmen, aber Medusa " +
|
||||
"erzeugt kein Versandlabel. Sobald die Zugangsdaten stehen, Server neu starten " +
|
||||
"und dieses Skript erneut ausführen — es meldet dann, welche Versandart auf den " +
|
||||
"DHL-Provider umgezogen werden muss."
|
||||
);
|
||||
}
|
||||
|
||||
const { data: zones } = await query.graph({ entity: "service_zone", fields: ["id", "name"] });
|
||||
const { data: profiles } = await query.graph({ entity: "shipping_profile", fields: ["id", "name"] });
|
||||
const zone = zones?.[0];
|
||||
const profile = profiles?.[0];
|
||||
if (!zone || !profile) {
|
||||
logger.error("Keine Service-Zone oder kein Versandprofil gefunden.");
|
||||
return;
|
||||
}
|
||||
logger.info(`Zone "${zone.name}", Profil "${profile.name}"`);
|
||||
|
||||
const { data: vorhanden } = await query.graph({ entity: "shipping_option", fields: OPTION_FIELDS });
|
||||
|
||||
for (const vorgabe of VORGABEN) {
|
||||
const providerId = vorgabe.brauchtDhl && dhl ? dhl.id : manuell.id;
|
||||
const bestehend = (vorhanden ?? []).find((o: any) => o.name === vorgabe.name);
|
||||
|
||||
if (bestehend) {
|
||||
if (bestehend.provider_id !== providerId) {
|
||||
logger.warn(
|
||||
` "${vorgabe.name}" liegt auf "${bestehend.provider_id}", gewünscht wäre ` +
|
||||
`"${providerId}". Der Dienstleister einer Versandart lässt sich nicht ändern — ` +
|
||||
"dafür die Versandart im Admin löschen und dieses Skript erneut ausführen."
|
||||
);
|
||||
}
|
||||
// Die Sichtbarkeit im Shop wird auch bei bestehenden Versandarten
|
||||
// nachgezogen, damit ein zweiter Lauf denselben Zustand herstellt.
|
||||
const regel = ladenRegel(bestehend, "enabled_in_store");
|
||||
const soll = String(vorgabe.imShop);
|
||||
if (regel && String(regel.value) !== soll) {
|
||||
await updateShippingOptionsWorkflow(container).run({
|
||||
input: [{ id: bestehend.id, rules: regelnMit(bestehend, "enabled_in_store", soll) }] as any,
|
||||
});
|
||||
logger.info(` "${vorgabe.name}": im Shop ${vorgabe.imShop ? "sichtbar" : "ausgeblendet"}.`);
|
||||
} else {
|
||||
logger.info(` "${vorgabe.name}" existiert bereits, unverändert.`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
await createShippingOptionsWorkflow(container).run({
|
||||
input: [
|
||||
{
|
||||
name: vorgabe.name,
|
||||
service_zone_id: zone.id,
|
||||
shipping_profile_id: profile.id,
|
||||
provider_id: providerId,
|
||||
price_type: "flat",
|
||||
type: { label: vorgabe.name, description: vorgabe.description, code: vorgabe.code },
|
||||
// Der DHL-Provider liest hieraus, welches Produkt gebucht wird.
|
||||
// Beim manuellen Dienstleister steht der Wert nur bereit.
|
||||
...(vorgabe.dhlProdukt ? { data: { dhl_product: vorgabe.dhlProdukt } } : {}),
|
||||
prices: [{ currency_code: "eur", amount: vorgabe.amount }],
|
||||
rules: [
|
||||
{ attribute: "enabled_in_store", operator: "eq", value: String(vorgabe.imShop) },
|
||||
{ attribute: "is_return", operator: "eq", value: "false" },
|
||||
],
|
||||
},
|
||||
] as any,
|
||||
});
|
||||
logger.info(
|
||||
` "${vorgabe.name}" angelegt (${providerId}, ${vorgabe.amount} EUR – Platzhalterpreis, ` +
|
||||
`${vorgabe.imShop ? "im Shop" : "nur intern"}).`
|
||||
);
|
||||
}
|
||||
|
||||
// Erst jetzt die alten ausblenden: vorher muss feststehen, dass der Shop
|
||||
// überhaupt noch eine Versandart anbieten kann.
|
||||
const { data: nachAnlage } = await query.graph({ entity: "shipping_option", fields: OPTION_FIELDS });
|
||||
const imShopDanach = (nachAnlage ?? []).filter((o: any) => {
|
||||
if (AUS_DEM_SHOP_NEHMEN.includes(o.name)) return false;
|
||||
const regel = ladenRegel(o, "enabled_in_store");
|
||||
return String(regel?.value) === "true";
|
||||
});
|
||||
|
||||
if (!imShopDanach.length) {
|
||||
logger.error(
|
||||
"Nach dem Ausblenden bliebe dem Webshop keine einzige Versandart. " +
|
||||
`"${AUS_DEM_SHOP_NEHMEN.join('", "')}" bleiben deshalb sichtbar.`
|
||||
);
|
||||
} else {
|
||||
for (const name of AUS_DEM_SHOP_NEHMEN) {
|
||||
const option = (nachAnlage ?? []).find((o: any) => o.name === name);
|
||||
if (!option) continue;
|
||||
const regel = ladenRegel(option, "enabled_in_store");
|
||||
if (!regel) {
|
||||
logger.warn(` "${name}" hat keine Regel enabled_in_store — übersprungen.`);
|
||||
continue;
|
||||
}
|
||||
if (String(regel.value) === "false") {
|
||||
logger.info(` "${name}" ist bereits aus dem Shop genommen.`);
|
||||
continue;
|
||||
}
|
||||
await updateShippingOptionsWorkflow(container).run({
|
||||
input: [{ id: option.id, rules: regelnMit(option, "enabled_in_store", "false") }] as any,
|
||||
});
|
||||
logger.info(` "${name}" aus dem Shop genommen, im Admin weiterhin wählbar.`);
|
||||
}
|
||||
}
|
||||
|
||||
// Die Schwelle für kostenfreien Versand gilt auch für die neuen
|
||||
// Versandarten — sonst verspricht der Shop etwas, das nur an den alten hing.
|
||||
const service: any = container.resolve(SUBSCRIPTION_MODULE);
|
||||
const settings = await service.getSettings();
|
||||
const ergebnis = await syncFreeShipping(container, settings.free_shipping_threshold);
|
||||
logger.info(
|
||||
settings.free_shipping_threshold
|
||||
? `Versandfrei ab ${settings.free_shipping_threshold} € auf ${ergebnis.geaendert} Versandart(en) nachgezogen.`
|
||||
: "Keine Schwelle für kostenfreien Versand eingestellt."
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Richtet die Bienenpatenschaft für den Bestellvorgang ein.
|
||||
*
|
||||
* npx medusa exec ./src/scripts/setup-sponsorship.ts
|
||||
*
|
||||
* Zwei Dinge:
|
||||
* 1. `metadata.sponsorship = true` — daran erkennt der Shop, dass er die
|
||||
* Angaben für Urkunde, Etikett und Beschenkten abfragen muss. Genauso
|
||||
* wie `metadata.subscription` beim Honig-Abo.
|
||||
* 2. Der Hinweis am Ende der Beschreibung verweist auf ein "Hinweisfeld
|
||||
* des Warenkorbes". Ein solches Feld gibt es in diesem Shop nicht —
|
||||
* die Angaben werden jetzt direkt am Produkt erfragt. Der Satz wird
|
||||
* deshalb entfernt, damit die Beschreibung nicht etwas verlangt, was
|
||||
* der Bestellvorgang schon erledigt.
|
||||
*
|
||||
* Wiederholbar: was schon stimmt, bleibt unangetastet.
|
||||
*/
|
||||
import { updateProductsWorkflow } from "@medusajs/core-flows";
|
||||
|
||||
/** Der Satz, der durch die eigenen Felder überflüssig geworden ist. */
|
||||
const ALTER_HINWEIS =
|
||||
"Wichtig: Wenn die Patenschaft verschenkt wird, Name und E-Mailadresse vom Beschenkten im Hinweisfeld des Warenkorbes eintragen.";
|
||||
|
||||
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", "description", "metadata", "categories.name"],
|
||||
});
|
||||
|
||||
const paten = (produkte ?? []).filter(
|
||||
(p: any) =>
|
||||
(p.categories ?? []).some((c: any) => c.name === "Bienenpatenschaften") ||
|
||||
p.metadata?.category === "Bienenpatenschaften"
|
||||
);
|
||||
|
||||
if (!paten.length) {
|
||||
logger.error('Kein Produkt in der Kategorie "Bienenpatenschaften" gefunden.');
|
||||
return;
|
||||
}
|
||||
|
||||
for (const p of paten) {
|
||||
const update: Record<string, any> = {};
|
||||
|
||||
if (!p.metadata?.sponsorship) {
|
||||
update.metadata = { ...(p.metadata ?? {}), sponsorship: true };
|
||||
}
|
||||
|
||||
const beschreibung = String(p.description ?? "");
|
||||
if (beschreibung.includes(ALTER_HINWEIS)) {
|
||||
update.description = beschreibung.replace(ALTER_HINWEIS, "").trimEnd();
|
||||
}
|
||||
|
||||
if (!Object.keys(update).length) {
|
||||
logger.info(` "${p.title}" ist bereits eingerichtet.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await updateProductsWorkflow(container).run({
|
||||
input: { selector: { id: p.id }, update } as any,
|
||||
});
|
||||
logger.info(
|
||||
` "${p.title}": ${[
|
||||
update.metadata ? "als Patenschaft markiert" : null,
|
||||
update.description ? "Hinweis auf das Warenkorb-Feld entfernt" : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(", ")}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Legt das Abo als normales Shop-Produkt an.
|
||||
*
|
||||
* npx medusa exec ./src/scripts/setup-subscription-product.ts
|
||||
*
|
||||
* Dadurch braucht es keine Sonderseite: Listung, Produktseite,
|
||||
* Variantenauswahl und Warenkorb sind die vorhandenen.
|
||||
*
|
||||
* Aufbau: Größe × Intervall sind echte Varianten (2 × 3 = 6). Die Sortenwahl
|
||||
* (Überraschung oder feste Sorte) läuft NICHT über Optionen — mit 12 Sorten
|
||||
* gäbe das 78 Varianten. Sie steht als Metadatum am Warenkorb-Posten.
|
||||
*
|
||||
* ⚠️ Die Preise sind PLATZHALTER. Im Sortiment kosten 250-g-Gläser zwischen
|
||||
* 4,80 und 9,90 EUR, 500-g-Gläser 7,90 bis 9,90 EUR — ein Abo mit
|
||||
* Zufallssorte braucht einen Mischpreis, den ihr festlegen müsst.
|
||||
*/
|
||||
import { createProductsWorkflow, createProductCategoriesWorkflow } from "@medusajs/core-flows";
|
||||
import { ProductStatus } from "@medusajs/framework/utils";
|
||||
|
||||
export const SUBSCRIPTION_PRODUCT_HANDLE = "honig-abo";
|
||||
export const SUBSCRIPTION_CATEGORY = "Abo";
|
||||
|
||||
const SIZES = [
|
||||
{ label: "250 Gramm", price: 6.9 },
|
||||
{ label: "500 Gramm", price: 10.9 },
|
||||
];
|
||||
const INTERVALS = [
|
||||
{ label: "Monatlich", key: "monthly" },
|
||||
{ label: "Alle 3 Monate", key: "quarterly" },
|
||||
{ label: "Alle 6 Monate", key: "biannual" },
|
||||
];
|
||||
|
||||
export default async function ({ container }: any) {
|
||||
const query = container.resolve("query");
|
||||
const logger = container.resolve("logger");
|
||||
|
||||
const { data: existing } = await query.graph({
|
||||
entity: "product",
|
||||
fields: ["id", "handle"],
|
||||
filters: { handle: SUBSCRIPTION_PRODUCT_HANDLE },
|
||||
});
|
||||
if (existing?.length) {
|
||||
logger.info(`Produkt "${SUBSCRIPTION_PRODUCT_HANDLE}" existiert bereits, nichts zu tun.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Eigene Kategorie, damit der Zufallsgenerator (der aus "Honig" zieht)
|
||||
// nicht versehentlich das Abo selbst auswählt.
|
||||
const { data: categories } = await query.graph({
|
||||
entity: "product_category",
|
||||
fields: ["id", "name"],
|
||||
});
|
||||
let category = categories?.find((c: any) => c.name === SUBSCRIPTION_CATEGORY);
|
||||
if (!category) {
|
||||
const { result } = await createProductCategoriesWorkflow(container).run({
|
||||
input: { product_categories: [{ name: SUBSCRIPTION_CATEGORY, is_active: true }] },
|
||||
});
|
||||
category = Array.isArray(result) ? result[0] : result;
|
||||
logger.info(`Kategorie "${SUBSCRIPTION_CATEGORY}" angelegt.`);
|
||||
}
|
||||
|
||||
const { data: profiles } = await query.graph({
|
||||
entity: "shipping_profile",
|
||||
fields: ["id"],
|
||||
});
|
||||
const { data: channels } = await query.graph({
|
||||
entity: "sales_channel",
|
||||
fields: ["id"],
|
||||
});
|
||||
|
||||
const variants = SIZES.flatMap((size) =>
|
||||
INTERVALS.map((interval) => ({
|
||||
title: `${size.label} / ${interval.label}`,
|
||||
sku: `ABO-${size.label.replace(/\D/g, "")}-${interval.key.toUpperCase()}`,
|
||||
// Ein Abo ist kein Lagerartikel — die Gläser werden erst bei der
|
||||
// Lieferung aus den echten Produkten gezogen. Ohne dieses Flag lehnt
|
||||
// Medusa das Hinzufügen ab, weil dem Verkaufskanal kein Lagerort für
|
||||
// die Variante zugeordnet ist.
|
||||
manage_inventory: false,
|
||||
options: { "Größe": size.label, "Intervall": interval.label },
|
||||
// Der Job liest hieraus, statt die deutschen Beschriftungen zu parsen.
|
||||
metadata: { subscription_interval: interval.key, subscription_size: size.label },
|
||||
prices: [{ amount: size.price, currency_code: "eur" }],
|
||||
}))
|
||||
);
|
||||
|
||||
await createProductsWorkflow(container).run({
|
||||
input: {
|
||||
products: [
|
||||
{
|
||||
title: "Honig-Abo",
|
||||
handle: SUBSCRIPTION_PRODUCT_HANDLE,
|
||||
status: ProductStatus.PUBLISHED,
|
||||
category_ids: [category.id],
|
||||
shipping_profile_id: profiles?.[0]?.id,
|
||||
sales_channels: channels?.map((c: any) => ({ id: c.id })),
|
||||
description:
|
||||
"Regelmäßig Honig aus Hamburg und der Region. Größe und Rhythmus wählen, " +
|
||||
"Sorte festlegen oder überraschen lassen. Jederzeit pausierbar und kündbar.",
|
||||
// Woran Storefront und Checkout erkennen, dass es ein Abo ist.
|
||||
metadata: { subscription: true },
|
||||
options: [
|
||||
{ title: "Größe", values: SIZES.map((s) => s.label) },
|
||||
{ title: "Intervall", values: INTERVALS.map((i) => i.label) },
|
||||
],
|
||||
variants,
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`Produkt "Honig-Abo" mit ${variants.length} Varianten angelegt (Kategorie "${SUBSCRIPTION_CATEGORY}").`
|
||||
);
|
||||
logger.warn("Die Preise sind Platzhalter — im Admin auf eure Kalkulation setzen.");
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||
import { PaymentEvents } from "@medusajs/framework/utils";
|
||||
import { bestellungZurZahlung, erfuelleBestellung } from "../lib/fulfill-order";
|
||||
|
||||
/**
|
||||
* Legt die Fulfillment automatisch an, sobald eine Zahlung bestätigt ist.
|
||||
*
|
||||
* Bewusst an `payment.captured` gehängt und nicht an `order.placed`: jedes
|
||||
* erzeugte Label kostet Porto, und unbezahlte oder abgebrochene Bestellungen
|
||||
* sollen keins auslösen. Die eigentliche Arbeit steht in
|
||||
* lib/fulfill-order.ts — Bestellungen, die ganz mit Gutschein bezahlt sind,
|
||||
* haben keine Zahlung und laufen über paid-by-voucher.ts.
|
||||
*
|
||||
* Der Subscriber ist absichtlich fehlertolerant — schlägt die Label-Erzeugung
|
||||
* fehl (Carrier-API down, Zugangsdaten falsch, Adresse unvollständig), wird
|
||||
* das protokolliert, aber die Zahlung nicht rückabgewickelt. Die Bestellung
|
||||
* lässt sich dann im Admin von Hand abwickeln.
|
||||
*/
|
||||
export default async function autoFulfillOnPayment({
|
||||
event,
|
||||
container,
|
||||
}: SubscriberArgs<{ id: string }>) {
|
||||
const logger = container.resolve("logger");
|
||||
const paymentId = event.data.id;
|
||||
|
||||
try {
|
||||
const orderId = await bestellungZurZahlung(container, paymentId);
|
||||
if (!orderId) return;
|
||||
await erfuelleBestellung(container, orderId);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[auto-fulfill] Label für Zahlung ${paymentId} fehlgeschlagen: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const config: SubscriberConfig = {
|
||||
event: PaymentEvents.CAPTURED,
|
||||
};
|
||||
@@ -0,0 +1,96 @@
|
||||
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 { geschenkAnkuendigung } from "../lib/order-emails";
|
||||
|
||||
/** 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
|
||||
* sie beim Beschenkten an.
|
||||
*
|
||||
* Hängt an `order.placed` und nicht am Zahlungseingang: das Geschenk läuft
|
||||
* über die normale Kasse, und dort gilt die Bestellung als Abschluss.
|
||||
*
|
||||
* Laufende Abos entstehen weiterhin über den Mollie-Webhook — dieser
|
||||
* Subscriber fasst nur Posten an, die als Geschenk gekennzeichnet sind.
|
||||
*/
|
||||
export default async function giftSubscription({
|
||||
event,
|
||||
container,
|
||||
}: SubscriberArgs<{ id: string }>) {
|
||||
const logger = container.resolve("logger");
|
||||
const query = container.resolve("query");
|
||||
const orderId = event.data.id;
|
||||
|
||||
try {
|
||||
const { data: orders } = await query.graph({
|
||||
entity: "order",
|
||||
fields: [
|
||||
"id",
|
||||
"display_id",
|
||||
"email",
|
||||
"customer_id",
|
||||
"region_id",
|
||||
"currency_code",
|
||||
"sales_channel_id",
|
||||
"shipping_address.*",
|
||||
"shipping_methods.shipping_option_id",
|
||||
...SUBSCRIPTION_CART_FIELDS.filter((f) => f.startsWith("items.")),
|
||||
],
|
||||
filters: { id: orderId },
|
||||
});
|
||||
|
||||
const order = orders?.[0];
|
||||
if (!order) return;
|
||||
|
||||
const angelegt = await createGiftSubscriptionsFromOrder({ container, order });
|
||||
if (!angelegt.length) return;
|
||||
|
||||
const notification: any = container.resolve(Modules.NOTIFICATION);
|
||||
const service: any = container.resolve(SUBSCRIPTION_MODULE);
|
||||
|
||||
for (const abo of angelegt) {
|
||||
// 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) {
|
||||
logger.error(
|
||||
`[geschenk] Bestellung ${orderId} konnte nicht in ein Abo überführt werden: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const config: SubscriberConfig = {
|
||||
event: "order.placed",
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||
import { PaymentEvents } from "@medusajs/framework/utils";
|
||||
import { bestellungZurZahlung } from "../lib/fulfill-order";
|
||||
import { gibGutscheineAus } from "../lib/gift-voucher";
|
||||
|
||||
/**
|
||||
* Gibt gekaufte Gutscheine aus, sobald die Zahlung eingegangen ist.
|
||||
*
|
||||
* Nicht an `order.placed`: bei Kauf auf Rechnung ist dann noch nichts
|
||||
* bezahlt, und ein verschickter Code lässt sich nicht zurückholen.
|
||||
*/
|
||||
export default async function giftVoucherOnPayment({
|
||||
event,
|
||||
container,
|
||||
}: SubscriberArgs<{ id: string }>) {
|
||||
const logger = container.resolve("logger");
|
||||
const paymentId = event.data.id;
|
||||
|
||||
try {
|
||||
const orderId = await bestellungZurZahlung(container, paymentId);
|
||||
if (!orderId) return;
|
||||
await gibGutscheineAus(container, orderId);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[gutschein] Ausgabe zu Zahlung ${paymentId} fehlgeschlagen: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const config: SubscriberConfig = {
|
||||
event: PaymentEvents.CAPTURED,
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import { bestellbestaetigung } from "../lib/order-emails";
|
||||
import { renderInvoicePdf } from "../lib/invoice-handler";
|
||||
import { eingeloesteGutscheine, gekuerzterCode } from "../lib/gift-voucher";
|
||||
|
||||
/**
|
||||
* Bestellbestätigung per E-Mail.
|
||||
*
|
||||
* § 312i Abs. 1 Nr. 3 BGB verlangt, den Eingang der Bestellung unverzüglich
|
||||
* zu bestätigen — deshalb an `order.placed` und nicht an die Zahlung: bei
|
||||
* Kauf auf Rechnung gibt es zum Bestellzeitpunkt noch keine.
|
||||
*
|
||||
* Fehlertolerant wie der Fulfillment-Subscriber: eine Bestellung darf nicht
|
||||
* daran scheitern, dass der Mailserver gerade nicht erreichbar ist.
|
||||
*/
|
||||
/**
|
||||
* Was der Kunde zu einer Bienenpatenschaft angegeben hat.
|
||||
*
|
||||
* Steht als Zeile unter dem Posten, damit der Name für Urkunde und Etikett
|
||||
* schwarz auf weiß in der Bestätigung steht.
|
||||
*/
|
||||
function patenschaftHinweis(metadata: any): string | null {
|
||||
const name = metadata?.sponsorship_name;
|
||||
if (!name) return null;
|
||||
const teile = [`Urkunde und Etikett auf: ${name}`];
|
||||
if (metadata.sponsorship_gift) {
|
||||
teile.push(`Geschenk an ${metadata.sponsorship_recipient_email ?? "—"}`);
|
||||
}
|
||||
return teile.join(" · ");
|
||||
}
|
||||
|
||||
/** Beim verschenkten Gutschein: an wen er geht, damit ein Tippfehler auffällt. */
|
||||
function gutscheinHinweis(metadata: any): string | null {
|
||||
if (metadata?.voucher_gift !== true || !metadata?.voucher_recipient_email) return null;
|
||||
return `Kommt per E-Mail an ${metadata.voucher_recipient_email}`;
|
||||
}
|
||||
|
||||
export default async function orderPlacedEmail({
|
||||
event,
|
||||
container,
|
||||
}: SubscriberArgs<{ id: string }>) {
|
||||
const logger = container.resolve("logger");
|
||||
const orderId = event.data.id;
|
||||
|
||||
try {
|
||||
const orderService: any = container.resolve(Modules.ORDER);
|
||||
const order = await orderService.retrieveOrder(orderId, {
|
||||
relations: ["items", "shipping_address", "shipping_methods"],
|
||||
});
|
||||
|
||||
// Der Abo-Job hängt die Abo-Kennung an den Warenkorb; sie wandert mit in
|
||||
// die Bestellung. Daran erkennt die Mail, dass niemand gerade bestellt hat.
|
||||
const ausAbo = Boolean((order.metadata as any)?.subscription_id);
|
||||
|
||||
if (!order?.email) {
|
||||
logger.warn(`[mail] Bestellung ${orderId} hat keine E-Mail-Adresse.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const inhalt = bestellbestaetigung({
|
||||
display_id: order.display_id,
|
||||
email: order.email,
|
||||
created_at: order.created_at,
|
||||
currency_code: order.currency_code,
|
||||
// Menge liegt auf `detail`, nicht am Posten selbst — dieselbe Stelle,
|
||||
// an der sich schon die Rechnung bedient.
|
||||
items: (order.items ?? []).map((item: any) => ({
|
||||
title: item.title,
|
||||
quantity: item.detail?.quantity ?? item.quantity ?? 1,
|
||||
unit_price: item.unit_price ?? 0,
|
||||
hinweis: patenschaftHinweis(item.metadata) ?? gutscheinHinweis(item.metadata),
|
||||
digital: item.requires_shipping === false,
|
||||
})),
|
||||
shipping_methods: (order.shipping_methods ?? []).map((m: any) => ({
|
||||
name: m.name,
|
||||
amount: m.amount ?? 0,
|
||||
})),
|
||||
shipping_address: order.shipping_address ?? null,
|
||||
aus_abo: ausAbo,
|
||||
gutscheine: (await eingeloesteGutscheine(container, order.id)).map((g) => ({
|
||||
code: gekuerzterCode(g.code),
|
||||
betrag: g.betrag,
|
||||
})),
|
||||
});
|
||||
|
||||
// Die Rechnung liegt bei. Scheitert sie, geht die Bestätigung trotzdem
|
||||
// raus: die Eingangsbestätigung ist die Pflicht, das PDF der Komfort —
|
||||
// und im Konto lässt es sich jederzeit erneut laden.
|
||||
let anhang: any[] = [];
|
||||
try {
|
||||
const pdf = await renderInvoicePdf(container, order.id);
|
||||
if (pdf) {
|
||||
anhang = [
|
||||
{
|
||||
filename: `rechnung-${order.display_id}.pdf`,
|
||||
content: pdf.toString("base64"),
|
||||
content_type: "application/pdf",
|
||||
},
|
||||
];
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[mail] Rechnung für ${order.display_id} nicht erzeugt: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
|
||||
const notification: any = container.resolve(Modules.NOTIFICATION);
|
||||
await notification.createNotifications({
|
||||
to: order.email,
|
||||
channel: "email",
|
||||
template: ausAbo ? "subscription-delivery" : "order-placed",
|
||||
content: inhalt,
|
||||
attachments: anhang,
|
||||
data: { order_id: order.id, display_id: order.display_id },
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`[mail] Bestellbestätigung ${order.display_id} an ${order.email}${
|
||||
anhang.length ? " mit Rechnung" : " ohne Rechnung"
|
||||
}.`
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[mail] Bestellbestätigung für ${orderId} fehlgeschlagen: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const config: SubscriberConfig = {
|
||||
event: "order.placed",
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||
import { erfuelleBestellung } from "../lib/fulfill-order";
|
||||
import { gibGutscheineAus } from "../lib/gift-voucher";
|
||||
|
||||
/**
|
||||
* Bestellungen, die vollständig mit Gutschein bezahlt sind.
|
||||
*
|
||||
* Deckt der Gutschein den ganzen Betrag, schließt Medusa den Warenkorb ohne
|
||||
* Zahlung ab — es gibt dann nie ein `payment.captured`, an dem sonst Versand
|
||||
* und Gutschein-Ausgabe hängen. Bezahlt ist trotzdem: das Guthaben wurde
|
||||
* beim Abschluss abgebucht. Deshalb hier dasselbe wie nach einer Zahlung.
|
||||
*
|
||||
* Erkannt wird das an eingelösten Gutscheinen ohne Payment-Collection.
|
||||
*/
|
||||
export default async function paidByVoucher({
|
||||
event,
|
||||
container,
|
||||
}: SubscriberArgs<{ id: string }>) {
|
||||
const logger = container.resolve("logger");
|
||||
const query = container.resolve("query");
|
||||
const orderId = event.data.id;
|
||||
|
||||
try {
|
||||
const { data: orders } = await query.graph({
|
||||
entity: "order",
|
||||
fields: ["id", "display_id", "credit_lines.reference", "payment_collections.id"],
|
||||
filters: { id: orderId },
|
||||
});
|
||||
const order = orders?.[0] as any;
|
||||
if (!order) return;
|
||||
|
||||
const mitGutschein = (order.credit_lines ?? []).some((zeile: any) => zeile?.reference === "gift-card");
|
||||
const ohneZahlung = !(order.payment_collections ?? []).length;
|
||||
if (!mitGutschein || !ohneZahlung) return;
|
||||
|
||||
logger.info(`[gutschein] Bestellung ${order.display_id} ist vollständig mit Gutschein bezahlt.`);
|
||||
await erfuelleBestellung(container, order.id);
|
||||
await gibGutscheineAus(container, order.id);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[gutschein] Abwicklung der Gutschein-Bestellung ${orderId} fehlgeschlagen: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const config: SubscriberConfig = {
|
||||
event: "order.placed",
|
||||
};
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import { versandnachricht, geschenkVersandnachricht } from "../lib/order-emails";
|
||||
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
||||
|
||||
/**
|
||||
* Versandnachricht mit Sendungsnummer.
|
||||
*
|
||||
* Hängt an `order.fulfillment_created`: in diesem Shop entsteht das Label
|
||||
* genau dort — der Fulfillment-Provider meldet die Sendung beim Carrier an
|
||||
* und gibt die Sendungsnummer als `labels[].tracking_number` zurück.
|
||||
*
|
||||
* Ohne Sendungsnummer wird nichts verschickt. Eine Mail "Ihr Paket ist
|
||||
* unterwegs" ohne Nummer wäre für die Kundin wertlos und erzeugt nur eine
|
||||
* Rückfrage.
|
||||
*/
|
||||
export default async function shipmentEmail({
|
||||
event,
|
||||
container,
|
||||
}: SubscriberArgs<{ order_id?: string; fulfillment_id?: string; id?: string }>) {
|
||||
const logger = container.resolve("logger");
|
||||
const query = container.resolve("query");
|
||||
const fulfillmentId = event.data.fulfillment_id ?? event.data.id;
|
||||
const orderId = event.data.order_id;
|
||||
|
||||
try {
|
||||
const { data: fulfillments } = await query.graph({
|
||||
entity: "fulfillment",
|
||||
fields: ["id", "labels.tracking_number", "labels.tracking_url"],
|
||||
filters: { id: fulfillmentId },
|
||||
});
|
||||
|
||||
const sendungen = (fulfillments?.[0]?.labels ?? [])
|
||||
.filter((label: any) => label?.tracking_number)
|
||||
.map((label: any) => ({
|
||||
tracking_number: label.tracking_number,
|
||||
tracking_url: label.tracking_url ?? null,
|
||||
}));
|
||||
|
||||
if (!sendungen.length) {
|
||||
logger.info(
|
||||
`[mail] Fulfillment ${fulfillmentId} hat keine Sendungsnummer — keine Versandnachricht.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!orderId) {
|
||||
logger.warn(`[mail] Fulfillment ${fulfillmentId} ohne Bestellbezug.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const orderService: any = container.resolve(Modules.ORDER);
|
||||
const order = await orderService.retrieveOrder(orderId, {
|
||||
relations: ["items", "shipping_address", "shipping_methods"],
|
||||
});
|
||||
|
||||
if (!order?.email) {
|
||||
logger.warn(`[mail] Bestellung ${orderId} hat keine E-Mail-Adresse.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const inhalt = versandnachricht(
|
||||
{
|
||||
display_id: order.display_id,
|
||||
email: order.email,
|
||||
created_at: order.created_at,
|
||||
currency_code: order.currency_code,
|
||||
items: (order.items ?? []).map((item: any) => ({
|
||||
title: item.title,
|
||||
quantity: item.detail?.quantity ?? item.quantity ?? 1,
|
||||
unit_price: item.unit_price ?? 0,
|
||||
})),
|
||||
shipping_methods: (order.shipping_methods ?? []).map((m: any) => ({
|
||||
name: m.name,
|
||||
amount: m.amount ?? 0,
|
||||
})),
|
||||
shipping_address: order.shipping_address ?? null,
|
||||
},
|
||||
sendungen
|
||||
);
|
||||
|
||||
const notification: any = container.resolve(Modules.NOTIFICATION);
|
||||
await notification.createNotifications({
|
||||
to: order.email,
|
||||
channel: "email",
|
||||
template: "shipment-created",
|
||||
content: inhalt,
|
||||
data: {
|
||||
order_id: order.id,
|
||||
display_id: order.display_id,
|
||||
tracking_numbers: sendungen.map((s) => s.tracking_number),
|
||||
},
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`[mail] Versandnachricht ${order.display_id} an ${order.email} (${sendungen
|
||||
.map((s) => s.tracking_number)
|
||||
.join(", ")}).`
|
||||
);
|
||||
|
||||
// Beim verschenkten Abo bekommt auch der Beschenkte Bescheid — mit
|
||||
// Sendungsnummer, aber ohne Beträge: bezahlt hat jemand anderes.
|
||||
const aboId = (order.metadata as any)?.subscription_id;
|
||||
if (!aboId) return;
|
||||
|
||||
const service: any = container.resolve(SUBSCRIPTION_MODULE);
|
||||
const [abo] = await service.listSubscriptions({ id: aboId });
|
||||
if (!abo?.gift_recipient_email) return;
|
||||
|
||||
const geschenkInhalt = geschenkVersandnachricht(
|
||||
abo.gift_recipient_name ?? "",
|
||||
(order.items ?? []).map((item: any) => ({
|
||||
title: item.title,
|
||||
quantity: item.detail?.quantity ?? item.quantity ?? 1,
|
||||
unit_price: 0,
|
||||
})),
|
||||
sendungen,
|
||||
abo.remaining_deliveries ?? 0
|
||||
);
|
||||
|
||||
await notification.createNotifications({
|
||||
to: abo.gift_recipient_email,
|
||||
channel: "email",
|
||||
template: "gift-shipment",
|
||||
content: geschenkInhalt,
|
||||
data: { subscription_id: abo.id, order_id: order.id },
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`[mail] Geschenk-Versandnachricht ${order.display_id} an ${abo.gift_recipient_email}.`
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[mail] Versandnachricht für Fulfillment ${fulfillmentId} fehlgeschlagen: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const config: SubscriberConfig = {
|
||||
event: "order.fulfillment_created",
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||
import { Modules } from "@medusajs/framework/utils";
|
||||
import { patenschaftAnkuendigung } from "../lib/order-emails";
|
||||
|
||||
/**
|
||||
* Kündigt eine verschenkte Bienenpatenschaft beim Beschenkten an.
|
||||
*
|
||||
* Ohne sie erführe er bis zur Ernte im Herbst nichts von seinem Geschenk.
|
||||
* Die Mail nennt keine Beträge — bezahlt hat jemand anderes.
|
||||
*
|
||||
* 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({
|
||||
event,
|
||||
container,
|
||||
}: SubscriberArgs<{ id: string }>) {
|
||||
const logger = container.resolve("logger");
|
||||
const query = container.resolve("query");
|
||||
const orderId = event.data.id;
|
||||
|
||||
try {
|
||||
const { data: orders } = await 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) => 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) {
|
||||
logger.error(
|
||||
`[patenschaft] Ankündigung für ${orderId} fehlgeschlagen: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const config: SubscriberConfig = {
|
||||
event: "order.placed",
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { listShippingOptionsForCartWorkflow } from "@medusajs/core-flows";
|
||||
import { StepResponse } from "@medusajs/framework/workflows-sdk";
|
||||
import { warenwertFuerVersand } from "../../lib/free-shipping";
|
||||
|
||||
/**
|
||||
* Versandpreise mit dem Warenwert ohne Gutscheine berechnen.
|
||||
*
|
||||
* Die Schwelle für kostenfreien Versand hängt als Bedingung auf `item_total`
|
||||
* am Versandpreis (lib/free-shipping.ts). Hier wird dieser Wert beim
|
||||
* Auflisten der Versandarten durch den Warenwert ohne Gutscheine ersetzt,
|
||||
* damit der Shop den Preis zeigt, der auch berechnet wird.
|
||||
*/
|
||||
listShippingOptionsForCartWorkflow.hooks.setPricingContext(async ({ cart }, { container }) => {
|
||||
const warenwert = await warenwertFuerVersand(container, (cart as any).id);
|
||||
return new StepResponse({ item_total: warenwert });
|
||||
});
|
||||
|
After Width: | Height: | Size: 3.0 MiB |
|
After Width: | Height: | Size: 2.3 MiB |
|
After Width: | Height: | Size: 3.0 MiB |
|
After Width: | Height: | Size: 2.3 MiB |
|
After Width: | Height: | Size: 3.0 MiB |
|
After Width: | Height: | Size: 3.0 MiB |
|
After Width: | Height: | Size: 3.0 MiB |
|
After Width: | Height: | Size: 2.2 MiB |
|
After Width: | Height: | Size: 3.0 MiB |
|
After Width: | Height: | Size: 2.3 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 2.2 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 2.2 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 6.2 MiB |
|
After Width: | Height: | Size: 2.9 MiB |