Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
+49
@@ -0,0 +1,49 @@
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { EmailMarketing_Summary } from "../routes/EmailMarketing_Summary";
|
||||
|
||||
export default function EmailMarketingSummaryRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<EmailMarketing_Summary.LoaderData>();
|
||||
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="border-border border-b pb-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("shared.overview")}</h3>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-3">
|
||||
<div className="bg-card border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("emailMarketing:overview.avgOpenRate")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">
|
||||
{formatters.percent(data.summary.avgOpenRate / 100, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="bg-card border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("emailMarketing:overview.avgClickRate")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">
|
||||
{formatters.percent(data.summary.avgClickRate / 100, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="bg-card border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs">
|
||||
<dt className="text-muted-foreground flex items-center space-x-2 truncate text-xs font-medium uppercase">
|
||||
<ColorBadge color={Colors.GREEN} />
|
||||
<div>{t("emailMarketing:overview.totalSent")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 flex items-baseline space-x-1 truncate text-2xl font-semibold">
|
||||
<div>
|
||||
{formatters.number(data.summary.outboundEmails.delivered)}/{formatters.number(data.summary.outboundEmails.sent)}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs font-normal lowercase">{t("emails.delivered")}</div>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { EmailSenderWithoutApiKey } from "~/modules/emailMarketing/db/emailSender";
|
||||
|
||||
interface Props {
|
||||
item?: EmailSenderWithoutApiKey;
|
||||
}
|
||||
|
||||
export default function EmailSenderForm({ item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const [provider, setProvider] = useState<string>(item?.provider ?? "mailjet");
|
||||
const [stream, setStream] = useState<string>(item?.stream ?? "default");
|
||||
const [apiKey, setApiKey] = useState<string>("*******************");
|
||||
const [secretKey, setSecretKey] = useState<string>("*******************");
|
||||
const [fromEmail, setFromEmail] = useState<string>(item?.fromEmail ?? "marketing@" + rootData.appConfiguration.app.domain);
|
||||
// const [fromName, setFromName] = useState<string>(item?.fromName ?? "");
|
||||
// const [replyToEmail, setReplyToEmail] = useState<string>(item?.replyToEmail ?? "");
|
||||
|
||||
return (
|
||||
<FormGroup id={item?.id} editing={true}>
|
||||
{/* <input type="hidden" name="order" value={order} hidden readOnly /> */}
|
||||
<InputSelect
|
||||
name="provider"
|
||||
title={t("emailMarketing:senders.provider")}
|
||||
value={provider}
|
||||
setValue={(e) => setProvider(e?.toString() ?? "")}
|
||||
options={[
|
||||
{
|
||||
name: "Mailjet",
|
||||
value: "mailjet",
|
||||
},
|
||||
]}
|
||||
required
|
||||
/>
|
||||
<InputText name="stream" title={t("emailMarketing:senders.stream") + " / Domain ID"} value={stream} setValue={setStream} required />
|
||||
<InputText type="password" name="apiKey" title={t("emailMarketing:senders.apiKey")} value={apiKey} setValue={setApiKey} required disabled={!!item} />
|
||||
<InputText type="password" name="secretKey" title={t("emailMarketing:senders.secretKey")} value={secretKey} setValue={setSecretKey} required disabled={!!item} />
|
||||
<InputText name="fromEmail" title={t("emailMarketing:senders.fromEmail")} value={fromEmail} setValue={setFromEmail} required />
|
||||
{/* <InputText name="fromName" title={t("emailMarketing:senders.fromName")} value={fromName} setValue={setFromName} />
|
||||
<InputText name="replyToEmail" title={t("emailMarketing:senders.replyToEmail")} value={replyToEmail} setValue={setReplyToEmail} /> */}
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
import { Link, useParams } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
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>[] = [
|
||||
{
|
||||
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>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "sentAt",
|
||||
title: t("emails.sentAt"),
|
||||
value: (i) => (
|
||||
<div className="flex justify-center">{i.sentAt ? <OutboundEmailDateFormat date={i.sentAt} /> : <XIcon className="h-4 w-4 text-red-500" />}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "delivered",
|
||||
title: t("emails.delivered"),
|
||||
value: (i) => (
|
||||
<div className="flex justify-center">
|
||||
{i.deliveredAt ? <CheckIcon className="h-4 w-4 text-teal-500" /> : <XIcon className="h-4 w-4 text-red-500" />}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "activity",
|
||||
title: t("emailMarketing:activity"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col justify-start space-y-1 text-left">
|
||||
<button
|
||||
type="button"
|
||||
disabled={i.opens.length === 0}
|
||||
onClick={() => setSelectedEmail(i)}
|
||||
className={clsx(
|
||||
i.opens.length === 0 ? "text-muted-foreground cursor-not-allowed text-left" : "text-blue-600 underline",
|
||||
"text-muted-foreground lowercase"
|
||||
)}
|
||||
>
|
||||
{formatters.number(i.opens.length)} {t("emails.opens")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={i.clicks.length === 0}
|
||||
onClick={() => setSelectedEmail(i)}
|
||||
className={clsx(
|
||||
i.clicks.length === 0 ? "text-muted-foreground cursor-not-allowed text-left" : "text-blue-600 underline",
|
||||
"text-muted-foreground lowercase"
|
||||
)}
|
||||
>
|
||||
{formatters.number(i.clicks.length)} {t("emails.clicks")}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "error",
|
||||
title: t("shared.error"),
|
||||
value: (i) => <div className="text-red-500">{i.error}</div>,
|
||||
},
|
||||
{
|
||||
name: "unsubscribedAt",
|
||||
title: t("emails.unsubscribedAt"),
|
||||
value: (i) => <OutboundEmailDateFormat date={i.unsubscribedAt} />,
|
||||
},
|
||||
{
|
||||
name: "bouncedAt",
|
||||
title: t("emails.bouncedAt"),
|
||||
value: (i) => <OutboundEmailDateFormat date={i.bouncedAt} />,
|
||||
},
|
||||
{
|
||||
name: "spamComplainedAt",
|
||||
title: t("emails.spamComplainedAt"),
|
||||
value: (i) => <OutboundEmailDateFormat date={i.spamComplainedAt} />,
|
||||
},
|
||||
];
|
||||
if (withCampaign) {
|
||||
headers = [
|
||||
{
|
||||
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.isPreview ? <SimpleBadge title={t("shared.preview")} color={Colors.GRAY} /> : <div>-</div>}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
...headers,
|
||||
];
|
||||
}
|
||||
setHeaders(headers);
|
||||
}, [contactEntity, formatters, params.tenant, t, withCampaign]);
|
||||
return (
|
||||
<div>
|
||||
<TableSimple headers={headers} items={items} pagination={pagination} />
|
||||
<Modal className="sm:max-w-md" open={!!selectedEmail} setOpen={() => setSelectedEmail(undefined)}>
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("emails.emailActivity")}</h3>
|
||||
</div>
|
||||
<div className="border-border overflow-hidden rounded-md border-2 border-dashed">
|
||||
<div className="h-64 overflow-y-auto">{selectedEmail && <OutboundEmailActivity email={selectedEmail} />}</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OutboundEmailDateFormat({ date }: { date: Date | null }) {
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
return (
|
||||
<>
|
||||
{date && (
|
||||
<div title={formatters.dateTime(date, { timeStyle: "medium" })} className="flex flex-col">
|
||||
<div>{formatters.date(date, { dateStyle: "medium" })}</div>
|
||||
<div className="text-xs">{formatters.relativeDate(date)}</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function OutboundEmailActivity({ email }: { email: OutboundEmailWithDetails }) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const [items, setItems] = useState<{ type: "click" | "open"; createdAt: Date; description: string }[]>([]);
|
||||
useEffect(() => {
|
||||
const items: { type: "click" | "open"; createdAt: Date; description: string }[] = [];
|
||||
email.opens.forEach((o) => {
|
||||
items.push({
|
||||
type: "open",
|
||||
createdAt: o.createdAt,
|
||||
description: o.firstOpen ? t("emailMarketing:activityLog.firstOpen") : "",
|
||||
});
|
||||
});
|
||||
email.clicks.forEach((c) => {
|
||||
items.push({
|
||||
type: "click",
|
||||
createdAt: c.createdAt,
|
||||
description: c.link,
|
||||
});
|
||||
});
|
||||
setItems(items.sort((a, b) => (b.createdAt > a.createdAt ? -1 : 1)));
|
||||
}, [email, t]);
|
||||
return (
|
||||
<TableSimple
|
||||
items={items}
|
||||
headers={[
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("emailMarketing:activityLog.date"),
|
||||
value: (i) => <div className="text-muted-foreground">{formatters.dateTime(i.createdAt, { timeStyle: "medium" })}</div>,
|
||||
},
|
||||
{
|
||||
name: "type",
|
||||
title: t("emailMarketing:activityLog.type"),
|
||||
value: (i) => (i.type === "open" ? t("emailMarketing:activityLog.open") : t("emailMarketing:activityLog.click")),
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("shared.description"),
|
||||
value: (i) => i.description,
|
||||
className: "w-full",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+324
@@ -0,0 +1,324 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
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} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
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("<script>alert('x')</script>");
|
||||
expect(html).not.toContain("<script>");
|
||||
});
|
||||
});
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
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("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
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}");
|
||||
});
|
||||
});
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import { OutboundEmails_List } from "../../routes/OutboundEmails_List";
|
||||
import OutboundEmailsTable from "../OutboundEmailsTable";
|
||||
import { useLoaderData } from "react-router";
|
||||
|
||||
export default function OutboundEmailsListRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<OutboundEmails_List.LoaderData>();
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-3 px-4 py-2 pb-6 sm:px-6 sm:pt-3 lg:px-8 xl:max-w-full">
|
||||
<div className="md:border-border md:border-b md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("emailMarketing:activity")}</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<InputFilters withSearch={false} filters={data.filterableProperties} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<OutboundEmailsTable allEntities={data.allEntities} items={data.items} pagination={data.pagination} withCampaign={true} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { useLoaderData, useNavigate, useParams } from "react-router";
|
||||
import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { Senders_Edit } from "../../routes/Senders_Edit";
|
||||
import EmailSenderForm from "../EmailSenderForm";
|
||||
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export default function SendersEditRoute() {
|
||||
const data = useLoaderData<Senders_Edit.LoaderData>();
|
||||
const params = useParams();
|
||||
const navigate = useNavigate();
|
||||
function close() {
|
||||
navigate(params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/senders", mode: "host-aware" }) : adminPath("email-marketing/senders", { mode: "host-aware" }));
|
||||
}
|
||||
return (
|
||||
<OpenModal className="sm:max-w-sm" onClose={close}>
|
||||
<EmailSenderForm item={data.item} />
|
||||
</OpenModal>
|
||||
);
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import { useSubmit, Outlet, useLoaderData, useActionData } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import InfoBanner from "~/components/ui/banners/InfoBanner";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { EmailSenderWithoutApiKey } from "../../db/emailSender";
|
||||
import { Senders_List } from "../../routes/Senders_List";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
export default function SendersListRoute() {
|
||||
const data = useLoaderData<Senders_List.LoaderData>();
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const submit = useSubmit();
|
||||
const actionData = useActionData<Senders_List.ActionData>();
|
||||
const hasMailjetSenders = data.items.some((item) => item.provider === "mailjet");
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function sendTest(item: EmailSenderWithoutApiKey) {
|
||||
const email = window.prompt(t("emailMarketing:senders.testEmail.prompt"), appOrAdminData.user?.email);
|
||||
if (!email || email.trim() === "") {
|
||||
return;
|
||||
}
|
||||
const form = new FormData();
|
||||
form.set("action", "send-test");
|
||||
form.set("senderId", item.id);
|
||||
form.set("email", email);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<div className="mx-auto w-full max-w-5xl space-y-3 px-4 py-2 pb-6 sm:px-6 sm:pt-3 lg:px-8 xl:max-w-full">
|
||||
<div className="md:border-border md:border-b md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("emailMarketing:senders.plural")}</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonPrimary to="new">{t("shared.new")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.items.length === 0 ? (
|
||||
<InfoBanner title={t("shared.note")} text="">
|
||||
{t("emailMarketing:senders.setup.mailjetApiTokenPrefix")}{" "}
|
||||
<a className="underline" target="_blank" rel="noreferrer" href="https://app.mailjet.com/account/apikeys">
|
||||
{t("emailMarketing:senders.setup.apiTokensLink")}
|
||||
</a>
|
||||
{t("emailMarketing:senders.setup.mailjetApiTokenSuffix")}
|
||||
</InfoBanner>
|
||||
) : !data.hasSetWebhooks && hasMailjetSenders ? (
|
||||
<WarningBanner title={t("shared.warning")} text="">
|
||||
{t("emailMarketing:senders.setup.mailjetWebhookRequired")}
|
||||
</WarningBanner>
|
||||
) : null}
|
||||
|
||||
<TableSimple
|
||||
headers={[
|
||||
{
|
||||
name: "provider",
|
||||
title: t("emailMarketing:senders.provider"),
|
||||
value: (item) => item.provider,
|
||||
},
|
||||
{
|
||||
name: "stream",
|
||||
title: t("emailMarketing:senders.stream"),
|
||||
value: (item) => item.stream,
|
||||
},
|
||||
{
|
||||
name: "fromEmail",
|
||||
title: t("emailMarketing:senders.fromEmail"),
|
||||
value: (item) => item.fromEmail,
|
||||
},
|
||||
{
|
||||
name: "fromName",
|
||||
title: t("emailMarketing:senders.fromName"),
|
||||
value: (item) => item.fromName,
|
||||
},
|
||||
{
|
||||
name: "replyToEmail",
|
||||
title: t("emailMarketing:senders.replyToEmail"),
|
||||
value: (item) => item.replyToEmail,
|
||||
},
|
||||
]}
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.emails.sendTest"),
|
||||
onClick: (_, item) => sendTest(item),
|
||||
},
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, item) => item.id,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
</div>
|
||||
<Outlet />
|
||||
</>
|
||||
);
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { useParams, useNavigate } from "react-router";
|
||||
import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import EmailSenderForm from "../EmailSenderForm";
|
||||
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export default function SendersNewRoute() {
|
||||
const params = useParams();
|
||||
const navigate = useNavigate();
|
||||
function close() {
|
||||
navigate(params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/senders", mode: "host-aware" }) : adminPath("email-marketing/senders", { mode: "host-aware" }));
|
||||
}
|
||||
return (
|
||||
<OpenModal className="sm:max-w-sm" onClose={close}>
|
||||
<EmailSenderForm />
|
||||
</OpenModal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const source = readRepoFile("apps/web/app/modules/emailMarketing/db/campaigns.db.server.ts");
|
||||
|
||||
describe("campaign db tenant scope", () => {
|
||||
test("updates campaigns and recipient replacement through tenant scope", () => {
|
||||
expect(source).toContain("export async function updateCampaign(");
|
||||
expect(source).toContain("tenantId: string | null,");
|
||||
expect(source).toContain("db.campaign.updateMany");
|
||||
expect(source).toContain("where: {\n id,\n tenantId,");
|
||||
expect(source).toContain('throw new Error("Campaign not found for tenant scope.")');
|
||||
expect(source).toContain("db.outboundEmail.deleteMany");
|
||||
expect(source).toContain("campaignId: id,\n tenantId,");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { Campaign, EmailSender, OutboundEmail, OutboundEmailClick, OutboundEmailOpen } from "@toolctrl/db/prisma-browser";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { RowWithValues } from "~/utils/db/entities/rows.db.server";
|
||||
|
||||
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[]> {
|
||||
return await db.campaign.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
status,
|
||||
},
|
||||
include: {
|
||||
emailSender: true,
|
||||
recipients: {
|
||||
include: {
|
||||
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",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getCampaign(id: string, tenantId: string | null): Promise<CampaignWithDetails | null> {
|
||||
return await db.campaign.findFirst({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
include: {
|
||||
emailSender: true,
|
||||
recipients: {
|
||||
include: {
|
||||
campaign: true,
|
||||
opens: true,
|
||||
clicks: true,
|
||||
contactRow: {
|
||||
include: {
|
||||
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
createdByApiKey: true,
|
||||
values: { include: { media: true, multiple: true, range: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createCampaign(
|
||||
data: {
|
||||
emailSenderId: string;
|
||||
tenantId: string | null;
|
||||
name: string;
|
||||
subject: string;
|
||||
htmlBody: string;
|
||||
textBody: string | undefined;
|
||||
track: boolean;
|
||||
},
|
||||
recipients: { fromSenderId: string; email: string; contactRowId: string }[]
|
||||
): Promise<Campaign> {
|
||||
const item = await db.campaign.create({
|
||||
data: {
|
||||
...data,
|
||||
recipients: {
|
||||
create: recipients.map((recipient) => {
|
||||
return {
|
||||
tenantId: data.tenantId,
|
||||
contactRowId: recipient.contactRowId,
|
||||
email: recipient.email,
|
||||
fromSenderId: recipient.fromSenderId,
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function updateCampaign(
|
||||
id: string,
|
||||
tenantId: string | null,
|
||||
data: {
|
||||
name?: string;
|
||||
subject?: string;
|
||||
htmlBody?: string;
|
||||
textBody?: string | undefined;
|
||||
status?: string;
|
||||
track?: boolean;
|
||||
sentAt?: Date;
|
||||
},
|
||||
recipients?: { fromSenderId: string; email: string; contactRowId: string }[]
|
||||
): Promise<Campaign> {
|
||||
const result = await db.campaign.updateMany({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
data,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw new Error("Campaign not found for tenant scope.");
|
||||
}
|
||||
const item = await db.campaign.findFirstOrThrow({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
if (recipients) {
|
||||
await db.outboundEmail.deleteMany({
|
||||
where: {
|
||||
campaignId: id,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
await db.outboundEmail.createMany({
|
||||
data: recipients.map((recipient) => {
|
||||
return {
|
||||
tenantId: item.tenantId,
|
||||
campaignId: id,
|
||||
contactRowId: recipient.contactRowId,
|
||||
email: recipient.email,
|
||||
fromSenderId: recipient.fromSenderId,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function deleteCampaign(id: string, tenantId: string | null) {
|
||||
return await db.campaign.deleteMany({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function groupCampaigns(tenantId: string | null) {
|
||||
return await db.campaign.groupBy({
|
||||
by: ["status"],
|
||||
where: {
|
||||
tenantId,
|
||||
},
|
||||
_count: {
|
||||
_all: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { EmailSender } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export type EmailSenderWithoutApiKey = Omit<EmailSender, "apiKey" | "apiSecret">;
|
||||
export async function getAllEmailSenders(tenantId: string | null): Promise<EmailSenderWithoutApiKey[]> {
|
||||
return await db.emailSender.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
provider: true,
|
||||
stream: true,
|
||||
fromName: true,
|
||||
fromEmail: true,
|
||||
replyToEmail: true,
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
fromName: "asc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEmailSender(id: string, tenantId: string | null): Promise<EmailSender | null> {
|
||||
return await db.emailSender.findFirst({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEmailSenderWithoutApiKey(id: string, tenantId: string | null): Promise<EmailSenderWithoutApiKey | null> {
|
||||
return await db.emailSender.findFirst({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
provider: true,
|
||||
stream: true,
|
||||
fromName: true,
|
||||
fromEmail: true,
|
||||
replyToEmail: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createEmailSender(data: {
|
||||
tenantId: string | null;
|
||||
provider: string;
|
||||
stream: string;
|
||||
apiKey: string;
|
||||
apiSecret?: string;
|
||||
fromEmail: string;
|
||||
fromName?: string;
|
||||
replyToEmail?: string;
|
||||
}): Promise<EmailSender> {
|
||||
const item = await db.emailSender.create({
|
||||
data,
|
||||
});
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function updateEmailSender(
|
||||
id: string,
|
||||
tenantId: string | null,
|
||||
data: {
|
||||
provider: string;
|
||||
stream: string;
|
||||
fromEmail: string;
|
||||
fromName?: string;
|
||||
replyToEmail?: string;
|
||||
}
|
||||
): Promise<EmailSender> {
|
||||
const result = await db.emailSender.updateMany({
|
||||
where: { id, tenantId },
|
||||
data,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw new Error("Email sender not found");
|
||||
}
|
||||
|
||||
const item = await getEmailSender(id, tenantId);
|
||||
if (!item) {
|
||||
throw new Error("Email sender not found");
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function deleteEmailSender(id: string, tenantId: string | null): Promise<EmailSender> {
|
||||
const existing = await getEmailSender(id, tenantId);
|
||||
if (!existing) {
|
||||
throw new Error("Email sender not found");
|
||||
}
|
||||
|
||||
await db.outboundEmail.deleteMany({
|
||||
where: { fromSenderId: id, tenantId },
|
||||
});
|
||||
const result = await db.emailSender.deleteMany({
|
||||
where: { id, tenantId },
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw new Error("Email sender not found");
|
||||
}
|
||||
|
||||
return existing;
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import type { Campaign, OutboundEmail, OutboundEmailClick, OutboundEmailOpen, Prisma } from "@toolctrl/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";
|
||||
|
||||
export type OutboundEmailWithDetails = OutboundEmail & {
|
||||
campaign: Campaign | null;
|
||||
opens: OutboundEmailOpen[];
|
||||
clicks: OutboundEmailClick[];
|
||||
contactRow: RowWithValues | null;
|
||||
};
|
||||
|
||||
export async function getAllOutboundEmails(
|
||||
tenantId: string | null,
|
||||
options: {
|
||||
where?: Prisma.OutboundEmailWhereInput;
|
||||
pagination: { page: number; pageSize: number };
|
||||
}
|
||||
): Promise<{ items: OutboundEmailWithDetails[]; pagination: PaginationDto }> {
|
||||
const items = await db.outboundEmail.findMany({
|
||||
take: options.pagination.pageSize,
|
||||
skip: options.pagination.pageSize * (options.pagination.page - 1),
|
||||
where: {
|
||||
tenantId,
|
||||
...options.where,
|
||||
},
|
||||
include: {
|
||||
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" }],
|
||||
});
|
||||
const totalItems = await db.outboundEmail.count({
|
||||
where: {
|
||||
tenantId,
|
||||
...options.where,
|
||||
},
|
||||
});
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: options.pagination?.page ?? 1,
|
||||
pageSize: options.pagination.pageSize ?? Constants.DEFAULT_PAGE_SIZE,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / (options.pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function findOutboundEmails(
|
||||
tenantId: string | null,
|
||||
options: {
|
||||
where?: Prisma.OutboundEmailWhereInput;
|
||||
}
|
||||
) {
|
||||
return await db.outboundEmail.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...options.where,
|
||||
},
|
||||
include: {
|
||||
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" }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOutboundEmail(id: string) {
|
||||
return await db.outboundEmail.findFirst({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
campaign: true,
|
||||
opens: true,
|
||||
clicks: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createOutboundEmailTest(data: {
|
||||
tenantId: string | null;
|
||||
contactRowId?: string;
|
||||
email: string;
|
||||
fromSenderId: string;
|
||||
}): Promise<OutboundEmail> {
|
||||
const item = await db.outboundEmail.create({
|
||||
data: {
|
||||
...data,
|
||||
isPreview: true,
|
||||
},
|
||||
});
|
||||
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: {
|
||||
error?: string;
|
||||
sentAt?: Date;
|
||||
deliveredAt?: Date;
|
||||
bouncedAt?: Date;
|
||||
spamComplainedAt?: Date;
|
||||
unsubscribedAt?: Date;
|
||||
}
|
||||
) {
|
||||
const item = await db.outboundEmail.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
});
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function openedOutboundEmail(outboundEmailId: string, data: { firstOpen: boolean }) {
|
||||
const item = await db.outboundEmailOpen.create({
|
||||
data: {
|
||||
outboundEmailId,
|
||||
firstOpen: data.firstOpen,
|
||||
},
|
||||
});
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function clickedOutboundEmail(
|
||||
outboundEmailId: string,
|
||||
data: {
|
||||
link: string;
|
||||
}
|
||||
) {
|
||||
const item = await db.outboundEmailClick.create({
|
||||
data: {
|
||||
outboundEmailId,
|
||||
link: data.link,
|
||||
},
|
||||
});
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function unsubscribeCampaignRecipient(
|
||||
id: string,
|
||||
data: {
|
||||
unsubscribedAt: Date;
|
||||
}
|
||||
) {
|
||||
const item = await db.outboundEmail.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
});
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function countOutboundEmails(
|
||||
tenantId: string | null,
|
||||
options?: {
|
||||
where: Prisma.OutboundEmailWhereInput;
|
||||
}
|
||||
): Promise<number> {
|
||||
return await db.outboundEmail.count({
|
||||
where: {
|
||||
tenantId,
|
||||
...options?.where,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
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 });
|
||||
}
|
||||
};
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
// @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 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
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;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
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 });
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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 { requireAuth } from "~/utils/loaders.middleware";
|
||||
|
||||
export namespace EmailMarketing_Summary {
|
||||
export type LoaderData = {
|
||||
title: string;
|
||||
summary: EmailMarketingSummaryDto;
|
||||
};
|
||||
|
||||
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),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
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 {
|
||||
export type LoaderData = {
|
||||
items: OutboundEmailWithDetails[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
allEntities: EntityWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const emailSenders = await getAllEmailSenders(tenantId);
|
||||
const campaigns = await getAllCampaigns(tenantId);
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "senderId",
|
||||
title: t("emailMarketing:activityFilters.sender"),
|
||||
options: [
|
||||
...emailSenders.map((i) => {
|
||||
return {
|
||||
value: i.id,
|
||||
name: i.fromEmail + " (" + i.provider + ")",
|
||||
};
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "campaignId",
|
||||
title: t("emailMarketing:activityFilters.campaign"),
|
||||
options: [
|
||||
{ name: t("emailMarketing:activityFilters.preview"), value: "null" },
|
||||
...campaigns.map((i) => {
|
||||
return {
|
||||
value: i.id,
|
||||
name: i.name,
|
||||
};
|
||||
}),
|
||||
],
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const fromSenderId = filters.properties.find((f) => f.name === "senderId")?.value ?? undefined;
|
||||
const campaignId = filters.properties.find((f) => f.name === "campaignId")?.value;
|
||||
const { items, pagination } = await getAllOutboundEmails(tenantId, {
|
||||
where: {
|
||||
fromSenderId,
|
||||
campaignId: campaignId === "null" ? null : campaignId ?? undefined,
|
||||
},
|
||||
pagination: currentPagination,
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
allEntities: await getAllEntities({ tenantId, active: true }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { LoaderFunctionArgs, redirect, ActionFunction } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { EmailSenderWithoutApiKey, getEmailSenderWithoutApiKey, getEmailSender, updateEmailSender, deleteEmailSender } from "../db/emailSender";
|
||||
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 Senders_Edit {
|
||||
export type LoaderData = {
|
||||
item: EmailSenderWithoutApiKey;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const item = await getEmailSenderWithoutApiKey(params.id!, tenantId);
|
||||
if (!item) {
|
||||
return redirect(params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/senders", mode: "host-aware" }) : adminPath("email-marketing/senders", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
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 });
|
||||
|
||||
const existing = await getEmailSender(params.id ?? "", tenantId);
|
||||
if (!existing) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
if (action === "edit") {
|
||||
try {
|
||||
const provider = form.get("provider")?.toString() ?? "";
|
||||
const stream = form.get("stream")?.toString() ?? "";
|
||||
const fromEmail = form.get("fromEmail")?.toString() ?? "";
|
||||
const fromName = form.get("fromName")?.toString() ?? "";
|
||||
const replyToEmail = form.get("replyToEmail")?.toString() ?? "";
|
||||
|
||||
await updateEmailSender(existing.id, tenantId, {
|
||||
provider,
|
||||
stream,
|
||||
fromEmail,
|
||||
fromName,
|
||||
replyToEmail,
|
||||
});
|
||||
return redirect(params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/senders", mode: "host-aware" }) : adminPath("email-marketing/senders", { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await deleteEmailSender(existing.id, tenantId);
|
||||
return redirect(params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/senders", mode: "host-aware" }) : adminPath("email-marketing/senders", { mode: "host-aware" }));
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { LoaderFunctionArgs, ActionFunction } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { EmailSenderWithoutApiKey, getAllEmailSenders, getEmailSender } from "../db/emailSender";
|
||||
import { createOutboundEmailTest, findOutboundEmails, updateOutboundEmail } from "../db/outboundEmails.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { sendBroadcast } from "../services/EmailMarketingSenderService.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requireEmailMarketingMutationAccess } from "./emailMarketingAccess.server";
|
||||
export namespace Senders_List {
|
||||
export type LoaderData = {
|
||||
items: EmailSenderWithoutApiKey[];
|
||||
hasSetWebhooks: boolean;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const items = await getAllEmailSenders(tenantId);
|
||||
const deliveredEmails = await findOutboundEmails(tenantId, {
|
||||
where: {
|
||||
deliveredAt: { not: null },
|
||||
},
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
hasSetWebhooks: deliveredEmails.length > 0,
|
||||
};
|
||||
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() ?? "";
|
||||
if (action === "send-test") {
|
||||
const sender = await getEmailSender(senderId, tenantId);
|
||||
if (!sender) {
|
||||
return Response.json({ error: t("emailMarketing:errors.invalidSender") }, { status: 400 });
|
||||
}
|
||||
const outbountEmail = await createOutboundEmailTest({
|
||||
tenantId,
|
||||
email,
|
||||
fromSenderId: senderId,
|
||||
});
|
||||
try {
|
||||
await sendBroadcast({
|
||||
sender,
|
||||
to: email,
|
||||
subject: t("emailMarketing:senders.testEmail.subject"),
|
||||
htmlBody: getTestHtmlBody(t),
|
||||
textBody: `${t("emailMarketing:defaults.body.testEmailWithLink")}: https://www.example.com.\n`,
|
||||
track: true,
|
||||
metadata: {
|
||||
outboundEmailId: outbountEmail.id,
|
||||
},
|
||||
});
|
||||
await updateOutboundEmail(outbountEmail.id, {
|
||||
sentAt: new Date(),
|
||||
});
|
||||
return Response.json({ success: t("shared.sent") }, { status: 200 });
|
||||
} catch (e: any) {
|
||||
await updateOutboundEmail(outbountEmail.id, {
|
||||
error: e.message,
|
||||
});
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getTestHtmlBody(t: (key: string) => string) {
|
||||
return `${t("emailMarketing:defaults.body.testEmailWithLink")}:
|
||||
${t("emailMarketing:defaults.body.linkLabel")}: <a href="https://www.google.com">Google</a><br/>
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { LoaderFunctionArgs, redirect, ActionFunction } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { createEmailSender } from "../db/emailSender";
|
||||
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 Senders_New {
|
||||
export type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("emailMarketing:senders.plural")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
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() ?? "";
|
||||
if (action === "create") {
|
||||
try {
|
||||
const provider = form.get("provider")?.toString() ?? "";
|
||||
const stream = form.get("stream")?.toString() ?? "";
|
||||
const apiKey = form.get("apiKey")?.toString() ?? "";
|
||||
const apiSecret = form.get("secretKey")?.toString() ?? "";
|
||||
const fromEmail = form.get("fromEmail")?.toString() ?? "";
|
||||
const fromName = form.get("fromName")?.toString() ?? "";
|
||||
const replyToEmail = form.get("replyToEmail")?.toString() ?? "";
|
||||
|
||||
await createEmailSender({
|
||||
tenantId,
|
||||
provider,
|
||||
stream,
|
||||
apiKey,
|
||||
apiSecret,
|
||||
fromEmail,
|
||||
fromName,
|
||||
replyToEmail,
|
||||
});
|
||||
return redirect(params.tenant ? appPath({ tenantSlug: params.tenant, path: "email-marketing/senders", mode: "host-aware" }) : adminPath("email-marketing/senders", { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
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",
|
||||
"modules/emailMarketing/routes/Senders_Edit.ts",
|
||||
"modules/emailMarketing/routes/Senders_List.ts",
|
||||
"modules/emailMarketing/routes/Senders_New.ts",
|
||||
];
|
||||
|
||||
describe("email marketing route authorization boundary", () => {
|
||||
test("requires tenant admin access and csrf before parsing mutating forms", () => {
|
||||
for (const relativePath of emailMarketingMutationHandlers) {
|
||||
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
|
||||
expect(source.indexOf("await requireEmailMarketingMutationAccess({ request, params, tenantId })"), relativePath).toBeGreaterThanOrEqual(0);
|
||||
expect(source.indexOf("await validateCSRFToken(request)"), relativePath).toBeGreaterThanOrEqual(0);
|
||||
expect(source.indexOf("await requireEmailMarketingMutationAccess({ request, params, tenantId })"), relativePath).toBeLessThan(
|
||||
source.indexOf("await request.formData()")
|
||||
);
|
||||
expect(source.indexOf("await validateCSRFToken(request)"), relativePath).toBeLessThan(source.indexOf("await request.formData()"));
|
||||
}
|
||||
});
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import type { Params } from "react-router";
|
||||
import { requireSuperUserOrAdmin } from "~/utils/loaders.middleware";
|
||||
|
||||
export async function requireEmailMarketingMutationAccess({
|
||||
request,
|
||||
params,
|
||||
tenantId,
|
||||
}: {
|
||||
request: Request;
|
||||
params: Params;
|
||||
tenantId: string | null;
|
||||
}) {
|
||||
if (tenantId) {
|
||||
await requireSuperUserOrAdmin({ request, params });
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import type { EmailSender } from "@toolctrl/db/prisma-browser";
|
||||
import { createMailjetProvider } from "@toolctrl/mail";
|
||||
|
||||
type BroadcastEmail = {
|
||||
sender: EmailSender;
|
||||
to: string;
|
||||
subject: string;
|
||||
htmlBody: string;
|
||||
textBody: string;
|
||||
track: boolean;
|
||||
metadata: { [key: string]: string };
|
||||
};
|
||||
|
||||
async function sendMailjetBroadcast({ sender, to, subject, htmlBody, textBody, track }: BroadcastEmail) {
|
||||
if (!sender.apiKey || !sender.apiSecret) {
|
||||
throw Error("Invalid Mailjet API credentials");
|
||||
}
|
||||
|
||||
const mailjet = createMailjetProvider({
|
||||
apiKey: sender.apiKey,
|
||||
secretKey: sender.apiSecret,
|
||||
fromEmail: sender.fromEmail,
|
||||
fromName: sender.fromName ?? undefined,
|
||||
});
|
||||
|
||||
return await mailjet.send({
|
||||
from: { email: sender.fromEmail, name: sender.fromName ?? undefined },
|
||||
to: [to],
|
||||
replyTo: sender.replyToEmail ? { email: sender.replyToEmail, name: sender.fromName ?? undefined } : undefined,
|
||||
subject,
|
||||
html: htmlBody,
|
||||
text: textBody,
|
||||
tags: ["email-marketing"],
|
||||
settings: {
|
||||
trackClicks: track,
|
||||
trackOpens: track,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendBroadcast(email: BroadcastEmail) {
|
||||
switch (email.sender.provider) {
|
||||
case "mailjet":
|
||||
return await sendMailjetBroadcast(email);
|
||||
default:
|
||||
throw Error(`Unsupported email marketing sender provider: ${email.sender.provider}`);
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
// @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: {} } } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,323 @@
|
||||
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,
|
||||
};
|
||||
Reference in new issue
Block a user