diff --git a/prisma/migrations/20261019200000_mail/migration.sql b/prisma/migrations/20261019200000_mail/migration.sql new file mode 100644 index 0000000..e17ff21 --- /dev/null +++ b/prisma/migrations/20261019200000_mail/migration.sql @@ -0,0 +1,61 @@ +-- AlterTable +ALTER TABLE "Invoice" ADD COLUMN "accessToken" TEXT NOT NULL DEFAULT ''; + +-- AlterTable +ALTER TABLE "NewsletterSubscriber" ADD COLUMN "confirmedAt" TIMESTAMP(3), +ADD COLUMN "token" TEXT; + +-- CreateTable +CREATE TABLE "EmailTemplate" ( + "key" TEXT NOT NULL, + "subject" TEXT NOT NULL, + "body" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "EmailTemplate_pkey" PRIMARY KEY ("key") +); + +-- CreateTable +CREATE TABLE "EmailLog" ( + "id" TEXT NOT NULL, + "to" TEXT NOT NULL, + "subject" TEXT NOT NULL, + "templateKey" TEXT NOT NULL, + "orderId" TEXT, + "ok" BOOLEAN NOT NULL, + "error" TEXT NOT NULL DEFAULT '', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "EmailLog_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "PasswordReset" ( + "tokenHash" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "expiresAt" TIMESTAMP(3) NOT NULL, + "usedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "PasswordReset_pkey" PRIMARY KEY ("tokenHash") +); + +-- CreateIndex +CREATE INDEX "EmailLog_orderId_idx" ON "EmailLog"("orderId"); + +-- CreateIndex +CREATE INDEX "EmailLog_createdAt_idx" ON "EmailLog"("createdAt"); + +-- CreateIndex +CREATE UNIQUE INDEX "NewsletterSubscriber_token_key" ON "NewsletterSubscriber"("token"); + +-- AddForeignKey +ALTER TABLE "PasswordReset" ADD CONSTRAINT "PasswordReset_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + + +-- Bisherige Anmeldungen gelten als bestätigt (vor Einführung des Double-Opt-in) +UPDATE "NewsletterSubscriber" SET "confirmedAt" = "createdAt" WHERE "confirmedAt" IS NULL; + +-- Bestehende Rechnungen bekommen einen Zugangsschlüssel +UPDATE "Invoice" SET "accessToken" = md5(random()::text || id) WHERE "accessToken" = ''; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index daec6c5..f3e7ff4 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -23,24 +23,25 @@ model Role { } model User { - id String @id @default(cuid()) - email String @unique + id String @id @default(cuid()) + email String @unique passwordHash String - firstName String @default("") - lastName String @default("") - phone String @default("") + firstName String @default("") + lastName String @default("") + phone String @default("") // Ohne Rolle ist ein Benutzer ein Kunde ohne Admin-Zugang roleId String? - role Role? @relation(fields: [roleId], references: [id], onDelete: SetNull) - active Boolean @default(true) - newsletter Boolean @default(false) + role Role? @relation(fields: [roleId], references: [id], onDelete: SetNull) + active Boolean @default(true) + newsletter Boolean @default(false) lastLoginAt DateTime? sessions Session[] identities UserIdentity[] + resets PasswordReset[] orders Order[] addresses Address[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } // Verknüpfte Anmeldungen über Google oder Apple. Konten nur mit dieser Anmeldung haben passwordHash "". @@ -69,70 +70,70 @@ model Session { } model Address { - id String @id @default(cuid()) - userId String - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - firstName String - lastName String - company String @default("") - street String - extra String @default("") - zip String - city String - country String @default("DE") - isDefault Boolean @default(false) + id String @id @default(cuid()) + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + firstName String + lastName String + company String @default("") + street String + extra String @default("") + zip String + city String + country String @default("DE") + isDefault Boolean @default(false) } // ---------- Katalog ---------- model Category { - id String @id @default(cuid()) + id String @id @default(cuid()) name String - slug String @unique - description String @default("") - image String @default("") - sort Int @default(0) - active Boolean @default(true) - showOnHome Boolean @default(true) + slug String @unique + description String @default("") + image String @default("") + sort Int @default(0) + active Boolean @default(true) + showOnHome Boolean @default(true) products Product[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } model Product { - id String @id @default(cuid()) + id String @id @default(cuid()) name String - slug String @unique - subtitle String @default("") // z. B. "Anthrazit · 8 mm" - description String @default("") - details String @default("") // Material & Pflege - sku String @default("") + slug String @unique + subtitle String @default("") // z. B. "Anthrazit · 8 mm" + description String @default("") + details String @default("") // Material & Pflege + sku String @default("") // Versandgewicht in Gramm, für DHL-Labels (0 = unbekannt) - weight Int @default(0) + weight Int @default(0) // Preise in Cent, brutto price Int compareAtPrice Int? - taxRate Int @default(19) - stock Int @default(0) - trackStock Boolean @default(true) - active Boolean @default(true) - featured Boolean @default(false) - badge String @default("") // "", "new", "best" + taxRate Int @default(19) + stock Int @default(0) + trackStock Boolean @default(true) + active Boolean @default(true) + featured Boolean @default(false) + badge String @default("") // "", "new", "best" images String[] - sort Int @default(0) + sort Int @default(0) categoryId String? - category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull) + category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull) variants ProductVariant[] orderItems OrderItem[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } model ProductVariant { id String @id @default(cuid()) productId String 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("") // Preis in Cent; leer = Produktpreis price Int? @@ -143,13 +144,13 @@ model ProductVariant { // ---------- Bestellungen ---------- enum OrderStatus { - PENDING // angelegt, Zahlung offen - PAID // bezahlt - PROCESSING // in Bearbeitung - SHIPPED // versendet - COMPLETED // abgeschlossen - CANCELLED // storniert - REFUNDED // erstattet + PENDING // angelegt, Zahlung offen + PAID // bezahlt + PROCESSING // in Bearbeitung + SHIPPED // versendet + COMPLETED // abgeschlossen + CANCELLED // storniert + REFUNDED // erstattet } enum PaymentStatus { @@ -212,18 +213,20 @@ model OrderItem { // Rechnungen und Stornorechnungen. `data` ist eine unveränderliche Momentaufnahme // (Verkäufer, Käufer, Positionen, Steuern) vom Zeitpunkt der Erstellung. model Invoice { - id String @id @default(cuid()) - number String @unique + id String @id @default(cuid()) + number String @unique // "invoice" = Rechnung, "credit" = Stornorechnung - kind String @default("invoice") - orderId String - order Order @relation(fields: [orderId], references: [id], onDelete: Restrict) + kind String @default("invoice") + orderId String + order Order @relation(fields: [orderId], references: [id], onDelete: Restrict) // Bei Stornorechnungen: die stornierte Rechnung - cancelsId String? - total Int - data Json - createdBy String @default("System") - createdAt DateTime @default(now()) + cancelsId String? + total Int + data Json + createdBy String @default("System") + // Geheimer Teil des Links, mit dem Kunden die Rechnung ohne Anmeldung öffnen (z. B. aus der E-Mail) + accessToken String @default("") + createdAt DateTime @default(now()) @@index([orderId]) } @@ -246,59 +249,59 @@ model OrderEvent { // ---------- Konfiguration ---------- model PaymentMethod { - id String @id @default(cuid()) + id String @id @default(cuid()) // stripe_card, stripe_sepa, stripe_klarna, paypal, prepayment, invoice, cod - code String @unique - name String - description String @default("") - enabled Boolean @default(false) - sort Int @default(0) + code String @unique + name String + description String @default("") + enabled Boolean @default(false) + sort Int @default(0) // Gebühr in Cent - fee Int @default(0) + fee Int @default(0) // Mindest- und Höchstbestellwert in Cent (0 = keine Grenze) - minTotal Int @default(0) - maxTotal Int @default(0) + minTotal Int @default(0) + maxTotal Int @default(0) // Nur für angemeldete Kunden (z. B. Rechnung) loggedInOnly Boolean @default(false) // Anbieter-spezifisch: Schlüssel, Testmodus, Bankdaten, Zahlungsziel … - config Json @default("{}") + config Json @default("{}") } model ShippingMethod { - id String @id @default(cuid()) + id String @id @default(cuid()) name String - description String @default("") + description String @default("") price Int // Ab diesem Warenwert kostenlos (0 = nie) - freeFrom Int @default(0) + freeFrom Int @default(0) countries String[] @default(["DE"]) - enabled Boolean @default(true) - sort Int @default(0) + enabled Boolean @default(true) + sort Int @default(0) } model Coupon { - id String @id @default(cuid()) - code String @unique + id String @id @default(cuid()) + code String @unique // "percent" oder "fixed" - type String @default("percent") - value Int // Prozent oder Cent - minTotal Int @default(0) - maxUses Int @default(0) - usedCount Int @default(0) - active Boolean @default(true) + type String @default("percent") + value Int // Prozent oder Cent + minTotal Int @default(0) + maxUses Int @default(0) + usedCount Int @default(0) + active Boolean @default(true) validUntil DateTime? - createdAt DateTime @default(now()) + createdAt DateTime @default(now()) } model Page { - id String @id @default(cuid()) - slug String @unique - title String - content String @default("") - published Boolean @default(true) - showInFooter String @default("") // "", "service", "company", "legal" - sort Int @default(0) - updatedAt DateTime @updatedAt + id String @id @default(cuid()) + slug String @unique + title String + content String @default("") + published Boolean @default(true) + showInFooter String @default("") // "", "service", "company", "legal" + sort Int @default(0) + updatedAt DateTime @updatedAt } model Setting { @@ -308,9 +311,45 @@ model Setting { } model NewsletterSubscriber { - id String @id @default(cuid()) - email String @unique - createdAt DateTime @default(now()) + id String @id @default(cuid()) + email String @unique + // Double-Opt-in: erst nach Klick auf den Link in der Bestätigungsmail gesetzt + confirmedAt DateTime? + token String? @unique + createdAt DateTime @default(now()) +} + +// Im Admin bearbeitete E-Mail-Vorlagen. Fehlt ein Eintrag, gilt die eingebaute Vorlage. +model EmailTemplate { + key String @id + subject String + body String + enabled Boolean @default(true) + updatedAt DateTime @updatedAt +} + +model EmailLog { + id String @id @default(cuid()) + to String + subject String + templateKey String + orderId String? + ok Boolean + error String @default("") + createdAt DateTime @default(now()) + + @@index([orderId]) + @@index([createdAt]) +} + +// Links zum Festlegen eines neuen Passworts (Passwort vergessen, Team-Einladung) +model PasswordReset { + tokenHash String @id + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + expiresAt DateTime + usedAt DateTime? + createdAt DateTime @default(now()) } model AuditLog { diff --git a/src/app/(shop)/actions.ts b/src/app/(shop)/actions.ts index 83ee9d4..c4b76db 100644 --- a/src/app/(shop)/actions.ts +++ b/src/app/(shop)/actions.ts @@ -6,12 +6,13 @@ import { z } from "zod"; import { db } from "@/lib/db"; import { readCartCookie, writeCartCookie } from "@/lib/cart"; import { findCoupon } from "@/lib/pricing"; +import { subscribe } from "@/lib/newsletter"; export async function subscribeNewsletter(_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." }; - await db.newsletterSubscriber.upsert({ where: { email: email.data }, create: { email: email.data }, update: {} }); - return { ok: true, error: null }; + const state = await subscribe(email.data); + return { ok: true, error: null, pending: state === "pending" }; } export async function addToCart(formData: FormData) { diff --git a/src/app/(shop)/kasse/actions.ts b/src/app/(shop)/kasse/actions.ts index 967a3b1..73397fc 100644 --- a/src/app/(shop)/kasse/actions.ts +++ b/src/app/(shop)/kasse/actions.ts @@ -10,6 +10,7 @@ import { availablePayments, availableShipping, createOrder, readCheckout, writeC import { computeTotals } from "@/lib/pricing"; import { getSettings } from "@/lib/settings"; import { autoInvoice } from "@/lib/invoices"; +import { mailOrderPlaced, sendLater } from "@/lib/mail/send"; import { getDefinition } from "@/lib/payments/catalog"; import { getCredentials } from "@/lib/payments/credentials"; import { createCheckoutSession } from "@/lib/payments/stripe"; @@ -104,6 +105,8 @@ export async function placeOrder(_prev: FormState, formData: FormData): Promise< return { message: e instanceof Error ? e.message : "Die Bestellung konnte nicht angelegt werden." }; } await autoInvoice(order.id, "order"); + const placedId = order.id; + sendLater(() => mailOrderPlaced(placedId, "placed")); await writeCheckout({ lastOrderId: order.id }); jar.set("sm_last_order", order.id, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 30 }); diff --git a/src/app/(shop)/konto/actions.ts b/src/app/(shop)/konto/actions.ts index 2549148..9b2fc1b 100644 --- a/src/app/(shop)/konto/actions.ts +++ b/src/app/(shop)/konto/actions.ts @@ -2,6 +2,7 @@ import { revalidatePath } from "next/cache"; import { z } from "zod"; import { db } from "@/lib/db"; +import { subscribe, unsubscribe } from "@/lib/newsletter"; import { getCurrentUser, hashPassword, verifyPassword } from "@/lib/auth"; import { COUNTRIES } from "@/lib/settings"; @@ -26,8 +27,8 @@ export async function updateProfile(_prev: AccountState, fd: FormData): Promise< if (!parsed.success) return { errors: issues(parsed.error), values: { firstName: String(fd.get("firstName") ?? ""), lastName: String(fd.get("lastName") ?? ""), phone: String(fd.get("phone") ?? "") } }; const newsletter = fd.get("newsletter") === "on"; await db.user.update({ where: { id: user.id }, data: { ...parsed.data, newsletter } }); - if (newsletter) await db.newsletterSubscriber.upsert({ where: { email: user.email }, create: { email: user.email }, update: {} }); - else await db.newsletterSubscriber.deleteMany({ where: { email: user.email } }); + if (newsletter && !user.newsletter) await subscribe(user.email); + else if (!newsletter) await unsubscribe(user.email); revalidatePath("/konto", "layout"); return { ok: "Deine Daten sind gespeichert." }; } diff --git a/src/app/(shop)/konto/passwort/neu/page.tsx b/src/app/(shop)/konto/passwort/neu/page.tsx new file mode 100644 index 0000000..48929ce --- /dev/null +++ b/src/app/(shop)/konto/passwort/neu/page.tsx @@ -0,0 +1,28 @@ +import Link from "next/link"; +import { findReset } from "@/lib/password-reset"; +import { NewPasswordForm } from "@/components/shop/AuthForms"; + +export const metadata = { title: "Neues Passwort", robots: { index: false } }; + +export default async function NewPasswordPage({ searchParams }: { searchParams: Promise<{ t?: string }> }) { + const { t = "" } = await searchParams; + const reset = await findReset(t); + return ( +
+
+

{reset ? "Neues Passwort festlegen" : "Link abgelaufen"}

+ {reset ? ( + <> +

Für {reset.user.email}

+ + + ) : ( + <> +

Dieser Link ist abgelaufen oder wurde schon benutzt.

+ Neuen Link anfordern + + )} +
+
+ ); +} diff --git a/src/app/(shop)/konto/passwort/page.tsx b/src/app/(shop)/konto/passwort/page.tsx new file mode 100644 index 0000000..cb0c434 --- /dev/null +++ b/src/app/(shop)/konto/passwort/page.tsx @@ -0,0 +1,17 @@ +import Link from "next/link"; +import { ResetRequestForm } from "@/components/shop/AuthForms"; + +export const metadata = { title: "Passwort vergessen" }; + +export default function ForgotPasswordPage() { + return ( +
+
+

Passwort vergessen?

+

Gib deine E-Mail-Adresse ein. Wir schicken dir einen Link, mit dem du ein neues Passwort festlegst.

+ +

Zurück zur Anmeldung

+
+
+ ); +} diff --git a/src/app/(shop)/newsletter/bestaetigen/page.tsx b/src/app/(shop)/newsletter/bestaetigen/page.tsx new file mode 100644 index 0000000..c852d42 --- /dev/null +++ b/src/app/(shop)/newsletter/bestaetigen/page.tsx @@ -0,0 +1,20 @@ +import Link from "next/link"; +import { confirm } from "@/lib/newsletter"; + +export const metadata = { title: "Newsletter bestätigen", robots: { index: false } }; + +export default async function ConfirmNewsletter({ searchParams }: { searchParams: Promise<{ t?: string }> }) { + const { t } = await searchParams; + const email = t ? await confirm(t) : null; + return ( +
+
+

{email ? "Danke, du bist dabei." : "Dieser Link ist ungültig."}

+

+ {email ? `Ab jetzt bekommst du unseren Newsletter an ${email}. Abmelden kannst du dich jederzeit.` : "Vielleicht ist er unvollständig kopiert worden. Melde dich einfach noch einmal an."} +

+ Zum Shop +
+
+ ); +} diff --git a/src/app/admin/(panel)/bestellungen/actions.ts b/src/app/admin/(panel)/bestellungen/actions.ts index 0881465..2f2b584 100644 --- a/src/app/admin/(panel)/bestellungen/actions.ts +++ b/src/app/admin/(panel)/bestellungen/actions.ts @@ -12,6 +12,7 @@ import { refundPayment } from "@/lib/payments/stripe"; import type { AddressData } from "@/lib/checkout"; import { cancelLabel, canCreateLabels, createLabel, getDhlConfig } from "@/lib/dhl"; import { autoInvoice, cancelInvoice, createInvoice } from "@/lib/invoices"; +import { mailCancelled, mailPaymentReceived, mailShipped, sendLater } from "@/lib/mail/send"; const authorName = (u: { firstName: string; lastName: string; email: string }) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email; @@ -45,8 +46,14 @@ export async function updateOrder(_prev: ActionResult, fd: FormData): Promise mailPaymentReceived(id)); + } + if (status === "SHIPPED" && order.status !== "SHIPPED") { + await autoInvoice(id, "shipped"); + sendLater(() => mailShipped(id)); + } revalidatePath(`/admin/bestellungen/${id}`); return ok(); } @@ -90,6 +97,7 @@ export async function cancelOrder(fd: FormData) { }); }); await cancelInvoice(id, authorName(user)); + sendLater(() => mailCancelled(id, wasPaid)); await audit(user, wasPaid ? "Bestellung erstattet" : "Bestellung storniert", order.number); revalidatePath(`/admin/bestellungen/${id}`); } @@ -123,7 +131,10 @@ export async function createDhlLabel(_prev: ActionResult, fd: FormData): Promise }, }); await audit(user, "DHL-Label erstellt", `${order.number}: ${result.shipmentNo}`); - if (shipped) await autoInvoice(id, "shipped"); + if (shipped) { + await autoInvoice(id, "shipped"); + sendLater(() => mailShipped(id)); + } revalidatePath(`/admin/bestellungen/${id}`); return ok("Label erstellt."); } diff --git a/src/app/admin/(panel)/emails/[key]/page.tsx b/src/app/admin/(panel)/emails/[key]/page.tsx new file mode 100644 index 0000000..b25c4ba --- /dev/null +++ b/src/app/admin/(panel)/emails/[key]/page.tsx @@ -0,0 +1,43 @@ +import { notFound } from "next/navigation"; +import { db } from "@/lib/db"; +import { requireAdmin } from "@/lib/auth"; +import { COMMON_PLACEHOLDERS } from "@/lib/mail/templates"; +import { getMailConfig, isMailReady } from "@/lib/mail/config"; +import { renderMail } from "@/lib/mail/render"; +import { commonVars, getBrand, getTemplate, sampleVars } from "@/lib/mail/send"; +import { ConfirmButton } from "@/components/admin/AdminForm"; +import { PageHead, Pill } from "@/components/admin/ui"; +import { MailEditor } from "@/components/admin/MailEditor"; +import { resetTemplate } from "../actions"; + +export default async function EmailTemplatePage({ params }: { params: Promise<{ key: string }> }) { + const user = await requireAdmin("emails.edit"); + const { key } = await params; + const t = await getTemplate(key); + if (!t) notFound(); + const [row, config] = await Promise.all([db.emailTemplate.findUnique({ where: { key } }), getMailConfig()]); + const vars = { ...(await commonVars()), ...(await sampleVars(t)) }; + const preview = renderMail(t, vars, await getBrand()); + const strip = (p: { key: string; label: string; block?: boolean }) => ({ key: p.key, label: p.label, block: p.block }); + return ( +
+ + An: {t.recipient === "team" ? "Team" : "Kunde"} + {t.customized && ( + + )} + + +
+ ); +} diff --git a/src/app/admin/(panel)/emails/actions.ts b/src/app/admin/(panel)/emails/actions.ts new file mode 100644 index 0000000..46c5749 --- /dev/null +++ b/src/app/admin/(panel)/emails/actions.ts @@ -0,0 +1,83 @@ +"use server"; +import { revalidatePath } from "next/cache"; +import { assertPermission, audit } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { fail, ok, type ActionResult } from "@/lib/action-result"; +import { COMMON_PLACEHOLDERS, getTemplateDef } from "@/lib/mail/templates"; +import { renderMail } from "@/lib/mail/render"; +import { commonVars, getBrand, sampleVars, sendTemplate } from "@/lib/mail/send"; +import { getMailConfig, isMailReady } from "@/lib/mail/config"; + +const str = (fd: FormData, k: string) => String(fd.get(k) ?? ""); + +function unknownPlaceholders(key: string, text: string) { + const def = getTemplateDef(key)!; + const known = new Set([...def.placeholders, ...COMMON_PLACEHOLDERS].map((p) => p.key)); + return [...new Set([...text.matchAll(/\{\{\s*([a-z_]+)\s*\}\}/g)].map((m) => m[1]).filter((k) => !known.has(k)))]; +} + +function check(key: string, subject: string, body: string) { + const def = getTemplateDef(key); + if (!def) return "Unbekannte Vorlage."; + if (!subject.trim()) return "Bitte gib einen Betreff ein."; + if (!body.trim()) return "Bitte gib einen Text ein."; + if (subject.length > 300 || body.length > 20000) return "Der Text ist zu lang."; + if (def.required && !/\{\{\s*link\s*\}\}/.test(body)) return "Diese Mail braucht den Platzhalter {{link}}, sonst kann der Empfänger nichts tun."; + return null; +} + +export async function saveTemplate(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("emails.edit"); + const key = str(fd, "key"); + const subject = str(fd, "subject").replace(/\s+/g, " ").trim(); + const body = str(fd, "body").replace(/\r\n/g, "\n").trim(); + const error = check(key, subject, body); + if (error) return fail(error); + const def = getTemplateDef(key)!; + const enabled = def.required ? true : fd.get("enabled") === "on"; + if (subject === def.subject && body === def.body.trim() && enabled) { + // Entspricht dem Original: keine Kopie speichern, damit spätere Verbesserungen am Standardtext ankommen + await db.emailTemplate.deleteMany({ where: { key } }); + } else { + await db.emailTemplate.upsert({ where: { key }, create: { key, subject, body, enabled }, update: { subject, body, enabled } }); + } + await audit(user, "E-Mail-Vorlage geändert", `${def.name}${enabled ? "" : " (ausgeschaltet)"}`); + revalidatePath("/admin/emails", "layout"); + const unknown = unknownPlaceholders(key, subject + body); + if (unknown.length) return ok(`Gespeichert. Achtung: ${unknown.map((u) => `{{${u}}}`).join(", ")} kenne ich nicht, das bleibt in der Mail leer.`); + return ok(enabled ? "Gespeichert." : "Gespeichert. Diese Mail wird nicht mehr verschickt."); +} + +/** Vorschau mit Beispieldaten, wird beim Tippen aufgerufen. */ +export async function previewTemplate(key: string, subject: string, body: string) { + await assertPermission("emails.edit"); + const def = getTemplateDef(key); + if (!def) return { subject: "", html: "" }; + const vars = { ...(await commonVars()), ...(await sampleVars(def)) }; + const mail = renderMail({ subject, body }, vars, await getBrand()); + return { subject: mail.subject, html: mail.html }; +} + +export async function sendTestTemplate(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("emails.edit"); + const key = str(fd, "key"); + const subject = str(fd, "subject"); + const body = str(fd, "body"); + const error = check(key, subject, body); + if (error) return fail(error); + if (!isMailReady(await getMailConfig())) return fail("Der Mail-Versand ist noch nicht eingerichtet oder ausgeschaltet. Das geht unter Verbindungen → E-Mail-Versand."); + const def = getTemplateDef(key)!; + const r = await sendTemplate({ key, to: user.email, vars: await sampleVars(def), force: true, override: { subject: `[Test] ${subject}`, body } }); + revalidatePath("/admin/emails"); + return r.ok ? ok(`Testmail mit Beispieldaten an ${user.email} verschickt.`) : fail(r.error ?? r.skipped ?? "Nicht verschickt."); +} + +export async function resetTemplate(fd: FormData) { + const user = await assertPermission("emails.edit"); + const key = str(fd, "key"); + const def = getTemplateDef(key); + if (!def) return; + await db.emailTemplate.deleteMany({ where: { key } }); + await audit(user, "E-Mail-Vorlage zurückgesetzt", def.name); + revalidatePath("/admin/emails", "layout"); +} diff --git a/src/app/admin/(panel)/emails/page.tsx b/src/app/admin/(panel)/emails/page.tsx new file mode 100644 index 0000000..517a0e2 --- /dev/null +++ b/src/app/admin/(panel)/emails/page.tsx @@ -0,0 +1,111 @@ +import Link from "next/link"; +import { db } from "@/lib/db"; +import { requireAdmin } from "@/lib/auth"; +import { dateFmt } from "@/lib/status"; +import { MAIL_TEMPLATES, getTemplateDef } from "@/lib/mail/templates"; +import { getMailConfig, isMailReady } from "@/lib/mail/config"; +import { Card, Empty, PageHead, Pill } from "@/components/admin/ui"; + +const GROUPS = ["Bestellung", "Konto", "Newsletter", "Team"] as const; + +export default async function EmailsPage({ searchParams }: { searchParams: Promise<{ tab?: string }> }) { + await requireAdmin("emails.edit"); + const { tab } = await searchParams; + const config = await getMailConfig(); + const ready = isMailReady(config); + return ( +
+ + {ready ? ( +

+ Versand über {config.host} als {config.fromName ? `${config.fromName} <${config.fromEmail}>` : config.fromEmail}. Ändern +

+ ) : ( +
+
+ {config.host ? "Der Mail-Versand ist ausgeschaltet. Gerade geht keine Mail raus." : "Der Mail-Versand ist noch nicht eingerichtet. Bis dahin geht keine Mail raus."}{" "} + Jetzt einrichten +
+
+ )} +
+ Vorlagen + Versandprotokoll +
+ {tab === "protokoll" ? : } +
+ ); +} + +async function Templates() { + const [rows, last] = await Promise.all([ + db.emailTemplate.findMany(), + db.emailLog.groupBy({ by: ["templateKey"], where: { ok: true }, _max: { createdAt: true }, _count: true }), + ]); + const custom = new Map(rows.map((r) => [r.key, r])); + const sent = new Map(last.map((l) => [l.templateKey, l])); + return ( +
+ {GROUPS.map((group) => ( + +
+ + + + {MAIL_TEMPLATES.filter((t) => t.group === group).map((t) => { + const row = custom.get(t.key); + const enabled = t.required || (row?.enabled ?? true); + const s = sent.get(t.key); + return ( + + + + + + + ); + })} + +
MailAnStatusZuletzt verschickt
+ {t.name} +
{t.description}
+
{t.recipient === "team" ? "Team" : "Kunde"} + {enabled ? {t.required ? "Immer an" : "An"} : Aus} {row && Angepasst} + {s?._max.createdAt ? `${dateFmt.format(s._max.createdAt)} (${s._count}×)` : "Noch nie"}
+
+
+ ))} +
+ ); +} + +async function Log() { + const logs = await db.emailLog.findMany({ orderBy: { createdAt: "desc" }, take: 100 }); + const orders = await db.order.findMany({ where: { id: { in: logs.flatMap((l) => (l.orderId ? [l.orderId] : [])) } }, select: { id: true, number: true } }); + const number = new Map(orders.map((o) => [o.id, o.number])); + return ( + + {logs.length === 0 ? : ( +
+ + + + {logs.map((l) => ( + + + + + + + + ))} + +
ZeitAnBetreffMailErgebnis
{dateFmt.format(l.createdAt)}{l.to} + {l.subject} + {l.orderId && number.get(l.orderId) &&
Bestellung {number.get(l.orderId)}
} +
{getTemplateDef(l.templateKey)?.name ?? (l.templateKey === "test" ? "Testmail" : l.templateKey)}{l.ok ? Verschickt : <>Fehler
{l.error}
}
+
+ )} +
+ ); +} diff --git a/src/app/admin/(panel)/newsletter/export/route.ts b/src/app/admin/(panel)/newsletter/export/route.ts index 3afef27..4b5566f 100644 --- a/src/app/admin/(panel)/newsletter/export/route.ts +++ b/src/app/admin/(panel)/newsletter/export/route.ts @@ -4,7 +4,8 @@ import { can, getCurrentUser } from "@/lib/auth"; export async function GET() { if (!can(await getCurrentUser(), "newsletter.view")) return new NextResponse("Kein Zugriff", { status: 403 }); - const subs = await db.newsletterSubscriber.findMany({ orderBy: { createdAt: "asc" } }); - const csv = "email;angemeldet_am\n" + subs.map((s) => `${s.email};${s.createdAt.toISOString()}`).join("\n"); + // Nur bestätigte Adressen dürfen Werbung bekommen + const subs = await db.newsletterSubscriber.findMany({ where: { confirmedAt: { not: null } }, orderBy: { createdAt: "asc" } }); + const csv = "email;angemeldet_am;bestaetigt_am\n" + subs.map((s) => `${s.email};${s.createdAt.toISOString()};${s.confirmedAt?.toISOString() ?? ""}`).join("\n"); return new NextResponse(csv, { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": 'attachment; filename="newsletter.csv"' } }); } diff --git a/src/app/admin/(panel)/newsletter/page.tsx b/src/app/admin/(panel)/newsletter/page.tsx index 142bf5b..3ff457d 100644 --- a/src/app/admin/(panel)/newsletter/page.tsx +++ b/src/app/admin/(panel)/newsletter/page.tsx @@ -1,21 +1,22 @@ import { db } from "@/lib/db"; import { requireAdmin } from "@/lib/auth"; import { dateFmt } from "@/lib/status"; -import { Card, Empty, PageHead } from "@/components/admin/ui"; +import { Card, Empty, PageHead, Pill } from "@/components/admin/ui"; 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; return (
- - {subs.length > 0 && Als CSV herunterladen} + confirmed ? `, ${subs.length - confirmed} warten auf Bestätigung` : ""}. Angemeldet ist erst, wer den Link in der Bestätigungsmail geklickt hat.`}> + {confirmed > 0 && Bestätigte als CSV} {subs.length === 0 ? : ( - - {subs.map((s) => )} + + {subs.map((s) => )}
E-MailAngemeldet am
{s.email}{dateFmt.format(s.createdAt)}
E-MailAngemeldet amStatus
{s.email}{dateFmt.format(s.createdAt)}{s.confirmedAt ? Bestätigt : Wartet}
)}
diff --git a/src/app/admin/(panel)/team/actions.ts b/src/app/admin/(panel)/team/actions.ts index 86826f2..1c2e5e4 100644 --- a/src/app/admin/(panel)/team/actions.ts +++ b/src/app/admin/(panel)/team/actions.ts @@ -5,6 +5,9 @@ import { z } from "zod"; import { db } from "@/lib/db"; import { assertPermission, audit, hashPassword, type CurrentUser } from "@/lib/auth"; import { fail, ok, type ActionResult } from "@/lib/action-result"; +import { getMailConfig, isMailReady } from "@/lib/mail/config"; +import { sendLater, sendTemplate } from "@/lib/mail/send"; +import { createResetLink } from "@/lib/password-reset"; /** Darf `actor` diese Rolle vergeben? Nur Inhaber vergeben Inhaber; sonst nur Rollen mit Rechten, die man selbst hat. */ async function canAssign(actor: CurrentUser, roleId: string) { @@ -28,12 +31,20 @@ export async function inviteMember(_prev: ActionResult, fd: FormData): Promise sendTemplate({ key: "team_invite", to, vars })); + } revalidatePath("/admin/team"); redirect(`/admin/team/${user.id}?neu=1`); } diff --git a/src/app/admin/(panel)/team/page.tsx b/src/app/admin/(panel)/team/page.tsx index 8693bf8..191a6b0 100644 --- a/src/app/admin/(panel)/team/page.tsx +++ b/src/app/admin/(panel)/team/page.tsx @@ -6,6 +6,7 @@ import { Field, SelectField } from "@/components/Field"; import { AdminForm } from "@/components/admin/AdminForm"; import { Card, PageHead, Pill } from "@/components/admin/ui"; import { inviteMember } from "./actions"; +import { getMailConfig, isMailReady } from "@/lib/mail/config"; export default async function TeamPage() { const me = await requireAdmin("users.manage"); @@ -13,6 +14,7 @@ export default async function TeamPage() { db.user.findMany({ where: { roleId: { not: null } }, include: { role: true }, orderBy: { createdAt: "asc" } }), db.role.findMany({ orderBy: { name: "asc" } }), ]); + const mailReady = isMailReady(await getMailConfig()); const assignable = roles.filter((r) => me.role?.isSystem || (!r.isSystem && r.permissions.every((p) => me.role!.permissions.includes(p)))); return (
@@ -37,14 +39,14 @@ export default async function TeamPage() {
- +
- + {!mailReady && } !r.isSystem)?.id}> {assignable.map((r) => )} diff --git a/src/app/admin/(panel)/verbindungen/[provider]/page.tsx b/src/app/admin/(panel)/verbindungen/[provider]/page.tsx index db09634..ccee5a4 100644 --- a/src/app/admin/(panel)/verbindungen/[provider]/page.tsx +++ b/src/app/admin/(panel)/verbindungen/[provider]/page.tsx @@ -13,7 +13,10 @@ import { CopyValue } from "@/components/admin/CopyValue"; import { KeyFileInput } from "@/components/admin/KeyFileInput"; import { OpenLink, Step, Steps } from "@/components/admin/Setup"; import { StatusPill } from "@/components/admin/IntegrationStatus"; -import { disconnect, retest, saveApple, saveDhlConnection, saveGoogle, savePaypal, saveStripe } from "../actions"; +import { MailServerFields } from "@/components/admin/MailServerFields"; +import { MAIL_PRESETS, getMailConfig } from "@/lib/mail/config"; +import { getSettings } from "@/lib/settings"; +import { disconnect, retest, saveApple, saveDhlConnection, saveGoogle, saveMail, savePaypal, saveStripe } from "../actions"; function LastTest({ t }: { t: TestResult | null }) { if (!t) return null; @@ -262,10 +265,46 @@ async function AppleWizard({ ok }: { ok: boolean }) { ); } +// ---------- E-Mail ---------- + +async function MailWizard({ ok }: { ok: boolean }) { + const [c, user, g] = await Promise.all([getMailConfig(), requireAdmin(), getSettings().then((s) => s.general)]); + const has = Boolean(c.host && c.fromEmail); + return ( + + + + +

Der Shop verschickt seine Mails über ein ganz normales Postfach, am besten eine eigene Adresse wie shop@ oder hallo@ deiner Domain. Wähle, wo dieses Postfach liegt. Server und Port trage ich dann selbst ein.

+ +
+ +

Die gleichen Daten, mit denen du dich auch in Outlook oder auf dem Handy in dieses Postfach einloggst.

+ + +
+ +

So sehen Kunden deine Mails im Posteingang. Die Absenderadresse sollte zum Postfach gehören, sonst landen Mails leicht im Spam.

+ + + + +
+ +

Ich melde mich am Mailserver an und schicke dir eine Testmail an {user.email}.

+ +
+
+
+
+ ); +} + const WIZARDS: Record Promise> = { stripe: StripeWizard, paypal: PaypalWizard, dhl: DhlWizard, google: GoogleWizard, apple: AppleWizard, + mail: MailWizard, }; diff --git a/src/app/admin/(panel)/verbindungen/actions.ts b/src/app/admin/(panel)/verbindungen/actions.ts index 8ec805f..555a343 100644 --- a/src/app/admin/(panel)/verbindungen/actions.ts +++ b/src/app/admin/(panel)/verbindungen/actions.ts @@ -7,7 +7,9 @@ import { getDhlConfig, saveDhlConfig, splitStreet } from "@/lib/dhl"; import { getSettings } from "@/lib/settings"; import { getLoginProviders, saveLoginProviders } from "@/lib/social/config"; import { isValidApplePrivateKey } from "@/lib/social/oauth"; -import { createStripeWebhook, detectPaypalMode, forgetTest, saveDetectedPaypal, testDhlConnection, testLogin, testPaypal, testStripe, type IntegrationKey } from "@/lib/integrations"; +import { createStripeWebhook, detectPaypalMode, forgetTest, saveDetectedPaypal, testDhlConnection, testLogin, testMail, testPaypal, testStripe, type IntegrationKey } from "@/lib/integrations"; +import { getMailConfig, saveMailConfig, type MailConfig } from "@/lib/mail/config"; +import { sendTestMail } from "@/lib/mail/send"; const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); // Leere Geheimfelder behalten den gespeicherten Wert @@ -16,6 +18,7 @@ const done = (r: { ok: boolean; message: string }) => { revalidatePath("/admin/verbindungen", "layout"); revalidatePath("/admin/zahlung"); revalidatePath("/admin/dhl"); + revalidatePath("/admin/emails"); return r.ok ? ok(r.message) : fail(r.message); }; @@ -150,7 +153,49 @@ export async function saveApple(_prev: ActionResult, fd: FormData): Promise = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit" }; +const EMAIL = /^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]+$/; + +export async function saveMail(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("emails.edit"); + const c = await getMailConfig(); + const security = str(fd, "security"); + const next: MailConfig = { + host: str(fd, "host").toLowerCase(), + port: Number(str(fd, "port")) || 587, + security: security === "tls" || security === "none" ? security : "starttls", + user: str(fd, "user"), + password: keep(String(fd.get("password") ?? ""), c.password), + fromName: str(fd, "fromName"), + fromEmail: str(fd, "fromEmail"), + replyTo: str(fd, "replyTo"), + adminEmail: str(fd, "adminEmail"), + enabled: fd.get("enabled") === "on", + }; + const errors: Record = {}; + if (!next.host) errors.host = "Bitte eintragen"; + if (next.port < 1 || next.port > 65535) errors.port = "Ungültig"; + if (!EMAIL.test(next.fromEmail)) errors.fromEmail = "Bitte eine E-Mail-Adresse"; + if (next.replyTo && !EMAIL.test(next.replyTo)) errors.replyTo = "Ungültig"; + if (next.adminEmail && !EMAIL.test(next.adminEmail)) errors.adminEmail = "Ungültig"; + if (next.user && !next.password) errors.password = "Bitte eintragen"; + if (Object.keys(errors).length) return fail(errors.host ? "Bitte wähle zuerst deinen Mail-Anbieter in Schritt 1." : "Bitte prüfe die markierten Felder.", errors); + const test = await testMail(next); + if (!test.ok) { + // Trotzdem speichern, damit nichts neu eingetippt werden muss, aber nicht verschicken + await saveMailConfig({ ...next, enabled: false }); + return done({ ok: false, message: `${test.message} Gespeichert, der Versand bleibt aus, bis der Test klappt.` }); + } + await saveMailConfig(next); + await audit(user, "E-Mail-Versand eingerichtet", `${next.host} (${next.enabled ? "an" : "aus"})`); + try { + await sendTestMail(next, user.email); + } catch (e) { + return done({ ok: false, message: `Anmeldung klappt, aber die Testmail wurde abgelehnt: ${e instanceof Error ? e.message : e}` }); + } + return done({ ok: true, message: `Testmail an ${user.email} verschickt. Schau in dein Postfach (auch im Spam-Ordner).${next.enabled ? "" : " Der Versand an Kunden ist noch ausgeschaltet."}` }); +} + +const PERMS: Record = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit", mail: "emails.edit" }; export async function disconnect(fd: FormData) { const key = str(fd, "provider") as IntegrationKey; @@ -164,6 +209,9 @@ export async function disconnect(fd: FormData) { } else if (key === "dhl") { const c = await getDhlConfig(); await saveDhlConfig({ ...c, apiKey: "", password: "", enabled: false }); + } else if (key === "mail") { + const c = await getMailConfig(); + await saveMailConfig({ ...c, host: "", user: "", password: "", enabled: false }); } else { const c = await getLoginProviders(); if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" }; @@ -179,6 +227,6 @@ export async function retest(_prev: ActionResult, fd: FormData): Promise }) { +export default async function InvoicePage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ t?: string }> }) { const { id } = await params; + const { t } = await searchParams; const [invoice, user, jar] = await Promise.all([ db.invoice.findUnique({ where: { id }, include: { order: { select: { id: true, userId: true } } } }), getCurrentUser(), cookies(), ]); if (!invoice) notFound(); - const allowed = can(user, "orders.view") || (user && invoice.order.userId === user.id) || jar.get("sm_last_order")?.value === invoice.order.id; + const allowed = (t && invoice.accessToken && t === invoice.accessToken) || can(user, "orders.view") || (user && invoice.order.userId === user.id) || jar.get("sm_last_order")?.value === invoice.order.id; if (!allowed) notFound(); const d = invoice.data as InvoiceData; diff --git a/src/components/admin/MailEditor.tsx b/src/components/admin/MailEditor.tsx new file mode 100644 index 0000000..403b77c --- /dev/null +++ b/src/components/admin/MailEditor.tsx @@ -0,0 +1,166 @@ +"use client"; +import { useActionState, useEffect, useRef, useState, useTransition } from "react"; +import type { ActionResult } from "@/lib/action-result"; +import { previewTemplate, saveTemplate, sendTestTemplate } from "@/app/admin/(panel)/emails/actions"; +import { Icon } from "../Icon"; + +type Placeholder = { key: string; label: string; block?: boolean }; + +function Message({ state }: { state: ActionResult }) { + if (!state?.message) return null; + return ( + + {state.message} + + ); +} + +/** Betreff und Text einer Mail bearbeiten, mit Platzhaltern zum Einfügen und Live-Vorschau. */ +export function MailEditor({ + templateKey, + required, + initial, + preview: initialPreview, + placeholders, + common, + mailReady, + userEmail, +}: { + templateKey: string; + required: boolean; + initial: { subject: string; body: string; enabled: boolean }; + preview: { subject: string; html: string }; + placeholders: Placeholder[]; + common: Placeholder[]; + mailReady: boolean; + userEmail: string; +}) { + const [subject, setSubject] = useState(initial.subject); + const [body, setBody] = useState(initial.body); + const [preview, setPreview] = useState(initialPreview); + const [device, setDevice] = useState<"desktop" | "mobile">("desktop"); + const [saveState, saveAction, saving] = useActionState(saveTemplate, null); + const [testState, testAction, testing] = useActionState(sendTestTemplate, null); + const [, startPreview] = useTransition(); + const bodyRef = useRef(null); + const subjectRef = useRef(null); + const lastFocus = useRef<"subject" | "body">("body"); + const first = useRef(true); + + useEffect(() => { + if (first.current) { + first.current = false; + return; + } + const t = setTimeout(() => startPreview(async () => setPreview(await previewTemplate(templateKey, subject, body))), 350); + return () => clearTimeout(t); + }, [subject, body, templateKey]); + + const insert = (p: Placeholder) => { + const tag = `{{${p.key}}}`; + if (lastFocus.current === "subject" && !p.block) { + const el = subjectRef.current!; + const [a, b] = [el.selectionStart ?? subject.length, el.selectionEnd ?? subject.length]; + setSubject(subject.slice(0, a) + tag + subject.slice(b)); + requestAnimationFrame(() => { el.focus(); el.setSelectionRange(a + tag.length, a + tag.length); }); + return; + } + const el = bodyRef.current!; + const [a, b] = [el.selectionStart ?? body.length, el.selectionEnd ?? body.length]; + // Blöcke brauchen eine eigene Zeile mit Leerzeile davor und danach + const before = body.slice(0, a); + const after = body.slice(b); + const text = p.block ? `${before && !before.endsWith("\n\n") ? (before.endsWith("\n") ? "\n" : "\n\n") : ""}${tag}${after && !after.startsWith("\n\n") ? (after.startsWith("\n") ? "\n" : "\n\n") : ""}` : tag; + setBody(before + text + after); + requestAnimationFrame(() => { el.focus(); el.setSelectionRange(a + text.length, a + text.length); }); + }; + + const chip = (p: Placeholder) => ( + + ); + + return ( +
+
+ +
+ +