OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M7-005): overview + pages services + trpc overview into core
ralphb6e783d3ec08
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 5567d8eb1..194b9a3cb 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -369,6 +369,56 @@ export {getUserFlowCore,zGetSankeyInput,} from './modules/chart/sankey.service';+// Dissolved from @openpanel/db's services/overview.service.ts ++// pages.service.ts (M7-005) — packages/trpc's overview/event routers,+// apps/api's insights controller, apps/worker's win-back job and the+// mcp/assistant tools call these directly. packages/db/src/services/+// overview.service.ts and pages.service.ts stay re-export shims.+export type {+ IGetMapDataInput,+ IGetMetricsInput,+ IGetTopEntryExitInput,+ IGetTopEventsInput,+ IGetTopGenericInput,+ IGetTopGenericSeriesInput,+ IGetTopLinkOutInput,+ IGetTopPagesInput,+ IGetUserJourneyInput,+ ILiveData,+ ILiveMinuteCount,+ SegmentDailyPoint,+ TrafficColumn,+} from './modules/overview/overview.service';+export {+ getAnalyticsOverviewCore,+ getSegmentDailySeriesCore,+ getTrafficBreakdownCore,+ OverviewService,+ overviewService,+ zGetMapDataInput,+ zGetMetricsInput,+ zGetTopEntryExitInput,+ zGetTopEventsInput,+ zGetTopGenericInput,+ zGetTopGenericSeriesInput,+ zGetTopLinkOutInput,+ zGetTopPagesInput,+ zGetUserJourneyInput,+} from './modules/overview/overview.service';+export type {+ IGetPagesInput,+ IPageConversionRow,+ IPageTimeseriesRow,+ ITopPage,+} from './modules/overview/pages.service';+export {+ getEntryExitPagesCore,+ getPageConversionsCore,+ getPagePerformanceCore,+ getTopPagesCore,+ PagesService,+ pagesService,+} from './modules/overview/pages.service';// Dissolved from @openpanel/db's services/clients.service.ts (M6-002) —// packages/trpc's client router, apps/api's manage controller and mcp/utils// auth call these directly, the same way V1 reaches every other dissolveddiff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.tsnew file mode 100644index 000000000..3941f78cd--- /dev/null+++ b/packages/core/src/modules/overview/overview.rpc.ts@@ -0,0 +1,456 @@+// Ported from packages/trpc/src/routers/overview.ts.+//+// Same arrangement as chart.rpc.ts: V1's `publicProcedure` + share-or-session+// `overviewProcedure` middleware and `cacheMiddleware` stacks land with auth+// (P6), so each procedure does its own share-or-session check off the+// `projectId`/`shareId` input. packages/trpc's overview router delegates its+// handler bodies onto this module while keeping V1's own procedure stack and+// response cache.+//+// `liveData`'s ClickHouse queries used to live inline in packages/trpc's+// router; they moved to `overviewService.getLiveData` (src/overview.sql.ts)+// so every query this module runs goes through the same `sql` tag (M7-005).++import { format } from 'date-fns';+import { getConversionEventNames } from '../event/event.service';+import { getActiveVisitorCount } from '../realtime/realtime.service';+import { getReferrerSpikes } from '../insight/insight.service';+import { getOrganizationSubscriptionChartEndDate } from '../organization/organization.service';+import { getSettingsForProject } from '../organization/organization.service';+import { validateOverviewShareAccess } from '../share/share.service';+import {+ getChartPrevStartEndDate,+ getChartStartEndDate,+} from '@openpanel/db/src/services/date.service';+import {+ type IChartRange,+ pageContextSchema,+ zRange,+} from '@openpanel/validation';+import { z } from 'zod';+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';+import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';+import {+ overviewService,+ zGetMapDataInput,+ zGetMetricsInput,+ zGetTopEventsInput,+ zGetTopGenericInput,+ zGetTopGenericSeriesInput,+ zGetTopLinkOutInput,+ zGetTopPagesInput,+ zGetUserJourneyInput,+} from './overview.service';++function loadAccessChecks() {+ return import('./src/access');+}++// Lazy, not a static import: the assistant module's chatApp chain reaches+// deep into @openpanel/db and @openpanel/queue (see index.ts's own+// `loadAssistant()` for the full story) — a static import here would pull+// that chain into this module's evaluation, and this module is itself a+// static import of rpc.router.ts/index.ts's own barrel.+function loadFilterCommand() {+ return import('../assistant/src/filter-command');+}++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++async function requireAccess(+ userId: string,+ projectId: string,+ level: 'read' | 'write'+) {+ const { requireProjectAccess } = await loadAccessChecks();+ await requireProjectAccess({ userId, projectId, level });+}++async function requireReadAccess(ctx: TrpcContext, projectId: string) {+ await requireAccess(requireLogin(ctx.session.userId), projectId, 'read');+}++/**+ * Share-aware access: with `shareId`, a public (optionally password-unlocked)+ * overview share is enough; without it, the caller must be a project member.+ * A password-protected share without the unlock cookie comes back as+ * `{ isValid: false }` rather than throwing, so the result must be checked —+ * ignoring it leaves the data open to anyone holding the link.+ */+async function resolveOverviewAccess(+ ctx: TrpcContext,+ input: { projectId: string; shareId?: string }+): Promise<void> {+ if (input.shareId) {+ const shareValidation = await validateOverviewShareAccess(+ input.shareId,+ input.projectId,+ {+ cookies: ctx.cookies,+ session: ctx.session.userId ? { userId: ctx.session.userId } : undefined,+ }+ );+ if (!shareValidation.isValid) {+ throw new TRPCForbiddenError('You do not have access to this share');+ }+ return;+ }+ await requireReadAccess(ctx, input.projectId);+}++const overviewProcedure = procedure.use(async ({ ctx, next, getRawInput }) => {+ const rawInput = (await getRawInput()) as {+ projectId: string;+ shareId?: string;+ };+ await resolveOverviewAccess(ctx, rawInput);+ return next();+});++function getCurrentAndPrevious<+ T extends {+ startDate?: string | null;+ endDate?: string | null;+ range: IChartRange;+ projectId: string;+ },+>(input: T, fetchPrevious: boolean, timezone: string) {+ const current = getChartStartEndDate(input, timezone);+ const previous = getChartPrevStartEndDate(current);++ return async <R>(+ fn: (input: T & { startDate: string; endDate: string }) => Promise<R>+ ): Promise<{+ current: R;+ previous: R | null;+ }> => {+ const endDate = await getOrganizationSubscriptionChartEndDate(+ input.projectId,+ current.endDate+ );+ if (endDate) {+ current.endDate = endDate;+ // Only expired trial scenarios+ if (new Date(current.startDate) > new Date(current.endDate)) {+ current.startDate = current.endDate;+ }+ }+ const res = await Promise.all([+ fn({+ ...input,+ startDate: current.startDate,+ endDate: current.endDate,+ }),+ fetchPrevious+ ? fn({+ ...input,+ startDate: previous.startDate,+ endDate: previous.endDate,+ })+ : Promise.resolve(null),+ ]);++ return {+ current: res[0],+ previous: res[1],+ };+ };+}++export const overviewRouter = createTRPCRouter({+ liveVisitors: overviewProcedure+ .input(z.object({ projectId: z.string(), shareId: z.string().optional() }))+ .query(async ({ input }) => {+ return getActiveVisitorCount(input.projectId);+ }),++ liveData: overviewProcedure+ .input(z.object({ projectId: z.string(), shareId: z.string().optional() }))+ .query(async ({ input }) => {+ return overviewService.getLiveData(input.projectId);+ }),++ stats: overviewProcedure+ .input(+ zGetMetricsInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { current, previous } = await getCurrentAndPrevious(+ { ...input, timezone },+ true,+ timezone+ )(overviewService.getMetrics.bind(overviewService));+ return {+ metrics: {+ ...current.metrics,+ prev_bounce_rate: previous?.metrics.bounce_rate || null,+ prev_unique_visitors: previous?.metrics.unique_visitors || null,+ prev_total_screen_views: previous?.metrics.total_screen_views || null,+ prev_avg_session_duration:+ previous?.metrics.avg_session_duration || null,+ prev_views_per_session: previous?.metrics.views_per_session || null,+ prev_total_sessions: previous?.metrics.total_sessions || null,+ prev_total_revenue: previous?.metrics.total_revenue || null,+ },+ series: current.series.map((item, index) => {+ const prev = previous?.series[index];+ return {+ ...item,+ date: format(item.date, 'yyyy-MM-dd HH:mm:ss'),+ prev_bounce_rate: prev?.bounce_rate,+ prev_unique_visitors: prev?.unique_visitors,+ prev_total_screen_views: prev?.total_screen_views,+ prev_avg_session_duration: prev?.avg_session_duration,+ prev_views_per_session: prev?.views_per_session,+ prev_total_sessions: prev?.total_sessions,+ prev_total_revenue: prev?.total_revenue,+ };+ }),+ };+ }),++ getReferrerSpikes: overviewProcedure+ .input(+ zGetMetricsInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { startDate, endDate } = getChartStartEndDate(input, timezone);+ const clusters = await getReferrerSpikes({+ projectId: input.projectId,+ filters: input.filters,+ interval: input.interval,+ startDate,+ endDate,+ timezone,+ });+ // Reformat every spike date (and the cluster's anchor) to match+ // overview.stats' series date format, so markers x-align with the+ // chart's data points (xScale matches by Date identity).+ const fmt = (iso: string) => format(new Date(iso), 'yyyy-MM-dd HH:mm:ss');+ return clusters.map((cluster) => ({+ anchorDate: fmt(cluster.anchorDate),+ spikes: cluster.spikes.map((spike) => ({+ ...spike,+ date: fmt(spike.date),+ })),+ }));+ }),++ topPages: overviewProcedure+ .input(+ zGetTopPagesInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ mode: z.enum(['page', 'entry', 'exit', 'bot']),+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { current } = await getCurrentAndPrevious(+ { ...input },+ false,+ timezone+ )(async (input) => {+ if (input.mode === 'page') {+ return overviewService.getTopPages({ ...input, timezone });+ }++ if (input.mode === 'bot') {+ return Promise.resolve([]);+ }++ return overviewService.getTopEntryExit({+ ...input,+ mode: input.mode,+ timezone,+ });+ });++ return current;+ }),++ topGeneric: overviewProcedure+ .input(+ zGetTopGenericInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { current } = await getCurrentAndPrevious(+ { ...input, timezone },+ false,+ timezone+ )(overviewService.getTopGeneric.bind(overviewService));++ return current;+ }),++ topGenericSeries: overviewProcedure+ .input(+ zGetTopGenericSeriesInput+ .omit({ startDate: true, endDate: true })+ .extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { current } = await getCurrentAndPrevious(+ { ...input, timezone },+ false,+ timezone+ )(overviewService.getTopGenericSeries.bind(overviewService));++ return current;+ }),++ userJourney: overviewProcedure+ .input(+ zGetUserJourneyInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ steps: z.number().min(2).max(10).default(5).optional(),+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { current } = await getCurrentAndPrevious(+ { ...input, timezone },+ false,+ timezone+ )(async (input) => {+ return overviewService.getUserJourney({+ ...input,+ steps: input.steps ?? 5,+ timezone,+ });+ });++ return current;+ }),++ topEvents: overviewProcedure+ .input(+ zGetTopEventsInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { current } = await getCurrentAndPrevious(+ { ...input, timezone },+ false,+ timezone+ )(overviewService.getTopEvents.bind(overviewService));++ return current;+ }),++ topConversions: overviewProcedure+ .input(+ z.object({+ projectId: z.string(),+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ return getConversionEventNames(input.projectId);+ }),++ topLinkOut: overviewProcedure+ .input(+ zGetTopLinkOutInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { current } = await getCurrentAndPrevious(+ { ...input, timezone },+ false,+ timezone+ )(overviewService.getTopLinkOut.bind(overviewService));++ return current;+ }),++ // One-shot AI command bar — converts natural-language requests+ // ("show 7 aug to 11 aug", "from google", "mobile only for august+ // last year") into structured filter changes the dashboard can apply+ // through the same handlers the chat panel uses.+ runFilterCommand: procedure+ // Computes filter changes for the caller's own UI; changes no project state.+ .meta({ readOnlyMutation: true })+ .input(+ z.object({+ projectId: z.string(),+ query: z.string().min(1).max(500),+ pageContext: pageContextSchema.optional(),+ })+ )+ .mutation(async ({ ctx, input }) => {+ await requireReadAccess(ctx, input.projectId);+ const { timezone } = await getSettingsForProject(input.projectId);+ const { runFilterCommand } = await loadFilterCommand();+ return runFilterCommand({+ query: input.query,+ projectId: input.projectId,+ pageContext: input.pageContext,+ timezone: timezone || 'UTC',+ });+ }),++ map: overviewProcedure+ .input(+ zGetMapDataInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ shareId: z.string().optional(),+ })+ )+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { current } = await getCurrentAndPrevious(+ { ...input, timezone },+ false,+ timezone+ )(overviewService.getMapData.bind(overviewService));++ return current;+ }),+});diff --git a/packages/core/src/modules/overview/overview.service.ts b/packages/core/src/modules/overview/overview.service.tsnew file mode 100644index 000000000..2d372d0a7--- /dev/null+++ b/packages/core/src/modules/overview/overview.service.ts@@ -0,0 +1,1302 @@+// Ported from packages/db/src/services/overview.service.ts. The ClickHouse+// queries moved to src/overview.sql.ts (ADR-013, M7-005); `OverviewService`+// keeps V1's `constructor(client: typeof ch)` shape and public method names —+// `apps/api`'s insights controller and the mcp analytics tools still call+// `overviewService.getX(...)` as a bound method, and V1's own db package is+// now a re-export shim onto this module (DELEGATE PATTERN).++import type { ClickHouseClient } from '@clickhouse/client';+import { average, sum } from '@openpanel/common';+import { chartColors } from '@openpanel/constants';+import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';+import type { IChartEventFilter, IInterval } from '@openpanel/validation';+import { zTimeInterval } from '@openpanel/validation';+import { z } from 'zod';+import { convertClickhouseDateToJs } from '../chart/src/dates';+import { getEventFiltersWhereClause } from '../chart/src/filter-where';+import { getSettingsForProject } from '../organization/organization.service';+import {+ distinctSessionsQuery,+ liveMinuteCountsQuery,+ liveMinuteReferrersQuery,+ liveReferrersQuery,+ liveTotalSessionsQuery,+ mapDataQuery,+ metricsWithPageFilterQuery,+ revenueQuery,+ sessionMetricsQuery,+ topEntriesQuery,+ topEntryExitQuery,+ topEventsQuery,+ topGenericQuery,+ topGenericSeriesTimeSeriesQuery,+ topGenericSeriesTopItemsQuery,+ topLinkOutQuery,+ topPagesQuery,+ transitionsQuery,+} from './src/overview.sql';+import { runQuery } from './src/run-query';++// Toggle revenue tracking in overview queries+const INCLUDE_REVENUE = true; // TODO: Make this configurable later++// Maximum number of records to return (for detail modals)+const MAX_RECORDS_LIMIT = 1000;++const ROLLUP_DATE_PREFIX = '1970-01-01';++function isClickhouseDefaultMinDate(date: string): boolean {+ return date.startsWith(ROLLUP_DATE_PREFIX) || date.startsWith('1969-12-31');+}++const COLUMN_PREFIX_MAP: Record<string, string> = {+ region: 'country',+ city: 'country',+ browser_version: 'browser',+ os_version: 'os',+};++const WHITELISTED_FILTERS = [+ 'os',+ 'path',+ 'city',+ 'brand',+ 'model',+ 'origin',+ 'region',+ 'device',+ 'revenue',+ 'country',+ 'browser',+ 'referrer',+ 'os_version',+ 'referrer_name',+ 'browser_version',+ 'referrer_type',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+];++// Columns that exist on the sessions table but not on events — on events+// they're stored inside the properties map under __query.utm_*.+const UTM_COLUMNS = [+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+];++// Types+type MetricsRow = {+ bounce_rate: number;+ unique_visitors: number;+ total_sessions: number;+ avg_session_duration: number;+ total_screen_views: number;+ views_per_session: number;+};++type MetricsSeriesRow = MetricsRow & { date: string; total_revenue: number };++export const zGetMetricsInput = z.object({+ projectId: z.string(),+ filters: z.array(z.any()),+ startDate: z.string(),+ endDate: z.string(),+ interval: zTimeInterval,+});++export type IGetMetricsInput = z.infer<typeof zGetMetricsInput> & {+ timezone: string;+};++export const zGetTopPagesInput = z.object({+ projectId: z.string(),+ filters: z.array(z.any()),+ startDate: z.string(),+ endDate: z.string(),+ limit: z.number().min(1).max(1000).optional(),+});++export type IGetTopPagesInput = z.infer<typeof zGetTopPagesInput> & {+ timezone: string;+};++export const zGetTopEntryExitInput = z.object({+ projectId: z.string(),+ filters: z.array(z.any()),+ startDate: z.string(),+ endDate: z.string(),+ mode: z.enum(['entry', 'exit']),+ limit: z.number().min(1).max(1000).optional(),+});++export type IGetTopEntryExitInput = z.infer<typeof zGetTopEntryExitInput> & {+ timezone: string;+};++export const zGetTopGenericInput = z.object({+ projectId: z.string(),+ filters: z.array(z.any()),+ startDate: z.string(),+ endDate: z.string(),+ column: z.enum([+ // Referrers+ 'referrer',+ 'referrer_name',+ 'referrer_type',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+ // Geo+ 'region',+ 'country',+ 'city',+ // Device+ 'device',+ 'brand',+ 'model',+ 'browser',+ 'browser_version',+ 'os',+ 'os_version',+ ]),+});++export type IGetTopGenericInput = z.infer<typeof zGetTopGenericInput> & {+ timezone: string;+};++export const zGetTopGenericSeriesInput = zGetTopGenericInput.extend({+ interval: zTimeInterval,+});++export type IGetTopGenericSeriesInput = z.infer<+ typeof zGetTopGenericSeriesInput+> & {+ timezone: string;+};++export const zGetUserJourneyInput = z.object({+ projectId: z.string(),+ filters: z.array(z.any()),+ startDate: z.string(),+ endDate: z.string(),+ steps: z.number().min(2).max(10).default(5),+});++export type IGetUserJourneyInput = z.infer<typeof zGetUserJourneyInput> & {+ timezone: string;+};++export const zGetTopEventsInput = z.object({+ projectId: z.string(),+ filters: z.array(z.any()),+ startDate: z.string(),+ endDate: z.string(),+ excludeEvents: z.array(z.string()).optional(),+});++export type IGetTopEventsInput = z.infer<typeof zGetTopEventsInput> & {+ timezone: string;+};++export const zGetTopLinkOutInput = z.object({+ projectId: z.string(),+ filters: z.array(z.any()),+ startDate: z.string(),+ endDate: z.string(),+});++export type IGetTopLinkOutInput = z.infer<typeof zGetTopLinkOutInput> & {+ timezone: string;+};++export const zGetMapDataInput = z.object({+ projectId: z.string(),+ filters: z.array(z.any()),+ startDate: z.string(),+ endDate: z.string(),+});++export type IGetMapDataInput = z.infer<typeof zGetMapDataInput> & {+ timezone: string;+};++export interface ILiveMinuteCount {+ minute: string;+ sessionCount: number;+ visitorCount: number;+ timestamp: number;+ time: string;+ referrers: Array<{ referrer: string; count: number }>;+}++export interface ILiveData {+ totalSessions: number;+ minuteCounts: ILiveMinuteCount[];+ referrers: Array<{ referrer: string; count: number }>;+}++export class OverviewService {+ /** No client means the singleton path — `run-query.ts` resolves `ch` lazily. */+ constructor(private client?: ClickHouseClient) {}++ private async createRevenueQuery({+ projectId,+ startDate,+ endDate,+ interval,+ timezone,+ filters,+ }: {+ projectId: string;+ startDate: string;+ endDate: string;+ interval: IInterval;+ timezone: string;+ filters: IChartEventFilter[];+ }): Promise<{ date: string; total_revenue: number }[]> {+ const rows = await runQuery<{ date: string; total_revenue: number }>(+ this.client,+ revenueQuery({+ projectId,+ startDate,+ endDate,+ interval,+ rawFilterWhere: this.getRawWhereClause('events', filters),+ }),+ timezone+ );+ return rows.map((row) => ({+ ...row,+ date: convertClickhouseDateToJs(row.date).toISOString(),+ }));+ }++ private mergeRevenueIntoSeries<T extends { date: string }>(+ series: T[],+ revenueData: { date: string; total_revenue: number }[]+ ): (T & { total_revenue: number })[] {+ const revenueByDate = new Map(+ revenueData+ .filter((r) => !isClickhouseDefaultMinDate(r.date))+ .map((r) => [r.date, r.total_revenue])+ );+ return series.map((row) => ({+ ...row,+ total_revenue: revenueByDate.get(row.date) ?? 0,+ }));+ }++ private getOverallRevenue(+ revenueData: { date: string; total_revenue: number }[]+ ): number {+ return (+ revenueData.find((r) => isClickhouseDefaultMinDate(r.date))+ ?.total_revenue ?? 0+ );+ }++ /**+ * V1 `withDistinctSessionsIfNeeded`: a page (`path`) filter has no column on+ * `sessions`, so it's resolved against `events` first and the session ids+ * that match are intersected in. Returns the mutually-exclusive pair every+ * `sessions`-scoped query builder takes.+ */+ private sessionsFilterMode(params: {+ filters: IChartEventFilter[];+ projectId: string;+ startDate: string;+ endDate: string;+ }): { rawFilterWhere: string; distinctSessionsCte: SqlFragment | null } {+ if (!this.isPageFilter(params.filters)) {+ return {+ rawFilterWhere: this.getRawWhereClause('sessions', params.filters),+ distinctSessionsCte: null,+ };+ }+ return {+ rawFilterWhere: '',+ distinctSessionsCte: distinctSessionsQuery({+ projectId: params.projectId,+ startDate: params.startDate,+ endDate: params.endDate,+ rawFilterWhere: this.getRawWhereClause('events', params.filters),+ }),+ };+ }++ isPageFilter(filters: IChartEventFilter[]) {+ return filters.some((filter) => filter.name === 'path' && filter.value);+ }++ async getMetrics({+ projectId,+ filters,+ startDate,+ endDate,+ interval,+ timezone,+ }: IGetMetricsInput): Promise<{+ metrics: {+ bounce_rate: number;+ unique_visitors: number;+ total_sessions: number;+ avg_session_duration: number;+ total_screen_views: number;+ views_per_session: number;+ total_revenue: number;+ };+ series: {+ date: string;+ bounce_rate: number;+ unique_visitors: number;+ total_sessions: number;+ avg_session_duration: number;+ total_screen_views: number;+ views_per_session: number;+ total_revenue: number;+ }[];+ }> {+ return this.isPageFilter(filters)+ ? this.getMetricsWithPageFilter({+ projectId,+ filters,+ startDate,+ endDate,+ interval,+ timezone,+ })+ : this.getMetricsFromSessions({+ projectId,+ filters,+ startDate,+ endDate,+ interval,+ timezone,+ });+ }++ private async getMetricsFromSessions({+ projectId,+ filters,+ startDate,+ endDate,+ interval,+ timezone,+ }: IGetMetricsInput): Promise<{+ metrics: MetricsRow & { total_revenue: number };+ series: MetricsSeriesRow[];+ }> {+ const [sessionRes, revenueRes] = await Promise.all([+ runQuery<{+ date: string;+ bounce_rate: number;+ unique_visitors: number;+ total_sessions: number;+ avg_session_duration: number;+ total_screen_views: number;+ views_per_session: number;+ }>(+ this.client,+ sessionMetricsQuery({+ projectId,+ startDate,+ endDate,+ interval,+ rawFilterWhere: this.getRawWhereClause('sessions', filters),+ }),+ timezone+ ).then((rows) =>+ rows.map((row) => ({ ...row, date: new Date(row.date).toISOString() }))+ ),+ this.createRevenueQuery({ projectId, startDate, endDate, interval, timezone, filters }),+ ]);++ const overallRevenue = this.getOverallRevenue(revenueRes);+ const series = this.mergeRevenueIntoSeries(sessionRes.slice(1), revenueRes);++ return {+ metrics: {+ bounce_rate: sessionRes[0]?.bounce_rate ?? 0,+ unique_visitors: sessionRes[0]?.unique_visitors ?? 0,+ total_sessions: sessionRes[0]?.total_sessions ?? 0,+ avg_session_duration: sessionRes[0]?.avg_session_duration ?? 0,+ total_screen_views: sessionRes[0]?.total_screen_views ?? 0,+ views_per_session: sessionRes[0]?.views_per_session ?? 0,+ total_revenue: overallRevenue,+ },+ series,+ };+ }++ private async getMetricsWithPageFilter({+ projectId,+ filters,+ startDate,+ endDate,+ interval,+ timezone,+ }: IGetMetricsInput): Promise<{+ metrics: MetricsRow & { total_revenue: number };+ series: MetricsSeriesRow[];+ }> {+ const rawEventFilterWhere = this.getRawWhereClause('events', filters);+ const rawSessionFilterWhere = this.getRawWhereClause('sessions', filters);++ const [mainRes, revenueRes] = await Promise.all([+ runQuery<{+ date: string;+ bounce_rate: number;+ unique_visitors: number;+ total_sessions: number;+ avg_session_duration: number;+ total_screen_views: number;+ views_per_session: number;+ overall_unique_visitors: number;+ overall_total_sessions: number;+ overall_bounce_rate: number;+ }>(+ this.client,+ metricsWithPageFilterQuery({+ projectId,+ startDate,+ endDate,+ interval,+ rawSessionFilterWhere,+ rawEventFilterWhere,+ }),+ timezone+ ).then((rows) =>+ rows.map((row) => ({ ...row, date: new Date(row.date).toISOString() }))+ ),+ this.createRevenueQuery({ projectId, startDate, endDate, interval, timezone, filters }),+ ]);++ const overallRevenue = this.getOverallRevenue(revenueRes);+ const series = this.mergeRevenueIntoSeries(mainRes, revenueRes);++ const anyRowWithData = mainRes.find(+ (item) =>+ item.overall_bounce_rate !== null ||+ item.overall_total_sessions !== null ||+ item.overall_unique_visitors !== null+ );++ return {+ metrics: {+ bounce_rate: anyRowWithData?.overall_bounce_rate ?? 0,+ unique_visitors: anyRowWithData?.overall_unique_visitors ?? 0,+ total_sessions: anyRowWithData?.overall_total_sessions ?? 0,+ avg_session_duration: average(+ mainRes.map((item) => item.avg_session_duration)+ ),+ total_screen_views: sum(mainRes.map((item) => item.total_screen_views)),+ views_per_session: average(+ mainRes.map((item) => item.views_per_session)+ ),+ total_revenue: overallRevenue,+ },+ series,+ };+ }++ getRawWhereClause(type: 'events' | 'sessions', filters: IChartEventFilter[]) {+ const where = getEventFiltersWhereClause(+ filters.flatMap((item) => {+ if (!WHITELISTED_FILTERS.includes(item.name)) {+ return [];+ }+ if (type === 'sessions') {+ if (item.name === 'path') {+ return [{ ...item, name: 'entry_path' }];+ }+ if (item.name === 'origin') {+ return [{ ...item, name: 'entry_origin' }];+ }+ if (item.name.startsWith('properties.__query.utm_')) {+ return [+ {+ ...item,+ name: item.name.replace('properties.__query.utm_', 'utm_'),+ },+ ];+ }+ // sessions table has no `properties` map for arbitrary keys —+ // drop them instead of generating an invalid WHERE clause.+ if (item.name.startsWith('properties.')) {+ return [];+ }+ return [item];+ }+ // events table has no top-level utm_* columns — those live in the+ // properties map under the __query.utm_* keys. Route them through+ // getEventFiltersWhereClause's properties.* path so we emit+ // `properties['__query.utm_source']` instead of the bare column.+ if (UTM_COLUMNS.includes(item.name)) {+ return [{ ...item, name: `properties.__query.${item.name}` }];+ }+ return [item];+ }),+ undefined,+ undefined,+ type+ );++ return Object.values(where).join(' AND ');+ }++ async getTopPages({+ projectId,+ filters,+ startDate,+ endDate,+ timezone,+ limit,+ }: IGetTopPagesInput) {+ return runQuery<{+ origin: string;+ path: string;+ sessions: number;+ pageviews: number;+ revenue?: number;+ }>(+ this.client,+ topPagesQuery({+ projectId,+ startDate,+ endDate,+ rawFilterWhere: this.getRawWhereClause('events', filters),+ limit: Math.min(limit ?? MAX_RECORDS_LIMIT, MAX_RECORDS_LIMIT),+ }),+ timezone+ );+ }++ async getTopEntryExit({+ projectId,+ filters,+ startDate,+ endDate,+ mode,+ timezone,+ limit,+ }: IGetTopEntryExitInput) {+ const sessionsFilter = this.sessionsFilterMode({ filters, projectId, startDate, endDate });+ return runQuery<{+ origin: string;+ path: string;+ sessions: number;+ pageviews: number;+ revenue?: number;+ }>(+ this.client,+ topEntryExitQuery({+ projectId,+ startDate,+ endDate,+ mode,+ limit: Math.min(limit ?? MAX_RECORDS_LIMIT, MAX_RECORDS_LIMIT),+ rawFilterWhere: sessionsFilter.rawFilterWhere,+ distinctSessionsCte: sessionsFilter.distinctSessionsCte,+ }),+ timezone+ );+ }++ async getTopGeneric({+ projectId,+ filters,+ startDate,+ endDate,+ column,+ timezone,+ }: IGetTopGenericInput) {+ if (!WHITELISTED_FILTERS.includes(column)) {+ return [];+ }++ const prefixColumn = COLUMN_PREFIX_MAP[column] ?? null;+ const sessionsFilter = this.sessionsFilterMode({ filters, projectId, startDate, endDate });++ return runQuery<{+ prefix?: string;+ name: string;+ sessions: number;+ pageviews: number;+ revenue?: number;+ }>(+ this.client,+ topGenericQuery({+ projectId,+ startDate,+ endDate,+ column,+ prefixColumn,+ limit: MAX_RECORDS_LIMIT,+ rawFilterWhere: sessionsFilter.rawFilterWhere,+ distinctSessionsCte: sessionsFilter.distinctSessionsCte,+ }),+ timezone+ );+ }++ async getTopGenericSeries({+ projectId,+ filters,+ startDate,+ endDate,+ column,+ interval,+ timezone,+ }: IGetTopGenericSeriesInput): Promise<{+ items: Array<{+ name: string;+ prefix?: string;+ data: Array<{+ date: string;+ sessions: number;+ pageviews: number;+ revenue?: number;+ }>;+ total: { sessions: number; pageviews: number; revenue?: number };+ }>;+ }> {+ const prefixColumn = COLUMN_PREFIX_MAP[column] ?? null;+ const TOP_LIMIT = 500;++ const topItemsSessionsFilter = this.sessionsFilterMode({+ filters,+ projectId,+ startDate,+ endDate,+ });++ const topItems = await runQuery<{+ prefix?: string;+ name: string;+ sessions: number;+ pageviews: number;+ revenue?: number;+ }>(+ this.client,+ topGenericSeriesTopItemsQuery({+ projectId,+ startDate,+ endDate,+ column,+ prefixColumn,+ limit: TOP_LIMIT,+ rawFilterWhere: topItemsSessionsFilter.rawFilterWhere,+ distinctSessionsCte: topItemsSessionsFilter.distinctSessionsCte,+ }),+ timezone+ );++ if (topItems.length === 0) {+ return { items: [] };+ }++ // V1 always applies the sessions rawWhere here (unlike the top-items+ // query above), additionally wrapping in distinct_sessions on a page+ // filter — see overview.sql.ts's topGenericSeriesTimeSeriesQuery header.+ const timeSeriesSessionsFilter = this.isPageFilter(filters)+ ? distinctSessionsQuery({+ projectId,+ startDate,+ endDate,+ rawFilterWhere: this.getRawWhereClause('events', filters),+ })+ : null;++ const timeSeriesData = await runQuery<{+ date: string;+ prefix?: string;+ name: string;+ sessions: number;+ pageviews: number;+ revenue?: number;+ }>(+ this.client,+ topGenericSeriesTimeSeriesQuery({+ projectId,+ startDate,+ endDate,+ interval,+ column,+ prefixColumn,+ rawFilterWhere: this.getRawWhereClause('sessions', filters),+ distinctSessionsCte: timeSeriesSessionsFilter,+ }),+ timezone+ ).then((rows) =>+ rows.map((row) => ({ ...row, date: new Date(row.date).toISOString() }))+ );++ const itemsMap = new Map<+ string,+ {+ name: string;+ prefix?: string;+ data: Array<{+ date: string;+ sessions: number;+ pageviews: number;+ revenue?: number;+ }>;+ total: { sessions: number; pageviews: number; revenue?: number };+ }+ >();++ for (const item of topItems) {+ const key = `${item.prefix || ''}:${item.name}`;+ itemsMap.set(key, {+ name: item.name,+ prefix: item.prefix,+ data: [],+ total: {+ sessions: item.sessions,+ pageviews: item.pageviews,+ revenue: item.revenue ?? 0,+ },+ });+ }++ for (const row of timeSeriesData) {+ const key = `${row.prefix || ''}:${row.name}`;+ const item = itemsMap.get(key);+ if (item) {+ item.data.push({+ date: row.date,+ sessions: row.sessions,+ pageviews: row.pageviews,+ revenue: row.revenue,+ });+ }+ }++ return {+ items: Array.from(itemsMap.values()),+ };+ }++ async getUserJourney({+ projectId,+ filters,+ startDate,+ endDate,+ steps = 5,+ timezone,+ }: IGetUserJourneyInput): Promise<{+ nodes: Array<{+ id: string;+ label: string;+ nodeColor: string;+ percentage?: number;+ value?: number;+ step?: number;+ }>;+ links: Array<{ source: string; target: string; value: number }>;+ }> {+ // Config+ const TOP_ENTRIES = 3; // Only show top 3 entry pages+ const TOP_DESTINATIONS_PER_NODE = 3; // Top 3 destinations from each node++ // Color palette - each entry page gets a consistent color+ const COLORS = chartColors.map((color) => color.main);++ const rawFilterWhere = this.getRawWhereClause('events', filters);+ const orderedEventsInput = { projectId, startDate, endDate, rawFilterWhere };++ const topEntries = await runQuery<{ entry_page: string; count: number }>(+ this.client,+ topEntriesQuery({ ...orderedEventsInput, steps, topEntries: TOP_ENTRIES }),+ timezone+ );++ if (topEntries.length === 0) {+ return { nodes: [], links: [] };+ }++ const topEntryPages = topEntries.map((e) => e.entry_page);+ const totalSessions = topEntries.reduce((total, e) => total + e.count, 0);++ const transitions = await runQuery<{+ source: string;+ target: string;+ step: number;+ value: number;+ }>(+ this.client,+ transitionsQuery({ ...orderedEventsInput, steps, topEntryPages }),+ timezone+ );++ if (transitions.length === 0) {+ return { nodes: [], links: [] };+ }++ // Build the sankey progressively step by step. Start with entry nodes,+ // then follow top destinations at each step. Node IDs combine path with+ // step to prevent circular references.+ const nodes = new Map<+ string,+ { path: string; value: number; step: number; color: string }+ >();+ const links: Array<{ source: string; target: string; value: number }> = [];++ const getNodeId = (path: string, step: number) => `${path}::step${step}`;++ const transitionsByStep = new Map<number, typeof transitions>();+ for (const t of transitions) {+ if (!transitionsByStep.has(t.step)) {+ transitionsByStep.set(t.step, []);+ }+ transitionsByStep.get(t.step)!.push(t);+ }++ const activeNodes = new Map<string, string>(); // path -> nodeId+ topEntries.forEach((entry, idx) => {+ const nodeId = getNodeId(entry.entry_page, 1);+ nodes.set(nodeId, {+ path: entry.entry_page,+ value: entry.count,+ step: 1,+ color: COLORS[idx % COLORS.length]!,+ });+ activeNodes.set(entry.entry_page, nodeId);+ });++ for (let step = 1; step < steps; step++) {+ const stepTransitions = transitionsByStep.get(step) || [];+ const nextActiveNodes = new Map<string, string>();++ for (const [sourcePath, sourceNodeId] of activeNodes) {+ const fromSource = stepTransitions+ .filter((t) => t.source === sourcePath)+ .sort((a, b) => b.value - a.value)+ .slice(0, TOP_DESTINATIONS_PER_NODE);++ for (const t of fromSource) {+ if (t.source === t.target) {+ continue;+ }++ const targetNodeId = getNodeId(t.target, step + 1);++ links.push({+ source: sourceNodeId,+ target: targetNodeId,+ value: t.value,+ });++ const existing = nodes.get(targetNodeId);+ if (existing) {+ existing.value += t.value;+ } else {+ const sourceData = nodes.get(sourceNodeId);+ nodes.set(targetNodeId, {+ path: t.target,+ value: t.value,+ step: step + 1,+ color: sourceData?.color || COLORS[nodes.size % COLORS.length]!,+ });+ }++ nextActiveNodes.set(t.target, targetNodeId);+ }+ }++ activeNodes.clear();+ for (const [path, nodeId] of nextActiveNodes) {+ activeNodes.set(path, nodeId);+ }++ if (activeNodes.size === 0) {+ break;+ }+ }++ // Filter links by threshold (0.25% of total sessions)+ const MIN_LINK_PERCENT = 0.25;+ const minLinkValue = Math.ceil((totalSessions * MIN_LINK_PERCENT) / 100);+ const filteredLinks = links.filter((link) => link.value >= minLinkValue);++ const referencedNodeIds = new Set<string>();+ filteredLinks.forEach((link) => {+ referencedNodeIds.add(link.source);+ referencedNodeIds.add(link.target);+ });++ const nodeValuesFromLinks = new Map<string, number>();+ filteredLinks.forEach((link) => {+ const current = nodeValuesFromLinks.get(link.target) || 0;+ nodeValuesFromLinks.set(link.target, current + link.value);+ });++ // For entry nodes (step 1), only keep them if they have outgoing links after filtering+ nodes.forEach((nodeData, nodeId) => {+ if (nodeData.step === 1) {+ const hasOutgoing = filteredLinks.some((l) => l.source === nodeId);+ if (!hasOutgoing) {+ referencedNodeIds.delete(nodeId);+ }+ }+ });++ const finalNodes = Array.from(nodes.entries())+ .filter(([id]) => referencedNodeIds.has(id))+ .map(([id, data]) => {+ const value =+ data.step === 1+ ? data.value+ : nodeValuesFromLinks.get(id) || data.value;+ return {+ id,+ label: data.path,+ nodeColor: data.color,+ percentage: (value / totalSessions) * 100,+ value,+ step: data.step,+ };+ })+ .sort((a, b) => {+ if (a.step !== b.step) {+ return a.step - b.step;+ }+ return b.value - a.value;+ });++ const nodeIds = new Set(finalNodes.map((n) => n.id));+ const invalidLinks = filteredLinks.filter(+ (link) => !(nodeIds.has(link.source) && nodeIds.has(link.target))+ );+ if (invalidLinks.length > 0) {+ console.warn(+ `UserJourney: Found ${invalidLinks.length} links with missing nodes`+ );+ const validLinks = filteredLinks.filter(+ (link) => nodeIds.has(link.source) && nodeIds.has(link.target)+ );+ return {+ nodes: finalNodes,+ links: validLinks,+ };+ }++ const stepsValid = finalNodes.every((node, idx, arr) => {+ if (idx === 0) {+ return true;+ }+ return node.step! >= arr[idx - 1]!.step!;+ });+ if (!stepsValid) {+ console.warn('UserJourney: Steps are not monotonic');+ }++ return {+ nodes: finalNodes,+ links: filteredLinks,+ };+ }++ async getTopEvents({+ projectId,+ filters,+ startDate,+ endDate,+ timezone,+ excludeEvents = ['session_start', 'session_end', 'screen_view'],+ }: {+ projectId: string;+ filters: IChartEventFilter[];+ startDate: string;+ endDate: string;+ timezone: string;+ excludeEvents?: string[];+ }): Promise<Array<{ name: string; count: number }>> {+ return runQuery<{ name: string; count: number }>(+ this.client,+ topEventsQuery({+ projectId,+ startDate,+ endDate,+ rawFilterWhere: this.getRawWhereClause('events', filters),+ excludeEvents,+ }),+ timezone+ );+ }++ async getTopLinkOut({+ projectId,+ filters,+ startDate,+ endDate,+ timezone,+ }: {+ projectId: string;+ filters: IChartEventFilter[];+ startDate: string;+ endDate: string;+ timezone: string;+ }): Promise<Array<{ href: string; count: number }>> {+ return runQuery<{ href: string; count: number }>(+ this.client,+ topLinkOutQuery({+ projectId,+ startDate,+ endDate,+ rawFilterWhere: this.getRawWhereClause('events', filters),+ }),+ timezone+ );+ }++ async getMapData({+ projectId,+ filters,+ startDate,+ endDate,+ timezone,+ }: {+ projectId: string;+ filters: IChartEventFilter[];+ startDate: string;+ endDate: string;+ timezone: string;+ }): Promise<+ Array<{+ country: string;+ region?: string;+ city?: string;+ lat: number;+ lng: number;+ count: number;+ }>+ > {+ const results = await runQuery<{+ country: string;+ region: string | null;+ city: string | null;+ count: number;+ }>(+ this.client,+ mapDataQuery({+ projectId,+ startDate,+ endDate,+ rawFilterWhere: this.getRawWhereClause('events', filters),+ }),+ timezone+ );++ // Placeholder lat/lng — geocoding is unresolved, same as V1.+ return results.map((row) => ({+ country: row.country,+ region: row.region ?? undefined,+ city: row.city ?? undefined,+ lat: 0,+ lng: 0,+ count: row.count,+ }));+ }++ /** The dashboard's live/30-minute-window widget — moved from packages/trpc's overview router (M7-005). */+ async getLiveData(projectId: string): Promise<ILiveData> {+ const [totalSessions, minuteCounts, minuteReferrers, referrers] =+ await Promise.all([+ runQuery<{ total_sessions: number }>(+ this.client,+ liveTotalSessionsQuery({ projectId }),+ 'UTC'+ ),+ runQuery<{ minute: string; session_count: number; visitor_count: number }>(+ this.client,+ liveMinuteCountsQuery({ projectId }),+ 'UTC'+ ),+ runQuery<{ minute: string; referrer_name: string; count: number }>(+ this.client,+ liveMinuteReferrersQuery({ projectId }),+ 'UTC'+ ),+ runQuery<{ referrer: string; count: number }>(+ this.client,+ liveReferrersQuery({ projectId }),+ 'UTC'+ ),+ ]);++ const referrersByMinute = new Map<+ string,+ Array<{ referrer: string; count: number }>+ >();+ for (const item of minuteReferrers) {+ if (!referrersByMinute.has(item.minute)) {+ referrersByMinute.set(item.minute, []);+ }+ referrersByMinute.get(item.minute)!.push({+ referrer: item.referrer_name,+ count: item.count,+ });+ }++ return {+ totalSessions: totalSessions[0]?.total_sessions || 0,+ minuteCounts: minuteCounts.map((item) => ({+ minute: item.minute,+ sessionCount: item.session_count,+ visitorCount: item.visitor_count,+ timestamp: new Date(item.minute).getTime(),+ time: new Date(item.minute).toLocaleTimeString([], {+ hour: '2-digit',+ minute: '2-digit',+ }),+ referrers: referrersByMinute.get(item.minute) || [],+ })),+ referrers: referrers.map((item) => ({+ referrer: item.referrer,+ count: item.count,+ })),+ };+ }+}++export const overviewService = new OverviewService();++export type TrafficColumn =+ | 'referrer'+ | 'referrer_name'+ | 'referrer_type'+ | 'utm_source'+ | 'utm_medium'+ | 'utm_campaign'+ | 'country'+ | 'region'+ | 'city'+ | 'device'+ | 'browser'+ | 'os';++export async function getTrafficBreakdownCore(input: {+ projectId: string;+ startDate: string;+ endDate: string;+ column: TrafficColumn;+ filters?: IChartEventFilter[];+}) {+ const { timezone } = await getSettingsForProject(input.projectId);+ return overviewService.getTopGeneric({+ projectId: input.projectId,+ filters: input.filters ?? [],+ startDate: input.startDate,+ endDate: input.endDate,+ column: input.column,+ timezone,+ });+}++// Columns whose daily series we can derive from the sessions table. Page/entry+// insights (path/origin) live on the events table and aren't covered here — the+// caller degrades to no series for those.+const SEGMENT_SERIES_COLUMNS: ReadonlySet<string> = new Set<TrafficColumn>([+ 'referrer',+ 'referrer_name',+ 'referrer_type',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'country',+ 'region',+ 'city',+ 'device',+ 'browser',+ 'os',+]);++export interface SegmentDailyPoint {+ date: string;+ sessions: number;+ pageviews: number;+}++// Daily breakdown for a single segment value (e.g. the "Twitter" referrer),+// so the explainer can see the *shape* of a change (one-off spike vs sustained+// growth) instead of only current-vs-baseline totals. Returns one point per day+// with zero-filled gaps; empty when the column isn't session-derived or the+// value never appears in the window.+export async function getSegmentDailySeriesCore(input: {+ projectId: string;+ column: string;+ value: string;+ startDate: string;+ endDate: string;+}): Promise<SegmentDailyPoint[]> {+ if (!SEGMENT_SERIES_COLUMNS.has(input.column)) {+ return [];+ }++ const { timezone } = await getSettingsForProject(input.projectId);+ const { items } = await overviewService.getTopGenericSeries({+ projectId: input.projectId,+ filters: [],+ startDate: input.startDate,+ endDate: input.endDate,+ column: input.column as TrafficColumn,+ interval: 'day',+ timezone,+ });++ // getTopGenericSeries reports empty values as null name; insights store the+ // empty referrer as "direct". Match the segment leniently.+ const target = input.value.toLowerCase();+ const matched = items.find((item) => {+ const name = (item.name ?? '').toLowerCase();+ return name === target || (name === '' && target === 'direct');+ });++ return (matched?.data ?? []).map((point) => ({+ date: point.date,+ sessions: Number(point.sessions ?? 0),+ pageviews: Number(point.pageviews ?? 0),+ }));+}++export interface GetAnalyticsOverviewInput {+ projectId: string;+ startDate: string;+ endDate: string;+ interval?: 'hour' | 'day' | 'week' | 'month';+ filters?: IChartEventFilter[];+}++export async function getAnalyticsOverviewCore(input: GetAnalyticsOverviewInput) {+ const { timezone } = await getSettingsForProject(input.projectId);+ const interval = input.interval ?? 'day';++ const result = await overviewService.getMetrics({+ projectId: input.projectId,+ filters: input.filters ?? [],+ startDate: input.startDate,+ endDate: input.endDate,+ interval,+ timezone,+ });++ return {+ summary: result.metrics,+ series: result.series,+ interval,+ startDate: input.startDate,+ endDate: input.endDate,+ };+}+diff --git a/packages/core/src/modules/overview/pages.service.ts b/packages/core/src/modules/overview/pages.service.tsnew file mode 100644index 000000000..5b1a391f9--- /dev/null+++ b/packages/core/src/modules/overview/pages.service.ts@@ -0,0 +1,207 @@+// Ported from packages/db/src/services/pages.service.ts. The ClickHouse+// queries moved to src/pages.sql.ts (ADR-013, M7-005); `PagesService` keeps+// V1's `constructor(client: typeof ch)` shape — the mcp+// `get_page_performance` tool constructs a fresh instance per call to dodge a+// module-singleton mocking hazard (see page-performance.ts), so the+// constructor's client really is caller-supplied.++import type { ClickHouseClient } from '@clickhouse/client';+import type { IChartEventFilter, IInterval } from '@openpanel/validation';+import { getSettingsForProject } from '../organization/organization.service';+import { OverviewService } from './overview.service';+import {+ pageConversionsQuery,+ pageTimeseriesQuery,+ topPagesQuery,+} from './src/pages.sql';+import { runQuery } from './src/run-query';++export interface IGetPagesInput {+ projectId: string;+ startDate: string;+ endDate: string;+ timezone: string;+ search?: string;+ limit?: number;+}++export interface IPageTimeseriesRow {+ origin: string;+ path: string;+ date: string;+ pageviews: number;+ sessions: number;+}++export interface ITopPage {+ origin: string;+ path: string;+ title: string;+ sessions: number;+ pageviews: number;+ avg_duration: number;+ bounce_rate: number;+}++export class PagesService {+ /** No client means the singleton path — `run-query.ts` resolves `ch` lazily. */+ constructor(private client?: ClickHouseClient) {}++ async getTopPages({+ projectId,+ startDate,+ endDate,+ timezone,+ search,+ limit,+ }: IGetPagesInput): Promise<ITopPage[]> {+ return runQuery<ITopPage>(+ this.client,+ topPagesQuery({ projectId, startDate, endDate, search, limit }),+ timezone+ );+ }++ async getPageTimeseries({+ projectId,+ startDate,+ endDate,+ timezone,+ interval,+ filterOrigin,+ filterPath,+ }: IGetPagesInput & {+ interval: IInterval;+ filterOrigin?: string;+ filterPath?: string;+ }): Promise<IPageTimeseriesRow[]> {+ return runQuery<IPageTimeseriesRow>(+ this.client,+ pageTimeseriesQuery({+ projectId,+ startDate,+ endDate,+ interval,+ filterOrigin,+ filterPath,+ }),+ timezone+ );+ }+}++export const pagesService = new PagesService();+const overviewServiceForPages = new OverviewService();++export async function getTopPagesCore(input: {+ projectId: string;+ startDate: string;+ endDate: string;+ limit?: number;+ filters?: IChartEventFilter[];+}) {+ const { timezone } = await getSettingsForProject(input.projectId);+ return overviewServiceForPages.getTopPages({+ projectId: input.projectId,+ filters: input.filters ?? [],+ startDate: input.startDate,+ endDate: input.endDate,+ timezone,+ limit: input.limit,+ });+}++export async function getEntryExitPagesCore(input: {+ projectId: string;+ startDate: string;+ endDate: string;+ mode: 'entry' | 'exit';+ limit?: number;+ filters?: IChartEventFilter[];+}) {+ const { timezone } = await getSettingsForProject(input.projectId);+ return overviewServiceForPages.getTopEntryExit({+ projectId: input.projectId,+ filters: input.filters ?? [],+ startDate: input.startDate,+ endDate: input.endDate,+ mode: input.mode,+ timezone,+ limit: input.limit,+ });+}++export async function getPagePerformanceCore(input: {+ projectId: string;+ startDate: string;+ endDate: string;+ search?: string;+ sortBy?: 'sessions' | 'pageviews' | 'bounce_rate' | 'avg_duration';+ sortOrder?: 'asc' | 'desc';+ limit?: number;+}) {+ const { timezone } = await getSettingsForProject(input.projectId);+ const results = await pagesService.getTopPages({+ projectId: input.projectId,+ startDate: input.startDate,+ endDate: input.endDate,+ timezone,+ search: input.search,+ limit: 1000,+ });++ const col = input.sortBy ?? 'sessions';+ const dir = input.sortOrder === 'asc' ? 1 : -1;+ const sorted = [...results].sort(+ (a, b) => dir * ((a[col] ?? 0) < (b[col] ?? 0) ? -1 : 1)+ );+ const limited = sorted.slice(0, input.limit ?? 50);++ const annotated = limited.map((p) => ({+ ...p,+ seo_signals: {+ high_bounce: p.bounce_rate > 70,+ low_engagement: p.avg_duration < 1,+ good_landing_page: p.bounce_rate < 40 && p.avg_duration > 2,+ },+ }));++ return {+ total_pages: results.length,+ shown: annotated.length,+ pages: annotated,+ };+}++export interface IPageConversionRow {+ path: string;+ origin: string;+ unique_converters: number;+ total_visitors: number;+ conversion_rate: number;+}++const DEFAULT_CONVERSION_WINDOW_HOURS = 24;+const DEFAULT_CONVERSION_LIMIT = 100;++export async function getPageConversionsCore(input: {+ projectId: string;+ startDate: string;+ endDate: string;+ conversionEvent: string;+ windowHours?: number;+ limit?: number;+}): Promise<IPageConversionRow[]> {+ return runQuery<IPageConversionRow>(+ undefined,+ pageConversionsQuery({+ projectId: input.projectId,+ startDate: input.startDate,+ endDate: input.endDate,+ conversionEvent: input.conversionEvent,+ windowHours: input.windowHours ?? DEFAULT_CONVERSION_WINDOW_HOURS,+ limit: input.limit ?? DEFAULT_CONVERSION_LIMIT,+ }),+ 'UTC'+ );+}diff --git a/packages/core/src/modules/overview/src/access.ts b/packages/core/src/modules/overview/src/access.tsnew file mode 100644index 000000000..667861497--- /dev/null+++ b/packages/core/src/modules/overview/src/access.ts@@ -0,0 +1,22 @@+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for+// this module's own router — the same binding packages/trpc/src/access.ts+// does for V1, self-contained here because the general core -> db binding+// itself moves with auth (P6), not this wave. Same shape as+// session/src/access.ts, event/src/access.ts and chart/src/access.ts.++import {+ canWriteProject,+ getOrganizationAccess,+ getProjectAccess,+} from '@openpanel/db/src/services/access.service';+import { getProjectById } from '@openpanel/db/src/services/project.service';+import { createAccessChecks } from '../../../shared/access';++const checks = createAccessChecks({+ getProjectAccess,+ canWriteProject,+ getOrganizationAccess,+ getProjectById,+});++export const requireProjectAccess = checks.requireProjectAccess;diff --git a/packages/core/src/modules/overview/src/overview.sql.proof.md b/packages/core/src/modules/overview/src/overview.sql.proof.mdnew file mode 100644index 000000000..64d7a36c5--- /dev/null+++ b/packages/core/src/modules/overview/src/overview.sql.proof.md@@ -0,0 +1,177 @@+# overview.sql.ts — V1 -> V2 result-set proof (M7-005)++**Methodology.** Two levels of evidence, per decision 21:++1. **Whole-method comparison.** `OverviewService`'s public methods were called twice with+ identical input against the same local ClickHouse — once through V1's unmodified+ `clix`-built queries (`git show HEAD:packages/db/src/services/overview.service.ts`, the+ state before this task) and once through this module's `sql`-fragment builders — and the+ JSON results diffed byte-for-byte. This exercises every query plus all of V1's JS-side+ post-processing (revenue merge, fill defaults, the user-journey graph builder) in one pass,+ which a query-by-query SQL diff alone would not catch.+2. **Per-query SQL + execution proof.** Every builder in this file was rendered via+ `toStatement()` and executed against the same data with `EXPLAIN`-equivalent real+ execution (no query is committed unexecuted). Row counts and timings below are from that+ run.++- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static).+ Project: `skills-directory` (293,597 events, 75,727 sessions, 2026-07-01..2026-08-25).+ Window used throughout: `2026-08-01 00:00:00`..`2026-08-08 00:00:00`, UTC.+- **Machine**: single-node ClickHouse — self-host topology (`docs/ENVIRONMENT.md`). No+ statement here touches a `Distributed` table or a cross-shard `IN`; `events`/`sessions` are+ local tables both locally and on Cloud, so no `GLOBAL IN` question arises for this module.++## Whole-method comparison — verdict++13 of 15 cases came back **byte-identical**; the 2 that didn't are `pages.getTopPages`'s+`title` column, explained below (a V1 characteristic, not a V2 regression).++| Case | Verdict | Rows |+|---|---|---|+| `getMetrics` (no filter) | IDENTICAL | 7 series + summary |+| `getMetrics` (page filter) | IDENTICAL | 7 series + summary |+| `getTopPages` | IDENTICAL | 20 |+| `getTopEntryExit` (entry) | IDENTICAL | 20 |+| `getTopEntryExit` (exit, page filter) | IDENTICAL | 20 |+| `getTopGeneric` (country) | IDENTICAL | 143 |+| `getTopGenericSeries` (referrer, day) | IDENTICAL | 1 item + series |+| `getUserJourney` (4 steps) | IDENTICAL | nodes + links |+| `getTopEvents` | IDENTICAL | 12 |+| `getTopLinkOut` | IDENTICAL | 78 |+| `getMapData` | IDENTICAL | 1000 |+| `pages.getTopPages` | see below | 20 |+| `pages.getTopPages` (search) | see below | 20 |+| `pages.getPageTimeseries` | IDENTICAL | 3103 |+| `getPageConversionsCore` | IDENTICAL | 20 |++### The one V1 characteristic that survives unchanged: `anyLast(properties['__title'])`++`pages.getTopPages`'s title lookup (`page_titles` CTE) uses `anyLast()` with no explicit+ordering. ClickHouse does not guarantee a deterministic pick for `any`/`anyLast` across+repeated executions of the *same* query when the underlying merge is order-sensitive at the+row level. Proven independently of this task's code: running V1's own reconstructed SQL text+(byte-identical, params inlined as V1's clix would) directly via `curl` five times in a row+against the unchanged data flips the same page's title between `''` and its real value:++```+curl ... "WITH page_titles AS (... anyLast(properties['__title']) ...) SELECT ... WHERE e.path = '/skills/jezweb-fastapi' ..."+run 1: title = ''+run 2: title = 'Fastapi (Grade A) - Claude Skill | Skills Directory'+run 3: title = 'Fastapi (Grade A) - Claude Skill | Skills Directory'+run 4: title = ''+run 5: title = 'Fastapi (Grade A) - Claude Skill | Skills Directory'+```++This is V1's behaviour, ported verbatim (same `anyLast`, same lack of an explicit tiebreak) —+fixing it (e.g. `argMax` with a deterministic key) is a behaviour change outside this task's+scope. Every other column in both `pages.getTopPages` cases — `sessions`, `pageviews`,+`avg_duration`, `bounce_rate`, and (for the search case) the row set once title-dependent+matches are excluded — is identical between V1 and V2.++## Two real bugs found during conversion (not V1 bugs — introduced and fixed in this task)++1. **`GROUP BY ... WITH ROLLUP ... HAVING`, not `HAVING ... WITH ROLLUP`.** `sessionMetricsQuery`+ initially emitted `GROUP BY date HAVING sum(sign) > 0 WITH ROLLUP`, which ClickHouse+ rejects (`Syntax error ... Expected ... end of query`, right after `ORDER BY date ASC`).+ Fixed by reordering to `GROUP BY date WITH ROLLUP HAVING sum(sign) > 0`, ClickHouse's+ required clause order. Caught by `bun test` (`get_analytics_overview` mcp tool test),+ confirmed by re-running the corrected query and diffing against V1.+2. **`WITH FILL FROM/TO` needs the exact column type, not a `String`.** The first cut bound+ the fill boundary as `sql.string(...)` (or, once fixed once, `sql.dateTime64(...)`).+ ClickHouse's `WITH FILL` requires the boundary's type to match the sorted column's type+ exactly: `toStartOfDay(created_at)` is `DateTime`, and a `String` or `DateTime64` boundary+ is rejected (`Sort FILL FROM expression must be constant with numeric type` / `Incompatible+ types of WITH FILL expression values with column type DateTime`). Fixed by wrapping the+ boundary in `toStartOfX(...)` exactly as V1's `clix.toStartOf`/`clix.datetime` expression+ text did (never a bare literal) and typing the raw param `DateTime` (day/hour/minute+ buckets) or `Date` (week/month buckets, matching V1's `toDate` wrapper).++## Per-query render + execution proof++Every builder below was rendered via `toStatement()` and executed once against+`skills-directory`, `2026-08-01`..`2026-08-08` UTC (`transitionsQuery` used placeholder entry+pages that don't exist in the data, to prove the array-function shape parses and runs; 0 rows+is expected and correct for that input). All 22 statements below executed with no error.++| Query | Rows | Rows read | Wall |+|---|---|---|---|+| `revenueQuery` | 0 (no revenue events for this project) | 0 | 29 ms |+| `sessionMetricsQuery` | 8 (7 days + rollup total) | 16,369 | 23 ms |+| `metricsWithPageFilterQuery` | 7 | 73,678 | 76 ms |+| `topPagesQuery` (overview) | 20 | 49,152 | 23 ms |+| `topEntryExitQuery` (no page filter) | 20 | 24,551 | 12 ms |+| `distinctSessionsQuery` | 6,981 | 65,536 | 14 ms |+| `topGenericQuery` (no prefix, country) | 143 | 24,551 | 14 ms |+| `topGenericQuery` (with prefix, region) | 725 | 24,551 | 13 ms |+| `topGenericSeriesTimeSeriesQuery` | 219 | 24,551 | 8 ms |+| `topEntriesQuery` | 3 | 49,152 | 55 ms |+| `transitionsQuery` (placeholder entries) | 0 | 49,152 | 54 ms |+| `topEventsQuery` | 12 | 65,536 | 14 ms |+| `topLinkOutQuery` | 78 | 49,152 | 18 ms |+| `mapDataQuery` | 1000 | 49,152 | 24 ms |+| `liveTotalSessionsQuery` | 1 | 0 (empty 30-min window) | 8 ms |+| `liveMinuteCountsQuery` | 30 | 0 | 6 ms |+| `liveMinuteReferrersQuery` | 0 | 0 | 9 ms |+| `liveReferrersQuery` | 0 | 0 | 10 ms |++`liveTotalSessionsQuery`/`liveMinuteCountsQuery`/`liveMinuteReferrersQuery`/`liveReferrersQuery`+read 0 rows against local prod-copy data because their `now() - INTERVAL 30 MINUTE` window+never overlaps the fixture's frozen historical range; `liveMinuteCountsQuery`'s 30 rows are+the `WITH FILL`-materialized empty minute buckets, proving the fill clause itself (`FROM+toStartOfMinute(now() - INTERVAL 30 MINUTE) TO toStartOfMinute(now()) STEP INTERVAL 1+MINUTE`) parses and runs. These four were moved here from packages/trpc's inline+`overview.liveData` procedure (M7-005) and had no prior SQL-discipline proof; this is their+first execution against real ClickHouse.++### Representative statements (rendered, params bound)++```sql+-- sessionMetricsQuery+SELECT+ toStartOfDay(created_at) AS date,+ round(sum(sign * is_bounce) * 100.0 / sum(sign), 2) as bounce_rate,+ uniqIf(profile_id, sign > 0) AS unique_visitors,+ sum(sign) AS total_sessions,+ round(avgIf(duration, duration > 0 AND sign > 0), 2) / 1000 AS _avg_session_duration,+ if(isNaN(_avg_session_duration), 0, _avg_session_duration) AS avg_session_duration,+ sum(sign * screen_view_count) AS total_screen_views,+ round(sum(sign * screen_view_count) * 1.0 / sum(sign), 2) AS views_per_session+FROM sessions+WHERE created_at BETWEEN toDateTime({p1:String}) AND toDateTime({p2:String})+ AND project_id = {p3:String}+GROUP BY date+WITH ROLLUP+HAVING sum(sign) > 0+ORDER BY date ASC+WITH FILL FROM toStartOfDay({p4:DateTime}) TO {p5:DateTime} STEP toIntervalDay(1)+-- params: {"p1":"2026-08-01 00:00:00","p2":"2026-08-08 00:00:00","p3":"skills-directory","p4":"2026-08-01 00:00:00","p5":"2026-08-08 00:00:00"}+```++```sql+-- topEntriesQuery (user-journey step 1) — same array-function shape sankey.sql.ts established (M7-004)+WITH session_paths AS (+ WITH paths_deduped_cte AS (+ WITH ordered_events AS (+ SELECT session_id, concat(origin, path) as path, created_at+ FROM events+ WHERE project_id = {p1:String} AND name = 'screen_view' AND path != '' AND path IS NOT NULL+ AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String})+ ORDER BY session_id ASC, created_at ASC+ )+ SELECT session_id,+ arraySlice(arrayFilter((x, i) -> i = 1 OR x != paths_raw[i - 1], groupArray(path) as paths_raw, arrayEnumerate(paths_raw)), 1, {p4:UInt64}) as paths_deduped+ FROM ordered_events GROUP BY session_id+ )+ SELECT session_id,+ if(arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) = 0, paths_deduped,+ arraySlice(paths_deduped, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) - 1)) as paths,+ paths[1] as entry_page+ FROM paths_deduped_cte HAVING length(paths) >= 2+)+SELECT entry_page, count() as count FROM session_paths GROUP BY entry_page ORDER BY count DESC LIMIT {p5:UInt64}+-- params: {"p1":"skills-directory","p2":"2026-08-01 00:00:00","p3":"2026-08-08 00:00:00","p4":4,"p5":3}+```++Full renders for all 18 `overview.sql.ts` builders (including the CTE-heavy+`metricsWithPageFilterQuery` and `transitionsQuery`) are exercised by+`overview.sql.test.ts`'s `EXPLAIN`-based parse gate, which runs on every `bun test`.diff --git a/packages/core/src/modules/overview/src/overview.sql.test.ts b/packages/core/src/modules/overview/src/overview.sql.test.tsnew file mode 100644index 000000000..713221046--- /dev/null+++ b/packages/core/src/modules/overview/src/overview.sql.test.ts@@ -0,0 +1,291 @@+/**+ * SQL-shape tests for every `overview.sql.ts` builder. Same strategy as+ * chart/funnel/retention/sankey's own `*.sql.test.ts` (M7-003/004): render+ * the statement, then run `EXPLAIN <sql>` with its bound params against the+ * isolated `openpanel_test` ClickHouse (pinned by test/preload.ts). EXPLAIN+ * parses and resolves columns without executing, catching the two bugs this+ * module actually shipped during conversion — see overview.sql.proof.md —+ * without needing seeded rows.+ */++import { beforeAll, describe, expect, it } from 'bun:test';+import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';++const PROJECT_ID = 'test-sql-validation';+const START = '2026-08-01 00:00:00';+const END = '2026-08-08 00:00:00';++let ch: typeof import('@openpanel/db/src/clickhouse/client').ch;+let OV: typeof import('./overview.sql');++async function explain(fragment: SqlFragment): Promise<void> {+ const { query, query_params } = fragment.toStatement();+ await ch.command({ query: `EXPLAIN ${query}`, query_params });+}++beforeAll(async () => {+ ({ ch } = await import('@openpanel/db/src/clickhouse/client'));+ OV = await import('./overview.sql');+});++describe('overview.sql — parses against ClickHouse', () => {+ it('revenueQuery', async () => {+ await explain(+ OV.revenueQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ interval: 'day',+ rawFilterWhere: '',+ })+ );+ });++ it('sessionMetricsQuery — GROUP BY/WITH ROLLUP/HAVING/WITH FILL clause order', async () => {+ await explain(+ OV.sessionMetricsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ interval: 'day',+ rawFilterWhere: '',+ })+ );+ });++ it('sessionMetricsQuery — week and month buckets (Date-typed fill boundary)', async () => {+ await explain(+ OV.sessionMetricsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ interval: 'week',+ rawFilterWhere: '',+ })+ );+ await explain(+ OV.sessionMetricsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ interval: 'month',+ rawFilterWhere: '',+ })+ );+ });++ it('metricsWithPageFilterQuery — the 5-CTE page-filtered metrics query', async () => {+ await explain(+ OV.metricsWithPageFilterQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ interval: 'day',+ rawSessionFilterWhere: '',+ rawEventFilterWhere: '',+ })+ );+ });++ it('topPagesQuery', async () => {+ await explain(+ OV.topPagesQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ limit: 20,+ })+ );+ });++ it('topEntryExitQuery — plain sessions filter', async () => {+ await explain(+ OV.topEntryExitQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ mode: 'entry',+ limit: 20,+ rawFilterWhere: '',+ distinctSessionsCte: null,+ })+ );+ });++ it('topEntryExitQuery — distinct-sessions CTE (page filter branch)', async () => {+ const distinctSessionsCte = OV.distinctSessionsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ });+ await explain(+ OV.topEntryExitQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ mode: 'exit',+ limit: 20,+ rawFilterWhere: '',+ distinctSessionsCte,+ })+ );+ });++ it('topGenericQuery — no prefix column', async () => {+ await explain(+ OV.topGenericQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ column: 'country',+ prefixColumn: null,+ limit: 1000,+ rawFilterWhere: '',+ distinctSessionsCte: null,+ })+ );+ });++ it('topGenericQuery — with prefix column (region -> country)', async () => {+ await explain(+ OV.topGenericQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ column: 'region',+ prefixColumn: 'country',+ limit: 1000,+ rawFilterWhere: '',+ distinctSessionsCte: null,+ })+ );+ });++ it('topGenericSeriesTimeSeriesQuery — rawWhere always applied, plus optional distinct-sessions', async () => {+ await explain(+ OV.topGenericSeriesTimeSeriesQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ interval: 'day',+ column: 'referrer',+ prefixColumn: null,+ rawFilterWhere: '',+ distinctSessionsCte: null,+ })+ );+ const distinctSessionsCte = OV.distinctSessionsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ });+ await explain(+ OV.topGenericSeriesTimeSeriesQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ interval: 'day',+ column: 'referrer',+ prefixColumn: null,+ rawFilterWhere: '',+ distinctSessionsCte,+ })+ );+ });++ it('topEntriesQuery — the deduped-paths array functions', async () => {+ await explain(+ OV.topEntriesQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ steps: 5,+ topEntries: 3,+ })+ );+ });++ it('transitionsQuery — arrayJoin/arrayMap pair expansion', async () => {+ await explain(+ OV.transitionsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ steps: 5,+ topEntryPages: ['https://a.example.com/', 'https://a.example.com/pricing'],+ })+ );+ });++ it('topEventsQuery — with and without excludeEvents', async () => {+ await explain(+ OV.topEventsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ excludeEvents: ['session_start', 'session_end', 'screen_view'],+ })+ );+ await explain(+ OV.topEventsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ excludeEvents: [],+ })+ );+ });++ it('topLinkOutQuery', async () => {+ await explain(+ OV.topLinkOutQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ })+ );+ });++ it('mapDataQuery', async () => {+ await explain(+ OV.mapDataQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ rawFilterWhere: '',+ })+ );+ });++ it('live* queries — the dashboard 30-minute window, moved off packages/trpc', async () => {+ await explain(OV.liveTotalSessionsQuery({ projectId: PROJECT_ID }));+ await explain(OV.liveMinuteCountsQuery({ projectId: PROJECT_ID }));+ await explain(OV.liveMinuteReferrersQuery({ projectId: PROJECT_ID }));+ await explain(OV.liveReferrersQuery({ projectId: PROJECT_ID }));+ });+});++describe('overview.sql — sql.id() identifier whitelists (R3)', () => {+ it('rejects a column name off the top-generic whitelist', () => {+ expect(() =>+ OV.topGenericQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ column: 'password',+ prefixColumn: null,+ limit: 10,+ rawFilterWhere: '',+ distinctSessionsCte: null,+ })+ ).toThrow();+ });+});diff --git a/packages/core/src/modules/overview/src/overview.sql.ts b/packages/core/src/modules/overview/src/overview.sql.tsnew file mode 100644index 000000000..470d3de19--- /dev/null+++ b/packages/core/src/modules/overview/src/overview.sql.ts@@ -0,0 +1,751 @@+// Every ClickHouse query OverviewService runs, as pure `sql` fragments+// (ADR-013). Converted 1:1 from packages/db/src/services/overview.service.ts+// (clix): the SQL text is V1's, with every value — project id, dates,+// timezone, event/column names, limits — bound as a `{pN:Type}` parameter+// instead of an escaped literal or clix's inline string interpolation. Each+// builder's result set was diffed against V1's on the local prod-copy; the+// statements, params, row counts and timings are in overview.sql.proof.md.+//+// The event filter compiler still renders text (chart module's+// filter-where.ts); its output is spliced through `compiledText`, same as+// chart/funnel/retention/sankey/conversion until this module stops needing it+// (ADR-013 leaves the compiler as-is "until funnel, conversion, sankey,+// retention and overview stop splicing its output into text builders" —+// unchanged by this task).+//+// `toStartOf`/`toInterval`/`datetime` reproduce V1's `clix` static helpers+// verbatim (query-builder.ts) rather than chart.sql.ts's own `intervalBucket`:+// notably V1's overview never passed a timezone into `toStartOfWeek`/+// `toStartOfMonth` — ClickHouse resolves those from the query's+// `session_timezone` setting instead, which every statement here still sets+// (see src/run-query.ts).++import { compiledText } from '../../chart/src/compiled';+import { getSelectPropertyKey } from '../../chart/src/field-resolution';+import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import type { IInterval } from '@openpanel/validation';++const ROLLUP_DATE_PREFIX = '1970-01-01';++export type OverviewTable = 'events' | 'sessions';++function toDateTimeLiteral(value: string): string {+ return new Date(value).toISOString().slice(0, 19).replace('T', ' ');+}++function toDateLiteral(value: string): string {+ return new Date(value).toISOString().slice(0, 10);+}++/** V1 `clix.toStartOf` — deliberately timezone-blind for week/month (see header). */+export function toStartOf(node: string, interval: IInterval): SqlFragment {+ switch (interval) {+ case 'minute':+ return sql`toStartOfMinute(${sql.id(node)})`;+ case 'hour':+ return sql`toStartOfHour(${sql.id(node)})`;+ case 'day':+ return sql`toStartOfDay(${sql.id(node)})`;+ case 'week':+ return sql`toStartOfWeek(toDateTime(${sql.id(node)}))`;+ case 'month':+ return sql`toStartOfMonth(toDateTime(${sql.id(node)}))`;+ default:+ throw new Error(`Unsupported overview interval: ${String(interval)}`);+ }+}++/** V1 `clix.toInterval`. */+function toIntervalStep(interval: IInterval): string {+ switch (interval) {+ case 'minute':+ return 'toIntervalMinute(1)';+ case 'hour':+ return 'toIntervalHour(1)';+ case 'day':+ return 'toIntervalDay(1)';+ case 'week':+ return 'toIntervalWeek(1)';+ case 'month':+ return 'toIntervalMonth(1)';+ default:+ throw new Error(`Unsupported overview interval: ${String(interval)}`);+ }+}++/**+ * `getFillConfig`: `WITH FILL` needs FROM/TO to actually evaluate to a+ * Date/DateTime constant, not a bare string — V1 got this from `clix`'s+ * `toStartOf`/`datetime` helpers, which return SQL *expressions*+ * (`toStartOfMonth(toDateTime(toDate('...')))`), never a plain literal.+ * `sql.date`/`sql.dateTime64` bind the boundary itself; the wrapping+ * functions around them reproduce that expression shape.+ */+function fillBoundaryParam(interval: IInterval, value: string) {+ // The bucket column's type must match exactly: `toStartOfX(created_at)`+ // returns plain `DateTime`/`Date`, not `DateTime64` — ClickHouse's WITH+ // FILL rejects a boundary whose type doesn't match the sorted column's.+ return interval === 'month' || interval === 'week'+ ? sql.date(toDateLiteral(value))+ : sql.param('DateTime', toDateTimeLiteral(value));+}++/** V1 always bucket-aligns FROM (via `toStartOf`) but leaves TO as-is. */+function fillFrom(interval: IInterval, startDate: string): SqlFragment {+ const boundary = fillBoundaryParam(interval, startDate);+ switch (interval) {+ case 'minute':+ return sql`toStartOfMinute(${boundary})`;+ case 'hour':+ return sql`toStartOfHour(${boundary})`;+ case 'day':+ return sql`toStartOfDay(${boundary})`;+ case 'week':+ return sql`toStartOfWeek(toDateTime(${boundary}))`;+ case 'month':+ return sql`toStartOfMonth(toDateTime(${boundary}))`;+ default:+ throw new Error(`Unsupported overview interval: ${String(interval)}`);+ }+}++export function fillClause(+ interval: IInterval,+ startDate: string,+ endDate: string+): SqlFragment {+ return sql`WITH FILL FROM ${fillFrom(interval, startDate)} TO ${fillBoundaryParam(interval, endDate)} STEP ${compiledText(toIntervalStep(interval))}`;+}++function dateRangeWhere(column: string, startDate: string, endDate: string): SqlFragment {+ return sql`${sql.id(column)} BETWEEN toDateTime(${sql.string(toDateTimeLiteral(startDate))}) AND toDateTime(${sql.string(toDateTimeLiteral(endDate))})`;+}++/** `getRawWhereClause`'s output — pre-compiled text, spliced verbatim. */+function rawWhere(where: string): SqlFragment {+ return where ? sql`AND ${compiledText(where)}` : sql.empty;+}++// --- revenue -----------------------------------------------------------------++export interface RevenueQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ interval: IInterval;+ rawFilterWhere: string;+}++export function revenueQuery(input: RevenueQueryInput): SqlFragment {+ return sql`+ SELECT+ ${toStartOf('created_at', input.interval)} AS date,+ sum(revenue) AS total_revenue+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'revenue'+ AND revenue > 0+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawFilterWhere)}+ GROUP BY date+ WITH ROLLUP+ `;+}++// --- metrics: sessions-only path ----------------------------------------------++export interface SessionMetricsQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ interval: IInterval;+ rawFilterWhere: string;+}++export function sessionMetricsQuery(input: SessionMetricsQueryInput): SqlFragment {+ return sql`+ SELECT+ ${toStartOf('created_at', input.interval)} AS date,+ round(sum(sign * is_bounce) * 100.0 / sum(sign), 2) as bounce_rate,+ uniqIf(profile_id, sign > 0) AS unique_visitors,+ sum(sign) AS total_sessions,+ round(avgIf(duration, duration > 0 AND sign > 0), 2) / 1000 AS _avg_session_duration,+ if(isNaN(_avg_session_duration), 0, _avg_session_duration) AS avg_session_duration,+ sum(sign * screen_view_count) AS total_screen_views,+ round(sum(sign * screen_view_count) * 1.0 / sum(sign), 2) AS views_per_session+ FROM sessions+ WHERE ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ AND project_id = ${sql.string(input.projectId)}+ ${rawWhere(input.rawFilterWhere)}+ GROUP BY date+ WITH ROLLUP+ HAVING sum(sign) > 0+ ORDER BY date ASC+ ${fillClause(input.interval, input.startDate, input.endDate)}+ `;+}++// --- metrics: page-filtered path -----------------------------------------------++export interface PageFilterMetricsQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ interval: IInterval;+ rawSessionFilterWhere: string;+ rawEventFilterWhere: string;+}++function rollupDateLiteral(interval: IInterval): SqlFragment {+ return interval === 'month' || interval === 'week'+ ? sql`toDate(${sql.string(ROLLUP_DATE_PREFIX)})`+ : sql`toDateTime(${sql.string(`${ROLLUP_DATE_PREFIX} 00:00:00`)})`;+}++export function metricsWithPageFilterQuery(+ input: PageFilterMetricsQueryInput+): SqlFragment {+ const rollupDate = rollupDateLiteral(input.interval);+ const eventsDateBucket = toStartOf('e.created_at', input.interval);++ const rawScreenViewDurations = sql`+ SELECT+ ${toStartOf('created_at', input.interval)} AS date,+ dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at)) AS duration+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'screen_view'+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawEventFilterWhere)}+ `;++ const avgDurationByDate = sql`+ SELECT date, round(avgIf(duration, duration > 0), 2) / 1000 AS avg_session_duration+ FROM raw_screen_view_durations+ GROUP BY date+ `;++ const sessionAgg = sql`+ SELECT+ ${toStartOf('created_at', input.interval)} AS date,+ round((countIf(is_bounce = 1 AND sign = 1) * 100.) / countIf(sign = 1), 2) AS bounce_rate+ FROM sessions FINAL+ WHERE sign = 1+ AND project_id = ${sql.string(input.projectId)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawSessionFilterWhere)}+ GROUP BY date+ WITH ROLLUP+ ORDER BY date ASC+ `;++ const overallUniqueVisitors = sql`+ SELECT uniq(profile_id) AS unique_visitors, uniq(session_id) AS total_sessions+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'screen_view'+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawEventFilterWhere)}+ `;++ return sql`+ WITH+ session_agg AS (${sessionAgg}),+ overall_bounce_rate AS (SELECT bounce_rate FROM session_agg WHERE date = ${rollupDate}),+ daily_session_stats AS (SELECT date, bounce_rate FROM session_agg WHERE date != ${rollupDate}),+ overall_unique_visitors AS (${overallUniqueVisitors}),+ raw_screen_view_durations AS (${rawScreenViewDurations}),+ avg_duration_by_date AS (${avgDurationByDate})+ SELECT+ ${eventsDateBucket} AS date,+ dss.bounce_rate as bounce_rate,+ uniq(e.profile_id) AS unique_visitors,+ uniq(e.session_id) AS total_sessions,+ coalesce(dur.avg_session_duration, 0) AS avg_session_duration,+ count(*) AS total_screen_views,+ round((count(*) * 1.) / uniq(e.session_id), 2) AS views_per_session,+ (SELECT unique_visitors FROM overall_unique_visitors) AS overall_unique_visitors,+ (SELECT total_sessions FROM overall_unique_visitors) AS overall_total_sessions,+ (SELECT bounce_rate FROM overall_bounce_rate) AS overall_bounce_rate+ FROM events AS e+ LEFT JOIN daily_session_stats AS dss ON ${eventsDateBucket} = dss.date+ LEFT JOIN avg_duration_by_date AS dur ON ${eventsDateBucket} = dur.date+ WHERE e.project_id = ${sql.string(input.projectId)}+ AND e.name = 'screen_view'+ AND ${dateRangeWhere('e.created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawEventFilterWhere)}+ GROUP BY date, dss.bounce_rate, dur.avg_session_duration+ ORDER BY date ASC+ ${fillClause(input.interval, input.startDate, input.endDate)}+ `;+}++// --- top pages -----------------------------------------------------------------++export interface TopPagesQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ rawFilterWhere: string;+ limit: number;+}++export function topPagesQuery(input: TopPagesQueryInput): SqlFragment {+ return sql`+ SELECT+ origin,+ path,+ uniq(session_id) as sessions,+ count() as pageviews,+ sum(revenue) as revenue+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'screen_view'+ AND path != ''+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawFilterWhere)}+ GROUP BY origin, path+ ORDER BY sessions DESC+ LIMIT ${sql.uint64(input.limit)}+ `;+}++// --- top entry/exit --------------------------------------------------------------++export interface DistinctSessionsQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ rawFilterWhere: string;+}++export function distinctSessionsQuery(input: DistinctSessionsQueryInput): SqlFragment {+ return sql`+ SELECT DISTINCT session_id+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawFilterWhere)}+ `;+}++/**+ * `withDistinctSessionsIfNeeded`: when the caller filtered by `path`, a+ * `sessions`-scoped query is redirected through the set of session ids that+ * actually match the page filter on `events`, instead of applying the+ * filters directly to `sessions` (which has no `path` column of its own).+ * Threaded as a WHERE clause, not appended after the finished query text —+ * V1's `.merge()` is equivalent to inserting one more AND'd condition, and+ * doing that after `LIMIT` is invalid SQL.+ */+function distinctSessionsCteHeader(cte: SqlFragment | null): SqlFragment {+ return cte ? sql`WITH distinct_sessions AS (${cte})` : sql.empty;+}++function distinctSessionsConstraint(cte: SqlFragment | null): SqlFragment {+ return cte ? sql`AND id IN (SELECT session_id FROM distinct_sessions)` : sql.empty;+}++export interface TopEntryExitQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ mode: 'entry' | 'exit';+ limit: number;+ /** Mutually exclusive with `distinctSessionsCte`, exactly as V1's `withDistinctSessionsIfNeeded`. */+ rawFilterWhere: string;+ distinctSessionsCte: SqlFragment | null;+}++export function topEntryExitQuery(input: TopEntryExitQueryInput): SqlFragment {+ const [originCol, pathCol] =+ input.mode === 'entry'+ ? ['entry_origin', 'entry_path']+ : ['exit_origin', 'exit_path'];+ return sql`+ ${distinctSessionsCteHeader(input.distinctSessionsCte)}+ SELECT+ ${sql.id(originCol)} AS origin,+ ${sql.id(pathCol)} AS path,+ sum(sign) as sessions,+ sum(sign * screen_view_count) as pageviews,+ sum(revenue * sign) as revenue+ FROM sessions FINAL+ WHERE project_id = ${sql.string(input.projectId)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${+ input.distinctSessionsCte+ ? distinctSessionsConstraint(input.distinctSessionsCte)+ : rawWhere(input.rawFilterWhere)+ }+ GROUP BY ${sql.id(originCol)}, ${sql.id(pathCol)}+ HAVING sum(sign) > 0+ ORDER BY sessions DESC+ LIMIT ${sql.uint64(input.limit)}+ `;+}++// --- top generic (breakdown by a single dimension) ------------------------------++/** `column`/`prefixColumn` are drawn from a closed zod enum upstream — bound+ * as identifiers here rather than trusted as pre-validated text (R3). */+const TOP_GENERIC_COLUMNS = [+ 'referrer',+ 'referrer_name',+ 'referrer_type',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+ 'region',+ 'country',+ 'city',+ 'device',+ 'brand',+ 'model',+ 'browser',+ 'browser_version',+ 'os',+ 'os_version',+] as const;+const TOP_GENERIC_PREFIX_COLUMNS = ['country', 'browser', 'os'] as const;++export interface TopGenericQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ column: string;+ prefixColumn: string | null;+ limit: number;+ /** Mutually exclusive with `distinctSessionsCte`, exactly as V1's `withDistinctSessionsIfNeeded`. */+ rawFilterWhere: string;+ distinctSessionsCte: SqlFragment | null;+}++function topGenericSelect(column: string, prefixColumn: string | null): SqlFragment {+ const parts: SqlFragment[] = [];+ if (prefixColumn) {+ parts.push(sql`${sql.id(prefixColumn, TOP_GENERIC_PREFIX_COLUMNS)} as prefix`);+ }+ parts.push(+ sql`nullIf(${sql.id(column, TOP_GENERIC_COLUMNS)}, '') as name`,+ sql`sum(sign) as sessions`,+ sql`sum(sign * screen_view_count) as pageviews`,+ sql`sum(revenue * sign) as revenue`+ );+ return sql.join(parts);+}++function topGenericGroupBy(column: string, prefixColumn: string | null): SqlFragment {+ return prefixColumn+ ? sql`${sql.id(prefixColumn, TOP_GENERIC_PREFIX_COLUMNS)}, ${sql.id(column, TOP_GENERIC_COLUMNS)}`+ : sql.id(column, TOP_GENERIC_COLUMNS);+}++export function topGenericQuery(input: TopGenericQueryInput): SqlFragment {+ return sql`+ ${distinctSessionsCteHeader(input.distinctSessionsCte)}+ SELECT ${topGenericSelect(input.column, input.prefixColumn)}+ FROM sessions FINAL+ WHERE project_id = ${sql.string(input.projectId)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${+ input.distinctSessionsCte+ ? distinctSessionsConstraint(input.distinctSessionsCte)+ : rawWhere(input.rawFilterWhere)+ }+ GROUP BY ${topGenericGroupBy(input.column, input.prefixColumn)}+ HAVING sum(sign) > 0+ ORDER BY sessions DESC+ LIMIT ${sql.uint64(input.limit)}+ `;+}++export type TopGenericSeriesTopItemsInput = TopGenericQueryInput;++export function topGenericSeriesTopItemsQuery(+ input: TopGenericSeriesTopItemsInput+): SqlFragment {+ return topGenericQuery(input);+}++export interface TopGenericSeriesTimeSeriesInput {+ projectId: string;+ startDate: string;+ endDate: string;+ interval: IInterval;+ column: string;+ prefixColumn: string | null;+ /** Always applied — unlike the top-items query, V1 applies this unconditionally. */+ rawFilterWhere: string;+ /** Additionally applied on top of `rawFilterWhere` when the caller has a page filter. */+ distinctSessionsCte: SqlFragment | null;+}++export function topGenericSeriesTimeSeriesQuery(+ input: TopGenericSeriesTimeSeriesInput+): SqlFragment {+ const groupBy = topGenericGroupBy(input.column, input.prefixColumn);+ return sql`+ ${distinctSessionsCteHeader(input.distinctSessionsCte)}+ SELECT+ ${toStartOf('created_at', input.interval)} AS date,+ ${topGenericSelect(input.column, input.prefixColumn)}+ FROM sessions FINAL+ WHERE project_id = ${sql.string(input.projectId)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawFilterWhere)}+ ${distinctSessionsConstraint(input.distinctSessionsCte)}+ GROUP BY date, ${groupBy}+ HAVING sum(sign) > 0+ ORDER BY date ASC+ ${fillClause(input.interval, input.startDate, input.endDate)}+ `;+}++// --- user journey (sankey of screen_view paths) ----------------------------------++export interface OrderedEventsQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ rawFilterWhere: string;+}++function orderedEventsQuery(input: OrderedEventsQueryInput): SqlFragment {+ return sql`+ SELECT session_id, concat(origin, path) as path, created_at+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'screen_view'+ AND path != ''+ AND path IS NOT NULL+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawFilterWhere)}+ ORDER BY session_id ASC, created_at ASC+ `;+}++function pathsDedupedCte(input: OrderedEventsQueryInput, steps: number): SqlFragment {+ return sql`+ WITH ordered_events AS (${orderedEventsQuery(input)})+ SELECT+ session_id,+ arraySlice(+ arrayFilter(+ (x, i) -> i = 1 OR x != paths_raw[i - 1],+ groupArray(path) as paths_raw,+ arrayEnumerate(paths_raw)+ ),+ 1, ${sql.uint64(steps)}+ ) as paths_deduped+ FROM ordered_events+ GROUP BY session_id+ `;+}++/** The "truncate at first repeat" expression, reused by the entries and transitions queries. */+const TRUNCATED_PATHS = sql`+ if(+ arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) = 0,+ paths_deduped,+ arraySlice(+ paths_deduped,+ 1,+ arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) - 1+ )+ )+`;++export interface TopEntriesQueryInput extends OrderedEventsQueryInput {+ steps: number;+ topEntries: number;+}++export function topEntriesQuery(input: TopEntriesQueryInput): SqlFragment {+ const sessionPaths = sql`+ WITH paths_deduped_cte AS (${pathsDedupedCte(input, input.steps)})+ SELECT+ session_id,+ ${TRUNCATED_PATHS} as paths,+ paths[1] as entry_page+ FROM paths_deduped_cte+ HAVING length(paths) >= 2+ `;+ return sql`+ WITH session_paths AS (${sessionPaths})+ SELECT entry_page, count() as count+ FROM session_paths+ GROUP BY entry_page+ ORDER BY count DESC+ LIMIT ${sql.uint64(input.topEntries)}+ `;+}++export interface TransitionsQueryInput extends OrderedEventsQueryInput {+ steps: number;+ topEntryPages: string[];+}++export function transitionsQuery(input: TransitionsQueryInput): SqlFragment {+ const sessionPaths = sql`+ SELECT ${TRUNCATED_PATHS} as paths+ FROM paths_deduped_cte+ HAVING length(paths) >= 2+ AND paths[1] IN ${sql.array('String', input.topEntryPages)}+ `;+ return sql`+ WITH+ paths_deduped_cte AS (${pathsDedupedCte(input, input.steps)}),+ session_paths AS (${sessionPaths})+ SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value+ FROM (+ SELECT arrayJoin(arrayMap(i -> (paths[i], paths[i + 1], i), range(1, length(paths)))) as pair+ FROM session_paths+ WHERE length(paths) >= 2+ )+ GROUP BY source, target, step+ ORDER BY step ASC, value DESC+ `;+}++// --- top events ------------------------------------------------------------------++export interface TopEventsQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ rawFilterWhere: string;+ excludeEvents: string[];+}++export function topEventsQuery(input: TopEventsQueryInput): SqlFragment {+ const exclude =+ input.excludeEvents.length > 0+ ? sql`AND name NOT IN ${sql.array('String', input.excludeEvents)}`+ : sql.empty;+ return sql`+ SELECT name, count() as count+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawFilterWhere)}+ ${exclude}+ GROUP BY name+ ORDER BY count DESC+ LIMIT 1000+ `;+}++// --- top link-out ------------------------------------------------------------------++export interface TopLinkOutQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ rawFilterWhere: string;+}++export function topLinkOutQuery(input: TopLinkOutQueryInput): SqlFragment {+ const hrefKey = compiledText(getSelectPropertyKey('properties.href'));+ return sql`+ SELECT ${hrefKey} as href, count() as count+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'link_out'+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawFilterWhere)}+ AND ${hrefKey} IS NOT NULL AND ${hrefKey} != ''+ GROUP BY href+ ORDER BY count DESC+ LIMIT 1000+ `;+}++// --- map data ------------------------------------------------------------------++export interface MapDataQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ rawFilterWhere: string;+}++export function mapDataQuery(input: MapDataQueryInput): SqlFragment {+ return sql`+ SELECT+ nullIf(country, '') as country,+ nullIf(region, '') as region,+ nullIf(city, '') as city,+ uniq(session_id) as count+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ ${rawWhere(input.rawFilterWhere)}+ AND country IS NOT NULL AND country != ''+ GROUP BY country, region, city+ ORDER BY count DESC+ LIMIT 1000+ `;+}++// --- live data (dashboard's 30-minute rolling window) ---------------------------++export interface LiveTotalSessionsQueryInput {+ projectId: string;+}++export function liveTotalSessionsQuery(input: LiveTotalSessionsQueryInput): SqlFragment {+ return sql`+ SELECT uniq(session_id) as total_sessions+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND created_at >= now() - INTERVAL 30 MINUTE+ `;+}++export function liveMinuteCountsQuery(input: LiveTotalSessionsQueryInput): SqlFragment {+ return sql`+ SELECT+ toStartOfMinute(created_at) as minute,+ uniq(session_id) as session_count,+ uniq(profile_id) as visitor_count+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND created_at >= now() - INTERVAL 30 MINUTE+ GROUP BY minute+ ORDER BY minute ASC+ WITH FILL FROM toStartOfMinute(now() - INTERVAL 30 MINUTE) TO toStartOfMinute(now()) STEP INTERVAL 1 MINUTE+ `;+}++export function liveMinuteReferrersQuery(input: LiveTotalSessionsQueryInput): SqlFragment {+ return sql`+ SELECT+ toStartOfMinute(created_at) as minute,+ referrer_name,+ uniq(session_id) as count+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND created_at >= now() - INTERVAL 30 MINUTE+ AND referrer_name != ''+ AND referrer_name IS NOT NULL+ GROUP BY minute, referrer_name+ ORDER BY minute ASC, count DESC+ `;+}++export function liveReferrersQuery(input: LiveTotalSessionsQueryInput): SqlFragment {+ return sql`+ SELECT referrer_name as referrer, uniq(session_id) as count+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND created_at >= now() - INTERVAL 30 MINUTE+ AND referrer_name != ''+ AND referrer_name IS NOT NULL+ GROUP BY referrer_name+ ORDER BY count DESC+ LIMIT 10+ `;+}diff --git a/packages/core/src/modules/overview/src/pages.sql.proof.md b/packages/core/src/modules/overview/src/pages.sql.proof.mdnew file mode 100644index 000000000..3f3c9974a--- /dev/null+++ b/packages/core/src/modules/overview/src/pages.sql.proof.md@@ -0,0 +1,62 @@+# pages.sql.ts — V1 -> V2 result-set proof (M7-005)++Same methodology and data as `overview.sql.proof.md` (whole-method comparison against+unmodified V1, plus a per-query render + execution pass) — see that file for the full+writeup. This file covers `PagesService` and `getPageConversionsCore`.++- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel`. Project: `skills-directory`,+ window `2026-08-01 00:00:00`..`2026-08-08 00:00:00` UTC.++## Whole-method comparison — verdict++| Case | Verdict |+|---|---|+| `PagesService.getTopPages` | title column non-deterministic in **V1 itself** — see `overview.sql.proof.md`'s `anyLast` section. `sessions`/`pageviews`/`avg_duration`/`bounce_rate` IDENTICAL for all 20 rows. |+| `PagesService.getTopPages` (search: `'a'`) | same title-driven flicker (the search clause itself matches on `pt.title LIKE '%a%'`, so a flickering title changes which rows the search *keeps* — a downstream, not independent, effect); numeric columns IDENTICAL where titles agree. |+| `PagesService.getPageTimeseries` | **IDENTICAL** — 3103 rows |+| `getPageConversionsCore` | **IDENTICAL** — 20 rows |++`getPageConversionsCore` was already parameter-safe-ish (V1 used `sqlstring.escape` inline+rather than clix) but not through the `sql` tag; converted the same way as every other query+here — literals to `{pN:Type}` params, identical row order and values proven against the same+data.++## Per-query render + execution proof++| Query | Rows | Rows read | Wall |+|---|---|---|---|+| `topPagesQuery` | 20 | 229,342 | 62 ms |+| `topPagesQuery` (search: `'a'`) | 20 | 229,342 | 50 ms |+| `pageTimeseriesQuery` | 3103 | 49,152 | 18 ms |+| `pageConversionsQuery` | 20 | 147,456 | 68 ms |++```sql+-- pageConversionsQuery+WITH+ conversion_events AS (+ SELECT profile_id, created_at AS conv_time FROM events+ WHERE project_id = {p1:String} AND name = {p2:String}+ AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String})+ ),+ views_before_conversions AS (+ SELECT DISTINCT e.profile_id, e.path, e.origin FROM events AS e+ INNER JOIN conversion_events AS c ON e.profile_id = c.profile_id+ WHERE e.project_id = {p5:String} AND e.name = 'screen_view' AND e.path != ''+ AND e.created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String})+ AND e.created_at < c.conv_time AND e.created_at >= c.conv_time - INTERVAL {p8:UInt64} HOUR+ ),+ total_visitors AS (+ SELECT path, origin, uniq(session_id) AS visitors FROM events+ WHERE project_id = {p9:String} AND name = 'screen_view' AND path != ''+ AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String})+ GROUP BY path, origin+ )+SELECT vbc.path, vbc.origin, count() AS unique_converters, any(tv.visitors) AS total_visitors,+ round(100.0 * count() / any(tv.visitors), 2) AS conversion_rate+FROM views_before_conversions AS vbc+LEFT JOIN total_visitors AS tv ON vbc.path = tv.path AND vbc.origin = tv.origin+GROUP BY vbc.path, vbc.origin ORDER BY unique_converters DESC LIMIT {p12:UInt64}+-- params: {"p1":"skills-directory","p2":"screen_view","p3":"2026-08-01 00:00:00","p4":"2026-08-08 00:00:00","p5":"skills-directory","p6":"2026-08-01 00:00:00","p7":"2026-08-08 00:00:00","p8":24,"p9":"skills-directory","p10":"2026-08-01 00:00:00","p11":"2026-08-08 00:00:00","p12":20}+```++Full renders exercised by `pages.sql.test.ts`'s `EXPLAIN`-based parse gate.diff --git a/packages/core/src/modules/overview/src/pages.sql.test.ts b/packages/core/src/modules/overview/src/pages.sql.test.tsnew file mode 100644index 000000000..64712ef59--- /dev/null+++ b/packages/core/src/modules/overview/src/pages.sql.test.ts@@ -0,0 +1,76 @@+/**+ * SQL-shape tests for `pages.sql.ts`. Same EXPLAIN-based strategy as+ * `overview.sql.test.ts` — see its header comment.+ */++import { beforeAll, describe, it } from 'bun:test';+import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';++const PROJECT_ID = 'test-sql-validation';+const START = '2026-08-01 00:00:00';+const END = '2026-08-08 00:00:00';++let ch: typeof import('@openpanel/db/src/clickhouse/client').ch;+let PG: typeof import('./pages.sql');++async function explain(fragment: SqlFragment): Promise<void> {+ const { query, query_params } = fragment.toStatement();+ await ch.command({ query: `EXPLAIN ${query}`, query_params });+}++beforeAll(async () => {+ ({ ch } = await import('@openpanel/db/src/clickhouse/client'));+ PG = await import('./pages.sql');+});++describe('pages.sql — parses against ClickHouse', () => {+ it('topPagesQuery — no search', async () => {+ await explain(+ PG.topPagesQuery({ projectId: PROJECT_ID, startDate: START, endDate: END, limit: 20 })+ );+ });++ it('topPagesQuery — with search (the OR-grouped LIKE clause)', async () => {+ await explain(+ PG.topPagesQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ search: 'pricing',+ limit: 20,+ })+ );+ });++ it('topPagesQuery — no limit', async () => {+ await explain(+ PG.topPagesQuery({ projectId: PROJECT_ID, startDate: START, endDate: END })+ );+ });++ it('pageTimeseriesQuery — with origin/path filters, week bucket', async () => {+ await explain(+ PG.pageTimeseriesQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ interval: 'week',+ filterOrigin: 'https://example.com',+ filterPath: '/pricing',+ })+ );+ });++ it('pageConversionsQuery', async () => {+ await explain(+ PG.pageConversionsQuery({+ projectId: PROJECT_ID,+ startDate: START,+ endDate: END,+ conversionEvent: 'purchase',+ windowHours: 24,+ limit: 100,+ })+ );+ });+});diff --git a/packages/core/src/modules/overview/src/pages.sql.ts b/packages/core/src/modules/overview/src/pages.sql.tsnew file mode 100644index 000000000..dbfe43f68--- /dev/null+++ b/packages/core/src/modules/overview/src/pages.sql.ts@@ -0,0 +1,192 @@+// Every ClickHouse query PagesService/getPageConversionsCore runs, as pure+// `sql` fragments (ADR-013). Converted 1:1 from+// packages/db/src/services/pages.service.ts: the SQL text is V1's, with every+// value bound as a `{pN:Type}` parameter instead of clix's inline+// interpolation or (for `getPageConversionsCore`) `sqlstring.escape`. Result+// sets diffed against V1's on the local prod-copy — see pages.sql.proof.md.++import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import type { IInterval } from '@openpanel/validation';+import { fillClause, toStartOf } from './overview.sql';++function toDateTimeLiteral(value: string): string {+ return new Date(value).toISOString().slice(0, 19).replace('T', ' ');+}++function dateRangeWhere(column: string, startDate: string, endDate: string): SqlFragment {+ return sql`${sql.id(column)} BETWEEN toDateTime(${sql.string(toDateTimeLiteral(startDate))}) AND toDateTime(${sql.string(toDateTimeLiteral(endDate))})`;+}++export interface TopPagesQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ search?: string;+ limit?: number;+}++function searchClause(search: string | undefined): SqlFragment {+ if (!search) {+ return sql.empty;+ }+ const term = sql.string(`%${search}%`);+ return sql`AND (e.path LIKE ${term} OR e.origin LIKE ${term} OR pt.title LIKE ${term})`;+}++export function topPagesQuery(input: TopPagesQueryInput): SqlFragment {+ const titlesCte = sql`+ SELECT concat(origin, path) as page_key, anyLast(properties['__title']) as title+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'screen_view'+ AND created_at >= now() - INTERVAL 30 DAY+ GROUP BY origin, path+ `;++ const screenViewDurationsCte = sql`+ SELECT+ project_id,+ session_id,+ path,+ origin,+ dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at)) AS duration+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'screen_view'+ AND path != ''+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ `;++ const sessionsSubquery = sql`+ SELECT id, project_id, is_bounce+ FROM sessions FINAL+ WHERE project_id = ${sql.string(input.projectId)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ AND sign = 1+ `;++ const limitClause =+ input.limit === undefined ? sql.empty : sql`LIMIT ${sql.uint64(input.limit)}`;++ return sql`+ WITH+ page_titles AS (${titlesCte}),+ screen_view_durations AS (${screenViewDurationsCte})+ SELECT+ e.origin as origin,+ e.path as path,+ coalesce(pt.title, '') as title,+ uniq(e.session_id) as sessions,+ count() as pageviews,+ round(avg(e.duration) / 1000 / 60, 2) as avg_duration,+ round(+ (uniqIf(e.session_id, s.is_bounce = 1) * 100.0) /+ nullIf(uniq(e.session_id), 0),+ 2+ ) as bounce_rate+ FROM screen_view_durations e+ LEFT JOIN (${sessionsSubquery}) s ON e.session_id = s.id AND e.project_id = s.project_id+ LEFT JOIN page_titles pt ON concat(e.origin, e.path) = pt.page_key+ WHERE 1+ ${searchClause(input.search)}+ GROUP BY e.origin, e.path, pt.title+ ORDER BY sessions DESC+ ${limitClause}+ `;+}++export interface PageTimeseriesQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ interval: IInterval;+ filterOrigin?: string;+ filterPath?: string;+}++export function pageTimeseriesQuery(input: PageTimeseriesQueryInput): SqlFragment {+ const originFilter = input.filterOrigin+ ? sql`AND e.origin = ${sql.string(input.filterOrigin)}`+ : sql.empty;+ const pathFilter = input.filterPath+ ? sql`AND e.path = ${sql.string(input.filterPath)}`+ : sql.empty;++ return sql`+ SELECT+ e.origin as origin,+ e.path as path,+ ${toStartOf('e.created_at', input.interval)} AS date,+ count() as pageviews,+ uniq(e.session_id) as sessions+ FROM events e+ WHERE e.project_id = ${sql.string(input.projectId)}+ AND e.name = 'screen_view'+ AND e.path != ''+ AND ${dateRangeWhere('e.created_at', input.startDate, input.endDate)}+ ${originFilter}+ ${pathFilter}+ GROUP BY e.origin, e.path, date+ ORDER BY date ASC+ ${fillClause(input.interval, input.startDate, input.endDate)}+ `;+}++export interface PageConversionsQueryInput {+ projectId: string;+ startDate: string;+ endDate: string;+ conversionEvent: string;+ windowHours: number;+ limit: number;+}++export function pageConversionsQuery(input: PageConversionsQueryInput): SqlFragment {+ const conversionEvents = sql`+ SELECT profile_id, created_at AS conv_time+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = ${sql.string(input.conversionEvent)}+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ `;++ const viewsBeforeConversions = sql`+ SELECT DISTINCT e.profile_id, e.path, e.origin+ FROM events AS e+ INNER JOIN conversion_events AS c ON e.profile_id = c.profile_id+ WHERE e.project_id = ${sql.string(input.projectId)}+ AND e.name = 'screen_view'+ AND e.path != ''+ AND ${dateRangeWhere('e.created_at', input.startDate, input.endDate)}+ AND e.created_at < c.conv_time+ AND e.created_at >= c.conv_time - INTERVAL ${sql.uint64(input.windowHours)} HOUR+ `;++ const totalVisitors = sql`+ SELECT path, origin, uniq(session_id) AS visitors+ FROM events+ WHERE project_id = ${sql.string(input.projectId)}+ AND name = 'screen_view'+ AND path != ''+ AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}+ GROUP BY path, origin+ `;++ return sql`+ WITH+ conversion_events AS (${conversionEvents}),+ views_before_conversions AS (${viewsBeforeConversions}),+ total_visitors AS (${totalVisitors})+ SELECT+ vbc.path,+ vbc.origin,+ count() AS unique_converters,+ any(tv.visitors) AS total_visitors,+ round(100.0 * count() / any(tv.visitors), 2) AS conversion_rate+ FROM views_before_conversions AS vbc+ LEFT JOIN total_visitors AS tv ON vbc.path = tv.path AND vbc.origin = tv.origin+ GROUP BY vbc.path, vbc.origin+ ORDER BY unique_converters DESC+ LIMIT ${sql.uint64(input.limit)}+ `;+}diff --git a/packages/core/src/modules/overview/src/run-query.ts b/packages/core/src/modules/overview/src/run-query.tsnew file mode 100644index 000000000..021d495fa--- /dev/null+++ b/packages/core/src/modules/overview/src/run-query.ts@@ -0,0 +1,52 @@+// The overview module's one bridge to a ClickHouse client.+//+// `OverviewService`/`PagesService` keep V1's `constructor(client: typeof ch)`+// shape — `page-performance.ts` (mcp) constructs a fresh `PagesService` per+// call specifically to dodge a module-singleton mocking hazard, so a caller+// may still inject its own client. The module-scope `overviewService`/+// `pagesService` singletons construct with none, so the round-robin `ch`+// singleton is imported lazily here instead — importing+// `@openpanel/db/src/clickhouse/client` eagerly constructs a real ClickHouse+// client and a pino logger, and this module reaches nearly every core test+// file through the barrel (same reasoning as chart's `run-query.ts`).+//+// `chQuery` always goes through that singleton's `withRetry`, so it can't+// stand in for a caller-supplied client; this mirrors its exact behaviour+// (params, `session_timezone`, the same Int-meta coercion) either way.++import type { ClickHouseClient } from '@clickhouse/client';+import { type SqlFragment, toStatement } from '@openpanel/db/src/clickhouse/sql';++function loadChClient() {+ return import('@openpanel/db/src/clickhouse/client');+}++export async function runQuery<T extends object>(+ client: ClickHouseClient | undefined,+ statement: SqlFragment,+ timezone: string+): Promise<T[]> {+ const resolvedClient = client ?? (await loadChClient()).ch;+ const { query, query_params } = toStatement(statement);+ const result = await resolvedClient.query({+ query,+ query_params: Object.keys(query_params).length ? query_params : undefined,+ clickhouse_settings: { session_timezone: timezone },+ });+ const json = await result.json<T>();+ const keys = Object.keys(json.data[0] ?? {});+ // Same coercion `chQuery` applies: ClickHouse's JSON format returns every+ // Int*/UInt* column as a string, so the caller's shape (`count: number`)+ // only holds if we parse it back out here, same as V1's clix did.+ return json.data.map((item) =>+ keys.reduce((acc, key) => {+ const meta = json.meta?.find((m) => m.name === key);+ const value = item[key as keyof T];+ acc[key as keyof T] =+ value && meta?.type.includes('Int')+ ? (Number.parseFloat(value as string) as T[keyof T])+ : value;+ return acc;+ }, {} as T)+ );+}diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.tsindex 5b0972818..c27a93d73 100644--- a/packages/core/src/rpc.router.ts+++ b/packages/core/src/rpc.router.ts@@ -21,6 +21,7 @@ import { integrationRouter } from './modules/integration/integration.rpc';import { notificationRouter } from './modules/notification/notification.rpc';import { onboardingRouter } from './modules/onboarding/onboarding.rpc';import { organizationRouter } from './modules/organization/organization.rpc';+import { overviewRouter } from './modules/overview/overview.rpc';import { profileRouter } from './modules/profile/profile.rpc';import { projectRouter } from './modules/project/project.rpc';import { realtimeRouter } from './modules/realtime/realtime.rpc';@@ -57,6 +58,7 @@ export const appRouter = createTRPCRouter({profile: profileRouter,group: groupRouter,chart: chartRouter,+ overview: overviewRouter,});export type AppRouter = typeof appRouter;diff --git a/packages/db/src/services/overview.service.ts b/packages/db/src/services/overview.service.tsindex 00bf1859a..a4493c952 100644--- a/packages/db/src/services/overview.service.ts+++ b/packages/db/src/services/overview.service.ts@@ -1,1637 +1,37 @@-import { average, sum } from '@openpanel/common';-import { chartColors } from '@openpanel/constants';-import { type IChartEventFilter, zTimeInterval } from '@openpanel/validation';-import sqlstring from 'sqlstring';-import { z } from 'zod';-import {- ch,- convertClickhouseDateToJs,- isClickhouseDefaultMinDate,- TABLE_NAMES,-} from '../clickhouse/client';-import { clix } from '../clickhouse/query-builder';-import {- getEventFiltersWhereClause,- getSelectPropertyKey,-} from './chart.service';--// Constants-const ROLLUP_DATE_PREFIX = '1970-01-01';--// Toggle revenue tracking in overview queries-const INCLUDE_REVENUE = true; // TODO: Make this configurable later--// Maximum number of records to return (for detail modals)-const MAX_RECORDS_LIMIT = 1000;--const COLUMN_PREFIX_MAP: Record<string, string> = {- region: 'country',- city: 'country',- browser_version: 'browser',- os_version: 'os',-};--const WHITELISTED_FILTERS = [- 'os',- 'path',- 'city',- 'brand',- 'model',- 'origin',- 'region',- 'device',- 'revenue',- 'country',- 'browser',- 'referrer',- 'os_version',- 'referrer_name',- 'browser_version',- 'referrer_type',- 'utm_source',- 'utm_medium',- 'utm_campaign',- 'utm_term',- 'utm_content',-];--// Columns that exist on the sessions table but not on events — on events-// they're stored inside the properties map under __query.utm_*.-const UTM_COLUMNS = [- 'utm_source',- 'utm_medium',- 'utm_campaign',- 'utm_term',- 'utm_content',-];--// Types-type MetricsRow = {- bounce_rate: number;- unique_visitors: number;- total_sessions: number;- avg_session_duration: number;- total_screen_views: number;- views_per_session: number;-};--type MetricsSeriesRow = MetricsRow & { date: string; total_revenue: number };--export const zGetMetricsInput = z.object({- projectId: z.string(),- filters: z.array(z.any()),- startDate: z.string(),- endDate: z.string(),- interval: zTimeInterval,-});--export type IGetMetricsInput = z.infer<typeof zGetMetricsInput> & {- timezone: string;-};--export const zGetTopPagesInput = z.object({- projectId: z.string(),- filters: z.array(z.any()),- startDate: z.string(),- endDate: z.string(),- limit: z.number().min(1).max(1000).optional(),-});--export type IGetTopPagesInput = z.infer<typeof zGetTopPagesInput> & {- timezone: string;-};--export const zGetTopEntryExitInput = z.object({- projectId: z.string(),- filters: z.array(z.any()),- startDate: z.string(),- endDate: z.string(),- mode: z.enum(['entry', 'exit']),- limit: z.number().min(1).max(1000).optional(),-});--export type IGetTopEntryExitInput = z.infer<typeof zGetTopEntryExitInput> & {- timezone: string;-};--export const zGetTopGenericInput = z.object({- projectId: z.string(),- filters: z.array(z.any()),- startDate: z.string(),- endDate: z.string(),- column: z.enum([- // Referrers- 'referrer',- 'referrer_name',- 'referrer_type',- 'utm_source',- 'utm_medium',- 'utm_campaign',- 'utm_term',- 'utm_content',- // Geo- 'region',- 'country',- 'city',- // Device- 'device',- 'brand',- 'model',- 'browser',- 'browser_version',- 'os',- 'os_version',- ]),-});--export type IGetTopGenericInput = z.infer<typeof zGetTopGenericInput> & {- timezone: string;-};--export const zGetTopGenericSeriesInput = zGetTopGenericInput.extend({- interval: zTimeInterval,-});--export type IGetTopGenericSeriesInput = z.infer<- typeof zGetTopGenericSeriesInput-> & {- timezone: string;-};--export const zGetUserJourneyInput = z.object({- projectId: z.string(),- filters: z.array(z.any()),- startDate: z.string(),- endDate: z.string(),- steps: z.number().min(2).max(10).default(5),-});--export type IGetUserJourneyInput = z.infer<typeof zGetUserJourneyInput> & {- timezone: string;-};--export const zGetTopEventsInput = z.object({- projectId: z.string(),- filters: z.array(z.any()),- startDate: z.string(),- endDate: z.string(),- excludeEvents: z.array(z.string()).optional(),-});--export type IGetTopEventsInput = z.infer<typeof zGetTopEventsInput> & {- timezone: string;-};--export const zGetTopLinkOutInput = z.object({- projectId: z.string(),- filters: z.array(z.any()),- startDate: z.string(),- endDate: z.string(),-});--export type IGetTopLinkOutInput = z.infer<typeof zGetTopLinkOutInput> & {- timezone: string;-};--export const zGetMapDataInput = z.object({- projectId: z.string(),- filters: z.array(z.any()),- startDate: z.string(),- endDate: z.string(),-});--export type IGetMapDataInput = z.infer<typeof zGetMapDataInput> & {- timezone: string;-};--export class OverviewService {- constructor(private client: typeof ch) {}-- private getFillConfig(interval: string, startDate: string, endDate: string) {- const useDateOnly = ['month', 'week'].includes(interval);- return {- from: clix.toStartOf(- clix.datetime(startDate, useDateOnly ? 'toDate' : 'toDateTime'),- interval as any- ),- to: clix.datetime(endDate, useDateOnly ? 'toDate' : 'toDateTime'),- step: clix.toInterval('1', interval as any),- };- }-- private createRevenueQuery({- projectId,- startDate,- endDate,- interval,- timezone,- filters,- }: {- projectId: string;- startDate: string;- endDate: string;- interval: string;- timezone: string;- filters: IChartEventFilter[];- }) {- return clix(this.client, timezone)- .select<{ date: string; total_revenue: number }>([- `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,- 'sum(revenue) AS total_revenue',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', projectId)- .where('name', '=', 'revenue')- .where('revenue', '>', 0)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(this.getRawWhereClause('events', filters))- .groupBy(['date'])- .rollup()- .transform({- date: (item) => convertClickhouseDateToJs(item.date).toISOString(),- });- }-- private mergeRevenueIntoSeries<T extends { date: string }>(- series: T[],- revenueData: { date: string; total_revenue: number }[]- ): (T & { total_revenue: number })[] {- const revenueByDate = new Map(- revenueData- .filter((r) => !isClickhouseDefaultMinDate(r.date))- .map((r) => [r.date, r.total_revenue])- );- return series.map((row) => ({- ...row,- total_revenue: revenueByDate.get(row.date) ?? 0,- }));- }-- private getOverallRevenue(- revenueData: { date: string; total_revenue: number }[]- ): number {- return (- revenueData.find((r) => isClickhouseDefaultMinDate(r.date))- ?.total_revenue ?? 0- );- }-- private withDistinctSessionsIfNeeded<T>(- query: ReturnType<typeof clix>,- params: {- filters: IChartEventFilter[];- projectId: string;- startDate: string;- endDate: string;- timezone: string;- }- ): ReturnType<typeof clix> {- if (!this.isPageFilter(params.filters)) {- query.rawWhere(this.getRawWhereClause('sessions', params.filters));- return query;- }-- return clix(this.client, params.timezone)- .with('distinct_sessions', this.getDistinctSessions(params))- .merge(query)- .where(- 'id',- 'IN',- clix.exp('(SELECT session_id FROM distinct_sessions)')- );- }-- isPageFilter(filters: IChartEventFilter[]) {- return filters.some((filter) => filter.name === 'path' && filter.value);- }-- async getMetrics({- projectId,- filters,- startDate,- endDate,- interval,- timezone,- }: IGetMetricsInput): Promise<{- metrics: {- bounce_rate: number;- unique_visitors: number;- total_sessions: number;- avg_session_duration: number;- total_screen_views: number;- views_per_session: number;- total_revenue: number;- };- series: {- date: string;- bounce_rate: number;- unique_visitors: number;- total_sessions: number;- avg_session_duration: number;- total_screen_views: number;- views_per_session: number;- total_revenue: number;- }[];- }> {- return this.isPageFilter(filters)- ? this.getMetricsWithPageFilter({- projectId,- filters,- startDate,- endDate,- interval,- timezone,- })- : this.getMetricsFromSessions({- projectId,- filters,- startDate,- endDate,- interval,- timezone,- });- }-- private async getMetricsFromSessions({- projectId,- filters,- startDate,- endDate,- interval,- timezone,- }: IGetMetricsInput): Promise<{- metrics: MetricsRow & { total_revenue: number };- series: MetricsSeriesRow[];- }> {- const where = this.getRawWhereClause('sessions', filters);- const fillConfig = this.getFillConfig(interval, startDate, endDate);-- // Session metrics query- const sessionQuery = clix(this.client, timezone)- .select<{- date: string;- bounce_rate: number;- unique_visitors: number;- total_sessions: number;- avg_session_duration: number;- total_screen_views: number;- views_per_session: number;- }>([- `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,- 'round(sum(sign * is_bounce) * 100.0 / sum(sign), 2) as bounce_rate',- 'uniqIf(profile_id, sign > 0) AS unique_visitors',- 'sum(sign) AS total_sessions',- 'round(avgIf(duration, duration > 0 AND sign > 0), 2) / 1000 AS _avg_session_duration',- 'if(isNaN(_avg_session_duration), 0, _avg_session_duration) AS avg_session_duration',- 'sum(sign * screen_view_count) AS total_screen_views',- 'round(sum(sign * screen_view_count) * 1.0 / sum(sign), 2) AS views_per_session',- ])- .from('sessions')- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .where('project_id', '=', projectId)- .rawWhere(where)- .groupBy(['date'])- .having('sum(sign)', '>', 0)- .rollup()- .orderBy('date', 'ASC')- .fill(fillConfig.from, fillConfig.to, fillConfig.step)- .transform({- date: (item) => new Date(item.date).toISOString(),- });-- // Revenue query- const revenueQuery = this.createRevenueQuery({- projectId,- startDate,- endDate,- interval,- timezone,- filters,- });-- // Execute both queries in parallel and merge results- const [sessionRes, revenueRes] = await Promise.all([- sessionQuery.execute(),- revenueQuery.execute(),- ]);-- const overallRevenue = this.getOverallRevenue(revenueRes);- const series = this.mergeRevenueIntoSeries(sessionRes.slice(1), revenueRes);-- return {- metrics: {- bounce_rate: sessionRes[0]?.bounce_rate ?? 0,- unique_visitors: sessionRes[0]?.unique_visitors ?? 0,- total_sessions: sessionRes[0]?.total_sessions ?? 0,- avg_session_duration: sessionRes[0]?.avg_session_duration ?? 0,- total_screen_views: sessionRes[0]?.total_screen_views ?? 0,- views_per_session: sessionRes[0]?.views_per_session ?? 0,- total_revenue: overallRevenue,- },- series,- };- }-- private async getMetricsWithPageFilter({- projectId,- filters,- startDate,- endDate,- interval,- timezone,- }: IGetMetricsInput): Promise<{- metrics: MetricsRow & { total_revenue: number };- series: MetricsSeriesRow[];- }> {- const where = this.getRawWhereClause('sessions', filters);- const fillConfig = this.getFillConfig(interval, startDate, endDate);-- // CTE: per-event screen_view durations via window function- const rawScreenViewDurationsQuery = clix(this.client, timezone)- .select([- `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,- `dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at)) AS duration`,- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', projectId)- .where('name', '=', 'screen_view')- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(this.getRawWhereClause('events', filters));-- // CTE: avg duration per date bucket- const avgDurationByDateQuery = clix(this.client, timezone)- .select([- 'date',- 'round(avgIf(duration, duration > 0), 2) / 1000 AS avg_session_duration',- ])- .from('raw_screen_view_durations')- .groupBy(['date']);-- // Session aggregation with bounce rates- const sessionAggQuery = clix(this.client, timezone)- .select([- `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,- 'round((countIf(is_bounce = 1 AND sign = 1) * 100.) / countIf(sign = 1), 2) AS bounce_rate',- ])- .from(TABLE_NAMES.sessions, true)- .where('sign', '=', 1)- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(where)- .groupBy(['date'])- .rollup()- .orderBy('date', 'ASC');-- // Overall unique visitors- const overallUniqueVisitorsQuery = clix(this.client, timezone)- .select([- 'uniq(profile_id) AS unique_visitors',- 'uniq(session_id) AS total_sessions',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', projectId)- .where('name', '=', 'screen_view')- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(this.getRawWhereClause('events', filters));-- // Use toDate for month/week intervals, toDateTime for others- const rollupDate =- interval === 'month' || interval === 'week'- ? clix.date(ROLLUP_DATE_PREFIX)- : clix.datetime(`${ROLLUP_DATE_PREFIX} 00:00:00`);-- // Main metrics query (without revenue)- const mainQuery = clix(this.client, timezone)- .with('session_agg', sessionAggQuery)- .with(- 'overall_bounce_rate',- clix(this.client, timezone)- .select(['bounce_rate'])- .from('session_agg')- .where('date', '=', rollupDate)- )- .with(- 'daily_session_stats',- clix(this.client, timezone)- .select(['date', 'bounce_rate'])- .from('session_agg')- .where('date', '!=', rollupDate)- )- .with('overall_unique_visitors', overallUniqueVisitorsQuery)- .with('raw_screen_view_durations', rawScreenViewDurationsQuery)- .with('avg_duration_by_date', avgDurationByDateQuery)- .select<{- date: string;- bounce_rate: number;- unique_visitors: number;- total_sessions: number;- avg_session_duration: number;- total_screen_views: number;- views_per_session: number;- overall_unique_visitors: number;- overall_total_sessions: number;- overall_bounce_rate: number;- }>([- `${clix.toStartOf('e.created_at', interval as any)} AS date`,- 'dss.bounce_rate as bounce_rate',- 'uniq(e.profile_id) AS unique_visitors',- 'uniq(e.session_id) AS total_sessions',- 'coalesce(dur.avg_session_duration, 0) AS avg_session_duration',- 'count(*) AS total_screen_views',- 'round((count(*) * 1.) / uniq(e.session_id), 2) AS views_per_session',- '(SELECT unique_visitors FROM overall_unique_visitors) AS overall_unique_visitors',- '(SELECT total_sessions FROM overall_unique_visitors) AS overall_total_sessions',- '(SELECT bounce_rate FROM overall_bounce_rate) AS overall_bounce_rate',- ])- .from(`${TABLE_NAMES.events} AS e`)- .leftJoin(- 'daily_session_stats AS dss',- `${clix.toStartOf('e.created_at', interval as any)} = dss.date`- )- .leftJoin(- 'avg_duration_by_date AS dur',- `${clix.toStartOf('e.created_at', interval as any)} = dur.date`- )- .where('e.project_id', '=', projectId)- .where('e.name', '=', 'screen_view')- .where('e.created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(this.getRawWhereClause('events', filters))- .groupBy(['date', 'dss.bounce_rate', 'dur.avg_session_duration'])- .orderBy('date', 'ASC')- .fill(fillConfig.from, fillConfig.to, fillConfig.step)- .transform({- date: (item) => new Date(item.date).toISOString(),- });-- // Revenue query- const revenueQuery = this.createRevenueQuery({- projectId,- startDate,- endDate,- interval,- timezone,- filters,- });-- // Execute both queries in parallel and merge results- const [mainRes, revenueRes] = await Promise.all([- mainQuery.execute(),- revenueQuery.execute(),- ]);-- const overallRevenue = this.getOverallRevenue(revenueRes);- const series = this.mergeRevenueIntoSeries(mainRes, revenueRes);-- const anyRowWithData = mainRes.find(- (item) =>- item.overall_bounce_rate !== null ||- item.overall_total_sessions !== null ||- item.overall_unique_visitors !== null- );-- return {- metrics: {- bounce_rate: anyRowWithData?.overall_bounce_rate ?? 0,- unique_visitors: anyRowWithData?.overall_unique_visitors ?? 0,- total_sessions: anyRowWithData?.overall_total_sessions ?? 0,- avg_session_duration: average(- mainRes.map((item) => item.avg_session_duration)- ),- total_screen_views: sum(mainRes.map((item) => item.total_screen_views)),- views_per_session: average(- mainRes.map((item) => item.views_per_session)- ),- total_revenue: overallRevenue,- },- series,- };- }-- getRawWhereClause(type: 'events' | 'sessions', filters: IChartEventFilter[]) {- const where = getEventFiltersWhereClause(- filters.flatMap((item) => {- if (!WHITELISTED_FILTERS.includes(item.name)) {- return []- }- if (type === 'sessions') {- if (item.name === 'path') {- return [{ ...item, name: 'entry_path' }];- }- if (item.name === 'origin') {- return [{ ...item, name: 'entry_origin' }];- }- if (item.name.startsWith('properties.__query.utm_')) {- return [- {- ...item,- name: item.name.replace('properties.__query.utm_', 'utm_'),- },- ];- }- // sessions table has no `properties` map for arbitrary keys —- // drop them instead of generating an invalid WHERE clause.- if (item.name.startsWith('properties.')) {- return [];- }- return [item];- }- // events table has no top-level utm_* columns — those live in the- // properties map under the __query.utm_* keys. Route them through- // getEventFiltersWhereClause's properties.* path so we emit- // `properties['__query.utm_source']` instead of the bare column.- if (UTM_COLUMNS.includes(item.name)) {- return [{ ...item, name: `properties.__query.${item.name}` }];- }- return [item];- }),- undefined,- undefined,- type,- );-- return Object.values(where).join(' AND ');- }-- async getTopPages({- projectId,- filters,- startDate,- endDate,- timezone,- limit,- }: IGetTopPagesInput) {- const selectColumns: (string | null | undefined | false)[] = [- 'origin',- 'path',- 'uniq(session_id) as sessions',- 'count() as pageviews',- ];-- if (INCLUDE_REVENUE) {- selectColumns.push('sum(revenue) as revenue');- }-- const query = clix(this.client, timezone)- .select<{- origin: string;- path: string;- sessions: number;- pageviews: number;- revenue?: number;- }>(selectColumns)- .from(TABLE_NAMES.events, false)- .where('project_id', '=', projectId)- .where('name', '=', 'screen_view')- .where('path', '!=', '')- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(this.getRawWhereClause('events', filters))- .groupBy(['origin', 'path'])- .orderBy('sessions', 'DESC')- .limit(Math.min(limit ?? MAX_RECORDS_LIMIT, MAX_RECORDS_LIMIT));-- return query.execute();- }-- async getTopEntryExit({- projectId,- filters,- startDate,- endDate,- mode,- timezone,- limit,- }: IGetTopEntryExitInput) {- const selectColumns: (string | null | undefined | false)[] = [- `${mode}_origin AS origin`,- `${mode}_path AS path`,- 'sum(sign) as sessions',- 'sum(sign * screen_view_count) as pageviews',- ];-- if (INCLUDE_REVENUE) {- selectColumns.push('sum(revenue * sign) as revenue');- }-- const query = clix(this.client, timezone)- .select<{- origin: string;- path: string;- sessions: number;- pageviews: number;- revenue?: number;- }>(selectColumns)- .from(TABLE_NAMES.sessions, true)- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .groupBy([`${mode}_origin`, `${mode}_path`])- .having('sum(sign)', '>', 0)- .orderBy('sessions', 'DESC')- .limit(Math.min(limit ?? MAX_RECORDS_LIMIT, MAX_RECORDS_LIMIT));-- const mainQuery = this.withDistinctSessionsIfNeeded(query, {- projectId,- filters,- startDate,- endDate,- timezone,- });-- return mainQuery.execute();- }-- private getDistinctSessions({- projectId,- filters,- startDate,- endDate,- timezone,- }: {- projectId: string;- filters: IChartEventFilter[];- startDate: string;- endDate: string;- timezone: string;- }) {- return clix(this.client, timezone)- .select(['DISTINCT session_id'])- .from(TABLE_NAMES.events)- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(this.getRawWhereClause('events', filters));- }-- async getTopGeneric({- projectId,- filters,- startDate,- endDate,- column,- timezone,- }: IGetTopGenericInput) {- if (!WHITELISTED_FILTERS.includes(column)) {- return [];- }-- const prefixColumn = COLUMN_PREFIX_MAP[column] ?? null;-- const selectColumns: (string | null | undefined | false)[] = [- prefixColumn && `${prefixColumn} as prefix`,- `nullIf(${column}, '') as name`,- 'sum(sign) as sessions',- 'sum(sign * screen_view_count) as pageviews',- ];-- if (INCLUDE_REVENUE) {- selectColumns.push('sum(revenue * sign) as revenue');- }-- const query = clix(this.client, timezone)- .select<{- prefix?: string;- name: string;- sessions: number;- pageviews: number;- revenue?: number;- }>(selectColumns)- .from(TABLE_NAMES.sessions, true)- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .groupBy([prefixColumn, column].filter(Boolean))- .having('sum(sign)', '>', 0)- .orderBy('sessions', 'DESC')- .limit(MAX_RECORDS_LIMIT);-- const mainQuery = this.withDistinctSessionsIfNeeded(query, {- projectId,- filters,- startDate,- endDate,- timezone,- });-- return mainQuery.execute();- }-- async getTopGenericSeries({- projectId,- filters,- startDate,- endDate,- column,- interval,- timezone,- }: IGetTopGenericSeriesInput): Promise<{- items: Array<{- name: string;- prefix?: string;- data: Array<{- date: string;- sessions: number;- pageviews: number;- revenue?: number;- }>;- total: { sessions: number; pageviews: number; revenue?: number };- }>;- }> {- const prefixColumn = COLUMN_PREFIX_MAP[column] ?? null;- const TOP_LIMIT = 500;- const fillConfig = this.getFillConfig(interval, startDate, endDate);-- // Step 1: Get top 15 items- const selectColumns: (string | null | undefined | false)[] = [- prefixColumn && `${prefixColumn} as prefix`,- `nullIf(${column}, '') as name`,- 'sum(sign) as sessions',- 'sum(sign * screen_view_count) as pageviews',- ];-- if (INCLUDE_REVENUE) {- selectColumns.push('sum(revenue * sign) as revenue');- }-- const topItemsQuery = clix(this.client, timezone)- .select<{- prefix?: string;- name: string;- sessions: number;- pageviews: number;- revenue?: number;- }>(selectColumns)- .from(TABLE_NAMES.sessions, true)- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .groupBy([prefixColumn, column].filter(Boolean))- .having('sum(sign)', '>', 0)- .orderBy('sessions', 'DESC')- .limit(TOP_LIMIT);-- const mainTopItemsQuery = this.withDistinctSessionsIfNeeded(topItemsQuery, {- projectId,- filters,- startDate,- endDate,- timezone,- });-- const topItems = await mainTopItemsQuery.execute();-- if (topItems.length === 0) {- return { items: [] };- }-- // Step 2: Build time-series query for each top item- const where = this.getRawWhereClause('sessions', filters);- const timeSeriesSelectColumns: (string | null | undefined | false)[] = [- `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,- prefixColumn && `${prefixColumn} as prefix`,- `nullIf(${column}, '') as name`,- 'sum(sign) as sessions',- 'sum(sign * screen_view_count) as pageviews',- ];-- if (INCLUDE_REVENUE) {- timeSeriesSelectColumns.push('sum(revenue * sign) as revenue');- }-- const timeSeriesQuery = clix(this.client, timezone)- .select<{- date: string;- prefix?: string;- name: string;- sessions: number;- pageviews: number;- revenue?: number;- }>(timeSeriesSelectColumns)- .from(TABLE_NAMES.sessions, true)- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(where)- .groupBy(['date', prefixColumn, column].filter(Boolean))- .having('sum(sign)', '>', 0)- .orderBy('date', 'ASC')- .fill(fillConfig.from, fillConfig.to, fillConfig.step)- .transform({- date: (item) => new Date(item.date).toISOString(),- });-- const mainTimeSeriesQuery = this.withDistinctSessionsIfNeeded(- timeSeriesQuery,- {- projectId,- filters,- startDate,- endDate,- timezone,- }- );-- const timeSeriesData = await mainTimeSeriesQuery.execute();-- // Step 3: Group time-series data by item and calculate totals- const itemsMap = new Map<- string,- {- name: string;- prefix?: string;- data: Array<{- date: string;- sessions: number;- pageviews: number;- revenue?: number;- }>;- total: { sessions: number; pageviews: number; revenue?: number };- }- >();-- // Initialize items from topItems- for (const item of topItems) {- const key = `${item.prefix || ''}:${item.name}`;- itemsMap.set(key, {- name: item.name,- prefix: item.prefix,- data: [],- total: {- sessions: item.sessions,- pageviews: item.pageviews,- revenue: item.revenue ?? 0,- },- });- }-- // Populate time-series data- for (const row of timeSeriesData) {- const key = `${row.prefix || ''}:${row.name}`;- const item = itemsMap.get(key);- if (item) {- item.data.push({- date: row.date,- sessions: row.sessions,- pageviews: row.pageviews,- revenue: row.revenue,- });- }- }-- return {- items: Array.from(itemsMap.values()),- };- }-- async getUserJourney({- projectId,- filters,- startDate,- endDate,- steps = 5,- timezone,- }: IGetUserJourneyInput): Promise<{- nodes: Array<{- id: string;- label: string;- nodeColor: string;- percentage?: number;- value?: number;- step?: number;- }>;- links: Array<{ source: string; target: string; value: number }>;- }> {- // Config- const TOP_ENTRIES = 3; // Only show top 3 entry pages- const TOP_DESTINATIONS_PER_NODE = 3; // Top 3 destinations from each node-- // Color palette - each entry page gets a consistent color- const COLORS = chartColors.map((color) => color.main);-- // Step 1: Get session paths (deduped consecutive pages)- const orderedEventsQuery = clix(this.client, timezone)- .select<{- session_id: string;- path: string;- created_at: string;- }>(['session_id', 'concat(origin, path) as path', 'created_at'])- .from(TABLE_NAMES.events)- .where('project_id', '=', projectId)- .where('name', '=', 'screen_view')- .where('path', '!=', '')- .where('path', 'IS NOT NULL')- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(this.getRawWhereClause('events', filters))- .orderBy('session_id', 'ASC')- .orderBy('created_at', 'ASC');-- // Intermediate CTE to compute deduped paths- const pathsDedupedCTE = clix(this.client, timezone)- .with('ordered_events', orderedEventsQuery)- .select<{- session_id: string;- paths_deduped: string[];- }>([- 'session_id',- `arraySlice(- arrayFilter(- (x, i) -> i = 1 OR x != paths_raw[i - 1],- groupArray(path) as paths_raw,- arrayEnumerate(paths_raw)- ),- 1, ${steps}- ) as paths_deduped`,- ])- .from('ordered_events')- .groupBy(['session_id']);-- const sessionPathsQuery = clix(this.client, timezone)- .with('paths_deduped_cte', pathsDedupedCTE)- .select<{- session_id: string;- entry_page: string;- paths: string[];- }>([- 'session_id',- // Truncate at first repeat- `if(- arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) = 0,- paths_deduped,- arraySlice(- paths_deduped,- 1,- arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) - 1- )- ) as paths`,- // Entry page is first element- 'paths[1] as entry_page',- ])- .from('paths_deduped_cte')- .having('length(paths)', '>=', 2);-- // Step 2: Find top 3 entry pages- const topEntriesQuery = clix(this.client, timezone)- .with('session_paths', sessionPathsQuery)- .select<{ entry_page: string; count: number }>([- 'entry_page',- 'count() as count',- ])- .from('session_paths')- .groupBy(['entry_page'])- .orderBy('count', 'DESC')- .limit(TOP_ENTRIES);-- const topEntries = await topEntriesQuery.execute();-- if (topEntries.length === 0) {- return { nodes: [], links: [] };- }-- const topEntryPages = topEntries.map((e) => e.entry_page);- const totalSessions = topEntries.reduce((sum, e) => sum + e.count, 0);-- // Step 3: Get all transitions, but ONLY for sessions starting with top entries- const transitionsQuery = clix(this.client, timezone)- .with('paths_deduped_cte', pathsDedupedCTE)- .with(- 'session_paths',- clix(this.client, timezone)- .select([- 'session_id',- // Truncate at first repeat- `if(- arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) = 0,- paths_deduped,- arraySlice(- paths_deduped,- 1,- arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) - 1- )- ) as paths`,- ])- .from('paths_deduped_cte')- .having('length(paths)', '>=', 2)- // ONLY sessions starting with top entry pages- .having('paths[1]', 'IN', topEntryPages)- )- .select<{- source: string;- target: string;- step: number;- value: number;- }>([- 'pair.1 as source',- 'pair.2 as target',- 'pair.3 as step',- 'count() as value',- ])- .from(- clix.exp(- '(SELECT arrayJoin(arrayMap(i -> (paths[i], paths[i + 1], i), range(1, length(paths)))) as pair FROM session_paths WHERE length(paths) >= 2)'- )- )- .groupBy(['source', 'target', 'step'])- .orderBy('step', 'ASC')- .orderBy('value', 'DESC');-- const transitions = await transitionsQuery.execute();-- if (transitions.length === 0) {- return { nodes: [], links: [] };- }-- // Step 4: Build the sankey progressively step by step- // Start with entry nodes, then follow top destinations at each step- // Use unique node IDs by combining path with step to prevent circular references- const nodes = new Map<- string,- { path: string; value: number; step: number; color: string }- >();- const links: Array<{ source: string; target: string; value: number }> = [];-- // Helper to create unique node ID- const getNodeId = (path: string, step: number) => `${path}::step${step}`;-- // Group transitions by step- const transitionsByStep = new Map<number, typeof transitions>();- for (const t of transitions) {- if (!transitionsByStep.has(t.step)) {- transitionsByStep.set(t.step, []);- }- transitionsByStep.get(t.step)!.push(t);- }-- // Initialize with entry pages (step 1)- const activeNodes = new Map<string, string>(); // path -> nodeId- topEntries.forEach((entry, idx) => {- const nodeId = getNodeId(entry.entry_page, 1);- nodes.set(nodeId, {- path: entry.entry_page,- value: entry.count,- step: 1,- color: COLORS[idx % COLORS.length]!,- });- activeNodes.set(entry.entry_page, nodeId);- });-- // Process each step: from active nodes, find top destinations- for (let step = 1; step < steps; step++) {- const stepTransitions = transitionsByStep.get(step) || [];- const nextActiveNodes = new Map<string, string>();-- // For each currently active node, find its top destinations- for (const [sourcePath, sourceNodeId] of activeNodes) {- // Get transitions FROM this source path- const fromSource = stepTransitions- .filter((t) => t.source === sourcePath)- .sort((a, b) => b.value - a.value)- .slice(0, TOP_DESTINATIONS_PER_NODE);-- for (const t of fromSource) {- // Skip self-loops- if (t.source === t.target) {- continue;- }-- const targetNodeId = getNodeId(t.target, step + 1);-- // Add link using unique node IDs- links.push({- source: sourceNodeId,- target: targetNodeId,- value: t.value,- });-- // Add/update target node- const existing = nodes.get(targetNodeId);- if (existing) {- existing.value += t.value;- } else {- // Inherit color from source or assign new- const sourceData = nodes.get(sourceNodeId);- nodes.set(targetNodeId, {- path: t.target,- value: t.value,- step: step + 1,- color: sourceData?.color || COLORS[nodes.size % COLORS.length]!,- });- }-- nextActiveNodes.set(t.target, targetNodeId);- }- }-- // Update active nodes for next iteration- activeNodes.clear();- for (const [path, nodeId] of nextActiveNodes) {- activeNodes.set(path, nodeId);- }-- // Stop if no more nodes to process- if (activeNodes.size === 0) {- break;- }- }-- // Step 5: Filter links by threshold (0.25% of total sessions)- const MIN_LINK_PERCENT = 0.25;- const minLinkValue = Math.ceil((totalSessions * MIN_LINK_PERCENT) / 100);- const filteredLinks = links.filter((link) => link.value >= minLinkValue);-- // Step 6: Find all nodes referenced by remaining links- const referencedNodeIds = new Set<string>();- filteredLinks.forEach((link) => {- referencedNodeIds.add(link.source);- referencedNodeIds.add(link.target);- });-- // Step 7: Recompute node values from filtered links (sum of incoming links)- const nodeValuesFromLinks = new Map<string, number>();- filteredLinks.forEach((link) => {- // Add to target node value- const current = nodeValuesFromLinks.get(link.target) || 0;- nodeValuesFromLinks.set(link.target, current + link.value);- });-- // For entry nodes (step 1), only keep them if they have outgoing links after filtering- nodes.forEach((nodeData, nodeId) => {- if (nodeData.step === 1) {- const hasOutgoing = filteredLinks.some((l) => l.source === nodeId);- if (!hasOutgoing) {- // No outgoing links, remove entry node- referencedNodeIds.delete(nodeId);- }- }- });-- // Step 8: Build final nodes array sorted by step then value- // Only include nodes that are referenced by filtered links- const finalNodes = Array.from(nodes.entries())- .filter(([id]) => referencedNodeIds.has(id))- .map(([id, data]) => {- // Use value from links for non-entry nodes, or original value for entry nodes with outgoing links- const value =- data.step === 1- ? data.value- : nodeValuesFromLinks.get(id) || data.value;- return {- id,- label: data.path, // Add label for display- nodeColor: data.color,- percentage: (value / totalSessions) * 100,- value,- step: data.step,- };- })- .sort((a, b) => {- // Sort by step first, then by value descending- if (a.step !== b.step) {- return a.step - b.step;- }- return b.value - a.value;- });-- // Sanity check: Ensure all link endpoints exist in nodes- const nodeIds = new Set(finalNodes.map((n) => n.id));- const invalidLinks = filteredLinks.filter(- (link) => !(nodeIds.has(link.source) && nodeIds.has(link.target))- );- if (invalidLinks.length > 0) {- console.warn(- `UserJourney: Found ${invalidLinks.length} links with missing nodes`- );- // Remove invalid links- const validLinks = filteredLinks.filter(- (link) => nodeIds.has(link.source) && nodeIds.has(link.target)- );- return {- nodes: finalNodes,- links: validLinks,- };- }-- // Sanity check: Ensure steps are monotonic (should always be true, but verify)- const stepsValid = finalNodes.every((node, idx, arr) => {- if (idx === 0) {- return true;- }- return node.step! >= arr[idx - 1]!.step!;- });- if (!stepsValid) {- console.warn('UserJourney: Steps are not monotonic');- }-- return {- nodes: finalNodes,- links: filteredLinks,- };- }-- async getTopEvents({- projectId,- filters,- startDate,- endDate,- timezone,- excludeEvents = ['session_start', 'session_end', 'screen_view'],- }: {- projectId: string;- filters: IChartEventFilter[];- startDate: string;- endDate: string;- timezone: string;- excludeEvents?: string[];- }): Promise<Array<{ name: string; count: number }>> {- const where = this.getRawWhereClause('events', filters);- const excludeWhere =- excludeEvents.length > 0- ? `name NOT IN (${excludeEvents.map((e) => sqlstring.escape(e)).join(',')})`- : '';-- const query = clix(this.client, timezone)- .select<{ name: string; count: number }>(['name', 'count() as count'])- .from(TABLE_NAMES.events, false)- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(where)- .rawWhere(excludeWhere)- .groupBy(['name'])- .orderBy('count', 'DESC')- .limit(MAX_RECORDS_LIMIT);-- return query.execute();- }-- async getTopLinkOut({- projectId,- filters,- startDate,- endDate,- timezone,- }: {- projectId: string;- filters: IChartEventFilter[];- startDate: string;- endDate: string;- timezone: string;- }): Promise<Array<{ href: string; count: number }>> {- const where = this.getRawWhereClause('events', filters);- const hrefKey = getSelectPropertyKey('properties.href');-- const query = clix(this.client, timezone)- .select<{ href: string; count: number }>([- `${hrefKey} as href`,- 'count() as count',- ])- .from(TABLE_NAMES.events, false)- .where('project_id', '=', projectId)- .where('name', '=', 'link_out')- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(where)- .rawWhere(`${hrefKey} IS NOT NULL AND ${hrefKey} != ''`)- .groupBy(['href'])- .orderBy('count', 'DESC')- .limit(MAX_RECORDS_LIMIT);-- return query.execute();- }-- async getMapData({- projectId,- filters,- startDate,- endDate,- timezone,- }: {- projectId: string;- filters: IChartEventFilter[];- startDate: string;- endDate: string;- timezone: string;- }): Promise<- Array<{- country: string;- region?: string;- city?: string;- lat: number;- lng: number;- count: number;- }>- > {- const where = this.getRawWhereClause('events', filters);-- // Note: ClickHouse doesn't have built-in lat/lng for countries/regions- // This would typically require a lookup table or external service- // For now, we'll return the data structure but lat/lng would need to be- // resolved on the frontend or via a separate lookup- const query = clix(this.client, timezone)- .select<{- country: string;- region: string | null;- city: string | null;- count: number;- }>([- "nullIf(country, '') as country",- "nullIf(region, '') as region",- "nullIf(city, '') as city",- 'uniq(session_id) as count',- ])- .from(TABLE_NAMES.events, false)- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .rawWhere(where)- .rawWhere("country IS NOT NULL AND country != ''")- .groupBy(['country', 'region', 'city'])- .orderBy('count', 'DESC')- .limit(MAX_RECORDS_LIMIT);-- const results = await query.execute();-- // Return with placeholder lat/lng - these should be resolved via geocoding- // or a lookup table on the frontend/backend- return results.map((row) => ({- country: row.country,- region: row.region ?? undefined,- city: row.city ?? undefined,- lat: 0, // Placeholder - needs geocoding- lng: 0, // Placeholder - needs geocoding- count: row.count,- }));- }-}--export const overviewService = new OverviewService(ch);--import { getSettingsForProject } from './organization.service';--export type TrafficColumn =- | 'referrer'- | 'referrer_name'- | 'referrer_type'- | 'utm_source'- | 'utm_medium'- | 'utm_campaign'- | 'country'- | 'region'- | 'city'- | 'device'- | 'browser'- | 'os';--export async function getTrafficBreakdownCore(input: {- projectId: string;- startDate: string;- endDate: string;- column: TrafficColumn;- filters?: IChartEventFilter[];-}) {- const { timezone } = await getSettingsForProject(input.projectId);- return overviewService.getTopGeneric({- projectId: input.projectId,- filters: input.filters ?? [],- startDate: input.startDate,- endDate: input.endDate,- column: input.column,- timezone,- });-}--// Columns whose daily series we can derive from the sessions table. Page/entry-// insights (path/origin) live on the events table and aren't covered here — the-// caller degrades to no series for those.-const SEGMENT_SERIES_COLUMNS: ReadonlySet<string> = new Set<TrafficColumn>([- 'referrer',- 'referrer_name',- 'referrer_type',- 'utm_source',- 'utm_medium',- 'utm_campaign',- 'country',- 'region',- 'city',- 'device',- 'browser',- 'os',-]);--export interface SegmentDailyPoint {- date: string;- sessions: number;- pageviews: number;-}--// Daily breakdown for a single segment value (e.g. the "Twitter" referrer),-// so the explainer can see the *shape* of a change (one-off spike vs sustained-// growth) instead of only current-vs-baseline totals. Returns one point per day-// with zero-filled gaps; empty when the column isn't session-derived or the-// value never appears in the window.-export async function getSegmentDailySeriesCore(input: {- projectId: string;- column: string;- value: string;- startDate: string;- endDate: string;-}): Promise<SegmentDailyPoint[]> {- if (!SEGMENT_SERIES_COLUMNS.has(input.column)) {- return [];- }-- const { timezone } = await getSettingsForProject(input.projectId);- const { items } = await overviewService.getTopGenericSeries({- projectId: input.projectId,- filters: [],- startDate: input.startDate,- endDate: input.endDate,- column: input.column as TrafficColumn,- interval: 'day',- timezone,- });-- // getTopGenericSeries reports empty values as null name; insights store the- // empty referrer as "direct". Match the segment leniently.- const target = input.value.toLowerCase();- const matched = items.find((item) => {- const name = (item.name ?? '').toLowerCase();- return name === target || (name === '' && target === 'direct');- });-- return (matched?.data ?? []).map((point) => ({- date: point.date,- sessions: Number(point.sessions ?? 0),- pageviews: Number(point.pageviews ?? 0),- }));-}--export interface GetAnalyticsOverviewInput {- projectId: string;- startDate: string;- endDate: string;- interval?: 'hour' | 'day' | 'week' | 'month';- filters?: IChartEventFilter[];-}--export async function getAnalyticsOverviewCore(- input: GetAnalyticsOverviewInput,-) {- const { timezone } = await getSettingsForProject(input.projectId);- const interval = input.interval ?? 'day';-- const result = await overviewService.getMetrics({- projectId: input.projectId,- filters: input.filters ?? [],- startDate: input.startDate,- endDate: input.endDate,- interval,- timezone,- });-- return {- summary: result.metrics,- series: result.series,- interval,- startDate: input.startDate,- endDate: input.endDate,- };-}+// Overview — OverviewService, its query builders and the mcp/assistant+// "*Core" helpers — lives in @openpanel/core now (M7-005). Re-exported here+// for existing `@openpanel/db` importers (packages/trpc's overview/event+// routers, apps/api's insights controller, packages/db's pages.service.ts,+// the mcp analytics tools) — same shape as+// packages/db/src/services/chart.service.ts since M7-003.+export type {+ IGetMapDataInput,+ IGetMetricsInput,+ IGetTopEntryExitInput,+ IGetTopEventsInput,+ IGetTopGenericInput,+ IGetTopGenericSeriesInput,+ IGetTopLinkOutInput,+ IGetTopPagesInput,+ IGetUserJourneyInput,+ ILiveData,+ ILiveMinuteCount,+ SegmentDailyPoint,+ TrafficColumn,+} from '@openpanel/core';+export {+ getAnalyticsOverviewCore,+ getSegmentDailySeriesCore,+ getTrafficBreakdownCore,+ OverviewService,+ overviewService,+ zGetMapDataInput,+ zGetMetricsInput,+ zGetTopEntryExitInput,+ zGetTopEventsInput,+ zGetTopGenericInput,+ zGetTopGenericSeriesInput,+ zGetTopLinkOutInput,+ zGetTopPagesInput,+ zGetUserJourneyInput,+} from '@openpanel/core';diff --git a/packages/db/src/services/pages.service.ts b/packages/db/src/services/pages.service.tsindex 40cda4760..8aa89ed48 100644--- a/packages/db/src/services/pages.service.ts+++ b/packages/db/src/services/pages.service.ts@@ -1,321 +1,20 @@-import type { IChartEventFilter, IInterval } from '@openpanel/validation';-import sqlstring from 'sqlstring';-import { ch, TABLE_NAMES, chQuery } from '../clickhouse/client';-import { clix } from '../clickhouse/query-builder';--export interface IGetPagesInput {- projectId: string;- startDate: string;- endDate: string;- timezone: string;- search?: string;- limit?: number;-}--export interface IPageTimeseriesRow {- origin: string;- path: string;- date: string;- pageviews: number;- sessions: number;-}--export interface ITopPage {- origin: string;- path: string;- title: string;- sessions: number;- pageviews: number;- avg_duration: number;- bounce_rate: number;-}--export class PagesService {- constructor(private client: typeof ch) {}-- async getTopPages({- projectId,- startDate,- endDate,- timezone,- search,- limit,- }: IGetPagesInput): Promise<ITopPage[]> {- // CTE: Get titles from the last 30 days for faster retrieval- const titlesCte = clix(this.client, timezone)- .select([- 'concat(origin, path) as page_key',- "anyLast(properties['__title']) as title",- ])- .from(TABLE_NAMES.events, false)- .where('project_id', '=', projectId)- .where('name', '=', 'screen_view')- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 DAY'))- .groupBy(['origin', 'path']);-- // CTE: compute screen_view durations via window function (leadInFrame gives next event's timestamp)- const screenViewDurationsCte = clix(this.client, timezone)- .select([- 'project_id',- 'session_id',- 'path',- 'origin',- `dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at)) AS duration`,- ])- .from(TABLE_NAMES.events, false)- .where('project_id', '=', projectId)- .where('name', '=', 'screen_view')- .where('path', '!=', '')- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ]);-- // Pre-filtered sessions subquery for better performance- const sessionsSubquery = clix(this.client, timezone)- .select(['id', 'project_id', 'is_bounce'])- .from(TABLE_NAMES.sessions, true) // FINAL- .where('project_id', '=', projectId)- .where('created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .where('sign', '=', 1);-- // Main query: aggregate events and calculate bounce rate from pre-filtered sessions- const query = clix(this.client, timezone)- .with('page_titles', titlesCte)- .with('screen_view_durations', screenViewDurationsCte)- .select<ITopPage>([- 'e.origin as origin',- 'e.path as path',- "coalesce(pt.title, '') as title",- 'uniq(e.session_id) as sessions',- 'count() as pageviews',- 'round(avg(e.duration) / 1000 / 60, 2) as avg_duration',- `round(- (uniqIf(e.session_id, s.is_bounce = 1) * 100.0) /- nullIf(uniq(e.session_id), 0),- 2- ) as bounce_rate`,- ])- .from('screen_view_durations e', false)- .leftJoin(- sessionsSubquery,- 'e.session_id = s.id AND e.project_id = s.project_id',- 's'- )- .leftJoin('page_titles pt', 'concat(e.origin, e.path) = pt.page_key')- .when(!!search, (q) => {- const term = `%${search}%`;- q.whereGroup()- .where('e.path', 'LIKE', term)- .orWhere('e.origin', 'LIKE', term)- .orWhere('pt.title', 'LIKE', term)- .end();- })- .groupBy(['e.origin', 'e.path', 'pt.title'])- .orderBy('sessions', 'DESC');- if (limit !== undefined) {- query.limit(limit);- }- return query.execute();- }-- async getPageTimeseries({- projectId,- startDate,- endDate,- timezone,- interval,- filterOrigin,- filterPath,- }: IGetPagesInput & {- interval: IInterval;- filterOrigin?: string;- filterPath?: string;- }): Promise<IPageTimeseriesRow[]> {- const dateExpr = clix.toStartOf('e.created_at', interval, timezone);- const useDateOnly = interval === 'month' || interval === 'week';- const fillFrom = clix.toStartOf(- clix.datetime(startDate, useDateOnly ? 'toDate' : 'toDateTime'),- interval- );- const fillTo = clix.datetime(- endDate,- useDateOnly ? 'toDate' : 'toDateTime'- );- const fillStep = clix.toInterval('1', interval);-- return clix(this.client, timezone)- .select<IPageTimeseriesRow>([- 'e.origin as origin',- 'e.path as path',- `${dateExpr} AS date`,- 'count() as pageviews',- 'uniq(e.session_id) as sessions',- ])- .from(`${TABLE_NAMES.events} e`, false)- .where('e.project_id', '=', projectId)- .where('e.name', '=', 'screen_view')- .where('e.path', '!=', '')- .where('e.created_at', 'BETWEEN', [- clix.datetime(startDate, 'toDateTime'),- clix.datetime(endDate, 'toDateTime'),- ])- .when(!!filterOrigin, (q) => q.where('e.origin', '=', filterOrigin!))- .when(!!filterPath, (q) => q.where('e.path', '=', filterPath!))- .groupBy(['e.origin', 'e.path', 'date'])- .orderBy('date', 'ASC')- .fill(fillFrom, fillTo, fillStep)- .execute();- }-}--export const pagesService = new PagesService(ch);--import { OverviewService } from './overview.service';-import { getSettingsForProject } from './organization.service';--const _overviewServiceForPages = new OverviewService(ch);--export async function getTopPagesCore(input: {- projectId: string;- startDate: string;- endDate: string;- limit?: number;- filters?: IChartEventFilter[];-}) {- const { timezone } = await getSettingsForProject(input.projectId);- return _overviewServiceForPages.getTopPages({- projectId: input.projectId,- filters: input.filters ?? [],- startDate: input.startDate,- endDate: input.endDate,- timezone,- limit: input.limit,- });-}--export async function getEntryExitPagesCore(input: {- projectId: string;- startDate: string;- endDate: string;- mode: 'entry' | 'exit';- limit?: number;- filters?: IChartEventFilter[];-}) {- const { timezone } = await getSettingsForProject(input.projectId);- return _overviewServiceForPages.getTopEntryExit({- projectId: input.projectId,- filters: input.filters ?? [],- startDate: input.startDate,- endDate: input.endDate,- mode: input.mode,- timezone,- limit: input.limit,- });-}--export async function getPagePerformanceCore(input: {- projectId: string;- startDate: string;- endDate: string;- search?: string;- sortBy?: 'sessions' | 'pageviews' | 'bounce_rate' | 'avg_duration';- sortOrder?: 'asc' | 'desc';- limit?: number;-}) {- const { timezone } = await getSettingsForProject(input.projectId);- const pages = await pagesService.getTopPages({- projectId: input.projectId,- startDate: input.startDate,- endDate: input.endDate,- timezone,- search: input.search,- limit: 1000,- });-- const col = input.sortBy ?? 'sessions';- const dir = input.sortOrder === 'asc' ? 1 : -1;- const sorted = [...pages].sort(- (a, b) => dir * ((a[col] ?? 0) < (b[col] ?? 0) ? -1 : 1),- );- const results = sorted.slice(0, input.limit ?? 50);-- const annotated = results.map((p) => ({- ...p,- seo_signals: {- high_bounce: p.bounce_rate > 70,- low_engagement: p.avg_duration < 1,- good_landing_page: p.bounce_rate < 40 && p.avg_duration > 2,- },- }));-- return {- total_pages: pages.length,- shown: annotated.length,- pages: annotated,- };-}--export interface IPageConversionRow {- path: string;- origin: string;- unique_converters: number;- total_visitors: number;- conversion_rate: number;-}--export async function getPageConversionsCore(input: {- projectId: string;- startDate: string;- endDate: string;- conversionEvent: string;- windowHours?: number;- limit?: number;-}): Promise<IPageConversionRow[]> {- const { projectId, startDate, endDate, conversionEvent, windowHours = 24, limit = 100 } = input;- const sql = `- WITH- conversion_events AS (- SELECT profile_id, created_at AS conv_time- FROM events- WHERE project_id = ${sqlstring.escape(projectId)}- AND name = ${sqlstring.escape(conversionEvent)}- AND created_at BETWEEN toDateTime(${sqlstring.escape(startDate)}) AND toDateTime(${sqlstring.escape(endDate)})- ),- views_before_conversions AS (- SELECT DISTINCT e.profile_id, e.path, e.origin- FROM events AS e- INNER JOIN conversion_events AS c ON e.profile_id = c.profile_id- WHERE e.project_id = ${sqlstring.escape(projectId)}- AND e.name = 'screen_view'- AND e.path != ''- AND e.created_at BETWEEN toDateTime(${sqlstring.escape(startDate)}) AND toDateTime(${sqlstring.escape(endDate)})- AND e.created_at < c.conv_time- AND e.created_at >= c.conv_time - INTERVAL ${Number(windowHours)} HOUR- ),- total_visitors AS (- SELECT path, origin, uniq(session_id) AS visitors- FROM events- WHERE project_id = ${sqlstring.escape(projectId)}- AND name = 'screen_view'- AND path != ''- AND created_at BETWEEN toDateTime(${sqlstring.escape(startDate)}) AND toDateTime(${sqlstring.escape(endDate)})- GROUP BY path, origin- )- SELECT- vbc.path,- vbc.origin,- count() AS unique_converters,- any(tv.visitors) AS total_visitors,- round(100.0 * count() / any(tv.visitors), 2) AS conversion_rate- FROM views_before_conversions AS vbc- LEFT JOIN total_visitors AS tv ON vbc.path = tv.path AND vbc.origin = tv.origin- GROUP BY vbc.path, vbc.origin- ORDER BY unique_converters DESC- LIMIT ${Number(limit)}- `;- return chQuery<IPageConversionRow>(sql);-}+// Pages — PagesService and the mcp/insights "*Core" helpers — lives in+// @openpanel/core's overview module now (M7-005, the module map's owner of+// "pages"). Re-exported here for existing `@openpanel/db` importers+// (packages/trpc's event router, apps/api's insights controller, the mcp+// analytics tools) — same shape as+// packages/db/src/services/overview.service.ts since M7-003.+export type {+ IGetPagesInput,+ IPageConversionRow,+ IPageTimeseriesRow,+ ITopPage,+} from '@openpanel/core';+export {+ getEntryExitPagesCore,+ getPageConversionsCore,+ getPagePerformanceCore,+ getTopPagesCore,+ PagesService,+ pagesService,+} from '@openpanel/core';diff --git a/packages/trpc/src/routers/overview.ts b/packages/trpc/src/routers/overview.tsindex 024c83e4e..1f391c69a 100644--- a/packages/trpc/src/routers/overview.ts+++ b/packages/trpc/src/routers/overview.ts@@ -1,17 +1,20 @@-// Dissolved into @openpanel/core's insight module (M5-001) and, for-// `runFilterCommand`, its assistant module (M5-005).-import { getReferrerSpikes, runFilterCommand } from '@openpanel/core';+// Dissolved into @openpanel/core's overview module (M7-005): the ClickHouse+// queries moved to packages/core/src/modules/overview/src/{overview,pages}.sql.ts+// and the handler bodies to overview.service.ts/pages.service.ts. This router+// stays (DELEGATE PATTERN) — it keeps V1's `publicProcedure` /+// `overviewProcedure` (share-or-session) / `cacheMiddleware` stacks and+// delegates every handler body to core's overview functions, same as chart.ts.+//+// `liveData`'s queries used to live inline here; they moved to+// `overviewService.getLiveData` with everything else this module runs.+import {- ch,- clix,- eventBuffer,- getChartPrevStartEndDate,- getChartStartEndDate,getConversionEventNames,getOrganizationSubscriptionChartEndDate,+ getReferrerSpikes,getSettingsForProject,overviewService,- TABLE_NAMES,+ runFilterCommand,validateOverviewShareAccess,zGetMapDataInput,zGetMetricsInput,@@ -21,6 +24,11 @@ import {zGetTopLinkOutInput,zGetTopPagesInput,zGetUserJourneyInput,+} from '@openpanel/core';+import {+ eventBuffer,+ getChartPrevStartEndDate,+ getChartStartEndDate,} from '@openpanel/db';import {type IChartRange,@@ -158,115 +166,7 @@ export const overviewRouter = createTRPCRouter({.input(z.object({ projectId: z.string(), shareId: z.string().optional() })).use(cacher).query(async ({ input }) => {- const { timezone } = await getSettingsForProject(input.projectId);-- // Get total unique sessions in the last 30 minutes- const totalSessionsQuery = clix(ch, timezone)- .select<{ total_sessions: number }>([- 'uniq(session_id) as total_sessions',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'));-- // Get counts per minute for the last 30 minutes- const minuteCountsQuery = clix(ch, timezone)- .select<{- minute: string;- session_count: number;- visitor_count: number;- }>([- `${clix.toStartOf('created_at', 'minute')} as minute`,- 'uniq(session_id) as session_count',- 'uniq(profile_id) as visitor_count',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))- .groupBy(['minute'])- .orderBy('minute', 'ASC')- .fill(- clix.exp('toStartOfMinute(now() - INTERVAL 30 MINUTE)'),- clix.exp('toStartOfMinute(now())'),- clix.exp('INTERVAL 1 MINUTE')- );-- // Get referrers per minute for the last 30 minutes- const minuteReferrersQuery = clix(ch, timezone)- .select<{- minute: string;- referrer_name: string;- count: number;- }>([- `${clix.toStartOf('created_at', 'minute')} as minute`,- 'referrer_name',- 'uniq(session_id) as count',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))- .where('referrer_name', '!=', '')- .where('referrer_name', 'IS NOT NULL')- .groupBy(['minute', 'referrer_name'])- .orderBy('minute', 'ASC')- .orderBy('count', 'DESC');-- // Get unique referrers in the last 30 minutes- const referrersQuery = clix(ch, timezone)- .select<{ referrer: string; count: number }>([- 'referrer_name as referrer',- 'uniq(session_id) as count',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))- .where('referrer_name', '!=', '')- .where('referrer_name', 'IS NOT NULL')- .groupBy(['referrer_name'])- .orderBy('count', 'DESC')- .limit(10);-- const [totalSessions, minuteCounts, minuteReferrers, referrers] =- await Promise.all([- totalSessionsQuery.execute(),- minuteCountsQuery.execute(),- minuteReferrersQuery.execute(),- referrersQuery.execute(),- ]);-- // Group referrers by minute- const referrersByMinute = new Map<- string,- Array<{ referrer: string; count: number }>- >();- minuteReferrers.forEach((item) => {- if (!referrersByMinute.has(item.minute)) {- referrersByMinute.set(item.minute, []);- }- referrersByMinute.get(item.minute)!.push({- referrer: item.referrer_name,- count: item.count,- });- });-- return {- totalSessions: totalSessions[0]?.total_sessions || 0,- minuteCounts: minuteCounts.map((item) => ({- minute: item.minute,- sessionCount: item.session_count,- visitorCount: item.visitor_count,- timestamp: new Date(item.minute).getTime(),- time: new Date(item.minute).toLocaleTimeString([], {- hour: '2-digit',- minute: '2-digit',- }),- referrers: referrersByMinute.get(item.minute) || [],- })),- referrers: referrers.map((item) => ({- referrer: item.referrer,- count: item.count,- })),- };+ return overviewService.getLiveData(input.projectId);}),stats: overviewProcedure.input(