Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+93
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildTokenMap, hasFooter, injectFooter, replaceTokens } from "./personalization";
|
||||
import { assignVariants, planCampaignSend, sendAtForIndex, type PlanRecipient, type PlanVariant } from "./campaignSendPlan";
|
||||
|
||||
describe("personalization", () => {
|
||||
it("builds standard + custom-field tokens", () => {
|
||||
const map = buildTokenMap({ vorname: "Ada", nachname: "Lovelace", email: "ada@x.de", orgName: "ACME", customFields: { sprache: "DE" } });
|
||||
expect(map).toMatchObject({ firstName: "Ada", lastName: "Lovelace", email: "ada@x.de", company_name: "ACME", "cf.sprache": "DE" });
|
||||
});
|
||||
|
||||
it("replaces known tokens and collapses unknown ones", () => {
|
||||
expect(replaceTokens("Hi {{firstName}} <{{email}}> {{missing}}", { firstName: "Ada", email: "ada@x.de" })).toBe("Hi Ada <ada@x.de> ");
|
||||
});
|
||||
|
||||
it("injects the footer once (idempotent) and fills the unsubscribe url", () => {
|
||||
const footer = '<a href="{{unsubscribeUrl}}">Abmelden</a> · Impressum';
|
||||
const once = injectFooter("<p>Body</p>", footer, "https://t.de/unsubscribe/tok");
|
||||
expect(hasFooter(once)).toBe(true);
|
||||
expect(once).toContain("https://t.de/unsubscribe/tok");
|
||||
const twice = injectFooter(once, footer, "https://t.de/unsubscribe/tok2");
|
||||
// footer block not duplicated; url refreshed
|
||||
expect(twice.match(/data-hg-footer/g)?.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assignVariants", () => {
|
||||
it("returns all null with no variants", () => {
|
||||
expect(assignVariants(3, [])).toEqual([null, null, null]);
|
||||
});
|
||||
it("interleaves 50/50 as a,b,a,b", () => {
|
||||
const variants: PlanVariant[] = [
|
||||
{ label: "a", subject: "A", htmlBody: "<p>A</p>", weightPercent: 50 },
|
||||
{ label: "b", subject: "B", htmlBody: "<p>B</p>", weightPercent: 50 },
|
||||
];
|
||||
expect(assignVariants(4, variants).map((v) => v?.label)).toEqual(["a", "b", "a", "b"]);
|
||||
});
|
||||
it("respects 60/40 weights over 5 (3:2, interleaved)", () => {
|
||||
const variants: PlanVariant[] = [
|
||||
{ label: "a", subject: "A", htmlBody: "<p>A</p>", weightPercent: 60 },
|
||||
{ label: "b", subject: "B", htmlBody: "<p>B</p>", weightPercent: 40 },
|
||||
];
|
||||
const labels = assignVariants(5, variants).map((v) => v?.label);
|
||||
expect(labels).toEqual(["a", "b", "a", "a", "b"]);
|
||||
expect(labels.filter((l) => l === "a")).toHaveLength(3);
|
||||
expect(labels.filter((l) => l === "b")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendAtForIndex", () => {
|
||||
it("returns startAt with no throttle", () => {
|
||||
expect(sendAtForIndex(500, 1000, 0)).toBe(1000);
|
||||
expect(sendAtForIndex(500, 1000)).toBe(1000);
|
||||
});
|
||||
it("spreads by minute buckets at the configured rate", () => {
|
||||
expect(sendAtForIndex(0, 1000, 100)).toBe(1000);
|
||||
expect(sendAtForIndex(99, 1000, 100)).toBe(1000);
|
||||
expect(sendAtForIndex(100, 1000, 100)).toBe(1000 + 60_000);
|
||||
expect(sendAtForIndex(250, 1000, 100)).toBe(1000 + 2 * 60_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("planCampaignSend", () => {
|
||||
const recipients: PlanRecipient[] = [
|
||||
{ outboundEmailId: "o1", kontaktId: "k1", email: "a@x.de", unsubscribeToken: "t1", tokens: { vorname: "Ada", email: "a@x.de" } },
|
||||
{ outboundEmailId: "o2", kontaktId: "k2", email: "b@x.de", unsubscribeToken: "t2", tokens: { vorname: "Bo", email: "b@x.de" } },
|
||||
];
|
||||
const base = { subject: "Hi {{firstName}}", htmlBody: "<p>Hello {{firstName}}</p>" };
|
||||
const footer = '<a href="{{unsubscribeUrl}}">Abmelden</a>';
|
||||
|
||||
it("personalizes, injects footer, builds list-unsubscribe + sendAt", () => {
|
||||
const plan = planCampaignSend({ recipients, base, footerHtml: footer, unsubscribeBaseUrl: "https://t.de/", startAt: 5000, ratePerMinute: 1 });
|
||||
expect(plan).toHaveLength(2);
|
||||
expect(plan[0].subject).toBe("Hi Ada");
|
||||
expect(plan[0].html).toContain("Hello Ada");
|
||||
expect(plan[0].html).toContain("https://t.de/unsubscribe/t1");
|
||||
expect(plan[0].listUnsubscribe).toBe("<https://t.de/unsubscribe/t1>");
|
||||
expect(plan[0].variantLabel).toBeNull();
|
||||
expect(plan[0].sendAt).toBe(5000);
|
||||
expect(plan[1].sendAt).toBe(5000 + 60_000); // rate 1/min
|
||||
});
|
||||
|
||||
it("assigns A/B variants by weight", () => {
|
||||
const variants: PlanVariant[] = [
|
||||
{ label: "a", subject: "A {{firstName}}", htmlBody: "<p>A</p>", weightPercent: 50 },
|
||||
{ label: "b", subject: "B {{firstName}}", htmlBody: "<p>B</p>", weightPercent: 50 },
|
||||
];
|
||||
const plan = planCampaignSend({ recipients, base, variants, footerHtml: footer, unsubscribeBaseUrl: "https://t.de", startAt: 0 });
|
||||
expect(plan[0].variantLabel).toBe("a");
|
||||
expect(plan[0].subject).toBe("A Ada");
|
||||
expect(plan[1].variantLabel).toBe("b");
|
||||
expect(plan[1].subject).toBe("B Bo");
|
||||
});
|
||||
});
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
// 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),
|
||||
};
|
||||
});
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
// AK-P14b (P14 email marketing) — pure personalization + footer injection.
|
||||
//
|
||||
// Replaces `{{token}}` placeholders in subject/body with per-recipient values
|
||||
// (standard contact tokens + tenant custom fields as `{{cf.<key>}}`), and injects
|
||||
// the DSGVO-mandatory footer (Impressum + unsubscribe link) when missing. PURE:
|
||||
// no DB, no React — fully unit-testable. Used by the send-engine (S3) and the
|
||||
// pre-send checklist (S5).
|
||||
|
||||
/** Standard token source for a recipient. */
|
||||
export interface RecipientTokenSource {
|
||||
vorname?: string | null;
|
||||
nachname?: string | null;
|
||||
email?: string | null;
|
||||
orgName?: string | null;
|
||||
/** Tenant custom-field values by field key (rendered as `{{cf.<key>}}`). */
|
||||
customFields?: Record<string, string>;
|
||||
}
|
||||
|
||||
/** Build the `{{token}} → value` map for a recipient. Missing values render
|
||||
* as empty strings so a template never leaks a raw `{{token}}`. */
|
||||
export function buildTokenMap(source: RecipientTokenSource): Record<string, string> {
|
||||
const map: Record<string, string> = {
|
||||
firstName: source.vorname ?? "",
|
||||
lastName: source.nachname ?? "",
|
||||
email: source.email ?? "",
|
||||
company_name: source.orgName ?? "",
|
||||
};
|
||||
for (const [key, value] of Object.entries(source.customFields ?? {})) {
|
||||
map[`cf.${key}`] = value;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
const TOKEN_PATTERN = /\{\{\s*([\w.]+)\s*\}\}/g;
|
||||
|
||||
/** Replace every `{{token}}` with its mapped value. Unknown tokens collapse to
|
||||
* an empty string (never left raw in a sent mail). */
|
||||
export function replaceTokens(template: string, tokens: Record<string, string>): string {
|
||||
return template.replace(TOKEN_PATTERN, (_match, key: string) => tokens[key] ?? "");
|
||||
}
|
||||
|
||||
/** Marker the footer carries so re-injection is idempotent. */
|
||||
export const FOOTER_MARKER = "data-hg-footer";
|
||||
|
||||
/** True when the html already contains an injected footer. */
|
||||
export function hasFooter(html: string): boolean {
|
||||
return html.includes(FOOTER_MARKER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Append the mandatory footer to the html body if not already present. The
|
||||
* footer carries the Impressum + the unsubscribe link; `{{unsubscribeUrl}}` in
|
||||
* the footer template is replaced with the per-recipient URL.
|
||||
*/
|
||||
export function injectFooter(html: string, footerHtml: string, unsubscribeUrl: string): string {
|
||||
if (hasFooter(html)) {
|
||||
return replaceTokens(html, { unsubscribeUrl });
|
||||
}
|
||||
const footer = replaceTokens(footerHtml, { unsubscribeUrl });
|
||||
const wrapped = `<div ${FOOTER_MARKER}="1">${footer}</div>`;
|
||||
return `${html}${wrapped}`;
|
||||
}
|
||||
|
||||
/** Build the public one-click unsubscribe URL for a signed token. */
|
||||
export function buildUnsubscribeUrl(baseUrl: string, token: string): string {
|
||||
const trimmed = baseUrl.replace(/\/+$/, "");
|
||||
return `${trimmed}/unsubscribe/${encodeURIComponent(token)}`;
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildKontaktWhere,
|
||||
collectLookupRefs,
|
||||
lookupRefKey,
|
||||
MAX_SEGMENT_DEPTH,
|
||||
SEGMENT_FILTER_ERRORS,
|
||||
validateSegmentTree,
|
||||
type SegmentNode,
|
||||
} from "./segmentFilter";
|
||||
|
||||
describe("validateSegmentTree", () => {
|
||||
it("accepts a valid nested AND/OR tree", () => {
|
||||
const tree = {
|
||||
op: "and",
|
||||
children: [
|
||||
{ field: "kontaktStatus", in: ["kunde", "bestandskunde"] },
|
||||
{ op: "or", children: [{ field: "tag", tagId: "t1" }, { field: "hasPrimaerEmail", value: true }] },
|
||||
],
|
||||
};
|
||||
const result = validateSegmentTree(tree);
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a non-object root", () => {
|
||||
expect(validateSegmentTree(null)).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidShape });
|
||||
expect(validateSegmentTree("nope")).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidShape });
|
||||
});
|
||||
|
||||
it("rejects an unknown leaf field", () => {
|
||||
expect(validateSegmentTree({ field: "ssn", eq: "x" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
|
||||
});
|
||||
|
||||
it("rejects a leaf with a bad value type", () => {
|
||||
expect(validateSegmentTree({ field: "hasPrimaerEmail", value: "yes" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
|
||||
expect(validateSegmentTree({ field: "kontaktStatus", in: ["bogus"] })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
|
||||
});
|
||||
|
||||
it("rejects a group missing children", () => {
|
||||
expect(validateSegmentTree({ op: "and" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidShape });
|
||||
});
|
||||
|
||||
it("rejects trees nested beyond the depth cap", () => {
|
||||
let node: unknown = { field: "hasPrimaerEmail", value: true };
|
||||
for (let i = 0; i <= MAX_SEGMENT_DEPTH + 1; i += 1) {
|
||||
node = { op: "and", children: [node] };
|
||||
}
|
||||
expect(validateSegmentTree(node)).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.tooDeep });
|
||||
});
|
||||
|
||||
it("accepts an ISO date for createdAfter and rejects garbage", () => {
|
||||
expect(validateSegmentTree({ field: "createdAfter", value: "2026-01-01" }).ok).toBe(true);
|
||||
expect(validateSegmentTree({ field: "createdAfter", value: "not-a-date" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
|
||||
});
|
||||
});
|
||||
|
||||
describe("collectLookupRefs", () => {
|
||||
it("collects unique tag + custom-field refs and dedupes by key", () => {
|
||||
const tree: SegmentNode = {
|
||||
op: "or",
|
||||
children: [
|
||||
{ field: "tag", tagId: "t1" },
|
||||
{ field: "tag", tagId: "t1" }, // dup
|
||||
{ field: "tag", tagId: "t2" },
|
||||
{ field: "customFieldExists", definitionId: "d1" },
|
||||
{ field: "customFieldEquals", definitionId: "d2", value: "DE" },
|
||||
],
|
||||
};
|
||||
const refs = collectLookupRefs(tree);
|
||||
expect(refs.map(lookupRefKey).sort()).toEqual(["cfEquals:d2:string:DE", "cfExists:d1", "tag:t1", "tag:t2"]);
|
||||
});
|
||||
|
||||
it("returns nothing for a tree of only native leaves", () => {
|
||||
expect(collectLookupRefs({ field: "kontaktTyp", eq: "organisation" })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildKontaktWhere", () => {
|
||||
const empty = new Map<string, readonly string[]>();
|
||||
|
||||
it("maps native leaves to Prisma where fragments", () => {
|
||||
expect(buildKontaktWhere({ field: "kontaktTyp", eq: "privatperson" }, empty)).toEqual({ kontaktTyp: "privatperson" });
|
||||
expect(buildKontaktWhere({ field: "kontaktStatus", in: ["kunde"] }, empty)).toEqual({ kontaktStatus: { in: ["kunde"] } });
|
||||
expect(buildKontaktWhere({ field: "hasPrimaerEmail", value: true }, empty)).toEqual({ primaerEmail: { not: null } });
|
||||
expect(buildKontaktWhere({ field: "hasPrimaerEmail", value: false }, empty)).toEqual({ primaerEmail: null });
|
||||
});
|
||||
|
||||
it("resolves a tag leaf to an id-IN fragment", () => {
|
||||
const resolved = new Map<string, readonly string[]>([["tag:t1", ["k1", "k2"]]]);
|
||||
expect(buildKontaktWhere({ field: "tag", tagId: "t1" }, resolved)).toEqual({ id: { in: ["k1", "k2"] } });
|
||||
});
|
||||
|
||||
it("falls back to an empty id-IN (match none) for an unresolved lookup", () => {
|
||||
expect(buildKontaktWhere({ field: "tag", tagId: "missing" }, empty)).toEqual({ id: { in: [] } });
|
||||
});
|
||||
|
||||
it("composes AND / OR groups", () => {
|
||||
const tree: SegmentNode = {
|
||||
op: "and",
|
||||
children: [
|
||||
{ field: "kontaktTyp", eq: "organisation" },
|
||||
{ op: "or", children: [{ field: "hasPrimaerEmail", value: true }] },
|
||||
],
|
||||
};
|
||||
expect(buildKontaktWhere(tree, empty)).toEqual({
|
||||
AND: [{ kontaktTyp: "organisation" }, { OR: [{ primaerEmail: { not: null } }] }],
|
||||
});
|
||||
});
|
||||
});
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
// AK-P14b (P14 email marketing) — pure segment filter logic.
|
||||
//
|
||||
// A RecipientSegment carries a nested AND/OR filter tree (`filterDefinition`
|
||||
// JSONB). This module is PURE (no DB, no React): it validates an untrusted tree,
|
||||
// collects the leaves that need DB resolution (tags / custom fields are
|
||||
// polymorphic in crm.prisma and cannot be a plain Kontakt relation join), and
|
||||
// builds a `Prisma.KontaktWhereInput`-shaped fragment from the tree + the
|
||||
// resolved lookup id-sets. The DB resolution + auto-exclusion happen in
|
||||
// SegmentService.server.ts. Kept pure so it is fully unit-testable with fixtures.
|
||||
|
||||
export type SegmentLogicalOp = "and" | "or";
|
||||
|
||||
export type KontaktTyp = "privatperson" | "organisation";
|
||||
export type KontaktStatus = "kontakt" | "kunde" | "bestandskunde";
|
||||
|
||||
/** A leaf predicate. `tag` / `customField*` are LOOKUP leaves (need DB id-sets);
|
||||
* the rest map directly onto native Kontakt columns. */
|
||||
export type SegmentLeaf =
|
||||
| { field: "kontaktTyp"; eq: KontaktTyp }
|
||||
| { field: "kontaktStatus"; in: KontaktStatus[] }
|
||||
| { field: "zustaendigerUserId"; eq: string }
|
||||
| { field: "createdBefore"; value: string } // ISO date string
|
||||
| { field: "createdAfter"; value: string } // ISO date string
|
||||
| { field: "hasPrimaerEmail"; value: boolean }
|
||||
| { field: "tag"; tagId: string }
|
||||
| { field: "customFieldEquals"; definitionId: string; value: string | number | boolean }
|
||||
| { field: "customFieldExists"; definitionId: string };
|
||||
|
||||
export interface SegmentGroup {
|
||||
op: SegmentLogicalOp;
|
||||
children: SegmentNode[];
|
||||
}
|
||||
|
||||
export type SegmentNode = SegmentGroup | SegmentLeaf;
|
||||
|
||||
/** A leaf that must be resolved to a set of Kontakt ids via the DB. */
|
||||
export type LookupRef =
|
||||
| { kind: "tag"; tagId: string }
|
||||
| { kind: "customFieldEquals"; definitionId: string; value: string | number | boolean }
|
||||
| { kind: "customFieldExists"; definitionId: string };
|
||||
|
||||
// Guard rails against abusive trees (deep nesting / huge node counts).
|
||||
export const MAX_SEGMENT_DEPTH = 6;
|
||||
export const MAX_SEGMENT_NODES = 200;
|
||||
|
||||
/** i18n message keys (M002 Klartext) the service maps to a catalog/VM error. */
|
||||
export const SEGMENT_FILTER_ERRORS = {
|
||||
invalidShape: "emailMarketing.segment.error.invalidShape",
|
||||
tooDeep: "emailMarketing.segment.error.tooDeep",
|
||||
tooManyNodes: "emailMarketing.segment.error.tooManyNodes",
|
||||
invalidLeaf: "emailMarketing.segment.error.invalidLeaf",
|
||||
} as const;
|
||||
|
||||
export type SegmentValidationError = (typeof SEGMENT_FILTER_ERRORS)[keyof typeof SEGMENT_FILTER_ERRORS];
|
||||
|
||||
export type SegmentValidation = { ok: true; tree: SegmentNode } | { ok: false; errorKey: SegmentValidationError };
|
||||
|
||||
function isGroup(node: SegmentNode): node is SegmentGroup {
|
||||
return (node as SegmentGroup).op === "and" || (node as SegmentGroup).op === "or";
|
||||
}
|
||||
|
||||
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === "object" && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
function validateLeaf(raw: Record<string, unknown>): SegmentLeaf | null {
|
||||
const field = raw.field;
|
||||
switch (field) {
|
||||
case "kontaktTyp":
|
||||
return raw.eq === "privatperson" || raw.eq === "organisation" ? { field, eq: raw.eq } : null;
|
||||
case "kontaktStatus": {
|
||||
if (!Array.isArray(raw.in) || raw.in.length === 0) return null;
|
||||
const allowed: KontaktStatus[] = ["kontakt", "kunde", "bestandskunde"];
|
||||
const values = raw.in.filter((v): v is KontaktStatus => allowed.includes(v as KontaktStatus));
|
||||
return values.length === raw.in.length ? { field, in: values } : null;
|
||||
}
|
||||
case "zustaendigerUserId":
|
||||
return typeof raw.eq === "string" && raw.eq.length > 0 ? { field, eq: raw.eq } : null;
|
||||
case "createdBefore":
|
||||
case "createdAfter":
|
||||
return typeof raw.value === "string" && !Number.isNaN(Date.parse(raw.value)) ? { field, value: raw.value } : null;
|
||||
case "hasPrimaerEmail":
|
||||
return typeof raw.value === "boolean" ? { field, value: raw.value } : null;
|
||||
case "tag":
|
||||
return typeof raw.tagId === "string" && raw.tagId.length > 0 ? { field, tagId: raw.tagId } : null;
|
||||
case "customFieldExists":
|
||||
return typeof raw.definitionId === "string" && raw.definitionId.length > 0 ? { field, definitionId: raw.definitionId } : null;
|
||||
case "customFieldEquals": {
|
||||
if (typeof raw.definitionId !== "string" || raw.definitionId.length === 0) return null;
|
||||
const value = raw.value;
|
||||
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
||||
return { field, definitionId: raw.definitionId, value };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function validateNode(raw: unknown, depth: number, counter: { n: number }): SegmentNode | SegmentValidationError {
|
||||
if (depth > MAX_SEGMENT_DEPTH) return SEGMENT_FILTER_ERRORS.tooDeep;
|
||||
counter.n += 1;
|
||||
if (counter.n > MAX_SEGMENT_NODES) return SEGMENT_FILTER_ERRORS.tooManyNodes;
|
||||
if (!isPlainObject(raw)) return SEGMENT_FILTER_ERRORS.invalidShape;
|
||||
|
||||
if (raw.op === "and" || raw.op === "or") {
|
||||
if (!Array.isArray(raw.children)) return SEGMENT_FILTER_ERRORS.invalidShape;
|
||||
const children: SegmentNode[] = [];
|
||||
for (const child of raw.children) {
|
||||
const result = validateNode(child, depth + 1, counter);
|
||||
if (typeof result === "string") return result;
|
||||
children.push(result);
|
||||
}
|
||||
return { op: raw.op, children };
|
||||
}
|
||||
|
||||
if (typeof raw.field === "string") {
|
||||
const leaf = validateLeaf(raw);
|
||||
return leaf ?? SEGMENT_FILTER_ERRORS.invalidLeaf;
|
||||
}
|
||||
|
||||
return SEGMENT_FILTER_ERRORS.invalidShape;
|
||||
}
|
||||
|
||||
/** Validate an untrusted `filterDefinition` into a typed tree (or an error key). */
|
||||
export function validateSegmentTree(input: unknown): SegmentValidation {
|
||||
const result = validateNode(input, 0, { n: 0 });
|
||||
if (typeof result === "string") return { ok: false, errorKey: result };
|
||||
return { ok: true, tree: result };
|
||||
}
|
||||
|
||||
/** Stable key for a lookup ref, used to map resolution results back. */
|
||||
export function lookupRefKey(ref: LookupRef): string {
|
||||
switch (ref.kind) {
|
||||
case "tag":
|
||||
return `tag:${ref.tagId}`;
|
||||
case "customFieldExists":
|
||||
return `cfExists:${ref.definitionId}`;
|
||||
case "customFieldEquals":
|
||||
return `cfEquals:${ref.definitionId}:${typeof ref.value}:${String(ref.value)}`;
|
||||
}
|
||||
}
|
||||
|
||||
function leafLookupRef(leaf: SegmentLeaf): LookupRef | null {
|
||||
switch (leaf.field) {
|
||||
case "tag":
|
||||
return { kind: "tag", tagId: leaf.tagId };
|
||||
case "customFieldExists":
|
||||
return { kind: "customFieldExists", definitionId: leaf.definitionId };
|
||||
case "customFieldEquals":
|
||||
return { kind: "customFieldEquals", definitionId: leaf.definitionId, value: leaf.value };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Collect the unique lookup leaves (by key) that need DB resolution. */
|
||||
export function collectLookupRefs(node: SegmentNode): LookupRef[] {
|
||||
const byKey = new Map<string, LookupRef>();
|
||||
const walk = (n: SegmentNode): void => {
|
||||
if (isGroup(n)) {
|
||||
n.children.forEach(walk);
|
||||
return;
|
||||
}
|
||||
const ref = leafLookupRef(n);
|
||||
if (ref) byKey.set(lookupRefKey(ref), ref);
|
||||
};
|
||||
walk(node);
|
||||
return [...byKey.values()];
|
||||
}
|
||||
|
||||
/** A Prisma.KontaktWhereInput-shaped fragment (kept loose to stay DB-free). */
|
||||
export type KontaktWhereFragment = Record<string, unknown>;
|
||||
|
||||
function leafToWhere(leaf: SegmentLeaf, resolved: ReadonlyMap<string, readonly string[]>): KontaktWhereFragment {
|
||||
switch (leaf.field) {
|
||||
case "kontaktTyp":
|
||||
return { kontaktTyp: leaf.eq };
|
||||
case "kontaktStatus":
|
||||
return { kontaktStatus: { in: leaf.in } };
|
||||
case "zustaendigerUserId":
|
||||
return { zustaendigerUserId: leaf.eq };
|
||||
case "createdBefore":
|
||||
return { createdAt: { lt: new Date(leaf.value) } };
|
||||
case "createdAfter":
|
||||
return { createdAt: { gt: new Date(leaf.value) } };
|
||||
case "hasPrimaerEmail":
|
||||
return leaf.value ? { primaerEmail: { not: null } } : { primaerEmail: null };
|
||||
case "tag":
|
||||
case "customFieldExists":
|
||||
case "customFieldEquals": {
|
||||
const ref = leafLookupRef(leaf);
|
||||
const ids = (ref && resolved.get(lookupRefKey(ref))) ?? [];
|
||||
return { id: { in: [...ids] } };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a `Prisma.KontaktWhereInput`-shaped fragment from the tree and the
|
||||
* resolved lookup id-sets. Empty AND ⇒ match all; empty OR ⇒ match none
|
||||
* (Prisma's native semantics for `{ AND: [] }` / `{ OR: [] }`).
|
||||
*/
|
||||
export function buildKontaktWhere(node: SegmentNode, resolved: ReadonlyMap<string, readonly string[]>): KontaktWhereFragment {
|
||||
if (isGroup(node)) {
|
||||
const children = node.children.map((c) => buildKontaktWhere(c, resolved));
|
||||
return node.op === "and" ? { AND: children } : { OR: children };
|
||||
}
|
||||
return leafToWhere(node, resolved);
|
||||
}
|
||||
Reference in new issue
Block a user