OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): save custom events and use them across reports (#550)
Carl-Gerhard Lindesvärda887576afeb0
diff --git a/apps/start/src/components/report/sidebar/ReportSeries.tsx b/apps/start/src/components/report/sidebar/ReportSeries.tsxindex 9bb884845..601144ccf 100644--- a/apps/start/src/components/report/sidebar/ReportSeries.tsx+++ b/apps/start/src/components/report/sidebar/ReportSeries.tsx@@ -41,6 +41,7 @@ import { ComboboxEvents } from '@/components/ui/combobox-events';import { Input } from '@/components/ui/input';import { InputEnter } from '@/components/ui/input-enter';import { useAppParams } from '@/hooks/use-app-params';+import { useCustomEvents } from '@/hooks/use-custom-events';import { useDebounceFn } from '@/hooks/use-debounce-fn';import { useEventNames } from '@/hooks/use-event-names';import { useDispatch, useSelector } from '@/redux';@@ -147,6 +148,10 @@ export function ReportSeries() {dispatch(changeEvent(event));});const isSelectManyEvents = chartType === 'retention';+ // Retention and user flow match stored event names, so they cannot resolve a custom event.+ const supportsCustomEvents = !(isSelectManyEvents || isSankey);+ const projectCustomEvents = useCustomEvents(projectId);+ const customEvents = supportsCustomEvents ? projectCustomEvents : [];const sensors = useSensors(useSensor(PointerSensor),@@ -303,6 +308,7 @@ export function ReportSeries() {<><ComboboxEventsclassName="flex-1"+ customEvents={customEvents}items={eventNames}multiple={isSelectManyEvents as false}onChange={(value) => {@@ -326,13 +332,29 @@ export function ReportSeries() {...event,type: 'event',name: value,+ customEventId: undefined,filters: [],}));}}+ onSelectCustomEvent={(customEvent) => {+ dispatch(+ changeEvent({+ ...event,+ type: 'event',+ name: customEvent.name,+ customEventId: customEvent.id,+ filters: [],+ })+ );+ }}placeholder="Select event"searchable+ selectedCustomEventId={+ (event as IChartEventItem & { type: 'event' })+ .customEventId+ }value={(isSelectManyEvents? ((@@ -378,6 +400,7 @@ export function ReportSeries() {<div className="flex gap-2"><ComboboxEventsclassName="flex-1"+ customEvents={customEvents}disabled={isAddEventDisabled || isSankeyEventLimitReached}items={eventNames}onChange={(value) => {@@ -407,6 +430,17 @@ export function ReportSeries() {);}}}+ onSelectCustomEvent={(customEvent) => {+ dispatch(+ addSerie({+ type: 'event',+ name: customEvent.name,+ customEventId: customEvent.id,+ segment: 'event',+ filters: [],+ })+ );+ }}placeholder="Select event"searchablevalue={''}diff --git a/apps/start/src/components/settings/custom-events.tsx b/apps/start/src/components/settings/custom-events.tsxnew file mode 100644index 000000000..338d60432--- /dev/null+++ b/apps/start/src/components/settings/custom-events.tsx@@ -0,0 +1,81 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Widget, WidgetBody, WidgetHead } from '@/components/widget';+import { useAppParams } from '@/hooks/use-app-params';+import { handleError, useTRPC } from '@/integrations/trpc/react';+import { pushModal, showConfirm } from '@/modals';++export function CustomEvents() {+ const { projectId } = useAppParams();+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const query = useQuery(trpc.customEvent.list.queryOptions({ projectId }));+ const deletion = useMutation(+ trpc.customEvent.delete.mutationOptions({+ onSuccess() {+ queryClient.invalidateQueries(trpc.customEvent.list.pathFilter());+ queryClient.invalidateQueries(trpc.chart.pathFilter());+ },+ onError: handleError,+ })+ );++ return (+ <Widget className="w-full max-w-screen-md">+ <WidgetHead className="space-y-2">+ <span className="title">Custom events</span>+ <p className="text-muted-foreground">+ Name a group of events once, like "Used navigation", and pick it in+ any report. Each event can be narrowed with its own filters.+ </p>+ </WidgetHead>+ <WidgetBody className="col gap-2">+ {query.data?.map((customEvent) => (+ <div+ className="row items-center gap-2 rounded-lg border bg-def-100 p-2 pl-4"+ key={customEvent.id}+ >+ <div className="min-w-0 flex-1">+ <div className="truncate font-medium">{customEvent.name}</div>+ <div className="truncate text-muted-foreground text-sm">+ {customEvent.items.map((item) => item.name).join(', ')}+ </div>+ </div>+ <Button+ aria-label={`Edit ${customEvent.name}`}+ icon={PencilIcon}+ onClick={() => pushModal('CustomEvent', { customEvent })}+ size="icon"+ variant="ghost"+ />+ <Button+ aria-label={`Delete ${customEvent.name}`}+ icon={Trash2Icon}+ onClick={() =>+ showConfirm({+ title: 'Delete custom event',+ text: `Reports using "${customEvent.name}" will stop loading until you pick another event.`,+ onConfirm() {+ deletion.mutate({ id: customEvent.id, projectId });+ },+ })+ }+ size="icon"+ variant="ghost"+ />+ </div>+ ))}+ <div>+ <Button+ icon={PlusIcon}+ onClick={() => pushModal('CustomEvent')}+ variant="outline"+ >+ Add custom event+ </Button>+ </div>+ </WidgetBody>+ </Widget>+ );+}diff --git a/apps/start/src/components/ui/combobox-events.tsx b/apps/start/src/components/ui/combobox-events.tsxindex b3f5eabf0..30b54ecda 100644--- a/apps/start/src/components/ui/combobox-events.tsx+++ b/apps/start/src/components/ui/combobox-events.tsx@@ -1,5 +1,10 @@import { PopoverPortal } from '@radix-ui/react-popover';-import { CheckIcon, ChevronsUpDown, GanttChartIcon } from 'lucide-react';+import {+ CheckIcon,+ ChevronsUpDown,+ GanttChartIcon,+ LayersIcon,+} from 'lucide-react';import VirtualList from 'rc-virtual-list';import * as React from 'react';import { EventIcon } from '../events/event-icon';@@ -57,8 +62,23 @@ export interface ComboboxProps<T, TMultiple extends boolean = false> {disabled?: boolean;multiple?: TMultiple;maxDisplayItems?: number;+ /** Listed above the events; picking one calls `onSelectCustomEvent`. */+ customEvents?: CustomEventOption[];+ selectedCustomEventId?: string;+ onSelectCustomEvent?: (customEvent: CustomEventOption) => void;+}++interface CustomEventOption {+ id: string;+ name: string;}+type EventOption = RouterOutputs['chart']['events'][number];++type Row =+ | { key: string; kind: 'custom'; customEvent: CustomEventOption }+ | { key: string; kind: 'event'; item: EventOption };+export function ComboboxEvents<T extends string,TMultiple extends boolean = false,@@ -76,6 +96,9 @@ export function ComboboxEvents<items,multiple = false as TMultiple,maxDisplayItems = 2,+ customEvents = [],+ selectedCustomEventId,+ onSelectCustomEvent,}: ComboboxProps<T, TMultiple>) {const number = useNumber();const [open, setOpen] = React.useState(false);@@ -98,6 +121,24 @@ export function ComboboxEvents<selectedValues.length > 0 && selectedValues[0]? find(selectedValues[0]): null;+ const currentCustomEvent = customEvents.find(+ (customEvent) => customEvent.id === selectedCustomEventId+ );++ const matchesSearch = (name: string) =>+ search === '' || name.toLowerCase().includes(search.toLowerCase());+ const rows: Row[] = [+ ...customEvents+ .filter((customEvent) => matchesSearch(customEvent.name))+ .map((customEvent) => ({+ key: `custom:${customEvent.id}`,+ kind: 'custom' as const,+ customEvent,+ })),+ ...items+ .filter((item) => matchesSearch(item.name))+ .map((item) => ({ key: item.name, kind: 'event' as const, item })),+ ];const handleSelection = (selectedValue: string) => {if (multiple) {@@ -112,7 +153,27 @@ export function ComboboxEvents<}};+ const renderTriggerIcon = () => {+ if (currentCustomEvent) {+ return <LayersIcon className="mr-2 shrink-0" size={16} />;+ }+ if (current?.meta) {+ return (+ <EventIcon+ className="mr-2 shrink-0"+ meta={current.meta}+ name={current.name}+ size="xs"+ />+ );+ }+ return <GanttChartIcon className="mr-2 shrink-0" size={16} />;+ };+const renderTriggerContent = () => {+ if (currentCustomEvent) {+ return currentCustomEvent.name;+ }if (selectedValues.length === 0) {return placeholder;}@@ -144,16 +205,7 @@ export function ComboboxEvents<variant="outline"><div className="flex min-w-0 items-center">- {current?.meta ? (- <EventIcon- className="mr-2 shrink-0"- meta={current.meta}- name={current.name}- size="xs"- />- ) : (- <GanttChartIcon className="mr-2 shrink-0" size={16} />- )}+ {renderTriggerIcon()}<span className="overflow-hidden text-ellipsis whitespace-nowrap">{renderTriggerContent()}</span>@@ -179,30 +231,59 @@ export function ComboboxEvents<<CommandEmpty>Nothing selected</CommandEmpty><VirtualListclassName="w-[33em] max-sm:max-w-[100vw]"- data={items.filter((item) => {- if (search === '') {- return true;- }- return item.name.toLowerCase().includes(search.toLowerCase());- })}+ data={rows}height={300}itemHeight={32}- itemKey="value"+ itemKey="key">- {(item) => {+ {(row) => {+ if (row.kind === 'custom') {+ const isSelected =+ row.customEvent.id === selectedCustomEventId;+ return (+ <CommandItem+ className={cn(+ 'gap-4 p-4 py-2.5',+ isSelected && 'bg-accent'+ )}+ key={row.key}+ onSelect={() => {+ onSelectCustomEvent?.(row.customEvent);+ setOpen(false);+ }}+ value={row.key}+ >+ {isSelected ? (+ <CheckIcon className="h-4 w-4 flex-shrink-0" />+ ) : (+ <LayersIcon className="h-4 w-4 flex-shrink-0" />+ )}+ <span className="flex-1 truncate font-medium">+ {row.customEvent.name}+ </span>+ <span className="text-muted-foreground text-xs">+ Custom event+ </span>+ </CommandItem>+ );+ }+ const { item } = row;+ const isSelected =+ !currentCustomEvent &&+ selectedValues.includes(item.name as T);return (<CommandItemclassName={cn('gap-4 p-4 py-2.5',- selectedValues.includes(item.name as T) && 'bg-accent'+ isSelected && 'bg-accent')}- key={item.name}- onSelect={(currentValue) => {+ key={row.key}+ onSelect={() => {handleSelection(item.name);}}value={item.name}>- {selectedValues.includes(item.name as T) ? (+ {isSelected ? (<CheckIcon className="h-4 w-4 flex-shrink-0" />) : (<EventIcon meta={item.meta} name={item.name} size="sm" />diff --git a/apps/start/src/hooks/use-custom-events.ts b/apps/start/src/hooks/use-custom-events.tsnew file mode 100644index 000000000..06f751f68--- /dev/null+++ b/apps/start/src/hooks/use-custom-events.ts@@ -0,0 +1,13 @@+import { useQuery } from '@tanstack/react-query';+import { useTRPC } from '@/integrations/trpc/react';++export function useCustomEvents(projectId: string) {+ const trpc = useTRPC();+ const query = useQuery(+ trpc.customEvent.list.queryOptions(+ { projectId },+ { enabled: !!projectId, staleTime: 1000 * 60 * 10 }+ )+ );+ return query.data ?? [];+}diff --git a/apps/start/src/modals/custom-event.tsx b/apps/start/src/modals/custom-event.tsxnew file mode 100644index 000000000..d877663d3--- /dev/null+++ b/apps/start/src/modals/custom-event.tsx@@ -0,0 +1,146 @@+import type { IServiceCustomEvent } from '@openpanel/core';+import type { ICustomEventItem } from '@openpanel/core/modules/report/report.constants';+import { useMutation, useQueryClient } from '@tanstack/react-query';+import { XIcon } from 'lucide-react';+import { useState } from 'react';+import { toast } from 'sonner';+import { popModal } from '.';+import { ModalContent, ModalHeader } from './Modal/Container';+import { ButtonContainer } from '@/components/button-container';+import { FiltersBuilder } from '@/components/filters/FiltersBuilder';+import { InputWithLabel } from '@/components/forms/input-with-label';+import { Button } from '@/components/ui/button';+import { ComboboxEvents } from '@/components/ui/combobox-events';+import { Label } from '@/components/ui/label';+import { useAppParams } from '@/hooks/use-app-params';+import { useEventNames } from '@/hooks/use-event-names';+import { handleError, useTRPC } from '@/integrations/trpc/react';++interface CustomEventProps {+ customEvent?: Pick<IServiceCustomEvent, 'id' | 'name' | 'items'>;+}++export default function CustomEvent({ customEvent }: CustomEventProps = {}) {+ const { projectId } = useAppParams();+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const eventNames = useEventNames({ projectId, anyEvents: false });+ const [name, setName] = useState(customEvent?.name ?? '');+ const [items, setItems] = useState<ICustomEventItem[]>(+ customEvent?.items ?? []+ );++ const onSuccess = () => {+ toast('Custom event saved');+ queryClient.invalidateQueries(trpc.customEvent.list.pathFilter());+ queryClient.invalidateQueries(trpc.chart.pathFilter());+ popModal();+ };+ const create = useMutation(+ trpc.customEvent.create.mutationOptions({ onSuccess, onError: handleError })+ );+ const update = useMutation(+ trpc.customEvent.update.mutationOptions({ onSuccess, onError: handleError })+ );++ const selectedNames = items.map((item) => item.name);+ const setSelectedNames = (names: string[]) => {+ setItems(+ names.map(+ (eventName) =>+ items.find((item) => item.name === eventName) ?? {+ name: eventName,+ filters: [],+ }+ )+ );+ };+ const setItemFilters = (+ index: number,+ filters: ICustomEventItem['filters']+ ) => {+ setItems(+ items.map((item, itemIndex) =>+ itemIndex === index ? { ...item, filters } : item+ )+ );+ };++ const isValid = name.trim().length > 0 && items.length > 0;+ const isPending = create.isPending || update.isPending;++ return (+ <ModalContent>+ <ModalHeader+ text="Matches when any of the events below happens. Use it in reports like any other event."+ title={customEvent ? 'Edit custom event' : 'Create custom event'}+ />+ <form+ className="flex flex-col gap-4"+ onSubmit={(event) => {+ event.preventDefault();+ const input = { projectId, name, items };+ if (customEvent) {+ update.mutate({ ...input, id: customEvent.id });+ } else {+ create.mutate(input);+ }+ }}+ >+ <InputWithLabel+ label="Name"+ onChange={(event) => setName(event.target.value)}+ placeholder="eg. Used navigation"+ value={name}+ />+ <div className="col gap-2">+ <Label>Events</Label>+ <ComboboxEvents+ items={eventNames}+ multiple+ onChange={setSelectedNames}+ placeholder="Select events"+ searchable+ value={selectedNames}+ />+ {items.map((item, index) => (+ <div className="rounded-lg border bg-def-100 p-2" key={item.name}>+ <div className="row items-center justify-between gap-2">+ <span className="truncate font-medium">{item.name}</span>+ <Button+ aria-label={`Remove ${item.name}`}+ icon={XIcon}+ onClick={() =>+ setSelectedNames(+ selectedNames.filter(+ (eventName) => eventName !== item.name+ )+ )+ }+ size="icon"+ type="button"+ variant="ghost"+ />+ </div>+ <FiltersBuilder+ addLabel="Narrow with filter"+ categories={['event']}+ eventName={item.name}+ onChange={(filters) => setItemFilters(index, filters)}+ value={item.filters}+ />+ </div>+ ))}+ </div>+ <ButtonContainer>+ <Button onClick={() => popModal()} type="button" variant="outline">+ Cancel+ </Button>+ <Button disabled={!isValid} loading={isPending} type="submit">+ Save+ </Button>+ </ButtonContainer>+ </form>+ </ModalContent>+ );+}diff --git a/apps/start/src/modals/index.tsx b/apps/start/src/modals/index.tsxindex b96d6ec88..95ad5c416 100644--- a/apps/start/src/modals/index.tsx+++ b/apps/start/src/modals/index.tsx@@ -14,6 +14,7 @@ import Confirm from './confirm';import ConfirmDeleteAccount from './confirm-delete-account';import ConfirmDeleteOrganization from './confirm-delete-organization';import CreateInvite from './create-invite';+import CustomEvent from './custom-event';import DateRangerPicker from './date-ranger-picker';import DateTimePicker from './date-time-picker';import DisableTwoFactor from './disable-two-factor';@@ -56,6 +57,7 @@ const modals = {OverviewTopGenericModal,RequestPasswordReset,EditEvent,+ CustomEvent,EditMember,EventDetails,InsightDetails,diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.events.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.events.tsxindex ff2af952c..27ad20118 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.events.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.events.tsx@@ -1,6 +1,7 @@import { useQuery } from '@tanstack/react-query';import { createFileRoute } from '@tanstack/react-router';import FullPageLoadingState from '@/components/full-page-loading-state';+import { CustomEvents } from '@/components/settings/custom-events';import EditProjectFilters from '@/components/settings/edit-project-filters';import { useAppParams } from '@/hooks/use-app-params';import { useTRPC } from '@/integrations/trpc/react';@@ -26,5 +27,10 @@ function Component() {return <div>Project not found</div>;}- return <EditProjectFilters project={query.data} />;+ return (+ <div className="col gap-8">+ <CustomEvents />+ <EditProjectFilters project={query.data} />+ </div>+ );}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 221ecfd27..986959d44 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -138,6 +138,7 @@ export {getClientByIdCached,} from './modules/client/client.service';export { createConversationService } from './modules/conversation/conversation.service';+export type { IServiceCustomEvent } from './modules/custom-event/custom-event.service';export type {IServiceDashboard,IServiceDashboards,diff --git a/packages/core/src/modules/chart/chart.service.ts b/packages/core/src/modules/chart/chart.service.tsindex c301c4d20..18981a8c3 100644--- a/packages/core/src/modules/chart/chart.service.ts+++ b/packages/core/src/modules/chart/chart.service.ts@@ -4,6 +4,7 @@import { getChartPrevStartEndDate } from '@openpanel/shared';import { flatten, map, pipe, prop, sort, uniq } from 'ramda';import type { ServiceDeps, Services } from '../../services';+import { expandCustomEvents } from '../custom-event/custom-event.service';import { getEventMetasCached } from '../event/event.service';import { getSettingsForProject } from '../organization/organization.service';import {@@ -627,7 +628,11 @@ export async function getChartBucketProfiles(deps: ServiceDeps,input: ChartBucketProfilesRequest): Promise<IServiceProfile[]> {- const serie = input.series[0];+ const [serie] = await expandCustomEvents(+ deps,+ input.projectId,+ input.series.slice(0, 1)+ );if (!serie) {throw new Error('Series not found');}diff --git a/packages/core/src/modules/chart/conversion.service.ts b/packages/core/src/modules/chart/conversion.service.tsindex 4be02ceca..1f1a8c960 100644--- a/packages/core/src/modules/chart/conversion.service.ts+++ b/packages/core/src/modules/chart/conversion.service.ts@@ -1,12 +1,14 @@import { sql } from '@openpanel/db/src/clickhouse/sql';import { omit } from 'ramda';import type { ServiceDeps, Services } from '../../services';+import { expandCustomEvents } from '../custom-event/custom-event.service';import type { IReportInput } from '../report/report.constants';import { NOT_SET_VALUE } from '../report/report.constants';import { mergeGlobalFilters, onlyReportEvents } from '../report/src/series';import { JOINABLE_PROFILE_COLUMNS } from './chart.constants';import { compiledText } from './src/compiled';import { type ConversionGroup, conversionQuery } from './src/conversion.sql';+import { eventMatchCondition, eventNamesOf } from './src/event-match';import {buildInlineCohortJoin,collectBreakdownCohortIds,@@ -88,7 +90,10 @@ export async function getConversion(timezone,}: ConversionChartInput) {- const mergedSeries = mergeGlobalFilters(series, globalFilters);+ const mergedSeries = mergeGlobalFilters(+ await expandCustomEvents(deps, projectId, series),+ globalFilters+ );const funnelOptions = options?.type === 'funnel' ? options : undefined;const funnelGroup = funnelOptions?.funnelGroup;const funnelWindow =@@ -165,8 +170,9 @@ export async function getConversion(interval,group,funnelWindowSeconds: funnelWindow * SECONDS_PER_HOUR,- firstEventName: eventA.name,- secondEventName: eventB.name,+ firstEventMatch: eventMatchCondition(eventA, projectId, 'events'),+ secondEventMatch: eventMatchCondition(eventB, projectId, 'events'),+ eventNames: [...eventNamesOf(eventA), ...eventNamesOf(eventB)],firstEventWhere: whereA,secondEventWhere: whereB,breakdownSelects,diff --git a/packages/core/src/modules/chart/funnel.service.ts b/packages/core/src/modules/chart/funnel.service.tsindex 6b283835f..d44e88d6d 100644--- a/packages/core/src/modules/chart/funnel.service.ts+++ b/packages/core/src/modules/chart/funnel.service.ts@@ -2,6 +2,7 @@ import { ifNaN } from '@openpanel/shared';import { last, reverse } from 'ramda';import type { ServiceDeps, Services } from '../../services';import { toRangeBoundaryLiteral } from '../../shared/ch-dates';+import { expandCustomEvents } from '../custom-event/custom-event.service';import { getSettingsForProject } from '../organization/organization.service';import type {IChartBreakdown,@@ -112,7 +113,10 @@ export async function buildFunnelBase(): Promise<FunnelBase> {const breakdowns = knownFunnelBreakdowns(initialBreakdowns);const eventSeries = onlyReportEvents(- mergeGlobalFilters(series, globalFilters)+ mergeGlobalFilters(+ await expandCustomEvents(deps, projectId, series),+ globalFilters+ ));const cohortMetadata = await fetchCohortsMetadata(deps,diff --git a/packages/core/src/modules/chart/src/conversion.sql.ts b/packages/core/src/modules/chart/src/conversion.sql.tsindex e91213cef..3682e390e 100644--- a/packages/core/src/modules/chart/src/conversion.sql.ts+++ b/packages/core/src/modules/chart/src/conversion.sql.ts@@ -45,8 +45,11 @@ export interface ConversionQueryInput {group: ConversionGroup;/** Funnel window in seconds. */funnelWindowSeconds: number;- firstEventName: string;- secondEventName: string;+ /** Each step's event-name condition (`null` matches every event). */+ firstEventMatch: SqlFragment | null;+ secondEventMatch: SqlFragment | null;+ /** Names both steps read, for the row pre-filter; `'*'` disables it. */+ eventNames: string[];/** Compiled filters per step (`null` when the step has no filters). */firstEventWhere: SqlFragment | null;secondEventWhere: SqlFragment | null;@@ -61,10 +64,12 @@ export interface ConversionQueryInput {cohortJoins: SqlFragment[];}-function stepCondition(name: string, where: SqlFragment | null): SqlFragment {- return where- ? sql`(events.name = ${sql.string(name)} AND ${where})`- : sql`events.name = ${sql.string(name)}`;+function stepCondition(+ match: SqlFragment | null,+ where: SqlFragment | null+): SqlFragment {+ const parts = [match, where].filter((part) => part !== null);+ return parts.length > 0 ? sql`(${sql.join(parts, ' AND ')})` : sql`1`;}function profileJoin(@@ -104,8 +109,9 @@ export function conversionQuery(input: ConversionQueryInput): SqlFragment {interval,group,funnelWindowSeconds,- firstEventName,- secondEventName,+ firstEventMatch,+ secondEventMatch,+ eventNames,firstEventWhere,secondEventWhere,breakdownSelects,@@ -121,7 +127,6 @@ export function conversionQuery(input: ConversionQueryInput): SqlFragment {);const outerKeys = [sql`event_day`, ...breakdownAliases];const converted = sql`countIf(steps >= ${sql.uint64(CONVERTED_STEP_COUNT)})`;- const eventNames = [firstEventName, secondEventName];const dateRange = sql`created_at BETWEEN toDateTime(${sql.string(startDate)}) AND toDateTime(${sql.string(endDate)})`;const activeProfiles = profileIdsInWindow({projectId,@@ -153,15 +158,15 @@ export function conversionQuery(input: ConversionQueryInput): SqlFragment {${innerBreakdownSelects}windowFunnel(${sql.uint64(funnelWindowSeconds)})(toDateTime(created_at),- ${stepCondition(firstEventName, firstEventWhere)},- ${stepCondition(secondEventName, secondEventWhere)}+ ${stepCondition(firstEventMatch, firstEventWhere)},+ ${stepCondition(secondEventMatch, secondEventWhere)}) as stepsFROM ${sql.id(CHART_TABLE.events)}${profileJoin(profileJoinFields, projectId, activeProfiles)}${groupJoin(needsGroupArrayJoin, projectId)}${sql.join(cohortJoins, ' ')}WHERE project_id = ${sql.string(projectId)}- AND events.name IN ${sql.array('String', eventNames)}+ ${eventNames.includes('*') ? sql.empty : sql`AND events.name IN ${sql.array('String', eventNames)}`}AND ${dateRange}GROUP BY ${groupKey}${innerBreakdownGroupBy})) WHERE steps > 0 GROUP BY ${sql.join(outerKeys)} ORDER BY ${sql.join(outerKeys.map((key) => sql`${key} ASC`))}`;diff --git a/packages/core/src/modules/chart/src/engine/fetch.ts b/packages/core/src/modules/chart/src/engine/fetch.tsindex d841ba1a9..22c3cc60d 100644--- a/packages/core/src/modules/chart/src/engine/fetch.ts+++ b/packages/core/src/modules/chart/src/engine/fetch.ts@@ -158,6 +158,7 @@ function queryEvent(event: EventDefinition): IGetChartDataInput['event'] {filters: event.filters,displayName: event.displayName,property: event.property,+ anyOf: event.anyOf,};}diff --git a/packages/core/src/modules/chart/src/engine/normalize.ts b/packages/core/src/modules/chart/src/engine/normalize.tsindex 3c3273c0c..b05f249f2 100644--- a/packages/core/src/modules/chart/src/engine/normalize.ts+++ b/packages/core/src/modules/chart/src/engine/normalize.ts@@ -1,4 +1,5 @@import type { ServiceDeps } from '../../../../services';+import { expandCustomEvents } from '../../../custom-event/custom-event.service';import { getSettingsForProject } from '../../../organization/organization.service';import type {IChartEvent,@@ -58,12 +59,14 @@ export async function normalize((input as { series?: LegacySeriesItem[] }).series ??(input as { events?: LegacySeriesItem[] }).events ??[];+ const series = await expandCustomEvents(+ deps,+ input.projectId,+ rawSeries.map(toSeriesDefinition)+ );return {...input,- series: mergeGlobalFilters(- rawSeries.map(toSeriesDefinition),- input.globalFilters- ),+ series: mergeGlobalFilters(series, input.globalFilters),startDate,endDate,timezone,diff --git a/packages/core/src/modules/chart/src/event-match.ts b/packages/core/src/modules/chart/src/event-match.tsnew file mode 100644index 000000000..c957ce1d4--- /dev/null+++ b/packages/core/src/modules/chart/src/event-match.ts@@ -0,0 +1,56 @@+import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import type { IChartEvent } from '../../report/report.constants';+import { getEventFiltersWhereClause } from './filter-where';++type MatchableEvent = Pick<IChartEvent, 'name' | 'anyOf'>;++/** The event names a series reads; `['*']` for every event. */+export function eventNamesOf(event: MatchableEvent): string[] {+ if (event.anyOf?.length) {+ return [...new Set(event.anyOf.map((item) => item.name))];+ }+ return [event.name];+}++/**+ * The WHERE condition selecting a series' events, or null for every event.+ * ClickHouse prunes with the `name` bloom index through the OR, so a custom+ * event needs no extra `name IN (...)` guard.+ */+export function eventMatchCondition(+ event: MatchableEvent,+ projectId: string,+ eventsAlias?: string+): SqlFragment | null {+ const nameColumn = sql.id(eventsAlias ? `${eventsAlias}.name` : 'name');+ if (!event.anyOf?.length) {+ return event.name === '*'+ ? null+ : sql`${nameColumn} = ${sql.string(event.name)}`;+ }++ const unfilteredNames = event.anyOf+ .filter((item) => item.filters.length === 0)+ .map((item) => item.name);+ const alternatives = event.anyOf+ .filter((item) => item.filters.length > 0)+ .map((item) => {+ const filters = Object.values(+ getEventFiltersWhereClause(item.filters, projectId, eventsAlias)+ );+ return sql`(${sql.join(+ [sql`${nameColumn} = ${sql.string(item.name)}`, ...filters],+ ' AND '+ )})`;+ });+ if (unfilteredNames.length > 0) {+ alternatives.unshift(+ sql`${nameColumn} IN ${sql.array('String', unfilteredNames)}`+ );+ }+ const [first, ...rest] = alternatives;+ if (first && rest.length === 0) {+ return first;+ }+ return sql`(${sql.join(alternatives, ' OR ')})`;+}diff --git a/packages/core/src/modules/chart/src/funnel.sql.test.ts b/packages/core/src/modules/chart/src/funnel.sql.test.tsindex 1db54007d..136a4413f 100644--- a/packages/core/src/modules/chart/src/funnel.sql.test.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.test.ts@@ -448,3 +448,35 @@ describe('funnel.sql / profile-property narrowing', () => {);});});++describe('funnel.sql — custom event steps', () => {+ const customEventStep = event({+ id: 'A',+ name: 'Used navigation',+ anyOf: [+ { name: 'menu_open', filters: [] },+ { name: 'tab_switch', filters: [] },+ {+ name: 'screen_view',+ filters: [{ name: 'path', operator: 'is', value: ['/nav'] }],+ },+ ],+ });+ const series = [customEventStep, event({ id: 'B', name: 'sign_up' })];++ it('scans every step name with one IN and keeps per-item filters inside the step', async () => {+ const { text } = render(await chartStatement({ series }));+ expect(text).toContain(+ "events.name IN ('menu_open', 'tab_switch', 'screen_view', 'sign_up')"+ );+ expect(text).toContain(+ "(events.name IN ('menu_open', 'tab_switch') OR (events.name = 'screen_view' AND "+ );+ expect(text).not.toContain("events.name = 'Used navigation'");+ });++ it('parses and resolves', async () => {+ await explain(await chartStatement({ series }));+ await explain(await profilesStatement({ series }));+ });+});diff --git a/packages/core/src/modules/chart/src/funnel.sql.ts b/packages/core/src/modules/chart/src/funnel.sql.tsindex 65db59c56..8890f4186 100644--- a/packages/core/src/modules/chart/src/funnel.sql.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.ts@@ -17,6 +17,7 @@ import type {} from '../../report/report.constants';import { JOINABLE_PROFILE_COLUMNS } from '../chart.constants';import { compiledText, fragmentWithProfileRefs } from './compiled';+import { eventMatchCondition, eventNamesOf } from './event-match';import {buildGroupsQuery,buildInlineCohortJoin,@@ -120,7 +121,7 @@ export function knownFunnelBreakdowns(}/**- * One `<filters> AND events.name = <name>` per step. Exported because each+ * One `<filters> AND <event match>` per step. Exported because each* step's complete condition has to appear twice — inside windowFunnel and in* the row-level pre-filter — and funnel.sql.test.ts counts exactly that.*/@@ -139,10 +140,9 @@ export function funnelStepConditions(const filters = Object.values(getEventFiltersWhereClause(event.filters, projectId, 'events')).map((clause) => fragmentWithProfileRefs(clause, profilePropertyKeys));- return sql.join(- [...filters, sql`events.name = ${sql.string(event.name)}`],- ' AND '- );+ const eventMatch = eventMatchCondition(event, projectId, 'events');+ const parts = eventMatch ? [...filters, eventMatch] : filters;+ return parts.length > 0 ? sql.join(parts, ' AND ') : sql`1`;});}@@ -393,7 +393,7 @@ export function funnelBase(input: FunnelBaseInput): FunnelBase {});const dateRange = sql`created_at BETWEEN toDateTime(${sql.string(input.startDate)}) AND toDateTime(${sql.string(input.endDate)})`;- const eventNames = eventSeries.map((event) => event.name);+ const eventNames = eventSeries.flatMap(eventNamesOf);const columns = profileCteColumns(input, profileFilters, profileKeys);const activeProfiles = profileIdsInWindow({projectId,@@ -432,7 +432,7 @@ export function funnelBase(input: FunnelBaseInput): FunnelBase {' OR ')})`;- const funnelCte = sql`SELECT ${sql.join(cteSelects)} FROM ${sql.id(CHART_TABLE.events)}${profileJoin}${groupJoin}${cohortJoins} WHERE project_id = ${sql.string(projectId)} AND ${dateRange} AND events.name IN ${sql.array('String', eventNames)} AND ${stepPreFilter} GROUP BY ${sql.join(groupByKeys)}`;+ const funnelCte = sql`SELECT ${sql.join(cteSelects)} FROM ${sql.id(CHART_TABLE.events)}${profileJoin}${groupJoin}${cohortJoins} WHERE project_id = ${sql.string(projectId)} AND ${dateRange}${eventNames.includes('*') ? sql.empty : sql` AND events.name IN ${sql.array('String', eventNames)}`} AND ${stepPreFilter} GROUP BY ${sql.join(groupByKeys)}`;const groupsCte = needsGroupArrayJoin? sql`_g AS (${buildGroupsQuery(projectId)}), `diff --git a/packages/core/src/modules/chart/src/sql.test.ts b/packages/core/src/modules/chart/src/sql.test.tsindex c33003705..01735ef8d 100644--- a/packages/core/src/modules/chart/src/sql.test.ts+++ b/packages/core/src/modules/chart/src/sql.test.ts@@ -674,8 +674,9 @@ describe('profile join window', () => {interval: 'day',group: 'profile_id',funnelWindowSeconds: 3600,- firstEventName: 'screen_view',- secondEventName: 'sign_up',+ firstEventMatch: sql`events.name = ${sql.string('screen_view')}`,+ secondEventMatch: sql`events.name = ${sql.string('sign_up')}`,+ eventNames: ['screen_view', 'sign_up'],firstEventWhere: null,secondEventWhere: null,breakdownSelects: [sql`${expression} as b_0`],@@ -800,3 +801,39 @@ describe('chartBucketProfilesQuery', () => {await explain(rendered);});});++describe('custom event series', () => {+ const customEvent = event({+ name: 'Used navigation',+ anyOf: [+ { name: 'menu_open', filters: [] },+ {+ name: 'screen_view',+ filters: [{ name: 'path', operator: 'is', value: ['/nav'] }],+ },+ ],+ });++ it('matches any item, each with its own filters', async () => {+ const rendered = await getChartSql({+ event: customEvent,+ breakdowns: [breakdown('country')],+ ...base,+ });+ expect(rendered.text).toContain(+ "(e.name IN ('menu_open') OR (e.name = 'screen_view' AND path = '/nav'))"+ );+ expect(rendered.text).toContain("'Used navigation' as label_0");+ await explain(rendered);+ });++ it('aggregate chart parses and resolves', async () => {+ await explain(+ await getAggregateChartSql({+ event: customEvent,+ breakdowns: [],+ ...base,+ })+ );+ });+});diff --git a/packages/core/src/modules/chart/src/sql.ts b/packages/core/src/modules/chart/src/sql.tsindex 79dbe4413..58761f4d4 100644--- a/packages/core/src/modules/chart/src/sql.ts+++ b/packages/core/src/modules/chart/src/sql.ts@@ -20,6 +20,7 @@ import type {} from '../../report/report.constants';import { compiledText, fragmentWithProfileRefs } from './compiled';import { formatClickhouseDate } from './dates';+import { eventMatchCondition, eventNamesOf } from './event-match';import {buildAllCohortsLabelExpr,buildAllCohortsMembershipQuery,@@ -78,7 +79,7 @@ const PROFILE_COLUMNS = [export type ChartQueryEvent = Pick<IChartEvent,- 'name' | 'segment' | 'filters' | 'property'+ 'name' | 'segment' | 'filters' | 'property' | 'anyOf'>;/** Breakdowns after `resolveChartBreakdowns`, plus the cohort rows they need. */@@ -301,11 +302,10 @@ function chartBody({where.projectId = sql`project_id = ${sql.string(projectId)}`;const select: Parts = {};- if (event.name !== '*') {- select.label_0 = sql`${sql.string(event.name)} as label_0`;- where.eventName = sql`e.name = ${sql.string(event.name)}`;- } else {- select.label_0 = sql`'*' as label_0`;+ select.label_0 = sql`${sql.string(event.name)} as label_0`;+ const eventMatch = eventMatchCondition(event, projectId, EVENTS_ALIAS);+ if (eventMatch) {+ where.eventName = eventMatch;}const dateRange = dateRangeWhere(startDate, endDate);Object.assign(where, dateRange);@@ -330,7 +330,7 @@ function chartBody({projectId,profileIdsInWindow({projectId,- eventNames: [event.name],+ eventNames: eventNamesOf(event),window: Object.values(dateRange),}));@@ -655,7 +655,7 @@ export interface ChartBucketProfilesInput {/** Bucket start as a `YYYY-MM-DD HH:mm:ss` string. */bucketDate: string;interval: IInterval;- event: Pick<IChartEvent, 'name' | 'filters'>;+ event: Pick<IChartEvent, 'name' | 'filters' | 'anyOf'>;breakdowns: Record<string, string>;/** Cap on the ids handed to the drill-down modal. */limit: number;@@ -711,8 +711,9 @@ export function chartBucketProfilesQuery(where.projectId = sql`project_id = ${sql.string(projectId)}`;const dateRange = bucketEquals(interval, bucketDate);where.dateRange = dateRange;- if (event.name !== '*') {- where.eventName = sql`name = ${sql.string(event.name)}`;+ const eventMatch = eventMatchCondition(event, projectId);+ if (eventMatch) {+ where.eventName = eventMatch;}const joins: Parts = {};@@ -726,7 +727,7 @@ export function chartBucketProfilesQuery(const fields = sql.join(profileFieldsToSelect(profileRefs), ', ');const activeProfiles = profileIdsInWindow({projectId,- eventNames: [event.name],+ eventNames: eventNamesOf(event),window: [dateRange],});joins.profiles = sql`LEFT ANY JOIN (SELECT id, ${fields} FROM ${sql.id(CHART_TABLE.profiles)} WHERE project_id = ${sql.string(projectId)} AND ${activeProfiles} GROUP BY id) as profile on profile.id = profile_id`;diff --git a/packages/core/src/modules/chart/src/sql.versions.test.ts b/packages/core/src/modules/chart/src/sql.versions.test.tsindex 6f41499a5..488397399 100644--- a/packages/core/src/modules/chart/src/sql.versions.test.ts+++ b/packages/core/src/modules/chart/src/sql.versions.test.ts@@ -234,8 +234,9 @@ describe('drill-down, funnel and conversion', () => {interval: 'day',group: 'profile_id',funnelWindowSeconds: 7 * 24 * 3600,- firstEventName: 'screen_view',- secondEventName: 'signup',+ firstEventMatch: sql`events.name = ${sql.string('screen_view')}`,+ secondEventMatch: sql`events.name = ${sql.string('signup')}`,+ eventNames: ['screen_view', 'signup'],firstEventWhere: null,secondEventWhere: null,breakdownSelects: [sql`${expression} as b_0`],diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.tsindex 54a0fae8e..c5e1e4d4c 100644--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts@@ -40,6 +40,7 @@ function stubJobCtx(organization: {} as Services['organization'],onboarding: {} as Services['onboarding'],session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],diff --git a/packages/core/src/modules/custom-event/custom-event.constants.ts b/packages/core/src/modules/custom-event/custom-event.constants.tsnew file mode 100644index 000000000..af1466772--- /dev/null+++ b/packages/core/src/modules/custom-event/custom-event.constants.ts@@ -0,0 +1,19 @@+import { z } from 'zod';+import { zCustomEventItem } from '../report/report.constants';++export const CUSTOM_EVENT_NAME_MAX_LENGTH = 100;+export const CUSTOM_EVENT_MAX_ITEMS = 200;++export const zCustomEventInput = z.object({+ projectId: z.string(),+ name: z.string().trim().min(1).max(CUSTOM_EVENT_NAME_MAX_LENGTH),+ items: z.array(zCustomEventItem).min(1).max(CUSTOM_EVENT_MAX_ITEMS),+});++export type ICustomEventInput = z.infer<typeof zCustomEventInput>;++export const zCustomEventUpdate = zCustomEventInput.extend({+ id: z.string().uuid(),+});++export type ICustomEventUpdate = z.infer<typeof zCustomEventUpdate>;diff --git a/packages/core/src/modules/custom-event/custom-event.rpc.ts b/packages/core/src/modules/custom-event/custom-event.rpc.tsnew file mode 100644index 000000000..1e305f1a3--- /dev/null+++ b/packages/core/src/modules/custom-event/custom-event.rpc.ts@@ -0,0 +1,52 @@+import { z } from 'zod';+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';+import {+ zCustomEventInput,+ zCustomEventUpdate,+} from './custom-event.constants';++export const customEventRouter = createTRPCRouter({+ list: protectedProcedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ input, ctx }) => {+ await ctx.services.auth.requireProjectAccess({+ userId: ctx.session.userId,+ projectId: input.projectId,+ level: 'read',+ });+ return ctx.services.customEvent.list(input.projectId);+ }),++ create: protectedProcedure+ .input(zCustomEventInput)+ .mutation(async ({ input, ctx }) => {+ await ctx.services.auth.requireProjectAccess({+ userId: ctx.session.userId,+ projectId: input.projectId,+ level: 'write',+ });+ return ctx.services.customEvent.create(input);+ }),++ update: protectedProcedure+ .input(zCustomEventUpdate)+ .mutation(async ({ input, ctx }) => {+ await ctx.services.auth.requireProjectAccess({+ userId: ctx.session.userId,+ projectId: input.projectId,+ level: 'write',+ });+ return ctx.services.customEvent.update(input);+ }),++ delete: protectedProcedure+ .input(z.object({ id: z.string().uuid(), projectId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ await ctx.services.auth.requireProjectAccess({+ userId: ctx.session.userId,+ projectId: input.projectId,+ level: 'write',+ });+ return ctx.services.customEvent.delete(input);+ }),+});diff --git a/packages/core/src/modules/custom-event/custom-event.service.test.ts b/packages/core/src/modules/custom-event/custom-event.service.test.tsnew file mode 100644index 000000000..f33e60003--- /dev/null+++ b/packages/core/src/modules/custom-event/custom-event.service.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it, mock } from 'bun:test';+import type { ServiceDeps } from '../../services';+import type { IChartSeries } from '../report/report.constants';+import { expandCustomEvents } from './custom-event.service';++const CUSTOM_EVENT_ID = '7f1c2a54-0000-4000-8000-000000000001';+const items = [+ { name: 'menu_open', filters: [] },+ {+ name: 'screen_view',+ filters: [{ name: 'path', operator: 'is' as const, value: ['/nav'] }],+ },+];++function depsWith(rows: unknown[]) {+ const findMany = mock(async () => rows);+ const deps = { db: { customEvent: { findMany } } } as unknown as ServiceDeps;+ return { deps, findMany };+}++// Unique per test: the list is cached in Redis by project id.+const projectId = () => `custom-event-test-${crypto.randomUUID()}`;++describe('expandCustomEvents', () => {+ it('passes series through without a lookup when none references a custom event', async () => {+ const { deps, findMany } = depsWith([]);+ const series: IChartSeries = [+ { type: 'event', name: 'sign_up', segment: 'event', filters: [] },+ { type: 'formula', formula: 'A*2' },+ ];++ expect(await expandCustomEvents(deps, projectId(), series)).toBe(series);+ expect(findMany).not.toHaveBeenCalled();+ });++ it('replaces the reference with the current name and items', async () => {+ const { deps, findMany } = depsWith([+ { id: CUSTOM_EVENT_ID, name: 'Used navigation', items },+ ]);+ const [expanded] = await expandCustomEvents(deps, projectId(), [+ {+ type: 'event',+ name: 'Old name',+ customEventId: CUSTOM_EVENT_ID,+ segment: 'user',+ filters: [],+ },+ ]);++ expect(findMany).toHaveBeenCalledTimes(1);+ expect(expanded).toMatchObject({+ name: 'Used navigation',+ anyOf: items,+ segment: 'user',+ });+ });++ it('fails loudly when the custom event was deleted', async () => {+ const { deps } = depsWith([]);+ const expansion = expandCustomEvents(deps, projectId(), [+ {+ type: 'event',+ name: 'Gone',+ customEventId: CUSTOM_EVENT_ID,+ segment: 'event',+ filters: [],+ },+ ]);++ await expect(expansion).rejects.toThrow(+ 'Custom event "Gone" no longer exists'+ );+ });+});diff --git a/packages/core/src/modules/custom-event/custom-event.service.ts b/packages/core/src/modules/custom-event/custom-event.service.tsnew file mode 100644index 000000000..94f89e199--- /dev/null+++ b/packages/core/src/modules/custom-event/custom-event.service.ts@@ -0,0 +1,138 @@+import type { CustomEvent } from '@openpanel/db/src/prisma-client';+import { cacheablePerDeps } from '../../cacheable-per-deps';+import { TRPCBadRequestError, TRPCNotFoundError } from '../../rpc/errors';+import type { ServiceDeps, Services } from '../../services';+import type { IChartSeries } from '../report/report.constants';+import type {+ ICustomEventInput,+ ICustomEventUpdate,+} from './custom-event.constants';++export type IServiceCustomEvent = CustomEvent;++const CUSTOM_EVENTS_CACHE_NAME = 'getCustomEvents';+const CUSTOM_EVENTS_CACHE_SECONDS = 60 * 5;++function listCustomEvents(+ deps: ServiceDeps,+ projectId: string+): Promise<CustomEvent[]> {+ return deps.db.customEvent.findMany({+ where: { projectId },+ orderBy: { name: 'asc' },+ });+}++const listCustomEventsCached = cacheablePerDeps(+ CUSTOM_EVENTS_CACHE_NAME,+ listCustomEvents,+ CUSTOM_EVENTS_CACHE_SECONDS+);++const UNIQUE_VIOLATION = 'P2002';++/** Turns the `(projectId, name)` unique index firing into a message the user can act on. */+async function withUniqueName<T>(name: string, write: Promise<T>): Promise<T> {+ try {+ return await write;+ } catch (error) {+ const isUniqueViolation =+ typeof error === 'object' &&+ error !== null &&+ (error as { code?: unknown }).code === UNIQUE_VIOLATION;+ if (isUniqueViolation) {+ throw new TRPCBadRequestError(+ `A custom event named "${name}" already exists`+ );+ }+ throw error;+ }+}++async function createCustomEvent(+ deps: ServiceDeps,+ input: ICustomEventInput+): Promise<CustomEvent> {+ const created = await withUniqueName(+ input.name,+ deps.db.customEvent.create({ data: input })+ );+ await listCustomEventsCached.clear(deps, input.projectId);+ return created;+}++async function updateCustomEvent(+ deps: ServiceDeps,+ { id, projectId, name, items }: ICustomEventUpdate+): Promise<CustomEvent> {+ const updated = await withUniqueName(+ name,+ deps.db.customEvent.update({+ where: { id, projectId },+ data: { name, items },+ })+ );+ await listCustomEventsCached.clear(deps, projectId);+ return updated;+}++async function deleteCustomEvent(+ deps: ServiceDeps,+ input: { id: string; projectId: string }+): Promise<void> {+ await deps.db.customEvent.delete({+ where: { id: input.id, projectId: input.projectId },+ });+ await listCustomEventsCached.clear(deps, input.projectId);+}++/**+ * Resolves every series that references a custom event to its current+ * definition. Series without one pass through untouched and cost no lookup.+ */+export async function expandCustomEvents(+ deps: ServiceDeps,+ projectId: string,+ series: IChartSeries+): Promise<IChartSeries> {+ const referencesCustomEvent = series.some(+ (item) => item.type === 'event' && item.customEventId+ );+ if (!referencesCustomEvent) {+ return series;+ }++ const customEvents = await listCustomEventsCached(deps, projectId);+ return series.map((item) => {+ if (item.type !== 'event' || !item.customEventId) {+ return item;+ }+ const customEvent = customEvents.find(+ (candidate) => candidate.id === item.customEventId+ );+ if (!customEvent) {+ throw new TRPCNotFoundError(+ `Custom event "${item.name}" no longer exists`+ );+ }+ return { ...item, name: customEvent.name, anyOf: customEvent.items };+ });+}++export function createCustomEventService(+ deps: ServiceDeps,+ _services: () => Services+) {+ return {+ list: (projectId: string): Promise<CustomEvent[]> =>+ listCustomEventsCached(deps, projectId),+ create: (input: ICustomEventInput): Promise<CustomEvent> =>+ createCustomEvent(deps, input),+ update: (input: ICustomEventUpdate): Promise<CustomEvent> =>+ updateCustomEvent(deps, input),+ delete: (input: { id: string; projectId: string }): Promise<void> =>+ deleteCustomEvent(deps, input),+ expand: (projectId: string, series: IChartSeries): Promise<IChartSeries> =>+ expandCustomEvents(deps, projectId, series),+ };+}diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.tsindex b52a5fd85..e732af7d8 100644--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts@@ -40,6 +40,7 @@ function stubJobCtx(organization: {} as Services['organization'],onboarding: {} as Services['onboarding'],session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],@@ -172,6 +173,7 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', asyncorganization: {} as Services['organization'],onboarding: {} as Services['onboarding'],session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.tsindex 99252136b..71f65d72a 100644--- a/packages/core/src/modules/import/import.jobs.test.ts+++ b/packages/core/src/modules/import/import.jobs.test.ts@@ -39,6 +39,7 @@ function stubJobCtx(organization: {} as Services['organization'],onboarding: {} as Services['onboarding'],session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.tsindex ee261bd51..87e4dfb3d 100644--- a/packages/core/src/modules/insight/insight.jobs.test.ts+++ b/packages/core/src/modules/insight/insight.jobs.test.ts@@ -44,6 +44,7 @@ function stubJobCtx(organization: {} as Services['organization'],onboarding: {} as Services['onboarding'],session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],@@ -159,6 +160,7 @@ test('insightsDaily fans out one insightsProject enqueue per candidate, jobId deorganization: {} as Services['organization'],onboarding: {} as Services['onboarding'],session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],diff --git a/packages/core/src/modules/notification/notification.jobs.test.ts b/packages/core/src/modules/notification/notification.jobs.test.tsindex 61bee8e4f..4a59068c9 100644--- a/packages/core/src/modules/notification/notification.jobs.test.ts+++ b/packages/core/src/modules/notification/notification.jobs.test.ts@@ -40,6 +40,7 @@ function stubJobCtx(organization: {} as Services['organization'],onboarding: {} as Services['onboarding'],session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts b/packages/core/src/modules/onboarding/onboarding.jobs.test.tsindex 30107a6ba..7a4739e2b 100644--- a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts@@ -41,6 +41,7 @@ function stubJobCtx(organization: {} as Services['organization'],onboarding: onboarding as ReturnType<typeof createOnboardingService>,session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.tsindex d101a8a60..8783b3bc2 100644--- a/packages/core/src/modules/organization/organization.jobs.test.ts+++ b/packages/core/src/modules/organization/organization.jobs.test.ts@@ -40,6 +40,7 @@ function stubJobCtx(organization: organization as ReturnType<typeof createOrganizationService>,onboarding: {} as Services['onboarding'],session: {} as Services['session'],+ customEvent: {} as Services['customEvent'],event: {} as Services['event'],profile: {} as Services['profile'],group: {} as Services['group'],diff --git a/packages/core/src/modules/report/report.constants.ts b/packages/core/src/modules/report/report.constants.tsindex 350d5beb3..4d4f9809c 100644--- a/packages/core/src/modules/report/report.constants.ts+++ b/packages/core/src/modules/report/report.constants.ts@@ -713,6 +713,30 @@ export const zChartEventSegment = z.default('event').describe('Defines how the event data should be segmented or aggregated');+const JOINED_FILTER_PREFIXES = ['profile.', 'group.'];+const COHORT_OPERATORS: string[] = ['inCohort', 'notInCohort'];++// Item filters compile inline on the events row; profile, group and cohort+// filters need joins the chart builds per series, so they stay series-level.+const zCustomEventItemFilter = zChartEventFilter.refine(+ (filter) =>+ !(+ JOINED_FILTER_PREFIXES.some((prefix) => filter.name.startsWith(prefix)) ||+ COHORT_OPERATORS.includes(filter.operator)+ ),+ 'Custom event filters may only use event properties'+);++export const zCustomEventItem = z.object({+ name: z.string().min(1).describe('An event name as tracked'),+ filters: z+ .array(zCustomEventItemFilter)+ .default([])+ .describe('Filters that narrow this event, AND-ed together'),+});++export type ICustomEventItem = z.infer<typeof zCustomEventItem>;+export const zChartEvent = z.object({id: z.string()@@ -734,6 +758,16 @@ export const zChartEvent = z.object({.array(zChartEventFilter).default([]).describe('Filters applied specifically to this event'),+ customEventId: z+ .string()+ .optional()+ .describe(+ 'A saved custom event this series counts instead of `name`; resolved to `anyOf` at query time'+ ),+ anyOf: z+ .array(zCustomEventItem)+ .optional()+ .describe('Matches any of these events, each with its own filters'),});export const zChartFormula = z.object({diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.tsindex eafcd6e4c..1a82a7403 100644--- a/packages/core/src/rpc.router.ts+++ b/packages/core/src/rpc.router.ts@@ -7,6 +7,7 @@ import { chartRouter } from './modules/chart/chart.rpc';import { clientRouter } from './modules/client/client.rpc';import { cohortRouter } from './modules/cohort/cohort.rpc';import { conversationRouter } from './modules/conversation/conversation.rpc';+import { customEventRouter } from './modules/custom-event/custom-event.rpc';import { dashboardRouter } from './modules/dashboard/dashboard.rpc';import { emailRouter } from './modules/email/email.rpc';import { eventRouter } from './modules/event/event.rpc';@@ -54,6 +55,7 @@ export const appRouter = createTRPCRouter({integration: integrationRouter,subscription: subscriptionRouter,session: sessionRouter,+ customEvent: customEventRouter,event: eventRouter,profile: profileRouter,group: groupRouter,diff --git a/packages/core/src/services.test.ts b/packages/core/src/services.test.tsindex e052a3d1c..bd34475e6 100644--- a/packages/core/src/services.test.ts+++ b/packages/core/src/services.test.ts@@ -6,7 +6,7 @@ import { expect, test } from 'bun:test';import type { Logger } from './logger';import { createServices, type ServiceDeps } from './services';-const SERVICE_COUNT = 36;+const SERVICE_COUNT = 37;function stubLogger(): Logger {const noop = () => undefined;diff --git a/packages/core/src/services.ts b/packages/core/src/services.tsindex d3ce7880a..d59f54c09 100644--- a/packages/core/src/services.ts+++ b/packages/core/src/services.ts@@ -9,6 +9,7 @@ import { createSankeyService } from './modules/chart/sankey.service';import { createClientService } from './modules/client/client.service';import { createCohortService } from './modules/cohort/cohort.service';import { createConversationService } from './modules/conversation/conversation.service';+import { createCustomEventService } from './modules/custom-event/custom-event.service';import { createDashboardService } from './modules/dashboard/dashboard.service';import { createEventService } from './modules/event/event.service';import { createExportService } from './modules/export/export.service';@@ -67,6 +68,7 @@ export interface Services {onboarding: ReturnType<typeof createOnboardingService>;notification: ReturnType<typeof createNotificationService>;session: ReturnType<typeof createSessionService>;+ customEvent: ReturnType<typeof createCustomEventService>;event: ReturnType<typeof createEventService>;profile: ReturnType<typeof createProfileService>;group: ReturnType<typeof createGroupService>;@@ -116,6 +118,7 @@ export function createServices(deps: ServiceDeps): Services {onboarding: createOnboardingService(deps, services),notification: createNotificationService(deps, services),session: createSessionService(deps, services),+ customEvent: createCustomEventService(deps, services),event: createEventService(deps, services),profile: createProfileService(deps, services),group: createGroupService(deps, services),diff --git a/packages/db/prisma/migrations/20261017140000_custom_events/migration.sql b/packages/db/prisma/migrations/20261017140000_custom_events/migration.sqlnew file mode 100644index 000000000..3bee83f55--- /dev/null+++ b/packages/db/prisma/migrations/20261017140000_custom_events/migration.sql@@ -0,0 +1,15 @@+-- A saved union of events (each optionally narrowed by filters) that reports reference by id.+CREATE TABLE "custom_events" (+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),+ "name" TEXT NOT NULL,+ "items" JSONB NOT NULL,+ "projectId" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "custom_events_pkey" PRIMARY KEY ("id")+);++CREATE UNIQUE INDEX "custom_events_projectId_name_key" ON "custom_events"("projectId", "name");++ALTER TABLE "custom_events" ADD CONSTRAINT "custom_events_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex ee418c502..5e6e69a91 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -285,6 +285,7 @@ model Project {shareReports ShareReport[]shareWidgets ShareWidget[]meta EventMeta[]+ customEvents CustomEvent[]references Reference[]access ProjectAccess[]notificationRules NotificationRule[]@@ -566,6 +567,21 @@ model EventMeta {@@map("event_meta")}+model CustomEvent {+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid+ name String+ /// [IPrismaCustomEventItems]+ items Json+ projectId String+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)++ createdAt DateTime @default(now())+ updatedAt DateTime @default(now()) @updatedAt++ @@unique([projectId, name])+ @@map("custom_events")+}+model Reference {id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuidtitle Stringdiff --git a/packages/db/src/types.ts b/packages/db/src/types.tsindex c52879fd4..ca9a78dca 100644--- a/packages/db/src/types.ts+++ b/packages/db/src/types.ts@@ -12,7 +12,10 @@ import type { IIntegrationConfig } from '@openpanel/core/modules/integration/intimport type { INotificationRuleConfig } from '@openpanel/core/modules/notification/notification.constants';import type { IProjectAccessGrant } from '@openpanel/core/modules/organization/organization.constants';import type { IProjectFilters } from '@openpanel/core/modules/project/project.constants';-import type { IWidgetOptions } from '@openpanel/core/modules/report/report.constants';+import type {+ ICustomEventItem,+ IWidgetOptions,+} from '@openpanel/core/modules/report/report.constants';declare global {namespace PrismaJson {@@ -28,6 +31,7 @@ declare global {type IPrismaClickhouseProfile = IClickhouseProfile;type IPrismaClickhouseBotEvent = IClickhouseBotEvent;type IPrismaCohortDefinition = CohortDefinition;+ type IPrismaCustomEventItems = ICustomEventItem[];// Each ChatMessage row stores one Better Agent `ConversationItem`// (message, tool call, or tool result) as JSON. Typed as `unknown[]`// here to avoid pulling `@better-agent/core` into @openpanel/db's