Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/integrations/email/campaignSendPlan.ts
T
2026-07-08 16:15:37 +02:00

130 lines
4.9 KiB
TypeScript

// AK-P14b (P14 email marketing) — pure campaign send planning.
//
// Turns a resolved recipient list + campaign content + variants + schedule into
// a deterministic list of per-recipient send instructions: which A/B variant,
// the personalized subject/html/text, and the throttled `sendAt` timestamp.
// PURE: no DB, no queue, no clock — `now` and rate are injected so it is fully
// unit-testable. The send-engine service (S3) persists OutboundEmail rows and
// enqueues one `mail.transactional` job per plan entry.
import { buildTokenMap, injectFooter, replaceTokens, type RecipientTokenSource } from "./personalization";
export type CampaignVariantLabel = "a" | "b";
/** One A/B variant's content + audience weight. */
export interface PlanVariant {
label: CampaignVariantLabel;
subject: string;
htmlBody: string;
textBody?: string | null;
weightPercent: number;
}
/** One resolved recipient (already eligibility-filtered by the segment engine). */
export interface PlanRecipient {
outboundEmailId: string;
kontaktId: string;
email: string;
unsubscribeToken: string;
tokens: RecipientTokenSource;
}
export interface PlanCampaignInput {
recipients: readonly PlanRecipient[];
/** Default (non-A/B) content. Used when `variants` is empty. */
base: { subject: string; htmlBody: string; textBody?: string | null };
variants?: readonly PlanVariant[];
footerHtml: string;
unsubscribeBaseUrl: string;
/** Send start (epoch ms). Already resolved to the campaign timezone by caller. */
startAt: number;
/** Max sends per minute (throttle). 0/undefined ⇒ no throttle (all at startAt). */
ratePerMinute?: number;
}
export interface PlannedSend {
outboundEmailId: string;
kontaktId: string;
email: string;
variantLabel: CampaignVariantLabel | null;
subject: string;
html: string;
text: string;
unsubscribeUrl: string;
listUnsubscribe: string;
sendAt: number;
}
function buildUnsubscribeUrl(baseUrl: string, token: string): string {
return `${baseUrl.replace(/\/+$/, "")}/unsubscribe/${encodeURIComponent(token)}`;
}
/**
* Assign `count` recipients to A/B variants proportionally to their weights,
* INTERLEAVED (d'Hondt highest-averages) so both variants are spread evenly
* across the send/throttle window rather than front-loading one variant. With
* weights [50,50] the sequence is a,b,a,b…; with [60,40] over 5 it is a,b,a,a,b.
* Deterministic ⇒ re-planning is idempotent.
*/
export function assignVariants(count: number, variants: readonly PlanVariant[]): (PlanVariant | null)[] {
if (variants.length === 0) return new Array(count).fill(null);
const weights = variants.map((v) => Math.max(0, v.weightPercent));
const totalWeight = weights.reduce((sum, w) => sum + w, 0);
if (totalWeight <= 0) return Array.from({ length: count }, (_, i) => variants[i % variants.length]);
const counts = variants.map(() => 0);
const out: (PlanVariant | null)[] = [];
for (let i = 0; i < count; i += 1) {
let best = 0;
let bestQuotient = -Infinity;
for (let j = 0; j < variants.length; j += 1) {
const quotient = weights[j] / (counts[j] + 1);
if (quotient > bestQuotient) {
bestQuotient = quotient;
best = j;
}
}
counts[best] += 1;
out.push(variants[best]);
}
return out;
}
/** Throttled send time for the i-th recipient. */
export function sendAtForIndex(index: number, startAt: number, ratePerMinute?: number): number {
if (!ratePerMinute || ratePerMinute <= 0) return startAt;
const minuteOffset = Math.floor(index / ratePerMinute);
return startAt + minuteOffset * 60_000;
}
export function planCampaignSend(input: PlanCampaignInput): PlannedSend[] {
const variants = input.variants ?? [];
const assignments = assignVariants(input.recipients.length, variants);
return input.recipients.map((recipient, index) => {
const variant = assignments[index];
const content = variant ?? { subject: input.base.subject, htmlBody: input.base.htmlBody, textBody: input.base.textBody };
const tokens = buildTokenMap(recipient.tokens);
const unsubscribeUrl = buildUnsubscribeUrl(input.unsubscribeBaseUrl, recipient.unsubscribeToken);
const tokensWithUrl = { ...tokens, unsubscribeUrl };
const subject = replaceTokens(content.subject, tokensWithUrl);
const htmlWithFooter = injectFooter(content.htmlBody, input.footerHtml, unsubscribeUrl);
const html = replaceTokens(htmlWithFooter, tokensWithUrl);
const text = replaceTokens(content.textBody ?? "", tokensWithUrl);
return {
outboundEmailId: recipient.outboundEmailId,
kontaktId: recipient.kontaktId,
email: recipient.email,
variantLabel: variant?.label ?? null,
subject,
html,
text,
unsubscribeUrl,
// RFC 8058 one-click List-Unsubscribe header value.
listUnsubscribe: `<${unsubscribeUrl}>`,
sendAt: sendAtForIndex(index, input.startAt, input.ratePerMinute),
};
});
}