Open source CapCut alternative.
TypeScript
feat(site): show the email outbox under su jobs
David Le96b52e2da7bb
diff --git a/site/src/app/api/su/email/route.ts b/site/src/app/api/su/email/route.tsnew file mode 100644index 00000000..b8051b44--- /dev/null+++ b/site/src/app/api/su/email/route.ts@@ -0,0 +1,29 @@+import { NextResponse } from "next/server";+import { z } from "zod";++import { invalidResponse } from "@/lib/config/experimentList";+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";+import { outboxOverview, retryEmail, scheduleDrain } from "@/lib/email/outbox";++// Without a queue configured (local dev) a drain runs inline before the+// response; give it room.+export const maxDuration = 300;++export const GET = withSuperUser(async () => NextResponse.json(await outboxOverview()));++const actionSchema = z.union([+ z.object({ action: z.literal("drain") }).strict(),+ z.object({ action: z.literal("retry"), id: z.string().min(1) }).strict(),+]);++// Drain now, or put one failed row back in the queue.+export const POST = withSuperUser(async (request) => {+ const parsed = actionSchema.safeParse(await request.json());+ if (!parsed.success) return invalidResponse(parsed.error.issues);+ if (parsed.data.action === "drain") {+ await scheduleDrain(0);+ } else if (!(await retryEmail(parsed.data.id))) {+ return notFoundResponse();+ }+ return NextResponse.json(await outboxOverview());+});diff --git a/site/src/app/su/jobs/email/DrainNowButton.tsx b/site/src/app/su/jobs/email/DrainNowButton.tsxnew file mode 100644index 00000000..805db16c--- /dev/null+++ b/site/src/app/su/jobs/email/DrainNowButton.tsx@@ -0,0 +1,23 @@+"use client";++import { Button } from "@/components/ui/button";+import { useEmailOutbox, useOutboxAction } from "@/queries/emailOutbox";++export function DrainNowButton() {+ const outbox = useEmailOutbox();+ const drain = useOutboxAction();+ const pending = outbox.data?.drainPending ?? false;+ return (+ <div className="flex items-center gap-3">+ {drain.isError ? <span className="text-sm text-destructive">Drain failed.</span> : null}+ <Button+ disabled={drain.isPending || pending}+ onClick={() => drain.mutate({ action: "drain" })}+ size="sm"+ variant="outline"+ >+ {pending ? "Draining…" : "Drain now"}+ </Button>+ </div>+ );+}diff --git a/site/src/app/su/jobs/email/page.tsx b/site/src/app/su/jobs/email/page.tsxnew file mode 100644index 00000000..fc0e3254--- /dev/null+++ b/site/src/app/su/jobs/email/page.tsx@@ -0,0 +1,202 @@+"use client";++import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { useEmailOutbox, useOutboxAction, type OutboxItem, type OutboxOverview } from "@/queries/emailOutbox";++function formatWhen(iso: string): string {+ const then = new Date(iso);+ const mins = Math.round((then.getTime() - Date.now()) / 60000);+ const abs = Math.abs(mins);+ if (abs < 1) return "now";+ const span =+ abs < 60+ ? `${abs}m`+ : abs < 60 * 24+ ? `${Math.floor(abs / 60)}h`+ : then.toLocaleDateString(undefined, { month: "short", day: "numeric" });+ return mins < 0 ? `${span} ago` : `in ${span}`;+}++function formatDuration(seconds: number): string {+ const h = Math.floor(seconds / 3600);+ const m = Math.floor((seconds % 3600) / 60);+ return h > 0 ? `${h}h ${m}m` : `${m}m`;+}++const stateDot: Record<string, string> = {+ queued: "bg-muted-foreground/40",+ sending: "bg-blue-500 animate-pulse",+ sent: "bg-emerald-500",+ skipped: "bg-muted-foreground/40",+ failed: "bg-destructive",+};++// The day's quota as three stop lines on one counter. Each bar is how far+// that class of send may go today; the fill is what has gone out so far.+function QuotaSection({ quota }: { quota: OutboxOverview["quota"] }) {+ const { forecast } = quota;+ const classes = [+ {+ label: "Manual",+ ceiling: quota.ceilings.manual,+ note:+ quota.manualReserve > 0+ ? `${quota.manualReserve} held below this for hand-sent mail while work hours remain`+ : "work hours over; the hand-sent reserve is released",+ },+ { label: "Transactional", ceiling: quota.ceilings.transactional, note: "welcome and credit emails" },+ {+ label: "Bulk",+ ceiling: quota.ceilings.bulk,+ note: `holds back ${forecast.total} for the rest of today: ${forecast.signups} signups expected, ${forecast.expiry} expiry notices owed, ${forecast.headroom} headroom`,+ },+ ];+ return (+ <section className="space-y-3">+ <div className="flex flex-wrap items-baseline gap-x-3 text-sm">+ <span className="font-medium">Today, {quota.day} UTC</span>+ <span className="text-muted-foreground">+ {quota.sent} of {quota.providerLimit} sent · resets in {formatDuration(quota.resetsInSeconds)}+ </span>+ </div>+ <ul className="space-y-3">+ {classes.map((c) => {+ const ceiling = Math.max(0, c.ceiling);+ const width = Math.min(100, (100 * ceiling) / quota.providerLimit);+ const fill = Math.min(100, (100 * Math.min(quota.sent, ceiling)) / quota.providerLimit);+ const left = Math.max(0, ceiling - quota.sent);+ return (+ <li key={c.label} className="grid grid-cols-[120px_1fr_72px] items-center gap-x-3 gap-y-0.5 text-sm">+ <span>{c.label}</span>+ <div className="relative h-2 rounded-full bg-muted">+ <div className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground/25" style={{ width: `${width}%` }} />+ <div className="absolute inset-y-0 left-0 rounded-full bg-foreground" style={{ width: `${fill}%` }} />+ </div>+ <span className={cn("text-right tabular-nums", left === 0 ? "text-destructive" : "text-muted-foreground")}>+ {left} left+ </span>+ <span className="col-span-3 text-xs text-muted-foreground">{c.note}</span>+ </li>+ );+ })}+ </ul>+ </section>+ );+}++function KindsSection({ kinds }: { kinds: OutboxOverview["kinds"] }) {+ const cell = "py-1.5 pr-3";+ return (+ <section className="space-y-2">+ <h2 className="text-sm font-medium">Kinds, in send order</h2>+ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead className="text-left text-xs text-muted-foreground">+ <tr>+ <th className="py-1 pr-3 font-normal">Kind</th>+ <th className="py-1 pr-3 font-normal">Priority</th>+ <th className="py-1 pr-3 font-normal">Quota</th>+ <th className="py-1 pr-3 text-right font-normal">Queued</th>+ <th className="py-1 pr-3 text-right font-normal">Sent today</th>+ <th className="py-1 text-right font-normal">Failed</th>+ </tr>+ </thead>+ <tbody>+ {[...kinds]+ .sort((a, b) => b.priority - a.priority)+ .map((k) => (+ <tr key={k.kind} className="border-t">+ <td className={cn(cell, "font-medium")}>{k.kind}</td>+ <td className={cn(cell, "tabular-nums text-muted-foreground")}>{k.priority}</td>+ <td className={cn(cell, "text-muted-foreground")}>{k.quota}</td>+ <td className={cn(cell, "text-right tabular-nums")}>{k.queued}</td>+ <td className={cn(cell, "text-right tabular-nums")}>{k.sentToday}</td>+ <td className={cn("py-1.5 text-right tabular-nums", k.failed > 0 && "text-destructive")}>{k.failed}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </section>+ );+}++function ItemRow({ item, onRetry, retrying }: { item: OutboxItem; onRetry: () => void; retrying: boolean }) {+ const when = item.sentAt+ ? formatWhen(item.sentAt)+ : item.backingOff+ ? `retries ${formatWhen(item.notBefore)}`+ : `queued ${formatWhen(item.createdAt)}`;+ return (+ <li className="flex items-start gap-2.5">+ <span className={cn("mt-1.5 size-2 shrink-0 rounded-full", stateDot[item.state] ?? stateDot.queued)} />+ <div className="min-w-0 flex-1 text-sm">+ <div className="flex flex-wrap items-baseline gap-x-2">+ <span className="font-medium">{item.kind}</span>+ {item.promotionName ? <span className="text-muted-foreground">{item.promotionName}</span> : null}+ <span className="text-muted-foreground">{item.email ?? "inbox"}</span>+ <span className="text-muted-foreground">{item.state}</span>+ <span className="text-muted-foreground">{when}</span>+ {item.attempts > 0 && item.state !== "sent" ? (+ <span className="text-muted-foreground">{item.attempts} tries</span>+ ) : null}+ </div>+ {item.error ? <p className="text-destructive">{item.error}</p> : null}+ </div>+ {item.state === "failed" ? (+ <Button disabled={retrying} onClick={onRetry} size="sm" variant="outline">+ Retry+ </Button>+ ) : null}+ </li>+ );+}++function ItemsSection({ title, items, empty }: { title: string; items: OutboxItem[]; empty: string }) {+ const action = useOutboxAction();+ return (+ <section className="space-y-2">+ <h2 className="text-sm font-medium">{title}</h2>+ {items.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}+ />+ ))}+ </ul>+ )}+ </section>+ );+}++// The outbox: where the day's quota stands, what each kind has queued and+// sent, and the rows waiting, failed, and lately sent. The layout gates this+// route to super users, so the hook runs unconditionally.+export default function SuEmailPage() {+ const outbox = useEmailOutbox();+ if (!outbox.data) {+ return (+ <p className="pb-9 text-sm text-muted-foreground">+ {outbox.isPending ? "Loading…" : "Could not load the outbox."}+ </p>+ );+ }+ const { items } = 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." />+ </div>+ );+}diff --git a/site/src/app/su/jobs/list/page.tsx b/site/src/app/su/jobs/list/page.tsxnew file mode 100644index 00000000..669b43e2--- /dev/null+++ b/site/src/app/su/jobs/list/page.tsx@@ -0,0 +1,105 @@+"use client";++import { cn } from "@/lib/utils";+import { useRecentJobs, type AsyncJobListItem } from "@/queries/jobs";++// The list shows each job's stored payload and result as-is, so it stays+// honest for job kinds this page doesn't know about: flatten the primitive+// fields into "email: [email protected] · projects: 3".+function describeFields(value: unknown): string {+ if (typeof value !== "object" || value === null) return "";+ return Object.entries(value)+ .filter(([, v]) => ["string", "number", "boolean"].includes(typeof v))+ .map(([k, v]) => `${k}: ${String(v)}`)+ .join(" · ");+}++// A finished delete-user job reads as one sentence; other kinds (and+// unfinished jobs) keep the flattened raw fields.+function doneSummary(item: AsyncJobListItem): string | null {+ if (item.kind !== "delete-user" || item.state !== "done") return null;+ const payload = item.payload as { email?: unknown } | null;+ const email = typeof payload?.email === "string" ? payload.email : "";+ const result = item.result;+ return (+ `Deleted ${email} — ${String(result?.projects ?? 0)} project(s), ` ++ `${String(result?.libraryAssets ?? 0)} library asset(s), ` ++ `${String(result?.r2Objects ?? 0)} stored object(s).`+ );+}++function formatWhen(iso: string): string {+ const then = new Date(iso);+ const mins = Math.floor((Date.now() - then.getTime()) / 60000);+ if (mins < 1) return "just now";+ if (mins < 60) return `${mins}m ago`;+ if (mins < 60 * 24) return `${Math.floor(mins / 60)}h ago`;+ return then.toLocaleDateString(undefined, { month: "short", day: "numeric" });+}++const stateDot: Record<AsyncJobListItem["state"], string> = {+ queued: "bg-muted-foreground/40",+ running: "bg-blue-500 animate-pulse",+ done: "bg-emerald-500",+ error: "bg-destructive",+};++// Background jobs across the super-user surfaces — deletes started on Users,+// the analytics rollup, the outreach scan — newest first. The query polls+// while anything is queued or running, so states settle here without a+// refresh. The layout gates this route to super users, so the hook runs+// unconditionally.+export default function SuJobsPage() {+ const recent = useRecentJobs(true);++ if (!recent.data?.jobs.length) {+ return (+ <p className="pb-9 text-sm text-muted-foreground">+ {recent.isPending ? "Loading…" : "No jobs yet."}+ </p>+ );+ }++ return (+ <ul className="max-w-3xl space-y-3 pb-9">+ {recent.data.jobs.map((item) => (+ <li key={item.id} className="flex items-start gap-2.5">+ <span+ className={cn(+ "mt-1.5 size-2 shrink-0 rounded-full",+ stateDot[item.state],+ )}+ />+ <div className="min-w-0 text-sm">+ <div className="flex flex-wrap items-baseline gap-x-2">+ <span className="font-medium">{item.kind}</span>+ <span className="text-muted-foreground">{item.state}</span>+ <span className="text-muted-foreground">+ {formatWhen(item.createdAt)}+ </span>+ </div>+ {doneSummary(item) ? (+ <p className="text-muted-foreground">{doneSummary(item)}</p>+ ) : (+ <>+ {describeFields(item.payload) ? (+ <p className="truncate text-muted-foreground">+ {describeFields(item.payload)}+ </p>+ ) : null}+ {item.state === "done" && describeFields(item.result) ? (+ <p className="truncate text-muted-foreground">+ {describeFields(item.result)}+ </p>+ ) : null}+ </>+ )}+ {item.state === "error" && item.error ? (+ <p className="text-destructive">{item.error}</p>+ ) : null}+ </div>+ </li>+ ))}+ </ul>+ );+}diff --git a/site/src/app/su/jobs/page.tsx b/site/src/app/su/jobs/page.tsxindex 669b43e2..7484f9f4 100644--- a/site/src/app/su/jobs/page.tsx+++ b/site/src/app/su/jobs/page.tsx@@ -1,105 +1,8 @@-"use client";+import { redirect } from "next/navigation";-import { cn } from "@/lib/utils";-import { useRecentJobs, type AsyncJobListItem } from "@/queries/jobs";+import { SU_NAV } from "@/app/su/nav";-// The list shows each job's stored payload and result as-is, so it stays-// honest for job kinds this page doesn't know about: flatten the primitive-// fields into "email: [email protected] · projects: 3".-function describeFields(value: unknown): string {- if (typeof value !== "object" || value === null) return "";- return Object.entries(value)- .filter(([, v]) => ["string", "number", "boolean"].includes(typeof v))- .map(([k, v]) => `${k}: ${String(v)}`)- .join(" · ");-}--// A finished delete-user job reads as one sentence; other kinds (and-// unfinished jobs) keep the flattened raw fields.-function doneSummary(item: AsyncJobListItem): string | null {- if (item.kind !== "delete-user" || item.state !== "done") return null;- const payload = item.payload as { email?: unknown } | null;- const email = typeof payload?.email === "string" ? payload.email : "";- const result = item.result;- return (- `Deleted ${email} — ${String(result?.projects ?? 0)} project(s), ` +- `${String(result?.libraryAssets ?? 0)} library asset(s), ` +- `${String(result?.r2Objects ?? 0)} stored object(s).`- );-}--function formatWhen(iso: string): string {- const then = new Date(iso);- const mins = Math.floor((Date.now() - then.getTime()) / 60000);- if (mins < 1) return "just now";- if (mins < 60) return `${mins}m ago`;- if (mins < 60 * 24) return `${Math.floor(mins / 60)}h ago`;- return then.toLocaleDateString(undefined, { month: "short", day: "numeric" });-}--const stateDot: Record<AsyncJobListItem["state"], string> = {- queued: "bg-muted-foreground/40",- running: "bg-blue-500 animate-pulse",- done: "bg-emerald-500",- error: "bg-destructive",-};--// Background jobs across the super-user surfaces — deletes started on Users,-// the analytics rollup, the outreach scan — newest first. The query polls-// while anything is queued or running, so states settle here without a-// refresh. The layout gates this route to super users, so the hook runs-// unconditionally.+// The section has no surface of its own; it opens its first tab.export default function SuJobsPage() {- const recent = useRecentJobs(true);-- if (!recent.data?.jobs.length) {- return (- <p className="pb-9 text-sm text-muted-foreground">- {recent.isPending ? "Loading…" : "No jobs yet."}- </p>- );- }-- return (- <ul className="max-w-3xl space-y-3 pb-9">- {recent.data.jobs.map((item) => (- <li key={item.id} className="flex items-start gap-2.5">- <span- className={cn(- "mt-1.5 size-2 shrink-0 rounded-full",- stateDot[item.state],- )}- />- <div className="min-w-0 text-sm">- <div className="flex flex-wrap items-baseline gap-x-2">- <span className="font-medium">{item.kind}</span>- <span className="text-muted-foreground">{item.state}</span>- <span className="text-muted-foreground">- {formatWhen(item.createdAt)}- </span>- </div>- {doneSummary(item) ? (- <p className="text-muted-foreground">{doneSummary(item)}</p>- ) : (- <>- {describeFields(item.payload) ? (- <p className="truncate text-muted-foreground">- {describeFields(item.payload)}- </p>- ) : null}- {item.state === "done" && describeFields(item.result) ? (- <p className="truncate text-muted-foreground">- {describeFields(item.result)}- </p>- ) : null}- </>- )}- {item.state === "error" && item.error ? (- <p className="text-destructive">{item.error}</p>- ) : null}- </div>- </li>- ))}- </ul>- );+ redirect(SU_NAV.find((s) => s.href === "/jobs")!.tabs![0].href);}diff --git a/site/src/app/su/nav.ts b/site/src/app/su/nav.tsindex 33af2b02..50dc8048 100644--- a/site/src/app/su/nav.ts+++ b/site/src/app/su/nav.ts@@ -11,6 +11,7 @@ import {import type { ComponentType } from "react";import { RunAnalyticsButton } from "@/app/su/analytics/RunAnalyticsButton";+import { DrainNowButton } from "@/app/su/jobs/email/DrainNowButton";import { ScanOutreachButton } from "@/app/su/outreach/ScanOutreachButton";// The super-user surfaces in rail order, addressed from the root of their own@@ -104,7 +105,19 @@ export const SU_NAV: SuSurface[] = [label: "Jobs",icon: ListChecks,title: "Jobs",- description: "Background work started from these surfaces, newest first.",+ tabs: [+ {+ href: "/jobs/list",+ label: "Jobs",+ description: "Background work started from these surfaces, newest first.",+ },+ {+ href: "/jobs/email",+ label: "Email",+ description: "The outbox: today's quota, what is queued by kind, and what failed.",+ Action: DrainNowButton,+ },+ ],},];diff --git a/site/src/queries/emailOutbox.ts b/site/src/queries/emailOutbox.tsnew file mode 100644index 00000000..c131f336--- /dev/null+++ b/site/src/queries/emailOutbox.ts@@ -0,0 +1,31 @@+"use client";++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 const emailOutboxQueryKey = ["su", "email", "outbox"] as const;++// Super-user only: the outbox and the day's quota. Polls while anything is+// queued so sends settle on screen without a refresh.+export function useEmailOutbox() {+ return useQuery({+ queryFn: () => apiFetch<OutboxOverview>("/api/su/email"),+ queryKey: emailOutboxQueryKey,+ refetchInterval: (query) => (query.state.data?.kinds.some((k) => k.queued > 0) ? 5000 : 60000),+ });+}++// Drain now, or put one failed row back in the queue; the response is the+// refreshed overview.+export function useOutboxAction() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (body: { action: "drain" } | { action: "retry"; id: string }) =>+ apiFetch<OutboxOverview>("/api/su/email", { body: JSON.stringify(body), method: "POST" }),+ onSuccess: (data) => queryClient.setQueryData(emailOutboxQueryKey, data),+ });+}