sanamare/src/lib/campaigns.ts

171 lines
9.3 KiB
TypeScript

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(/&amp;/g, "&").replace(/&quot;/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 };
}