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
@@ -0,0 +1,286 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loader } from "./$id.stats";
|
||||
import { dbRead } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
const dbMocks = vi.hoisted(() => ({
|
||||
sequenceFindFirst: vi.fn(),
|
||||
runGroupBy: vi.fn(),
|
||||
deliveryGroupBy: vi.fn(),
|
||||
deliveryFindMany: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
dbRead: {
|
||||
emailSequence: {
|
||||
findFirst: dbMocks.sequenceFindFirst,
|
||||
},
|
||||
emailSequenceRun: {
|
||||
groupBy: dbMocks.runGroupBy,
|
||||
},
|
||||
emailSequenceStepDelivery: {
|
||||
groupBy: dbMocks.deliveryGroupBy,
|
||||
findMany: dbMocks.deliveryFindMany,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("i18next", () => ({
|
||||
t: (key: string) => key,
|
||||
}));
|
||||
|
||||
async function callLoader() {
|
||||
const request = new Request("https://admin.example.test/email-sequences/seq-1/stats");
|
||||
const response = (await loader({
|
||||
request,
|
||||
params: { id: "seq-1" },
|
||||
context: {},
|
||||
unstable_pattern: "admin/email-sequences/:id/stats",
|
||||
} as LoaderFunctionArgs)) as Response;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
describe("admin email sequence stats loader", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(dbRead.emailSequence.findFirst).mockResolvedValue({
|
||||
id: "seq-1",
|
||||
name: "Onboarding",
|
||||
triggerEvent: "lead.created",
|
||||
isEnabled: true,
|
||||
stepsJson: [
|
||||
{ stepIndex: 0, template: "welcome", subject: "Welcome" },
|
||||
{ stepIndex: 1, template: "follow-up", subject: "Checking in" },
|
||||
],
|
||||
} as never);
|
||||
vi.mocked(dbRead.emailSequenceRun.groupBy).mockResolvedValue([
|
||||
{ status: "completed", _count: { _all: 2 } },
|
||||
{ status: "running", _count: { _all: 1 } },
|
||||
{ status: "cancelled", _count: { _all: 1 } },
|
||||
] as never);
|
||||
vi.mocked(dbRead.emailSequenceStepDelivery.groupBy)
|
||||
.mockResolvedValueOnce([
|
||||
{ stepIndex: 0, status: "sent", _count: { _all: 2 } },
|
||||
{ stepIndex: 0, status: "bounced", _count: { _all: 1 } },
|
||||
{ stepIndex: 1, status: "skipped", _count: { _all: 1 } },
|
||||
{ stepIndex: 1, status: "failed", _count: { _all: 1 } },
|
||||
] as never)
|
||||
.mockResolvedValueOnce([
|
||||
{ stepIndex: 0, _count: { _all: 2 } },
|
||||
{ stepIndex: 1, _count: { _all: 1 } },
|
||||
] as never)
|
||||
.mockResolvedValueOnce([{ stepIndex: 0, _count: { _all: 1 } }] as never);
|
||||
});
|
||||
|
||||
it("aggregates delivery stats in the database instead of loading deliveries", async () => {
|
||||
const data = await callLoader();
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.marketing.leads.view");
|
||||
expect(dbRead.emailSequenceStepDelivery.findMany).not.toHaveBeenCalled();
|
||||
expect(dbRead.emailSequenceStepDelivery.groupBy).toHaveBeenCalledTimes(3);
|
||||
expect(dbRead.emailSequenceStepDelivery.groupBy).toHaveBeenNthCalledWith(1, {
|
||||
by: ["stepIndex", "status"],
|
||||
where: { run: { sequenceId: "seq-1" } },
|
||||
_count: { _all: true },
|
||||
});
|
||||
expect(dbRead.emailSequenceStepDelivery.groupBy).toHaveBeenNthCalledWith(2, {
|
||||
by: ["stepIndex"],
|
||||
where: { run: { sequenceId: "seq-1" }, openedAt: { not: null } },
|
||||
_count: { _all: true },
|
||||
});
|
||||
expect(dbRead.emailSequenceStepDelivery.groupBy).toHaveBeenNthCalledWith(3, {
|
||||
by: ["stepIndex"],
|
||||
where: { run: { sequenceId: "seq-1" }, clickedAt: { not: null } },
|
||||
_count: { _all: true },
|
||||
});
|
||||
expect(data).toMatchObject({
|
||||
totals: {
|
||||
enrolled: 4,
|
||||
completed: 2,
|
||||
active: 1,
|
||||
unsubscribed: 0,
|
||||
failed: 1,
|
||||
},
|
||||
stepStats: [
|
||||
{
|
||||
stepIndex: 0,
|
||||
template: "welcome",
|
||||
subject: "Welcome",
|
||||
scheduled: 3,
|
||||
sent: 2,
|
||||
opened: 2,
|
||||
clicked: 1,
|
||||
bounced: 1,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
},
|
||||
{
|
||||
stepIndex: 1,
|
||||
template: "follow-up",
|
||||
subject: "Checking in",
|
||||
scheduled: 2,
|
||||
sent: 0,
|
||||
opened: 1,
|
||||
clicked: 0,
|
||||
bounced: 0,
|
||||
skipped: 1,
|
||||
failed: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps live status totals and malformed step shapes stable until the stats cron exists", async () => {
|
||||
vi.mocked(dbRead.emailSequence.findFirst).mockResolvedValueOnce({
|
||||
id: "seq-1",
|
||||
name: "Onboarding",
|
||||
triggerEvent: "lead.created",
|
||||
isEnabled: true,
|
||||
stepsJson: [
|
||||
{ template: "welcome" },
|
||||
{ stepIndex: 4, subject: "Missing template" },
|
||||
"not-a-step-object",
|
||||
],
|
||||
} as never);
|
||||
vi.mocked(dbRead.emailSequenceRun.groupBy).mockResolvedValueOnce([
|
||||
{ status: "pending", _count: { _all: 2 } },
|
||||
{ status: "running", _count: { _all: 3 } },
|
||||
{ status: "failed", _count: { _all: 4 } },
|
||||
{ status: "cancelled", _count: { _all: 5 } },
|
||||
{ status: "unsubscribed", _count: { _all: 6 } },
|
||||
] as never);
|
||||
vi.mocked(dbRead.emailSequenceStepDelivery.groupBy).mockReset();
|
||||
vi.mocked(dbRead.emailSequenceStepDelivery.groupBy)
|
||||
.mockResolvedValueOnce([
|
||||
{ stepIndex: 0, status: "queued", _count: { _all: 7 } },
|
||||
{ stepIndex: 4, status: "sent", _count: { _all: 0 } },
|
||||
{ stepIndex: 4, status: "failed", _count: { _all: 2 } },
|
||||
{ stepIndex: 2, status: "skipped", _count: { _all: 1 } },
|
||||
] as never)
|
||||
.mockResolvedValueOnce([
|
||||
{ stepIndex: 4, _count: { _all: 3 } },
|
||||
{ stepIndex: 99, _count: { _all: 9 } },
|
||||
] as never)
|
||||
.mockResolvedValueOnce([{ stepIndex: 4, _count: { _all: 1 } }] as never);
|
||||
|
||||
const data = await callLoader();
|
||||
|
||||
expect(data.totals).toEqual({
|
||||
enrolled: 20,
|
||||
completed: 0,
|
||||
active: 5,
|
||||
unsubscribed: 6,
|
||||
failed: 9,
|
||||
});
|
||||
expect(data.stepStats).toEqual([
|
||||
{
|
||||
stepIndex: 0,
|
||||
template: "welcome",
|
||||
subject: "?",
|
||||
scheduled: 7,
|
||||
sent: 0,
|
||||
opened: 0,
|
||||
clicked: 0,
|
||||
bounced: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
},
|
||||
{
|
||||
stepIndex: 4,
|
||||
template: "?",
|
||||
subject: "Missing template",
|
||||
scheduled: 2,
|
||||
sent: 0,
|
||||
opened: 3,
|
||||
clicked: 1,
|
||||
bounced: 0,
|
||||
skipped: 0,
|
||||
failed: 2,
|
||||
},
|
||||
{
|
||||
stepIndex: 2,
|
||||
template: "?",
|
||||
subject: "?",
|
||||
scheduled: 1,
|
||||
sent: 0,
|
||||
opened: 0,
|
||||
clicked: 0,
|
||||
bounced: 0,
|
||||
skipped: 1,
|
||||
failed: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps delivery-only step indexes visible when sequence JSON was edited after runs started", async () => {
|
||||
vi.mocked(dbRead.emailSequenceStepDelivery.groupBy).mockReset();
|
||||
vi.mocked(dbRead.emailSequenceStepDelivery.groupBy)
|
||||
.mockResolvedValueOnce([
|
||||
{ stepIndex: 0, status: "sent", _count: { _all: 1 } },
|
||||
{ stepIndex: 8, status: "bounced", _count: { _all: 2 } },
|
||||
] as never)
|
||||
.mockResolvedValueOnce([{ stepIndex: 8, _count: { _all: 1 } }] as never)
|
||||
.mockResolvedValueOnce([{ stepIndex: 8, _count: { _all: 1 } }] as never);
|
||||
|
||||
const data = await callLoader();
|
||||
|
||||
expect(data.stepStats).toEqual([
|
||||
{
|
||||
stepIndex: 0,
|
||||
template: "welcome",
|
||||
subject: "Welcome",
|
||||
scheduled: 1,
|
||||
sent: 1,
|
||||
opened: 0,
|
||||
clicked: 0,
|
||||
bounced: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
},
|
||||
{
|
||||
stepIndex: 1,
|
||||
template: "follow-up",
|
||||
subject: "Checking in",
|
||||
scheduled: 0,
|
||||
sent: 0,
|
||||
opened: 0,
|
||||
clicked: 0,
|
||||
bounced: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
},
|
||||
{
|
||||
stepIndex: 8,
|
||||
template: "?",
|
||||
subject: "?",
|
||||
scheduled: 2,
|
||||
sent: 0,
|
||||
opened: 1,
|
||||
clicked: 1,
|
||||
bounced: 2,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns no step stats when persisted stepsJson is not an array", async () => {
|
||||
vi.mocked(dbRead.emailSequence.findFirst).mockResolvedValueOnce({
|
||||
id: "seq-1",
|
||||
name: "Onboarding",
|
||||
triggerEvent: "lead.created",
|
||||
isEnabled: true,
|
||||
stepsJson: { invalid: true },
|
||||
} as never);
|
||||
|
||||
const data = await callLoader();
|
||||
|
||||
expect(data.stepStats).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* Admin email-sequence stats dashboard (Phase 05 #80 follow-up).
|
||||
*
|
||||
* GET /admin/email-sequences/:id/stats — per-step open/click/bounce
|
||||
* counts + sequence-level enrollment + conversion summaries.
|
||||
* Aggregated via dbRead.groupBy on EmailSequenceStepDelivery so the
|
||||
* page is replica-friendly. Numbers are exact — no time-bucketing
|
||||
* (the follow-up statistics-aggregation cron from spec Step 9 is
|
||||
* the home for periodic snapshots).
|
||||
*/
|
||||
import { Link, type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { dbRead } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type StepStat = {
|
||||
stepIndex: number;
|
||||
template: string;
|
||||
subject: string;
|
||||
scheduled: number;
|
||||
sent: number;
|
||||
opened: number;
|
||||
clicked: number;
|
||||
bounced: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
sequence: {
|
||||
id: string;
|
||||
name: string;
|
||||
triggerEvent: string;
|
||||
isEnabled: boolean;
|
||||
};
|
||||
totals: {
|
||||
enrolled: number;
|
||||
completed: number;
|
||||
active: number;
|
||||
unsubscribed: number;
|
||||
failed: number;
|
||||
};
|
||||
stepStats: StepStat[];
|
||||
};
|
||||
|
||||
function safePercent(numerator: number, denominator: number, formatPercent: (value: number, options?: Intl.NumberFormatOptions) => string): string {
|
||||
if (!denominator) return "—";
|
||||
return formatPercent(numerator / denominator, { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
||||
}
|
||||
|
||||
export const loader = async ({ params, request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.marketing.leads.view");
|
||||
const id = String(params["id"] ?? "");
|
||||
const sequence = await dbRead.emailSequence.findFirst({ where: { id } });
|
||||
if (!sequence) throw new Response(null, { status: 404 });
|
||||
|
||||
const runStats = await dbRead.emailSequenceRun.groupBy({
|
||||
by: ["status"],
|
||||
where: { sequenceId: id },
|
||||
_count: { _all: true },
|
||||
});
|
||||
const totals: LoaderData["totals"] = {
|
||||
enrolled: 0,
|
||||
completed: 0,
|
||||
active: 0,
|
||||
unsubscribed: 0,
|
||||
failed: 0,
|
||||
};
|
||||
for (const row of runStats) {
|
||||
totals.enrolled += row._count._all;
|
||||
if (row.status === "completed") totals.completed = row._count._all;
|
||||
else if (row.status === "running" || row.status === "pending") totals.active += row._count._all;
|
||||
else if (row.status === "unsubscribed") totals.unsubscribed = row._count._all;
|
||||
else if (row.status === "failed" || row.status === "cancelled") totals.failed += row._count._all;
|
||||
}
|
||||
|
||||
const deliveryStatusAgg = await dbRead.emailSequenceStepDelivery.groupBy({
|
||||
by: ["stepIndex", "status"],
|
||||
where: { run: { sequenceId: id } },
|
||||
_count: { _all: true },
|
||||
});
|
||||
const openedAgg = await dbRead.emailSequenceStepDelivery.groupBy({
|
||||
by: ["stepIndex"],
|
||||
where: { run: { sequenceId: id }, openedAt: { not: null } },
|
||||
_count: { _all: true },
|
||||
});
|
||||
const clickedAgg = await dbRead.emailSequenceStepDelivery.groupBy({
|
||||
by: ["stepIndex"],
|
||||
where: { run: { sequenceId: id }, clickedAt: { not: null } },
|
||||
_count: { _all: true },
|
||||
});
|
||||
|
||||
const stepsRaw = sequence.stepsJson;
|
||||
const steps: Array<{ stepIndex: number; template: string; subject: string }> = Array.isArray(stepsRaw)
|
||||
? (stepsRaw as Array<Record<string, unknown>>).map((s, idx) => ({
|
||||
stepIndex: typeof s["stepIndex"] === "number" ? (s["stepIndex"] as number) : idx,
|
||||
template: typeof s["template"] === "string" ? (s["template"] as string) : "?",
|
||||
subject: typeof s["subject"] === "string" ? (s["subject"] as string) : "?",
|
||||
}))
|
||||
: [];
|
||||
|
||||
const statusCountsByStep = new Map<number, Record<string, number>>();
|
||||
for (const row of deliveryStatusAgg) {
|
||||
const counts = statusCountsByStep.get(row.stepIndex) ?? {};
|
||||
counts[String(row.status)] = Number(row._count._all ?? 0);
|
||||
statusCountsByStep.set(row.stepIndex, counts);
|
||||
}
|
||||
const openedByStep = new Map(openedAgg.map((row) => [row.stepIndex, Number(row._count._all ?? 0)]));
|
||||
const clickedByStep = new Map(clickedAgg.map((row) => [row.stepIndex, Number(row._count._all ?? 0)]));
|
||||
|
||||
const configuredStepIndexes = new Set(steps.map((step) => step.stepIndex));
|
||||
const deliveryOnlySteps = Array.isArray(stepsRaw)
|
||||
? Array.from(statusCountsByStep.keys())
|
||||
.filter((stepIndex) => !configuredStepIndexes.has(stepIndex))
|
||||
.sort((a, b) => a - b)
|
||||
.map((stepIndex) => ({ stepIndex, template: "?", subject: "?" }))
|
||||
: [];
|
||||
|
||||
const stepStats: StepStat[] = [...steps, ...deliveryOnlySteps].map((s) => {
|
||||
const statusCounts = statusCountsByStep.get(s.stepIndex) ?? {};
|
||||
return {
|
||||
stepIndex: s.stepIndex,
|
||||
template: s.template,
|
||||
subject: s.subject,
|
||||
scheduled: Object.values(statusCounts).reduce((total, count) => total + count, 0),
|
||||
sent: statusCounts.sent ?? 0,
|
||||
opened: openedByStep.get(s.stepIndex) ?? 0,
|
||||
clicked: clickedByStep.get(s.stepIndex) ?? 0,
|
||||
bounced: statusCounts.bounced ?? 0,
|
||||
skipped: statusCounts.skipped ?? 0,
|
||||
failed: statusCounts.failed ?? 0,
|
||||
};
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
sequence: { id: sequence.id, name: sequence.name, triggerEvent: sequence.triggerEvent, isEnabled: sequence.isEnabled },
|
||||
totals,
|
||||
stepStats,
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function EmailSequenceStats() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const formatters = useLocaleFormatters();
|
||||
const editHref = `${adminPath("email-sequences", { mode: "host-aware" })}/${data.sequence.id}`;
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-7xl space-y-5 px-4 py-4 sm:px-6 lg:px-8">
|
||||
<div className="border-border flex flex-col gap-2 border-b pb-5 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-lg font-medium leading-6">{data.sequence.name}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
{i18nT("admin.emailSequences.stats.trigger")}: {data.sequence.triggerEvent}
|
||||
</p>
|
||||
</div>
|
||||
<Link to={editHref} className="hover:bg-muted rounded-md border px-3 py-1.5 text-sm">
|
||||
{i18nT("admin.emailSequences.stats.editSequence")}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<dl className="grid gap-2 sm:grid-cols-3 lg:grid-cols-5">
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow">
|
||||
<dt className="text-muted-foreground text-xs font-medium uppercase">{i18nT("admin.emailSequences.stats.enrolled")}</dt>
|
||||
<dd className="mt-1 text-2xl font-semibold">{formatters.number(data.totals.enrolled)}</dd>
|
||||
</div>
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow">
|
||||
<dt className="text-muted-foreground text-xs font-medium uppercase">{i18nT("admin.emailSequences.col.active")}</dt>
|
||||
<dd className="mt-1 text-2xl font-semibold">{formatters.number(data.totals.active)}</dd>
|
||||
</div>
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow">
|
||||
<dt className="text-muted-foreground text-xs font-medium uppercase">{i18nT("admin.emailSequences.col.completed")}</dt>
|
||||
<dd className="mt-1 text-2xl font-semibold">{formatters.number(data.totals.completed)}</dd>
|
||||
</div>
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow">
|
||||
<dt className="text-muted-foreground text-xs font-medium uppercase">{i18nT("admin.emailSequences.col.unsubscribed")}</dt>
|
||||
<dd className="mt-1 text-2xl font-semibold">{formatters.number(data.totals.unsubscribed)}</dd>
|
||||
</div>
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow">
|
||||
<dt className="text-muted-foreground text-xs font-medium uppercase">{i18nT("admin.emailSequences.stats.failed")}</dt>
|
||||
<dd className="mt-1 text-2xl font-semibold">{formatters.number(data.totals.failed)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/40 text-muted-foreground text-xs uppercase">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left">{i18nT("admin.emailSequences.columns.step")}</th>
|
||||
<th className="px-3 py-2 text-left">{i18nT("admin.emailSequences.columns.template")}</th>
|
||||
<th className="px-3 py-2 text-left">{i18nT("admin.emailSequences.columns.subject")}</th>
|
||||
<th className="px-3 py-2 text-right">{i18nT("admin.emailSequences.columns.scheduled")}</th>
|
||||
<th className="px-3 py-2 text-right">{i18nT("admin.emailSequences.columns.sent")}</th>
|
||||
<th className="px-3 py-2 text-right">{i18nT("admin.emailSequences.columns.opened")}</th>
|
||||
<th className="px-3 py-2 text-right">{i18nT("admin.emailSequences.columns.openRate")}</th>
|
||||
<th className="px-3 py-2 text-right">{i18nT("admin.emailSequences.columns.clicked")}</th>
|
||||
<th className="px-3 py-2 text-right">{i18nT("admin.emailSequences.columns.clickRate")}</th>
|
||||
<th className="px-3 py-2 text-right">{i18nT("admin.emailSequences.columns.bounced")}</th>
|
||||
<th className="px-3 py-2 text-right">{i18nT("admin.emailSequences.columns.skipped")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.stepStats.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={11} className="text-muted-foreground px-3 py-6 text-center">
|
||||
{i18nT("admin.emailSequences.stats.noSteps")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
data.stepStats.map((s) => (
|
||||
<tr key={s.stepIndex} className="border-border border-t">
|
||||
<td className="px-3 py-2">{formatters.number(s.stepIndex)}</td>
|
||||
<td className="text-muted-foreground px-3 py-2 text-xs">{s.template}</td>
|
||||
<td className="px-3 py-2">{s.subject}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(s.scheduled)}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(s.sent)}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(s.opened)}</td>
|
||||
<td className="text-muted-foreground px-3 py-2 text-right text-xs">{safePercent(s.opened, s.sent, formatters.percent)}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(s.clicked)}</td>
|
||||
<td className="text-muted-foreground px-3 py-2 text-right text-xs">{safePercent(s.clicked, s.sent, formatters.percent)}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(s.bounced)}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(s.skipped)}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{i18nT("admin.emailSequences.stats.ratesNote")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { action } from "./$id";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
const dbMocks = vi.hoisted(() => ({
|
||||
sequenceFindFirst: vi.fn(),
|
||||
sequenceUpdate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
emailSequence: {
|
||||
findFirst: dbMocks.sequenceFindFirst,
|
||||
update: dbMocks.sequenceUpdate,
|
||||
},
|
||||
},
|
||||
dbRead: {
|
||||
emailSequence: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => `translated:${key}` })),
|
||||
}));
|
||||
|
||||
vi.mock("i18next", () => ({
|
||||
t: (key: string) => key,
|
||||
}));
|
||||
|
||||
async function callAction(values: Record<string, string>) {
|
||||
const body = new URLSearchParams(values);
|
||||
const response = (await action({
|
||||
request: new Request("https://admin.example.test/email-sequences/seq-1", {
|
||||
method: "POST",
|
||||
body,
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
}),
|
||||
params: { id: "seq-1" },
|
||||
context: {},
|
||||
unstable_pattern: "admin/email-sequences/:id",
|
||||
} as ActionFunctionArgs)) as Response;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
describe("admin email sequence detail action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(db.emailSequence.findFirst).mockResolvedValue({
|
||||
id: "seq-1",
|
||||
isEnabled: false,
|
||||
} as never);
|
||||
vi.mocked(db.emailSequence.update).mockResolvedValue({ id: "seq-1" } as never);
|
||||
});
|
||||
|
||||
it("localizes validation errors for visible edit-form feedback", async () => {
|
||||
const result = await callAction({
|
||||
name: "",
|
||||
triggerEvent: "lead.captured",
|
||||
stepsJson: "[]",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
error: "translated:admin.emailSequences.errors.nameRequired",
|
||||
field: "name",
|
||||
});
|
||||
expect(getTranslations).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(db.emailSequence.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the shared conditions JSON translation key on parse failure", async () => {
|
||||
const result = await callAction({
|
||||
name: "Welcome",
|
||||
triggerEvent: "lead.captured",
|
||||
stepsJson: "[]",
|
||||
conditionsJson: "{",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
error: "translated:admin.emailSequences.errors.conditionsJsonInvalid",
|
||||
field: "conditionsJson",
|
||||
});
|
||||
expect(db.emailSequence.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Admin email-sequence detail + edit view (Phase 05 #80 follow-up).
|
||||
*
|
||||
* GET /admin/email-sequences/:id — render the edit form (name +
|
||||
* trigger + enabled toggle + JSON editors for steps + conditions).
|
||||
* POST /admin/email-sequences/:id — accept the edit form and persist
|
||||
* the updated sequence; supports the special action `toggle` to
|
||||
* flip `isEnabled`.
|
||||
*
|
||||
* No visual rule builder for steps / conditions — operators paste in
|
||||
* the JSON. The shape is validated by `parseSequenceSteps` from the
|
||||
* engine package before save so bad JSON cannot corrupt a run.
|
||||
*/
|
||||
import { Form, Link, type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { db, dbRead } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
sequence: {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
triggerEvent: string;
|
||||
isEnabled: boolean;
|
||||
stepsJson: unknown;
|
||||
conditionsJson: unknown;
|
||||
updatedAt: string;
|
||||
};
|
||||
};
|
||||
|
||||
type ActionResponse = { ok: true } | { ok: false; error: string; field?: string };
|
||||
|
||||
export const loader = async ({ params, request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.marketing.leads.view");
|
||||
const id = String(params["id"] ?? "");
|
||||
const sequence = await dbRead.emailSequence.findFirst({ where: { id } });
|
||||
if (!sequence) throw new Response(null, { status: 404 });
|
||||
return Response.json({
|
||||
sequence: {
|
||||
id: sequence.id,
|
||||
name: sequence.name,
|
||||
description: sequence.description,
|
||||
triggerEvent: sequence.triggerEvent,
|
||||
isEnabled: sequence.isEnabled,
|
||||
stepsJson: sequence.stepsJson,
|
||||
conditionsJson: sequence.conditionsJson,
|
||||
updatedAt: sequence.updatedAt.toISOString(),
|
||||
},
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ params, request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.marketing.leads.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const id = String(params["id"] ?? "");
|
||||
const formData = await request.formData();
|
||||
const intent = String(formData.get("intent") ?? "save");
|
||||
const existing = await db.emailSequence.findFirst({ where: { id } });
|
||||
if (!existing) throw new Response(null, { status: 404 });
|
||||
|
||||
if (intent === "toggle") {
|
||||
await db.emailSequence.update({ where: { id }, data: { isEnabled: !existing.isEnabled } });
|
||||
return redirect(`${adminPath("email-sequences", { mode: "host-aware" })}/${id}`);
|
||||
}
|
||||
|
||||
const name = String(formData.get("name") ?? "").trim();
|
||||
const description = String(formData.get("description") ?? "").trim();
|
||||
const triggerEvent = String(formData.get("triggerEvent") ?? "").trim();
|
||||
const stepsRaw = String(formData.get("stepsJson") ?? "[]");
|
||||
const conditionsRaw = String(formData.get("conditionsJson") ?? "");
|
||||
if (!name) return Response.json({ ok: false, error: t("admin.emailSequences.errors.nameRequired"), field: "name" } satisfies ActionResponse);
|
||||
if (!triggerEvent) {
|
||||
return Response.json({ ok: false, error: t("admin.emailSequences.errors.triggerEventRequired"), field: "triggerEvent" } satisfies ActionResponse);
|
||||
}
|
||||
let stepsJson: unknown;
|
||||
try {
|
||||
stepsJson = JSON.parse(stepsRaw);
|
||||
} catch {
|
||||
return Response.json({ ok: false, error: t("admin.emailSequences.errors.stepsJsonInvalid"), field: "stepsJson" } satisfies ActionResponse);
|
||||
}
|
||||
const { parseSequenceSteps } = await import("@toolctrl/email-sequences");
|
||||
try {
|
||||
parseSequenceSteps(stepsJson);
|
||||
} catch (error) {
|
||||
return Response.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : t("admin.emailSequences.errors.stepsJsonValidationFailed"),
|
||||
field: "stepsJson",
|
||||
} satisfies ActionResponse);
|
||||
}
|
||||
let conditionsJson: unknown = null;
|
||||
if (conditionsRaw.trim().length > 0) {
|
||||
try {
|
||||
conditionsJson = JSON.parse(conditionsRaw);
|
||||
} catch {
|
||||
return Response.json({
|
||||
ok: false,
|
||||
error: t("admin.emailSequences.errors.conditionsJsonInvalid"),
|
||||
field: "conditionsJson",
|
||||
} satisfies ActionResponse);
|
||||
}
|
||||
}
|
||||
await db.emailSequence.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name,
|
||||
description: description || null,
|
||||
triggerEvent,
|
||||
stepsJson: stepsJson as never,
|
||||
conditionsJson: conditionsJson as never,
|
||||
},
|
||||
});
|
||||
return redirect(`${adminPath("email-sequences", { mode: "host-aware" })}/${id}`);
|
||||
};
|
||||
|
||||
export default function EmailSequenceDetail() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const action = useActionData<ActionResponse>();
|
||||
const stepsPretty = JSON.stringify(data.sequence.stepsJson, null, 2);
|
||||
const conditionsPretty = data.sequence.conditionsJson
|
||||
? JSON.stringify(data.sequence.conditionsJson, null, 2)
|
||||
: "";
|
||||
const statsHref = `${adminPath("email-sequences", { mode: "host-aware" })}/${data.sequence.id}/stats`;
|
||||
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8">
|
||||
<div className="border-border flex flex-col gap-2 border-b pb-5 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-lg font-medium leading-6">{data.sequence.name}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
{i18nT("admin.emailSequences.detail.triggerPrefix", { triggerEvent: data.sequence.triggerEvent })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
to={statsHref}
|
||||
className="hover:bg-muted rounded-md border px-3 py-1.5 text-sm"
|
||||
>
|
||||
{i18nT("admin.emailSequences.actions.stats")}
|
||||
</Link>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="intent" value="toggle" />
|
||||
<button
|
||||
type="submit"
|
||||
className={`rounded-md px-3 py-1.5 text-sm ${
|
||||
data.sequence.isEnabled
|
||||
? "bg-rose-100 text-rose-800 hover:bg-rose-200"
|
||||
: "bg-emerald-100 text-emerald-800 hover:bg-emerald-200"
|
||||
}`}
|
||||
>
|
||||
{data.sequence.isEnabled ? i18nT("admin.emailSequences.actions.disable") : i18nT("admin.emailSequences.actions.enable")}
|
||||
</button>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{action && !action.ok ? (
|
||||
<div className="rounded-md border border-rose-300 bg-rose-50 px-3 py-2 text-sm text-rose-800">
|
||||
{action.error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Form method="post" className="space-y-4">
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="name">
|
||||
{i18nT("admin.emailSequences.form.name")}
|
||||
</label>
|
||||
<input
|
||||
id="name"
|
||||
name="name"
|
||||
defaultValue={data.sequence.name}
|
||||
required
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="description">
|
||||
{i18nT("admin.emailSequences.form.description")}
|
||||
</label>
|
||||
<input
|
||||
id="description"
|
||||
name="description"
|
||||
defaultValue={data.sequence.description ?? ""}
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="triggerEvent">
|
||||
{i18nT("admin.emailSequences.form.triggerEvent")}
|
||||
</label>
|
||||
<input
|
||||
id="triggerEvent"
|
||||
name="triggerEvent"
|
||||
defaultValue={data.sequence.triggerEvent}
|
||||
required
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 text-sm"
|
||||
/>
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
{i18nT("admin.emailSequences.form.triggerHint")} <code>lead.captured</code>, <code>tenant.signup</code>, <code>tenant.trial_expiring</code>.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="stepsJson">
|
||||
{i18nT("admin.emailSequences.form.stepsJson")}
|
||||
</label>
|
||||
<textarea
|
||||
id="stepsJson"
|
||||
name="stepsJson"
|
||||
defaultValue={stepsPretty}
|
||||
rows={14}
|
||||
spellCheck={false}
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="conditionsJson">
|
||||
{i18nT("admin.emailSequences.form.conditionsJson")}
|
||||
</label>
|
||||
<textarea
|
||||
id="conditionsJson"
|
||||
name="conditionsJson"
|
||||
defaultValue={conditionsPretty}
|
||||
rows={6}
|
||||
spellCheck={false}
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Link to={adminPath("email-sequences", { mode: "host-aware" })} className="text-primary text-sm hover:underline">
|
||||
{i18nT("admin.emailSequences.actions.backToList")}
|
||||
</Link>
|
||||
<button type="submit" className="bg-primary text-primary-foreground rounded-md px-3 py-1.5 text-sm">
|
||||
{i18nT("admin.emailSequences.actions.save")}
|
||||
</button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(routeDir, "../../../../../..");
|
||||
|
||||
function readRoute(fileName: string) {
|
||||
return fs.readFileSync(path.join(routeDir, fileName), "utf8");
|
||||
}
|
||||
|
||||
function readTranslations(locale: "en" | "de") {
|
||||
const filePath = path.join(repoRoot, "apps/web/public/locales", locale, "translations.json");
|
||||
return JSON.parse(fs.readFileSync(filePath, "utf8")) as {
|
||||
admin: {
|
||||
emailSequences: {
|
||||
actions: Record<string, string>;
|
||||
col: Record<string, string>;
|
||||
columns: Record<string, string>;
|
||||
subtitle: string;
|
||||
detail: Record<string, string>;
|
||||
errors: Record<string, string>;
|
||||
form: Record<string, string>;
|
||||
placeholders: Record<string, string>;
|
||||
stats: Record<string, string>;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
describe("admin email sequence route i18n", () => {
|
||||
it("uses namespaced email sequence keys for create and edit form chrome", () => {
|
||||
const source = `${readRoute("new.tsx")}\n${readRoute("$id.tsx")}`;
|
||||
|
||||
for (const key of [
|
||||
"admin.emailSequences.actions.backToList",
|
||||
"admin.emailSequences.actions.createDisabled",
|
||||
"admin.emailSequences.actions.disable",
|
||||
"admin.emailSequences.actions.enable",
|
||||
"admin.emailSequences.actions.save",
|
||||
"admin.emailSequences.actions.stats",
|
||||
"admin.emailSequences.detail.triggerPrefix",
|
||||
"admin.emailSequences.form.conditionsJson",
|
||||
"admin.emailSequences.form.description",
|
||||
"admin.emailSequences.form.instructions",
|
||||
"admin.emailSequences.form.name",
|
||||
"admin.emailSequences.form.newTitle",
|
||||
"admin.emailSequences.form.stepsJson",
|
||||
"admin.emailSequences.form.triggerEvent",
|
||||
"admin.emailSequences.form.triggerHint",
|
||||
"admin.emailSequences.placeholders.triggerEvent",
|
||||
]) {
|
||||
expect(source).toContain(key);
|
||||
}
|
||||
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain(">Name<");
|
||||
expect(source).not.toContain(">Description<");
|
||||
expect(source).not.toContain(">Steps (JSON)<");
|
||||
expect(source).not.toContain(">Sequence-level conditions (optional JSON)<");
|
||||
expect(source).not.toContain('placeholder="lead.captured"');
|
||||
expect(source).not.toContain(">Create (disabled until enabled)<");
|
||||
expect(source).not.toContain(">Save<");
|
||||
expect(source).not.toContain(">Stats<");
|
||||
expect(source).not.toContain('"Disable"');
|
||||
expect(source).not.toContain('"Enable"');
|
||||
expect(source).not.toContain("trigger: {data.sequence.triggerEvent}");
|
||||
});
|
||||
|
||||
it("keeps English and German admin email sequence form keys in parity", () => {
|
||||
const en = readTranslations("en").admin.emailSequences;
|
||||
const de = readTranslations("de").admin.emailSequences;
|
||||
|
||||
expect(Object.keys(de.actions).sort()).toEqual(Object.keys(en.actions).sort());
|
||||
expect(Object.keys(de.col).sort()).toEqual(Object.keys(en.col).sort());
|
||||
expect(Object.keys(de.columns).sort()).toEqual(Object.keys(en.columns).sort());
|
||||
expect(Object.keys(de.detail).sort()).toEqual(Object.keys(en.detail).sort());
|
||||
expect(Object.keys(de.errors).sort()).toEqual(Object.keys(en.errors).sort());
|
||||
expect(Object.keys(de.form).sort()).toEqual(Object.keys(en.form).sort());
|
||||
expect(Object.keys(de.placeholders).sort()).toEqual(Object.keys(en.placeholders).sort());
|
||||
expect(Object.keys(de.stats).sort()).toEqual(Object.keys(en.stats).sort());
|
||||
});
|
||||
|
||||
it("keeps trigger event terminology coherent across email sequence locales", () => {
|
||||
const en = readTranslations("en").admin.emailSequences;
|
||||
const de = readTranslations("de").admin.emailSequences;
|
||||
|
||||
expect(en.detail.triggerPrefix).toBe("Trigger: {{triggerEvent}}");
|
||||
expect(de.subtitle).toContain("Trigger-Ereignisse");
|
||||
expect(de.detail.triggerPrefix).toBe("Trigger-Ereignis: {{triggerEvent}}");
|
||||
expect(de.form.triggerEvent).toBe("Trigger-Ereignis");
|
||||
expect(de.form.instructions).toContain("Sequenzmodul");
|
||||
expect(de.form.instructions).toContain("Trigger-Lauf");
|
||||
expect(de.form.instructions).not.toContain("Trigger-Handler");
|
||||
expect(de.form.instructions).not.toContain("Engine");
|
||||
expect(de.stats.trigger).toBe("Trigger-Ereignis");
|
||||
expect(de.stats.enrolled).toBe("Aufgenommen");
|
||||
expect(de.stats.ratesNote).toContain("automatische Linkprüfungen");
|
||||
expect(de.stats.ratesNote).not.toContain("Ad-hoc-Klickauflösungen");
|
||||
});
|
||||
|
||||
it("uses locale formatters for visible index and stats numbers", () => {
|
||||
const source = `${readRoute("index.tsx")}\n${readRoute("$id.stats.tsx")}`;
|
||||
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formattedCount: formatters.number(data.total)");
|
||||
expect(source).toContain("formatters.dateTime(row.updatedAt");
|
||||
expect(source).toContain("safePercent(s.opened, s.sent, formatters.percent)");
|
||||
expect(source).not.toContain(".toFixed(1)}%");
|
||||
expect(source).not.toContain(".toISOString().slice");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loader } from "./index";
|
||||
import { dbRead } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
const dbMocks = vi.hoisted(() => ({
|
||||
sequenceFindMany: vi.fn(),
|
||||
runGroupBy: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
dbRead: {
|
||||
emailSequence: {
|
||||
findMany: dbMocks.sequenceFindMany,
|
||||
},
|
||||
emailSequenceRun: {
|
||||
groupBy: dbMocks.runGroupBy,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
async function callLoader() {
|
||||
const response = (await loader({
|
||||
request: new Request("https://admin.example.test/email-sequences"),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/email-sequences",
|
||||
} as LoaderFunctionArgs)) as Response;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
describe("admin email sequence index loader", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(dbRead.emailSequence.findMany).mockResolvedValue([
|
||||
{
|
||||
id: "seq-1",
|
||||
name: "Welcome",
|
||||
description: "Intro sequence",
|
||||
triggerEvent: "lead.created",
|
||||
isEnabled: true,
|
||||
stepsJson: [{ template: "welcome" }, { template: "follow-up" }],
|
||||
updatedAt: new Date("2026-05-01T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "seq-2",
|
||||
name: "Trial",
|
||||
description: null,
|
||||
triggerEvent: "tenant.trial_expiring",
|
||||
isEnabled: false,
|
||||
stepsJson: [],
|
||||
updatedAt: new Date("2026-05-02T00:00:00.000Z"),
|
||||
},
|
||||
] as never);
|
||||
vi.mocked(dbRead.emailSequenceRun.groupBy).mockResolvedValue([
|
||||
{ sequenceId: "seq-1", status: "running", _count: { _all: 2 } },
|
||||
{ sequenceId: "seq-1", status: "pending", _count: { _all: 1 } },
|
||||
{ sequenceId: "seq-1", status: "completed", _count: { _all: 4 } },
|
||||
{ sequenceId: "seq-1", status: "cancelled", _count: { _all: 1 } },
|
||||
] as never);
|
||||
});
|
||||
|
||||
it("scopes run aggregation to the listed sequence ids", async () => {
|
||||
const data = await callLoader();
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.marketing.leads.view");
|
||||
expect(dbRead.emailSequenceRun.groupBy).toHaveBeenCalledWith({
|
||||
by: ["sequenceId", "status"],
|
||||
where: { sequenceId: { in: ["seq-1", "seq-2"] } },
|
||||
_count: { _all: true },
|
||||
});
|
||||
expect(data).toMatchObject({
|
||||
total: 2,
|
||||
items: [
|
||||
{
|
||||
id: "seq-1",
|
||||
stepCount: 2,
|
||||
stats: { active: 3, completed: 4, unsubscribed: 0, failed: 1 },
|
||||
},
|
||||
{
|
||||
id: "seq-2",
|
||||
stepCount: 0,
|
||||
stats: { active: 0, completed: 0, unsubscribed: 0, failed: 0 },
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("skips run aggregation when no sequences are listed", async () => {
|
||||
vi.mocked(dbRead.emailSequence.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
const data = await callLoader();
|
||||
|
||||
expect(dbRead.emailSequenceRun.groupBy).not.toHaveBeenCalled();
|
||||
expect(data).toEqual({ items: [], total: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Admin email-sequence list view (Phase 05 #80 follow-up).
|
||||
*
|
||||
* GET /admin/email-sequences — DataTable with name, trigger event,
|
||||
* enabled badge, step-count and recent-run statistics (active,
|
||||
* completed, unsubscribed counts) per sequence. Backed by a single
|
||||
* groupBy query on EmailSequenceRun for performance — see the
|
||||
* read-replica usage via `dbRead` (#41).
|
||||
*/
|
||||
import { Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { dbRead } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type SequenceRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
triggerEvent: string;
|
||||
isEnabled: boolean;
|
||||
stepCount: number;
|
||||
updatedAt: string;
|
||||
stats: {
|
||||
active: number;
|
||||
completed: number;
|
||||
unsubscribed: number;
|
||||
failed: number;
|
||||
};
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
items: SequenceRow[];
|
||||
total: number;
|
||||
};
|
||||
|
||||
function countSteps(stepsJson: unknown): number {
|
||||
return Array.isArray(stepsJson) ? stepsJson.length : 0;
|
||||
}
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.marketing.leads.view");
|
||||
const sequences = await dbRead.emailSequence.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
triggerEvent: true,
|
||||
isEnabled: true,
|
||||
stepsJson: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
const sequenceIds = sequences.map((sequence) => sequence.id);
|
||||
const runStats =
|
||||
sequenceIds.length > 0
|
||||
? await dbRead.emailSequenceRun.groupBy({
|
||||
by: ["sequenceId", "status"],
|
||||
where: { sequenceId: { in: sequenceIds } },
|
||||
_count: { _all: true },
|
||||
})
|
||||
: [];
|
||||
const statsMap = new Map<string, SequenceRow["stats"]>();
|
||||
for (const row of runStats) {
|
||||
const bucket = statsMap.get(row.sequenceId) ?? { active: 0, completed: 0, unsubscribed: 0, failed: 0 };
|
||||
if (row.status === "running" || row.status === "pending") bucket.active += row._count._all;
|
||||
else if (row.status === "completed") bucket.completed = row._count._all;
|
||||
else if (row.status === "unsubscribed") bucket.unsubscribed = row._count._all;
|
||||
else if (row.status === "failed" || row.status === "cancelled") bucket.failed += row._count._all;
|
||||
statsMap.set(row.sequenceId, bucket);
|
||||
}
|
||||
const items: SequenceRow[] = sequences.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
triggerEvent: s.triggerEvent,
|
||||
isEnabled: s.isEnabled,
|
||||
stepCount: countSteps(s.stepsJson),
|
||||
updatedAt: s.updatedAt.toISOString(),
|
||||
stats: statsMap.get(s.id) ?? { active: 0, completed: 0, unsubscribed: 0, failed: 0 },
|
||||
}));
|
||||
return Response.json({ items, total: items.length } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export default function EmailSequencesIndex() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-7xl space-y-5 px-4 py-4 sm:px-6 lg:px-8">
|
||||
<div className="border-border flex flex-col gap-2 border-b pb-5 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-lg font-medium leading-6">{t("admin.emailSequences.title")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("admin.emailSequences.subtitle")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("admin.emailSequences.totalSequences", { count: data.total, formattedCount: formatters.number(data.total) })}
|
||||
</div>
|
||||
<Link
|
||||
to={`${adminPath("email-sequences", { mode: "host-aware" })}/new`}
|
||||
className="bg-primary text-primary-foreground rounded-md px-3 py-1.5 text-sm"
|
||||
>
|
||||
{t("admin.emailSequences.createNew")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/40 text-muted-foreground text-xs uppercase">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left">{t("admin.emailSequences.col.name")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.emailSequences.col.trigger")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.emailSequences.col.status")}</th>
|
||||
<th className="px-3 py-2 text-right">{t("admin.emailSequences.col.steps")}</th>
|
||||
<th className="px-3 py-2 text-right">{t("admin.emailSequences.col.active")}</th>
|
||||
<th className="px-3 py-2 text-right">{t("admin.emailSequences.col.completed")}</th>
|
||||
<th className="px-3 py-2 text-right">{t("admin.emailSequences.col.unsubscribed")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.emailSequences.col.updated")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.items.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="text-muted-foreground px-3 py-6 text-center">
|
||||
{t("admin.emailSequences.empty")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
data.items.map((row) => (
|
||||
<tr key={row.id} className="border-border hover:bg-muted/30 border-t">
|
||||
<td className="px-3 py-2">
|
||||
<Link to={`${adminPath("email-sequences", { mode: "host-aware" })}/${row.id}`} className="text-primary hover:underline">
|
||||
{row.name}
|
||||
</Link>
|
||||
{row.description ? <p className="text-muted-foreground mt-0.5 truncate text-xs">{row.description}</p> : null}
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2 text-xs">{row.triggerEvent}</td>
|
||||
<td className="px-3 py-2">
|
||||
<span
|
||||
className={`rounded px-1.5 py-0.5 text-xs ${
|
||||
row.isEnabled ? "bg-emerald-100 text-emerald-800" : "bg-gray-100 text-gray-700"
|
||||
}`}
|
||||
>
|
||||
{row.isEnabled ? t("shared.enabled") : t("shared.disabled")}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(row.stepCount)}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(row.stats.active)}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(row.stats.completed)}</td>
|
||||
<td className="px-3 py-2 text-right">{formatters.number(row.stats.unsubscribed)}</td>
|
||||
<td className="text-muted-foreground px-3 py-2 text-xs">
|
||||
{formatters.dateTime(row.updatedAt, { dateStyle: "medium", timeStyle: "short" })}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* Admin email-sequence create form (Phase 05 #80 follow-up).
|
||||
*
|
||||
* POST /admin/email-sequences/new — create a sequence and redirect to
|
||||
* its detail page. Validates the steps JSON via the engine package
|
||||
* before inserting so the row is always renderable by the trigger
|
||||
* handler.
|
||||
*/
|
||||
import { Form, Link, redirect, useActionData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type ActionResponse = { ok: true } | { ok: false; error: string };
|
||||
|
||||
const DEFAULT_STEPS = JSON.stringify(
|
||||
[
|
||||
{
|
||||
stepIndex: 0,
|
||||
delayHours: 0,
|
||||
template: "welcome",
|
||||
subject: i18nT("admin.emailSequences.defaults.welcomeSubject"),
|
||||
variables: { productName: "Toolctrl" },
|
||||
},
|
||||
],
|
||||
null,
|
||||
2
|
||||
);
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.marketing.leads.view");
|
||||
return Response.json({});
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.marketing.leads.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const formData = await request.formData();
|
||||
const name = String(formData.get("name") ?? "").trim();
|
||||
const description = String(formData.get("description") ?? "").trim();
|
||||
const triggerEvent = String(formData.get("triggerEvent") ?? "").trim();
|
||||
const stepsRaw = String(formData.get("stepsJson") ?? "[]");
|
||||
const conditionsRaw = String(formData.get("conditionsJson") ?? "");
|
||||
if (!name) return Response.json({ ok: false, error: t("admin.emailSequences.errors.nameRequired") } satisfies ActionResponse);
|
||||
if (!triggerEvent) return Response.json({ ok: false, error: t("admin.emailSequences.errors.triggerEventRequired") } satisfies ActionResponse);
|
||||
let stepsJson: unknown;
|
||||
try {
|
||||
stepsJson = JSON.parse(stepsRaw);
|
||||
} catch {
|
||||
return Response.json({ ok: false, error: t("admin.emailSequences.errors.stepsJsonInvalid") } satisfies ActionResponse);
|
||||
}
|
||||
const { parseSequenceSteps } = await import("@toolctrl/email-sequences");
|
||||
try {
|
||||
parseSequenceSteps(stepsJson);
|
||||
} catch (error) {
|
||||
return Response.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : t("admin.emailSequences.errors.stepsJsonValidationFailed"),
|
||||
} satisfies ActionResponse);
|
||||
}
|
||||
let conditionsJson: unknown = null;
|
||||
if (conditionsRaw.trim().length > 0) {
|
||||
try {
|
||||
conditionsJson = JSON.parse(conditionsRaw);
|
||||
} catch {
|
||||
return Response.json({ ok: false, error: t("admin.emailSequences.errors.conditionsJsonInvalid") } satisfies ActionResponse);
|
||||
}
|
||||
}
|
||||
const created = await db.emailSequence.create({
|
||||
data: {
|
||||
name,
|
||||
description: description || null,
|
||||
triggerEvent,
|
||||
stepsJson: stepsJson as never,
|
||||
conditionsJson: conditionsJson as never,
|
||||
isEnabled: false,
|
||||
},
|
||||
});
|
||||
return redirect(`${adminPath("email-sequences", { mode: "host-aware" })}/${created.id}`);
|
||||
};
|
||||
|
||||
export default function EmailSequenceNew() {
|
||||
const action = useActionData<ActionResponse>();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h1 className="text-lg leading-6 font-medium">{i18nT("admin.emailSequences.form.newTitle")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">
|
||||
{i18nT("admin.emailSequences.form.instructions")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{action && !action.ok ? <div className="rounded-md border border-rose-300 bg-rose-50 px-3 py-2 text-sm text-rose-800">{action.error}</div> : null}
|
||||
|
||||
<Form method="post" className="space-y-4">
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="name">
|
||||
{i18nT("admin.emailSequences.form.name")}
|
||||
</label>
|
||||
<input id="name" name="name" required className="border-border w-full rounded-md border px-3 py-1.5 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="description">
|
||||
{i18nT("admin.emailSequences.form.description")}
|
||||
</label>
|
||||
<input id="description" name="description" className="border-border w-full rounded-md border px-3 py-1.5 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="triggerEvent">
|
||||
{i18nT("admin.emailSequences.form.triggerEvent")}
|
||||
</label>
|
||||
<input
|
||||
id="triggerEvent"
|
||||
name="triggerEvent"
|
||||
required
|
||||
placeholder={i18nT("admin.emailSequences.placeholders.triggerEvent")}
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="stepsJson">
|
||||
{i18nT("admin.emailSequences.form.stepsJson")}
|
||||
</label>
|
||||
<textarea
|
||||
id="stepsJson"
|
||||
name="stepsJson"
|
||||
defaultValue={DEFAULT_STEPS}
|
||||
rows={14}
|
||||
spellCheck={false}
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-foreground mb-1 block text-sm font-medium" htmlFor="conditionsJson">
|
||||
{i18nT("admin.emailSequences.form.conditionsJson")}
|
||||
</label>
|
||||
<textarea
|
||||
id="conditionsJson"
|
||||
name="conditionsJson"
|
||||
rows={6}
|
||||
spellCheck={false}
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Link to={adminPath("email-sequences", { mode: "host-aware" })} className="text-primary text-sm hover:underline">
|
||||
{i18nT("admin.emailSequences.actions.backToList")}
|
||||
</Link>
|
||||
<button type="submit" className="bg-primary text-primary-foreground rounded-md px-3 py-1.5 text-sm">
|
||||
{i18nT("admin.emailSequences.actions.createDisabled")}
|
||||
</button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user