Open source CapCut alternative.
TypeScript
feat(site): read one account's offers, credit, mail and storage for su
David Lef75d68e87172
diff --git a/site/prisma/Email.prisma b/site/prisma/Email.prismaindex 1dcd7336..8bab472e 100644--- a/site/prisma/Email.prisma+++ b/site/prisma/Email.prisma@@ -50,6 +50,7 @@ model EmailSend {@@index([state, priority, rank, createdAt])@@index([promotionId, state])+ @@index([userId, sentAt])}// Global outbound email cap for free-tier limits: how many emails were sentdiff --git a/site/src/app/api/su/users/[id]/history/route.ts b/site/src/app/api/su/users/[id]/history/route.tsnew file mode 100644index 00000000..9902c6b3--- /dev/null+++ b/site/src/app/api/su/users/[id]/history/route.ts@@ -0,0 +1,19 @@+import { NextResponse } from "next/server";+import { z } from "zod";++import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";+import { readUserHistory } from "@/lib/marketing/userHistory";+import { prisma } from "@/lib/prisma";++type Params = { params: Promise<{ id: string }> };+const idSchema = z.string().trim().min(1);++// One account's offers, grants, mail and storage, for the operator writing+// to the person.+export const GET = withSuperUser(async (_request, { params }: Params) => {+ const id = idSchema.safeParse((await params).id);+ if (!id.success) return notFoundResponse();+ const user = await prisma.user.findUnique({ select: { id: true }, where: { id: id.data } });+ if (!user) return notFoundResponse();+ return NextResponse.json(await readUserHistory(user.id));+});diff --git a/site/src/app/su/outreach/UserHistory.tsx b/site/src/app/su/outreach/UserHistory.tsxnew file mode 100644index 00000000..25466997--- /dev/null+++ b/site/src/app/su/outreach/UserHistory.tsx@@ -0,0 +1,204 @@+"use client";++import { useState } from "react";++import { formatBytes } from "@/lib/bytes";+import { formatUsdPlain } from "@/lib/credits/format-usd";+import { useAnalyticsRollup } from "@/queries/analytics";+import { type OutreachRow } from "@/queries/outreach";+import { useUserHistory, type UserHistory } from "@/queries/userHistory";++// What the site has already given and sent one person: paid money, storage+// held, and one timeline of the offers that reached them, the credit that+// landed, and the mail that went out. Money comes from the analytics rollup+// every su page already holds; the rest is one read of the account's rows.++const GRANT_LABELS: Record<string, string> = {+ signup: "Signup bonus",+ manual_dollar: "Credit offer claimed",+ subscribe_bonus: "Subscribe bonus landed",+ stripe_topup: "Top-up",+ stripe_autoreload: "Auto reload",+ pro_subscription: "Pro allowance",+};++const OFFER_LABELS: Record<string, string> = {+ manual: "Credit offer",+ promotion_email: "Promotion offer",+ promotion_subscribe: "Promotion offer for subscribing",+ subscribe_bonus: "Subscribe bonus offered",+};++const EMAIL_LABELS: Record<string, string> = {+ promotion: "Promotion",+ "promotion-hand": "Promotion, sent by hand",+ outreach: "Note",+ "credit-offer": "Credit offer email",+ "credit-expiry": "Credit expiry notice",+ welcome: "Welcome",+};++const day = (iso: string) =>+ new Date(iso).toLocaleDateString("en-US", { day: "numeric", month: "short", year: "numeric" });++const dollars = (micros: string) => formatUsdPlain((Number(micros) / 1_000_000).toFixed(2));++type Event = {+ at: string;+ key: string;+ title: string;+ amount: string | null;+ notes: string[];+ tone: "landed" | "open" | "missed" | "plain";+};++// The three lists as one story, newest first. An offer says where it stands+// — claimed, still open, or missed — and a grant what is left of it.+function timeline(history: UserHistory, now: number): Event[] {+ const events: Event[] = [];+ for (const offer of history.offers) {+ const notes: string[] = [];+ if (offer.emailSentAt) notes.push(`emailed ${day(offer.emailSentAt)}`);+ let tone: Event["tone"] = "open";+ if (offer.claimedAt) {+ notes.push(`claimed ${day(offer.claimedAt)}`);+ tone = "landed";+ } else if (offer.closesAt && Date.parse(offer.closesAt) < now) {+ notes.push(`closed ${day(offer.closesAt)} unclaimed`);+ tone = "missed";+ } else if (offer.closesAt) {+ notes.push(`open until ${day(offer.closesAt)}`);+ } else {+ notes.push("open");+ }+ events.push({+ at: offer.createdAt,+ key: `offer:${offer.id}`,+ title: offer.promotion ? `${OFFER_LABELS[offer.kind] ?? offer.kind} · ${offer.promotion.name}` : (OFFER_LABELS[offer.kind] ?? offer.description ?? offer.kind),+ amount: formatUsdPlain(offer.dollars),+ notes,+ tone,+ });+ }+ for (const grant of history.grants) {+ const notes: string[] = [];+ const left = Number(grant.remainingDollars);+ const expired = grant.expiresAt !== null && Date.parse(grant.expiresAt) < now;+ if (left > 0 && !expired) notes.push(`${formatUsdPlain(grant.remainingDollars)} left`);+ if (grant.expiresAt) notes.push(`${expired ? "expired" : "expires"} ${day(grant.expiresAt)}`);+ if (grant.status !== "active") notes.push(grant.status);+ events.push({+ at: grant.createdAt,+ key: `grant:${grant.id}`,+ title: GRANT_LABELS[grant.source] ?? grant.description ?? grant.source,+ amount: formatUsdPlain(grant.dollars),+ notes,+ tone: "landed",+ });+ }+ for (const email of history.emails) {+ const subject = email.promotion?.subject ?? email.subject;+ events.push({+ at: email.sentAt,+ key: `email:${email.id}`,+ title: email.promotion+ ? `${EMAIL_LABELS[email.kind] ?? email.kind} · ${email.promotion.name}`+ : subject+ ? `${EMAIL_LABELS[email.kind] ?? email.kind} · ${subject}`+ : (EMAIL_LABELS[email.kind] ?? email.kind),+ amount: null,+ notes: email.clickedAt ? [`clicked ${day(email.clickedAt)}`] : [],+ tone: "plain",+ });+ }+ return events.sort((a, b) => Date.parse(b.at) - Date.parse(a.at));+}++const TONE: Record<Event["tone"], string> = {+ landed: "bg-emerald-500",+ open: "bg-sky-500",+ missed: "bg-muted-foreground/40",+ plain: "bg-muted-foreground/40",+};++export function UserHistoryPanel({ target }: { target: OutreachRow }) {+ const history = useUserHistory(target.userId);+ const rollup = useAnalyticsRollup();+ const rolled = rollup.data?.users.find((user) => user.id === target.userId);+ // The rollup's billing events name the payer by email; the window's charges+ // for this person are the ones with theirs.+ const charges = (rollup.data?.billing?.events ?? []).filter(+ (event) => event.email === target.email && event.kind !== "canceled" && event.amountMicros !== null,+ );+ // The moment the panel opened; offers and grants are read against it.+ const [now] = useState(() => Date.now());+ const events = history.data ? timeline(history.data, now) : [];++ return (+ <div className="flex min-h-0 flex-col gap-4 overflow-y-auto pr-1">+ <dl className="grid grid-cols-2 gap-x-6 gap-y-2 text-sm sm:grid-cols-4">+ <Fact label="Paid all-time" value={rolled?.fundedMicros ? dollars(rolled.fundedMicros) : "$0"} />+ <Fact label="Balance" value={formatUsdPlain(target.balance)} />+ <Fact+ label="Storage"+ value={history.data ? formatBytes(Number(history.data.storageBytes)) : formatBytes(Number(target.storageBytes))}+ />+ <Fact label="Joined" value={day(target.signedUpAt)} />+ </dl>++ {charges.length > 0 ? (+ <section className="space-y-1.5">+ <h3 className="text-xs font-medium text-muted-foreground">Payments in the analytics window</h3>+ <ul className="divide-y rounded-lg border">+ {charges.map((charge, i) => (+ <li className="flex items-center gap-3 px-3 py-1.5 text-sm" key={`${charge.objectId ?? i}`}>+ <span className="w-24 shrink-0 tabular-nums text-muted-foreground">{day(charge.day)}</span>+ <span className="min-w-0 flex-1 truncate">+ {charge.kind === "paid" ? "Paid" : "Declined"}+ {charge.detail ? ` · ${charge.detail}` : ""}+ </span>+ <span className="tabular-nums">{dollars(charge.amountMicros!)}</span>+ </li>+ ))}+ </ul>+ </section>+ ) : null}++ <section className="space-y-1.5">+ <h3 className="text-xs font-medium text-muted-foreground">Offers, credit and mail</h3>+ {history.isPending ? (+ <p className="text-sm text-muted-foreground">Loading…</p>+ ) : history.isError ? (+ <p className="text-sm text-destructive">Couldn't read this account's history.</p>+ ) : events.length === 0 ? (+ <p className="text-sm text-muted-foreground">Nothing sent or granted yet.</p>+ ) : (+ <ul className="divide-y rounded-lg border">+ {events.map((event) => (+ <li className="flex items-start gap-3 px-3 py-1.5 text-sm" key={event.key}>+ <span className="w-24 shrink-0 tabular-nums text-muted-foreground">{day(event.at)}</span>+ <span className={`mt-1.5 size-2 shrink-0 rounded-full ${TONE[event.tone]}`} />+ <span className="min-w-0 flex-1">+ <span className="block truncate">{event.title}</span>+ {event.notes.length > 0 ? (+ <span className="block text-xs text-muted-foreground">{event.notes.join(" · ")}</span>+ ) : null}+ </span>+ {event.amount ? <span className="tabular-nums">{event.amount}</span> : null}+ </li>+ ))}+ </ul>+ )}+ </section>+ </div>+ );+}++function Fact({ label, value }: { label: string; value: string }) {+ return (+ <div>+ <dt className="text-xs text-muted-foreground">{label}</dt>+ <dd className="tabular-nums">{value}</dd>+ </div>+ );+}diff --git a/site/src/lib/marketing/userHistory.ts b/site/src/lib/marketing/userHistory.tsnew file mode 100644index 00000000..482853ab--- /dev/null+++ b/site/src/lib/marketing/userHistory.ts@@ -0,0 +1,151 @@+import { creditMicrosToString } from "@/lib/credits/amounts";+import { PROMOTION_OFFER_KINDS } from "@/lib/credits/offerKinds";+import { prisma } from "@/lib/prisma";++// One account's money and mail, as an operator reads it before writing to+// the person: every credit offer with when it reached them and when it was+// claimed, every grant that landed (the signup bonus among them), every+// email the site sent them, and the storage they hold. Each list is one+// indexed read bounded by the account, so the whole answer is a handful of+// small queries however large the tables grow.++export type UserHistoryPromotion = { id: string; name: string; subject: string };++export type UserHistoryOffer = {+ id: string;+ kind: string;+ promotion: UserHistoryPromotion | null;+ dollars: string;+ description: string | null;+ createdAt: string;+ emailSentAt: string | null;+ closesAt: string | null;+ claimedAt: string | null;+};++export type UserHistoryGrant = {+ id: string;+ source: string;+ dollars: string;+ remainingDollars: string;+ status: string;+ description: string | null;+ createdAt: string;+ expiresAt: string | null;+};++export type UserHistoryEmail = {+ id: string;+ kind: string;+ promotion: UserHistoryPromotion | null;+ subject: string | null;+ sentAt: string;+ clickedAt: string | null;+};++export type UserHistory = {+ storageBytes: string;+ offers: UserHistoryOffer[];+ grants: UserHistoryGrant[];+ emails: UserHistoryEmail[];+};++// The mail a person can be said to have received: tests go to the operator+// and a forwarded reply is the person's own words coming back.+const RECEIVED_EMAIL_KINDS = ["promotion", "promotion-hand", "outreach", "credit-offer", "credit-expiry", "welcome"];++const EMAIL_CAP = 100;++// A promotion's offer is keyed on the promotion and the account, so the+// promotion is the id's first half.+function promotionIdOfOffer(offer: { id: string; kind: string }): string | null {+ if (!(PROMOTION_OFFER_KINDS as readonly string[]).includes(offer.kind)) return null;+ const at = offer.id.indexOf(":");+ return at > 0 ? offer.id.slice(0, at) : null;+}++const iso = (d: Date | null) => (d ? d.toISOString() : null);++export async function readUserHistory(userId: string): Promise<UserHistory> {+ const [offers, grants, emails, storage] = await Promise.all([+ prisma.creditOffer.findMany({+ orderBy: { createdAt: "desc" },+ where: { userId },+ }),+ prisma.userCreditGrant.findMany({+ orderBy: { createdAt: "desc" },+ where: { userId },+ }),+ prisma.emailSend.findMany({+ orderBy: { sentAt: "desc" },+ select: {+ clickedAt: true,+ id: true,+ kind: true,+ payload: true,+ promotionId: true,+ sentAt: true,+ },+ take: EMAIL_CAP,+ where: { kind: { in: RECEIVED_EMAIL_KINDS }, state: "sent", userId },+ }),+ prisma.cutStorageUsage.findUnique({ select: { bytes: true }, where: { userId } }),+ ]);++ // The promotions behind offers and emails, read once for all of them.+ const promotionIds = new Set<string>();+ for (const offer of offers) {+ const id = promotionIdOfOffer(offer);+ if (id) promotionIds.add(id);+ }+ for (const email of emails) if (email.promotionId) promotionIds.add(email.promotionId);+ const promotions = new Map<string, UserHistoryPromotion>();+ if (promotionIds.size > 0) {+ const rows = await prisma.promotion.findMany({+ select: { id: true, name: true, subject: true },+ where: { id: { in: [...promotionIds] } },+ });+ for (const row of rows) promotions.set(row.id, row);+ }+ const promotionOf = (id: string | null) => (id ? (promotions.get(id) ?? null) : null);++ return {+ storageBytes: (storage?.bytes ?? BigInt(0)).toString(),+ offers: offers.map((offer) => ({+ id: offer.id,+ kind: offer.kind,+ promotion: promotionOf(promotionIdOfOffer(offer)),+ dollars: creditMicrosToString(offer.amountMicros),+ description: offer.description,+ createdAt: offer.createdAt.toISOString(),+ emailSentAt: iso(offer.emailSentAt),+ closesAt: iso(offer.closesAt),+ claimedAt: iso(offer.claimedAt),+ })),+ grants: grants.map((grant) => ({+ id: grant.id,+ source: grant.source,+ dollars: creditMicrosToString(grant.originalAmountMicros),+ remainingDollars: creditMicrosToString(grant.remainingAmountMicros),+ status: grant.status,+ description: grant.description,+ createdAt: grant.createdAt.toISOString(),+ expiresAt: iso(grant.expiresAt),+ })),+ emails: emails.flatMap((email) => {+ if (!email.sentAt) return [];+ const payload = email.payload as { subject?: unknown } | null;+ const subject = typeof payload?.subject === "string" ? payload.subject : null;+ return [+ {+ id: email.id,+ kind: email.kind,+ promotion: promotionOf(email.promotionId),+ subject,+ sentAt: email.sentAt.toISOString(),+ clickedAt: iso(email.clickedAt),+ },+ ];+ }),+ };+}diff --git a/site/src/queries/outreach.ts b/site/src/queries/outreach.tsindex 2c46e549..6911c708 100644--- a/site/src/queries/outreach.ts+++ b/site/src/queries/outreach.ts@@ -128,7 +128,11 @@ export function useOutreachAction() {method: "POST",}),mutationKey: outreachActionKey,- onSuccess: () => queryClient.invalidateQueries({ queryKey: ["outreach"] }),+ // A send lands in the person's history too.+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: ["outreach"] });+ void queryClient.invalidateQueries({ queryKey: ["su", "users"] });+ },});}diff --git a/site/src/queries/userHistory.ts b/site/src/queries/userHistory.tsnew file mode 100644index 00000000..26794d3a--- /dev/null+++ b/site/src/queries/userHistory.ts@@ -0,0 +1,20 @@+"use client";++import { useQuery } from "@tanstack/react-query";++import type { UserHistory } from "@/lib/marketing/userHistory";+import { apiFetch } from "@/queries/apiClient";++export type { UserHistory, UserHistoryEmail, UserHistoryGrant, UserHistoryOffer } from "@/lib/marketing/userHistory";++// Super-user only: one account's offers, grants, mail and storage. Read when+// the operator opens the history, and held for the session — a note sent+// from the same dialog invalidates it.+export function useUserHistory(userId: string | null) {+ return useQuery({+ enabled: userId !== null,+ queryFn: () => apiFetch<UserHistory>(`/api/su/users/${encodeURIComponent(userId!)}/history`),+ queryKey: ["su", "users", userId, "history"] as const,+ staleTime: 5 * 60_000,+ });+}