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 { const row = await db.setting.findUnique({ where: { key: SETTINGS_KEY } }); return { ...DEFAULTS, ...((row?.value ?? {}) as Partial) }; } 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 { 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> { 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> { 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) { 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 ? `${formatPrice(p.compareAtPrice)} ${formatPrice(p.price)}` : formatPrice(p.price); return ` ${p.image ? `${esc(p.name)}` : ""} ${esc(p.name)} ${p.subtitle ? `${esc(p.subtitle)}` : ""} ${price} `; }; const rows: string[] = []; for (let i = 0; i < list.length; i += 2) { const pair = list.slice(i, i + 2); rows.push(`${pair.map(cell).join("")}${pair.length === 1 ? '' : ""}`); } return { html: `${rows.join("")}
`, text: list.map((p) => `${p.name}, ${formatPrice(p.price)}: ${appUrl()}/produkt/${p.slug}`).join("\n"), }; } function blockHtml(b: CampaignBlock, vars: MailVars, products: Map) { 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 = `${esc(b.alt)}`; const link = b.link.trim() ? renderSubject(b.link, vars) : ""; return { html: link && /^https?:|^\//.test(link) ? `${img}` : img, text: b.alt ? `[${b.alt}]` : "" }; } case "products": return productsHtml(b.productIds, products); case "divider": return { html: `
`, text: "———" }; } } export type RenderOpts = { vars: MailVars; products: Map; // 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 += ``; const footer = `

Du bekommst diese Mail, weil du dich für den Newsletter von ${esc(brand.shopName)} angemeldet hast.
Newsletter abbestellen`; 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) { 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 { return { ...(await commonVars()), vorname: name.firstName, nachname: name.lastName, email }; }