OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat: add cohort details page
Carl-Gerhard Lindesvärd61215b5370c8
diff --git a/apps/start/src/components/cohort/cohort-events-chart.tsx b/apps/start/src/components/cohort/cohort-events-chart.tsxnew file mode 100644index 000000000..77c89326f--- /dev/null+++ b/apps/start/src/components/cohort/cohort-events-chart.tsx@@ -0,0 +1,121 @@+import { ActivityIcon } from 'lucide-react';+import {+ Area,+ AreaChart,+ CartesianGrid,+ Tooltip as RechartTooltip,+ ResponsiveContainer,+ XAxis,+ YAxis,+} from 'recharts';+import {+ useXAxisProps,+ useYAxisProps,+} from '@/components/report-chart/common/axis';+import { Widget, WidgetBody } from '@/components/widget';+import { useFormatDateInterval } from '@/hooks/use-format-date-interval';+import { useNumber } from '@/hooks/use-numer-formatter';+import { getChartColor } from '@/utils/theme';+import { WidgetHead, WidgetTitle } from '../overview/overview-widget';++type Props = {+ data: { date: string; count: number }[];+};++function Tooltip(props: any) {+ const number = useNumber();+ const formatDate = useFormatDateInterval({ interval: 'day', short: false });+ const payload = props.payload?.[0]?.payload;++ if (!payload) return null;++ return (+ <div className="flex min-w-[160px] flex-col gap-2 rounded-xl border bg-card p-3 shadow-xl">+ <div className="text-muted-foreground text-sm">+ {formatDate(new Date(payload.timestamp))}+ </div>+ <div className="flex items-center gap-2">+ <div+ className="h-10 w-1 rounded-full"+ style={{ background: getChartColor(0) }}+ />+ <div className="col gap-1">+ <div className="text-muted-foreground text-sm">Events</div>+ <div+ className="font-semibold text-lg"+ style={{ color: getChartColor(0) }}+ >+ {number.format(payload.count)}+ </div>+ </div>+ </div>+ </div>+ );+}++export function CohortEventsChart({ data }: Props) {+ const xAxisProps = useXAxisProps({ interval: 'day' });+ const yAxisProps = useYAxisProps({});+ const color = getChartColor(0);++ const chartData = data.map((item) => ({+ date: item.date,+ timestamp: new Date(item.date).getTime(),+ count: item.count,+ }));++ const gradientId = 'cohortEventsGradient';+ const total = data.reduce((acc, d) => acc + d.count, 0);++ return (+ <Widget className="w-full">+ <WidgetHead>+ <WidgetTitle icon={ActivityIcon}>+ Events last 30 days ({total.toLocaleString()})+ </WidgetTitle>+ </WidgetHead>+ <WidgetBody>+ {total === 0 ? (+ <p className="py-4 text-center text-muted-foreground text-sm">+ No events yet+ </p>+ ) : (+ <div className="h-[200px] w-full">+ <ResponsiveContainer>+ <AreaChart data={chartData}>+ <defs>+ <linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">+ <stop offset="5%" stopColor={color} stopOpacity={0.3} />+ <stop offset="95%" stopColor={color} stopOpacity={0.02} />+ </linearGradient>+ </defs>+ <RechartTooltip+ content={<Tooltip />}+ cursor={{ stroke: color, strokeOpacity: 0.3 }}+ />+ <Area+ dataKey="count"+ dot={false}+ fill={`url(#${gradientId})`}+ isAnimationActive={false}+ stroke={color}+ strokeWidth={2}+ type="monotone"+ />+ <XAxis {...xAxisProps} />+ <YAxis {...yAxisProps} />+ <CartesianGrid+ className="stroke-border"+ horizontal={true}+ strokeDasharray="3 3"+ strokeOpacity={0.5}+ vertical={false}+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ )}+ </WidgetBody>+ </Widget>+ );+}diff --git a/apps/start/src/modals/add-cohort.tsx b/apps/start/src/modals/add-cohort.tsxindex 75ac793d0..a45eeb043 100644--- a/apps/start/src/modals/add-cohort.tsx+++ b/apps/start/src/modals/add-cohort.tsx@@ -96,7 +96,7 @@ export default function AddCohort() {/>)}/>- <Label htmlFor="isStatic" className="cursor-pointer text-sm">+ <Label htmlFor="isStatic" className="cursor-pointer text-sm mb-0">Freeze snapshot (don't auto-refresh)</Label></div>diff --git a/apps/start/src/modals/edit-cohort.tsx b/apps/start/src/modals/edit-cohort.tsxindex ab6bbc573..cfe4b4378 100644--- a/apps/start/src/modals/edit-cohort.tsx+++ b/apps/start/src/modals/edit-cohort.tsx@@ -98,7 +98,7 @@ export default function EditCohort(props: EditCohortProps) {/>)}/>- <Label htmlFor="isStatic" className="cursor-pointer text-sm">+ <Label htmlFor="isStatic" className="cursor-pointer text-sm mb-0">Freeze snapshot (don't auto-refresh)</Label></div>diff --git a/apps/start/src/routeTree.gen.ts b/apps/start/src/routeTree.gen.tsindex 6881e99d4..475bb06e1 100644--- a/apps/start/src/routeTree.gen.ts+++ b/apps/start/src/routeTree.gen.ts@@ -88,12 +88,16 @@ import { Route as AppOrganizationIdProjectIdGroupsGroupIdTabsRouteImport } fromimport { Route as AppOrganizationIdProjectIdEventsTabsStatsRouteImport } from './routes/_app.$organizationId.$projectId.events._tabs.stats'import { Route as AppOrganizationIdProjectIdEventsTabsEventsRouteImport } from './routes/_app.$organizationId.$projectId.events._tabs.events'import { Route as AppOrganizationIdProjectIdEventsTabsConversionsRouteImport } from './routes/_app.$organizationId.$projectId.events._tabs.conversions'+import { Route as AppOrganizationIdProjectIdCohortsCohortIdTabsRouteImport } from './routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs'import { Route as AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRouteImport } from './routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.index'import { Route as AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRouteImport } from './routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.index'+import { Route as AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRouteImport } from './routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.index'import { Route as AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRouteImport } from './routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.sessions'import { Route as AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRouteImport } from './routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.events'import { Route as AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRouteImport } from './routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.members'import { Route as AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRouteImport } from './routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.events'+import { Route as AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRouteImport } from './routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.members'+import { Route as AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRouteImport } from './routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.events'const AppOrganizationIdProfileRouteImport = createFileRoute('/_app/$organizationId/profile',@@ -122,6 +126,9 @@ const AppOrganizationIdProjectIdProfilesProfileIdRouteImport = createFileRoute(const AppOrganizationIdProjectIdGroupsGroupIdRouteImport = createFileRoute('/_app/$organizationId/$projectId/groups_/$groupId',)()+const AppOrganizationIdProjectIdCohortsCohortIdRouteImport = createFileRoute(+ '/_app/$organizationId/$projectId/cohorts_/$cohortId',+)()const UnsubscribeRoute = UnsubscribeRouteImport.update({id: '/unsubscribe',@@ -389,6 +396,12 @@ const AppOrganizationIdProjectIdGroupsGroupIdRoute =path: '/groups/$groupId',getParentRoute: () => AppOrganizationIdProjectIdRoute,} as any)+const AppOrganizationIdProjectIdCohortsCohortIdRoute =+ AppOrganizationIdProjectIdCohortsCohortIdRouteImport.update({+ id: '/cohorts_/$cohortId',+ path: '/cohorts/$cohortId',+ getParentRoute: () => AppOrganizationIdProjectIdRoute,+ } as any)const AppOrganizationIdProfileTabsIndexRoute =AppOrganizationIdProfileTabsIndexRouteImport.update({id: '/',@@ -605,6 +618,11 @@ const AppOrganizationIdProjectIdEventsTabsConversionsRoute =path: '/conversions',getParentRoute: () => AppOrganizationIdProjectIdEventsTabsRoute,} as any)+const AppOrganizationIdProjectIdCohortsCohortIdTabsRoute =+ AppOrganizationIdProjectIdCohortsCohortIdTabsRouteImport.update({+ id: '/_tabs',+ getParentRoute: () => AppOrganizationIdProjectIdCohortsCohortIdRoute,+ } as any)const AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRoute =AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRouteImport.update({id: '/',@@ -617,6 +635,12 @@ const AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute =path: '/',getParentRoute: () => AppOrganizationIdProjectIdGroupsGroupIdTabsRoute,} as any)+const AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRoute =+ AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => AppOrganizationIdProjectIdCohortsCohortIdTabsRoute,+ } as any)const AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRoute =AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRouteImport.update({id: '/sessions',@@ -641,6 +665,18 @@ const AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute =path: '/events',getParentRoute: () => AppOrganizationIdProjectIdGroupsGroupIdTabsRoute,} as any)+const AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRoute =+ AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRouteImport.update({+ id: '/members',+ path: '/members',+ getParentRoute: () => AppOrganizationIdProjectIdCohortsCohortIdTabsRoute,+ } as any)+const AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRoute =+ AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRouteImport.update({+ id: '/events',+ path: '/events',+ getParentRoute: () => AppOrganizationIdProjectIdCohortsCohortIdTabsRoute,+ } as any)export interface FileRoutesByFullPath {'/': typeof IndexRoute@@ -694,6 +730,7 @@ export interface FileRoutesByFullPath {'/$organizationId/integrations/': typeof AppOrganizationIdIntegrationsTabsIndexRoute'/$organizationId/members/': typeof AppOrganizationIdMembersTabsIndexRoute'/$organizationId/profile/': typeof AppOrganizationIdProfileTabsIndexRoute+ '/$organizationId/$projectId/cohorts/$cohortId': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsRouteWithChildren'/$organizationId/$projectId/events/conversions': typeof AppOrganizationIdProjectIdEventsTabsConversionsRoute'/$organizationId/$projectId/events/events': typeof AppOrganizationIdProjectIdEventsTabsEventsRoute'/$organizationId/$projectId/events/stats': typeof AppOrganizationIdProjectIdEventsTabsStatsRoute@@ -716,10 +753,13 @@ export interface FileRoutesByFullPath {'/$organizationId/$projectId/notifications/': typeof AppOrganizationIdProjectIdNotificationsTabsIndexRoute'/$organizationId/$projectId/profiles/': typeof AppOrganizationIdProjectIdProfilesTabsIndexRoute'/$organizationId/$projectId/settings/': typeof AppOrganizationIdProjectIdSettingsTabsIndexRoute+ '/$organizationId/$projectId/cohorts/$cohortId/events': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRoute+ '/$organizationId/$projectId/cohorts/$cohortId/members': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRoute'/$organizationId/$projectId/groups/$groupId/events': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute'/$organizationId/$projectId/groups/$groupId/members': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute'/$organizationId/$projectId/profiles/$profileId/events': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRoute'/$organizationId/$projectId/profiles/$profileId/sessions': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRoute+ '/$organizationId/$projectId/cohorts/$cohortId/': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRoute'/$organizationId/$projectId/groups/$groupId/': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute'/$organizationId/$projectId/profiles/$profileId/': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRoute}@@ -770,6 +810,7 @@ export interface FileRoutesByTo {'/$organizationId/members/invitations': typeof AppOrganizationIdMembersTabsInvitationsRoute'/$organizationId/members/members': typeof AppOrganizationIdMembersTabsMembersRoute'/$organizationId/profile/email-preferences': typeof AppOrganizationIdProfileTabsEmailPreferencesRoute+ '/$organizationId/$projectId/cohorts/$cohortId': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRoute'/$organizationId/$projectId/events/conversions': typeof AppOrganizationIdProjectIdEventsTabsConversionsRoute'/$organizationId/$projectId/events/events': typeof AppOrganizationIdProjectIdEventsTabsEventsRoute'/$organizationId/$projectId/events/stats': typeof AppOrganizationIdProjectIdEventsTabsStatsRoute@@ -788,6 +829,8 @@ export interface FileRoutesByTo {'/$organizationId/$projectId/settings/mcp': typeof AppOrganizationIdProjectIdSettingsTabsMcpRoute'/$organizationId/$projectId/settings/tracking': typeof AppOrganizationIdProjectIdSettingsTabsTrackingRoute'/$organizationId/$projectId/settings/widgets': typeof AppOrganizationIdProjectIdSettingsTabsWidgetsRoute+ '/$organizationId/$projectId/cohorts/$cohortId/events': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRoute+ '/$organizationId/$projectId/cohorts/$cohortId/members': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRoute'/$organizationId/$projectId/groups/$groupId/events': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute'/$organizationId/$projectId/groups/$groupId/members': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute'/$organizationId/$projectId/profiles/$profileId/events': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRoute@@ -857,6 +900,8 @@ export interface FileRoutesById {'/_app/$organizationId/integrations/_tabs/': typeof AppOrganizationIdIntegrationsTabsIndexRoute'/_app/$organizationId/members/_tabs/': typeof AppOrganizationIdMembersTabsIndexRoute'/_app/$organizationId/profile/_tabs/': typeof AppOrganizationIdProfileTabsIndexRoute+ '/_app/$organizationId/$projectId/cohorts_/$cohortId': typeof AppOrganizationIdProjectIdCohortsCohortIdRouteWithChildren+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsRouteWithChildren'/_app/$organizationId/$projectId/events/_tabs/conversions': typeof AppOrganizationIdProjectIdEventsTabsConversionsRoute'/_app/$organizationId/$projectId/events/_tabs/events': typeof AppOrganizationIdProjectIdEventsTabsEventsRoute'/_app/$organizationId/$projectId/events/_tabs/stats': typeof AppOrganizationIdProjectIdEventsTabsStatsRoute@@ -881,10 +926,13 @@ export interface FileRoutesById {'/_app/$organizationId/$projectId/notifications/_tabs/': typeof AppOrganizationIdProjectIdNotificationsTabsIndexRoute'/_app/$organizationId/$projectId/profiles/_tabs/': typeof AppOrganizationIdProjectIdProfilesTabsIndexRoute'/_app/$organizationId/$projectId/settings/_tabs/': typeof AppOrganizationIdProjectIdSettingsTabsIndexRoute+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/events': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRoute+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/members': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRoute'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/events': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/members': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/events': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsEventsRoute'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/sessions': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsSessionsRoute+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/': typeof AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRoute'/_app/$organizationId/$projectId/groups_/$groupId/_tabs/': typeof AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRoute'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/': typeof AppOrganizationIdProjectIdProfilesProfileIdTabsIndexRoute}@@ -942,6 +990,7 @@ export interface FileRouteTypes {| '/$organizationId/integrations/'| '/$organizationId/members/'| '/$organizationId/profile/'+ | '/$organizationId/$projectId/cohorts/$cohortId'| '/$organizationId/$projectId/events/conversions'| '/$organizationId/$projectId/events/events'| '/$organizationId/$projectId/events/stats'@@ -964,10 +1013,13 @@ export interface FileRouteTypes {| '/$organizationId/$projectId/notifications/'| '/$organizationId/$projectId/profiles/'| '/$organizationId/$projectId/settings/'+ | '/$organizationId/$projectId/cohorts/$cohortId/events'+ | '/$organizationId/$projectId/cohorts/$cohortId/members'| '/$organizationId/$projectId/groups/$groupId/events'| '/$organizationId/$projectId/groups/$groupId/members'| '/$organizationId/$projectId/profiles/$profileId/events'| '/$organizationId/$projectId/profiles/$profileId/sessions'+ | '/$organizationId/$projectId/cohorts/$cohortId/'| '/$organizationId/$projectId/groups/$groupId/'| '/$organizationId/$projectId/profiles/$profileId/'fileRoutesByTo: FileRoutesByTo@@ -1018,6 +1070,7 @@ export interface FileRouteTypes {| '/$organizationId/members/invitations'| '/$organizationId/members/members'| '/$organizationId/profile/email-preferences'+ | '/$organizationId/$projectId/cohorts/$cohortId'| '/$organizationId/$projectId/events/conversions'| '/$organizationId/$projectId/events/events'| '/$organizationId/$projectId/events/stats'@@ -1036,6 +1089,8 @@ export interface FileRouteTypes {| '/$organizationId/$projectId/settings/mcp'| '/$organizationId/$projectId/settings/tracking'| '/$organizationId/$projectId/settings/widgets'+ | '/$organizationId/$projectId/cohorts/$cohortId/events'+ | '/$organizationId/$projectId/cohorts/$cohortId/members'| '/$organizationId/$projectId/groups/$groupId/events'| '/$organizationId/$projectId/groups/$groupId/members'| '/$organizationId/$projectId/profiles/$profileId/events'@@ -1104,6 +1159,8 @@ export interface FileRouteTypes {| '/_app/$organizationId/integrations/_tabs/'| '/_app/$organizationId/members/_tabs/'| '/_app/$organizationId/profile/_tabs/'+ | '/_app/$organizationId/$projectId/cohorts_/$cohortId'+ | '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs'| '/_app/$organizationId/$projectId/events/_tabs/conversions'| '/_app/$organizationId/$projectId/events/_tabs/events'| '/_app/$organizationId/$projectId/events/_tabs/stats'@@ -1128,10 +1185,13 @@ export interface FileRouteTypes {| '/_app/$organizationId/$projectId/notifications/_tabs/'| '/_app/$organizationId/$projectId/profiles/_tabs/'| '/_app/$organizationId/$projectId/settings/_tabs/'+ | '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/events'+ | '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/members'| '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/events'| '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/members'| '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/events'| '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/sessions'+ | '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/'| '/_app/$organizationId/$projectId/groups_/$groupId/_tabs/'| '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/'fileRoutesById: FileRoutesById@@ -1499,6 +1559,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdRouteImportparentRoute: typeof AppOrganizationIdProjectIdRoute}+ '/_app/$organizationId/$projectId/cohorts_/$cohortId': {+ id: '/_app/$organizationId/$projectId/cohorts_/$cohortId'+ path: '/cohorts/$cohortId'+ fullPath: '/$organizationId/$projectId/cohorts/$cohortId'+ preLoaderRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdRouteImport+ parentRoute: typeof AppOrganizationIdProjectIdRoute+ }'/_app/$organizationId/profile/_tabs/': {id: '/_app/$organizationId/profile/_tabs/'path: '/'@@ -1758,6 +1825,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppOrganizationIdProjectIdEventsTabsConversionsRouteImportparentRoute: typeof AppOrganizationIdProjectIdEventsTabsRoute}+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs': {+ id: '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs'+ path: '/cohorts/$cohortId'+ fullPath: '/$organizationId/$projectId/cohorts/$cohortId'+ preLoaderRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsRouteImport+ parentRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdRoute+ }'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/': {id: '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/'path: '/'@@ -1772,6 +1846,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsIndexRouteImportparentRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRoute}+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/': {+ id: '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/'+ path: '/'+ fullPath: '/$organizationId/$projectId/cohorts/$cohortId/'+ preLoaderRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRouteImport+ parentRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsRoute+ }'/_app/$organizationId/$projectId/profiles/$profileId/_tabs/sessions': {id: '/_app/$organizationId/$projectId/profiles/$profileId/_tabs/sessions'path: '/sessions'@@ -1800,6 +1881,20 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRouteImportparentRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsRoute}+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/members': {+ id: '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/members'+ path: '/members'+ fullPath: '/$organizationId/$projectId/cohorts/$cohortId/members'+ preLoaderRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRouteImport+ parentRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsRoute+ }+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/events': {+ id: '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/events'+ path: '/events'+ fullPath: '/$organizationId/$projectId/cohorts/$cohortId/events'+ preLoaderRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRouteImport+ parentRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsRoute+ }}}@@ -2010,6 +2105,42 @@ const AppOrganizationIdProjectIdSettingsRouteWithChildren =AppOrganizationIdProjectIdSettingsRouteChildren,)+interface AppOrganizationIdProjectIdCohortsCohortIdTabsRouteChildren {+ AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRoute+ AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRoute+ AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRoute+}++const AppOrganizationIdProjectIdCohortsCohortIdTabsRouteChildren: AppOrganizationIdProjectIdCohortsCohortIdTabsRouteChildren =+ {+ AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRoute:+ AppOrganizationIdProjectIdCohortsCohortIdTabsEventsRoute,+ AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRoute:+ AppOrganizationIdProjectIdCohortsCohortIdTabsMembersRoute,+ AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRoute:+ AppOrganizationIdProjectIdCohortsCohortIdTabsIndexRoute,+ }++const AppOrganizationIdProjectIdCohortsCohortIdTabsRouteWithChildren =+ AppOrganizationIdProjectIdCohortsCohortIdTabsRoute._addFileChildren(+ AppOrganizationIdProjectIdCohortsCohortIdTabsRouteChildren,+ )++interface AppOrganizationIdProjectIdCohortsCohortIdRouteChildren {+ AppOrganizationIdProjectIdCohortsCohortIdTabsRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdTabsRouteWithChildren+}++const AppOrganizationIdProjectIdCohortsCohortIdRouteChildren: AppOrganizationIdProjectIdCohortsCohortIdRouteChildren =+ {+ AppOrganizationIdProjectIdCohortsCohortIdTabsRoute:+ AppOrganizationIdProjectIdCohortsCohortIdTabsRouteWithChildren,+ }++const AppOrganizationIdProjectIdCohortsCohortIdRouteWithChildren =+ AppOrganizationIdProjectIdCohortsCohortIdRoute._addFileChildren(+ AppOrganizationIdProjectIdCohortsCohortIdRouteChildren,+ )+interface AppOrganizationIdProjectIdGroupsGroupIdTabsRouteChildren {AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsEventsRouteAppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdTabsMembersRoute@@ -2065,6 +2196,7 @@ interface AppOrganizationIdProjectIdRouteChildren {AppOrganizationIdProjectIdReportsReportIdRoute: typeof AppOrganizationIdProjectIdReportsReportIdRouteAppOrganizationIdProjectIdSessionsSessionIdRoute: typeof AppOrganizationIdProjectIdSessionsSessionIdRouteAppOrganizationIdProjectIdSettingsRoute: typeof AppOrganizationIdProjectIdSettingsRouteWithChildren+ AppOrganizationIdProjectIdCohortsCohortIdRoute: typeof AppOrganizationIdProjectIdCohortsCohortIdRouteWithChildrenAppOrganizationIdProjectIdGroupsGroupIdRoute: typeof AppOrganizationIdProjectIdGroupsGroupIdRouteWithChildren}@@ -2103,6 +2235,8 @@ const AppOrganizationIdProjectIdRouteChildren: AppOrganizationIdProjectIdRouteChAppOrganizationIdProjectIdSessionsSessionIdRoute,AppOrganizationIdProjectIdSettingsRoute:AppOrganizationIdProjectIdSettingsRouteWithChildren,+ AppOrganizationIdProjectIdCohortsCohortIdRoute:+ AppOrganizationIdProjectIdCohortsCohortIdRouteWithChildren,AppOrganizationIdProjectIdGroupsGroupIdRoute:AppOrganizationIdProjectIdGroupsGroupIdRouteWithChildren,}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.cohorts.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts.tsxindex bae875661..8b891e948 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.cohorts.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts.tsx@@ -1,6 +1,7 @@import { Card, CardActions, CardActionsItem } from '@/components/card';import { FullPageEmptyState } from '@/components/full-page-empty-state';import FullPageLoadingState from '@/components/full-page-loading-state';+import { ProjectLink } from '@/components/links';import { PageContainer } from '@/components/page-container';import { PageHeader } from '@/components/page-header';import { Button } from '@/components/ui/button';@@ -120,7 +121,10 @@ function Component() {const displayCount = count ?? 0;return (<Card key={cohort.id} hover>- <div className="flex flex-col p-4">+ <ProjectLink+ href={`/cohorts/${cohort.id}`}+ className="flex flex-col p-4 outline-none"+ ><div className="col gap-2"><div className="font-medium">{cohort.name}</div>{cohort.description && (@@ -149,7 +153,7 @@ function Component() {</div>)}</div>- </div>+ </ProjectLink><CardActions><CardActionsItem className="w-full" asChild>diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.events.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.events.tsxnew file mode 100644index 000000000..3d072aea3--- /dev/null+++ b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.events.tsx@@ -0,0 +1,46 @@+import { useInfiniteQuery } from '@tanstack/react-query';+import { createFileRoute } from '@tanstack/react-router';+import { parseAsIsoDateTime, useQueryState } from 'nuqs';+import { EventsTable } from '@/components/events/table';+import { useReadColumnVisibility } from '@/components/ui/data-table/data-table-hooks';+import { useEventQueryNamesFilter } from '@/hooks/use-event-query-filters';+import { useTRPC } from '@/integrations/trpc/react';+import { createProjectTitle, PAGE_TITLES } from '@/utils/title';++export const Route = createFileRoute(+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/events'+)({+ component: Component,+ head: () => ({+ meta: [{ title: createProjectTitle(PAGE_TITLES.COHORT_EVENTS) }],+ }),+});++function Component() {+ const { projectId, cohortId } = Route.useParams();+ const trpc = useTRPC();+ const [startDate] = useQueryState('startDate', parseAsIsoDateTime);+ const [endDate] = useQueryState('endDate', parseAsIsoDateTime);+ const [eventNames] = useEventQueryNamesFilter();+ const columnVisibility = useReadColumnVisibility('events');++ const query = useInfiniteQuery(+ trpc.event.events.infiniteQueryOptions(+ {+ projectId,+ cohortId,+ filters: [],+ startDate: startDate || undefined,+ endDate: endDate || undefined,+ events: eventNames,+ columnVisibility: columnVisibility ?? {},+ },+ {+ enabled: columnVisibility !== null,+ getNextPageParam: (lastPage) => lastPage.meta.next,+ }+ )+ );++ return <EventsTable query={query} />;+}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.index.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.index.tsxnew file mode 100644index 000000000..25f4e22b4--- /dev/null+++ b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.index.tsx@@ -0,0 +1,131 @@+import { useSuspenseQuery } from '@tanstack/react-query';+import { createFileRoute } from '@tanstack/react-router';+import { InfoIcon } from 'lucide-react';+import { CohortEventsChart } from '@/components/cohort/cohort-events-chart';+import FullPageLoadingState from '@/components/full-page-loading-state';+import { OverviewMetricCard } from '@/components/overview/overview-metric-card';+import { MostEvents } from '@/components/profiles/most-events';+import { PopularRoutes } from '@/components/profiles/popular-routes';+import { useTRPC } from '@/integrations/trpc/react';+import { createProjectTitle, PAGE_TITLES } from '@/utils/title';++export const Route = createFileRoute(+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/'+)({+ component: Component,+ loader: async ({ context, params }) => {+ await Promise.all([+ context.queryClient.prefetchQuery(+ context.trpc.cohort.eventsPerDay.queryOptions({+ projectId: params.projectId,+ cohortId: params.cohortId,+ })+ ),+ context.queryClient.prefetchQuery(+ context.trpc.cohort.mostEvents.queryOptions({+ projectId: params.projectId,+ cohortId: params.cohortId,+ })+ ),+ context.queryClient.prefetchQuery(+ context.trpc.cohort.popularRoutes.queryOptions({+ projectId: params.projectId,+ cohortId: params.cohortId,+ })+ ),+ ]);+ },+ pendingComponent: FullPageLoadingState,+ head: () => ({+ meta: [{ title: createProjectTitle(PAGE_TITLES.COHORT_DETAIL) }],+ }),+});++function Component() {+ const { projectId, cohortId } = Route.useParams();+ const trpc = useTRPC();++ const cohort = useSuspenseQuery(+ trpc.cohort.get.queryOptions({ id: cohortId })+ );+ const eventsPerDay = useSuspenseQuery(+ trpc.cohort.eventsPerDay.queryOptions({ projectId, cohortId })+ );+ const mostEvents = useSuspenseQuery(+ trpc.cohort.mostEvents.queryOptions({ projectId, cohortId })+ );+ const popularRoutes = useSuspenseQuery(+ trpc.cohort.popularRoutes.queryOptions({ projectId, cohortId })+ );++ const c = cohort.data;+ if (!c) return null;++ const notComputed = c.lastComputedAt === null;+ const isCapped = c.profileCount >= 10000;++ return (+ <div className="col gap-6">+ {notComputed && (+ <div className="flex items-center gap-2 rounded-md border border-blue-200 bg-blue-50 px-4 py-3 text-blue-900 text-sm">+ <InfoIcon className="size-4 shrink-0" />+ <span>+ This cohort hasn't been computed yet. Membership will appear+ within a minute.+ </span>+ </div>+ )}++ {isCapped && (+ <div className="flex items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-amber-900 text-sm">+ <InfoIcon className="size-4 shrink-0" />+ <span>+ Capped at 10,000 members — consider narrowing the criteria.+ </span>+ </div>+ )}++ <div className="card grid grid-cols-1 overflow-hidden rounded-md md:grid-cols-3">+ <OverviewMetricCard+ data={[]}+ id="profileCount"+ isLoading={false}+ label="Members"+ metric={{ current: c.profileCount, previous: null }}+ unit=""+ />+ <OverviewMetricCard+ data={[]}+ id="lastComputedAt"+ isLoading={false}+ label="Last computed"+ metric={{+ current: c.lastComputedAt+ ? new Date(c.lastComputedAt).getTime()+ : 0,+ previous: null,+ }}+ unit="timeAgo"+ />+ <OverviewMetricCard+ data={[]}+ id="createdAt"+ isLoading={false}+ label="Created"+ metric={{+ current: new Date(c.createdAt).getTime(),+ previous: null,+ }}+ unit="timeAgo"+ />+ </div>++ <CohortEventsChart data={eventsPerDay.data} />++ <div className="grid grid-cols-1 gap-6 md:grid-cols-2">+ <MostEvents data={mostEvents.data} />+ <PopularRoutes data={popularRoutes.data} />+ </div>+ </div>+ );+}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.members.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.members.tsxnew file mode 100644index 000000000..9a28c9fe6--- /dev/null+++ b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.members.tsx@@ -0,0 +1,42 @@+import { keepPreviousData, useQuery } from '@tanstack/react-query';+import { createFileRoute } from '@tanstack/react-router';+import { ProfilesTable } from '@/components/profiles/table';+import { useDataTablePagination } from '@/components/ui/data-table/data-table-hooks';+import { useSearchQueryState } from '@/hooks/use-search-query-state';+import { useTRPC } from '@/integrations/trpc/react';+import { createProjectTitle, PAGE_TITLES } from '@/utils/title';++export const Route = createFileRoute(+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs/members'+)({+ component: Component,+ head: () => ({+ meta: [{ title: createProjectTitle(PAGE_TITLES.COHORT_MEMBERS) }],+ }),+});++function Component() {+ const { projectId, cohortId } = Route.useParams();+ const trpc = useTRPC();+ const { debouncedSearch } = useSearchQueryState();+ const { page } = useDataTablePagination(50);++ const query = useQuery({+ ...trpc.cohort.listProfiles.queryOptions({+ projectId,+ cohortId,+ cursor: page - 1,+ take: 50,+ search: debouncedSearch || undefined,+ }),+ placeholderData: keepPreviousData,+ });++ return (+ <ProfilesTable+ pageSize={50}+ query={query as Parameters<typeof ProfilesTable>[0]['query']}+ type="profiles"+ />+ );+}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.tsxnew file mode 100644index 000000000..4be8fcbba--- /dev/null+++ b/apps/start/src/routes/_app.$organizationId.$projectId.cohorts_.$cohortId._tabs.tsx@@ -0,0 +1,208 @@+import {+ useMutation,+ useQueryClient,+ useSuspenseQuery,+} from '@tanstack/react-query';+import {+ createFileRoute,+ Outlet,+ useNavigate,+ useRouter,+} from '@tanstack/react-router';+import {+ DownloadIcon,+ PencilIcon,+ RefreshCwIcon,+ TargetIcon,+ Trash2Icon,+} from 'lucide-react';+import { toast } from 'sonner';+import FullPageLoadingState from '@/components/full-page-loading-state';+import { PageContainer } from '@/components/page-container';+import { PageHeader } from '@/components/page-header';+import { Button } from '@/components/ui/button';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { usePageTabs } from '@/hooks/use-page-tabs';+import { handleError, useTRPC } from '@/integrations/trpc/react';+import { pushModal, showConfirm } from '@/modals';+import { cohortMembersToCSV, downloadCSV } from '@/utils/csv-download';+import { createProjectTitle, PAGE_TITLES } from '@/utils/title';++export const Route = createFileRoute(+ '/_app/$organizationId/$projectId/cohorts_/$cohortId/_tabs'+)({+ component: Component,+ loader: async ({ context, params }) => {+ await context.queryClient.prefetchQuery(+ context.trpc.cohort.get.queryOptions({ id: params.cohortId })+ );+ },+ pendingComponent: FullPageLoadingState,+ head: () => ({+ meta: [{ title: createProjectTitle(PAGE_TITLES.COHORT_DETAIL) }],+ }),+});++function Component() {+ const router = useRouter();+ const { projectId, organizationId, cohortId } = Route.useParams();+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const navigate = useNavigate();++ const cohort = useSuspenseQuery(+ trpc.cohort.get.queryOptions({ id: cohortId })+ );++ const deleteMutation = useMutation(+ trpc.cohort.delete.mutationOptions({+ onSuccess() {+ queryClient.invalidateQueries(trpc.cohort.list.pathFilter());+ navigate({+ to: '/$organizationId/$projectId/cohorts',+ params: { organizationId, projectId },+ });+ },+ onError: handleError,+ })+ );++ const refreshMutation = useMutation(+ trpc.cohort.refresh.mutationOptions({+ onSuccess() {+ toast('Success', { description: 'Cohort refresh queued.' });+ queryClient.invalidateQueries(trpc.cohort.get.pathFilter());+ },+ onError: handleError,+ })+ );++ async function handleDownload() {+ if (!c) return;+ try {+ const result = await queryClient.fetchQuery(+ trpc.cohort.exportProfiles.queryOptions({ cohortId })+ );+ const csv = cohortMembersToCSV(result.profileIds);+ downloadCSV(csv, `${c.name}-members.csv`);+ } catch {+ toast.error('Failed to download cohort members');+ }+ }++ const { activeTab, tabs } = usePageTabs([+ {+ id: '/$organizationId/$projectId/cohorts/$cohortId',+ label: 'Overview',+ },+ { id: 'members', label: 'Members' },+ { id: 'events', label: 'Events' },+ ]);++ const handleTabChange = (tabId: string) => {+ router.navigate({+ from: Route.fullPath,+ to: tabId,+ });+ };++ const c = cohort.data;++ if (!c) {+ return (+ <PageContainer>+ <div className="flex flex-col items-center justify-center gap-3 py-24 text-muted-foreground">+ <TargetIcon className="size-10 opacity-30" />+ <p className="text-sm">Cohort not found</p>+ </div>+ </PageContainer>+ );+ }++ return (+ <PageContainer className="col">+ <PageHeader+ actions={+ <div className="row gap-2">+ <Button+ onClick={handleDownload}+ size="sm"+ variant="outline"+ >+ <DownloadIcon className="mr-2 size-4" />+ Download+ </Button>+ {!c.isStatic && (+ <Button+ disabled={refreshMutation.isPending}+ onClick={() => refreshMutation.mutate({ cohortId: c.id })}+ size="sm"+ variant="outline"+ >+ <RefreshCwIcon className="mr-2 size-4" />+ Refresh+ </Button>+ )}+ <Button+ onClick={() =>+ pushModal('EditCohort', {+ id: c.id,+ name: c.name,+ description: c.description,+ definition: c.definition as never,+ isStatic: c.isStatic,+ })+ }+ size="sm"+ variant="outline"+ >+ <PencilIcon className="mr-2 size-4" />+ Edit+ </Button>+ <Button+ onClick={() =>+ showConfirm({+ title: 'Delete cohort',+ text: `Are you sure you want to delete "${c.name}"? This action cannot be undone.`,+ onConfirm: () => deleteMutation.mutate({ id: c.id }),+ })+ }+ size="sm"+ variant="outline"+ >+ <Trash2Icon className="mr-2 size-4" />+ Delete+ </Button>+ </div>+ }+ description={c.description || undefined}+ title={+ <div className="row min-w-0 items-center gap-3">+ <TargetIcon className="size-6 shrink-0" />+ <span className="truncate">{c.name}</span>+ {c.isStatic && (+ <span className="rounded bg-blue-100 px-2 py-0.5 text-xs text-blue-700">+ Static+ </span>+ )}+ </div>+ }+ />++ <Tabs+ className="mt-2 mb-8"+ onValueChange={handleTabChange}+ value={activeTab}+ >+ <TabsList>+ {tabs.map((tab) => (+ <TabsTrigger key={tab.id} value={tab.id}>+ {tab.label}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ <Outlet />+ </PageContainer>+ );+}diff --git a/apps/start/src/utils/title.ts b/apps/start/src/utils/title.tsindex 7d88dd98d..a282639ed 100644--- a/apps/start/src/utils/title.ts+++ b/apps/start/src/utils/title.ts@@ -100,6 +100,9 @@ export const PAGE_TITLES = {GROUP_DETAILS: 'Group details',// CohortsCOHORTS: 'Cohorts',+ COHORT_DETAIL: 'Cohort',+ COHORT_MEMBERS: 'Cohort members',+ COHORT_EVENTS: 'Cohort events',// Sub-sectionsCONVERSIONS: 'Conversions',diff --git a/packages/db/code-migrations/15-backfill-cohort-mvs.ts b/packages/db/code-migrations/15-backfill-cohort-mvs.tsnew file mode 100644index 000000000..c8fe6795c--- /dev/null+++ b/packages/db/code-migrations/15-backfill-cohort-mvs.ts@@ -0,0 +1,251 @@+import { TABLE_NAMES } from '../src/clickhouse/client';+import {+ chMigrationClient,+ runClickhouseMigrationCommands,+} from '../src/clickhouse/migration';+import { getIsCluster } from './helpers';++/**+ * Backfill the two cohort MVs for the last 30 days.+ *+ * - profile_event_summary_mv+ * - profile_event_property_summary_mv+ *+ * Both were created with `populate: false` so they only index events inserted+ * AFTER their CREATE ran. This backfill feeds them the recent history so+ * cohorts with relative timeframes (e.g. "last 30 days") work immediately.+ *+ * AggregatingMergeTree merges *State aggregate values on read, so re-running+ * this migration is safe — duplicate rows collapse correctly.+ *+ * Flags:+ * --dry Print the first batch SQL and exit; don't execute.+ * --days=N Override the 30-day window (useful for testing).+ * --batch-hours=N How many hours of data to INSERT per batch (default 1).+ */++const DEFAULT_DAYS = 30;+const DEFAULT_BATCH_HOURS = 1;++type Batch = { startTime: string; endTime: string; sql: string };++function getArg(name: string): string | undefined {+ const prefix = `--${name}=`;+ const arg = process.argv.find((a) => a.startsWith(prefix));+ return arg?.slice(prefix.length);+}++function resolveTargetTable(baseName: string, isClustered: boolean): string {+ // INSERT targets the replicated (storage) side in clustered mode; writes+ // will distribute via the MV's own replication. In non-clustered mode,+ // there's only one table.+ return isClustered ? `${baseName}_replicated` : baseName;+}++function formatChDateTime(d: Date): string {+ return d.toISOString().slice(0, 19).replace('T', ' ');+}++function generateSummaryBatches(+ startDate: Date,+ endDate: Date,+ batchHours: number,+ targetTable: string,+): Batch[] {+ const batches: Batch[] = [];+ let cursor = new Date(startDate);++ while (cursor < endDate) {+ const next = new Date(cursor);+ next.setUTCHours(next.getUTCHours() + batchHours);+ const batchEnd = next > endDate ? endDate : next;++ const startStr = formatChDateTime(cursor);+ const endStr = formatChDateTime(batchEnd);++ const sql = `INSERT INTO ${targetTable}+SELECT+ project_id,+ profile_id,+ name,+ toStartOfDay(created_at) AS event_date,+ countState() AS event_count,+ minState(created_at) AS first_event_time,+ maxState(created_at) AS last_event_time,+ sumState(duration) AS total_duration+FROM events+WHERE created_at >= toDateTime('${startStr}')+ AND created_at < toDateTime('${endStr}')+ AND profile_id != device_id+GROUP BY project_id, profile_id, name, event_date`;++ batches.push({ startTime: startStr, endTime: endStr, sql });+ cursor = batchEnd;+ }++ return batches;+}++function generatePropertyBatches(+ startDate: Date,+ endDate: Date,+ batchHours: number,+ targetTable: string,+): Batch[] {+ const batches: Batch[] = [];+ let cursor = new Date(startDate);++ while (cursor < endDate) {+ const next = new Date(cursor);+ next.setUTCHours(next.getUTCHours() + batchHours);+ const batchEnd = next > endDate ? endDate : next;++ const startStr = formatChDateTime(cursor);+ const endStr = formatChDateTime(batchEnd);++ const sql = `INSERT INTO ${targetTable}+SELECT+ project_id,+ profile_id,+ name,+ property_key,+ property_value,+ toStartOfDay(created_at) AS event_date,+ countState() AS event_count,+ minState(created_at) AS first_event_time,+ maxState(created_at) AS last_event_time+FROM events+ARRAY JOIN mapKeys(properties) AS property_key, mapValues(properties) AS property_value+WHERE created_at >= toDateTime('${startStr}')+ AND created_at < toDateTime('${endStr}')+ AND profile_id != device_id+ AND property_key != ''+ AND property_value != ''+GROUP BY project_id, profile_id, name, property_key, property_value, event_date`;++ batches.push({ startTime: startStr, endTime: endStr, sql });+ cursor = batchEnd;+ }++ return batches;+}++async function hasEventsInRange(start: Date, end: Date): Promise<boolean> {+ const result = await chMigrationClient.query({+ query: `+ SELECT count() AS c+ FROM events+ WHERE created_at >= toDateTime('${formatChDateTime(start)}')+ AND created_at < toDateTime('${formatChDateTime(end)}')+ AND profile_id != device_id+ `,+ format: 'JSONEachRow',+ });+ const rows = await result.json<{ c: string }>();+ return Number(rows[0]?.c ?? 0) > 0;+}++async function executeBatches(label: string, batches: Batch[]): Promise<void> {+ const total = batches.length;+ const startedAt = Date.now();+ let completed = 0;++ console.log('');+ console.log(`🚀 ${label}: executing ${total} batches`);++ for (const batch of batches) {+ const t0 = Date.now();+ await runClickhouseMigrationCommands([batch.sql]);+ completed++;++ const logEvery = Math.max(1, Math.ceil(total / 10));+ if (completed % logEvery === 0 || completed === total) {+ const elapsedSec = Math.round((Date.now() - startedAt) / 1000);+ const pct = Math.round((completed / total) * 100);+ const lastSec = Math.round((Date.now() - t0) / 1000);+ console.log(+ ` [${pct}%] ${completed}/${total} last=${lastSec}s elapsed=${elapsedSec}s (${batch.startTime} → ${batch.endTime})`,+ );+ }+ }+}++export async function up() {+ const isClustered = getIsCluster();+ const isDryRun = process.argv.includes('--dry');++ const days = Number.parseInt(getArg('days') ?? String(DEFAULT_DAYS), 10);+ const batchHours = Number.parseInt(+ getArg('batch-hours') ?? String(DEFAULT_BATCH_HOURS),+ 10,+ );++ const endDate = new Date();+ endDate.setUTCMinutes(0, 0, 0);+ const startDate = new Date(endDate);+ startDate.setUTCDate(startDate.getUTCDate() - days);++ const summaryTarget = resolveTargetTable(+ TABLE_NAMES.profile_event_summary_mv,+ isClustered,+ );+ const propertyTarget = resolveTargetTable(+ TABLE_NAMES.profile_event_property_summary_mv,+ isClustered,+ );++ console.log('');+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');+ console.log('📦 Cohort MV backfill');+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');+ console.log(` Window: ${formatChDateTime(startDate)} → ${formatChDateTime(endDate)} (${days} days)`);+ console.log(` Batch size: ${batchHours} hour${batchHours === 1 ? '' : 's'}`);+ console.log(` Clustered: ${isClustered}`);+ console.log(` Summary MV: ${summaryTarget}`);+ console.log(` Property MV: ${propertyTarget}`);+ console.log(` Mode: ${isDryRun ? 'DRY RUN' : 'EXECUTE'}`);+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');++ const hasEvents = await hasEventsInRange(startDate, endDate);+ if (!hasEvents) {+ console.log('');+ console.log('⚠️ No identified events found in window — skipping backfill.');+ return;+ }++ const summaryBatches = generateSummaryBatches(+ startDate,+ endDate,+ batchHours,+ summaryTarget,+ );+ const propertyBatches = generatePropertyBatches(+ startDate,+ endDate,+ batchHours,+ propertyTarget,+ );++ if (isDryRun) {+ console.log('');+ console.log(`🔍 DRY RUN — ${summaryBatches.length} summary batches, ${propertyBatches.length} property batches`);+ console.log('');+ console.log('── Sample batch (profile_event_summary_mv) ──');+ console.log(summaryBatches[0]?.sql);+ console.log('');+ console.log('── Sample batch (profile_event_property_summary_mv) ──');+ console.log(propertyBatches[0]?.sql);+ return;+ }++ await executeBatches('profile_event_summary_mv', summaryBatches);+ await executeBatches('profile_event_property_summary_mv', propertyBatches);++ console.log('');+ console.log('✅ Backfill complete.');+}++export async function down() {+ console.log('⚠️ No down migration — backfill writes MV state, not schema.');+ console.log(' If a clean slate is needed, DROP + CREATE the two MVs and re-run.');+}diff --git a/packages/db/src/services/cohort.service.ts b/packages/db/src/services/cohort.service.tsindex fa10029be..3a73d4416 100644--- a/packages/db/src/services/cohort.service.ts+++ b/packages/db/src/services/cohort.service.ts@@ -12,6 +12,7 @@ import type {import { cohortComputeQueue } from '@openpanel/queue';import { TABLE_NAMES, ch, chQuery } from '../clickhouse/client';import { db } from '../prisma-client';+import { getProfiles, type IServiceProfile } from './profile.service';export const COHORT_MATERIALIZE_LIMIT = 10000;@@ -586,3 +587,124 @@ export async function enqueueCohortCompute(cohortId: string): Promise<void> {},);}++export async function removeCohortComputeJob(cohortId: string): Promise<void> {+ await cohortComputeQueue.remove(+ `cohort-${cohortId}`,+ );+}++export async function listCohortMemberProfiles({+ projectId,+ cohortId,+ cursor,+ take,+ search,+}: {+ projectId: string;+ cohortId: string;+ cursor?: number;+ take: number;+ search?: string;+}): Promise<{ data: IServiceProfile[]; count: number }> {+ const offset = Math.max(0, (cursor ?? 0) * take);+ const trimmed = search?.trim();+ const searchCondition = trimmed+ ? `AND (email ILIKE ${sqlstring.escape(`%${trimmed}%`)} OR first_name ILIKE ${sqlstring.escape(`%${trimmed}%`)} OR last_name ILIKE ${sqlstring.escape(`%${trimmed}%`)})`+ : '';++ const rows = await chQuery<{ id: string; total_count: number }>(`+ SELECT id, count() OVER () AS total_count+ FROM ${TABLE_NAMES.profiles} FINAL+ WHERE project_id = ${sqlstring.escape(projectId)}+ AND id IN (+ SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL+ WHERE cohort_id = ${sqlstring.escape(cohortId)}+ AND project_id = ${sqlstring.escape(projectId)}+ )+ ${searchCondition}+ ORDER BY created_at DESC+ LIMIT ${take} OFFSET ${offset}+ `);++ const count = rows[0]?.total_count ?? 0;+ const ids = rows.map((r) => r.id);+ if (ids.length === 0) return { data: [], count };++ const profiles = await getProfiles(ids, projectId);+ const byId = new Map(profiles.map((p) => [p.id, p]));+ const data = ids+ .map((id) => byId.get(id))+ .filter(Boolean) as IServiceProfile[];+ return { data, count };+}++export async function getCohortMemberEvents(+ projectId: string,+ cohortId: string,+ limit = 10,+): Promise<{ name: string; count: number }[]> {+ return chQuery<{ name: string; count: number }>(`+ SELECT name, count() AS count+ FROM ${TABLE_NAMES.events}+ WHERE project_id = ${sqlstring.escape(projectId)}+ AND profile_id IN (+ SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL+ WHERE cohort_id = ${sqlstring.escape(cohortId)}+ AND project_id = ${sqlstring.escape(projectId)}+ )+ AND name NOT IN ('screen_view', 'session_start', 'session_end')+ GROUP BY name+ ORDER BY count DESC+ LIMIT ${limit}+ `);+}++export async function getCohortEventsPerDay(+ projectId: string,+ cohortId: string,+ days = 30,+): Promise<{ date: string; count: number }[]> {+ const rows = await chQuery<{ date: string; count: number }>(`+ SELECT+ toDate(created_at) AS date,+ count() AS count+ FROM ${TABLE_NAMES.events}+ WHERE project_id = ${sqlstring.escape(projectId)}+ AND created_at >= toDate(now() - INTERVAL ${days} DAY)+ AND profile_id IN (+ SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL+ WHERE cohort_id = ${sqlstring.escape(cohortId)}+ AND project_id = ${sqlstring.escape(projectId)}+ )+ GROUP BY date+ ORDER BY date ASC+ WITH FILL+ FROM toDate(now() - INTERVAL ${days} DAY)+ TO toDate(now() + INTERVAL 1 DAY)+ STEP INTERVAL 1 DAY+ `);+ return rows.map((r) => ({ date: String(r.date), count: Number(r.count) }));+}++export async function getCohortMemberRoutes(+ projectId: string,+ cohortId: string,+ limit = 10,+): Promise<{ path: string; count: number }[]> {+ return chQuery<{ path: string; count: number }>(`+ SELECT path, count() AS count+ FROM ${TABLE_NAMES.events}+ WHERE project_id = ${sqlstring.escape(projectId)}+ AND profile_id IN (+ SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL+ WHERE cohort_id = ${sqlstring.escape(cohortId)}+ AND project_id = ${sqlstring.escape(projectId)}+ )+ AND name = 'screen_view'+ AND path != ''+ GROUP BY path+ ORDER BY count DESC+ LIMIT ${limit}+ `);+}diff --git a/packages/db/src/services/event.service.ts b/packages/db/src/services/event.service.tsindex 50c29f831..c295bd3c0 100644--- a/packages/db/src/services/event.service.ts+++ b/packages/db/src/services/event.service.ts@@ -441,6 +441,7 @@ export interface GetEventListOptions {profileId?: string;sessionId?: string;groupId?: string;+ cohortId?: string;take: number;cursor?: number | Date;events?: string[] | null;@@ -460,6 +461,7 @@ export async function getEventList(options: GetEventListOptions) {profileId,sessionId,groupId,+ cohortId,events,filters,startDate,@@ -613,6 +615,10 @@ export async function getEventList(options: GetEventListOptions) {sb.where.groupId = `has(groups, ${sqlstring.escape(groupId)})`;}+ if (cohortId) {+ sb.where.cohortId = `profile_id IN (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id = ${sqlstring.escape(cohortId)} AND project_id = ${sqlstring.escape(projectId)})`;+ }+if (startDate && endDate) {sb.where.created_at = `toDate(created_at) BETWEEN toDate('${formatClickhouseDate(startDate)}') AND toDate('${formatClickhouseDate(endDate)}')`;}@@ -677,6 +683,7 @@ export async function getEventsCount({projectId,profileId,groupId,+ cohortId,events,filters,startDate,@@ -692,6 +699,10 @@ export async function getEventsCount({sb.where.groupId = `has(groups, ${sqlstring.escape(groupId)})`;}+ if (cohortId) {+ sb.where.cohortId = `profile_id IN (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id = ${sqlstring.escape(cohortId)} AND project_id = ${sqlstring.escape(projectId)})`;+ }+if (startDate && endDate) {sb.where.created_at = `toDate(created_at) BETWEEN toDate('${formatClickhouseDate(startDate)}') AND toDate('${formatClickhouseDate(endDate)}')`;}diff --git a/packages/trpc/src/routers/cohort.ts b/packages/trpc/src/routers/cohort.tsindex 577b32a08..909173aa0 100644--- a/packages/trpc/src/routers/cohort.ts+++ b/packages/trpc/src/routers/cohort.ts@@ -1,15 +1,18 @@import { z } from 'zod';import {- TABLE_NAMES,- chQuery,computeCohort,countCohort,db,deleteCohortMembership,enqueueCohortCompute,getCohortCount,+ getCohortEventsPerDay,+ getCohortMemberEvents,+ getCohortMemberRoutes,getCohortMembers,+ listCohortMemberProfiles,+ removeCohortComputeJob,} from '@openpanel/db';import {type CohortDefinition,@@ -17,7 +20,6 @@ import {zCohortInput,zCohortUpdate,} from '@openpanel/validation';-import sqlstring from 'sqlstring';import { getProjectAccess } from '../access';import { TRPCAccessError, TRPCNotFoundError } from '../errors';@@ -154,64 +156,48 @@ export const cohortRouter = createTRPCRouter({return { success: true };}),- getProfiles: protectedProcedure+ listProfiles: protectedProcedure.input(z.object({+ projectId: z.string(),cohortId: z.string(),- limit: z.number().int().min(1).max(500).default(50),- offset: z.number().int().min(0).default(0),+ cursor: z.number().optional(),+ take: z.number().default(50),+ search: z.string().optional(),}),)- .query(async ({ input, ctx }) => {- const cohort = await db.cohort.findUnique({- where: { id: input.cohortId },- });-- if (!cohort) {- throw TRPCNotFoundError('Cohort not found');- }-- const access = await getProjectAccess({- projectId: cohort.projectId,- userId: ctx.session.userId!,- });-- if (!access) {- throw TRPCAccessError('You do not have access to this cohort');- }-- const result = await getCohortMembers(input.cohortId, cohort.projectId, {- limit: input.limit,- offset: input.offset,- });-- if (result.profileIds.length > 0) {- const profiles = await chQuery<{- id: string;- email: string;- first_name: string;- last_name: string;- properties: Record<string, string>;- created_at: string;- }>(`- SELECT id, email, first_name, last_name, properties, created_at- FROM ${TABLE_NAMES.profiles} FINAL- WHERE project_id = ${sqlstring.escape(cohort.projectId)}- AND id IN (${result.profileIds.map((id) => sqlstring.escape(id)).join(',')})- `);-- return {- profiles,- total: result.total,- };- }-+ .query(async ({ input }) => {+ const { data, count } = await listCohortMemberProfiles(input);return {- profiles: [],- total: result.total,+ data,+ meta: { count, pageCount: input.take },};}),+ mostEvents: protectedProcedure+ .input(+ z.object({ projectId: z.string(), cohortId: z.string() }),+ )+ .query(({ input }) =>+ getCohortMemberEvents(input.projectId, input.cohortId),+ ),++ eventsPerDay: protectedProcedure+ .input(+ z.object({ projectId: z.string(), cohortId: z.string() }),+ )+ .query(({ input }) =>+ getCohortEventsPerDay(input.projectId, input.cohortId),+ ),++ popularRoutes: protectedProcedure+ .input(+ z.object({ projectId: z.string(), cohortId: z.string() }),+ )+ .query(({ input }) =>+ getCohortMemberRoutes(input.projectId, input.cohortId),+ ),+getCount: protectedProcedure.input(z.object({ cohortId: z.string() })).query(async ({ input, ctx }) => {@@ -318,6 +304,7 @@ export const cohortRouter = createTRPCRouter({);}+ await removeCohortComputeJob(input.cohortId);await enqueueCohortCompute(input.cohortId);return { success: true };diff --git a/packages/trpc/src/routers/event.ts b/packages/trpc/src/routers/event.tsindex e7ac6c065..cdcdec51f 100644--- a/packages/trpc/src/routers/event.ts+++ b/packages/trpc/src/routers/event.ts@@ -123,6 +123,7 @@ export const eventRouter = createTRPCRouter({profileId: z.string().optional(),sessionId: z.string().optional(),groupId: z.string().optional(),+ cohortId: z.string().optional(),cursor: z.string().optional(),filters: z.array(zChartEventFilter).default([]),startDate: z.date().optional(),