Newsletter-Versand im Admin: Editor mit Bausteinen, Testmail, Planen, Versand in Portionen, Abmeldung, Statistik; Abonnenten entfernen
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
39eea12b47
commit
7ee30b12ee
21 changed files with 1413 additions and 28 deletions
|
|
@ -0,0 +1,48 @@
|
|||
-- CreateTable
|
||||
CREATE TABLE "NewsletterCampaign" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"subject" TEXT NOT NULL DEFAULT '',
|
||||
"preheader" TEXT NOT NULL DEFAULT '',
|
||||
"blocks" JSONB NOT NULL DEFAULT '[]',
|
||||
"segment" TEXT NOT NULL DEFAULT 'all',
|
||||
"status" TEXT NOT NULL DEFAULT 'draft',
|
||||
"scheduledAt" TIMESTAMP(3),
|
||||
"startedAt" TIMESTAMP(3),
|
||||
"finishedAt" TIMESTAMP(3),
|
||||
"links" TEXT[],
|
||||
"linkClicks" INTEGER[],
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "NewsletterCampaign_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "NewsletterRecipient" (
|
||||
"id" TEXT NOT NULL,
|
||||
"campaignId" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"token" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||
"error" TEXT NOT NULL DEFAULT '',
|
||||
"sentAt" TIMESTAMP(3),
|
||||
"openedAt" TIMESTAMP(3),
|
||||
"clickedAt" TIMESTAMP(3),
|
||||
"clicks" INTEGER NOT NULL DEFAULT 0,
|
||||
"unsubscribedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "NewsletterRecipient_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "NewsletterRecipient_token_key" ON "NewsletterRecipient"("token");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "NewsletterRecipient_campaignId_status_idx" ON "NewsletterRecipient"("campaignId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "NewsletterRecipient_campaignId_email_key" ON "NewsletterRecipient"("campaignId", "email");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "NewsletterRecipient" ADD CONSTRAINT "NewsletterRecipient_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "NewsletterCampaign"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
|
@ -378,3 +378,47 @@ model Sale {
|
|||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
// ---------- Newsletter-Versand ----------
|
||||
|
||||
// Eine Newsletter-Ausgabe. Inhalt als Liste von Bausteinen (Überschrift, Text, Bild, Button, Produkte, Linie).
|
||||
model NewsletterCampaign {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
subject String @default("")
|
||||
preheader String @default("")
|
||||
blocks Json @default("[]")
|
||||
// all | customers | nonbuyers
|
||||
segment String @default("all")
|
||||
// draft | scheduled | sending | sent | cancelled
|
||||
status String @default("draft")
|
||||
scheduledAt DateTime?
|
||||
startedAt DateTime?
|
||||
finishedAt DateTime?
|
||||
// Beim Start festgehaltene Links, Klicks zeigen per Nummer darauf (kein offener Redirect)
|
||||
links String[]
|
||||
linkClicks Int[]
|
||||
recipients NewsletterRecipient[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
// Empfänger einer Ausgabe, beim Start festgehalten. Dient zugleich als Versandprotokoll und Statistik.
|
||||
model NewsletterRecipient {
|
||||
id String @id @default(cuid())
|
||||
campaignId String
|
||||
campaign NewsletterCampaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
|
||||
email String
|
||||
token String @unique
|
||||
// pending | sent | failed | skipped
|
||||
status String @default("pending")
|
||||
error String @default("")
|
||||
sentAt DateTime?
|
||||
openedAt DateTime?
|
||||
clickedAt DateTime?
|
||||
clicks Int @default(0)
|
||||
unsubscribedAt DateTime?
|
||||
|
||||
@@unique([campaignId, email])
|
||||
@@index([campaignId, status])
|
||||
}
|
||||
|
|
|
|||
49
src/app/(shop)/newsletter/abmelden/page.tsx
Normal file
49
src/app/(shop)/newsletter/abmelden/page.tsx
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { db } from "@/lib/db";
|
||||
import { unsubscribeByToken } from "@/lib/newsletter";
|
||||
|
||||
export const metadata = { title: "Newsletter abbestellen", robots: { index: false } };
|
||||
|
||||
async function confirmUnsubscribe(fd: FormData) {
|
||||
"use server";
|
||||
const t = String(fd.get("t") ?? "");
|
||||
const email = await unsubscribeByToken(t);
|
||||
redirect(`/newsletter/abmelden?t=${encodeURIComponent(t)}${email ? "&fertig=1" : ""}`);
|
||||
}
|
||||
|
||||
export default async function Unsubscribe({ searchParams }: { searchParams: Promise<{ t?: string; fertig?: string }> }) {
|
||||
const { t, fertig } = await searchParams;
|
||||
// Erst nach dem Klick abmelden, damit Link-Scanner von Mailprogrammen niemanden versehentlich austragen
|
||||
const r = t ? await db.newsletterRecipient.findUnique({ where: { token: t }, select: { email: true } }) : null;
|
||||
const subscribed = r ? Boolean(await db.newsletterSubscriber.findUnique({ where: { email: r.email } })) : false;
|
||||
const done = Boolean(r && (fertig || !subscribed));
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<div className="sm-auth" style={{ textAlign: "center" }}>
|
||||
{!r ? (
|
||||
<>
|
||||
<h1 className="display-lg sm-page__title">Dieser Link ist ungültig.</h1>
|
||||
<p className="body sm-page__lead">Nutze den Abmeldelink unten in einer unserer Newsletter-Mails. Mit Kundenkonto kannst du den Newsletter auch unter Konto → Profil abbestellen.</p>
|
||||
<Link className="sm-btn sm-btn--primary" href="/konto/profil">Zum Konto</Link>
|
||||
</>
|
||||
) : done ? (
|
||||
<>
|
||||
<h1 className="display-lg sm-page__title">Du bist abgemeldet.</h1>
|
||||
<p className="body sm-page__lead">An {r.email} schicken wir keinen Newsletter mehr. Bestellbestätigungen und Versandinfos bekommst du natürlich weiterhin.</p>
|
||||
<Link className="sm-btn sm-btn--primary" href="/shop">Zum Shop</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h1 className="display-lg sm-page__title">Newsletter abbestellen?</h1>
|
||||
<p className="body sm-page__lead">Wir schicken dann keinen Newsletter mehr an {r.email}.</p>
|
||||
<form action={confirmUnsubscribe}>
|
||||
<input type="hidden" name="t" value={t} />
|
||||
<button className="sm-btn sm-btn--primary" type="submit">Ja, abbestellen</button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
134
src/app/admin/(panel)/newsletter/[id]/page.tsx
Normal file
134
src/app/admin/(panel)/newsletter/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
import { notFound } from "next/navigation";
|
||||
import { db } from "@/lib/db";
|
||||
import { requireAdmin } from "@/lib/auth";
|
||||
import { dateFmt } from "@/lib/status";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { toBerlinLocal } from "@/lib/berlin-time";
|
||||
import { getMailConfig, isMailReady } from "@/lib/mail/config";
|
||||
import { CAMPAIGN_STATUS, SEGMENTS, cleanBlocks, type CampaignStatus, type Segment } from "@/lib/campaign-blocks";
|
||||
import { getNewsletterSettings, loadProducts, renderCampaign, sampleNewsletterVars, segmentCounts } from "@/lib/campaigns";
|
||||
import { ConfirmButton } from "@/components/admin/AdminForm";
|
||||
import { CampaignEditor } from "@/components/admin/CampaignEditor";
|
||||
import { Card, PageHead, Pill } from "@/components/admin/ui";
|
||||
import { AutoRefresh } from "@/components/admin/AutoRefresh";
|
||||
import { cancelCampaign, deleteCampaign, duplicateCampaign, unscheduleCampaign } from "../actions";
|
||||
|
||||
export default async function CampaignPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const user = await requireAdmin("newsletter.send");
|
||||
const { id } = await params;
|
||||
const c = await db.newsletterCampaign.findUnique({ where: { id } });
|
||||
if (!c) notFound();
|
||||
const blocks = cleanBlocks(c.blocks);
|
||||
const status = (c.status in CAMPAIGN_STATUS ? c.status : "draft") as CampaignStatus;
|
||||
const st = CAMPAIGN_STATUS[status];
|
||||
const products = await loadProducts(blocks);
|
||||
const preview = await renderCampaign({ subject: c.subject, preheader: c.preheader, blocks }, { vars: await sampleNewsletterVars(), products, unsubscribeUrl: "#" });
|
||||
const back = { href: "/admin/newsletter", label: "Newsletter" };
|
||||
const tools = (
|
||||
<>
|
||||
<ConfirmButton action={duplicateCampaign} hidden={{ id: c.id }} confirm="Als neuen Entwurf kopieren?" className="sm-btn sm-btn--secondary">Duplizieren</ConfirmButton>
|
||||
{status !== "sending" && <ConfirmButton action={deleteCampaign} hidden={{ id: c.id }} confirm="Newsletter samt Statistik löschen?" className="sm-btn sm-btn--ghost">Löschen</ConfirmButton>}
|
||||
</>
|
||||
);
|
||||
|
||||
if (status === "draft" || status === "scheduled") {
|
||||
const all = await db.product.findMany({ where: { active: true }, orderBy: [{ sort: "asc" }, { name: "asc" }], include: { category: { select: { name: true } } } });
|
||||
return (
|
||||
<div className="ad-wrap ad-wrap--wide">
|
||||
<PageHead title={c.name} lead={status === "scheduled" && c.scheduledAt ? `Geplant für ${dateFmt.format(c.scheduledAt)}. Du kannst bis dahin noch alles ändern.` : "Entwurf. Baue den Newsletter aus Bausteinen, rechts siehst du sofort das Ergebnis."} back={back}>
|
||||
{status === "scheduled" && (
|
||||
<>
|
||||
<Pill tone="gold">Geplant</Pill>
|
||||
<ConfirmButton action={unscheduleCampaign} hidden={{ id: c.id }} confirm="Planung aufheben?" className="sm-btn sm-btn--secondary">Planung aufheben</ConfirmButton>
|
||||
</>
|
||||
)}
|
||||
{tools}
|
||||
</PageHead>
|
||||
<CampaignEditor
|
||||
initial={{ id: c.id, name: c.name, subject: c.subject, preheader: c.preheader, segment: (c.segment in SEGMENTS ? c.segment : "all") as Segment, blocks }}
|
||||
preview={{ subject: preview.subject, html: preview.html }}
|
||||
products={all.map((p) => ({ id: p.id, name: p.name, detail: [p.category?.name, formatPrice(p.price)].filter(Boolean).join(" · "), image: p.images[0] ?? "" }))}
|
||||
counts={await segmentCounts()}
|
||||
mailReady={isMailReady(await getMailConfig())}
|
||||
userEmail={user.email}
|
||||
scheduledFor={status === "scheduled" ? toBerlinLocal(c.scheduledAt) : ""}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Gestartet: Fortschritt und Statistik
|
||||
const [counts, failed, settings, mailReady] = await Promise.all([
|
||||
db.newsletterRecipient.groupBy({ by: ["status"], where: { campaignId: c.id }, _count: true }),
|
||||
db.newsletterRecipient.findMany({ where: { campaignId: c.id, status: "failed" }, take: 20, select: { email: true, error: true } }),
|
||||
getNewsletterSettings(),
|
||||
getMailConfig().then(isMailReady),
|
||||
]);
|
||||
const n = (s: string) => counts.find((x) => x.status === s)?._count ?? 0;
|
||||
const total = counts.reduce((a, x) => a + x._count, 0);
|
||||
const sent = n("sent");
|
||||
const pending = n("pending");
|
||||
const [opened, clicked, unsubscribed] = await Promise.all([
|
||||
db.newsletterRecipient.count({ where: { campaignId: c.id, openedAt: { not: null } } }),
|
||||
db.newsletterRecipient.count({ where: { campaignId: c.id, clickedAt: { not: null } } }),
|
||||
db.newsletterRecipient.count({ where: { campaignId: c.id, unsubscribedAt: { not: null } } }),
|
||||
]);
|
||||
const pct = (a: number) => (sent ? `${Math.round((a / sent) * 100)} %` : "–");
|
||||
const links = c.links.map((url, i) => ({ url, clicks: c.linkClicks[i] ?? 0 })).filter((l) => l.clicks > 0).sort((a, b) => b.clicks - a.clicks);
|
||||
const minutesLeft = pending ? Math.ceil(pending / settings.perMinute) : 0;
|
||||
|
||||
return (
|
||||
<div className="ad-wrap">
|
||||
{status === "sending" && <AutoRefresh seconds={15} />}
|
||||
<PageHead title={c.name} lead={`„${preview.subject}“ an ${SEGMENTS[c.segment as Segment]?.label ?? "Abonnenten"}${c.startedAt ? `, gestartet ${dateFmt.format(c.startedAt)}` : ""}${c.finishedAt ? `, fertig ${dateFmt.format(c.finishedAt)}` : ""}.`} back={back}>
|
||||
<Pill tone={st.tone}>{st.label}</Pill>
|
||||
{status === "sending" && <ConfirmButton action={cancelCampaign} hidden={{ id: c.id }} confirm="Restlichen Versand abbrechen?" className="sm-btn sm-btn--secondary">Versand abbrechen</ConfirmButton>}
|
||||
{tools}
|
||||
</PageHead>
|
||||
|
||||
{status === "sending" && (
|
||||
<Card>
|
||||
<div className="ad-nl-progress" role="progressbar" aria-valuemin={0} aria-valuemax={total} aria-valuenow={total - pending} aria-label="Versandfortschritt">
|
||||
<span style={{ width: `${total ? ((total - pending) / total) * 100 : 0}%` }} />
|
||||
</div>
|
||||
<p className="body-sm" style={{ margin: "var(--space-3) 0 0" }}>
|
||||
{total - pending} von {total} bearbeitet. {settings.perMinute} Mails pro Minute, noch etwa {minutesLeft} {minutesLeft === 1 ? "Minute" : "Minuten"}.
|
||||
{!mailReady && <strong> Der Mail-Versand ist ausgeschaltet, der Newsletter wartet.</strong>}
|
||||
</p>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="ad-kpis" style={{ marginTop: status === "sending" ? "var(--space-5)" : 0 }}>
|
||||
<div className="ad-kpi"><div className="ad-kpi__label">Zugestellt</div><div className="ad-kpi__value">{sent}</div><div className="ad-kpi__hint">von {total} Empfängern{n("failed") ? `, ${n("failed")} fehlgeschlagen` : ""}</div></div>
|
||||
<div className="ad-kpi"><div className="ad-kpi__label">Geöffnet</div><div className="ad-kpi__value">{settings.tracking || opened ? pct(opened) : "–"}</div><div className="ad-kpi__hint">{opened} Empfänger</div></div>
|
||||
<div className="ad-kpi"><div className="ad-kpi__label">Geklickt</div><div className="ad-kpi__value">{settings.tracking || clicked ? pct(clicked) : "–"}</div><div className="ad-kpi__hint">{clicked} Empfänger</div></div>
|
||||
<div className="ad-kpi"><div className="ad-kpi__label">Abgemeldet</div><div className="ad-kpi__value">{unsubscribed}</div><div className="ad-kpi__hint">über diesen Newsletter</div></div>
|
||||
</div>
|
||||
<p className="ad-help" style={{ marginBottom: "var(--space-5)" }}>Öffnungen sind ein Richtwert: Manche Mailprogramme laden Bilder nicht oder laden sie automatisch vor.</p>
|
||||
|
||||
<div className="ad-grid ad-grid--2-1">
|
||||
<Card title="Vorschau" flush>
|
||||
<div className="ad-mailedit__frame">
|
||||
<iframe title="Vorschau des Newsletters" srcDoc={preview.html} sandbox="allow-same-origin" style={{ width: "100%", height: 900 }} />
|
||||
</div>
|
||||
</Card>
|
||||
<div style={{ display: "grid", gap: "var(--space-5)", alignContent: "start" }}>
|
||||
<Card title="Beliebteste Links" flush>
|
||||
{links.length === 0 ? <div className="ad-empty body-sm">Noch keine Klicks.</div> : (
|
||||
<table className="ad-table">
|
||||
<tbody>{links.map((l) => <tr key={l.url}><td className="body-sm" style={{ wordBreak: "break-all" }}>{l.url.replace(/^https?:\/\//, "")}</td><td className="num">{l.clicks}</td></tr>)}</tbody>
|
||||
</table>
|
||||
)}
|
||||
</Card>
|
||||
{failed.length > 0 && (
|
||||
<Card title="Fehlgeschlagen" flush>
|
||||
<table className="ad-table">
|
||||
<tbody>{failed.map((f) => <tr key={f.email}><td className="body-sm">{f.email}<div className="caption ad-muted">{f.error}</div></td></tr>)}</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
164
src/app/admin/(panel)/newsletter/actions.ts
Normal file
164
src/app/admin/(panel)/newsletter/actions.ts
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { assertPermission, audit } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||
import { unsubscribe } from "@/lib/newsletter";
|
||||
import { parseBerlinLocal } from "@/lib/berlin-time";
|
||||
import { getMailConfig, isMailReady } from "@/lib/mail/config";
|
||||
import { sendSmtp } from "@/lib/mail/smtp";
|
||||
import { sendLater } from "@/lib/mail/send";
|
||||
import { appUrl } from "@/lib/social/config";
|
||||
import { cleanBlocks, SEGMENTS, type CampaignBlock, type Segment } from "@/lib/campaign-blocks";
|
||||
import { loadProducts, renderCampaign, sampleNewsletterVars, saveNewsletterSettings, segmentEmails } from "@/lib/campaigns";
|
||||
import { processNewsletterQueue } from "@/lib/campaign-sender";
|
||||
|
||||
export type CampaignInput = { id: string; name: string; subject: string; preheader: string; segment: Segment; blocks: CampaignBlock[] };
|
||||
|
||||
function clean(input: CampaignInput) {
|
||||
return {
|
||||
name: String(input.name ?? "").trim().slice(0, 120) || "Newsletter",
|
||||
subject: String(input.subject ?? "").replace(/\s+/g, " ").trim().slice(0, 200),
|
||||
preheader: String(input.preheader ?? "").replace(/\s+/g, " ").trim().slice(0, 200),
|
||||
segment: (input.segment in SEGMENTS ? input.segment : "all") as Segment,
|
||||
blocks: cleanBlocks(input.blocks),
|
||||
};
|
||||
}
|
||||
|
||||
const EDITABLE = ["draft", "scheduled"];
|
||||
|
||||
export async function createCampaign() {
|
||||
const user = await assertPermission("newsletter.send");
|
||||
const date = new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric", timeZone: "Europe/Berlin" }).format(new Date());
|
||||
const id = () => Math.random().toString(36).slice(2, 10);
|
||||
const c = await db.newsletterCampaign.create({
|
||||
data: {
|
||||
name: `Newsletter ${date}`,
|
||||
subject: "Neu bei {{shop_name}}",
|
||||
blocks: [
|
||||
{ id: id(), type: "heading", text: "Neu im Studio" },
|
||||
{ id: id(), type: "text", text: "Hallo {{vorname}},\n\nhier kommt, was es Neues bei uns gibt." },
|
||||
{ id: id(), type: "products", productIds: [] },
|
||||
{ id: id(), type: "button", label: "Zum Shop", url: "{{shop_link}}" },
|
||||
],
|
||||
},
|
||||
});
|
||||
await audit(user, "Newsletter angelegt", c.name);
|
||||
redirect(`/admin/newsletter/${c.id}`);
|
||||
}
|
||||
|
||||
export async function saveCampaign(input: CampaignInput): Promise<ActionResult> {
|
||||
await assertPermission("newsletter.send");
|
||||
const c = await db.newsletterCampaign.findUnique({ where: { id: input.id } });
|
||||
if (!c) return fail("Newsletter nicht gefunden.");
|
||||
if (!EDITABLE.includes(c.status)) return fail("Ein versendeter Newsletter lässt sich nicht mehr ändern. Dupliziere ihn für eine neue Ausgabe.");
|
||||
await db.newsletterCampaign.update({ where: { id: c.id }, data: clean(input) });
|
||||
revalidatePath("/admin/newsletter");
|
||||
return ok("Gespeichert.");
|
||||
}
|
||||
|
||||
export async function previewCampaign(input: CampaignInput) {
|
||||
await assertPermission("newsletter.send");
|
||||
const d = clean(input);
|
||||
const mail = await renderCampaign(d, { vars: await sampleNewsletterVars(), products: await loadProducts(d.blocks), unsubscribeUrl: "#" });
|
||||
return { subject: mail.subject, html: mail.html };
|
||||
}
|
||||
|
||||
export async function testCampaign(input: CampaignInput, to: string): Promise<ActionResult> {
|
||||
const user = await assertPermission("newsletter.send");
|
||||
const d = clean(input);
|
||||
to = to.trim();
|
||||
if (!/^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]+$/.test(to)) return fail("Bitte gib eine gültige E-Mail-Adresse ein.");
|
||||
if (!d.subject) return fail("Bitte gib einen Betreff ein.");
|
||||
const config = await getMailConfig();
|
||||
if (!isMailReady(config)) return fail("Richte zuerst den Mail-Versand unter Verbindungen ein.");
|
||||
const mail = await renderCampaign(d, { vars: await sampleNewsletterVars({ firstName: user.firstName || "Marie", lastName: user.lastName || "Keller" }, to), products: await loadProducts(d.blocks), unsubscribeUrl: `${appUrl()}/newsletter/abmelden` });
|
||||
try {
|
||||
await sendSmtp(config, { from: { name: config.fromName, email: config.fromEmail }, to, replyTo: config.replyTo || undefined, ...mail, subject: `[Test] ${mail.subject}` });
|
||||
} catch (e) {
|
||||
return fail(`Testmail fehlgeschlagen: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
return ok(`Testmail an ${to} verschickt.`);
|
||||
}
|
||||
|
||||
/** Planen (Zeitpunkt in deutscher Zeit) oder mit leerem Zeitpunkt sofort senden. */
|
||||
export async function scheduleCampaign(input: CampaignInput, when: string): Promise<ActionResult> {
|
||||
const user = await assertPermission("newsletter.send");
|
||||
const c = await db.newsletterCampaign.findUnique({ where: { id: input.id } });
|
||||
if (!c || !EDITABLE.includes(c.status)) return fail("Dieser Newsletter kann nicht mehr geplant werden.");
|
||||
const d = clean(input);
|
||||
if (!d.subject) return fail("Bitte gib einen Betreff ein.");
|
||||
if (!d.blocks.some((b) => b.type !== "divider")) return fail("Der Newsletter hat noch keinen Inhalt.");
|
||||
if (!isMailReady(await getMailConfig())) return fail("Richte zuerst den Mail-Versand unter Verbindungen ein.");
|
||||
const count = (await segmentEmails(d.segment)).length;
|
||||
if (!count) return fail("In dieser Zielgruppe gibt es noch keine bestätigten Abonnenten.");
|
||||
let at = new Date();
|
||||
if (when) {
|
||||
const parsed = parseBerlinLocal(when);
|
||||
if (!parsed) return fail("Bitte gib einen gültigen Zeitpunkt an.");
|
||||
if (parsed.getTime() < Date.now() - 60_000) return fail("Der Zeitpunkt liegt in der Vergangenheit.");
|
||||
at = parsed;
|
||||
}
|
||||
await db.newsletterCampaign.update({ where: { id: c.id }, data: { ...d, status: "scheduled", scheduledAt: at } });
|
||||
await audit(user, when ? "Newsletter geplant" : "Newsletter-Versand gestartet", `${d.name} an ${count} Empfänger`);
|
||||
if (!when) sendLater(processNewsletterQueue);
|
||||
revalidatePath("/admin/newsletter");
|
||||
return ok(when ? "Geplant." : "Versand gestartet.");
|
||||
}
|
||||
|
||||
export async function unscheduleCampaign(fd: FormData) {
|
||||
await assertPermission("newsletter.send");
|
||||
const id = String(fd.get("id"));
|
||||
await db.newsletterCampaign.updateMany({ where: { id, status: "scheduled" }, data: { status: "draft", scheduledAt: null } });
|
||||
revalidatePath(`/admin/newsletter/${id}`);
|
||||
}
|
||||
|
||||
export async function cancelCampaign(fd: FormData) {
|
||||
const user = await assertPermission("newsletter.send");
|
||||
const id = String(fd.get("id"));
|
||||
const c = await db.newsletterCampaign.findUnique({ where: { id } });
|
||||
if (!c || !["scheduled", "sending"].includes(c.status)) return;
|
||||
await db.newsletterRecipient.updateMany({ where: { campaignId: id, status: "pending" }, data: { status: "skipped", error: "Versand abgebrochen" } });
|
||||
await db.newsletterCampaign.update({ where: { id }, data: { status: "cancelled", finishedAt: new Date() } });
|
||||
await audit(user, "Newsletter-Versand abgebrochen", c.name);
|
||||
revalidatePath(`/admin/newsletter/${id}`);
|
||||
}
|
||||
|
||||
export async function duplicateCampaign(fd: FormData) {
|
||||
const user = await assertPermission("newsletter.send");
|
||||
const c = await db.newsletterCampaign.findUnique({ where: { id: String(fd.get("id")) } });
|
||||
if (!c) return;
|
||||
const copy = await db.newsletterCampaign.create({ data: { name: `${c.name} (Kopie)`, subject: c.subject, preheader: c.preheader, segment: c.segment, blocks: c.blocks ?? [] } });
|
||||
await audit(user, "Newsletter dupliziert", c.name);
|
||||
redirect(`/admin/newsletter/${copy.id}`);
|
||||
}
|
||||
|
||||
export async function deleteCampaign(fd: FormData) {
|
||||
const user = await assertPermission("newsletter.send");
|
||||
const c = await db.newsletterCampaign.findUnique({ where: { id: String(fd.get("id")) } });
|
||||
if (!c || c.status === "sending") return;
|
||||
await db.newsletterCampaign.delete({ where: { id: c.id } });
|
||||
await audit(user, "Newsletter gelöscht", c.name);
|
||||
revalidatePath("/admin/newsletter");
|
||||
redirect("/admin/newsletter");
|
||||
}
|
||||
|
||||
export async function removeSubscriber(fd: FormData) {
|
||||
const user = await assertPermission("newsletter.send");
|
||||
const sub = await db.newsletterSubscriber.findUnique({ where: { id: String(fd.get("id")) } });
|
||||
if (!sub) return;
|
||||
await unsubscribe(sub.email);
|
||||
await audit(user, "Newsletter-Abonnent entfernt", sub.email);
|
||||
revalidatePath("/admin/newsletter");
|
||||
}
|
||||
|
||||
export async function saveSettings(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||
const user = await assertPermission("newsletter.send");
|
||||
const perMinute = Math.round(Number(fd.get("perMinute")));
|
||||
if (!Number.isFinite(perMinute) || perMinute < 1 || perMinute > 500) return fail("Bitte gib eine Zahl zwischen 1 und 500 an.", { perMinute: "Zwischen 1 und 500" });
|
||||
await saveNewsletterSettings({ perMinute, tracking: fd.get("tracking") === "on" });
|
||||
await audit(user, "Newsletter-Einstellungen geändert");
|
||||
revalidatePath("/admin/newsletter");
|
||||
return ok();
|
||||
}
|
||||
|
|
@ -1,24 +1,147 @@
|
|||
import Link from "next/link";
|
||||
import { db } from "@/lib/db";
|
||||
import { requireAdmin } from "@/lib/auth";
|
||||
import { can, requireAdmin } from "@/lib/auth";
|
||||
import { dateFmt } from "@/lib/status";
|
||||
import { Card, Empty, PageHead, Pill } from "@/components/admin/ui";
|
||||
import { getMailConfig, isMailReady } from "@/lib/mail/config";
|
||||
import { CAMPAIGN_STATUS, SEGMENTS, type CampaignStatus, type Segment } from "@/lib/campaign-blocks";
|
||||
import { getNewsletterSettings } from "@/lib/campaigns";
|
||||
import { commonVars } from "@/lib/mail/send";
|
||||
import { renderSubject } from "@/lib/mail/render";
|
||||
import { Field } from "@/components/Field";
|
||||
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
|
||||
import { Card, Empty, PageHead, Pill, Switch } from "@/components/admin/ui";
|
||||
import { createCampaign, removeSubscriber, saveSettings } from "./actions";
|
||||
|
||||
export default async function NewsletterPage() {
|
||||
await requireAdmin("newsletter.view");
|
||||
const subs = await db.newsletterSubscriber.findMany({ orderBy: { createdAt: "desc" } });
|
||||
const confirmed = subs.filter((s) => s.confirmedAt).length;
|
||||
type Tab = "ausgaben" | "abonnenten" | "einstellungen";
|
||||
|
||||
export default async function NewsletterPage({ searchParams }: { searchParams: Promise<{ tab?: string; q?: string }> }) {
|
||||
const user = await requireAdmin("newsletter.view");
|
||||
const { tab: rawTab, q } = await searchParams;
|
||||
const canSend = can(user, "newsletter.send");
|
||||
const tab: Tab = rawTab === "abonnenten" || (rawTab === "einstellungen" && canSend) ? rawTab : canSend ? "ausgaben" : "abonnenten";
|
||||
const [confirmed, waiting] = await Promise.all([db.newsletterSubscriber.count({ where: { confirmedAt: { not: null } } }), db.newsletterSubscriber.count({ where: { confirmedAt: null } })]);
|
||||
return (
|
||||
<div className="ad-wrap ad-wrap--narrow">
|
||||
<PageHead title="Newsletter" lead={`${confirmed} bestätigte Anmeldungen${subs.length > confirmed ? `, ${subs.length - confirmed} warten auf Bestätigung` : ""}. Angemeldet ist erst, wer den Link in der Bestätigungsmail geklickt hat.`}>
|
||||
{confirmed > 0 && <a className="sm-btn sm-btn--secondary" href="/admin/newsletter/export">Bestätigte als CSV</a>}
|
||||
</PageHead>
|
||||
<Card flush>
|
||||
{subs.length === 0 ? <Empty title="Noch keine Anmeldungen" /> : (
|
||||
<table className="ad-table">
|
||||
<thead><tr><th>E-Mail</th><th>Angemeldet am</th><th>Status</th></tr></thead>
|
||||
<tbody>{subs.map((s) => <tr key={s.id}><td>{s.email}</td><td className="body-sm">{dateFmt.format(s.createdAt)}</td><td>{s.confirmedAt ? <Pill tone="success">Bestätigt</Pill> : <Pill tone="gold">Wartet</Pill>}</td></tr>)}</tbody>
|
||||
</table>
|
||||
<div className="ad-wrap">
|
||||
<PageHead title="Newsletter" lead={`${confirmed} bestätigte Abonnenten${waiting ? `, ${waiting} warten auf Bestätigung` : ""}. Gestalte Ausgaben im Shop-Design und verschicke sie über deinen eigenen Mailserver.`}>
|
||||
{canSend && tab === "ausgaben" && (
|
||||
<form action={createCampaign}>
|
||||
<button className="sm-btn sm-btn--primary" type="submit">Neuer Newsletter</button>
|
||||
</form>
|
||||
)}
|
||||
{tab === "abonnenten" && confirmed > 0 && <a className="sm-btn sm-btn--secondary" href="/admin/newsletter/export">Bestätigte als CSV</a>}
|
||||
</PageHead>
|
||||
<div className="ad-tabs" style={{ marginBottom: "var(--space-5)" }}>
|
||||
{canSend && <Link className={`ad-tab${tab === "ausgaben" ? " is-active" : ""}`} href="/admin/newsletter">Ausgaben</Link>}
|
||||
<Link className={`ad-tab${tab === "abonnenten" ? " is-active" : ""}`} href="/admin/newsletter?tab=abonnenten">Abonnenten</Link>
|
||||
{canSend && <Link className={`ad-tab${tab === "einstellungen" ? " is-active" : ""}`} href="/admin/newsletter?tab=einstellungen">Einstellungen</Link>}
|
||||
</div>
|
||||
{tab === "ausgaben" ? <Campaigns /> : tab === "abonnenten" ? <Subscribers q={q ?? ""} canRemove={canSend} /> : <Settings />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function Campaigns() {
|
||||
const [campaigns, mailReady] = await Promise.all([
|
||||
db.newsletterCampaign.findMany({ orderBy: { createdAt: "desc" }, take: 100, include: { _count: { select: { recipients: true } } } }),
|
||||
getMailConfig().then(isMailReady),
|
||||
]);
|
||||
const ids = campaigns.filter((c) => c.startedAt).map((c) => c.id);
|
||||
const stats = ids.length
|
||||
? await db.newsletterRecipient.groupBy({ by: ["campaignId"], where: { campaignId: { in: ids } }, _count: { sentAt: true, openedAt: true, clickedAt: true } })
|
||||
: [];
|
||||
const byId = new Map(stats.map((s) => [s.campaignId, s._count]));
|
||||
const vars = await commonVars();
|
||||
const pct = (a: number, b: number) => (b ? `${Math.round((a / b) * 100)} %` : "–");
|
||||
return (
|
||||
<>
|
||||
{!mailReady && (
|
||||
<p className="ad-help" style={{ marginBottom: "var(--space-4)" }}>
|
||||
Der Mail-Versand ist noch nicht eingerichtet. <Link href="/admin/verbindungen/mail">Jetzt einrichten</Link>, damit Newsletter rausgehen können.
|
||||
</p>
|
||||
)}
|
||||
<Card flush>
|
||||
{campaigns.length === 0 ? (
|
||||
<Empty title="Noch keine Newsletter" text="Lege eine Ausgabe an, füge Text, Bilder und Produkte hinzu und schick sie an deine Abonnenten.">
|
||||
<form action={createCampaign}><button className="sm-btn sm-btn--secondary" type="submit">Ersten Newsletter anlegen</button></form>
|
||||
</Empty>
|
||||
) : (
|
||||
<div className="ad-table-wrap">
|
||||
<table className="ad-table">
|
||||
<thead><tr><th>Newsletter</th><th>Status</th><th>Empfänger</th><th className="num">Geöffnet</th><th className="num">Geklickt</th></tr></thead>
|
||||
<tbody>
|
||||
{campaigns.map((c) => {
|
||||
const st = CAMPAIGN_STATUS[c.status as CampaignStatus] ?? CAMPAIGN_STATUS.draft;
|
||||
const s = byId.get(c.id);
|
||||
const when = c.status === "scheduled" && c.scheduledAt ? `geplant für ${dateFmt.format(c.scheduledAt)}` : c.finishedAt ? `versendet ${dateFmt.format(c.finishedAt)}` : `angelegt ${dateFmt.format(c.createdAt)}`;
|
||||
return (
|
||||
<tr key={c.id}>
|
||||
<td>
|
||||
<Link className="ad-rowlink" href={`/admin/newsletter/${c.id}`}>{c.name}</Link>
|
||||
<div className="body-sm ad-muted">{c.subject ? renderSubject(c.subject, vars) : "Ohne Betreff"} · {when}</div>
|
||||
</td>
|
||||
<td><Pill tone={st.tone}>{st.label}</Pill></td>
|
||||
<td className="body-sm">{c.startedAt ? `${s?.sentAt ?? 0} von ${c._count.recipients}` : SEGMENTS[c.segment as Segment]?.label}</td>
|
||||
<td className="num">{c.startedAt ? pct(s?.openedAt ?? 0, s?.sentAt ?? 0) : "–"}</td>
|
||||
<td className="num">{c.startedAt ? pct(s?.clickedAt ?? 0, s?.sentAt ?? 0) : "–"}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
async function Subscribers({ q, canRemove }: { q: string; canRemove: boolean }) {
|
||||
const term = q.trim();
|
||||
const subs = await db.newsletterSubscriber.findMany({ where: term ? { email: { contains: term, mode: "insensitive" } } : undefined, orderBy: { createdAt: "desc" }, take: 500 });
|
||||
return (
|
||||
<Card flush>
|
||||
<form className="ad-toolbar" role="search">
|
||||
<input type="hidden" name="tab" value="abonnenten" />
|
||||
<input className="sm-input" type="search" name="q" defaultValue={term} placeholder="E-Mail suchen …" aria-label="E-Mail suchen" />
|
||||
<button className="sm-btn sm-btn--secondary sm-btn--sm" type="submit">Suchen</button>
|
||||
{term && <Link className="body-sm" href="/admin/newsletter?tab=abonnenten">Zurücksetzen</Link>}
|
||||
</form>
|
||||
{subs.length === 0 ? (
|
||||
<Empty title={term ? "Keine Treffer" : "Noch keine Anmeldungen"} />
|
||||
) : (
|
||||
<div className="ad-table-wrap">
|
||||
<table className="ad-table">
|
||||
<thead><tr><th>E-Mail</th><th>Angemeldet am</th><th>Status</th>{canRemove && <th />}</tr></thead>
|
||||
<tbody>
|
||||
{subs.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td>{s.email}</td>
|
||||
<td className="body-sm">{dateFmt.format(s.createdAt)}</td>
|
||||
<td>{s.confirmedAt ? <Pill tone="success">Bestätigt</Pill> : <Pill tone="gold">Wartet</Pill>}</td>
|
||||
{canRemove && (
|
||||
<td className="num">
|
||||
<ConfirmButton action={removeSubscriber} hidden={{ id: s.id }} confirm="Aus dem Newsletter entfernen?" className="sm-btn sm-btn--ghost sm-btn--sm" title={`${s.email} entfernen`}>Entfernen</ConfirmButton>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
async function Settings() {
|
||||
const s = await getNewsletterSettings();
|
||||
return (
|
||||
<div className="ad-wrap--narrow" style={{ margin: 0 }}>
|
||||
<Card title="Versand">
|
||||
<AdminForm action={saveSettings}>
|
||||
<Field label="Mails pro Minute" name="perMinute" type="number" min={1} max={500} defaultValue={String(s.perMinute)} hint={`Das sind etwa ${s.perMinute * 60} pro Stunde. Viele Mail-Anbieter begrenzen, wie viele Mails ein Postfach pro Stunde oder Tag senden darf. Wird die Grenze überschritten, lehnt der Server weitere Mails ab oder sperrt das Postfach vorübergehend. Frag im Zweifel bei deinem Anbieter nach und bleib darunter.`} />
|
||||
<Switch name="tracking" label="Öffnungen und Klicks messen" hint="Zählt per unsichtbarem Bild, wer den Newsletter öffnet, und welche Links geklickt werden. Erwähne das in deiner Datenschutzerklärung und im Anmeldetext." defaultChecked={s.tracking} />
|
||||
</AdminForm>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
16
src/app/api/newsletter/abmelden/route.ts
Normal file
16
src/app/api/newsletter/abmelden/route.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { unsubscribeByToken } from "@/lib/newsletter";
|
||||
import { appUrl } from "@/lib/social/config";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Ein-Klick-Abmeldung aus dem Mailprogramm (List-Unsubscribe-Post, RFC 8058). */
|
||||
export async function POST(req: Request) {
|
||||
const t = new URL(req.url).searchParams.get("t") ?? "";
|
||||
await unsubscribeByToken(t);
|
||||
return new Response("Abgemeldet", { status: 200 });
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const t = new URL(req.url).searchParams.get("t") ?? "";
|
||||
return Response.redirect(`${appUrl()}/newsletter/abmelden?t=${encodeURIComponent(t)}`, 302);
|
||||
}
|
||||
19
src/app/api/newsletter/c/[token]/[idx]/route.ts
Normal file
19
src/app/api/newsletter/c/[token]/[idx]/route.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { db } from "@/lib/db";
|
||||
import { appUrl } from "@/lib/social/config";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Klick zählen und weiterleiten. Ziel ist nur ein beim Versand gespeicherter Link, nie eine Adresse aus der URL. */
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ token: string; idx: string }> }) {
|
||||
const { token, idx } = await params;
|
||||
const i = Number(idx);
|
||||
const r = await db.newsletterRecipient.findUnique({ where: { token }, include: { campaign: { select: { id: true, links: true } } } });
|
||||
const target = r && Number.isInteger(i) ? r.campaign.links[i] : undefined;
|
||||
if (!r || !target) return Response.redirect(appUrl(), 302);
|
||||
const now = new Date();
|
||||
await db.newsletterRecipient.update({ where: { id: r.id }, data: { clicks: { increment: 1 }, clickedAt: r.clickedAt ?? now, openedAt: r.openedAt ?? now } });
|
||||
// Postgres-Arrays beginnen bei 1
|
||||
await db.$executeRaw`UPDATE "NewsletterCampaign" SET "linkClicks"[${i + 1}] = COALESCE("linkClicks"[${i + 1}], 0) + 1 WHERE id = ${r.campaign.id}`;
|
||||
const url = target.startsWith("/") ? `${appUrl()}${target}` : /^https?:\/\//.test(target) ? target : appUrl();
|
||||
return Response.redirect(url, 302);
|
||||
}
|
||||
12
src/app/api/newsletter/o/[token]/route.ts
Normal file
12
src/app/api/newsletter/o/[token]/route.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { db } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const GIF = Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64");
|
||||
|
||||
/** Zählpixel: erste Öffnung merken. */
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ token: string }> }) {
|
||||
const { token } = await params;
|
||||
await db.newsletterRecipient.updateMany({ where: { token, openedAt: null }, data: { openedAt: new Date() } }).catch(() => undefined);
|
||||
return new Response(new Uint8Array(GIF), { headers: { "Content-Type": "image/gif", "Cache-Control": "no-store, max-age=0" } });
|
||||
}
|
||||
13
src/components/admin/AutoRefresh.tsx
Normal file
13
src/components/admin/AutoRefresh.tsx
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
"use client";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
/** Lädt die Seitendaten regelmäßig neu, z. B. für den Fortschritt eines laufenden Versands. */
|
||||
export function AutoRefresh({ seconds }: { seconds: number }) {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => document.visibilityState === "visible" && router.refresh(), seconds * 1000);
|
||||
return () => clearInterval(id);
|
||||
}, [router, seconds]);
|
||||
return null;
|
||||
}
|
||||
326
src/components/admin/CampaignEditor.tsx
Normal file
326
src/components/admin/CampaignEditor.tsx
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
"use client";
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import { useEffect, useRef, useState, useTransition } from "react";
|
||||
import type { ActionResult } from "@/lib/action-result";
|
||||
import { BLOCK_LABELS, SEGMENTS, type BlockType, type CampaignBlock, type Segment } from "@/lib/campaign-blocks";
|
||||
import { previewCampaign, saveCampaign, scheduleCampaign, testCampaign, type CampaignInput } from "@/app/admin/(panel)/newsletter/actions";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
export type PickerProduct = { id: string; name: string; detail: string; image: string };
|
||||
|
||||
const uid = () => Math.random().toString(36).slice(2, 10);
|
||||
|
||||
function newBlock(type: BlockType): CampaignBlock {
|
||||
const id = uid();
|
||||
switch (type) {
|
||||
case "heading": return { id, type, text: "" };
|
||||
case "text": return { id, type, text: "" };
|
||||
case "image": return { id, type, url: "", alt: "", link: "" };
|
||||
case "button": return { id, type, label: "Jetzt entdecken", url: "{{shop_link}}" };
|
||||
case "products": return { id, type, productIds: [] };
|
||||
case "divider": return { id, type };
|
||||
}
|
||||
}
|
||||
|
||||
function Message({ state }: { state: ActionResult }) {
|
||||
if (!state?.message) return null;
|
||||
return (
|
||||
<span className={state.ok ? "ad-ok" : "ad-err"} role="status">
|
||||
<Icon name={state.ok ? "check" : "alert"} size="sm" /> {state.message}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageBlockFields({ block, onChange }: { block: Extract<CampaignBlock, { type: "image" }>; onChange: (b: CampaignBlock) => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
async function upload(files: FileList | null) {
|
||||
if (!files?.[0]) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
const fd = new FormData();
|
||||
fd.append("files", files[0]);
|
||||
try {
|
||||
const res = await fetch("/admin/upload", { method: "POST", body: fd });
|
||||
const body = (await res.json()) as { urls?: string[]; error?: string };
|
||||
if (body.urls?.[0]) onChange({ ...block, url: body.urls[0] });
|
||||
else setError(body.error ?? "Hochladen fehlgeschlagen.");
|
||||
} catch {
|
||||
setError("Hochladen fehlgeschlagen.");
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
return (
|
||||
<div className="ad-nl-fields">
|
||||
<div className="ad-nl-image">
|
||||
{block.url ? <img src={block.url} alt="" /> : <span className="ad-muted body-sm">Noch kein Bild</span>}
|
||||
<label className="sm-btn sm-btn--secondary sm-btn--sm">
|
||||
{busy ? "Lädt hoch …" : block.url ? "Anderes Bild" : "Bild hochladen"}
|
||||
<input type="file" hidden accept="image/jpeg,image/png,image/gif,image/webp" disabled={busy} onChange={(e) => upload(e.target.files)} />
|
||||
</label>
|
||||
</div>
|
||||
{error && <span className="sm-field__error" role="alert"><Icon name="alert" /> {error}</span>}
|
||||
<p className="caption ad-muted" style={{ margin: 0 }}>JPG oder PNG funktionieren in allen Mailprogrammen. WebP zeigt Outlook nicht an.</p>
|
||||
<label className="sm-field"><span className="sm-field__label">Beschreibung <span className="sm-optional">(für Leser ohne Bilder)</span></span><input className="sm-input" value={block.alt} onChange={(e) => onChange({ ...block, alt: e.target.value })} /></label>
|
||||
<label className="sm-field"><span className="sm-field__label">Link beim Klick <span className="sm-optional">(optional)</span></span><input className="sm-input" value={block.link} placeholder="https://… oder /produkt/…" onChange={(e) => onChange({ ...block, link: e.target.value })} /></label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProductBlockFields({ block, products, onChange }: { block: Extract<CampaignBlock, { type: "products" }>; products: PickerProduct[]; onChange: (b: CampaignBlock) => void }) {
|
||||
const [q, setQ] = useState("");
|
||||
const term = q.trim().toLowerCase();
|
||||
const toggle = (id: string) => onChange({ ...block, productIds: block.productIds.includes(id) ? block.productIds.filter((x) => x !== id) : [...block.productIds, id].slice(0, 12) });
|
||||
const shown = products.filter((p) => !term || `${p.name} ${p.detail}`.toLowerCase().includes(term));
|
||||
return (
|
||||
<div className="ad-picker" style={{ marginTop: 0 }}>
|
||||
<input className="sm-input" type="search" placeholder="Produkt suchen …" value={q} onChange={(e) => setQ(e.target.value)} aria-label="Produkt suchen" />
|
||||
<div className="ad-picker__list">
|
||||
{shown.map((p) => (
|
||||
<label key={p.id} className="ad-picker__item">
|
||||
<input type="checkbox" checked={block.productIds.includes(p.id)} onChange={() => toggle(p.id)} />
|
||||
{p.image ? <img className="ad-nl-thumb" src={p.image} alt="" /> : <span className="ad-nl-thumb" />}
|
||||
<span><strong>{p.name}</strong><small>{p.detail}</small></span>
|
||||
</label>
|
||||
))}
|
||||
{shown.length === 0 && <div className="ad-empty body-sm">Kein Produkt gefunden.</div>}
|
||||
</div>
|
||||
<small className="ad-muted">{block.productIds.length} ausgewählt, höchstens 12. Preise und Sales werden beim Versand aktuell eingesetzt.</small>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BlockFields({ block, products, onChange }: { block: CampaignBlock; products: PickerProduct[]; onChange: (b: CampaignBlock) => void }) {
|
||||
switch (block.type) {
|
||||
case "heading":
|
||||
return <input className="sm-input" value={block.text} placeholder="Überschrift" onChange={(e) => onChange({ ...block, text: e.target.value })} aria-label="Überschrift" />;
|
||||
case "text":
|
||||
return (
|
||||
<>
|
||||
<textarea className="sm-textarea" rows={6} value={block.text} onChange={(e) => onChange({ ...block, text: e.target.value })} aria-label="Text" spellCheck />
|
||||
<p className="caption ad-muted" style={{ margin: "var(--space-1) 0 0" }}>Leere Zeile = neuer Absatz · <code>**fett**</code> · <code>- Punkt</code> · <code>[Linktext](https://…)</code> · <code>{"{{vorname}}"}</code> wird durch den Vornamen ersetzt, falls bekannt.</p>
|
||||
</>
|
||||
);
|
||||
case "button":
|
||||
return (
|
||||
<div className="sm-form-row">
|
||||
<label className="sm-field"><span className="sm-field__label">Beschriftung</span><input className="sm-input" value={block.label} onChange={(e) => onChange({ ...block, label: e.target.value })} /></label>
|
||||
<label className="sm-field"><span className="sm-field__label">Link</span><input className="sm-input" value={block.url} placeholder="https://… oder /shop" onChange={(e) => onChange({ ...block, url: e.target.value })} /></label>
|
||||
</div>
|
||||
);
|
||||
case "image":
|
||||
return <ImageBlockFields block={block} onChange={onChange} />;
|
||||
case "products":
|
||||
return <ProductBlockFields block={block} products={products} onChange={onChange} />;
|
||||
case "divider":
|
||||
return <p className="body-sm ad-muted" style={{ margin: 0 }}>Eine feine Linie zwischen zwei Abschnitten.</p>;
|
||||
}
|
||||
}
|
||||
|
||||
/** Newsletter gestalten: Bausteine links, Live-Vorschau rechts, unten Testmail und Versand. */
|
||||
export function CampaignEditor({
|
||||
initial,
|
||||
preview: initialPreview,
|
||||
products,
|
||||
counts,
|
||||
mailReady,
|
||||
userEmail,
|
||||
scheduledFor,
|
||||
}: {
|
||||
initial: CampaignInput;
|
||||
preview: { subject: string; html: string };
|
||||
products: PickerProduct[];
|
||||
counts: Record<Segment, number>;
|
||||
mailReady: boolean;
|
||||
userEmail: string;
|
||||
scheduledFor: string;
|
||||
}) {
|
||||
const [name, setName] = useState(initial.name);
|
||||
const [subject, setSubject] = useState(initial.subject);
|
||||
const [preheader, setPreheader] = useState(initial.preheader);
|
||||
const [segment, setSegment] = useState<Segment>(initial.segment);
|
||||
const [blocks, setBlocks] = useState<CampaignBlock[]>(initial.blocks);
|
||||
const [preview, setPreview] = useState(initialPreview);
|
||||
const [device, setDevice] = useState<"desktop" | "mobile">("desktop");
|
||||
const [message, setMessage] = useState<ActionResult>(null);
|
||||
const [testTo, setTestTo] = useState(userEmail);
|
||||
const [mode, setMode] = useState<"now" | "later">(scheduledFor ? "later" : "now");
|
||||
const [when, setWhen] = useState(scheduledFor);
|
||||
const [armed, setArmed] = useState(false);
|
||||
const [busy, startBusy] = useTransition();
|
||||
const [, startPreview] = useTransition();
|
||||
const first = useRef(true);
|
||||
const dirty = useRef(false);
|
||||
|
||||
const data = (): CampaignInput => ({ id: initial.id, name, subject, preheader, segment, blocks });
|
||||
|
||||
useEffect(() => {
|
||||
if (first.current) {
|
||||
first.current = false;
|
||||
return;
|
||||
}
|
||||
dirty.current = true;
|
||||
const t = setTimeout(() => startPreview(async () => setPreview(await previewCampaign({ id: initial.id, name, subject, preheader, segment, blocks }))), 400);
|
||||
return () => clearTimeout(t);
|
||||
}, [name, subject, preheader, segment, blocks, initial.id]);
|
||||
|
||||
// Vor dem Verlassen mit ungespeicherten Änderungen warnen
|
||||
useEffect(() => {
|
||||
const onLeave = (e: BeforeUnloadEvent) => {
|
||||
if (dirty.current) e.preventDefault();
|
||||
};
|
||||
window.addEventListener("beforeunload", onLeave);
|
||||
return () => window.removeEventListener("beforeunload", onLeave);
|
||||
}, []);
|
||||
|
||||
const update = (i: number, b: CampaignBlock) => setBlocks((cur) => cur.map((x, j) => (j === i ? b : x)));
|
||||
const move = (i: number, d: number) =>
|
||||
setBlocks((cur) => {
|
||||
const j = i + d;
|
||||
if (j < 0 || j >= cur.length) return cur;
|
||||
const next = [...cur];
|
||||
[next[i], next[j]] = [next[j], next[i]];
|
||||
return next;
|
||||
});
|
||||
const remove = (i: number) => setBlocks((cur) => cur.filter((_, j) => j !== i));
|
||||
const add = (type: BlockType) => setBlocks((cur) => [...cur, newBlock(type)]);
|
||||
|
||||
const run = (fn: () => Promise<ActionResult>, after?: (r: ActionResult) => void) =>
|
||||
startBusy(async () => {
|
||||
const r = await fn();
|
||||
setMessage(r);
|
||||
after?.(r);
|
||||
});
|
||||
|
||||
const save = () => run(() => saveCampaign(data()), (r) => r?.ok && (dirty.current = false));
|
||||
const test = () => run(() => testCampaign(data(), testTo));
|
||||
const send = () =>
|
||||
run(
|
||||
() => scheduleCampaign(data(), mode === "later" ? when : ""),
|
||||
(r) => {
|
||||
setArmed(false);
|
||||
if (r?.ok) {
|
||||
dirty.current = false;
|
||||
window.location.reload();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const recipients = counts[segment];
|
||||
|
||||
return (
|
||||
<div className="ad-mailedit">
|
||||
<div className="ad-nl-editor">
|
||||
<section className="ad-card">
|
||||
<div className="ad-card__body">
|
||||
<label className="sm-field"><span className="sm-field__label">Name <span className="sm-optional">(nur für dich)</span></span><input className="sm-input" value={name} maxLength={120} onChange={(e) => setName(e.target.value)} /></label>
|
||||
<label className="sm-field"><span className="sm-field__label">Betreff</span><input className="sm-input" value={subject} maxLength={200} onChange={(e) => setSubject(e.target.value)} placeholder="z. B. Neu: die Reformer-Kollektion" /></label>
|
||||
<label className="sm-field"><span className="sm-field__label">Vorschautext <span className="sm-optional">(optional)</span></span><input className="sm-input" value={preheader} maxLength={200} onChange={(e) => setPreheader(e.target.value)} /><span className="sm-field__hint">Erscheint in vielen Postfächern neben dem Betreff.</span></label>
|
||||
<fieldset className="ad-scope">
|
||||
<legend className="sm-field__label">An wen?</legend>
|
||||
{(Object.keys(SEGMENTS) as Segment[]).map((k) => (
|
||||
<label key={k} className={`ad-scope__option${segment === k ? " is-active" : ""}`}>
|
||||
<input type="radio" name="segment" checked={segment === k} onChange={() => setSegment(k)} />
|
||||
<span><strong>{SEGMENTS[k].label} · {counts[k]}</strong><small>{SEGMENTS[k].hint}</small></span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{blocks.map((b, i) => (
|
||||
<section key={b.id} className="ad-card ad-nl-block">
|
||||
<div className="ad-nl-block__head">
|
||||
<strong>{BLOCK_LABELS[b.type]}</strong>
|
||||
<span className="ad-nl-block__tools">
|
||||
<button type="button" onClick={() => move(i, -1)} disabled={i === 0} aria-label="Nach oben" title="Nach oben"><Icon name="arrow" size="sm" className="ad-rot-up" /></button>
|
||||
<button type="button" onClick={() => move(i, 1)} disabled={i === blocks.length - 1} aria-label="Nach unten" title="Nach unten"><Icon name="arrow" size="sm" className="ad-rot-down" /></button>
|
||||
<button type="button" onClick={() => remove(i)} aria-label="Baustein entfernen" title="Entfernen"><Icon name="trash" size="sm" /></button>
|
||||
</span>
|
||||
</div>
|
||||
<div className="ad-nl-block__body">
|
||||
<BlockFields block={b} products={products} onChange={(nb) => update(i, nb)} />
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
<div className="ad-nl-add" role="group" aria-label="Baustein hinzufügen">
|
||||
<span className="body-sm ad-muted">Hinzufügen:</span>
|
||||
{(Object.keys(BLOCK_LABELS) as BlockType[]).map((t) => (
|
||||
<button key={t} type="button" className="sm-btn sm-btn--secondary sm-btn--sm" onClick={() => add(t)}><Icon name="plus" size="sm" /> {BLOCK_LABELS[t]}</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<section className="ad-card">
|
||||
<div className="ad-card__body">
|
||||
<h2 className="ad-nl-h">Testen und versenden</h2>
|
||||
<div className="ad-nl-test">
|
||||
<input className="sm-input" type="email" value={testTo} onChange={(e) => setTestTo(e.target.value)} aria-label="Testmail an" />
|
||||
<button className="sm-btn sm-btn--secondary" type="button" onClick={test} disabled={busy || !mailReady} title={mailReady ? "" : "Erst den Mail-Versand einrichten"}>Testmail senden</button>
|
||||
</div>
|
||||
<fieldset className="ad-scope" style={{ marginTop: "var(--space-4)" }}>
|
||||
<legend className="sm-field__label">Wann?</legend>
|
||||
<label className={`ad-scope__option${mode === "now" ? " is-active" : ""}`}>
|
||||
<input type="radio" checked={mode === "now"} onChange={() => setMode("now")} />
|
||||
<span><strong>Jetzt senden</strong><small>Startet sofort und läuft in Portionen</small></span>
|
||||
</label>
|
||||
<label className={`ad-scope__option${mode === "later" ? " is-active" : ""}`}>
|
||||
<input type="radio" checked={mode === "later"} onChange={() => setMode("later")} />
|
||||
<span><strong>Planen</strong><small>Zu einem festen Zeitpunkt (deutsche Zeit)</small></span>
|
||||
</label>
|
||||
</fieldset>
|
||||
{mode === "later" && (
|
||||
<label className="sm-field" style={{ marginTop: "var(--space-3)" }}><span className="sm-field__label">Zeitpunkt</span><input className="sm-input" type="datetime-local" value={when} onChange={(e) => setWhen(e.target.value)} /></label>
|
||||
)}
|
||||
<div style={{ marginTop: "var(--space-4)" }}>
|
||||
{armed ? (
|
||||
<span className="ad-nl-confirm">
|
||||
<span className="body-sm">{mode === "now" ? `Jetzt an ${recipients} Empfänger senden?` : `Für ${recipients} Empfänger planen?`}</span>
|
||||
<button type="button" className="sm-btn sm-btn--primary sm-btn--sm" onClick={send} disabled={busy}>Ja</button>
|
||||
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" onClick={() => setArmed(false)}>Nein</button>
|
||||
</span>
|
||||
) : (
|
||||
<button type="button" className="sm-btn sm-btn--primary" onClick={() => setArmed(true)} disabled={busy || !mailReady || !recipients || (mode === "later" && !when)}>
|
||||
{mode === "now" ? `An ${recipients} Empfänger senden` : scheduledFor ? "Neuen Zeitpunkt speichern" : "Versand planen"}
|
||||
</button>
|
||||
)}
|
||||
{!mailReady && <p className="ad-help" style={{ marginTop: "var(--space-2)" }}>Richte zuerst den Mail-Versand unter Verbindungen ein.</p>}
|
||||
{mailReady && !recipients && <p className="ad-help" style={{ marginTop: "var(--space-2)" }}>In dieser Zielgruppe gibt es noch keine bestätigten Abonnenten.</p>}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="ad-savebar">
|
||||
<span className="ad-savebar__msg" aria-live="polite"><Message state={message} /></span>
|
||||
<button className="sm-btn sm-btn--primary" type="button" onClick={save} disabled={busy}>{busy ? "Moment …" : "Speichern"}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="ad-card ad-mailedit__preview" aria-label="Vorschau">
|
||||
<div className="ad-card__head">
|
||||
<div>
|
||||
<h2>Vorschau</h2>
|
||||
<p>Betreff: <strong>{preview.subject || "–"}</strong></p>
|
||||
</div>
|
||||
<div className="ad-tabs" role="group" aria-label="Ansicht" style={{ flexWrap: "nowrap" }}>
|
||||
<button type="button" className={`ad-tab${device === "desktop" ? " is-active" : ""}`} onClick={() => setDevice("desktop")}>Computer</button>
|
||||
<button type="button" className={`ad-tab${device === "mobile" ? " is-active" : ""}`} onClick={() => setDevice("mobile")}>Handy</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ad-mailedit__frame">
|
||||
<iframe
|
||||
title="Vorschau des Newsletters"
|
||||
srcDoc={preview.html}
|
||||
sandbox="allow-same-origin"
|
||||
onLoad={(e) => {
|
||||
const f = e.currentTarget;
|
||||
const h = f.contentDocument?.documentElement.scrollHeight;
|
||||
if (h) f.style.height = `${h}px`;
|
||||
}}
|
||||
style={{ width: device === "mobile" ? 375 : "100%" }}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
8
src/instrumentation.ts
Normal file
8
src/instrumentation.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
// Läuft einmal beim Start des Servers: Takt für den Newsletter-Versand.
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
72
src/lib/campaign-blocks.ts
Normal file
72
src/lib/campaign-blocks.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// Bausteine einer Newsletter-Ausgabe. Wird im Editor (Browser) und beim Versand (Server) verwendet.
|
||||
|
||||
export type CampaignBlock =
|
||||
| { id: string; type: "heading"; text: string }
|
||||
| { id: string; type: "text"; text: string }
|
||||
| { id: string; type: "image"; url: string; alt: string; link: string }
|
||||
| { id: string; type: "button"; label: string; url: string }
|
||||
| { id: string; type: "products"; productIds: string[] }
|
||||
| { id: string; type: "divider" };
|
||||
|
||||
export type BlockType = CampaignBlock["type"];
|
||||
|
||||
export const BLOCK_LABELS: Record<BlockType, string> = {
|
||||
heading: "Überschrift",
|
||||
text: "Text",
|
||||
image: "Bild",
|
||||
button: "Button",
|
||||
products: "Produkte",
|
||||
divider: "Trennlinie",
|
||||
};
|
||||
|
||||
export type Segment = "all" | "customers" | "nonbuyers";
|
||||
|
||||
export const SEGMENTS: Record<Segment, { label: string; hint: string }> = {
|
||||
all: { label: "Alle Abonnenten", hint: "Jeder mit bestätigter Anmeldung" },
|
||||
customers: { label: "Nur Käufer", hint: "Abonnenten, die schon einmal bestellt haben" },
|
||||
nonbuyers: { label: "Noch nie gekauft", hint: "Abonnenten ohne bezahlte Bestellung" },
|
||||
};
|
||||
|
||||
export type CampaignStatus = "draft" | "scheduled" | "sending" | "sent" | "cancelled";
|
||||
|
||||
export const CAMPAIGN_STATUS: Record<CampaignStatus, { label: string; tone: "neutral" | "gold" | "success" | "danger" }> = {
|
||||
draft: { label: "Entwurf", tone: "neutral" },
|
||||
scheduled: { label: "Geplant", tone: "gold" },
|
||||
sending: { label: "Wird versendet", tone: "gold" },
|
||||
sent: { label: "Versendet", tone: "success" },
|
||||
cancelled: { label: "Abgebrochen", tone: "danger" },
|
||||
};
|
||||
|
||||
const str = (v: unknown, max = 5000) => (typeof v === "string" ? v.slice(0, max) : "");
|
||||
|
||||
/** Prüft und bereinigt Bausteine aus dem Browser oder der Datenbank. */
|
||||
export function cleanBlocks(input: unknown): CampaignBlock[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const out: CampaignBlock[] = [];
|
||||
for (const raw of input.slice(0, 60)) {
|
||||
if (!raw || typeof raw !== "object") continue;
|
||||
const b = raw as Record<string, unknown>;
|
||||
const id = str(b.id, 40) || Math.random().toString(36).slice(2, 10);
|
||||
switch (b.type) {
|
||||
case "heading":
|
||||
out.push({ id, type: "heading", text: str(b.text, 300) });
|
||||
break;
|
||||
case "text":
|
||||
out.push({ id, type: "text", text: str(b.text, 10000) });
|
||||
break;
|
||||
case "image":
|
||||
out.push({ id, type: "image", url: str(b.url, 1000), alt: str(b.alt, 300), link: str(b.link, 1000) });
|
||||
break;
|
||||
case "button":
|
||||
out.push({ id, type: "button", label: str(b.label, 80), url: str(b.url, 1000) });
|
||||
break;
|
||||
case "products":
|
||||
out.push({ id, type: "products", productIds: Array.isArray(b.productIds) ? b.productIds.filter((x): x is string => typeof x === "string").slice(0, 12) : [] });
|
||||
break;
|
||||
case "divider":
|
||||
out.push({ id, type: "divider" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
120
src/lib/campaign-sender.ts
Normal file
120
src/lib/campaign-sender.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import "server-only";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { NewsletterCampaign } from "@prisma/client";
|
||||
import { db } from "./db";
|
||||
import { appUrl } from "./social/config";
|
||||
import { getMailConfig, isMailReady } from "./mail/config";
|
||||
import { openSmtpSession } from "./mail/smtp";
|
||||
import { commonVars } from "./mail/send";
|
||||
import { cleanBlocks, type Segment } from "./campaign-blocks";
|
||||
import { collectLinks, getNewsletterSettings, loadProducts, namesFor, renderCampaign, segmentEmails } from "./campaigns";
|
||||
|
||||
const TICK_MS = 60_000;
|
||||
|
||||
/** Empfänger festhalten, Links für die Klickzählung merken und die Ausgabe auf „wird versendet“ setzen. */
|
||||
async function startCampaign(c: NewsletterCampaign) {
|
||||
const blocks = cleanBlocks(c.blocks);
|
||||
const emails = await segmentEmails(c.segment as Segment);
|
||||
const links = await collectLinks({ subject: c.subject, preheader: c.preheader, blocks }, await loadProducts(blocks));
|
||||
for (let i = 0; i < emails.length; i += 500) {
|
||||
await db.newsletterRecipient.createMany({
|
||||
data: emails.slice(i, i + 500).map((email) => ({ campaignId: c.id, email, token: randomBytes(18).toString("base64url") })),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
await db.newsletterCampaign.update({ where: { id: c.id }, data: { status: emails.length ? "sending" : "sent", startedAt: new Date(), finishedAt: emails.length ? null : new Date(), links, linkClicks: links.map(() => 0) } });
|
||||
}
|
||||
|
||||
/** Einen Schwung Mails der ältesten laufenden Ausgabe senden. */
|
||||
async function sendBatch() {
|
||||
const c = await db.newsletterCampaign.findFirst({ where: { status: "sending" }, orderBy: { startedAt: "asc" } });
|
||||
if (!c) return;
|
||||
const config = await getMailConfig();
|
||||
// Ohne Mailserver bleibt die Ausgabe stehen und läuft weiter, sobald er eingerichtet ist
|
||||
if (!isMailReady(config)) return;
|
||||
const settings = await getNewsletterSettings();
|
||||
const batch = await db.newsletterRecipient.findMany({ where: { campaignId: c.id, status: "pending" }, take: Math.max(1, Math.min(500, settings.perMinute)) });
|
||||
if (!batch.length) {
|
||||
await db.newsletterCampaign.update({ where: { id: c.id }, data: { status: "sent", finishedAt: new Date() } });
|
||||
return;
|
||||
}
|
||||
// Wer sich inzwischen abgemeldet hat, bekommt nichts mehr
|
||||
const still = new Set((await db.newsletterSubscriber.findMany({ where: { email: { in: batch.map((r) => r.email) }, confirmedAt: { not: null } }, select: { email: true } })).map((s) => s.email));
|
||||
const blocks = cleanBlocks(c.blocks);
|
||||
const products = await loadProducts(blocks);
|
||||
const names = await namesFor(batch.map((r) => r.email));
|
||||
const base = await commonVars();
|
||||
const url = appUrl();
|
||||
|
||||
let session: Awaited<ReturnType<typeof openSmtpSession>> | null = null;
|
||||
try {
|
||||
for (const r of batch) {
|
||||
if (!still.has(r.email)) {
|
||||
await db.newsletterRecipient.update({ where: { id: r.id }, data: { status: "skipped", error: "Inzwischen abgemeldet" } });
|
||||
continue;
|
||||
}
|
||||
const n = names.get(r.email);
|
||||
const unsubscribeUrl = `${url}/newsletter/abmelden?t=${r.token}`;
|
||||
const mail = await renderCampaign(
|
||||
{ subject: c.subject, preheader: c.preheader, blocks },
|
||||
{
|
||||
vars: { ...base, vorname: n?.firstName ?? "", nachname: n?.lastName ?? "", email: r.email },
|
||||
products,
|
||||
unsubscribeUrl,
|
||||
mapLink: settings.tracking ? (link) => (c.links.includes(link) ? `${url}/api/newsletter/c/${r.token}/${c.links.indexOf(link)}` : link) : undefined,
|
||||
pixelUrl: settings.tracking ? `${url}/api/newsletter/o/${r.token}` : undefined,
|
||||
},
|
||||
);
|
||||
const message = {
|
||||
from: { name: config.fromName, email: config.fromEmail },
|
||||
to: r.email,
|
||||
replyTo: config.replyTo || undefined,
|
||||
...mail,
|
||||
headers: { "List-Unsubscribe": `<${url}/api/newsletter/abmelden?t=${r.token}>`, "List-Unsubscribe-Post": "List-Unsubscribe=One-Click", Precedence: "bulk" },
|
||||
};
|
||||
try {
|
||||
session ??= await openSmtpSession(config);
|
||||
await session.send(message);
|
||||
await db.newsletterRecipient.update({ where: { id: r.id }, data: { status: "sent", sentAt: new Date(), error: "" } });
|
||||
} catch (e) {
|
||||
const error = (e instanceof Error ? e.message : String(e)).slice(0, 300);
|
||||
// Verbindung weg oder Anmeldung gescheitert: Rest beim nächsten Durchlauf erneut versuchen
|
||||
if (!session || /Verbindung|Zeitüberschreitung|Keine Antwort|Anmeldung|ECONN|socket/i.test(error)) {
|
||||
session?.close();
|
||||
session = null;
|
||||
console.error("Newsletter: Versand unterbrochen", error);
|
||||
break;
|
||||
}
|
||||
await db.newsletterRecipient.update({ where: { id: r.id }, data: { status: "failed", error } });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
session?.close();
|
||||
}
|
||||
const left = await db.newsletterRecipient.count({ where: { campaignId: c.id, status: "pending" } });
|
||||
if (!left) await db.newsletterCampaign.update({ where: { id: c.id }, data: { status: "sent", finishedAt: new Date() } });
|
||||
}
|
||||
|
||||
const state = globalThis as unknown as { newsletterBusy?: boolean; newsletterTimer?: NodeJS.Timeout };
|
||||
|
||||
/** Fällige Ausgaben starten und einen Schwung senden. Läuft nie doppelt. */
|
||||
export async function processNewsletterQueue() {
|
||||
if (state.newsletterBusy) return;
|
||||
state.newsletterBusy = true;
|
||||
try {
|
||||
const due = await db.newsletterCampaign.findMany({ where: { status: "scheduled", scheduledAt: { lte: new Date() } } });
|
||||
for (const c of due) await startCampaign(c);
|
||||
await sendBatch();
|
||||
} catch (e) {
|
||||
console.error("Newsletter-Versand fehlgeschlagen", e);
|
||||
} finally {
|
||||
state.newsletterBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Startet beim Hochfahren des Servers den Takt für geplante und laufende Ausgaben (einmal pro Minute). */
|
||||
export function startNewsletterTimer() {
|
||||
if (state.newsletterTimer) return;
|
||||
state.newsletterTimer = setInterval(() => void processNewsletterQueue(), TICK_MS);
|
||||
state.newsletterTimer.unref?.();
|
||||
}
|
||||
171
src/lib/campaigns.ts
Normal file
171
src/lib/campaigns.ts
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
import "server-only";
|
||||
import { db } from "./db";
|
||||
import { formatPrice } from "./money";
|
||||
import { withSales } from "./sales";
|
||||
import { appUrl } from "./social/config";
|
||||
import { getBrand, commonVars } from "./mail/send";
|
||||
import { C, SANS, SERIF, esc, layout, renderBody, renderSubject, type MailVars } from "./mail/render";
|
||||
import type { CampaignBlock, Segment } from "./campaign-blocks";
|
||||
|
||||
// ---------- Einstellungen ----------
|
||||
|
||||
export type NewsletterSettings = {
|
||||
// So viele Mails pro Minute; Anbieter begrenzen den Versand pro Stunde oder Tag
|
||||
perMinute: number;
|
||||
// Öffnungen (Zählpixel) und Klicks messen
|
||||
tracking: boolean;
|
||||
};
|
||||
|
||||
const SETTINGS_KEY = "newsletter";
|
||||
const DEFAULTS: NewsletterSettings = { perMinute: 20, tracking: true };
|
||||
|
||||
export async function getNewsletterSettings(): Promise<NewsletterSettings> {
|
||||
const row = await db.setting.findUnique({ where: { key: SETTINGS_KEY } });
|
||||
return { ...DEFAULTS, ...((row?.value ?? {}) as Partial<NewsletterSettings>) };
|
||||
}
|
||||
|
||||
export async function saveNewsletterSettings(value: NewsletterSettings) {
|
||||
await db.setting.upsert({ where: { key: SETTINGS_KEY }, create: { key: SETTINGS_KEY, value }, update: { value } });
|
||||
}
|
||||
|
||||
// ---------- Empfänger ----------
|
||||
|
||||
const BOUGHT = ["PAID", "PROCESSING", "SHIPPED", "COMPLETED"] as const;
|
||||
|
||||
/** Bestätigte Abonnenten einer Zielgruppe. */
|
||||
export async function segmentEmails(segment: Segment): Promise<string[]> {
|
||||
const subs = await db.newsletterSubscriber.findMany({ where: { confirmedAt: { not: null } }, select: { email: true }, orderBy: { createdAt: "asc" } });
|
||||
if (segment === "all") return subs.map((s) => s.email);
|
||||
const buyers = await db.order.findMany({ where: { status: { in: [...BOUGHT] } }, select: { email: true }, distinct: ["email"] });
|
||||
const set = new Set(buyers.map((b) => b.email.toLowerCase()));
|
||||
return subs.map((s) => s.email).filter((e) => (segment === "customers" ? set.has(e.toLowerCase()) : !set.has(e.toLowerCase())));
|
||||
}
|
||||
|
||||
export async function segmentCounts(): Promise<Record<Segment, number>> {
|
||||
const [all, customers] = await Promise.all([segmentEmails("all"), segmentEmails("customers")]);
|
||||
return { all: all.length, customers: customers.length, nonbuyers: all.length - customers.length };
|
||||
}
|
||||
|
||||
/** Vor- und Nachname, falls die Adresse zu einem Kundenkonto gehört. */
|
||||
export async function namesFor(emails: string[]) {
|
||||
const users = await db.user.findMany({ where: { email: { in: emails } }, select: { email: true, firstName: true, lastName: true } });
|
||||
return new Map(users.map((u) => [u.email, u]));
|
||||
}
|
||||
|
||||
// ---------- Darstellung ----------
|
||||
|
||||
type ProductCard = { id: string; name: string; subtitle: string; slug: string; image: string; price: number; compareAtPrice: number | null };
|
||||
|
||||
export async function loadProducts(blocks: CampaignBlock[]): Promise<Map<string, ProductCard>> {
|
||||
const ids = [...new Set(blocks.flatMap((b) => (b.type === "products" ? b.productIds : [])))];
|
||||
if (!ids.length) return new Map();
|
||||
const rows = await db.product.findMany({ where: { id: { in: ids }, active: true }, include: { variants: { select: { price: true } } } });
|
||||
const priced = await withSales(rows);
|
||||
return new Map(
|
||||
priced.map((p) => {
|
||||
// Ab-Preis bei Varianten: der günstigste
|
||||
const cheapest = p.variants.length ? p.variants.reduce((a, v) => ((v.price ?? p.price) < (a.price ?? p.price) ? v : a)) : null;
|
||||
const price = cheapest?.price ?? p.price;
|
||||
const compare = cheapest ? cheapest.compareAtPrice : p.compareAtPrice;
|
||||
return [p.id, { id: p.id, name: p.name, subtitle: p.subtitle, slug: p.slug, image: p.images[0] ?? "", price, compareAtPrice: compare && compare > price ? compare : null }];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const abs = (url: string) => (url.startsWith("/") ? `${appUrl()}${url}` : url);
|
||||
|
||||
function productsHtml(ids: string[], products: Map<string, ProductCard>) {
|
||||
const list = ids.map((id) => products.get(id)).filter((p): p is ProductCard => Boolean(p));
|
||||
if (!list.length) return { html: "", text: "" };
|
||||
const cell = (p: ProductCard) => {
|
||||
const href = esc(`${appUrl()}/produkt/${p.slug}`);
|
||||
const price = p.compareAtPrice
|
||||
? `<span style="color:${C.subtle};text-decoration:line-through;">${formatPrice(p.compareAtPrice)}</span> <span style="color:${C.goldDeep};font-weight:600;">${formatPrice(p.price)}</span>`
|
||||
: formatPrice(p.price);
|
||||
return `<td width="50%" valign="top" style="padding:0 8px 20px;">
|
||||
<a href="${href}" style="text-decoration:none;color:${C.ink};">
|
||||
${p.image ? `<img src="${esc(abs(p.image))}" width="250" alt="${esc(p.name)}" style="display:block;width:100%;max-width:250px;height:auto;border:0;background:${C.bg};margin:0 0 10px;">` : ""}
|
||||
<span style="display:block;font-family:${SERIF};font-size:19px;line-height:24px;color:${C.ink};">${esc(p.name)}</span>
|
||||
${p.subtitle ? `<span style="display:block;font-family:${SANS};font-size:12px;line-height:18px;color:${C.subtle};">${esc(p.subtitle)}</span>` : ""}
|
||||
<span style="display:block;font-family:${SANS};font-size:14px;line-height:22px;margin-top:4px;color:${C.ink};">${price}</span>
|
||||
</a></td>`;
|
||||
};
|
||||
const rows: string[] = [];
|
||||
for (let i = 0; i < list.length; i += 2) {
|
||||
const pair = list.slice(i, i + 2);
|
||||
rows.push(`<tr>${pair.map(cell).join("")}${pair.length === 1 ? '<td width="50%"></td>' : ""}</tr>`);
|
||||
}
|
||||
return {
|
||||
html: `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin:8px -8px 4px;width:calc(100% + 16px);">${rows.join("")}</table>`,
|
||||
text: list.map((p) => `${p.name}, ${formatPrice(p.price)}: ${appUrl()}/produkt/${p.slug}`).join("\n"),
|
||||
};
|
||||
}
|
||||
|
||||
function blockHtml(b: CampaignBlock, vars: MailVars, products: Map<string, ProductCard>) {
|
||||
switch (b.type) {
|
||||
case "heading":
|
||||
return b.text.trim() ? renderBody(`## ${b.text.replace(/\n/g, " ")}`, vars) : null;
|
||||
case "text":
|
||||
return b.text.trim() ? renderBody(b.text, vars) : null;
|
||||
case "button":
|
||||
return b.label.trim() && b.url.trim() ? renderBody(`[${b.label.replace(/[[\]]/g, "")}](${b.url.trim()})`, vars) : null;
|
||||
case "image": {
|
||||
if (!b.url) return null;
|
||||
const img = `<img src="${esc(abs(b.url))}" width="528" alt="${esc(b.alt)}" style="display:block;width:100%;height:auto;border:0;margin:0 0 20px;">`;
|
||||
const link = b.link.trim() ? renderSubject(b.link, vars) : "";
|
||||
return { html: link && /^https?:|^\//.test(link) ? `<a href="${esc(abs(link))}">${img}</a>` : img, text: b.alt ? `[${b.alt}]` : "" };
|
||||
}
|
||||
case "products":
|
||||
return productsHtml(b.productIds, products);
|
||||
case "divider":
|
||||
return { html: `<hr style="border:0;border-top:1px solid ${C.line};margin:24px 0;">`, text: "———" };
|
||||
}
|
||||
}
|
||||
|
||||
export type RenderOpts = {
|
||||
vars: MailVars;
|
||||
products: Map<string, ProductCard>;
|
||||
// Ersetzt jede Link-Adresse im Inhalt, z. B. durch die Klickzählung
|
||||
mapLink?: (url: string) => string;
|
||||
unsubscribeUrl: string;
|
||||
pixelUrl?: string;
|
||||
};
|
||||
|
||||
const unescapeHref = (s: string) => s.replace(/&/g, "&").replace(/"/g, '"');
|
||||
|
||||
/** Eine Ausgabe für einen Empfänger zusammensetzen. */
|
||||
export async function renderCampaign(c: { subject: string; preheader: string; blocks: CampaignBlock[] }, o: RenderOpts) {
|
||||
const brand = await getBrand();
|
||||
// Ohne bekannten Vornamen „Hallo {{vorname}},“ zu „Hallo,“ statt „Hallo ,“
|
||||
const blocks = o.vars.vorname ? c.blocks : c.blocks.map((b) => (b.type === "text" || b.type === "heading" ? { ...b, text: b.text.replace(/\s*\{\{\s*vorname\s*\}\}/g, "") } : b));
|
||||
const parts = blocks.map((b) => blockHtml(b, o.vars, o.products)).filter((x): x is { html: string; text: string } => Boolean(x?.html));
|
||||
// Links wie /shop gelten im Mailprogramm nicht, daher immer mit voller Adresse
|
||||
let content = parts.map((p) => p.html).join("\n").replace(/href="\/(?!\/)/g, `href="${appUrl()}/`);
|
||||
if (o.mapLink) content = content.replace(/href="([^"]+)"/g, (_, h: string) => `href="${esc(o.mapLink!(unescapeHref(h)))}"`);
|
||||
if (o.pixelUrl) content += `<img src="${esc(o.pixelUrl)}" width="1" height="1" alt="" style="display:block;border:0;width:1px;height:1px;">`;
|
||||
const footer = `<br><br>Du bekommst diese Mail, weil du dich für den Newsletter von ${esc(brand.shopName)} angemeldet hast.<br><a href="${esc(o.unsubscribeUrl)}" style="color:${C.subtle};text-decoration:underline;">Newsletter abbestellen</a>`;
|
||||
const subject = renderSubject(c.subject, o.vars);
|
||||
const html = layout(content, brand, c.preheader ? renderSubject(c.preheader, o.vars) : subject, footer);
|
||||
const text = `${parts.map((p) => p.text.replace(/: \/(?!\/)/g, `: ${appUrl()}/`)).filter(Boolean).join("\n\n")}\n\n--\n${brand.footerLines.join("\n")}\nNewsletter abbestellen: ${o.unsubscribeUrl}`;
|
||||
return { subject, html, text };
|
||||
}
|
||||
|
||||
/** Alle Links im Inhalt in der Reihenfolge ihres Auftretens, für die Klickzählung. */
|
||||
export async function collectLinks(c: { subject: string; preheader: string; blocks: CampaignBlock[] }, products: Map<string, ProductCard>) {
|
||||
const links: string[] = [];
|
||||
await renderCampaign(c, {
|
||||
vars: await commonVars(),
|
||||
products,
|
||||
unsubscribeUrl: "",
|
||||
mapLink: (url) => {
|
||||
if (!links.includes(url)) links.push(url);
|
||||
return url;
|
||||
},
|
||||
});
|
||||
return links;
|
||||
}
|
||||
|
||||
/** Beispieldaten für Vorschau und Testmail. */
|
||||
export async function sampleNewsletterVars(name = { firstName: "Marie", lastName: "Keller" }, email = "marie@beispiel.de"): Promise<MailVars> {
|
||||
return { ...(await commonVars()), vorname: name.firstName, nachname: name.lastName, email };
|
||||
}
|
||||
|
|
@ -18,6 +18,7 @@ export async function deleteCustomerAccount(id: string) {
|
|||
await unsubscribe(user.email);
|
||||
// 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 } });
|
||||
// Sitzungen, Social-Logins, Reset-Links und Adressen hängen per Cascade am Konto
|
||||
await db.user.delete({ where: { id } });
|
||||
return { email: user.email };
|
||||
|
|
|
|||
|
|
@ -4,9 +4,9 @@ export type RichValue = { html: string; text: string };
|
|||
export type MailVars = Record<string, string | RichValue>;
|
||||
export type Brand = { shopName: string; shopUrl: string; logoUrl: string; footerLines: string[] };
|
||||
|
||||
const C = { bg: "#f7f4ee", card: "#ffffff", ink: "#161411", muted: "#5d574d", subtle: "#7d766b", line: "#e2dbcd", gold: "#c6a24c", goldDeep: "#7a5e1a" };
|
||||
const SANS = "Jost, 'Avenir Next', 'Segoe UI', Helvetica, Arial, sans-serif";
|
||||
const SERIF = "'Cormorant Garamond', Georgia, 'Times New Roman', serif";
|
||||
export const C = { bg: "#f7f4ee", card: "#ffffff", ink: "#161411", muted: "#5d574d", subtle: "#7d766b", line: "#e2dbcd", gold: "#c6a24c", goldDeep: "#7a5e1a" };
|
||||
export const SANS = "Jost, 'Avenir Next', 'Segoe UI', Helvetica, Arial, sans-serif";
|
||||
export const SERIF = "'Cormorant Garamond', Georgia, 'Times New Roman', serif";
|
||||
|
||||
export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
|
|
@ -52,7 +52,7 @@ function inlineText(src: string, vars: MailVars) {
|
|||
return fillText(src, vars).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, "$1: $2").replace(/\*\*([^*]+)\*\*/g, "$1");
|
||||
}
|
||||
|
||||
function button(label: string, href: string) {
|
||||
export function button(label: string, href: string) {
|
||||
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:8px 0 24px;"><tr><td style="background:${C.ink};border-radius:2px;">
|
||||
<a href="${esc(href)}" style="display:inline-block;padding:14px 28px;font-family:${SANS};font-size:13px;font-weight:600;letter-spacing:0.12em;text-transform:uppercase;color:#ffffff;text-decoration:none;">${label}</a>
|
||||
</td></tr></table>`;
|
||||
|
|
@ -103,7 +103,7 @@ export function renderBody(body: string, vars: MailVars) {
|
|||
return { html: html.join("\n"), text: text.join("\n\n") };
|
||||
}
|
||||
|
||||
export function layout(content: string, brand: Brand, preheader = "") {
|
||||
export function layout(content: string, brand: Brand, preheader = "", footerHtml = "") {
|
||||
return `<!doctype html>
|
||||
<html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>${esc(brand.shopName)}</title></head>
|
||||
<body style="margin:0;padding:0;background:${C.bg};">
|
||||
|
|
@ -119,7 +119,7 @@ export function layout(content: string, brand: Brand, preheader = "") {
|
|||
${content}
|
||||
</td></tr>
|
||||
<tr><td align="center" style="padding:24px 12px 0;font-family:${SANS};font-size:12px;line-height:18px;color:${C.subtle};">
|
||||
${brand.footerLines.map(esc).join("<br>")}
|
||||
${brand.footerLines.map(esc).join("<br>")}${footerHtml}
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ export type MailMessage = {
|
|||
subject: string;
|
||||
html: string;
|
||||
text: string;
|
||||
// Zusätzliche Kopfzeilen, z. B. List-Unsubscribe beim Newsletter
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
const TIMEOUT = 20_000;
|
||||
|
|
@ -186,6 +188,7 @@ export function buildMime(m: MailMessage) {
|
|||
`Subject: ${encodeWord(oneLine(m.subject))}`,
|
||||
`Date: ${new Date().toUTCString().replace("GMT", "+0000")}`,
|
||||
`Message-ID: <${randomBytes(16).toString("hex")}@${domain}>`,
|
||||
...Object.entries(m.headers ?? {}).map(([k, v]) => `${k.replace(/[^A-Za-z0-9-]/g, "")}: ${oneLine(v)}`),
|
||||
"MIME-Version: 1.0",
|
||||
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
||||
];
|
||||
|
|
@ -207,16 +210,39 @@ export function buildMime(m: MailMessage) {
|
|||
].join("\r\n");
|
||||
}
|
||||
|
||||
async function deliver(c: SmtpConnection, m: MailMessage) {
|
||||
await c.cmd(`MAIL FROM:<${m.from.email}>`, [250]);
|
||||
await c.cmd(`RCPT TO:<${m.to}>`, [250, 251]);
|
||||
await c.cmd("DATA", [354]);
|
||||
// Zeilen, die mit einem Punkt beginnen, verdoppeln (Dot-Stuffing); base64 enthält ohnehin keine
|
||||
const data = buildMime(m).replace(/^\./gm, "..");
|
||||
await c.cmd(`${data}\r\n.`, [250]);
|
||||
}
|
||||
|
||||
export async function sendSmtp(o: SmtpOptions, m: MailMessage) {
|
||||
const c = await open(o);
|
||||
try {
|
||||
await c.cmd(`MAIL FROM:<${m.from.email}>`, [250]);
|
||||
await c.cmd(`RCPT TO:<${m.to}>`, [250, 251]);
|
||||
await c.cmd("DATA", [354]);
|
||||
// Zeilen, die mit einem Punkt beginnen, verdoppeln (Dot-Stuffing); base64 enthält ohnehin keine
|
||||
const data = buildMime(m).replace(/^\./gm, "..");
|
||||
await c.cmd(`${data}\r\n.`, [250]);
|
||||
await deliver(c, m);
|
||||
} finally {
|
||||
c.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Verbindung für viele Mails (Newsletter). Nach einer abgelehnten Adresse setzt RSET
|
||||
* den Zustand zurück, damit die nächste Mail über dieselbe Verbindung geht.
|
||||
*/
|
||||
export async function openSmtpSession(o: SmtpOptions) {
|
||||
const c = await open(o);
|
||||
return {
|
||||
async send(m: MailMessage) {
|
||||
try {
|
||||
await deliver(c, m);
|
||||
} catch (e) {
|
||||
await c.cmd("RSET", [250]).catch(() => undefined);
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
close: () => c.close(),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,4 +26,14 @@ export async function confirm(token: string) {
|
|||
|
||||
export async function unsubscribe(email: string) {
|
||||
await db.newsletterSubscriber.deleteMany({ where: { email } });
|
||||
await db.user.updateMany({ where: { email, newsletter: true }, data: { newsletter: false } });
|
||||
}
|
||||
|
||||
/** Abmelden über den Link in einer Newsletter-Mail. Gibt die Adresse zurück oder null bei ungültigem Link. */
|
||||
export async function unsubscribeByToken(token: string) {
|
||||
const r = await db.newsletterRecipient.findUnique({ where: { token } });
|
||||
if (!r) return null;
|
||||
await unsubscribe(r.email);
|
||||
if (!r.unsubscribedAt) await db.newsletterRecipient.update({ where: { id: r.id }, data: { unsubscribedAt: new Date() } });
|
||||
return r.email;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ export const PERMISSION_GROUPS = [
|
|||
{ key: "customers.delete", label: "Kundenkonten löschen" },
|
||||
{ key: "coupons.edit", label: "Gutscheine und Sales verwalten" },
|
||||
{ key: "newsletter.view", label: "Newsletter-Anmeldungen ansehen" },
|
||||
{ key: "newsletter.send", label: "Newsletter gestalten, versenden und Abonnenten entfernen" },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
|
|||
|
|
@ -252,3 +252,31 @@ a.ad-kpi:hover { border-color: var(--line-strong); }
|
|||
.ad-theme-btn { display: inline-grid; place-items: center; width: 36px; height: 36px; margin: -6px 0 -6px -8px; border: 0; border-radius: 50%; background: none; cursor: pointer; }
|
||||
.ad-theme-btn:hover { background: var(--surface-sunken); }
|
||||
.ad-theme-btn svg { width: 18px; height: 18px; }
|
||||
|
||||
/* Newsletter */
|
||||
.ad-wrap--wide { max-width: 1440px; }
|
||||
.ad-nl-editor { display: grid; gap: var(--space-4); min-width: 0; }
|
||||
.ad-nl-editor .ad-savebar { margin-top: 0; }
|
||||
.ad-nl-block__head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); padding: var(--space-3) var(--space-5); border-bottom: var(--hairline) solid var(--line); }
|
||||
.ad-nl-block__head strong { font-size: 13px; font-weight: 500; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-muted); }
|
||||
.ad-nl-block__tools { display: inline-flex; gap: 2px; }
|
||||
.ad-nl-block__tools button { display: inline-grid; place-items: center; width: 32px; height: 32px; border: 0; border-radius: var(--radius-sm, 4px); background: transparent; color: var(--ink-muted); cursor: pointer; }
|
||||
.ad-nl-block__tools button:hover:not(:disabled) { background: var(--surface); color: var(--ink); }
|
||||
.ad-nl-block__tools button:disabled { opacity: 0.3; cursor: default; }
|
||||
.ad-nl-block__body { padding: var(--space-4) var(--space-5); }
|
||||
.ad-nl-block__body .sm-field:first-child { margin-top: 0; }
|
||||
.ad-rot-up { transform: rotate(-90deg); }
|
||||
.ad-rot-down { transform: rotate(90deg); }
|
||||
.ad-nl-fields { display: grid; gap: var(--space-3); }
|
||||
.ad-nl-fields .sm-field { margin: 0; }
|
||||
.ad-nl-image { display: flex; align-items: center; gap: var(--space-4); flex-wrap: wrap; }
|
||||
.ad-nl-image img { max-width: 220px; max-height: 140px; border-radius: var(--radius-sm, 4px); border: var(--hairline) solid var(--line); object-fit: cover; }
|
||||
.ad-nl-thumb { width: 40px; height: 40px; flex: none; object-fit: cover; border-radius: 3px; background: var(--surface); }
|
||||
.ad-nl-add { display: flex; flex-wrap: wrap; gap: var(--space-2); align-items: center; padding: var(--space-3) var(--space-4); border: 1px dashed var(--line-strong); border-radius: var(--radius-md); }
|
||||
.ad-nl-add .sm-btn { gap: 6px; }
|
||||
.ad-nl-h { font-family: var(--font-serif); font-size: 22px; font-weight: 500; margin: 0 0 var(--space-4); }
|
||||
.ad-nl-test { display: flex; gap: var(--space-3); flex-wrap: wrap; }
|
||||
.ad-nl-test .sm-input { flex: 1 1 220px; }
|
||||
.ad-nl-confirm { display: inline-flex; gap: var(--space-2); align-items: center; flex-wrap: wrap; }
|
||||
.ad-nl-progress { height: 8px; border-radius: 4px; background: var(--surface); overflow: hidden; }
|
||||
.ad-nl-progress span { display: block; height: 100%; background: var(--gold); transition: width 0.4s; }
|
||||
|
|
|
|||
Loading…
Reference in a new issue