Skip to content

Open source CapCut alternative.

TypeScript

feat(site): referral-source charts on the analytics dashboard

David Lebb18f70761e4
diff --git a/site/src/app/cut/app/su/analytics/page.tsx b/site/src/app/cut/app/su/analytics/page.tsx
index d5fea269..a67c7381 100644
--- a/site/src/app/cut/app/su/analytics/page.tsx
+++ b/site/src/app/cut/app/su/analytics/page.tsx
@@ -11,7 +11,8 @@ import {
ChartTooltipContent,
type ChartConfig,
} from "@/components/ui/chart";
-import type { AnalyticsRollup } from "@/lib/analytics/schema";
+import type { AnalyticsReferrals, AnalyticsRollup } from "@/lib/analytics/schema";
+import { REFERRAL_SOURCES } from "@/lib/onboarding/sequence";
import { cn } from "@/lib/utils";
import { useAnalyticsRollup } from "@/queries/analytics";
import { ApiError } from "@/queries/apiClient";
@@ -129,6 +130,39 @@ function deriveView(rollup: AnalyticsRollup): RollupView {
};
}
+// One chart point per day: the per-source answer counts under their source
+// ids, plus the running total of users who answered.
+type ReferralView = {
+ config: ChartConfig;
+ series: Record<string, number | string>[];
+ respondents: number;
+};
+
+function deriveReferrals(referrals: AnalyticsReferrals): ReferralView {
+ const labels = new Map<string, string>(REFERRAL_SOURCES.map((s) => [s.id, s.label]));
+ const config: ChartConfig = {};
+ referrals.sources.forEach((id, i) => {
+ config[id] = {
+ color: `var(--chart-${Math.min(i + 1, 8)})`,
+ label: labels.get(id) ?? id,
+ };
+ });
+ let respondents = 0;
+ const series = referrals.days.map((entry) => {
+ respondents += entry.respondents;
+ const point: Record<string, number | string> = { day: entry.day, totalResponses: respondents };
+ referrals.sources.forEach((id, i) => {
+ point[id] = entry.counts[i] ?? 0;
+ });
+ return point;
+ });
+ return { config, respondents, series };
+}
+
+const totalResponsesConfig = {
+ totalResponses: { label: "Total responses", color: "var(--chart-1)" },
+} satisfies ChartConfig;
+
const activesConfig = {
active: { label: "Active", color: "var(--chart-1)" },
working: { label: "Working", color: "var(--chart-2)" },
@@ -297,6 +331,10 @@ export default function SuAnalyticsPage() {
() => (rollup.data ? deriveView(rollup.data) : null),
[rollup.data],
);
+ const referrals = useMemo(
+ () => (rollup.data?.referrals ? deriveReferrals(rollup.data.referrals) : null),
+ [rollup.data],
+ );
if (rollup.isPending) return null;
@@ -444,6 +482,79 @@ export default function SuAnalyticsPage() {
</ChartCard>
</div>
+ {referrals && (
+ <div className="grid gap-6 xl:grid-cols-2">
+ <ChartCard
+ title="Referral sources"
+ subtitle="Onboarding answers per day, by source · one user can pick several"
+ >
+ <ChartContainer className="w-full" config={referrals.config}>
+ <BarChart accessibilityLayer data={referrals.series} margin={{ left: -16 }}>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ axisLine={false}
+ dataKey="day"
+ minTickGap={32}
+ tickFormatter={formatDay}
+ tickLine={false}
+ tickMargin={8}
+ />
+ <YAxis allowDecimals={false} axisLine={false} tickLine={false} width={48} />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent labelFormatter={(label) => formatDay(String(label))} />
+ }
+ />
+ {Object.keys(referrals.config).map((id) => (
+ <Bar
+ key={id}
+ dataKey={id}
+ fill={`var(--color-${id})`}
+ maxBarSize={24}
+ stackId="sources"
+ />
+ ))}
+ <ChartLegend content={<ChartLegendContent />} />
+ </BarChart>
+ </ChartContainer>
+ </ChartCard>
+
+ <ChartCard
+ title="Referral responses"
+ subtitle={`Running total of users who answered · ${referrals.respondents.toLocaleString("en-US")} all time`}
+ >
+ <ChartContainer className="w-full" config={totalResponsesConfig}>
+ <AreaChart accessibilityLayer data={referrals.series} margin={{ left: -16 }}>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ axisLine={false}
+ dataKey="day"
+ minTickGap={32}
+ tickFormatter={formatDay}
+ tickLine={false}
+ tickMargin={8}
+ />
+ <YAxis allowDecimals={false} axisLine={false} tickLine={false} width={48} />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent labelFormatter={(label) => formatDay(String(label))} />
+ }
+ />
+ <Area
+ dataKey="totalResponses"
+ dot={false}
+ fill="var(--color-totalResponses)"
+ fillOpacity={0.1}
+ stroke="var(--color-totalResponses)"
+ strokeWidth={2}
+ type="monotone"
+ />
+ </AreaChart>
+ </ChartContainer>
+ </ChartCard>
+ </div>
+ )}
+
<ChartCard title="Total registered" subtitle="Cumulative registrations, last 60 days">
<ChartContainer className="max-h-56 w-full" config={totalRegisteredConfig}>
<AreaChart accessibilityLayer data={view.series} margin={{ left: -16 }}>
diff --git a/site/src/app/globals.css b/site/src/app/globals.css
index 91b08c10..4ab1f9eb 100644
--- a/site/src/app/globals.css
+++ b/site/src/app/globals.css
@@ -25,6 +25,9 @@
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
+ --color-chart-8: var(--chart-8);
+ --color-chart-7: var(--chart-7);
+ --color-chart-6: var(--chart-6);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
@@ -83,6 +86,9 @@
--chart-3: #1baf7a;
--chart-4: #eda100;
--chart-5: #e87ba4;
+ --chart-6: #008300;
+ --chart-7: #4a3aa7;
+ --chart-8: #e34948;
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
@@ -120,6 +126,9 @@
--chart-3: #199e70;
--chart-4: #c98500;
--chart-5: #d55181;
+ --chart-6: #008300;
+ --chart-7: #9085e9;
+ --chart-8: #e66767;
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
diff --git a/site/src/lib/analytics/pipeline.ts b/site/src/lib/analytics/pipeline.ts
index 70f00944..28f7ff65 100644
--- a/site/src/lib/analytics/pipeline.ts
+++ b/site/src/lib/analytics/pipeline.ts
@@ -23,6 +23,7 @@ import {
type AnalyticsSnapshotFile,
utcDayOf,
} from "@/lib/analytics/schema";
+import { REFERRAL_SOURCES } from "@/lib/onboarding/sequence";
import { prisma } from "@/lib/prisma";
const ANALYTICS_PREFIX = "analytics/";
@@ -166,12 +167,29 @@ async function writeSnapshot(): Promise<AnalyticsSnapshotFile> {
for (;;) {
const page = await prisma.user.findMany({
orderBy: { id: "asc" },
- select: { createdAt: true, email: true, id: true, name: true },
+ select: {
+ createdAt: true,
+ email: true,
+ id: true,
+ name: true,
+ onboarding: { select: { referralAnsweredAt: true, referralSources: true } },
+ },
take: SNAPSHOT_PAGE_SIZE,
...(userCursor === undefined ? {} : { cursor: { id: userCursor }, skip: 1 }),
});
for (const u of page) {
- users.push({ createdAt: u.createdAt.toISOString(), email: u.email, id: u.id, name: u.name });
+ users.push({
+ createdAt: u.createdAt.toISOString(),
+ email: u.email,
+ id: u.id,
+ name: u.name,
+ ...(u.onboarding?.referralAnsweredAt
+ ? {
+ referralAnsweredAt: u.onboarding.referralAnsweredAt.toISOString(),
+ referralSources: u.onboarding.referralSources,
+ }
+ : {}),
+ });
}
if (page.length < SNAPSHOT_PAGE_SIZE) break;
userCursor = page[page.length - 1].id;
@@ -268,6 +286,7 @@ async function consolidate(
days,
generatedAt: new Date().toISOString(),
missing,
+ referrals: buildReferrals(snapshot, yesterday),
sources: [...ANALYTICS_SOURCES],
users,
version: ANALYTICS_ROLLUP_VERSION,
@@ -276,6 +295,44 @@ async function consolidate(
return rollup;
}
+// The snapshot covers every user, so this recomputes the whole referral
+// history each run — an answer moved by a replayed onboarding lands on its
+// new day with nothing left behind on the old one.
+function buildReferrals(
+ snapshot: AnalyticsSnapshotFile,
+ through: string,
+): AnalyticsRollup["referrals"] {
+ const answered = snapshot.users
+ .flatMap((u) =>
+ u.referralAnsweredAt === undefined
+ ? []
+ : [{ day: utcDayOf(new Date(u.referralAnsweredAt)), sources: u.referralSources ?? [] }],
+ )
+ .filter((a) => a.day <= through);
+ if (answered.length === 0) return undefined;
+
+ const sources: string[] = REFERRAL_SOURCES.map((s) => s.id);
+ for (const a of answered) {
+ for (const id of a.sources) if (!sources.includes(id)) sources.push(id);
+ }
+
+ const first = answered.reduce((min, a) => (a.day < min ? a.day : min), through);
+ const byDay = new Map<string, { day: string; respondents: number; counts: number[] }>();
+ const days: NonNullable<AnalyticsRollup["referrals"]>["days"] = [];
+ for (let day = first; day <= through; day = addUtcDays(day, 1)) {
+ const entry = { counts: sources.map(() => 0), day, respondents: 0 };
+ byDay.set(day, entry);
+ days.push(entry);
+ }
+ for (const a of answered) {
+ const entry = byDay.get(a.day);
+ if (!entry) continue;
+ entry.respondents++;
+ for (const id of a.sources) entry.counts[sources.indexOf(id)]++;
+ }
+ return { days, sources };
+}
+
async function putJson(key: string, value: unknown): Promise<void> {
await putObject(key, Buffer.from(JSON.stringify(value)), "application/json");
}
diff --git a/site/src/lib/analytics/schema.ts b/site/src/lib/analytics/schema.ts
index cf587f6b..271b5a0e 100644
--- a/site/src/lib/analytics/schema.ts
+++ b/site/src/lib/analytics/schema.ts
@@ -70,6 +70,9 @@ export const analyticsSnapshotFileSchema = z.object({
email: z.string(),
name: z.string(),
createdAt: z.string(),
+ // The onboarding referral answer; present once the user answered.
+ referralAnsweredAt: z.string().optional(),
+ referralSources: z.array(z.string()).optional(),
}),
),
balances: z.array(z.object({ userId: z.string(), balanceMicros: z.string() })),
@@ -88,6 +91,23 @@ export const analyticsRollupSchema = z.object({
// Day files that were absent or unreadable at consolidation; the UI can gray
// those columns out. Entries name the file kind: "db" or "posthog".
missing: z.array(z.object({ day: analyticsDaySchema, sources: z.array(z.string()) })),
+ // All-time onboarding referral answers, one entry per UTC day from the first
+ // answer through yesterday, zero-filled. Source ids copy REFERRAL_SOURCES at
+ // write time, plus any stored id beyond that list appended; counts align
+ // with sources. The question is multi-select, so a day's counts can sum past
+ // its respondents. Absent from rollups written before this shipped.
+ referrals: z
+ .object({
+ sources: z.array(z.string()),
+ days: z.array(
+ z.object({
+ day: analyticsDaySchema,
+ respondents: z.number(),
+ counts: z.array(z.number()),
+ }),
+ ),
+ })
+ .optional(),
users: z.array(
z.object({
id: z.string(),
@@ -103,3 +123,4 @@ export const analyticsRollupSchema = z.object({
});
export type AnalyticsRollup = z.infer<typeof analyticsRollupSchema>;
export type AnalyticsRollupUser = AnalyticsRollup["users"][number];
+export type AnalyticsReferrals = NonNullable<AnalyticsRollup["referrals"]>;