Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

Add click heatmaps report

Mike Caoa6b13b71db73
diff --git a/db/clickhouse/migrations/12_add_heatmap.sql b/db/clickhouse/migrations/12_add_heatmap.sql
new file mode 100644
index 000000000..de6439236
--- /dev/null
+++ b/db/clickhouse/migrations/12_add_heatmap.sql
@@ -0,0 +1,21 @@
+-- Create heatmap_event
+CREATE TABLE umami.heatmap_event
+(
+ heatmap_event_id UUID,
+ website_id UUID,
+ session_id UUID,
+ visit_id UUID,
+ url_path String,
+ event_type UInt8,
+ node_id Nullable(Int32),
+ x Nullable(Int32),
+ y Nullable(Int32),
+ viewport_w Nullable(Int32),
+ viewport_h Nullable(Int32),
+ scroll_pct Nullable(UInt8),
+ created_at DateTime('UTC')
+)
+ENGINE = MergeTree
+ PARTITION BY toYYYYMM(created_at)
+ ORDER BY (website_id, url_path, event_type, created_at)
+ SETTINGS index_granularity = 8192;
diff --git a/db/clickhouse/schema.sql b/db/clickhouse/schema.sql
index 0540c97b2..f587825b8 100644
--- a/db/clickhouse/schema.sql
+++ b/db/clickhouse/schema.sql
@@ -344,3 +344,25 @@ AS SELECT
groupArrayState(data_type) AS property_types
FROM umami.event_data
GROUP BY website_id, session_id, event_id, event_name, url_path, created_at;
+
+-- Create heatmap_event
+CREATE TABLE umami.heatmap_event
+(
+ heatmap_event_id UUID,
+ website_id UUID,
+ session_id UUID,
+ visit_id UUID,
+ url_path String,
+ event_type UInt8,
+ node_id Nullable(Int32),
+ x Nullable(Int32),
+ y Nullable(Int32),
+ viewport_w Nullable(Int32),
+ viewport_h Nullable(Int32),
+ scroll_pct Nullable(UInt8),
+ created_at DateTime('UTC')
+)
+ENGINE = MergeTree
+ PARTITION BY toYYYYMM(created_at)
+ ORDER BY (website_id, url_path, event_type, created_at)
+ SETTINGS index_granularity = 8192;
diff --git a/prisma/migrations/20_add_heatmap/migration.sql b/prisma/migrations/20_add_heatmap/migration.sql
new file mode 100644
index 000000000..10266df15
--- /dev/null
+++ b/prisma/migrations/20_add_heatmap/migration.sql
@@ -0,0 +1,24 @@
+-- CreateTable
+CREATE TABLE "heatmap_event" (
+ "heatmap_event_id" UUID NOT NULL,
+ "website_id" UUID NOT NULL,
+ "session_id" UUID NOT NULL,
+ "visit_id" UUID NOT NULL,
+ "url_path" VARCHAR(500) NOT NULL,
+ "event_type" INTEGER NOT NULL,
+ "node_id" INTEGER,
+ "x" INTEGER,
+ "y" INTEGER,
+ "viewport_w" INTEGER,
+ "viewport_h" INTEGER,
+ "scroll_pct" INTEGER,
+ "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "heatmap_event_pkey" PRIMARY KEY ("heatmap_event_id")
+);
+
+-- CreateIndex
+CREATE INDEX "heatmap_event_website_id_idx" ON "heatmap_event"("website_id");
+CREATE INDEX "heatmap_event_visit_id_idx" ON "heatmap_event"("visit_id");
+CREATE INDEX "heatmap_event_website_id_created_at_idx" ON "heatmap_event"("website_id", "created_at");
+CREATE INDEX "heatmap_event_website_id_url_path_event_type_created_at_idx" ON "heatmap_event"("website_id", "url_path", "event_type", "created_at");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 63c81ec0d..9cc0d946d 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -88,6 +88,7 @@ model Website {
sessionData SessionData[]
sessionReplays SessionReplay[]
sessionReplaysSaved SessionReplaySaved[]
+ heatmapEvents HeatmapEvent[]
@@index([userId])
@@index([teamId])
@@ -398,4 +399,28 @@ model SessionReplaySaved {
@@index([visitId])
@@index([websiteId, createdAt])
@@map("session_replay_saved")
+}
+
+model HeatmapEvent {
+ id String @id() @map("heatmap_event_id") @db.Uuid
+ websiteId String @map("website_id") @db.Uuid
+ sessionId String @map("session_id") @db.Uuid
+ visitId String @map("visit_id") @db.Uuid
+ urlPath String @map("url_path") @db.VarChar(500)
+ eventType Int @map("event_type") @db.Integer
+ nodeId Int? @map("node_id") @db.Integer
+ x Int? @db.Integer
+ y Int? @db.Integer
+ viewportW Int? @map("viewport_w") @db.Integer
+ viewportH Int? @map("viewport_h") @db.Integer
+ scrollPct Int? @map("scroll_pct") @db.Integer
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
+
+ website Website @relation(fields: [websiteId], references: [id])
+
+ @@index([websiteId])
+ @@index([visitId])
+ @@index([websiteId, createdAt])
+ @@index([websiteId, urlPath, eventType, createdAt])
+ @@map("heatmap_event")
}
\ No newline at end of file
diff --git a/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.module.css b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.module.css
new file mode 100644
index 000000000..edea449db
--- /dev/null
+++ b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.module.css
@@ -0,0 +1,80 @@
+.pageList {
+ overflow-y: auto;
+ padding-right: 8px;
+ max-height: 100%;
+}
+
+.pageButton {
+ width: 100%;
+ text-align: left;
+ border: 0;
+ background: transparent;
+ border-radius: 6px;
+ padding: 8px 10px;
+ cursor: pointer;
+ font: inherit;
+ color: inherit;
+}
+
+.pageButton:hover {
+ background: var(--interactive-bg-hover);
+}
+
+.pageButtonSelected,
+.pageButtonSelected:hover {
+ background: var(--surface-inverted);
+ color: var(--surface-base);
+}
+
+.toggleButton {
+ border: 1px solid var(--border-base);
+ background: var(--surface-base);
+ border-radius: 6px;
+ padding: 4px 10px;
+ cursor: pointer;
+ font: inherit;
+ color: inherit;
+}
+
+.toggleButton:hover {
+ background: var(--interactive-bg-hover);
+}
+
+.canvas {
+ position: relative;
+ overflow: hidden;
+ border: 1px solid var(--border-base);
+ border-radius: 8px;
+ background: var(--surface-sunken);
+}
+
+.iframe {
+ position: absolute;
+ top: 0;
+ left: 0;
+ border: 0;
+ transform-origin: top left;
+ pointer-events: none;
+}
+
+.overlay {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ pointer-events: none;
+}
+
+.dot {
+ position: absolute;
+ border-radius: 50%;
+ background: radial-gradient(
+ circle,
+ rgba(255, 60, 0, 0.9) 0%,
+ rgba(255, 200, 0, 0.6) 45%,
+ rgba(255, 200, 0, 0) 80%
+ );
+ pointer-events: auto;
+ mix-blend-mode: multiply;
+}
diff --git a/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.tsx b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.tsx
new file mode 100644
index 000000000..5e71c29cf
--- /dev/null
+++ b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.tsx
@@ -0,0 +1,194 @@
+'use client';
+import { Column, Grid, Heading, Row, Text } from '@umami/react-zen';
+import { useMemo, useState } from 'react';
+import { LoadingPanel } from '@/components/common/LoadingPanel';
+import { useResultQuery, useWebsite } from '@/components/hooks';
+import { formatLongNumber } from '@/lib/format';
+import type { HeatmapPoint, HeatmapResult } from '@/queries/sql';
+import styles from './Heatmap.module.css';
+
+const RENDER_WIDTH = 1024;
+
+interface ViewportBucket {
+ width: number;
+ height: number;
+ count: number;
+}
+
+interface HeatmapProps {
+ websiteId: string;
+ urlPath: string;
+ onUrlPathChange: (urlPath: string) => void;
+}
+
+export function Heatmap({ websiteId, urlPath, onUrlPathChange }: HeatmapProps) {
+ const website = useWebsite();
+ const { data, error, isLoading } = useResultQuery<HeatmapResult>('heatmap', {
+ websiteId,
+ urlPath: urlPath || undefined,
+ });
+
+ const pages = data?.pages ?? [];
+ const points = data?.points ?? [];
+
+ return (
+ <LoadingPanel data={data} isLoading={isLoading} error={error} height="100%">
+ <Grid columns="320px 1fr" gap height="100%">
+ <PageList pages={pages} selected={urlPath} onSelect={onUrlPathChange} />
+ <Column gap>
+ {urlPath ? (
+ <HeatmapView domain={website?.domain ?? null} urlPath={urlPath} points={points} />
+ ) : (
+ <EmptyState />
+ )}
+ </Column>
+ </Grid>
+ </LoadingPanel>
+ );
+}
+
+function PageList({
+ pages,
+ selected,
+ onSelect,
+}: {
+ pages: HeatmapResult['pages'];
+ selected: string;
+ onSelect: (urlPath: string) => void;
+}) {
+ return (
+ <Column className={styles.pageList} gap="2">
+ <Heading size="lg">Pages</Heading>
+ {pages.length === 0 && <Text color="muted">No data yet</Text>}
+ {pages.map(p => (
+ <button
+ key={p.urlPath}
+ type="button"
+ onClick={() => onSelect(p.urlPath)}
+ className={`${styles.pageButton} ${selected === p.urlPath ? styles.pageButtonSelected : ''}`}
+ >
+ <Row alignItems="center" justifyContent="space-between" gap="2">
+ <Text truncate>{p.urlPath}</Text>
+ <Text color="muted">{formatLongNumber(p.count)}</Text>
+ </Row>
+ </button>
+ ))}
+ </Column>
+ );
+}
+
+function pickViewport(points: HeatmapPoint[]): ViewportBucket | null {
+ if (!points.length) return null;
+ const buckets = new Map<string, ViewportBucket>();
+ for (const p of points) {
+ const key = `${p.viewportW}x${p.viewportH}`;
+ const existing = buckets.get(key);
+ if (existing) {
+ existing.count += p.count;
+ } else {
+ buckets.set(key, { width: p.viewportW, height: p.viewportH, count: p.count });
+ }
+ }
+ let best: ViewportBucket | null = null;
+ for (const b of buckets.values()) {
+ if (!best || b.count > best.count) best = b;
+ }
+ return best;
+}
+
+function HeatmapView({
+ domain,
+ urlPath,
+ points,
+}: {
+ domain: string | null;
+ urlPath: string;
+ points: HeatmapPoint[];
+}) {
+ const [showPage, setShowPage] = useState(true);
+
+ const viewport = useMemo(() => pickViewport(points), [points]);
+
+ const visible = useMemo(() => {
+ if (!viewport) return [];
+ return points.filter(p => p.viewportW === viewport.width && p.viewportH === viewport.height);
+ }, [points, viewport]);
+
+ const maxCount = useMemo(
+ () => visible.reduce((m, p) => (p.count > m ? p.count : m), 1),
+ [visible],
+ );
+
+ if (!viewport || visible.length === 0) {
+ return <EmptyState />;
+ }
+
+ const scale = RENDER_WIDTH / viewport.width;
+ const renderHeight = Math.round(viewport.height * scale);
+ const iframeSrc = domain ? `https://${domain}${urlPath}` : null;
+
+ return (
+ <Column gap>
+ <Row alignItems="center" justifyContent="space-between" gap>
+ <Text color="muted">
+ {visible.length} positions · {formatLongNumber(visible.reduce((s, p) => s + p.count, 0))}{' '}
+ clicks · viewport {viewport.width}×{viewport.height}
+ </Text>
+ {iframeSrc && (
+ <button
+ type="button"
+ className={styles.toggleButton}
+ onClick={() => setShowPage(v => !v)}
+ >
+ {showPage ? 'Hide page' : 'Show page'}
+ </button>
+ )}
+ </Row>
+ <div
+ className={styles.canvas}
+ style={{ width: RENDER_WIDTH, height: renderHeight }}
+ >
+ {showPage && iframeSrc && (
+ <iframe
+ className={styles.iframe}
+ src={iframeSrc}
+ width={viewport.width}
+ height={viewport.height}
+ style={{ transform: `scale(${scale})` }}
+ sandbox="allow-same-origin"
+ referrerPolicy="no-referrer"
+ />
+ )}
+ <div className={styles.overlay}>
+ {visible.map((p, i) => {
+ const intensity = Math.min(1, p.count / maxCount);
+ const size = 24 + intensity * 36;
+ return (
+ <div
+ key={`${p.x}-${p.y}-${i}`}
+ className={styles.dot}
+ style={{
+ left: p.x * scale - size / 2,
+ top: p.y * scale - size / 2,
+ width: size,
+ height: size,
+ opacity: 0.25 + intensity * 0.55,
+ }}
+ title={`${p.count} click${p.count === 1 ? '' : 's'}`}
+ />
+ );
+ })}
+ </div>
+ </div>
+ </Column>
+ );
+}
+
+function EmptyState() {
+ return (
+ <Column alignItems="center" justifyContent="center" height="100%" gap>
+ <Heading size="lg">Select a page</Heading>
+ <Text color="muted">Choose a page from the list to view its click heatmap.</Text>
+ </Column>
+ );
+}
diff --git a/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/HeatmapsPage.tsx b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/HeatmapsPage.tsx
new file mode 100644
index 000000000..369469483
--- /dev/null
+++ b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/HeatmapsPage.tsx
@@ -0,0 +1,19 @@
+'use client';
+import { Column } from '@umami/react-zen';
+import { useState } from 'react';
+import { WebsiteControls } from '@/app/(main)/websites/[websiteId]/WebsiteControls';
+import { Panel } from '@/components/common/Panel';
+import { Heatmap } from './Heatmap';
+
+export function HeatmapsPage({ websiteId }: { websiteId: string }) {
+ const [urlPath, setUrlPath] = useState<string>('');
+
+ return (
+ <Column gap>
+ <WebsiteControls websiteId={websiteId} />
+ <Panel height="900px" allowFullscreen>
+ <Heatmap websiteId={websiteId} urlPath={urlPath} onUrlPathChange={setUrlPath} />
+ </Panel>
+ </Column>
+ );
+}
diff --git a/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/page.tsx b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/page.tsx
new file mode 100644
index 000000000..d980279ce
--- /dev/null
+++ b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/page.tsx
@@ -0,0 +1,12 @@
+import type { Metadata } from 'next';
+import { HeatmapsPage } from './HeatmapsPage';
+
+export default async function ({ params }: { params: Promise<{ websiteId: string }> }) {
+ const { websiteId } = await params;
+
+ return <HeatmapsPage websiteId={websiteId} />;
+}
+
+export const metadata: Metadata = {
+ title: 'Heatmaps',
+};
diff --git a/src/app/api/record/route.ts b/src/app/api/record/route.ts
index 20ca53469..59d51d59f 100644
--- a/src/app/api/record/route.ts
+++ b/src/app/api/record/route.ts
@@ -9,6 +9,8 @@ import { parseRequest } from '@/lib/request';
import { badRequest, forbidden, json, serverError } from '@/lib/response';
import { getWebsite } from '@/queries/prisma';
import { saveRecording } from '@/queries/sql';
+import { extractHeatmapEvents } from '@/queries/sql/heatmap/extractHeatmapEvents';
+import { saveHeatmapEvents } from '@/queries/sql/heatmap/saveHeatmapEvents';
interface Cache {
sessionId: string;
@@ -113,6 +115,22 @@ export async function POST(request: Request) {
endedAt,
});
+ try {
+ const heatmapRows = extractHeatmapEvents(events).map(e => ({
+ websiteId,
+ sessionId,
+ visitId,
+ ...e,
+ }));
+
+ if (heatmapRows.length) {
+ await saveHeatmapEvents(heatmapRows);
+ }
+ } catch (e) {
+ // eslint-disable-next-line no-console
+ console.log('heatmap extraction failed', serializeError(e));
+ }
+
return json({ ok: true });
} catch (e) {
const error = serializeError(e);
diff --git a/src/app/api/reports/heatmap/route.ts b/src/app/api/reports/heatmap/route.ts
new file mode 100644
index 000000000..79af35c3e
--- /dev/null
+++ b/src/app/api/reports/heatmap/route.ts
@@ -0,0 +1,25 @@
+import { parseRequest, setWebsiteDate } from '@/lib/request';
+import { json, unauthorized } from '@/lib/response';
+import { reportResultSchema } from '@/lib/schema';
+import { canViewWebsite } from '@/permissions';
+import { getHeatmap, type HeatmapParameters } from '@/queries/sql';
+
+export async function POST(request: Request) {
+ const { auth, body, error } = await parseRequest(request, reportResultSchema);
+
+ if (error) {
+ return error();
+ }
+
+ const { websiteId } = body;
+
+ if (!(await canViewWebsite(auth, websiteId))) {
+ return unauthorized();
+ }
+
+ const parameters = (await setWebsiteDate(websiteId, body.parameters)) as HeatmapParameters;
+
+ const data = await getHeatmap(websiteId, parameters);
+
+ return json(data);
+}
diff --git a/src/components/hooks/useWebsiteNavItems.tsx b/src/components/hooks/useWebsiteNavItems.tsx
index 11c5b8caf..09731f101 100644
--- a/src/components/hooks/useWebsiteNavItems.tsx
+++ b/src/components/hooks/useWebsiteNavItems.tsx
@@ -3,6 +3,7 @@ import {
ChartPie,
Clock,
Eye,
+ Flame,
Sheet,
Tag,
User,
@@ -107,6 +108,12 @@ export function useWebsiteNavItems(websiteId: string) {
icon: <Video />,
path: renderPath('/replays'),
},
+ {
+ id: 'heatmaps',
+ label: t(labels.heatmaps),
+ icon: <Flame />,
+ path: renderPath('/heatmaps'),
+ },
],
},
{
diff --git a/src/components/messages.ts b/src/components/messages.ts
index 79adab814..e3d228dca 100644
--- a/src/components/messages.ts
+++ b/src/components/messages.ts
@@ -283,6 +283,9 @@ export const labels: Record<string, string> = {
journey: 'label.journey',
journeys: 'label.journeys',
journeyDescription: 'label.journey-description',
+ heatmap: 'label.heatmap',
+ heatmaps: 'label.heatmaps',
+ heatmapDescription: 'label.heatmap-description',
compareDates: 'label.compare-dates',
compare: 'label.compare',
current: 'label.current',
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index f7c182b15..463e08404 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -119,6 +119,11 @@ export const EVENT_TYPE = {
performance: 5,
} as const;
+export const HEATMAP_EVENT_TYPE = {
+ click: 1,
+ scroll: 2,
+} as const;
+
export const ENTITY_TYPE = {
website: 1,
link: 2,
diff --git a/src/lib/schema.ts b/src/lib/schema.ts
index 2567c3de6..667c52f9d 100644
--- a/src/lib/schema.ts
+++ b/src/lib/schema.ts
@@ -131,6 +131,7 @@ export const reportTypeParam = z.enum([
'breakdown',
'funnel',
'goal',
+ 'heatmap',
'journey',
'performance',
'retention',
@@ -268,6 +269,15 @@ export const breakdownReportSchema = z.object({
}),
});
+export const heatmapReportSchema = z.object({
+ type: z.literal('heatmap'),
+ parameters: z.object({
+ startDate: z.coerce.date(),
+ endDate: z.coerce.date(),
+ urlPath: z.string().max(500).optional(),
+ }),
+});
+
export const reportBaseSchema = z.object({
websiteId: z.uuid(),
type: reportTypeParam,
@@ -286,6 +296,7 @@ export const reportTypeSchema = z.discriminatedUnion('type', [
revenueReportSchema,
attributionReportSchema,
breakdownReportSchema,
+ heatmapReportSchema,
]);
export const reportSchema = reportBaseSchema;
diff --git a/src/queries/sql/heatmap/extractHeatmapEvents.ts b/src/queries/sql/heatmap/extractHeatmapEvents.ts
new file mode 100644
index 000000000..04e223530
--- /dev/null
+++ b/src/queries/sql/heatmap/extractHeatmapEvents.ts
@@ -0,0 +1,79 @@
+import { HEATMAP_EVENT_TYPE } from '@/lib/constants';
+
+const RRWEB_TYPE_INCREMENTAL = 3;
+const RRWEB_TYPE_META = 4;
+const RRWEB_SOURCE_MOUSE_INTERACTION = 2;
+const RRWEB_SOURCE_VIEWPORT_RESIZE = 4;
+const RRWEB_MOUSE_CLICK = 2;
+
+export interface ExtractedHeatmapEvent {
+ eventType: number;
+ nodeId: number | null;
+ x: number | null;
+ y: number | null;
+ viewportW: number | null;
+ viewportH: number | null;
+ scrollPct: number | null;
+ urlPath: string;
+ createdAt: Date;
+}
+
+function safePathname(href: unknown): string | null {
+ if (typeof href !== 'string') return null;
+ try {
+ return new URL(href).pathname || '/';
+ } catch {
+ return href.startsWith('/') ? href.split(/[?#]/)[0] : null;
+ }
+}
+
+export function extractHeatmapEvents(events: any[]): ExtractedHeatmapEvent[] {
+ if (!Array.isArray(events) || events.length === 0) return [];
+
+ let urlPath: string | null = null;
+ let viewportW: number | null = null;
+ let viewportH: number | null = null;
+ const out: ExtractedHeatmapEvent[] = [];
+
+ for (const ev of events) {
+ if (!ev || typeof ev !== 'object') continue;
+
+ if (ev.type === RRWEB_TYPE_META && ev.data) {
+ const path = safePathname(ev.data.href);
+ if (path) urlPath = path;
+ if (typeof ev.data.width === 'number') viewportW = ev.data.width;
+ if (typeof ev.data.height === 'number') viewportH = ev.data.height;
+ continue;
+ }
+
+ if (ev.type !== RRWEB_TYPE_INCREMENTAL || !ev.data) continue;
+
+ const d = ev.data;
+
+ if (d.source === RRWEB_SOURCE_VIEWPORT_RESIZE) {
+ if (typeof d.width === 'number') viewportW = d.width;
+ if (typeof d.height === 'number') viewportH = d.height;
+ continue;
+ }
+
+ if (
+ d.source === RRWEB_SOURCE_MOUSE_INTERACTION &&
+ d.type === RRWEB_MOUSE_CLICK &&
+ urlPath !== null
+ ) {
+ out.push({
+ eventType: HEATMAP_EVENT_TYPE.click,
+ nodeId: typeof d.id === 'number' ? d.id : null,
+ x: typeof d.x === 'number' ? Math.round(d.x) : null,
+ y: typeof d.y === 'number' ? Math.round(d.y) : null,
+ viewportW,
+ viewportH,
+ scrollPct: null,
+ urlPath,
+ createdAt: new Date(typeof ev.timestamp === 'number' ? ev.timestamp : Date.now()),
+ });
+ }
+ }
+
+ return out;
+}
diff --git a/src/queries/sql/heatmap/getHeatmap.ts b/src/queries/sql/heatmap/getHeatmap.ts
new file mode 100644
index 000000000..9be595f2c
--- /dev/null
+++ b/src/queries/sql/heatmap/getHeatmap.ts
@@ -0,0 +1,207 @@
+import clickhouse from '@/lib/clickhouse';
+import { HEATMAP_EVENT_TYPE } from '@/lib/constants';
+import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db';
+import prisma from '@/lib/prisma';
+
+const FUNCTION_NAME = 'getHeatmap';
+
+const POINT_LIMIT = 5000;
+const PAGE_LIMIT = 100;
+
+export interface HeatmapParameters {
+ startDate: Date;
+ endDate: Date;
+ urlPath?: string;
+}
+
+export interface HeatmapPage {
+ urlPath: string;
+ count: number;
+ sessions: number;
+}
+
+export interface HeatmapPoint {
+ nodeId: number | null;
+ x: number;
+ y: number;
+ viewportW: number;
+ viewportH: number;
+ count: number;
+}
+
+export interface HeatmapResult {
+ pages: HeatmapPage[];
+ points: HeatmapPoint[];
+}
+
+export async function getHeatmap(
+ websiteId: string,
+ parameters: HeatmapParameters,
+): Promise<HeatmapResult> {
+ return runQuery({
+ [PRISMA]: () => relationalQuery(websiteId, parameters),
+ [CLICKHOUSE]: () => clickhouseQuery(websiteId, parameters),
+ });
+}
+
+async function relationalQuery(
+ websiteId: string,
+ { startDate, endDate, urlPath }: HeatmapParameters,
+): Promise<HeatmapResult> {
+ const { rawQuery } = prisma;
+
+ const pages: HeatmapPage[] = await rawQuery(
+ `
+ select
+ url_path as "urlPath",
+ count(*)::int as count,
+ count(distinct visit_id)::int as sessions
+ from heatmap_event
+ where website_id = {{websiteId::uuid}}
+ and event_type = {{eventType}}
+ and created_at between {{startDate}} and {{endDate}}
+ group by url_path
+ order by count desc
+ limit ${PAGE_LIMIT}
+ `,
+ {
+ websiteId,
+ eventType: HEATMAP_EVENT_TYPE.click,
+ startDate,
+ endDate,
+ },
+ FUNCTION_NAME,
+ );
+
+ if (!urlPath) {
+ return { pages, points: [] };
+ }
+
+ const rawPoints: HeatmapPoint[] = await rawQuery(
+ `
+ select
+ node_id as "nodeId",
+ x,
+ y,
+ viewport_w as "viewportW",
+ viewport_h as "viewportH",
+ count(*)::int as count
+ from heatmap_event
+ where website_id = {{websiteId::uuid}}
+ and event_type = {{eventType}}
+ and url_path = {{urlPath}}
+ and created_at between {{startDate}} and {{endDate}}
+ and x is not null
+ and y is not null
+ and viewport_w is not null
+ and viewport_h is not null
+ group by node_id, x, y, viewport_w, viewport_h
+ order by count desc
+ limit ${POINT_LIMIT}
+ `,
+ {
+ websiteId,
+ eventType: HEATMAP_EVENT_TYPE.click,
+ urlPath,
+ startDate,
+ endDate,
+ },
+ FUNCTION_NAME,
+ );
+
+ return { pages, points: rawPoints };
+}
+
+async function clickhouseQuery(
+ websiteId: string,
+ { startDate, endDate, urlPath }: HeatmapParameters,
+): Promise<HeatmapResult> {
+ const { rawQuery } = clickhouse;
+
+ const pageRows = await rawQuery<
+ { urlPath: string; count: string | number; sessions: string | number }[]
+ >(
+ `
+ select
+ url_path as urlPath,
+ count() as count,
+ uniq(visit_id) as sessions
+ from heatmap_event
+ where website_id = {websiteId:UUID}
+ and event_type = {eventType:UInt8}
+ and created_at between {startDate:DateTime64} and {endDate:DateTime64}
+ group by url_path
+ order by count desc
+ limit ${PAGE_LIMIT}
+ `,
+ {
+ websiteId,
+ eventType: HEATMAP_EVENT_TYPE.click,
+ startDate,
+ endDate,
+ },
+ FUNCTION_NAME,
+ );
+
+ const pages: HeatmapPage[] = pageRows.map(p => ({
+ urlPath: p.urlPath,
+ count: Number(p.count),
+ sessions: Number(p.sessions),
+ }));
+
+ if (!urlPath) {
+ return { pages, points: [] };
+ }
+
+ const pointRows = await rawQuery<
+ {
+ nodeId: number | null;
+ x: number;
+ y: number;
+ viewportW: number;
+ viewportH: number;
+ count: string | number;
+ }[]
+ >(
+ `
+ select
+ node_id as nodeId,
+ x,
+ y,
+ viewport_w as viewportW,
+ viewport_h as viewportH,
+ count() as count
+ from heatmap_event
+ where website_id = {websiteId:UUID}
+ and event_type = {eventType:UInt8}
+ and url_path = {urlPath:String}
+ and created_at between {startDate:DateTime64} and {endDate:DateTime64}
+ and x is not null
+ and y is not null
+ and viewport_w is not null
+ and viewport_h is not null
+ group by node_id, x, y, viewport_w, viewport_h
+ order by count desc
+ limit ${POINT_LIMIT}
+ `,
+ {
+ websiteId,
+ eventType: HEATMAP_EVENT_TYPE.click,
+ urlPath,
+ startDate,
+ endDate,
+ },
+ FUNCTION_NAME,
+ );
+
+ const points: HeatmapPoint[] = pointRows.map(p => ({
+ nodeId: p.nodeId === null || p.nodeId === undefined ? null : Number(p.nodeId),
+ x: Number(p.x),
+ y: Number(p.y),
+ viewportW: Number(p.viewportW),
+ viewportH: Number(p.viewportH),
+ count: Number(p.count),
+ }));
+
+ return { pages, points };
+}
diff --git a/src/queries/sql/heatmap/saveHeatmapEvents.ts b/src/queries/sql/heatmap/saveHeatmapEvents.ts
new file mode 100644
index 000000000..b4860074e
--- /dev/null
+++ b/src/queries/sql/heatmap/saveHeatmapEvents.ts
@@ -0,0 +1,76 @@
+import clickhouse from '@/lib/clickhouse';
+import { uuid } from '@/lib/crypto';
+import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db';
+import kafka from '@/lib/kafka';
+import prisma from '@/lib/prisma';
+
+export interface HeatmapEventRow {
+ websiteId: string;
+ sessionId: string;
+ visitId: string;
+ urlPath: string;
+ eventType: number;
+ nodeId: number | null;
+ x: number | null;
+ y: number | null;
+ viewportW: number | null;
+ viewportH: number | null;
+ scrollPct: number | null;
+ createdAt: Date;
+}
+
+export async function saveHeatmapEvents(rows: HeatmapEventRow[]) {
+ if (!rows?.length) return;
+
+ return runQuery({
+ [PRISMA]: () => relationalQuery(rows),
+ [CLICKHOUSE]: () => clickhouseQuery(rows),
+ });
+}
+
+async function relationalQuery(rows: HeatmapEventRow[]) {
+ return prisma.client.heatmapEvent.createMany({
+ data: rows.map(r => ({
+ id: uuid(),
+ websiteId: r.websiteId,
+ sessionId: r.sessionId,
+ visitId: r.visitId,
+ urlPath: r.urlPath,
+ eventType: r.eventType,
+ nodeId: r.nodeId,
+ x: r.x,
+ y: r.y,
+ viewportW: r.viewportW,
+ viewportH: r.viewportH,
+ scrollPct: r.scrollPct,
+ createdAt: r.createdAt,
+ })),
+ });
+}
+
+async function clickhouseQuery(rows: HeatmapEventRow[]) {
+ const { insert, getUTCString } = clickhouse;
+ const { sendMessage } = kafka;
+
+ const messages = rows.map(r => ({
+ heatmap_event_id: uuid(),
+ website_id: r.websiteId,
+ session_id: r.sessionId,
+ visit_id: r.visitId,
+ url_path: r.urlPath,
+ event_type: r.eventType,
+ node_id: r.nodeId,
+ x: r.x,
+ y: r.y,
+ viewport_w: r.viewportW,
+ viewport_h: r.viewportH,
+ scroll_pct: r.scrollPct,
+ created_at: getUTCString(r.createdAt),
+ }));
+
+ if (kafka.enabled) {
+ return sendMessage('heatmap_event', messages);
+ }
+
+ return insert('heatmap_event', messages);
+}
diff --git a/src/queries/sql/index.ts b/src/queries/sql/index.ts
index f5a05d758..b5d57f8e1 100644
--- a/src/queries/sql/index.ts
+++ b/src/queries/sql/index.ts
@@ -26,6 +26,9 @@ export * from './getValues';
export * from './getWebsiteDateRange';
export * from './getWebsiteStats';
export * from './getWeeklyTraffic';
+export * from './heatmap/extractHeatmapEvents';
+export * from './heatmap/getHeatmap';
+export * from './heatmap/saveHeatmapEvents';
export * from './pageviews/getPageviewExpandedMetrics';
export * from './pageviews/getPageviewMetrics';
export * from './pageviews/getPageviewStats';