Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,140 @@
import type { VMState } from "../index.js";
/**
* AK-P14b · campaign detail + reporting view-model (DoD 6). Pure — no
* React/Prisma. Turns raw aggregate counts + per-recipient rows + click rows
* into KPI percentages, a sorted click-map, the per-recipient table and the A/B
* comparison. Percentages are integer-rounded; rates use delivered as the
* denominator (0 when nothing delivered).
*/
export type CampaignVariantLabel = "a" | "b";
export interface CampaignStatsInput {
total: number;
delivered: number;
opened: number;
clicked: number;
bounced: number;
unsubscribed: number;
}
export interface CampaignClickInput {
link: string;
count: number;
}
export interface CampaignRecipientInput {
email: string;
name: string;
variantLabel: CampaignVariantLabel | null;
deliveredAt: Date | null;
openedAt: Date | null;
clickedAt: Date | null;
bouncedAt: Date | null;
}
export interface CampaignVariantStatsInput {
label: CampaignVariantLabel;
subject: string;
delivered: number;
opened: number;
clicked: number;
}
export interface BuildCampaignDetailVMInput {
campaign: { id: string; name: string; subject: string; status: string; sentAt: Date | null };
stats: CampaignStatsInput;
clickMap: readonly CampaignClickInput[];
recipients: readonly CampaignRecipientInput[];
variants?: readonly CampaignVariantStatsInput[];
}
export interface KpiVM {
readonly delivered: number;
readonly openRate: number;
readonly clickRate: number;
readonly bounceRate: number;
readonly unsubscribeRate: number;
}
export interface ClickMapRowVM {
readonly link: string;
readonly count: number;
}
export type RecipientStatus = "bounced" | "clicked" | "opened" | "delivered" | "pending";
export interface RecipientRowVM {
readonly email: string;
readonly name: string;
readonly variantLabel: CampaignVariantLabel | null;
readonly status: RecipientStatus;
readonly statusLabelKey: string;
}
export interface VariantComparisonRowVM {
readonly label: CampaignVariantLabel;
readonly subject: string;
readonly delivered: number;
readonly openRate: number;
readonly clickRate: number;
}
export interface CampaignDetailData {
readonly id: string;
readonly name: string;
readonly subject: string;
readonly status: string;
readonly statusLabelKey: string;
readonly sentAtIso: string | null;
readonly kpi: KpiVM;
readonly clickMap: readonly ClickMapRowVM[];
readonly recipients: readonly RecipientRowVM[];
readonly variants: readonly VariantComparisonRowVM[];
readonly hasAbTest: boolean;
}
export type CampaignDetailVM = VMState<CampaignDetailData>;
export function rate(numerator: number, denominator: number): number {
return denominator > 0 ? Math.round((numerator / denominator) * 100) : 0;
}
function recipientStatus(r: CampaignRecipientInput): RecipientStatus {
if (r.bouncedAt) return "bounced";
if (r.clickedAt) return "clicked";
if (r.openedAt) return "opened";
if (r.deliveredAt) return "delivered";
return "pending";
}
export function buildCampaignDetailVM(input: BuildCampaignDetailVMInput): CampaignDetailVM {
const { stats } = input;
const variants = input.variants ?? [];
return {
status: "ready",
data: {
id: input.campaign.id,
name: input.campaign.name,
subject: input.campaign.subject,
status: input.campaign.status,
statusLabelKey: `emailMarketing.campaign.status.${input.campaign.status}`,
sentAtIso: input.campaign.sentAt ? input.campaign.sentAt.toISOString() : null,
kpi: {
delivered: stats.delivered,
openRate: rate(stats.opened, stats.delivered),
clickRate: rate(stats.clicked, stats.delivered),
bounceRate: rate(stats.bounced, stats.total),
unsubscribeRate: rate(stats.unsubscribed, stats.delivered),
},
clickMap: [...input.clickMap].sort((a, b) => b.count - a.count).map((c) => ({ link: c.link, count: c.count })),
recipients: input.recipients.map((r) => {
const status = recipientStatus(r);
return { email: r.email, name: r.name, variantLabel: r.variantLabel, status, statusLabelKey: `emailMarketing.recipient.status.${status}` };
}),
variants: variants.map((v) => ({ label: v.label, subject: v.subject, delivered: v.delivered, openRate: rate(v.opened, v.delivered), clickRate: rate(v.clicked, v.delivered) })),
hasAbTest: variants.length > 0,
},
};
}
@@ -0,0 +1,54 @@
import type { VMState } from "../index.js";
import { rate } from "./campaign-detail.vm.js";
/**
* AK-P14b · campaign list view-model (DoD 6). Pure — no React/Prisma. One row
* per campaign with status pill, recipient count, send date and open/click rate.
*/
export interface CampaignListItemInput {
id: string;
name: string;
status: string;
recipientCount: number;
delivered: number;
opened: number;
clicked: number;
sentAt: Date | null;
}
export interface CampaignListRowVM {
readonly id: string;
readonly name: string;
readonly status: string;
readonly statusLabelKey: string;
readonly recipientCount: number;
readonly openRate: number;
readonly clickRate: number;
readonly sentAtIso: string | null;
}
export interface CampaignListData {
readonly rows: readonly CampaignListRowVM[];
}
export type CampaignListVM = VMState<CampaignListData>;
export function buildCampaignListVM(input: { items: readonly CampaignListItemInput[] }): CampaignListVM {
if (input.items.length === 0) return { status: "empty" };
return {
status: "ready",
data: {
rows: input.items.map((c) => ({
id: c.id,
name: c.name,
status: c.status,
statusLabelKey: `emailMarketing.campaign.status.${c.status}`,
recipientCount: c.recipientCount,
openRate: rate(c.opened, c.delivered),
clickRate: rate(c.clicked, c.delivered),
sentAtIso: c.sentAt ? c.sentAt.toISOString() : null,
})),
},
};
}
@@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import { buildPresendChecklistVM, evaluatePresendChecklist } from "./presend-checklist.vm.js";
import { buildCampaignDetailVM, rate } from "./campaign-detail.vm.js";
import { buildCampaignListVM } from "./campaign-list.vm.js";
import { buildSegmentVM } from "./segment.vm.js";
describe("presend-checklist.vm", () => {
const ok = { domainVerified: true, footerConfigured: true, subject: "Hi", recipientCount: 10, dailyCapUsed: 0, dailyCapLimit: 1000 };
it("passes when all green", () => {
expect(evaluatePresendChecklist(ok).blocked).toBe(false);
});
it("blocks on unverified domain + over cap + empty subject + 0 recipients", () => {
expect(evaluatePresendChecklist({ ...ok, domainVerified: false }).blocked).toBe(true);
expect(evaluatePresendChecklist({ ...ok, dailyCapUsed: 995, recipientCount: 10, dailyCapLimit: 1000 }).blocked).toBe(true);
expect(evaluatePresendChecklist({ ...ok, dailyCapUsed: 9e9, dailyCapLimit: null }).blocked).toBe(false);
expect(evaluatePresendChecklist({ ...ok, subject: " " }).blocked).toBe(true);
expect(evaluatePresendChecklist({ ...ok, recipientCount: 0 }).blocked).toBe(true);
});
it("VM adds label keys + tone + fix key", () => {
const vm = buildPresendChecklistVM({ ...ok, domainVerified: false });
expect(vm.status).toBe("ready");
const domain = vm.data?.items.find((i) => i.key === "domain");
expect(domain).toMatchObject({ ok: false, tone: "danger", labelKey: "emailMarketing.presend.check.domain", fixKey: "emailMarketing.presend.fix.domain" });
expect(vm.data?.blocked).toBe(true);
});
});
describe("campaign-detail.vm", () => {
it("rate() rounds and guards zero denominator", () => {
expect(rate(1, 4)).toBe(25);
expect(rate(1, 3)).toBe(33);
expect(rate(5, 0)).toBe(0);
});
it("computes KPIs, sorts click-map, classifies recipients, builds A/B", () => {
const vm = buildCampaignDetailVM({
campaign: { id: "c1", name: "N", subject: "S", status: "completed", sentAt: new Date("2026-06-01T00:00:00Z") },
stats: { total: 100, delivered: 80, opened: 40, clicked: 20, bounced: 20, unsubscribed: 8 },
clickMap: [
{ link: "https://a", count: 3 },
{ link: "https://b", count: 9 },
],
recipients: [
{ email: "a@x.de", name: "A", variantLabel: "a", deliveredAt: new Date(), openedAt: new Date(), clickedAt: new Date(), bouncedAt: null },
{ email: "b@x.de", name: "B", variantLabel: "b", deliveredAt: new Date(), openedAt: null, clickedAt: null, bouncedAt: null },
{ email: "c@x.de", name: "C", variantLabel: null, deliveredAt: null, openedAt: null, clickedAt: null, bouncedAt: new Date() },
],
variants: [
{ label: "a", subject: "A", delivered: 40, opened: 24, clicked: 12 },
{ label: "b", subject: "B", delivered: 40, opened: 16, clicked: 8 },
],
});
expect(vm.data?.kpi).toEqual({ delivered: 80, openRate: 50, clickRate: 25, bounceRate: 20, unsubscribeRate: 10 });
expect(vm.data?.clickMap.map((c) => c.link)).toEqual(["https://b", "https://a"]);
expect(vm.data?.recipients.map((r) => r.status)).toEqual(["clicked", "delivered", "bounced"]);
expect(vm.data?.hasAbTest).toBe(true);
expect(vm.data?.variants[0]).toMatchObject({ label: "a", openRate: 60, clickRate: 30 });
});
});
describe("campaign-list.vm", () => {
it("is empty with no items and builds rows otherwise", () => {
expect(buildCampaignListVM({ items: [] }).status).toBe("empty");
const vm = buildCampaignListVM({ items: [{ id: "c1", name: "N", status: "draft", recipientCount: 5, delivered: 4, opened: 2, clicked: 1, sentAt: null }] });
expect(vm.data?.rows[0]).toMatchObject({ id: "c1", statusLabelKey: "emailMarketing.campaign.status.draft", openRate: 50, clickRate: 25, sentAtIso: null });
});
});
describe("segment.vm", () => {
it("sums exclusion and exposes labelled rows", () => {
const vm = buildSegmentVM({
matched: 100,
eligible: 70,
exclusion: { archived: 5, noEmail: 10, unsubscribed: 6, suppressed: 4, noOptIn: 5 },
sample: [{ kontaktId: "k1", name: "Ada", email: "ada@x.de" }],
scanCapped: false,
isStaticSnapshot: false,
});
expect(vm.data?.excludedTotal).toBe(30);
expect(vm.data?.exclusion.map((r) => r.reason)).toEqual(["archived", "noEmail", "unsubscribed", "suppressed", "noOptIn"]);
expect(vm.data?.exclusion[0]).toMatchObject({ labelKey: "emailMarketing.segment.exclusion.archived", count: 5 });
expect(vm.data?.sample).toHaveLength(1);
});
});
@@ -0,0 +1,95 @@
import type { VMState } from "../index.js";
/**
* AK-P14b · pre-send checklist (DoD 5). Pure — no React/Prisma. Computes the
* DSGVO/deliverability gate that BLOCKS a campaign send when red: verified
* sending domain, unsubscribe link, Impressum, subject, > 0 recipients, daily
* cap. The server send-engine calls `evaluatePresendChecklist` as a hard gate;
* the route renders `buildPresendChecklistVM` with i18n labels + fix-links.
*/
export type PresendCheckKey = "domain" | "unsubscribe" | "impressum" | "subject" | "recipients" | "dailyCap";
export interface PresendChecklistInput {
/** TenantSendingDomain.verificationStatus === "verified". */
domainVerified: boolean;
/** A non-empty footer is configured (carries unsubscribe link + Impressum). */
footerConfigured: boolean;
subject: string;
recipientCount: number;
/** Sends already counted against today's cap for this tenant. */
dailyCapUsed: number;
/** Daily send cap; null = no cap configured. */
dailyCapLimit: number | null;
}
export interface PresendCheckItem {
key: PresendCheckKey;
ok: boolean;
/** i18n key for the fix action (only present when not ok). */
fixKey?: string;
}
export interface PresendChecklistResult {
items: PresendCheckItem[];
/** True when at least one check failed — the send action must be blocked. */
blocked: boolean;
}
const FIX_KEYS: Record<PresendCheckKey, string> = {
domain: "emailMarketing.presend.fix.domain",
unsubscribe: "emailMarketing.presend.fix.unsubscribe",
impressum: "emailMarketing.presend.fix.impressum",
subject: "emailMarketing.presend.fix.subject",
recipients: "emailMarketing.presend.fix.recipients",
dailyCap: "emailMarketing.presend.fix.dailyCap",
};
export function evaluatePresendChecklist(input: PresendChecklistInput): PresendChecklistResult {
const withinCap = input.dailyCapLimit === null || input.dailyCapUsed + input.recipientCount <= input.dailyCapLimit;
const checks: Array<[PresendCheckKey, boolean]> = [
["domain", input.domainVerified],
["unsubscribe", input.footerConfigured],
["impressum", input.footerConfigured],
["subject", input.subject.trim().length > 0],
["recipients", input.recipientCount > 0],
["dailyCap", withinCap],
];
const items: PresendCheckItem[] = checks.map(([key, ok]) => (ok ? { key, ok } : { key, ok, fixKey: FIX_KEYS[key] }));
return { items, blocked: items.some((i) => !i.ok) };
}
// --- View-model (presentation: i18n labels + tone) -------------------------
export interface PresendCheckItemVM {
readonly key: PresendCheckKey;
readonly ok: boolean;
/** i18n label key, e.g. `emailMarketing.presend.check.domain`. */
readonly labelKey: string;
readonly tone: "success" | "danger";
readonly fixKey: string | null;
}
export interface PresendChecklistData {
readonly items: readonly PresendCheckItemVM[];
readonly blocked: boolean;
}
export type PresendChecklistVM = VMState<PresendChecklistData>;
export function buildPresendChecklistVM(input: PresendChecklistInput): PresendChecklistVM {
const result = evaluatePresendChecklist(input);
return {
status: "ready",
data: {
blocked: result.blocked,
items: result.items.map((i) => ({
key: i.key,
ok: i.ok,
labelKey: `emailMarketing.presend.check.${i.key}`,
tone: i.ok ? "success" : "danger",
fixKey: i.fixKey ?? null,
})),
},
};
}
@@ -0,0 +1,74 @@
import type { VMState } from "../index.js";
/**
* AK-P14b · segment resolution view-model (DoD 2). Pure — no React/Prisma. Turns
* a SegmentService resolution (matched / eligible / non-overlapping exclusion
* breakdown / sample) into the segment screen: live recipient count, the
* auto-exclusion rows (each with an i18n label) and the sample preview.
*/
export type SegmentExclusionReason = "archived" | "noEmail" | "unsubscribed" | "suppressed" | "noOptIn";
export interface SegmentExclusionInput {
archived: number;
noEmail: number;
unsubscribed: number;
suppressed: number;
noOptIn: number;
}
export interface SegmentSampleInput {
kontaktId: string;
name: string;
email: string;
}
export interface BuildSegmentVMInput {
matched: number;
eligible: number;
exclusion: SegmentExclusionInput;
sample: readonly SegmentSampleInput[];
scanCapped: boolean;
isStaticSnapshot: boolean;
}
export interface SegmentExclusionRowVM {
readonly reason: SegmentExclusionReason;
readonly labelKey: string;
readonly count: number;
}
export interface SegmentData {
readonly matched: number;
readonly eligible: number;
readonly excludedTotal: number;
readonly exclusion: readonly SegmentExclusionRowVM[];
readonly sample: readonly SegmentSampleInput[];
readonly scanCapped: boolean;
readonly isStaticSnapshot: boolean;
}
export type SegmentVM = VMState<SegmentData>;
const REASON_ORDER: SegmentExclusionReason[] = ["archived", "noEmail", "unsubscribed", "suppressed", "noOptIn"];
export function buildSegmentVM(input: BuildSegmentVMInput): SegmentVM {
const exclusion = REASON_ORDER.map((reason) => ({
reason,
labelKey: `emailMarketing.segment.exclusion.${reason}`,
count: input.exclusion[reason],
}));
const excludedTotal = exclusion.reduce((sum, row) => sum + row.count, 0);
return {
status: "ready",
data: {
matched: input.matched,
eligible: input.eligible,
excludedTotal,
exclusion,
sample: input.sample.map((s) => ({ kontaktId: s.kontaktId, name: s.name, email: s.email })),
scanCapped: input.scanCapped,
isStaticSnapshot: input.isStaticSnapshot,
},
};
}
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { buildSendingDomainVM } from "./sending-domain.vm.js";
const baseDomain = {
id: "d1",
domain: "acme.test",
status: "verifying" as const,
dkimSelector: "mailjet._domainkey.acme.test",
dkimRecord: "v=DKIM1; k=rsa; p=MIIB...",
spfRecord: "v=spf1 include:spf.mailjet.com ~all",
dmarcRecord: "v=DMARC1; p=none",
errorMessageKey: null,
};
describe("buildSendingDomainVM", () => {
it("returns empty state when no domain is configured", () => {
const vm = buildSendingDomainVM({ domain: null, bccAddress: null, bccEnabled: false, canManage: true });
expect(vm.status).toBe("empty");
});
it("builds three DNS record cards with copy values and the status ampel", () => {
const vm = buildSendingDomainVM({ domain: baseDomain, bccAddress: "crm@acme.test", bccEnabled: true, canManage: true });
expect(vm.status).toBe("ready");
expect(vm.data?.records.map((r) => r.kind)).toEqual(["dkim", "spf", "dmarc"]);
expect(vm.data?.records[2]).toMatchObject({ kind: "dmarc", host: "_dmarc.acme.test", value: "v=DMARC1; p=none" });
expect(vm.data?.statusLabelKey).toBe("email.domain.status.verifying");
expect(vm.data?.statusTone).toBe("warning");
expect(vm.data?.canSend).toBe(false);
expect(vm.data?.bccAddress).toBe("crm@acme.test");
expect(vm.data?.bccEnabled).toBe(true);
});
it("unlocks sending and uses the success tone when verified", () => {
const vm = buildSendingDomainVM({ domain: { ...baseDomain, status: "verified" }, bccAddress: null, bccEnabled: false, canManage: false });
expect(vm.data?.canSend).toBe(true);
expect(vm.data?.statusTone).toBe("success");
expect(vm.data?.showFailure).toBe(false);
expect(vm.data?.errorMessageKey).toBeNull();
});
it("surfaces the 7-day Klartext failure when failed", () => {
const vm = buildSendingDomainVM({ domain: { ...baseDomain, status: "failed", errorMessageKey: "email.domain.error.notVerifiedAfter7Days" }, bccAddress: null, bccEnabled: false, canManage: true });
expect(vm.data?.showFailure).toBe(true);
expect(vm.data?.statusTone).toBe("danger");
expect(vm.data?.errorMessageKey).toBe("email.domain.error.notVerifiedAfter7Days");
});
it("falls back to the default failure key when failed without a detail", () => {
const vm = buildSendingDomainVM({ domain: { ...baseDomain, status: "failed", errorMessageKey: null }, bccAddress: null, bccEnabled: false, canManage: true });
expect(vm.data?.errorMessageKey).toBe("email.domain.error.notVerifiedAfter7Days");
});
});
@@ -0,0 +1,104 @@
import type { VMState } from "../index.js";
/**
* AK-P14a · Sending-domain view-model. Pure functions — no React, no Prisma, no
* app imports. Maps a TenantSendingDomain (+ its BCC-logging inbound address)
* into the settings screen: DNS record cards with copy values, the verification
* status ampel (pending/verifying/verified/failed) with a tone token, the 7-day
* Klartext failure surface, and the BCC-logging toggle.
*/
export type SendingDomainStatusVM = "pending" | "verifying" | "verified" | "failed";
export type DnsRecordKind = "dkim" | "spf" | "dmarc";
export interface DnsRecordCard {
readonly kind: DnsRecordKind;
/** i18n label key, e.g. `email.domain.record.dkim`. */
readonly labelKey: string;
/** Host/name the tenant publishes the record at (may be null until provisioned). */
readonly host: string | null;
/** The record value to copy (null until Mailjet returns it). */
readonly value: string | null;
}
export interface SendingDomainData {
readonly hasDomain: boolean;
readonly id: string | null;
readonly domain: string | null;
readonly status: SendingDomainStatusVM;
/** i18n key for the status pill, e.g. `email.domain.status.verified`. */
readonly statusLabelKey: string;
readonly statusTone: "success" | "warning" | "danger" | "neutral";
readonly records: readonly DnsRecordCard[];
/** True once the domain has failed (incomplete > 7 days) → show Klartext error. */
readonly showFailure: boolean;
/** i18n key carrying the Klartext failure detail, or null. */
readonly errorMessageKey: string | null;
/** Whether sending is unlocked (verified) — gates the marketing send (AK-P14b). */
readonly canSend: boolean;
readonly bccAddress: string | null;
readonly bccEnabled: boolean;
readonly canManage: boolean;
readonly emptyHeadlineKey: string;
readonly emptyBodyKey: string;
}
export type SendingDomainVM = VMState<SendingDomainData>;
const STATUS_TONE: Record<SendingDomainStatusVM, SendingDomainData["statusTone"]> = {
pending: "neutral",
verifying: "warning",
verified: "success",
failed: "danger",
};
export interface BuildSendingDomainVMInput {
readonly domain: {
readonly id: string;
readonly domain: string;
readonly status: SendingDomainStatusVM;
readonly dkimSelector: string | null;
readonly dkimRecord: string | null;
readonly spfRecord: string | null;
readonly dmarcRecord: string | null;
readonly errorMessageKey: string | null;
} | null;
readonly bccAddress: string | null;
readonly bccEnabled: boolean;
readonly canManage: boolean;
}
export function buildSendingDomainVM(input: BuildSendingDomainVMInput): SendingDomainVM {
if (!input.domain) {
return {
status: "empty",
};
}
const d = input.domain;
const records: DnsRecordCard[] = [
{ kind: "dkim", labelKey: "email.domain.record.dkim", host: d.dkimSelector, value: d.dkimRecord },
{ kind: "spf", labelKey: "email.domain.record.spf", host: d.domain, value: d.spfRecord },
{ kind: "dmarc", labelKey: "email.domain.record.dmarc", host: `_dmarc.${d.domain}`, value: d.dmarcRecord },
];
return {
status: "ready",
data: {
hasDomain: true,
id: d.id,
domain: d.domain,
status: d.status,
statusLabelKey: `email.domain.status.${d.status}`,
statusTone: STATUS_TONE[d.status],
records,
showFailure: d.status === "failed",
errorMessageKey: d.status === "failed" ? d.errorMessageKey ?? "email.domain.error.notVerifiedAfter7Days" : null,
canSend: d.status === "verified",
bccAddress: input.bccAddress,
bccEnabled: input.bccEnabled,
canManage: input.canManage,
emptyHeadlineKey: "email.domain.empty.headline",
emptyBodyKey: "email.domain.empty.body",
},
};
}