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

@@ -1,4 +1,3 @@
import { Link, useParams } from "react-router";
import clsx from "clsx";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -6,53 +5,38 @@ import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
import { Colors } from "~/application/enums/shared/Colors";
import { OutboundEmailWithDetails } from "~/modules/emailMarketing/db/outboundEmails.db.server";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import RowHelper from "~/utils/helpers/RowHelper";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import CheckIcon from "~/components/ui/icons/CheckIcon";
import XIcon from "~/components/ui/icons/XIcon";
import Modal from "~/components/ui/modals/Modal";
import TableSimple from "~/components/ui/tables/TableSimple";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { createLocaleFormatters, useLocaleFormatters } from "~/locale/format";
export default function OutboundEmailsTable({
items,
pagination,
withCampaign,
allEntities,
}: {
items: OutboundEmailWithDetails[];
pagination?: PaginationDto;
withCampaign?: boolean;
allEntities: EntityWithDetails[];
}) {
const { t, i18n } = useTranslation();
const formatters = useMemo(() => createLocaleFormatters(i18n.language), [i18n.language]);
const params = useParams();
const [headers, setHeaders] = useState<RowHeaderDisplayDto<OutboundEmailWithDetails>[]>([]);
const [contactEntity, setContactEntity] = useState<EntityWithDetails>();
const [selectedEmail, setSelectedEmail] = useState<OutboundEmailWithDetails>();
useEffect(() => {
setContactEntity(allEntities.find((e) => e.name === "contact"));
}, [allEntities]);
useEffect(() => {
let headers: RowHeaderDisplayDto<OutboundEmailWithDetails>[] = [
{
// R-P14C: recipient is identified by the typed `email` field. The former
// Entity-Builder contact-name lookup (RowHelper + contactRow) is removed.
name: "email",
title: t("emails.to"),
value: (i) => (
<div className="flex flex-col">
<div>
{i.contactRow && contactEntity ? (
<div>{RowHelper.getTextDescription({ entity: contactEntity, item: i.contactRow, t })}</div>
) : (
<div className="text-muted-foreground text-xs italic">
<div>{i.email}</div>
</div>
)}
<div className="text-muted-foreground text-xs italic">
<div>{i.email}</div>
</div>
</div>
),
@@ -127,21 +111,14 @@ export default function OutboundEmailsTable({
if (withCampaign) {
headers = [
{
// R-P14C: the campaign-detail editor route was removed (Variante A);
// show the campaign name as plain text until David's bespoke editor.
name: "campaignId",
title: t("emailMarketing:campaign"),
value: (item) => (
<div>
{item.campaignId ? (
<Link
to={
params.tenant
? appPath({ tenantSlug: params.tenant, path: `email-marketing/campaigns/${item.campaignId}`, mode: "host-aware" })
: adminPath(`email-marketing/campaigns/${item.campaignId}`, { mode: "host-aware" })
}
className="focus:bg-secondary/90 hover:border-border rounded-md border-b border-dashed border-transparent"
>
{item.campaign?.name}
</Link>
<div>{item.campaign?.name}</div>
) : (
<div>{item.isPreview ? <SimpleBadge title={t("shared.preview")} color={Colors.GRAY} /> : <div>-</div>}</div>
)}
@@ -152,7 +129,7 @@ export default function OutboundEmailsTable({
];
}
setHeaders(headers);
}, [contactEntity, formatters, params.tenant, t, withCampaign]);
}, [formatters, t, withCampaign]);
return (
<div>
<TableSimple headers={headers} items={items} pagination={pagination} />
@@ -1,324 +0,0 @@
import { useParams, useSubmit, Form, useActionData, useNavigation, useLoaderData } from "react-router";
import clsx from "clsx";
import { useState, useRef, useEffect, FormEvent } from "react";
import { useTranslation } from "react-i18next";
import { Colors } from "~/application/enums/shared/Colors";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
import InputSearch from "~/components/ui/input/InputSearch";
import InputSelector from "~/components/ui/input/InputSelector";
import InputText from "~/components/ui/input/InputText";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
import { Campaigns_Edit } from "../../routes/Campaigns_Edit";
import OutboundEmailsTable from "../OutboundEmailsTable";
import toast from "react-hot-toast";
import InputContent from "~/components/ui/input/InputContent";
import UrlUtils from "~/utils/app/UrlUtils";
import { useLocaleFormatters } from "~/locale/format";
export default function CampaignsEditRoute() {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const appOrAdminData = useAppOrAdminData();
const params = useParams();
const data = useLoaderData<Campaigns_Edit.LoaderData>();
const actionData = useActionData<Campaigns_Edit.ActionData>();
const navigation = useNavigation();
const submit = useSubmit();
const confirmDelete = useRef<RefConfirmModal>(null);
const [searchInput, setSearchInput] = useState("");
const [maxDisplayedEmails, setMaxDisplayedEmails] = useState(1000000);
const [name, setName] = useState(data.item.name);
const [subject, setSubject] = useState(data.item.subject);
const [senderId, setSenderId] = useState<string | number | undefined>(data.item.emailSenderId);
const [contentType, setContentType] = useState<"wysiwyg" | "markdown">("wysiwyg");
const [htmlBody, setHtmlBody] = useState(data.item.htmlBody);
const recipientCount = data.item.recipients.length;
const formattedRecipientCount = formatters.number(recipientCount);
const modalConfirm = useRef<RefConfirmModal>(null);
useEffect(() => {
if (actionData?.success) {
toast.success(actionData.success);
} else if (actionData?.error) {
toast.error(actionData.error);
}
}, [actionData]);
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.stopPropagation();
e.preventDefault();
const formData = new FormData(e.currentTarget);
submit(formData, {
method: "post",
});
}
function sendTest(i?: RowWithDetails) {
const email = window.prompt(t("emails.object"), appOrAdminData.user?.email);
if (!email || email.trim() === "") {
return;
}
const form = new FormData();
form.set("action", "send-preview");
form.set("email", email);
submit(form, {
method: "post",
});
}
function send() {
modalConfirm.current?.show(
t("emailMarketing:confirmSend"),
t("shared.send"),
t("shared.back"),
t("emailMarketing:sendingToContacts", { count: recipientCount, formattedCount: formattedRecipientCount })
);
}
function onConfirmSend() {
const form = new FormData();
form.set("action", "send");
submit(form, {
method: "post",
});
}
function onDelete() {
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
}
function onDeleteConfirm() {
const form = new FormData();
form.set("action", "delete");
submit(form, {
method: "post",
});
}
// function saveEmail() {
// const form = new FormData();
// form.set("action", "update");
// form.set("htmlBody", htmlBody);
// submit(form, {
// method: "post",
// });
// }
function canUpdate() {
if (data.item.status !== "draft") {
return false;
}
if (
name.trim() === "" ||
name !== data.item.name ||
subject.trim() === "" ||
subject !== data.item.subject ||
senderId !== data.item.emailSenderId ||
htmlBody.trim() !== data.item.htmlBody.trim()
) {
return true;
}
return false;
}
function filteredRecipients() {
let emails = data.item.recipients;
// if (maxDisplayedEmails === 10) {
// emails = emails.slice(0, 10);
// }
if (!searchInput.trim()) {
return emails;
}
return emails.filter((f) => f.email?.toString().toUpperCase().includes(searchInput.toUpperCase()));
}
return (
<EditPageLayout
title={t("emailMarketing:campaignDetails")}
menu={[
{
title: t("emailMarketing:campaigns"),
routePath: UrlUtils.getModulePath(params, "email-marketing/campaigns"),
},
{
title: t("shared.edit"),
routePath: UrlUtils.getModulePath(params, `email-marketing/campaigns/${params.id}`),
},
]}
>
<Form onSubmit={handleSubmit} className="pb-20">
{/* <input type="hidden" name="action" value="create" hidden readOnly /> */}
<input type="hidden" name="action" value="update" hidden readOnly />
<div className="relative space-y-4">
<div className="flex flex-col space-y-4">
{/* <InputGroup title="Email" className="bg-secondary"> */}
<div className="space-y-4">
<div className="grid gap-2 sm:grid-cols-3">
<InputSelector
name="status"
title={t("shared.status")}
value={data.item.status}
withColors={true}
disabled={true}
options={[
{
value: "draft",
name: t("emailMarketing:campaignList.status.draft"),
color: Colors.YELLOW,
},
{
value: "sending",
name: t("emailMarketing:campaignList.status.sending"),
color: Colors.ORANGE,
},
{
value: "incomplete",
name: t("emailMarketing:campaignList.status.incomplete"),
color: Colors.RED,
},
{
value: "completed",
name: t("emailMarketing:campaignList.status.completed"),
color: Colors.GREEN,
},
].map((i) => {
return {
value: i.value,
name: i.name,
color: i.color,
};
})}
/>
<InputText
name="name"
title={t("shared.name")}
value={name}
setValue={setName}
placeholder={t("emailMarketing:campaignList.form.namePlaceholder")}
required
disabled={data.item.status !== "draft"}
/>
<InputSelector
name="senderId"
title={t("emails.sender")}
value={senderId}
setValue={setSenderId}
disabled={data.item.status !== "draft"}
withSearch={false}
options={data.emailSenders.map((s) => {
return {
name: s.fromEmail,
value: s.id,
};
})}
required
/>
<InputText
className="sm:col-span-3"
name="subject"
title={t("emails.subject")}
value={subject}
setValue={setSubject}
required
disabled={data.item.status !== "draft"}
/>
<div className="sm:col-span-3">
<div className="w-full space-y-2">
{/* <Tabs
asLinks={false}
onSelected={(selected) => {
setEmailBodyTab(selected === 0 ? "html" : "text");
}}
className="w-full sm:w-auto"
tabs={[{ name: "HTML" }, { name: "Preview" }]}
/> */}
<div>
{data.item.status === "draft" && <input type="hidden" name="htmlBody" value={htmlBody} hidden readOnly />}
{/* {emailBodyTab === "html" && ( */}
<div className={clsx(data.item.status === "draft" ? "bg-background" : "bg-secondary/90")}>
<InputContent
name="htmlBody"
value={htmlBody}
onChangeValue={setHtmlBody}
contentType={contentType}
onChangeContentType={setContentType}
disabled={data.item.status === "completed"}
/>
</div>
{data.item.status === "draft" && (
<div className="mt-2 flex justify-end">
<ButtonSecondary type="submit" disabled={!canUpdate()}>
{t("shared.saveChanges")}
</ButtonSecondary>
</div>
)}
{/* )} */}
</div>
</div>
</div>
</div>
</div>
{/* </InputGroup> */}
<div className="">
<div className="space-y-2">
<div className="flex justify-between">
<div className="text-foreground text-sm font-medium">
{t("emails.recipientsCount", { count: recipientCount, formattedCount: formattedRecipientCount })}
</div>
</div>
<InputSearch value={searchInput} setValue={setSearchInput} />
<div className="bg-background max-h-96 overflow-auto rounded-md shadow-md">
<OutboundEmailsTable allEntities={data.allEntities} items={filteredRecipients()} />
</div>
<div className="flex justify-end">
{maxDisplayedEmails === 10 && (
<ButtonTertiary onClick={() => setMaxDisplayedEmails(100000)}>
{t("emailMarketing:campaignList.actions.showRecipients", { count: recipientCount, formattedCount: formattedRecipientCount })}
</ButtonTertiary>
)}
</div>
</div>
</div>
{data.item.status === "draft" && (
<div className="flex items-center justify-between">
<div>
{data.item.status === "draft" && (
<ButtonSecondary
destructive
onClick={onDelete}
disabled={data.item.status !== "draft" || navigation.state === "submitting"}
className="truncate"
>
{t("shared.delete")}
</ButtonSecondary>
)}
</div>
<div className="flex justify-between space-x-2">
<ButtonSecondary disabled={navigation.state === "submitting"} onClick={() => sendTest()} className="truncate">
{t("emailMarketing:sendPreview")}
</ButtonSecondary>
<ButtonPrimary disabled={navigation.state === "submitting"} onClick={send} className="truncate">
{t("emailMarketing:sendCampaignToContacts", { count: recipientCount, formattedCount: formattedRecipientCount })}
</ButtonPrimary>
</div>
</div>
)}
</div>
</div>
</Form>
<ConfirmModal ref={modalConfirm} onYes={onConfirmSend} />
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
</EditPageLayout>
);
}
@@ -1,207 +0,0 @@
import { useParams, useLoaderData, useSearchParams } from "react-router";
import { useTranslation } from "react-i18next";
import { Colors } from "~/application/enums/shared/Colors";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import WarningBanner from "~/components/ui/banners/WarningBanner";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import SentIconFilled from "~/components/ui/icons/emails/SentIconFilled";
import TableSimple from "~/components/ui/tables/TableSimple";
import TabsWithIcons from "~/components/ui/tabs/TabsWithIcons";
import UrlUtils from "~/utils/app/UrlUtils";
import { Campaigns_List } from "../../routes/Campaigns_List";
import { useLocaleFormatters } from "~/locale/format";
export default function CampaignsListRoute() {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const data = useLoaderData<Campaigns_List.LoaderData>();
const params = useParams();
const [searchParams] = useSearchParams();
function countStatus(status?: string) {
if (!status) {
let total = 0;
data.groupByStatus.forEach((item) => {
total += item.count;
});
return total;
}
const item = data.groupByStatus.find((item) => item.status === status);
return item ? item.count : 0;
}
function tabLabel(key: "all" | "draft" | "sending" | "incomplete" | "completed", count: number) {
return t(`emailMarketing:campaignList.tabs.${key}`, { count, formattedCount: formatters.number(count) });
}
return (
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
<div className="flex items-center justify-between space-x-2">
<div className="flex-grow">
<TabsWithIcons
tabs={[
{
name: tabLabel("all", countStatus()),
href: "?",
current: !searchParams.get("status") || searchParams.get("status") === "all",
},
{
name: tabLabel("draft", countStatus("draft")),
href: "?status=draft",
current: searchParams.get("status") === "draft",
},
{
name: tabLabel("sending", countStatus("sending")),
href: "?status=sending",
current: searchParams.get("status") === "sending",
},
{
name: tabLabel("incomplete", countStatus("incomplete")),
href: "?status=incomplete",
current: searchParams.get("status") === "incomplete",
},
{
name: tabLabel("completed", countStatus("completed")),
href: "?status=completed",
current: searchParams.get("status") === "completed",
},
]}
/>
</div>
<div>
<ButtonPrimary to="new">
<div>{t("shared.new")}</div>
<SentIconFilled className="h-5 w-5" />
</ButtonPrimary>
</div>
</div>
{data.emailSenders.length === 0 && (
<WarningBanner
title={t("shared.warning")}
text={t("emailMarketing:senders.requiredForCampaign")}
redirect={UrlUtils.getModulePath(params, "email-marketing/senders")}
/>
)}
<TableSimple
items={data.items}
actions={[
{
title: t("shared.overview"),
onClickRoute: (_, i) => `${i.id}`,
},
]}
headers={[
{
name: "campaign",
title: t("emailMarketing:campaign"),
value: (i) => (
<div className="flex flex-col">
<div className="flex items-center space-x-2">
<div className="text-base font-bold">{i.name}</div>
<div>
<CampaignStatusBadge status={i.status} />
</div>
{i.sentAt ? (
<>
<div>•</div>
<div className="text-muted-foreground text-sm">
<span>{formatters.date(i.sentAt, { dateStyle: "medium" })}</span>
</div>
</>
) : null}
</div>
<div className="flex items-center space-x-2">
{(() => {
const recipientCount = i.recipients.length;
const deliveredCount = i.recipients.filter((f) => f.deliveredAt).length;
const openedCount = i.recipients.filter((f) => f.opens.length > 0).length;
const clickedCount = i.recipients.filter((f) => f.clicks.length > 0).length;
const unsubscribedCount = i.recipients.filter((f) => f.unsubscribedAt).length;
return (
<>
<div>
{t("emailMarketing:campaignList.metrics.recipients", {
count: recipientCount,
formattedCount: formatters.number(recipientCount),
})}
</div>
{i.track && (
<>
<div>•</div>
<div className="text-muted-foreground text-sm">
{formatters.number(deliveredCount)}/{formatters.number(recipientCount)} {t("emails.delivered")}
</div>
</>
)}
{i.track && (
<>
<div>•</div>
<div className="text-muted-foreground text-sm">
{formatters.percent(recipientCount > 0 ? openedCount / recipientCount : 0, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}{" "}
{t("emailMarketing:campaignList.metrics.openRate")}
</div>
</>
)}
{i.track && (
<>
<div>•</div>
<div className="text-muted-foreground text-sm">
{formatters.percent(recipientCount > 0 ? clickedCount / recipientCount : 0, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}{" "}
{t("emailMarketing:campaignList.metrics.clickRate")}
</div>
<div>•</div>
<div className="text-muted-foreground text-sm">
{t("emailMarketing:campaignList.metrics.clicks", {
count: clickedCount,
formattedCount: formatters.number(clickedCount),
})}
</div>
</>
)}
{i.track && (
<>
<div>•</div>
<div className="text-muted-foreground text-sm">
{t("emailMarketing:campaignList.metrics.unsubscribers", {
count: unsubscribedCount,
formattedCount: formatters.number(unsubscribedCount),
})}
</div>
</>
)}
</>
);
})()}
</div>
</div>
),
},
]}
noRecords={
<div className="p-12 text-center">
<h3 className="mt-1 text-sm font-medium text-gray-900">{t("emailMarketing:campaignList.empty.title")}</h3>
<p className="text-muted-foreground mt-1 text-sm">{t("emailMarketing:campaignList.empty.description")}</p>
</div>
}
/>
</div>
);
}
function CampaignStatusBadge({ status }: { status: string }) {
const { t } = useTranslation();
return (
<>
{status === "draft" && <SimpleBadge title={t("emailMarketing:campaignList.status.draft")} color={Colors.YELLOW} />}
{status === "sending" && <SimpleBadge title={t("emailMarketing:campaignList.status.sending")} color={Colors.ORANGE} />}
{status === "incomplete" && <SimpleBadge title={t("emailMarketing:campaignList.status.incomplete")} color={Colors.RED} />}
{status === "completed" && <SimpleBadge title={t("emailMarketing:campaignList.status.completed")} color={Colors.GREEN} />}
</>
);
}
@@ -1,160 +0,0 @@
import { useParams, useSubmit, Form, Link, useActionData, useLoaderData } from "react-router";
import { useState, useEffect, FormEvent } from "react";
import { useTranslation } from "react-i18next";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import InputGroup from "~/components/ui/forms/InputGroup";
import InputSelector from "~/components/ui/input/InputSelector";
import InputText from "~/components/ui/input/InputText";
import { EntityViewsApi } from "~/utils/api/.server/EntityViewsApi";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
import { Campaigns_New } from "../../routes/Campaigns_New";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import toast from "react-hot-toast";
import InputContent from "~/components/ui/input/InputContent";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import UrlUtils from "~/utils/app/UrlUtils";
import { getDefaultCampaignHtmlBody } from "./campaignDefaults";
export default function CampaignsNewRoute() {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
const data = useLoaderData<Campaigns_New.LoaderData>();
const actionData = useActionData<Campaigns_New.ActionData>();
const params = useParams();
const submit = useSubmit();
const [name, setName] = useState(() => t("emailMarketing:defaults.campaignName"));
const [subject, setSubject] = useState(() => t("emailMarketing:defaults.subject"));
const [senderId, setSenderId] = useState<string | number | undefined>(data.emailSenders.length > 0 ? data.emailSenders[0].id : "");
const [contentType, setContentType] = useState<"wysiwyg" | "markdown">("wysiwyg");
const [htmlBody, setHtmlBody] = useState(() => getDefaultCampaignHtmlBody(t));
const [selectedContactsViewId, setSelectedContactsViewId] = useState<string>(data.contactsViews.length > 0 ? (data.contactsViews[0].view?.id ?? "") : "");
const [, setSelectedContactsView] = useState<EntityViewsApi.GetEntityViewsWithRows>();
useEffect(() => {
if (actionData?.success) {
toast.success(actionData.success);
} else if (actionData?.error) {
toast.error(actionData.error);
}
}, [actionData]);
useEffect(() => {
setSelectedContactsView(data.contactsViews.find((v) => v.view?.id === selectedContactsViewId));
}, [data.contactsViews, selectedContactsViewId]);
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.stopPropagation();
e.preventDefault();
const formData = new FormData(e.currentTarget);
submit(formData, {
method: "post",
});
}
function sendTest(i?: RowWithDetails) {
const email = window.prompt(t("emails.object"), appOrAdminData.user?.email);
if (!email || email.trim() === "") {
return;
}
const form = new FormData();
form.set("action", i ? "send-contact-preview" : "send-preview");
form.set("senderId", senderId?.toString() ?? "");
form.set("contactRowId", i?.id.toString() ?? "");
form.set("email", email);
form.set("subject", subject);
form.set("htmlBody", htmlBody);
form.set("textBody", "");
submit(form, {
method: "post",
});
}
return (
<EditPageLayout
title={t("emailMarketing:newCampaign")}
menu={[
{
title: t("emailMarketing:campaigns"),
routePath: UrlUtils.getModulePath(params, "email-marketing/campaigns"),
},
{ title: t("shared.new") },
]}
>
<Form onSubmit={handleSubmit} className="pb-10">
<input type="hidden" name="action" value="create" hidden readOnly />
<div className="relative space-y-4">
<div className="sticky top-0 right-0 left-0 z-10">
<div className="border-border bg-background rounded-lg border border-dashed p-4">
<div className="space-y-2 lg:flex lg:justify-between lg:space-y-0 lg:space-x-2">
<div className="grow">
<InputText name="name" title={t("shared.name")} value={name} setValue={setName} withLabel={false} placeholder={t("emailMarketing:campaignList.form.namePlaceholder")} required />
</div>
<div className="flex justify-between space-x-2">
<ButtonSecondary onClick={() => sendTest()}>{t("emailMarketing:sendPreview")}</ButtonSecondary>
<ButtonPrimary type="submit">{t("emailMarketing:saveDraft")}</ButtonPrimary>
</div>
</div>
</div>
</div>
<div className="flex flex-col space-y-4">
<div className="">
<InputGroup title={t("emails.object")}>
<div className="grid gap-2 sm:grid-cols-2">
<InputSelector
name="senderId"
title={t("emails.sender")}
value={senderId}
setValue={setSenderId}
withSearch={false}
hint={
data.emailSenders.length === 0 ? (
<>
<Link to={params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/senders", mode: "host-aware" }) : adminPath(`email-marketing/senders`, { mode: "host-aware" })}>
<span className="text-xs hover:underline">{t("emailMarketing:senders.manage")}</span>
</Link>
</>
) : null
}
options={data.emailSenders.map((s) => {
return {
name: s.fromEmail,
value: s.id,
};
})}
required
/>
<InputSelector
required
name="contactViewId"
title={t("emails.recipientList")}
value={selectedContactsViewId}
setValue={(e) => setSelectedContactsViewId(e?.toString() ?? "")}
options={data.contactsViews.map((v) => {
return {
value: v.view?.id,
name: (v.view ? t(v.view.title) : t("shared.default")) + " (" + v.rowsCount + ")",
};
})}
/>
<div className="sm:col-span-2">
<InputText name="subject" title={t("emails.subject")} value={subject} setValue={setSubject} required placeholder={t("emails.subject")} />
</div>
<div className="sm:col-span-2">
{/* <input type="hidden" name="htmlBody" value={htmlBody} hidden readOnly /> */}
<InputContent name="htmlBody" value={htmlBody} onChangeValue={setHtmlBody} contentType={contentType} onChangeContentType={setContentType} />
</div>
</div>
</InputGroup>
</div>
</div>
</div>
</Form>
</EditPageLayout>
);
}
@@ -1,39 +0,0 @@
import type { TFunction } from "i18next";
import { describe, expect, it } from "vitest";
import { getDefaultCampaignHtmlBody } from "./campaignDefaults";
const defaultCopy: Record<string, string> = {
"emailMarketing:defaults.body.testEmail": "This is a test email.",
"emailMarketing:defaults.body.richTextIntro": "It includes",
"emailMarketing:defaults.body.bold": "bold",
"emailMarketing:defaults.body.italics": "italics",
"emailMarketing:defaults.body.combinedFormatting": "and combined formatting with",
"emailMarketing:defaults.body.strikethroughIntro": "It also includes",
"emailMarketing:defaults.body.strikethrough": "strikethrough",
"emailMarketing:defaults.body.exampleLink": "A link",
"emailMarketing:defaults.body.end": "The end.",
"emailMarketing:defaults.body.managePreferences": "Manage preferences",
};
function createT(copy: Record<string, string> = defaultCopy) {
return ((key: string) => copy[key] ?? key) as TFunction;
}
describe("campaign defaults", () => {
it("builds translated campaign HTML without leaking i18n expressions", () => {
const html = getDefaultCampaignHtmlBody(createT());
expect(html).toContain("<p>This is a test email.</p>");
expect(html).toContain(">A link</a");
expect(html).toContain(">Manage preferences</a");
expect(html).not.toContain("i18nT(");
expect(html).not.toContain("ui.autogenerated");
});
it("escapes translated text before injecting it into the default HTML", () => {
const html = getDefaultCampaignHtmlBody(createT({ ...defaultCopy, "emailMarketing:defaults.body.testEmail": "<script>alert('x')</script>" }));
expect(html).toContain("&lt;script&gt;alert(&#39;x&#39;)&lt;/script&gt;");
expect(html).not.toContain("<script>");
});
});
@@ -1,31 +0,0 @@
import type { TFunction } from "i18next";
export function getDefaultCampaignHtmlBody(t: TFunction) {
return `<p>${escapeHtml(t("emailMarketing:defaults.body.testEmail"))}</p>
<p>${escapeHtml(t("emailMarketing:defaults.body.richTextIntro"))} <strong>${escapeHtml(t("emailMarketing:defaults.body.bold"))}</strong>, <em>${escapeHtml(t("emailMarketing:defaults.body.italics"))}</em>, ${escapeHtml(t("emailMarketing:defaults.body.combinedFormatting"))} <strong><em>${escapeHtml(t("emailMarketing:defaults.body.bold"))}</em></strong
>. ${escapeHtml(t("emailMarketing:defaults.body.strikethroughIntro"))} <s>${escapeHtml(t("emailMarketing:defaults.body.strikethrough"))}</s>.
<a
target="_blank"
rel="noopener noreferrer"
class="underline text-blue-500"
href="https://www.example.com"
>${escapeHtml(t("emailMarketing:defaults.body.exampleLink"))}</a
>.
</p>
<p>-</p>
<p>${escapeHtml(t("emailMarketing:defaults.body.end"))}</p>
<p>
<a
target="_blank"
rel="noopener noreferrer"
class="underline text-blue-500"
href="https://www.example.com/preferences"
>${escapeHtml(t("emailMarketing:defaults.body.managePreferences"))}</a
>
</p>
`;
}
function escapeHtml(value: string) {
return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
}
@@ -1,64 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = process.cwd();
function read(relativePath: string) {
return fs.readFileSync(path.resolve(repoRoot, relativePath), "utf8");
}
describe("email marketing i18n", () => {
const files = [
"apps/web/app/modules/emailMarketing/components/campaigns/CampaignsNewRoute.tsx",
"apps/web/app/modules/emailMarketing/components/campaigns/CampaignsEditRoute.tsx",
"apps/web/app/modules/emailMarketing/components/campaigns/CampaignsListRoute.tsx",
"apps/web/app/modules/emailMarketing/components/senders/SendersListRoute.tsx",
"apps/web/app/modules/emailMarketing/components/EmailMarketingSummaryRoute.tsx",
"apps/web/app/modules/emailMarketing/components/OutboundEmailsTable.tsx",
"apps/web/app/modules/emailMarketing/routes/Campaigns_List.ts",
"apps/web/app/modules/emailMarketing/routes/Campaigns_New.ts",
"apps/web/app/modules/emailMarketing/routes/OutboundEmails_List.ts",
"apps/web/app/modules/emailMarketing/routes/Senders_List.ts",
"apps/web/app/modules/emailMarketing/services/EmailMarketingService.ts",
];
it("keeps campaign and activity UI copy behind emailMarketing keys", () => {
const source = files.map(read).join("\n");
expect(source).toContain("emailMarketing:campaignList.status.draft");
expect(source).toContain("emailMarketing:campaignList.metrics.openRate");
expect(source).toContain("emailMarketing:senders.requiredForCampaign");
expect(source).toContain("emailMarketing:senders.setup.mailjetWebhookRequired");
expect(source).toContain("emailMarketing:senders.testEmail.subject");
expect(source).toContain("emailMarketing:campaignPreview.testSubject");
expect(source).toContain("emailMarketing:activityFilters.sender");
expect(source).toContain("emailMarketing:activityFilters.campaign");
expect(source).toContain("emailMarketing:activityFilters.preview");
expect(source).toContain("emailMarketing:activityLog.firstOpen");
expect(source).toContain("useLocaleFormatters");
expect(source).toContain("formatters.number(deliveredCount)");
expect(source).toContain("formatters.number(recipientCount)");
expect(source).toContain("formatters.number(i.opens.length)");
expect(source).toContain("formatters.number(i.clicks.length)");
expect(source).toContain("emails.recipientsCount");
expect(source).toContain("emailMarketing:campaignList.actions.showRecipients");
expect(source).toContain("formattedRecipientCount");
expect(source).not.toContain("ui.autogenerated");
expect(source).not.toContain('from "~/utils/shared/NumberUtils"');
expect(source).not.toContain('from "~/utils/shared/DateUtils"');
expect(source).not.toContain('window.prompt("Email"');
expect(source).not.toContain('"Draft"');
expect(source).not.toContain('"No campaigns"');
expect(source).not.toContain("open rate");
expect(source).not.toContain("First open");
expect(source).not.toContain("{i.opens.length} {t(\"emails.opens\")}");
expect(source).not.toContain("{i.clicks.length} {t(\"emails.clicks\")}");
expect(source).not.toContain("{ 0:");
expect(source).not.toContain("{{0}}");
expect(source).not.toContain("sendCampaignPreviewToContact");
expect(source).not.toContain("sendCampaignPreviewToContacts");
expect(source).not.toMatch(/sendCampaignToContact["')]/);
expect(source).not.toContain("{data.item.recipients.length}");
});
});
@@ -19,7 +19,7 @@ export default function OutboundEmailsListRoute() {
</div>
</div>
<OutboundEmailsTable allEntities={data.allEntities} items={data.items} pagination={data.pagination} withCampaign={true} />
<OutboundEmailsTable items={data.items} pagination={data.pagination} withCampaign={true} />
</div>
);
}
@@ -1,15 +1,14 @@
import type { Campaign, EmailSender, OutboundEmail, OutboundEmailClick, OutboundEmailOpen } from "@toolctrl/db/prisma-browser";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
import type { Campaign, EmailSender, OutboundEmail, OutboundEmailClick, OutboundEmailOpen } from "@hivegrid/db/prisma-browser";
import { db } from "~/utils/db.server";
import { RowWithValues } from "~/utils/db/entities/rows.db.server";
// R-P14C (AD-2): the legacy Entity-Builder contactRow join is removed. The typed
// recipient link is the bare `kontaktId` scalar on OutboundEmail (AK-P14b).
export type CampaignWithDetails = Campaign & {
emailSender: EmailSender;
recipients: (OutboundEmail & {
campaign: Campaign | null;
opens: OutboundEmailOpen[];
clicks: OutboundEmailClick[];
contactRow: RowWithValues | null;
})[];
};
export async function getAllCampaigns(tenantId: string | null, status?: string): Promise<CampaignWithDetails[]> {
@@ -25,13 +24,6 @@ export async function getAllCampaigns(tenantId: string | null, status?: string):
campaign: true,
opens: true,
clicks: true,
contactRow: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
},
@@ -54,13 +46,6 @@ export async function getCampaign(id: string, tenantId: string | null): Promise<
campaign: true,
opens: true,
clicks: true,
contactRow: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
},
@@ -77,7 +62,7 @@ export async function createCampaign(
textBody: string | undefined;
track: boolean;
},
recipients: { fromSenderId: string; email: string; contactRowId: string }[]
recipients: { fromSenderId: string; email: string; kontaktId: string }[]
): Promise<Campaign> {
const item = await db.campaign.create({
data: {
@@ -86,7 +71,7 @@ export async function createCampaign(
create: recipients.map((recipient) => {
return {
tenantId: data.tenantId,
contactRowId: recipient.contactRowId,
kontaktId: recipient.kontaktId,
email: recipient.email,
fromSenderId: recipient.fromSenderId,
};
@@ -110,7 +95,7 @@ export async function updateCampaign(
track?: boolean;
sentAt?: Date;
},
recipients?: { fromSenderId: string; email: string; contactRowId: string }[]
recipients?: { fromSenderId: string; email: string; kontaktId: string }[]
): Promise<Campaign> {
const result = await db.campaign.updateMany({
where: {
@@ -140,7 +125,7 @@ export async function updateCampaign(
return {
tenantId: item.tenantId,
campaignId: id,
contactRowId: recipient.contactRowId,
kontaktId: recipient.kontaktId,
email: recipient.email,
fromSenderId: recipient.fromSenderId,
};
@@ -1,4 +1,4 @@
import type { EmailSender } from "@toolctrl/db/prisma-browser";
import type { EmailSender } from "@hivegrid/db/prisma-browser";
import { db } from "~/utils/db.server";
export type EmailSenderWithoutApiKey = Omit<EmailSender, "apiKey" | "apiSecret">;
@@ -15,6 +15,9 @@ export async function getAllEmailSenders(tenantId: string | null): Promise<Email
fromName: true,
fromEmail: true,
replyToEmail: true,
isDefault: true,
isDemoData: true,
sendingDomainId: true,
},
orderBy: [
{
@@ -47,6 +50,9 @@ export async function getEmailSenderWithoutApiKey(id: string, tenantId: string |
fromName: true,
fromEmail: true,
replyToEmail: true,
isDefault: true,
isDemoData: true,
sendingDomainId: true,
},
});
}
@@ -1,15 +1,14 @@
import type { Campaign, OutboundEmail, OutboundEmailClick, OutboundEmailOpen, Prisma } from "@toolctrl/db/prisma-browser";
import type { Campaign, OutboundEmail, OutboundEmailClick, OutboundEmailOpen, Prisma } from "@hivegrid/db/prisma-browser";
import Constants from "~/application/Constants";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
import { db } from "~/utils/db.server";
import { RowWithValues } from "~/utils/db/entities/rows.db.server";
// R-P14C (AD-2): the legacy Entity-Builder contactRow join is removed; the typed
// recipient link is the bare `kontaktId` scalar on OutboundEmail (AK-P14b).
export type OutboundEmailWithDetails = OutboundEmail & {
campaign: Campaign | null;
opens: OutboundEmailOpen[];
clicks: OutboundEmailClick[];
contactRow: RowWithValues | null;
};
export async function getAllOutboundEmails(
@@ -30,13 +29,6 @@ export async function getAllOutboundEmails(
campaign: true,
opens: true,
clicks: true,
contactRow: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
orderBy: [{ sentAt: "desc" }],
});
@@ -72,12 +64,6 @@ export async function findOutboundEmails(
campaign: true,
opens: true,
clicks: true,
contactRow: {
include: {
createdByUser: { select: { id: true, email: true, firstName: true, lastName: true, phone: true } },
values: { include: { media: true } },
},
},
},
orderBy: [{ sentAt: "desc" }],
});
@@ -98,7 +84,6 @@ export async function getOutboundEmail(id: string) {
export async function createOutboundEmailTest(data: {
tenantId: string | null;
contactRowId?: string;
email: string;
fromSenderId: string;
}): Promise<OutboundEmail> {
@@ -111,19 +96,6 @@ export async function createOutboundEmailTest(data: {
return item;
}
export async function createOutboundEmail(data: {
tenantId: string | null;
contactRowId: string;
email: string;
fromSenderId: string;
campaignId?: string;
}): Promise<OutboundEmail> {
const item = await db.outboundEmail.create({
data,
});
return item;
}
export async function updateOutboundEmail(
id: string,
data: {
@@ -1,92 +0,0 @@
import { LoaderFunctionArgs, redirect, ActionFunction } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { CampaignWithDetails, getCampaign, deleteCampaign, updateCampaign } from "../db/campaigns.db.server";
import { EmailSenderWithoutApiKey, getAllEmailSenders } from "../db/emailSender";
import EmailMarketingService from "../services/EmailMarketingService";
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { validateCSRFToken } from "~/utils/session.server";
import { requireEmailMarketingMutationAccess } from "./emailMarketingAccess.server";
export namespace Campaigns_Edit {
export type LoaderData = {
title: string;
item: CampaignWithDetails;
emailSenders: EmailSenderWithoutApiKey[];
allEntities: EntityWithDetails[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const tenantId = await getTenantIdOrNull({ request, params });
const item = await getCampaign(params.id!, tenantId);
if (!item) {
return redirect(params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/campaigns", mode: "host-aware" }) : adminPath("email-marketing/campaigns", { mode: "host-aware" }));
}
const emailSenders = await getAllEmailSenders(tenantId);
const data: LoaderData = {
title: `${item.name} | ${process.env.APP_NAME}`,
item,
emailSenders,
allEntities: await getAllEntities({ tenantId, active: true }),
};
return data;
};
export type ActionData = {
error?: string;
success?: string;
};
export const action: ActionFunction = async ({ request, params }) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
await requireEmailMarketingMutationAccess({ request, params, tenantId });
await validateCSRFToken(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const item = await getCampaign(params.id!, tenantId);
if (!item) {
return Response.json({ error: t("shared.notFound") }, { status: 404 });
}
if (action === "delete") {
try {
await deleteCampaign(params.id!, tenantId);
return redirect(params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/campaigns", mode: "host-aware" }) : adminPath("email-marketing/campaigns", { mode: "host-aware" }));
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
}
} else if (action === "update") {
try {
await updateCampaign(params.id!, tenantId, {
name: form.get("name")?.toString(),
subject: form.get("subject")?.toString(),
htmlBody: form.get("htmlBody")?.toString(),
textBody: form.get("textBody")?.toString(),
// status: form.get("status")?.toString(),
});
return Response.json({ success: t("shared.saved") });
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
}
} else if (action === "send") {
try {
await EmailMarketingService.sendCampaign(item);
return Response.json({ success: t("shared.sent") }, { status: 200 });
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
}
} else if (action === "send-preview") {
try {
const email = form.get("email")?.toString() ?? "";
await EmailMarketingService.sendCampaignTest(item, email);
return Response.json({ success: t("shared.sent") }, { status: 200 });
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
}
} else {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
};
}
@@ -1,103 +0,0 @@
// @vitest-environment node
import { LoaderFunctionArgs } from "react-router";
import { describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
getAllCampaigns: vi.fn(),
groupCampaigns: vi.fn(),
getAllEmailSenders: vi.fn(),
getTenantIdOrNull: vi.fn(),
requireAuth: vi.fn(),
t: vi.fn(),
}));
vi.mock("../db/campaigns.db.server", () => ({
getAllCampaigns: mocks.getAllCampaigns,
groupCampaigns: mocks.groupCampaigns,
}));
vi.mock("../db/emailSender", () => ({
getAllEmailSenders: mocks.getAllEmailSenders,
}));
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdOrNull: mocks.getTenantIdOrNull,
}));
vi.mock("~/utils/loaders.middleware", () => ({
requireAuth: mocks.requireAuth,
}));
vi.mock("i18next", () => ({
t: mocks.t,
}));
function deferred<T>() {
let resolve: (value: T) => void = () => {};
const promise = new Promise<T>((promiseResolve) => {
resolve = promiseResolve;
});
return { promise, resolve };
}
async function flushPromises() {
await Promise.resolve();
await Promise.resolve();
}
describe("email marketing campaigns loader performance", () => {
it("starts independent campaign collections before awaiting any collection result", async () => {
vi.clearAllMocks();
mocks.requireAuth.mockResolvedValue(undefined);
mocks.getTenantIdOrNull.mockResolvedValue("tenant_1");
mocks.t.mockReturnValue("Campaigns | ToolCtrl");
const campaigns = deferred<unknown[]>();
const campaignGroups = deferred<{ status: string; _count: { _all: number } }[]>();
const emailSenders = deferred<unknown[]>();
const startedCalls: string[] = [];
mocks.getAllCampaigns.mockImplementation((tenantId: string | null, status: string | undefined) => {
startedCalls.push("campaigns");
expect(tenantId).toBe("tenant_1");
expect(status).toBe("draft");
return campaigns.promise;
});
mocks.groupCampaigns.mockImplementation((tenantId: string | null) => {
startedCalls.push("groups");
expect(tenantId).toBe("tenant_1");
return campaignGroups.promise;
});
mocks.getAllEmailSenders.mockImplementation((tenantId: string | null) => {
startedCalls.push("senders");
expect(tenantId).toBe("tenant_1");
return emailSenders.promise;
});
const { Campaigns_List } = await import("./Campaigns_List");
const loaderPromise = Campaigns_List.loader({
request: new Request("https://app.example.test/app/acme/email-marketing/campaigns?status=draft"),
params: { tenant: "acme" },
context: {},
} as LoaderFunctionArgs);
await flushPromises();
expect(startedCalls).toEqual(["campaigns", "groups", "senders"]);
campaigns.resolve([{ id: "campaign_1" }]);
campaignGroups.resolve([{ status: "draft", _count: { _all: 2 } }]);
emailSenders.resolve([{ id: "sender_1" }]);
await expect(loaderPromise).resolves.toEqual({
title: "Campaigns | ToolCtrl",
items: [{ id: "campaign_1" }],
groupByStatus: [{ status: "draft", count: 2 }],
emailSenders: [{ id: "sender_1" }],
});
expect(mocks.requireAuth).toHaveBeenCalledTimes(1);
expect(mocks.getTenantIdOrNull).toHaveBeenCalledTimes(1);
expect(mocks.t).toHaveBeenCalledWith("emailMarketing:meta.campaigns", { appName: process.env.APP_NAME });
});
});
@@ -1,42 +0,0 @@
import { LoaderFunctionArgs } from "react-router";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { CampaignWithDetails, getAllCampaigns, groupCampaigns } from "../db/campaigns.db.server";
import { EmailSenderWithoutApiKey, getAllEmailSenders } from "../db/emailSender";
import { requireAuth } from "~/utils/loaders.middleware";
import { t as i18nT } from "i18next";
export namespace Campaigns_List {
export type LoaderData = {
title: string;
items: CampaignWithDetails[];
groupByStatus: {
status: string;
count: number;
}[];
emailSenders: EmailSenderWithoutApiKey[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const tenantId = await getTenantIdOrNull({ request, params });
const searchParams = new URL(request.url).searchParams;
const status = searchParams.get("status")?.toString();
const [items, campaignsCount, emailSenders] = await Promise.all([
getAllCampaigns(tenantId, status),
groupCampaigns(tenantId),
getAllEmailSenders(tenantId),
]);
const groupByStatus = campaignsCount.map((item) => {
return {
status: item.status,
count: item._count._all,
};
});
const data: LoaderData = {
title: i18nT("emailMarketing:meta.campaigns", { appName: process.env.APP_NAME }),
items,
groupByStatus,
emailSenders,
};
return data;
};
}
@@ -1,110 +0,0 @@
import { LoaderFunctionArgs, ActionFunction, redirect } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { EntityViewsApi } from "~/utils/api/.server/EntityViewsApi";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { EmailSenderWithoutApiKey, getAllEmailSenders, getEmailSender } from "../db/emailSender";
import EmailMarketingService from "../services/EmailMarketingService";
import { requireAuth } from "~/utils/loaders.middleware";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { validateCSRFToken } from "~/utils/session.server";
import { requireEmailMarketingMutationAccess } from "./emailMarketingAccess.server";
import { t as i18nT } from "i18next";
export namespace Campaigns_New {
export type LoaderData = {
title: string;
contactsViews: EntityViewsApi.GetEntityViewsWithRows[];
emailSenders: EmailSenderWithoutApiKey[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const tenantId = await getTenantIdOrNull({ request, params });
const emailSenders = await getAllEmailSenders(tenantId);
const data: LoaderData = {
title: i18nT("emailMarketing:meta.newCampaign", { appName: process.env.APP_NAME }),
emailSenders,
contactsViews: await EntityViewsApi.getAll({
entityName: "contact",
tenantId,
withDefault: false,
withRows: false,
}),
};
return data;
};
export type ActionData = {
error?: string;
success?: string;
};
export const action: ActionFunction = async ({ request, params }) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
await requireEmailMarketingMutationAccess({ request, params, tenantId });
await validateCSRFToken(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const email = form.get("email")?.toString() ?? "";
const senderId = form.get("senderId")?.toString() ?? "";
let subject = form.get("subject")?.toString() ?? "";
let htmlBody = form.get("htmlBody")?.toString() ?? "";
let textBody = form.get("textBody")?.toString() ?? "";
const sender = await getEmailSender(senderId, tenantId);
if (!sender) {
return Response.json({ error: t("emailMarketing:errors.invalidSender") }, { status: 400 });
}
if (!htmlBody && !textBody) {
return Response.json({ error: t("emailMarketing:errors.emailBodyRequired") }, { status: 400 });
}
if (action === "send-preview") {
try {
await EmailMarketingService.sendPreview({
from: { sender, tenantId },
email: { to: email, subject, htmlBody, textBody, track: true },
});
return Response.json({ success: t("shared.sent") }, { status: 200 });
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
}
} else if (action === "send-contact-preview") {
try {
const contactRowId = form.get("contactRowId")?.toString() ?? "";
await EmailMarketingService.sendContactPreview({
contactRowId,
from: { sender, tenantId },
email: { to: email, subject, htmlBody, textBody, track: true },
});
return Response.json({ success: t("shared.sent") }, { status: 200 });
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
}
} else if (action === "create") {
const name = form.get("name")?.toString() ?? "";
if (!name) {
return Response.json({ error: t("emailMarketing:errors.invalidName") }, { status: 400 });
}
const contactViewId = form.get("contactViewId")?.toString();
if (!contactViewId) {
return Response.json({ error: t("emailMarketing:errors.invalidRecipientList") }, { status: 400 });
}
try {
const campaign = await EmailMarketingService.createCampaignDraft({
name: form.get("name")?.toString() ?? "",
contactViewId,
from: { sender, tenantId },
email: { subject, htmlBody, textBody, track: true },
});
return redirect(
params.tenant
? appPath({ tenantSlug: params.tenant, path: `email-marketing/campaigns/${campaign.id}`, mode: "host-aware" })
: adminPath(`email-marketing/campaigns/${campaign.id}`, { mode: "host-aware" })
);
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
}
} else {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
};
}
@@ -1,22 +1,53 @@
import { LoaderFunctionArgs } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import EmailMarketingService, { EmailMarketingSummaryDto } from "../services/EmailMarketingService";
import { countOutboundEmails } from "../db/outboundEmails.db.server";
import { requireAuth } from "~/utils/loaders.middleware";
export namespace EmailMarketing_Summary {
// R-P14C: summary is computed inline from the typed OutboundEmail counters
// (was EmailMarketingService.getSummary, which lived on the removed
// Entity-Builder service). No CRM/Entity-Builder reads here.
export type SummaryDto = {
avgOpenRate: number;
avgClickRate: number;
outboundEmails: {
sent: number;
delivered: number;
};
};
export type LoaderData = {
title: string;
summary: EmailMarketingSummaryDto;
summary: SummaryDto;
};
async function buildSummary(tenantId: string | null): Promise<SummaryDto> {
const [total, sent, delivered, outboundEmailsWithOpens, outboundEmailsWithClicks] = await Promise.all([
countOutboundEmails(tenantId),
countOutboundEmails(tenantId, { where: { sentAt: { not: null } } }),
countOutboundEmails(tenantId, { where: { deliveredAt: { not: null } } }),
countOutboundEmails(tenantId, { where: { opens: { some: {} } } }),
countOutboundEmails(tenantId, { where: { clicks: { some: {} } } }),
]);
const avgOpenRate = total > 0 ? (outboundEmailsWithOpens / total) * 100 : 0;
const avgClickRate = total > 0 ? (outboundEmailsWithClicks / total) * 100 : 0;
return {
avgOpenRate,
avgClickRate,
outboundEmails: {
sent,
delivered,
},
};
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
const data: LoaderData = {
title: `${t("emailMarketing:title")} | ${process.env.APP_NAME}`,
summary: await EmailMarketingService.getSummary(tenantId),
summary: await buildSummary(tenantId),
};
return data;
};
@@ -7,7 +7,6 @@ import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { getAllCampaigns } from "../db/campaigns.db.server";
import { getAllEmailSenders } from "../db/emailSender";
import { OutboundEmailWithDetails, getAllOutboundEmails } from "../db/outboundEmails.db.server";
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
import { requireAuth } from "~/utils/loaders.middleware";
export namespace OutboundEmails_List {
@@ -15,7 +14,6 @@ export namespace OutboundEmails_List {
items: OutboundEmailWithDetails[];
pagination: PaginationDto;
filterableProperties: FilterablePropertyDto[];
allEntities: EntityWithDetails[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
@@ -66,7 +64,6 @@ export namespace OutboundEmails_List {
items,
pagination,
filterableProperties,
allEntities: await getAllEntities({ tenantId, active: true }),
};
return data;
};
@@ -6,8 +6,8 @@ import { resolveRepoPath } from "~/utils/testing/repoPaths";
const appRoot = resolveRepoPath("apps/web/app");
const emailMarketingMutationHandlers = [
"modules/emailMarketing/routes/Campaigns_Edit.ts",
"modules/emailMarketing/routes/Campaigns_New.ts",
// R-P14C: the Campaigns_Edit/Campaigns_New mutation handlers were removed with
// the Entity-Builder campaign editor (Variante A). Senders handlers remain.
"modules/emailMarketing/routes/Senders_Edit.ts",
"modules/emailMarketing/routes/Senders_List.ts",
"modules/emailMarketing/routes/Senders_New.ts",
@@ -0,0 +1,263 @@
// AK-P14b (P14 email marketing) — campaign send-engine (BullMQ).
//
// Orchestrates a DSGVO-safe campaign send on the TYPED path (AD-2):
// 1. resolve the audience from the campaign's RecipientSegment (dynamic) or its
// frozen snapshot (static) — eligibility already excludes unsubscribed /
// suppressed / no-opt-in / archived / no-email (SegmentService, S2);
// 2. HARD pre-send checklist gate (S5 core) — a red check throws, never sends;
// 3. per recipient: defensive suppression re-check (AK-P14a), persist an
// OutboundEmail row with a signed per-recipient unsubscribe token, and
// enqueue ONE `mail.transactional` job (List-Unsubscribe header + throttled
// timezone-aware sendAt) onto the existing email queue.
//
// The pure planning (A/B split, throttle, footer/token injection) lives in
// campaignSendPlan.ts. Enqueue uses the boilerplate email queue + producer — no
// new worker queue. NO React/UI imports. Audit is automatic (M001 middleware);
// the caller (route) fires notify() (M011) from the returned result.
import { buildTransactionalMailJob, enqueueJob, queueNames, resolveRedisConnectionOptionsFromProcessEnv, type TypedQueue } from "@hivegrid/queue";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { isEmailSuppressed } from "@hivegrid/db/email-suppression";
import type { CrmVisibilityContext } from "~/utils/integrations/crm/crmService.server";
import { resolveSegment } from "./SegmentService.server";
import { planCampaignSend, type PlanRecipient, type PlanVariant } from "~/utils/integrations/email/campaignSendPlan";
import { evaluatePresendChecklist, type PresendChecklistResult } from "@hivegrid/view-models";
import { signMarketingToken } from "~/utils/email/marketingToken.server";
const KONTAKT_ENTITY_TYPE = "kontakt";
// Default daily send cap per tenant; override via EMAIL_MARKETING_DAILY_CAP
// ("0"/unset ⇒ no cap). Documented default-decision (Ticket-Doc lückenhaft).
function resolveDailyCap(): number | null {
const raw = process.env.EMAIL_MARKETING_DAILY_CAP;
if (!raw) return null;
const n = Number(raw);
return Number.isFinite(n) && n > 0 ? n : null;
}
function resolveRatePerMinute(): number | undefined {
const raw = process.env.EMAIL_MARKETING_RATE_PER_MINUTE;
const n = raw ? Number(raw) : NaN;
return Number.isFinite(n) && n > 0 ? n : undefined;
}
/** Domain error carrying an i18n message key (M002 Klartext). */
export class CampaignSendError extends Error {
readonly messageKey: string;
readonly checklist?: PresendChecklistResult;
constructor(messageKey: string, checklist?: PresendChecklistResult) {
super(messageKey);
this.name = "CampaignSendError";
this.messageKey = messageKey;
this.checklist = checklist;
}
}
export interface CampaignSendResult {
campaignId: string;
enqueued: number;
skippedSuppressed: number;
recipientCount: number;
checklist: PresendChecklistResult;
}
export interface DispatchCampaignInput {
tenantId: string;
ctx: CrmVisibilityContext;
campaignId: string;
/** Public base URL for unsubscribe links (e.g. https://app.tenant.de). */
baseUrl: string;
/** Injected clock + queue for tests; default to env-derived queue. */
now?: () => Date;
queue?: TypedQueue<typeof queueNames.email>;
}
type CampaignRow = {
id: string;
tenantId: string | null;
emailSenderId: string;
subject: string;
htmlBody: string;
textBody: string | null;
footerHtml: string | null;
recipientSegmentId: string | null;
scheduledAt: Date | null;
track: boolean;
status: string;
};
async function loadAudienceKontaktIds(input: DispatchCampaignInput, campaign: CampaignRow, segmentIsStatic: boolean): Promise<string[]> {
if (!campaign.recipientSegmentId) return [];
if (segmentIsStatic) {
return withTenantRLS(input.tenantId, async (tx) => {
const rows = await tx.segmentSnapshotMember.findMany({
where: { tenantId: input.tenantId, segmentId: campaign.recipientSegmentId! },
select: { kontaktId: true },
});
return rows.map((r) => r.kontaktId);
});
}
const segment = await withTenantRLS(input.tenantId, async (tx) =>
tx.recipientSegment.findFirst({ where: { tenantId: input.tenantId, id: campaign.recipientSegmentId! }, select: { filterDefinition: true } })
);
if (!segment) return [];
const resolution = await resolveSegment({ tenantId: input.tenantId, ctx: input.ctx, filterDefinition: segment.filterDefinition });
return resolution.eligibleKontaktIds;
}
/** Build per-kontakt custom-field token maps (`cf.<key>`) for the audience. */
async function loadCustomFieldTokens(tx: TenantRlsClient, tenantId: string, kontaktIds: string[]): Promise<Map<string, Record<string, string>>> {
const result = new Map<string, Record<string, string>>();
if (kontaktIds.length === 0) return result;
const [defs, values] = await Promise.all([
tx.customFieldDefinition.findMany({ where: { tenantId, entityType: KONTAKT_ENTITY_TYPE }, select: { id: true, key: true } }),
tx.customFieldValue.findMany({ where: { tenantId, entityType: KONTAKT_ENTITY_TYPE, entityId: { in: kontaktIds } }, select: { definitionId: true, entityId: true, wert: true } }),
]);
const keyByDef = new Map(defs.map((d) => [d.id, d.key]));
for (const v of values) {
const key = keyByDef.get(v.definitionId);
if (!key) continue;
const map = result.get(v.entityId) ?? {};
map[key] = v.wert == null ? "" : typeof v.wert === "string" ? v.wert : JSON.stringify(v.wert);
result.set(v.entityId, map);
}
return result;
}
async function acquireQueue(input: DispatchCampaignInput): Promise<{ queue: TypedQueue<typeof queueNames.email>; close: boolean }> {
if (input.queue) return { queue: input.queue, close: false };
const connection = resolveRedisConnectionOptionsFromProcessEnv();
if (!connection) throw new CampaignSendError("emailMarketing.send.error.noQueue");
const queueRuntimeModule = "@hivegrid/queue/runtime";
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@hivegrid/queue/runtime");
return { queue: createQueue(queueNames.email, { connection }), close: true };
}
/**
* Dispatch a campaign: gate on the pre-send checklist, then persist + enqueue one
* throttled transactional mail per eligible recipient. Throws CampaignSendError
* (with the failed checklist) when blocked — nothing is sent.
*/
export async function dispatchCampaign(input: DispatchCampaignInput): Promise<CampaignSendResult> {
const nowMs = (input.now ? input.now() : new Date()).getTime();
// Load campaign + sender + variants + segment meta (read tx).
const loaded = await withTenantRLS(input.tenantId, async (tx) => {
const campaign = (await tx.campaign.findFirst({
where: { id: input.campaignId, tenantId: input.tenantId },
select: {
id: true, tenantId: true, emailSenderId: true, subject: true, htmlBody: true, textBody: true,
footerHtml: true, recipientSegmentId: true, scheduledAt: true, track: true, status: true,
},
})) as CampaignRow | null;
if (!campaign) return null;
const [sender, variants, segment] = await Promise.all([
tx.emailSender.findFirst({ where: { id: campaign.emailSenderId }, select: { id: true, sendingDomainId: true } }),
tx.campaignVariant.findMany({ where: { tenantId: input.tenantId, campaignId: campaign.id }, select: { label: true, subject: true, htmlBody: true, textBody: true, weightPercent: true } }),
campaign.recipientSegmentId
? tx.recipientSegment.findFirst({ where: { tenantId: input.tenantId, id: campaign.recipientSegmentId }, select: { isStaticSnapshot: true } })
: Promise.resolve(null),
]);
const domain = sender?.sendingDomainId
? await tx.tenantSendingDomain.findFirst({ where: { tenantId: input.tenantId, id: sender.sendingDomainId }, select: { verificationStatus: true } })
: null;
const dailyCapUsed = await tx.outboundEmail.count({ where: { tenantId: input.tenantId, sentAt: { gte: new Date(nowMs - 24 * 60 * 60 * 1000) } } });
return { campaign, variants, segmentIsStatic: segment?.isStaticSnapshot ?? false, domainVerified: domain?.verificationStatus === "verified", dailyCapUsed };
});
if (!loaded) throw new CampaignSendError("emailMarketing.send.error.notFound");
const { campaign, variants, segmentIsStatic, domainVerified, dailyCapUsed } = loaded;
// Resolve audience (own tx) and load recipient details.
const kontaktIds = await loadAudienceKontaktIds(input, campaign, segmentIsStatic);
const checklist = evaluatePresendChecklist({
domainVerified,
footerConfigured: Boolean(campaign.footerHtml && campaign.footerHtml.trim().length > 0),
subject: campaign.subject,
recipientCount: kontaktIds.length,
dailyCapUsed,
dailyCapLimit: resolveDailyCap(),
});
if (checklist.blocked) {
throw new CampaignSendError("emailMarketing.send.error.checklistBlocked", checklist);
}
// Persist OutboundEmail rows + collect plan recipients (write tx).
const planRecipients = await withTenantRLS(input.tenantId, async (tx) => {
const kontakte = await tx.kontakt.findMany({
where: { tenantId: input.tenantId, id: { in: kontaktIds }, archivedAt: null, primaerEmail: { not: null } },
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true },
});
const cfTokens = await loadCustomFieldTokens(tx, input.tenantId, kontaktIds);
const recipients: PlanRecipient[] = [];
let skippedSuppressed = 0;
for (const k of kontakte) {
const email = k.primaerEmail!;
if (await isEmailSuppressed({ tenantId: input.tenantId, emailAddress: email }, tx)) {
skippedSuppressed += 1;
continue;
}
const unsubscribeToken = signMarketingToken({ purpose: "unsub", tenantId: input.tenantId, kontaktId: k.id, campaignId: campaign.id });
const trackingToken = signMarketingToken({ purpose: "unsub", tenantId: input.tenantId, kontaktId: k.id, campaignId: campaign.id, now: () => new Date(nowMs + 1) });
const outbound = await tx.outboundEmail.create({
data: { tenantId: input.tenantId, campaignId: campaign.id, kontaktId: k.id, email, fromSenderId: campaign.emailSenderId, unsubscribeToken, trackingToken },
select: { id: true },
});
recipients.push({
outboundEmailId: outbound.id,
kontaktId: k.id,
email,
unsubscribeToken,
tokens: { vorname: k.vorname, nachname: k.nachname, email, orgName: k.orgName, customFields: cfTokens.get(k.id) ?? {} },
});
}
return { recipients, skippedSuppressed };
});
// Plan (A/B split + throttle + footer/token injection).
const planVariants: PlanVariant[] = variants.map((v) => ({ label: v.label, subject: v.subject, htmlBody: v.htmlBody, textBody: v.textBody, weightPercent: v.weightPercent }));
const startAt = campaign.scheduledAt ? campaign.scheduledAt.getTime() : nowMs;
const plan = planCampaignSend({
recipients: planRecipients.recipients,
base: { subject: campaign.subject, htmlBody: campaign.htmlBody, textBody: campaign.textBody },
variants: planVariants,
footerHtml: campaign.footerHtml ?? "",
unsubscribeBaseUrl: input.baseUrl,
startAt,
ratePerMinute: resolveRatePerMinute(),
});
// Enqueue one transactional mail per planned send.
const { queue, close } = await acquireQueue(input);
try {
for (const p of plan) {
const descriptor = buildTransactionalMailJob({
to: [p.email],
subject: p.subject,
html: p.html,
text: p.text || undefined,
tenantId: input.tenantId,
precedenceBulk: true,
listUnsubscribe: p.listUnsubscribe,
settings: { trackOpens: campaign.track, trackClicks: campaign.track },
tags: ["email-marketing", `campaign:${campaign.id}`],
metadata: { idempotencyKey: p.outboundEmailId, outboundEmailId: p.outboundEmailId, ...(p.variantLabel ? { variant: p.variantLabel } : {}) },
});
// BullMQ `delay` carries the throttle/timezone-aware schedule (the worker
// releases the job at sendAt); no provider-side sendAt to avoid double-delay.
const delay = Math.max(0, p.sendAt - nowMs);
await enqueueJob(queue, descriptor, { tenantId: input.tenantId, ...(delay > 0 ? { delay } : {}) });
}
} finally {
if (close) await queue.close();
}
// Mark campaign as scheduled/sending (audited by M001 middleware).
await withTenantRLS(input.tenantId, async (tx) => {
await tx.campaign.update({
where: { id: campaign.id },
data: { status: campaign.scheduledAt && campaign.scheduledAt.getTime() > nowMs ? "scheduled" : "sending", sentAt: new Date(nowMs) },
});
});
return { campaignId: campaign.id, enqueued: plan.length, skippedSuppressed: planRecipients.skippedSuppressed, recipientCount: kontaktIds.length, checklist };
}
@@ -0,0 +1,84 @@
// AK-P14b (P14 email marketing) — marketing consent (DSGVO double-opt-in) +
// unsubscribe write paths. Typed Kontakt id (bare scalar), tenant-scoped via
// withTenantRLS. NO React/UI imports.
//
// startDoubleOptIn — record single opt-in + mint the confirmation token
// (the caller sends the opt-in mail).
// confirmOptIn — verify the token, flip consent to `double`.
// unsubscribeKontakt— write an Unsubscribe row + stamp consent (idempotent).
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { signMarketingToken, verifyMarketingToken } from "~/utils/email/marketingToken.server";
/** Injectable clock (test seam). */
type ClockFn = () => Date;
export interface StartOptInResult {
token: string;
status: "single";
}
/** Record a single opt-in and return the double-opt-in confirmation token. */
export async function startDoubleOptIn(input: { tenantId: string; kontaktId: string; source?: string; now?: ClockFn }): Promise<StartOptInResult> {
const token = signMarketingToken({ purpose: "optin", tenantId: input.tenantId, kontaktId: input.kontaktId, now: input.now });
const at = input.now ? input.now() : new Date();
await withTenantRLS(input.tenantId, async (tx) => {
await tx.kontaktMarketingConsent.upsert({
where: { tenantId_kontaktId: { tenantId: input.tenantId, kontaktId: input.kontaktId } },
create: { tenantId: input.tenantId, kontaktId: input.kontaktId, status: "single", optInSource: input.source ?? null, optInAt: at, doubleOptInToken: token },
update: { status: "single", optInSource: input.source ?? null, optInAt: at, doubleOptInToken: token, unsubscribedAt: null },
});
});
return { token, status: "single" };
}
export type ConfirmOptInResult = "confirmed" | "already_confirmed" | "invalid";
/** Verify a double-opt-in token and flip the contact's consent to `double`. */
export async function confirmOptIn(token: string | null | undefined, now?: ClockFn): Promise<ConfirmOptInResult> {
const payload = verifyMarketingToken(token, { expectedPurpose: "optin" });
if (!payload) return "invalid";
return withTenantRLS(payload.tenantId, async (tx) => {
const existing = await tx.kontaktMarketingConsent.findUnique({
where: { tenantId_kontaktId: { tenantId: payload.tenantId, kontaktId: payload.kontaktId } },
select: { status: true },
});
if (existing?.status === "double") return "already_confirmed";
const at = now ? now() : new Date();
await tx.kontaktMarketingConsent.upsert({
where: { tenantId_kontaktId: { tenantId: payload.tenantId, kontaktId: payload.kontaktId } },
create: { tenantId: payload.tenantId, kontaktId: payload.kontaktId, status: "double", optInAt: at, confirmedAt: at },
update: { status: "double", confirmedAt: at, unsubscribedAt: null },
});
return "confirmed";
});
}
export type UnsubscribeResult = "unsubscribed" | "already_unsubscribed";
/** Write a tenant-scoped unsubscribe (one-click). Idempotent on (tenant, kontakt)
* for scope `all`; also stamps the consent row's `unsubscribedAt`. */
export async function unsubscribeKontakt(input: {
tenantId: string;
kontaktId: string;
campaignId?: string | null;
reason?: string | null;
now?: ClockFn;
}): Promise<UnsubscribeResult> {
return withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.unsubscribe.findFirst({
where: { tenantId: input.tenantId, kontaktId: input.kontaktId, scope: "all" },
select: { id: true },
});
if (existing) return "already_unsubscribed";
const at = input.now ? input.now() : new Date();
await tx.unsubscribe.create({
data: { tenantId: input.tenantId, kontaktId: input.kontaktId, scope: "all", campaignId: input.campaignId ?? null, reason: input.reason ?? null },
});
await tx.kontaktMarketingConsent.updateMany({
where: { tenantId: input.tenantId, kontaktId: input.kontaktId },
data: { unsubscribedAt: at },
});
return "unsubscribed";
});
}
@@ -1,5 +1,5 @@
import type { EmailSender } from "@toolctrl/db/prisma-browser";
import { createMailjetProvider } from "@toolctrl/mail";
import type { EmailSender } from "@hivegrid/db/prisma-browser";
import { createMailjetProvider } from "@hivegrid/mail";
type BroadcastEmail = {
sender: EmailSender;
@@ -1,171 +0,0 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
getContact: vi.fn(),
getContactsInRowIds: vi.fn(),
countOutboundEmails: vi.fn(),
getAllOutboundEmails: vi.fn(),
updateCampaign: vi.fn(),
updateOutboundEmail: vi.fn(),
sendBroadcast: vi.fn(),
}));
vi.mock("~/modules/crm/services/CrmService", () => ({
default: {
getContact: mocks.getContact,
getContactsInRowIds: mocks.getContactsInRowIds,
},
}));
vi.mock("../db/campaigns.db.server", () => ({
createCampaign: vi.fn(),
updateCampaign: mocks.updateCampaign,
}));
vi.mock("../db/outboundEmails.db.server", () => ({
countOutboundEmails: mocks.countOutboundEmails,
getAllOutboundEmails: mocks.getAllOutboundEmails,
createOutboundEmailTest: vi.fn(),
updateOutboundEmail: mocks.updateOutboundEmail,
createOutboundEmail: vi.fn(),
}));
vi.mock("./EmailMarketingSenderService.server", () => ({
sendBroadcast: mocks.sendBroadcast,
}));
function campaignWithRecipients(count: number) {
return {
id: "campaign_1",
tenantId: "tenant_1",
emailSender: { id: "sender_1", email: "marketing@example.com" },
subject: "Hello {{firstName}}",
htmlBody: "<p>{{email}}</p>",
textBody: "Hi {{firstName}}",
track: true,
recipients: Array.from({ length: count }, (_, index) => ({
id: `outbound_${index + 1}`,
email: `recipient-${index + 1}@example.com`,
contactRowId: `row_${index + 1}`,
contactRow: { id: `row_${index + 1}` },
opens: [],
clicks: [],
campaign: null,
})),
};
}
describe("EmailMarketingService.sendCampaign", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getContact.mockImplementation(async (rowId: string) => ({
id: rowId,
email: `${rowId}@example.com`,
firstName: rowId,
lastName: "Recipient",
jobTitle: "Buyer",
company: { name: "Acme" },
marketingSubscriber: true,
}));
mocks.getContactsInRowIds.mockImplementation(async (rowIds: string[]) =>
rowIds.map((rowId) => ({
id: rowId,
email: `${rowId}@example.com`,
firstName: rowId,
lastName: "Recipient",
jobTitle: "Buyer",
company: { name: "Acme" },
marketingSubscriber: true,
}))
);
mocks.updateCampaign.mockResolvedValue({});
mocks.updateOutboundEmail.mockResolvedValue({});
});
it("limits concurrent broadcasts while completing a campaign", async () => {
let active = 0;
let maxActive = 0;
mocks.sendBroadcast.mockImplementation(async () => {
active += 1;
maxActive = Math.max(maxActive, active);
await Promise.resolve();
active -= 1;
});
const EmailMarketingService = (await import("./EmailMarketingService")).default;
const campaign = campaignWithRecipients(6) as Parameters<typeof EmailMarketingService.sendCampaign>[0];
await EmailMarketingService.sendCampaign(campaign, { concurrency: 2 });
expect(mocks.sendBroadcast).toHaveBeenCalledTimes(6);
expect(mocks.getContact).not.toHaveBeenCalled();
expect(mocks.getContactsInRowIds).toHaveBeenCalledTimes(1);
expect(mocks.getContactsInRowIds).toHaveBeenCalledWith(
["row_1", "row_2", "row_3", "row_4", "row_5", "row_6"],
"tenant_1"
);
expect(maxActive).toBeLessThanOrEqual(2);
expect(mocks.updateCampaign).toHaveBeenNthCalledWith(1, "campaign_1", "tenant_1", { status: "sending" });
expect(mocks.updateCampaign).toHaveBeenLastCalledWith("campaign_1", "tenant_1", { status: "completed" });
}, 10000);
it("marks missing prefetched contacts as incomplete without sending to them", async () => {
mocks.getContactsInRowIds.mockImplementation(async (rowIds: string[]) =>
rowIds
.filter((rowId) => rowId !== "row_2")
.map((rowId) => ({
id: rowId,
email: `${rowId}@example.com`,
firstName: rowId,
lastName: "Recipient",
jobTitle: "Buyer",
company: { name: "Acme" },
marketingSubscriber: true,
}))
);
const EmailMarketingService = (await import("./EmailMarketingService")).default;
const campaign = campaignWithRecipients(3) as Parameters<typeof EmailMarketingService.sendCampaign>[0];
await EmailMarketingService.sendCampaign(campaign, { concurrency: 2 });
expect(mocks.getContact).not.toHaveBeenCalled();
expect(mocks.getContactsInRowIds).toHaveBeenCalledTimes(1);
expect(mocks.sendBroadcast).toHaveBeenCalledTimes(2);
expect(mocks.updateOutboundEmail).toHaveBeenCalledWith("outbound_2", {
error: "Could not parse contact not found: recipient-2@example.com",
});
expect(mocks.updateCampaign).toHaveBeenLastCalledWith("campaign_1", "tenant_1", { status: "incomplete" });
});
});
describe("EmailMarketingService.getSummary", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("uses aggregate counts instead of loading detailed outbound email rows", async () => {
mocks.countOutboundEmails
.mockResolvedValueOnce(10)
.mockResolvedValueOnce(8)
.mockResolvedValueOnce(6)
.mockResolvedValueOnce(5)
.mockResolvedValueOnce(2);
const EmailMarketingService = (await import("./EmailMarketingService")).default;
await expect(EmailMarketingService.getSummary("tenant_1")).resolves.toEqual({
avgOpenRate: 50,
avgClickRate: 20,
outboundEmails: {
sent: 8,
delivered: 6,
},
});
expect(mocks.getAllOutboundEmails).not.toHaveBeenCalled();
expect(mocks.countOutboundEmails).toHaveBeenNthCalledWith(1, "tenant_1");
expect(mocks.countOutboundEmails).toHaveBeenNthCalledWith(2, "tenant_1", { where: { sentAt: { not: null } } });
expect(mocks.countOutboundEmails).toHaveBeenNthCalledWith(3, "tenant_1", { where: { deliveredAt: { not: null } } });
expect(mocks.countOutboundEmails).toHaveBeenNthCalledWith(4, "tenant_1", { where: { opens: { some: {} } } });
expect(mocks.countOutboundEmails).toHaveBeenNthCalledWith(5, "tenant_1", { where: { clicks: { some: {} } } });
});
});
@@ -1,323 +0,0 @@
import type { Campaign, EmailSender } from "@toolctrl/db/prisma-browser";
import { mapWithConcurrency } from "@toolctrl/foundation";
import { EntityViewsApi } from "~/utils/api/.server/EntityViewsApi";
import CrmService, { ContactDto } from "~/modules/crm/services/CrmService";
import { createCampaign, CampaignWithDetails, updateCampaign } from "../db/campaigns.db.server";
import { countOutboundEmails, createOutboundEmailTest, updateOutboundEmail, createOutboundEmail } from "../db/outboundEmails.db.server";
import { sendBroadcast } from "./EmailMarketingSenderService.server";
import { t as i18nT } from "i18next";
export type EmailMarketingSummaryDto = {
avgOpenRate: number;
avgClickRate: number;
outboundEmails: {
sent: number;
delivered: number;
};
};
async function getSummary(tenantId: string | null): Promise<EmailMarketingSummaryDto> {
const [total, sent, delivered, outboundEmailsWithOpens, outboundEmailsWithClicks] = await Promise.all([
countOutboundEmails(tenantId),
countOutboundEmails(tenantId, { where: { sentAt: { not: null } } }),
countOutboundEmails(tenantId, { where: { deliveredAt: { not: null } } }),
countOutboundEmails(tenantId, { where: { opens: { some: {} } } }),
countOutboundEmails(tenantId, { where: { clicks: { some: {} } } }),
]);
const avgOpenRate = total > 0 ? (outboundEmailsWithOpens / total) * 100 : 0;
const avgClickRate = total > 0 ? (outboundEmailsWithClicks / total) * 100 : 0;
return {
avgOpenRate,
avgClickRate,
outboundEmails: {
sent,
delivered,
},
};
}
async function sendPreview({
from,
email,
}: {
from: { tenantId: string | null; sender: EmailSender };
email: { to: string; subject: string; htmlBody: string; textBody: string; track: true };
}): Promise<boolean> {
const outbountEmail = await createOutboundEmailTest({
tenantId: from.tenantId,
email: email.to,
fromSenderId: from.sender.id,
});
try {
email.htmlBody = replaceVariables(email.htmlBody, undefined);
email.textBody = replaceVariables(email.textBody, undefined);
email.subject = replaceVariables(email.subject, undefined);
await sendBroadcast({
sender: from.sender,
to: email.to,
subject: email.subject,
htmlBody: email.htmlBody,
textBody: email.textBody,
track: email.track,
metadata: { outboundEmailId: outbountEmail.id },
});
await updateOutboundEmail(outbountEmail.id, {
sentAt: new Date(),
});
return true;
} catch (e: any) {
await updateOutboundEmail(outbountEmail.id, {
error: e.message,
});
throw e;
}
}
async function sendContactPreview({
contactRowId,
from,
email,
}: {
contactRowId: string;
from: { tenantId: string | null; sender: EmailSender };
email: { to: string; subject: string; htmlBody: string; textBody: string; track: boolean };
}): Promise<boolean> {
const contact = await CrmService.getContact(contactRowId, from.tenantId);
if (!contact) {
throw Error("Contact not found: " + contactRowId);
}
const outbountEmail = await createOutboundEmail({
tenantId: from.tenantId,
contactRowId,
email: email.to,
fromSenderId: from.sender.id,
});
try {
if (!contact.marketingSubscriber) {
throw new Error(`Contact ${contact.email} is not a marketing subscriber`);
}
email.htmlBody = replaceVariables(email.htmlBody, contact);
email.textBody = replaceVariables(email.textBody, contact);
email.subject = replaceVariables(email.subject, contact);
await sendBroadcast({
sender: from.sender,
to: email.to,
subject: email.subject,
htmlBody: email.htmlBody,
textBody: email.textBody,
track: email.track,
metadata: { outboundEmailId: outbountEmail.id },
});
await updateOutboundEmail(outbountEmail.id, {
sentAt: new Date(),
});
return true;
} catch (e: any) {
await updateOutboundEmail(outbountEmail.id, {
error: e.message,
});
throw e;
}
}
function replaceVariables(value: string, contact?: ContactDto): string {
value = value.replace(/{{firstName}}/g, contact?.firstName ?? "");
value = value.replace(/{{lastName}}/g, contact?.lastName ?? "");
value = value.replace(/{{email}}/g, contact?.email ?? "");
value = value.replace(/{{job_title}}/g, contact?.jobTitle ?? "");
value = value.replace(/{{company_name}}/g, contact?.company?.name ?? "");
return value;
}
async function getCampaignRecipientContacts(campaign: CampaignWithDetails): Promise<Map<string, ContactDto>> {
const contactRowIds = Array.from(
new Set(campaign.recipients.map((recipient) => recipient.contactRow?.id).filter((id): id is string => Boolean(id)))
);
const contacts = contactRowIds.length > 0 ? await CrmService.getContactsInRowIds(contactRowIds, campaign.tenantId) : [];
return new Map(contacts.map((contact) => [contact.id, contact]));
}
async function createCampaignDraft({
name,
contactViewId,
from,
email,
}: {
name: string;
contactViewId: string | undefined;
from: { tenantId: string | null; sender: EmailSender };
email: {
subject: string;
htmlBody: string;
textBody: string | undefined;
track: boolean;
};
}): Promise<Campaign> {
const contacts = await getContactMarketingSubscribersFromView({ contactViewId, tenantId: from.tenantId });
if (contacts.length === 0) {
throw new Error("No contacts found that are marketing subscribers");
}
const campaign = await createCampaign(
{
emailSenderId: from.sender.id,
tenantId: from.tenantId,
name,
subject: email.subject,
htmlBody: email.htmlBody,
textBody: email.textBody,
track: email.track,
},
contacts.map((contact) => {
return { contactRowId: contact.id, email: contact.email, fromSenderId: from.sender.id };
})
);
if (!campaign) {
throw new Error("Failed to create campaign");
}
return campaign;
}
async function getContactMarketingSubscribersFromView({
contactViewId,
tenantId,
}: {
contactViewId: string | undefined;
tenantId: string | null;
}): Promise<ContactDto[]> {
const contactView = await EntityViewsApi.get(contactViewId, {
tenantId,
entityName: "contact",
pageSize: -1,
});
if (!contactView) {
if (contactViewId) {
throw new Error("Contact view not found: " + contactViewId);
} else {
throw Error("Contact default view not found");
}
}
if (contactView.rowsData.items.length === 0) {
throw Error("No contacts found");
}
const contacts = await CrmService.getContactsInRowIds(
contactView.rowsData.items.map((i) => i.id),
tenantId
);
if (contacts.length === 0) {
if (contactView.rowsData.currentView) {
throw Error("No contacts found in view: " + contactView.rowsData.currentView.name);
} else {
throw Error("No contacts found in default view");
}
}
const notMarketingSubscribers = contacts.filter((c) => !c.marketingSubscriber);
if (notMarketingSubscribers.length > 0) {
throw Error(
`${notMarketingSubscribers.length}/${contacts.length} contacts are not marketing subscribers: ${notMarketingSubscribers.map((c) => c.email).join(", ")}`
);
}
return contacts;
}
async function sendCampaignTest(campaign: CampaignWithDetails, email: string): Promise<boolean> {
if (campaign.recipients.length === 0) {
throw new Error("No recipients found");
}
const notContacts = campaign.recipients.filter((r) => !r.contactRowId);
if (notContacts.length > 0) {
throw new Error("Campaign has non-contact recipients: " + notContacts.map((r) => r.email).join(", "));
}
let maxTests = 5;
let recipients = campaign.recipients.slice(0, maxTests);
await Promise.all(
recipients.map(async (recipient, idx) => {
await sendContactPreview({
contactRowId: recipient.contactRowId ?? "",
from: {
tenantId: campaign.tenantId,
sender: campaign.emailSender,
},
email: {
to: email,
subject: i18nT("emailMarketing:campaignPreview.testSubject", {
index: idx + 1,
total: campaign.recipients.length,
subject: campaign.subject,
}),
htmlBody: campaign.htmlBody,
textBody: campaign.textBody ?? "",
track: campaign.track,
},
});
})
);
return true;
}
async function sendCampaign(campaign: CampaignWithDetails, options: { concurrency?: number } = {}): Promise<boolean> {
if (campaign.recipients.length === 0) {
throw new Error("No recipients found");
}
const notContacts = campaign.recipients.filter((r) => !r.contactRowId);
if (notContacts.length > 0) {
throw new Error("Campaign has non-contact recipients: " + notContacts.map((r) => r.email).join(", "));
}
await updateCampaign(campaign.id, campaign.tenantId, {
status: "sending",
});
const contactsByRowId = await getCampaignRecipientContacts(campaign);
let totalSent = 0;
await mapWithConcurrency(campaign.recipients, options.concurrency ?? 5, async (recipient) => {
try {
if (!recipient.contactRow) {
throw new Error("Contact not found: " + recipient.email);
}
const contact = contactsByRowId.get(recipient.contactRow.id);
if (!contact) {
throw new Error("Could not parse contact not found: " + recipient.email);
}
await updateOutboundEmail(recipient.id, {
sentAt: new Date(),
error: undefined,
});
await sendBroadcast({
sender: campaign.emailSender,
to: recipient.email,
subject: replaceVariables(campaign.subject, contact),
htmlBody: replaceVariables(campaign.htmlBody, contact),
textBody: replaceVariables(campaign.textBody ?? "", contact),
track: campaign.track,
metadata: { outboundEmailId: recipient.id },
});
totalSent++;
} catch (e: any) {
await updateOutboundEmail(recipient.id, {
error: e.message,
});
}
});
if (totalSent === campaign.recipients.length) {
await updateCampaign(campaign.id, campaign.tenantId, {
status: "completed",
});
} else {
await updateCampaign(campaign.id, campaign.tenantId, {
status: "incomplete",
});
}
return true;
}
export default {
getSummary,
getContactMarketingSubscribersFromView,
sendPreview,
sendContactPreview,
createCampaignDraft,
sendCampaignTest,
sendCampaign,
};
@@ -0,0 +1,243 @@
// AK-P14b (P14 email marketing) — typed segment resolution service.
//
// Resolves a RecipientSegment's nested AND/OR filter tree against the R-P6 TYPED
// Kontakt model (AD-2: NOT the Entity-Builder / CrmService). Tags + custom fields
// are polymorphic in crm.prisma (no Kontakt relation), so their leaves are
// resolved to Kontakt id-sets first (mirrors crmService.resolveKontaktBrowserWhere)
// and fed into the pure where-builder. Auto-exclusion removes contacts that must
// not receive marketing: archived, no e-mail, unsubscribed, suppressed (AK-P14a)
// or without a confirmed double-opt-in. Always tenant + owner scoped via
// withTenantRLS. NO React/UI imports.
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { ownerScopeWhere, type CrmVisibilityContext } from "~/utils/integrations/crm/crmService.server";
import {
buildKontaktWhere,
collectLookupRefs,
lookupRefKey,
validateSegmentTree,
type LookupRef,
type SegmentNode,
type SegmentValidationError,
} from "~/utils/integrations/email/segmentFilter";
const KONTAKT_ENTITY_TYPE = "kontakt";
// Upper bound on the rows pulled into memory for partitioning. Generous for v1;
// segments larger than this are reported as capped (see `scanCapped`).
const MAX_SEGMENT_SCAN = 100_000;
const SAMPLE_SIZE = 50;
/** Domain error carrying an i18n message key (M002 Klartext). */
export class SegmentServiceError extends Error {
readonly messageKey: SegmentValidationError;
constructor(messageKey: SegmentValidationError) {
super(messageKey);
this.name = "SegmentServiceError";
this.messageKey = messageKey;
}
}
/** Non-overlapping exclusion breakdown (priority order: archived → noEmail →
* unsubscribed → suppressed → noOptIn). Sums to `matched - eligible`. */
export interface SegmentExclusionBreakdown {
archived: number;
noEmail: number;
unsubscribed: number;
suppressed: number;
noOptIn: number;
}
export interface SegmentSampleRow {
kontaktId: string;
name: string;
email: string;
}
export interface SegmentResolution {
matched: number;
eligible: number;
exclusion: SegmentExclusionBreakdown;
eligibleKontaktIds: string[];
sample: SegmentSampleRow[];
scanCapped: boolean;
}
type MatchedRow = {
id: string;
vorname: string | null;
nachname: string | null;
orgName: string | null;
primaerEmail: string | null;
archivedAt: Date | null;
};
function displayName(row: MatchedRow): string {
const person = [row.vorname, row.nachname].filter(Boolean).join(" ").trim();
return row.orgName?.trim() || person || row.primaerEmail || row.id;
}
/** Resolve one lookup leaf to the set of matching Kontakt ids (tenant-scoped). */
async function resolveLookupRef(tx: TenantRlsClient, tenantId: string, ref: LookupRef): Promise<string[]> {
if (ref.kind === "tag") {
const rows = await tx.tagAssignment.findMany({
where: { tenantId, entityType: KONTAKT_ENTITY_TYPE, tagId: ref.tagId },
select: { entityId: true },
});
return [...new Set(rows.map((r) => r.entityId))];
}
// custom-field leaves. `wert` is a Json column; for an equality leaf we compare
// the stored scalar in JS (Prisma returns the parsed value) — avoids the Json
// filter typing and is correct for string/number/boolean custom fields.
const rows = await tx.customFieldValue.findMany({
where: { tenantId, entityType: KONTAKT_ENTITY_TYPE, definitionId: ref.definitionId },
select: { entityId: true, wert: true },
});
const matched = ref.kind === "customFieldEquals" ? rows.filter((r) => r.wert === ref.value) : rows;
return [...new Set(matched.map((r) => r.entityId))];
}
/**
* Resolve a segment filter to a count / eligibility breakdown / sample. The
* returned `eligibleKontaktIds` is the audience the send-engine (S3) uses.
*/
export async function resolveSegment(input: {
tenantId: string;
ctx: CrmVisibilityContext;
filterDefinition: unknown;
}): Promise<SegmentResolution> {
const validation = validateSegmentTree(input.filterDefinition);
if (!validation.ok) {
throw new SegmentServiceError(validation.errorKey);
}
const tree: SegmentNode = validation.tree;
return withTenantRLS(input.tenantId, async (tx) => {
// 1. Resolve lookup leaves (tags / custom fields) to Kontakt id-sets.
const refs = collectLookupRefs(tree);
const resolved = new Map<string, readonly string[]>();
for (const ref of refs) {
resolved.set(lookupRefKey(ref), await resolveLookupRef(tx, input.tenantId, ref));
}
// 2. Build the typed where and pull the matched rows (archived included so we
// can attribute the "archived" exclusion reason).
const segmentWhere = buildKontaktWhere(tree, resolved);
const where = { AND: [{ tenantId: input.tenantId }, ownerScopeWhere(input.ctx), segmentWhere] };
const total = await tx.kontakt.count({ where });
const matchedRows = (await tx.kontakt.findMany({
where,
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true, archivedAt: true },
orderBy: { createdAt: "desc" },
take: MAX_SEGMENT_SCAN,
})) as MatchedRow[];
const scanCapped = total > matchedRows.length;
// 3. Load auto-exclusion sources for the tenant.
const matchedIds = matchedRows.map((r) => r.id);
const matchedEmails = matchedRows.map((r) => r.primaerEmail).filter((e): e is string => Boolean(e));
const [unsubRows, consentRows, suppressionRows] = await Promise.all([
tx.unsubscribe.findMany({ where: { tenantId: input.tenantId, scope: "all", kontaktId: { in: matchedIds } }, select: { kontaktId: true } }),
tx.kontaktMarketingConsent.findMany({ where: { tenantId: input.tenantId, kontaktId: { in: matchedIds } }, select: { kontaktId: true, status: true } }),
tx.emailSuppressionList.findMany({ where: { tenantId: input.tenantId, emailAddress: { in: matchedEmails } }, select: { emailAddress: true } }),
]);
const unsubscribed = new Set(unsubRows.map((r) => r.kontaktId));
const confirmed = new Set(consentRows.filter((r) => r.status === "double").map((r) => r.kontaktId));
const suppressed = new Set(suppressionRows.map((r) => r.emailAddress.toLowerCase()));
// 4. Partition in priority order (non-overlapping).
const exclusion: SegmentExclusionBreakdown = { archived: 0, noEmail: 0, unsubscribed: 0, suppressed: 0, noOptIn: 0 };
const eligibleKontaktIds: string[] = [];
const sample: SegmentSampleRow[] = [];
for (const row of matchedRows) {
if (row.archivedAt) {
exclusion.archived += 1;
} else if (!row.primaerEmail) {
exclusion.noEmail += 1;
} else if (unsubscribed.has(row.id)) {
exclusion.unsubscribed += 1;
} else if (suppressed.has(row.primaerEmail.toLowerCase())) {
exclusion.suppressed += 1;
} else if (!confirmed.has(row.id)) {
exclusion.noOptIn += 1;
} else {
eligibleKontaktIds.push(row.id);
if (sample.length < SAMPLE_SIZE) {
sample.push({ kontaktId: row.id, name: displayName(row), email: row.primaerEmail });
}
}
}
return { matched: total, eligible: eligibleKontaktIds.length, exclusion, eligibleKontaktIds, sample, scanCapped };
});
}
export interface SegmentListRow {
id: string;
name: string;
isStaticSnapshot: boolean;
filterDefinition: unknown;
createdAt: Date;
}
/** List the tenant's (non-archived) recipient segments. */
export async function listSegments(tenantId: string): Promise<SegmentListRow[]> {
return withTenantRLS(tenantId, async (tx) => {
const rows = await tx.recipientSegment.findMany({
where: { tenantId, archivedAt: null },
select: { id: true, name: true, isStaticSnapshot: true, filterDefinition: true, createdAt: true },
orderBy: { createdAt: "desc" },
});
return rows as SegmentListRow[];
});
}
/** Create a recipient segment after validating its filter tree. For a static
* snapshot, immediately freeze the eligible membership. */
export async function createSegment(input: {
tenantId: string;
ctx: CrmVisibilityContext;
name: string;
filterDefinition: unknown;
isStaticSnapshot: boolean;
}): Promise<{ id: string }> {
const validation = validateSegmentTree(input.filterDefinition);
if (!validation.ok) throw new SegmentServiceError(validation.errorKey);
const created = await withTenantRLS(input.tenantId, async (tx) =>
tx.recipientSegment.create({
data: {
tenantId: input.tenantId,
name: input.name,
entityType: KONTAKT_ENTITY_TYPE,
filterDefinition: input.filterDefinition as object,
isStaticSnapshot: input.isStaticSnapshot,
},
select: { id: true },
})
);
if (input.isStaticSnapshot) {
await snapshotSegment({ tenantId: input.tenantId, ctx: input.ctx, segmentId: created.id, filterDefinition: input.filterDefinition });
}
return created;
}
/** Freeze a dynamic segment's current eligible membership into snapshot rows. */
export async function snapshotSegment(input: {
tenantId: string;
ctx: CrmVisibilityContext;
segmentId: string;
filterDefinition: unknown;
}): Promise<{ memberCount: number }> {
const resolution = await resolveSegment({ tenantId: input.tenantId, ctx: input.ctx, filterDefinition: input.filterDefinition });
await withTenantRLS(input.tenantId, async (tx) => {
await tx.segmentSnapshotMember.deleteMany({ where: { tenantId: input.tenantId, segmentId: input.segmentId } });
if (resolution.eligibleKontaktIds.length > 0) {
await tx.segmentSnapshotMember.createMany({
data: resolution.eligibleKontaktIds.map((kontaktId) => ({ tenantId: input.tenantId, segmentId: input.segmentId, kontaktId })),
skipDuplicates: true,
});
}
});
return { memberCount: resolution.eligibleKontaktIds.length };
}