237 lines
11 KiB
TypeScript
237 lines
11 KiB
TypeScript
/**
|
|
* 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 { requestScopedT as i18nT } from "~/locale/request-scoped-t";
|
|
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>
|
|
);
|
|
}
|