Erinnerung bei ausverkauften Produkten: Eintragen auf der Produktseite, automatische Mail bei Wiederauffüllung, Übersicht im Admin
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
This commit is contained in:
parent
dc45fae81b
commit
451160ab71
16 changed files with 304 additions and 14 deletions
24
prisma/migrations/20261020190000_stock_alerts/migration.sql
Normal file
24
prisma/migrations/20261020190000_stock_alerts/migration.sql
Normal file
|
|
@ -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;
|
||||||
|
|
||||||
|
|
@ -125,20 +125,38 @@ model Product {
|
||||||
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||||
variants ProductVariant[]
|
variants ProductVariant[]
|
||||||
orderItems OrderItem[]
|
orderItems OrderItem[]
|
||||||
|
stockAlerts StockAlert[]
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
}
|
}
|
||||||
|
|
||||||
model ProductVariant {
|
model ProductVariant {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
productId String
|
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"
|
name String // z. B. "183 cm" oder "Anthrazit"
|
||||||
sku String @default("")
|
sku String @default("")
|
||||||
// Preis in Cent; leer = Produktpreis
|
// Preis in Cent; leer = Produktpreis
|
||||||
price Int?
|
price Int?
|
||||||
stock Int @default(0)
|
stock Int @default(0)
|
||||||
sort 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 ----------
|
// ---------- Bestellungen ----------
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import { db } from "@/lib/db";
|
||||||
import { readCartCookie, writeCartCookie } from "@/lib/cart";
|
import { readCartCookie, writeCartCookie } from "@/lib/cart";
|
||||||
import { findCoupon } from "@/lib/pricing";
|
import { findCoupon } from "@/lib/pricing";
|
||||||
import { subscribe } from "@/lib/newsletter";
|
import { subscribe } from "@/lib/newsletter";
|
||||||
|
import { addStockAlert } from "@/lib/stock-alerts";
|
||||||
|
|
||||||
export async function subscribeNewsletter(_prev: unknown, formData: FormData) {
|
export async function subscribeNewsletter(_prev: unknown, formData: FormData) {
|
||||||
const email = z.email().safeParse(String(formData.get("email") ?? "").trim().toLowerCase());
|
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" };
|
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) {
|
export async function addToCart(formData: FormData) {
|
||||||
const productId = String(formData.get("productId") ?? "");
|
const productId = String(formData.get("productId") ?? "");
|
||||||
const variantId = String(formData.get("variantId") ?? "") || null;
|
const variantId = String(formData.get("variantId") ?? "") || null;
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import { getCurrentUser } from "@/lib/auth";
|
||||||
import { withSale, withSales } from "@/lib/sales";
|
import { withSale, withSales } from "@/lib/sales";
|
||||||
import { Icon } from "@/components/Icon";
|
import { Icon } from "@/components/Icon";
|
||||||
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
|
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
|
||||||
|
|
@ -29,8 +30,9 @@ export default async function ProductPage({
|
||||||
});
|
});
|
||||||
if (!raw || !raw.active) notFound();
|
if (!raw || !raw.active) notFound();
|
||||||
const product = await withSale(raw);
|
const product = await withSale(raw);
|
||||||
const [settings, related] = await Promise.all([
|
const [settings, user, related] = await Promise.all([
|
||||||
getSettings(),
|
getSettings(),
|
||||||
|
getCurrentUser(),
|
||||||
db.product.findMany({
|
db.product.findMany({
|
||||||
where: { active: true, id: { not: product.id }, ...(product.categoryId ? { categoryId: product.categoryId } : {}) },
|
where: { active: true, id: { not: product.id }, ...(product.categoryId ? { categoryId: product.categoryId } : {}) },
|
||||||
include: { variants: true },
|
include: { variants: true },
|
||||||
|
|
@ -66,6 +68,7 @@ export default async function ProductPage({
|
||||||
saleEndsAt={product.sale?.endsAt?.toISOString() ?? null}
|
saleEndsAt={product.sale?.endsAt?.toISOString() ?? null}
|
||||||
variantLabel="Variante"
|
variantLabel="Variante"
|
||||||
missingVariant={variante === "fehlt"}
|
missingVariant={variante === "fehlt"}
|
||||||
|
userEmail={user?.email}
|
||||||
/>
|
/>
|
||||||
<ul className="sm-pdp__facts" style={{ marginTop: "var(--space-2)" }}>
|
<ul className="sm-pdp__facts" style={{ marginTop: "var(--space-2)" }}>
|
||||||
{shippingNote && <li><Icon name={shippingNote.icon} /> {shippingNote.title}</li>}
|
{shippingNote && <li><Icon name={shippingNote.icon} /> {shippingNote.title}</li>}
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import { MAIL_TEMPLATES, getTemplateDef } from "@/lib/mail/templates";
|
||||||
import { getMailConfig, isMailReady } from "@/lib/mail/config";
|
import { getMailConfig, isMailReady } from "@/lib/mail/config";
|
||||||
import { Card, Empty, PageHead, Pill } from "@/components/admin/ui";
|
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 }> }) {
|
export default async function EmailsPage({ searchParams }: { searchParams: Promise<{ tab?: string }> }) {
|
||||||
await requireAdmin("emails.edit");
|
await requireAdmin("emails.edit");
|
||||||
|
|
|
||||||
65
src/app/admin/(panel)/erinnerungen/page.tsx
Normal file
65
src/app/admin/(panel)/erinnerungen/page.tsx
Normal file
|
|
@ -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<string, { productId: string; name: string; variant: string; stock: number; count: number; first: Date; last: Date }>();
|
||||||
|
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 (
|
||||||
|
<div className="ad-wrap">
|
||||||
|
<PageHead
|
||||||
|
title="Wieder-da-Wünsche"
|
||||||
|
lead={`Kunden, die bei ausverkauften Produkten „Erinnere mich“ gewählt haben. Erhöhst du den Bestand, geht automatisch eine Mail raus. In den letzten 30 Tagen benachrichtigt: ${notified30}, insgesamt ${notifiedTotal}.`}
|
||||||
|
>
|
||||||
|
<Link className="sm-btn sm-btn--secondary" href="/admin/emails/back_in_stock">Mail bearbeiten</Link>
|
||||||
|
</PageHead>
|
||||||
|
<Card flush>
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<Empty title="Gerade wartet niemand" text="Sobald ein Produkt ausverkauft ist, können Kunden sich auf der Produktseite eintragen." />
|
||||||
|
) : (
|
||||||
|
<div className="ad-table-wrap">
|
||||||
|
<table className="ad-table">
|
||||||
|
<thead><tr><th>Produkt</th><th className="num">Wartende</th><th>Bestand</th><th>Erster Wunsch</th><th>Letzter Wunsch</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.map((r) => (
|
||||||
|
<tr key={`${r.productId}${r.variant}`}>
|
||||||
|
<td>
|
||||||
|
<Link className="ad-rowlink" href={`/admin/produkte/${r.productId}`}>{r.name}</Link>
|
||||||
|
{r.variant && <div className="body-sm ad-muted">Variante: {r.variant}</div>}
|
||||||
|
</td>
|
||||||
|
<td className="num"><strong>{r.count}</strong></td>
|
||||||
|
<td>{r.stock > 0 ? <Pill tone="success">{Number.isFinite(r.stock) ? `${r.stock} auf Lager, Mails gehen raus` : "Ohne Bestandsführung"}</Pill> : <Pill tone="danger">Ausverkauft</Pill>}</td>
|
||||||
|
<td className="body-sm">{dateFmt.format(r.first)}</td>
|
||||||
|
<td className="body-sm">{dateFmt.format(r.last)}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
<p className="ad-help" style={{ marginTop: "var(--space-4)" }}>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.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -18,6 +18,7 @@ export default async function EditProduct({ params, searchParams }: { params: Pr
|
||||||
]);
|
]);
|
||||||
if (!p) notFound();
|
if (!p) notFound();
|
||||||
const sale = bestSale(await getRunningSales(), p);
|
const sale = bestSale(await getRunningSales(), p);
|
||||||
|
const waiting = await db.stockAlert.count({ where: { productId: p.id, notifiedAt: null } });
|
||||||
return (
|
return (
|
||||||
<div className="ad-wrap">
|
<div className="ad-wrap">
|
||||||
<PageHead title={p.name} back={{ href: "/admin/produkte", label: "Produkte" }}>
|
<PageHead title={p.name} back={{ href: "/admin/produkte", label: "Produkte" }}>
|
||||||
|
|
@ -36,6 +37,13 @@ export default async function EditProduct({ params, searchParams }: { params: Pr
|
||||||
</Alert>
|
</Alert>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{waiting > 0 && (
|
||||||
|
<div style={{ marginBottom: "var(--space-5)" }}>
|
||||||
|
<Alert title={`${waiting} ${waiting === 1 ? "Kunde wartet" : "Kunden warten"} darauf, dass dieses Produkt wieder da ist`}>
|
||||||
|
Sobald du den Bestand erhöhst und speicherst, bekommen sie automatisch eine Mail. <a href="/admin/erinnerungen">Alle Wieder-da-Wünsche</a>
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<ProductForm
|
<ProductForm
|
||||||
canStock={can(user, "stock.edit")}
|
canStock={can(user, "stock.edit")}
|
||||||
categories={categories}
|
categories={categories}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
"use server";
|
"use server";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { sendLater } from "@/lib/mail/send";
|
||||||
|
import { notifyBackInStock } from "@/lib/stock-alerts";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { assertPermission, audit, can } from "@/lib/auth";
|
import { assertPermission, audit, can } from "@/lib/auth";
|
||||||
|
|
@ -77,6 +79,8 @@ export async function saveProduct(_prev: ActionResult, fd: FormData): Promise<Ac
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
await audit(user, id ? "Produkt geändert" : "Produkt angelegt", name);
|
await audit(user, id ? "Produkt geändert" : "Produkt angelegt", name);
|
||||||
|
// Wieder auf Lager? Wartende Kunden gleich benachrichtigen
|
||||||
|
if (id) sendLater(() => notifyBackInStock(id));
|
||||||
revalidatePath("/", "layout");
|
revalidatePath("/", "layout");
|
||||||
if (!id) redirect(`/admin/produkte/${productId}?neu=1`);
|
if (!id) redirect(`/admin/produkte/${productId}?neu=1`);
|
||||||
return ok();
|
return ok();
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
|
||||||
items: [
|
items: [
|
||||||
{ href: "/admin/produkte", label: "Produkte", icon: "box", permission: "products.view", badge: "lowStock" },
|
{ href: "/admin/produkte", label: "Produkte", icon: "box", permission: "products.view", badge: "lowStock" },
|
||||||
{ href: "/admin/kategorien", label: "Kategorien", icon: "folder", permission: "categories.edit" },
|
{ href: "/admin/kategorien", label: "Kategorien", icon: "folder", permission: "categories.edit" },
|
||||||
|
{ href: "/admin/erinnerungen", label: "Wieder-da-Wünsche", icon: "heart", permission: "products.view" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { useState } from "react";
|
||||||
import { useFormStatus } from "react-dom";
|
import { useFormStatus } from "react-dom";
|
||||||
import { addToCart } from "@/app/(shop)/actions";
|
import { addToCart } from "@/app/(shop)/actions";
|
||||||
import { Icon } from "../Icon";
|
import { Icon } from "../Icon";
|
||||||
|
import { StockAlertForm } from "./StockAlertForm";
|
||||||
|
|
||||||
type Variant = { id: string; name: string; price: number; compareAt?: number | null; stock: number };
|
type Variant = { id: string; name: string; price: number; compareAt?: number | null; stock: number };
|
||||||
|
|
||||||
|
|
@ -27,6 +28,7 @@ export function BuyBox(props: {
|
||||||
variantLabel: string;
|
variantLabel: string;
|
||||||
missingVariant: boolean;
|
missingVariant: boolean;
|
||||||
saleEndsAt?: string | null;
|
saleEndsAt?: string | null;
|
||||||
|
userEmail?: string;
|
||||||
}) {
|
}) {
|
||||||
const firstAvailable = props.variants.find((v) => !props.trackStock || v.stock > 0);
|
const firstAvailable = props.variants.find((v) => !props.trackStock || v.stock > 0);
|
||||||
const [variantId, setVariantId] = useState<string | null>(props.variants.length === 1 ? (firstAvailable?.id ?? null) : null);
|
const [variantId, setVariantId] = useState<string | null>(props.variants.length === 1 ? (firstAvailable?.id ?? null) : null);
|
||||||
|
|
@ -35,12 +37,16 @@ export function BuyBox(props: {
|
||||||
const price = variant?.price ?? props.price;
|
const price = variant?.price ?? props.price;
|
||||||
const stock = props.trackStock ? (variant ? variant.stock : props.variants.length ? Infinity : props.stock) : 99;
|
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;
|
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 max = Math.min(Number.isFinite(stock) ? stock : 99, 99);
|
||||||
const needsVariant = props.variants.length > 0 && !variant;
|
const needsVariant = props.variants.length > 0 && !variant;
|
||||||
const compareBase = variant ? (variant.compareAt ?? props.compareAt) : props.compareAt;
|
const compareBase = variant ? (variant.compareAt ?? props.compareAt) : props.compareAt;
|
||||||
const compare = compareBase && compareBase > price ? compareBase : null;
|
const compare = compareBase && compareBase > price ? compareBase : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<form action={addToCart}>
|
<form action={addToCart}>
|
||||||
<input type="hidden" name="productId" value={props.productId} />
|
<input type="hidden" name="productId" value={props.productId} />
|
||||||
<input type="hidden" name="variantId" value={variantId ?? ""} />
|
<input type="hidden" name="variantId" value={variantId ?? ""} />
|
||||||
|
|
@ -63,7 +69,7 @@ export function BuyBox(props: {
|
||||||
</div>
|
</div>
|
||||||
<div className="sm-pdp__sizes" role="radiogroup" aria-label={`${props.variantLabel} wählen`}>
|
<div className="sm-pdp__sizes" role="radiogroup" aria-label={`${props.variantLabel} wählen`}>
|
||||||
{props.variants.map((v) => {
|
{props.variants.map((v) => {
|
||||||
const disabled = props.trackStock && v.stock <= 0;
|
const out = props.trackStock && v.stock <= 0;
|
||||||
return (
|
return (
|
||||||
<span key={v.id}>
|
<span key={v.id}>
|
||||||
<input
|
<input
|
||||||
|
|
@ -71,13 +77,12 @@ export function BuyBox(props: {
|
||||||
id={`v-${v.id}`}
|
id={`v-${v.id}`}
|
||||||
name="_variant"
|
name="_variant"
|
||||||
checked={variantId === v.id}
|
checked={variantId === v.id}
|
||||||
disabled={disabled}
|
|
||||||
onChange={() => {
|
onChange={() => {
|
||||||
setVariantId(v.id);
|
setVariantId(v.id);
|
||||||
setQty(1);
|
setQty(1);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<label className="sm-pdp__size" htmlFor={`v-${v.id}`}>{v.name}</label>
|
<label className={`sm-pdp__size${out ? " is-soldout" : ""}`} htmlFor={`v-${v.id}`} title={out ? "Ausverkauft, wähle sie für eine Erinnerung" : undefined}>{v.name}</label>
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
@ -90,6 +95,7 @@ export function BuyBox(props: {
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!showAlert && (
|
||||||
<div className="sm-pdp__cta">
|
<div className="sm-pdp__cta">
|
||||||
<div className="sm-qty" role="group" aria-label="Menge">
|
<div className="sm-qty" role="group" aria-label="Menge">
|
||||||
<button className="sm-qty__btn" type="button" aria-label="Menge verringern" disabled={qty <= 1} onClick={() => setQty((q) => Math.max(1, q - 1))}>
|
<button className="sm-qty__btn" type="button" aria-label="Menge verringern" disabled={qty <= 1} onClick={() => setQty((q) => Math.max(1, q - 1))}>
|
||||||
|
|
@ -111,21 +117,25 @@ export function BuyBox(props: {
|
||||||
</div>
|
</div>
|
||||||
<Submit disabled={soldOut || needsVariant} />
|
<Submit disabled={soldOut || needsVariant} />
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
{needsVariant && !soldOut && (
|
{needsVariant && !soldOut && (
|
||||||
<p className="caption" style={{ color: "var(--ink-muted)", marginTop: "var(--space-2)" }}>Wähle oben eine Variante, dann kannst du bestellen.</p>
|
<p className="caption" style={{ color: "var(--ink-muted)", marginTop: "var(--space-2)" }}>Wähle oben eine Variante, dann kannst du bestellen.</p>
|
||||||
)}
|
)}
|
||||||
<ul className="sm-pdp__facts">
|
<ul className="sm-pdp__facts">
|
||||||
<li>
|
<li>
|
||||||
{soldOut ? (
|
{showAlert ? (
|
||||||
<span className="sm-badge sm-badge--soldout">Ausverkauft</span>
|
<span className="sm-badge sm-badge--soldout">Ausverkauft</span>
|
||||||
) : max <= 3 && props.trackStock && !needsVariant ? (
|
) : max <= 3 && props.trackStock && !needsVariant ? (
|
||||||
<span className="sm-badge sm-badge--low">Nur noch {max} Stück</span>
|
<span className="sm-badge sm-badge--low">Nur noch {max} Stück</span>
|
||||||
) : (
|
) : (
|
||||||
<span className="sm-badge sm-badge--stock"><span className="sm-dot" aria-hidden="true" />Auf Lager</span>
|
<span className="sm-badge sm-badge--stock"><span className="sm-dot" aria-hidden="true" />Auf Lager</span>
|
||||||
)}
|
)}
|
||||||
{!soldOut && " Lieferung in 2–4 Werktagen"}
|
{!showAlert && " Lieferung in 2–4 Werktagen"}
|
||||||
|
{variantSoldOut && !soldOut && " Diese Variante ist gerade nicht da."}
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</form>
|
</form>
|
||||||
|
{showAlert && <StockAlertForm productId={props.productId} variantId={variantSoldOut ? variant!.id : null} variantName={variantSoldOut ? variant!.name : undefined} email={props.userEmail} />}
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
31
src/components/shop/StockAlertForm.tsx
Normal file
31
src/components/shop/StockAlertForm.tsx
Normal file
|
|
@ -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 (
|
||||||
|
<div className="sm-stockalert sm-stockalert--done" role="status">
|
||||||
|
<Icon name="check" /> <span>Wir sagen dir Bescheid, sobald {variantName ? `„${variantName}“` : "es"} wieder da ist. Einmal, per E-Mail.</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<form className="sm-stockalert" action={action} key={variantId ?? "p"}>
|
||||||
|
<input type="hidden" name="productId" value={productId} />
|
||||||
|
<input type="hidden" name="variantId" value={variantId ?? ""} />
|
||||||
|
<input type="text" name="website" tabIndex={-1} autoComplete="off" hidden aria-hidden="true" />
|
||||||
|
<p className="sm-stockalert__title"><Icon name="mail" /> Erinnere mich, wenn {variantName ? `„${variantName}“` : "das Produkt"} wieder erhältlich ist</p>
|
||||||
|
<div className="sm-input-group">
|
||||||
|
<label className="sm-visually-hidden" htmlFor="sa-email">E-Mail-Adresse</label>
|
||||||
|
<input className="sm-input" id="sa-email" name="email" type="email" defaultValue={email} placeholder="Deine E-Mail-Adresse" autoComplete="email" required />
|
||||||
|
<button className="sm-btn sm-btn--primary" type="submit" disabled={pending}>{pending ? "Moment …" : "Erinnern"}</button>
|
||||||
|
</div>
|
||||||
|
{state?.error && <span className="sm-field__error" role="alert"><Icon name="alert" /> {state.error}</span>}
|
||||||
|
<p className="caption sm-stockalert__note">Du bekommst genau eine Mail, wenn es wieder da ist. Danach löschen wir deine Adresse. Kein Newsletter.</p>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -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.
|
// Die Abfrage muss so geschrieben sein, damit der Edge-Build den Node-Teil weglässt.
|
||||||
export async function register() {
|
export async function register() {
|
||||||
if (process.env.NEXT_RUNTIME === "nodejs") {
|
if (process.env.NEXT_RUNTIME === "nodejs") {
|
||||||
const { startNewsletterTimer } = await import("./lib/campaign-sender");
|
const { startNewsletterTimer } = await import("./lib/campaign-sender");
|
||||||
startNewsletterTimer();
|
startNewsletterTimer();
|
||||||
|
const { startStockAlertTimer } = await import("./lib/stock-alerts");
|
||||||
|
startStockAlertTimer();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,7 @@ export async function deleteCustomerAccount(id: string) {
|
||||||
// Mails ohne Bestellbezug (z. B. Passwort vergessen) sind nicht aufbewahrungspflichtig
|
// Mails ohne Bestellbezug (z. B. Passwort vergessen) sind nicht aufbewahrungspflichtig
|
||||||
await db.emailLog.deleteMany({ where: { to: user.email, orderId: null } });
|
await db.emailLog.deleteMany({ where: { to: user.email, orderId: null } });
|
||||||
await db.newsletterRecipient.deleteMany({ where: { email: user.email } });
|
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
|
// Sitzungen, Social-Logins, Reset-Links und Adressen hängen per Cascade am Konto
|
||||||
await db.user.delete({ where: { id } });
|
await db.user.delete({ where: { id } });
|
||||||
return { email: user.email };
|
return { email: user.email };
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ export type MailTemplateDef = {
|
||||||
name: string;
|
name: string;
|
||||||
description: string;
|
description: string;
|
||||||
recipient: "customer" | "team";
|
recipient: "customer" | "team";
|
||||||
group: "Bestellung" | "Konto" | "Newsletter" | "Team";
|
group: "Bestellung" | "Produkt" | "Konto" | "Newsletter" | "Team";
|
||||||
placeholders: Placeholder[];
|
placeholders: Placeholder[];
|
||||||
subject: string;
|
subject: string;
|
||||||
body: string;
|
body: string;
|
||||||
|
|
@ -161,6 +161,32 @@ dein {{shop_name}}-Team`,
|
||||||
{{artikel}}
|
{{artikel}}
|
||||||
|
|
||||||
[Im Admin öffnen]({{admin_link}})`,
|
[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",
|
key: "welcome",
|
||||||
|
|
|
||||||
77
src/lib/stock-alerts.ts
Normal file
77
src/lib/stock-alerts.ts
Normal file
|
|
@ -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?.();
|
||||||
|
}
|
||||||
|
|
@ -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 { 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 li { display: flex; justify-content: space-between; gap: var(--space-4); flex-wrap: wrap; align-items: baseline; }
|
||||||
.sm-invoices small { color: var(--ink-subtle); }
|
.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; }
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue