Skip to content

Open source CapCut alternative.

TypeScript

feat(site): fold the outbox's rows under their campaign

David Le2f93b70c2688
diff --git a/site/src/app/su/jobs/email/page.tsx b/site/src/app/su/jobs/email/page.tsx
index fc0e3254..729d7309 100644
--- a/site/src/app/su/jobs/email/page.tsx
+++ b/site/src/app/su/jobs/email/page.tsx
@@ -1,8 +1,17 @@
"use client";
+import { ChevronRight } from "lucide-react";
+import { useState } from "react";
+
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { useEmailOutbox, useOutboxAction, type OutboxItem, type OutboxOverview } from "@/queries/emailOutbox";
+import {
+ useEmailOutbox,
+ useOutboxAction,
+ type OutboxCampaign,
+ type OutboxItem,
+ type OutboxOverview,
+} from "@/queries/emailOutbox";
function formatWhen(iso: string): string {
const then = new Date(iso);
@@ -153,23 +162,104 @@ function ItemRow({ item, onRetry, retrying }: { item: OutboxItem; onRetry: () =>
);
}
-function ItemsSection({ title, items, empty }: { title: string; items: OutboxItem[]; empty: string }) {
+function ItemList({ items }: { items: OutboxItem[] }) {
const action = useOutboxAction();
+ return (
+ <ul className="space-y-2">
+ {items.map((item) => (
+ <ItemRow
+ key={item.id}
+ item={item}
+ onRetry={() => action.mutate({ action: "retry", id: item.id })}
+ retrying={action.isPending}
+ />
+ ))}
+ </ul>
+ );
+}
+
+// A campaign's rows fold under one line carrying the whole count from the
+// server; the rows beneath are the section's page of it.
+function CampaignGroup({ campaign, count, items }: { campaign: OutboxCampaign; count: number; items: OutboxItem[] }) {
+ const [open, setOpen] = useState(false);
+ const dot = stateDot[items[0].state] ?? stateDot.queued;
+ return (
+ <li className="space-y-2">
+ <button
+ type="button"
+ className="flex w-full items-start gap-2.5 text-left text-sm"
+ aria-expanded={open}
+ onClick={() => setOpen((v) => !v)}
+ >
+ <span className={cn("mt-1.5 size-2 shrink-0 rounded-full", dot)} />
+ <span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2">
+ <span className="font-medium">promotion</span>
+ <span className="text-muted-foreground">{campaign.name}</span>
+ <span className="tabular-nums">{count}</span>
+ {items.length < count ? <span className="text-muted-foreground">showing {items.length}</span> : null}
+ </span>
+ <ChevronRight className={cn("mt-0.5 size-4 shrink-0 transition-transform duration-200", open && "rotate-90")} />
+ </button>
+ {open ? (
+ <div className="border-l pl-4">
+ <ItemList items={items} />
+ </div>
+ ) : null}
+ </li>
+ );
+}
+
+function ItemsSection({
+ title,
+ items,
+ empty,
+ campaigns,
+ countOf,
+}: {
+ title: string;
+ items: OutboxItem[];
+ empty: string;
+ campaigns: OutboxCampaign[];
+ countOf: (campaign: OutboxCampaign) => number;
+}) {
+ // Rows keep their order; a campaign's rows collapse into one entry at the
+ // place its first row sits.
+ const entries: ({ kind: "item"; item: OutboxItem } | { kind: "campaign"; campaign: OutboxCampaign; items: OutboxItem[] })[] =
+ [];
+ const grouped = new Map<string, OutboxItem[]>();
+ for (const item of items) {
+ const campaign = item.promotionId ? campaigns.find((c) => c.id === item.promotionId) : undefined;
+ if (!campaign) {
+ entries.push({ kind: "item", item });
+ continue;
+ }
+ const rows = grouped.get(campaign.id);
+ if (rows) rows.push(item);
+ else {
+ const fresh = [item];
+ grouped.set(campaign.id, fresh);
+ entries.push({ kind: "campaign", campaign, items: fresh });
+ }
+ }
return (
<section className="space-y-2">
<h2 className="text-sm font-medium">{title}</h2>
- {items.length === 0 ? (
+ {entries.length === 0 ? (
<p className="text-sm text-muted-foreground">{empty}</p>
) : (
<ul className="space-y-2">
- {items.map((item) => (
- <ItemRow
- key={item.id}
- item={item}
- onRetry={() => action.mutate({ action: "retry", id: item.id })}
- retrying={action.isPending}
- />
- ))}
+ {entries.map((entry) =>
+ entry.kind === "item" ? (
+ <ItemList key={entry.item.id} items={[entry.item]} />
+ ) : (
+ <CampaignGroup
+ key={entry.campaign.id}
+ campaign={entry.campaign}
+ count={countOf(entry.campaign)}
+ items={entry.items}
+ />
+ ),
+ )}
</ul>
)}
</section>
@@ -188,15 +278,33 @@ export default function SuEmailPage() {
</p>
);
}
- const { items } = outbox.data;
+ const { items, campaigns } = outbox.data;
const byState = (states: string[]) => items.filter((i) => states.includes(i.state));
return (
<div className="max-w-3xl space-y-8 pb-9">
<QuotaSection quota={outbox.data.quota} />
<KindsSection kinds={outbox.data.kinds} />
- <ItemsSection title="Waiting" items={byState(["queued", "sending"])} empty="Nothing waiting." />
- <ItemsSection title="Failed" items={byState(["failed"])} empty="Nothing failed." />
- <ItemsSection title="Recently sent" items={byState(["sent", "skipped"])} empty="Nothing sent yet." />
+ <ItemsSection
+ title="Waiting"
+ items={byState(["queued", "sending"])}
+ empty="Nothing waiting."
+ campaigns={campaigns}
+ countOf={(c) => c.queued}
+ />
+ <ItemsSection
+ title="Failed"
+ items={byState(["failed"])}
+ empty="Nothing failed."
+ campaigns={campaigns}
+ countOf={(c) => c.failed}
+ />
+ <ItemsSection
+ title="Recently sent"
+ items={byState(["sent", "skipped"])}
+ empty="Nothing sent yet."
+ campaigns={campaigns}
+ countOf={(c) => c.sent + c.skipped}
+ />
</div>
);
}
diff --git a/site/src/lib/email/outbox.ts b/site/src/lib/email/outbox.ts
index f9ca1bf3..b9719de3 100644
--- a/site/src/lib/email/outbox.ts
+++ b/site/src/lib/email/outbox.ts
@@ -277,6 +277,7 @@ export type OutboxItem = {
priority: number;
rank: number;
email: string | null;
+ promotionId: string | null;
promotionName: string | null;
attempts: number;
error: string | null;
@@ -287,9 +288,21 @@ export type OutboxItem = {
createdAt: string;
};
+// One promotion's standing across every row it ever queued, so a campaign
+// reads as one line with whole counts however many rows the lists show.
+export type OutboxCampaign = {
+ id: string;
+ name: string;
+ queued: number;
+ sent: number;
+ skipped: number;
+ failed: number;
+};
+
export type OutboxOverview = {
quota: DailyEmailQuotaStatus;
kinds: OutboxKindRow[];
+ campaigns: OutboxCampaign[];
// What is waiting, then what failed, then what went most recently.
items: OutboxItem[];
// A drainer is running or due now; one held back by a quota wait is not.
@@ -302,12 +315,13 @@ const ITEMS = 60;
* rows worth a look. */
export async function outboxOverview(now = new Date()): Promise<OutboxOverview> {
const dayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
- const [quota, priorities, queued, sentToday, failed, waiting, broken, recent, drain] = await Promise.all([
+ const [quota, priorities, queued, sentToday, failed, byCampaign, waiting, broken, recent, drain] = await Promise.all([
dailyEmailQuotaStatus(now),
getGlobalSetting("emailPriorities"),
prisma.emailSend.groupBy({ _count: true, by: ["kind"], where: { state: { in: ["queued", "sending"] } } }),
prisma.emailSend.groupBy({ _count: true, by: ["kind"], where: { sentAt: { gte: dayStart }, state: "sent" } }),
prisma.emailSend.groupBy({ _count: true, by: ["kind"], where: { state: "failed" } }),
+ prisma.emailSend.groupBy({ _count: true, by: ["promotionId", "state"], where: { promotionId: { not: null } } }),
prisma.emailSend.findMany({
include: { promotion: { select: { name: true } }, user: { select: { email: true } } },
orderBy: [{ priority: "desc" }, { rank: "asc" }, { createdAt: "asc" }],
@@ -344,6 +358,20 @@ export async function outboxOverview(now = new Date()): Promise<OutboxOverview>
sentToday: countOf(sentToday, kind),
failed: countOf(failed, kind),
}));
+ const campaignIds = [...new Set(byCampaign.map((g) => g.promotionId).filter((id): id is string => id !== null))];
+ const names = await prisma.promotion.findMany({ select: { id: true, name: true }, where: { id: { in: campaignIds } } });
+ const campaigns = names.map((p) => {
+ const count = (states: string[]) =>
+ byCampaign.filter((g) => g.promotionId === p.id && states.includes(g.state)).reduce((n, g) => n + g._count, 0);
+ return {
+ id: p.id,
+ name: p.name,
+ queued: count(["queued", "sending"]),
+ sent: count(["sent"]),
+ skipped: count(["skipped"]),
+ failed: count(["failed"]),
+ };
+ });
const items = [...waiting, ...broken, ...recent].map((row) => ({
id: row.id,
kind: row.kind,
@@ -351,6 +379,7 @@ export async function outboxOverview(now = new Date()): Promise<OutboxOverview>
priority: row.priority,
rank: row.rank,
email: row.user?.email ?? null,
+ promotionId: row.promotionId,
promotionName: row.promotion?.name ?? null,
attempts: row.attempts,
error: row.error,
@@ -359,7 +388,7 @@ export async function outboxOverview(now = new Date()): Promise<OutboxOverview>
sentAt: row.sentAt?.toISOString() ?? null,
createdAt: row.createdAt.toISOString(),
}));
- return { quota, kinds, items, drainPending: drain !== null };
+ return { quota, kinds, campaigns, items, drainPending: drain !== null };
}
/** Puts a failed row back in the queue with a clean slate and sends for a
diff --git a/site/src/queries/emailOutbox.ts b/site/src/queries/emailOutbox.ts
index c131f336..a2c9488f 100644
--- a/site/src/queries/emailOutbox.ts
+++ b/site/src/queries/emailOutbox.ts
@@ -5,7 +5,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { OutboxOverview } from "@/lib/email/outbox";
import { apiFetch } from "@/queries/apiClient";
-export type { OutboxItem, OutboxKindRow, OutboxOverview } from "@/lib/email/outbox";
+export type { OutboxCampaign, OutboxItem, OutboxKindRow, OutboxOverview } from "@/lib/email/outbox";
export const emailOutboxQueryKey = ["su", "email", "outbox"] as const;