diff --git a/prisma/migrations/20261020190000_stock_alerts/migration.sql b/prisma/migrations/20261020190000_stock_alerts/migration.sql
new file mode 100644
index 0000000..dc4605b
--- /dev/null
+++ b/prisma/migrations/20261020190000_stock_alerts/migration.sql
@@ -0,0 +1,24 @@
+-- CreateTable
+CREATE TABLE "StockAlert" (
+ "id" TEXT NOT NULL,
+ "productId" TEXT NOT NULL,
+ "variantId" TEXT,
+ "email" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "notifiedAt" TIMESTAMP(3),
+
+ CONSTRAINT "StockAlert_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "StockAlert_productId_notifiedAt_idx" ON "StockAlert"("productId", "notifiedAt");
+
+-- CreateIndex
+CREATE INDEX "StockAlert_email_idx" ON "StockAlert"("email");
+
+-- AddForeignKey
+ALTER TABLE "StockAlert" ADD CONSTRAINT "StockAlert_productId_fkey" FOREIGN KEY ("productId") REFERENCES "Product"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "StockAlert" ADD CONSTRAINT "StockAlert_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "ProductVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index b70809d..0167566 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -125,20 +125,38 @@ model Product {
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
variants ProductVariant[]
orderItems OrderItem[]
+ stockAlerts StockAlert[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model ProductVariant {
- id String @id @default(cuid())
+ id String @id @default(cuid())
productId String
- product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
+ product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
name String // z. B. "183 cm" oder "Anthrazit"
- sku String @default("")
+ sku String @default("")
// Preis in Cent; leer = Produktpreis
price Int?
- stock Int @default(0)
- sort Int @default(0)
+ stock Int @default(0)
+ sort Int @default(0)
+ alerts StockAlert[]
+}
+
+// „Erinnere mich, wenn wieder da“: Kunde trägt sich bei einem ausverkauften Produkt (oder einer Variante) ein
+model StockAlert {
+ id String @id @default(cuid())
+ productId String
+ product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
+ variantId String?
+ variant ProductVariant? @relation(fields: [variantId], references: [id], onDelete: Cascade)
+ email String
+ createdAt DateTime @default(now())
+ // Gesetzt, sobald die Mail „wieder da“ verschickt wurde
+ notifiedAt DateTime?
+
+ @@index([productId, notifiedAt])
+ @@index([email])
}
// ---------- Bestellungen ----------
diff --git a/src/app/(shop)/actions.ts b/src/app/(shop)/actions.ts
index c4b76db..96605b8 100644
--- a/src/app/(shop)/actions.ts
+++ b/src/app/(shop)/actions.ts
@@ -7,6 +7,7 @@ import { db } from "@/lib/db";
import { readCartCookie, writeCartCookie } from "@/lib/cart";
import { findCoupon } from "@/lib/pricing";
import { subscribe } from "@/lib/newsletter";
+import { addStockAlert } from "@/lib/stock-alerts";
export async function subscribeNewsletter(_prev: unknown, formData: FormData) {
const email = z.email().safeParse(String(formData.get("email") ?? "").trim().toLowerCase());
@@ -15,6 +16,15 @@ export async function subscribeNewsletter(_prev: unknown, formData: FormData) {
return { ok: true, error: null, pending: state === "pending" };
}
+export async function subscribeStockAlert(_prev: unknown, formData: FormData) {
+ const email = z.email().safeParse(String(formData.get("email") ?? "").trim().toLowerCase());
+ if (!email.success) return { ok: false, error: "Bitte gib eine gültige E-Mail-Adresse ein." };
+ // Verstecktes Feld: von Menschen nie ausgefüllt, von Bots oft
+ if (String(formData.get("website") ?? "")) return { ok: true, error: null };
+ const r = await addStockAlert(String(formData.get("productId") ?? ""), String(formData.get("variantId") ?? "") || null, email.data);
+ return r.ok ? { ok: true, error: null } : { ok: false, error: r.error };
+}
+
export async function addToCart(formData: FormData) {
const productId = String(formData.get("productId") ?? "");
const variantId = String(formData.get("variantId") ?? "") || null;
diff --git a/src/app/(shop)/produkt/[slug]/page.tsx b/src/app/(shop)/produkt/[slug]/page.tsx
index e1064a4..8188738 100644
--- a/src/app/(shop)/produkt/[slug]/page.tsx
+++ b/src/app/(shop)/produkt/[slug]/page.tsx
@@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
import Link from "next/link";
import { db } from "@/lib/db";
import { getSettings } from "@/lib/settings";
+import { getCurrentUser } from "@/lib/auth";
import { withSale, withSales } from "@/lib/sales";
import { Icon } from "@/components/Icon";
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
@@ -29,8 +30,9 @@ export default async function ProductPage({
});
if (!raw || !raw.active) notFound();
const product = await withSale(raw);
- const [settings, related] = await Promise.all([
+ const [settings, user, related] = await Promise.all([
getSettings(),
+ getCurrentUser(),
db.product.findMany({
where: { active: true, id: { not: product.id }, ...(product.categoryId ? { categoryId: product.categoryId } : {}) },
include: { variants: true },
@@ -66,6 +68,7 @@ export default async function ProductPage({
saleEndsAt={product.sale?.endsAt?.toISOString() ?? null}
variantLabel="Variante"
missingVariant={variante === "fehlt"}
+ userEmail={user?.email}
/>
{shippingNote && - {shippingNote.title}
}
diff --git a/src/app/admin/(panel)/emails/page.tsx b/src/app/admin/(panel)/emails/page.tsx
index 517a0e2..32e1130 100644
--- a/src/app/admin/(panel)/emails/page.tsx
+++ b/src/app/admin/(panel)/emails/page.tsx
@@ -6,7 +6,7 @@ import { MAIL_TEMPLATES, getTemplateDef } from "@/lib/mail/templates";
import { getMailConfig, isMailReady } from "@/lib/mail/config";
import { Card, Empty, PageHead, Pill } from "@/components/admin/ui";
-const GROUPS = ["Bestellung", "Konto", "Newsletter", "Team"] as const;
+const GROUPS = ["Bestellung", "Produkt", "Konto", "Newsletter", "Team"] as const;
export default async function EmailsPage({ searchParams }: { searchParams: Promise<{ tab?: string }> }) {
await requireAdmin("emails.edit");
diff --git a/src/app/admin/(panel)/erinnerungen/page.tsx b/src/app/admin/(panel)/erinnerungen/page.tsx
new file mode 100644
index 0000000..6301921
--- /dev/null
+++ b/src/app/admin/(panel)/erinnerungen/page.tsx
@@ -0,0 +1,65 @@
+import Link from "next/link";
+import { db } from "@/lib/db";
+import { requireAdmin } from "@/lib/auth";
+import { dateFmt } from "@/lib/status";
+import { Card, Empty, PageHead, Pill } from "@/components/admin/ui";
+
+export default async function StockAlertsPage() {
+ await requireAdmin("products.view");
+ const [pending, notified30, notifiedTotal] = await Promise.all([
+ db.stockAlert.findMany({
+ where: { notifiedAt: null },
+ include: { product: { select: { id: true, name: true, stock: true, trackStock: true, variants: { select: { id: true, stock: true } } } }, variant: { select: { id: true, name: true, stock: true } } },
+ orderBy: { createdAt: "asc" },
+ }),
+ db.stockAlert.count({ where: { notifiedAt: { gte: new Date(Date.now() - 30 * 86400_000) } } }),
+ db.stockAlert.count({ where: { notifiedAt: { not: null } } }),
+ ]);
+ // Nach Produkt und Variante zusammenfassen
+ const groups = new Map();
+ for (const a of pending) {
+ const key = `${a.productId}:${a.variantId ?? ""}`;
+ const stock = !a.product.trackStock ? Infinity : a.variant ? a.variant.stock : a.product.variants.length ? a.product.variants.reduce((n, v) => n + Math.max(0, v.stock), 0) : a.product.stock;
+ const g = groups.get(key) ?? { productId: a.productId, name: a.product.name, variant: a.variant?.name ?? "", stock, count: 0, first: a.createdAt, last: a.createdAt };
+ g.count++;
+ g.last = a.createdAt;
+ groups.set(key, g);
+ }
+ const rows = [...groups.values()].sort((a, b) => b.count - a.count);
+ return (
+
+
+ Mail bearbeiten
+
+
+ {rows.length === 0 ? (
+
+ ) : (
+
+
+ | Produkt | Wartende | Bestand | Erster Wunsch | Letzter Wunsch |
+
+ {rows.map((r) => (
+
+ |
+ {r.name}
+ {r.variant && Variante: {r.variant} }
+ |
+ {r.count} |
+ {r.stock > 0 ? {Number.isFinite(r.stock) ? `${r.stock} auf Lager, Mails gehen raus` : "Ohne Bestandsführung"} : Ausverkauft} |
+ {dateFmt.format(r.first)} |
+ {dateFmt.format(r.last)} |
+
+ ))}
+
+
+
+ )}
+
+
Jeder bekommt nur eine Mail. Danach wird die Adresse gelöscht. Ist der Mail-Versand aus, warten die Einträge, bis er wieder läuft.
+
+ );
+}
diff --git a/src/app/admin/(panel)/produkte/[id]/page.tsx b/src/app/admin/(panel)/produkte/[id]/page.tsx
index 0a014f3..9d1ef54 100644
--- a/src/app/admin/(panel)/produkte/[id]/page.tsx
+++ b/src/app/admin/(panel)/produkte/[id]/page.tsx
@@ -18,6 +18,7 @@ export default async function EditProduct({ params, searchParams }: { params: Pr
]);
if (!p) notFound();
const sale = bestSale(await getRunningSales(), p);
+ const waiting = await db.stockAlert.count({ where: { productId: p.id, notifiedAt: null } });
return (
@@ -36,6 +37,13 @@ export default async function EditProduct({ params, searchParams }: { params: Pr
)}
+ {waiting > 0 && (
+
+
+ Sobald du den Bestand erhöhst und speicherst, bekommen sie automatisch eine Mail. Alle Wieder-da-Wünsche
+
+
+ )}
notifyBackInStock(id));
revalidatePath("/", "layout");
if (!id) redirect(`/admin/produkte/${productId}?neu=1`);
return ok();
diff --git a/src/components/admin/nav.ts b/src/components/admin/nav.ts
index ca09dd5..9d0c21c 100644
--- a/src/components/admin/nav.ts
+++ b/src/components/admin/nav.ts
@@ -26,6 +26,7 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
items: [
{ href: "/admin/produkte", label: "Produkte", icon: "box", permission: "products.view", badge: "lowStock" },
{ href: "/admin/kategorien", label: "Kategorien", icon: "folder", permission: "categories.edit" },
+ { href: "/admin/erinnerungen", label: "Wieder-da-Wünsche", icon: "heart", permission: "products.view" },
],
},
{
diff --git a/src/components/shop/BuyBox.tsx b/src/components/shop/BuyBox.tsx
index 6ebfae1..f3e0136 100644
--- a/src/components/shop/BuyBox.tsx
+++ b/src/components/shop/BuyBox.tsx
@@ -3,6 +3,7 @@ import { useState } from "react";
import { useFormStatus } from "react-dom";
import { addToCart } from "@/app/(shop)/actions";
import { Icon } from "../Icon";
+import { StockAlertForm } from "./StockAlertForm";
type Variant = { id: string; name: string; price: number; compareAt?: number | null; stock: number };
@@ -27,6 +28,7 @@ export function BuyBox(props: {
variantLabel: string;
missingVariant: boolean;
saleEndsAt?: string | null;
+ userEmail?: string;
}) {
const firstAvailable = props.variants.find((v) => !props.trackStock || v.stock > 0);
const [variantId, setVariantId] = useState(props.variants.length === 1 ? (firstAvailable?.id ?? null) : null);
@@ -35,12 +37,16 @@ export function BuyBox(props: {
const price = variant?.price ?? props.price;
const stock = props.trackStock ? (variant ? variant.stock : props.variants.length ? Infinity : props.stock) : 99;
const soldOut = props.variants.length ? props.trackStock && props.variants.every((v) => v.stock <= 0) : stock <= 0;
+ // Ausverkaufte Variante gewählt: statt Warenkorb die Erinnerung anbieten
+ const variantSoldOut = Boolean(variant && props.trackStock && variant.stock <= 0);
+ const showAlert = soldOut || variantSoldOut;
const max = Math.min(Number.isFinite(stock) ? stock : 99, 99);
const needsVariant = props.variants.length > 0 && !variant;
const compareBase = variant ? (variant.compareAt ?? props.compareAt) : props.compareAt;
const compare = compareBase && compareBase > price ? compareBase : null;
return (
+ <>
+ {showAlert && }
+ >
);
}
diff --git a/src/components/shop/StockAlertForm.tsx b/src/components/shop/StockAlertForm.tsx
new file mode 100644
index 0000000..9e1ebfd
--- /dev/null
+++ b/src/components/shop/StockAlertForm.tsx
@@ -0,0 +1,31 @@
+"use client";
+import { useActionState } from "react";
+import { subscribeStockAlert } from "@/app/(shop)/actions";
+import { Icon } from "../Icon";
+
+/** „Erinnere mich, wenn wieder da“ bei ausverkauften Produkten oder Varianten. */
+export function StockAlertForm({ productId, variantId, variantName, email }: { productId: string; variantId: string | null; variantName?: string; email?: string }) {
+ const [state, action, pending] = useActionState(subscribeStockAlert, null);
+ if (state?.ok) {
+ return (
+
+ Wir sagen dir Bescheid, sobald {variantName ? `„${variantName}“` : "es"} wieder da ist. Einmal, per E-Mail.
+
+ );
+ }
+ return (
+
+ );
+}
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index 82ec87d..cf57bb2 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -1,8 +1,10 @@
-// Läuft einmal beim Start des Servers: Takt für den Newsletter-Versand.
+// Läuft einmal beim Start des Servers: Takt für Newsletter-Versand und Wieder-da-Erinnerungen.
// Die Abfrage muss so geschrieben sein, damit der Edge-Build den Node-Teil weglässt.
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
const { startNewsletterTimer } = await import("./lib/campaign-sender");
startNewsletterTimer();
+ const { startStockAlertTimer } = await import("./lib/stock-alerts");
+ startStockAlertTimer();
}
}
diff --git a/src/lib/customer-delete.ts b/src/lib/customer-delete.ts
index 5d689a1..9b4606f 100644
--- a/src/lib/customer-delete.ts
+++ b/src/lib/customer-delete.ts
@@ -19,6 +19,7 @@ export async function deleteCustomerAccount(id: string) {
// Mails ohne Bestellbezug (z. B. Passwort vergessen) sind nicht aufbewahrungspflichtig
await db.emailLog.deleteMany({ where: { to: user.email, orderId: null } });
await db.newsletterRecipient.deleteMany({ where: { email: user.email } });
+ await db.stockAlert.deleteMany({ where: { email: user.email } });
// Sitzungen, Social-Logins, Reset-Links und Adressen hängen per Cascade am Konto
await db.user.delete({ where: { id } });
return { email: user.email };
diff --git a/src/lib/mail/templates.ts b/src/lib/mail/templates.ts
index e24fe98..1acd84f 100644
--- a/src/lib/mail/templates.ts
+++ b/src/lib/mail/templates.ts
@@ -8,7 +8,7 @@ export type MailTemplateDef = {
name: string;
description: string;
recipient: "customer" | "team";
- group: "Bestellung" | "Konto" | "Newsletter" | "Team";
+ group: "Bestellung" | "Produkt" | "Konto" | "Newsletter" | "Team";
placeholders: Placeholder[];
subject: string;
body: string;
@@ -161,6 +161,32 @@ dein {{shop_name}}-Team`,
{{artikel}}
[Im Admin öffnen]({{admin_link}})`,
+ },
+ {
+ key: "back_in_stock",
+ name: "Wieder erhältlich",
+ description: "Wenn ein ausverkauftes Produkt wieder lieferbar ist, an alle, die sich auf der Produktseite dafür eingetragen haben.",
+ recipient: "customer",
+ group: "Produkt",
+ placeholders: [
+ { key: "produkt", label: "Name des Produkts", sample: "Reformer Matte Pro" },
+ { key: "variante", label: "Variante (leer, wenn keine gewählt war)", sample: "183 cm" },
+ { key: "variante_hinweis", label: "Satz zur Variante, z. B. „Gewählte Variante: 183 cm“ (entfällt ohne Variante)", sample: "Gewählte Variante: 183 cm" },
+ { key: "produkt_link", label: "Link zum Produkt", sample: "https://sanamare.de/produkt/reformer-matte-pro" },
+ ],
+ subject: "{{produkt}} ist wieder da",
+ body: `Hallo,
+
+gute Nachricht: **{{produkt}}** ist wieder erhältlich. Du hattest uns gebeten, dir Bescheid zu geben.
+
+{{variante_hinweis}}
+
+[Jetzt ansehen]({{produkt_link}})
+
+Der Bestand ist oft schnell wieder weg. Diese Erinnerung schicken wir nur einmal, deine Adresse haben wir danach wieder gelöscht.
+
+Herzliche Grüße
+dein {{shop_name}}-Team`,
},
{
key: "welcome",
diff --git a/src/lib/stock-alerts.ts b/src/lib/stock-alerts.ts
new file mode 100644
index 0000000..5b27765
--- /dev/null
+++ b/src/lib/stock-alerts.ts
@@ -0,0 +1,77 @@
+import "server-only";
+import { db } from "./db";
+import { appUrl } from "./social/config";
+import { sendTemplate } from "./mail/send";
+
+const MAX_PER_EMAIL = 30;
+
+/** Kunde möchte benachrichtigt werden. Doppelte Einträge für dasselbe Produkt werden ignoriert. */
+export async function addStockAlert(productId: string, variantId: string | null, email: string) {
+ const product = await db.product.findFirst({ where: { id: productId, active: true }, include: { variants: true } });
+ if (!product) return { ok: false as const, error: "Produkt nicht gefunden." };
+ if (variantId && !product.variants.some((v) => v.id === variantId)) return { ok: false as const, error: "Variante nicht gefunden." };
+ const existing = await db.stockAlert.findFirst({ where: { productId, variantId, email, notifiedAt: null } });
+ if (!existing) {
+ // Schutz vor Missbrauch: nicht beliebig viele Einträge für eine Adresse
+ if ((await db.stockAlert.count({ where: { email, notifiedAt: null } })) >= MAX_PER_EMAIL) return { ok: false as const, error: "Du hast schon sehr viele Erinnerungen eingetragen." };
+ await db.stockAlert.create({ data: { productId, variantId, email } });
+ }
+ return { ok: true as const };
+}
+
+type ProductWithVariants = { trackStock: boolean; stock: number; active: boolean; variants: { id: string; stock: number }[] };
+
+function available(p: ProductWithVariants, variantId: string | null) {
+ if (!p.active) return false;
+ if (!p.trackStock) return true;
+ if (variantId) return (p.variants.find((v) => v.id === variantId)?.stock ?? 0) > 0;
+ return p.variants.length ? p.variants.some((v) => v.stock > 0) : p.stock > 0;
+}
+
+/**
+ * Verschickt „wieder da“ an alle wartenden Kunden, deren Produkt (oder Variante) wieder lieferbar ist.
+ * Ohne productId werden alle wartenden Einträge geprüft (läuft jede Minute mit, z. B. nach Stornos).
+ * Nach dem Versand wird die Adresse gelöscht, sie wird für nichts anderes gebraucht.
+ */
+export async function notifyBackInStock(productId?: string) {
+ const alerts = await db.stockAlert.findMany({
+ where: { notifiedAt: null, ...(productId ? { productId } : {}) },
+ include: { product: { include: { variants: { select: { id: true, stock: true, name: true } } } }, variant: { select: { name: true } } },
+ take: 200,
+ orderBy: { createdAt: "asc" },
+ });
+ let sent = 0;
+ for (const a of alerts) {
+ if (!available(a.product, a.variantId)) continue;
+ const r = await sendTemplate({
+ key: "back_in_stock",
+ to: a.email,
+ vars: { produkt: a.product.name, variante: a.variant?.name ?? "", variante_hinweis: a.variant ? `Gewählte Variante: ${a.variant.name}` : "", produkt_link: `${appUrl()}/produkt/${a.product.slug}` },
+ });
+ // Ausgeschaltete Vorlage oder fehlender Mailserver: Eintrag bleibt und wird später erneut versucht
+ if (r.ok) {
+ await db.stockAlert.update({ where: { id: a.id }, data: { notifiedAt: new Date(), email: "" } });
+ sent++;
+ }
+ }
+ return sent;
+}
+
+const timer = globalThis as unknown as { stockAlertTimer?: NodeJS.Timeout; stockAlertBusy?: boolean };
+
+/** Prüft jede Minute, ob Wartende benachrichtigt werden können (fängt auch Stornos und andere Bestandsänderungen ab). */
+export function startStockAlertTimer() {
+ if (timer.stockAlertTimer) return;
+ timer.stockAlertTimer = setInterval(async () => {
+ if (timer.stockAlertBusy) return;
+ timer.stockAlertBusy = true;
+ try {
+ if (await db.stockAlert.count({ where: { notifiedAt: null } })) await notifyBackInStock();
+ } catch (e) {
+ console.error("Wieder-da-Erinnerungen fehlgeschlagen", e);
+ } finally {
+ timer.stockAlertBusy = false;
+ }
+ }, 60_000);
+ timer.stockAlertTimer.unref?.();
+}
diff --git a/src/styles/shop.css b/src/styles/shop.css
index de4cee1..5a41e7f 100644
--- a/src/styles/shop.css
+++ b/src/styles/shop.css
@@ -245,3 +245,13 @@ button.sm-pdp__main { display: block; width: 100%; padding: 0; border: 0; cursor
.sm-invoices { list-style: none; margin: var(--space-3) 0 0; padding: 0; display: grid; gap: var(--space-3); }
.sm-invoices li { display: flex; justify-content: space-between; gap: var(--space-4); flex-wrap: wrap; align-items: baseline; }
.sm-invoices small { color: var(--ink-subtle); }
+
+/* Erinnerung bei ausverkauften Produkten */
+.sm-pdp__sizes label.sm-pdp__size.is-soldout { color: var(--ink-subtle); border-color: var(--line); text-decoration: line-through; background: var(--surface); }
+.sm-pdp__sizes input:checked + label.sm-pdp__size.is-soldout { border: 2px solid var(--ink-muted); color: var(--ink-muted); }
+.sm-stockalert { margin: var(--space-4) 0 var(--space-2); padding: var(--space-4) var(--space-5); background: var(--surface); border-left: 2px solid var(--gold); border-radius: var(--radius-sm); }
+.sm-stockalert__title { display: flex; gap: var(--space-2); align-items: center; margin: 0 0 var(--space-3); font-weight: 500; }
+.sm-stockalert .sm-input-group .sm-input { min-width: 0; }
+.sm-stockalert__note { margin: var(--space-2) 0 0; color: var(--ink-muted); }
+.sm-stockalert--done { display: flex; gap: var(--space-2); align-items: flex-start; color: var(--ink); }
+.sm-stockalert--done svg { color: var(--success); flex: none; margin-top: 3px; }