From 2771abc6a718fe3ea8ccf85e8061504f2d0719a0 Mon Sep 17 00:00:00 2001 From: Leon Acosta Date: Sat, 4 Jul 2026 18:45:45 +0700 Subject: [PATCH 1/8] verify Kafka broker TLS certificate by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When SASL credentials are present, getClient() connected with `rejectUnauthorized: false`, so the SASL password was sent over a TLS connection whose broker certificate was never verified — a MITM could present any certificate and capture the credentials. Verify by default; set KAFKA_SSL_ALLOW_UNAUTHORIZED=true to opt out for self-signed brokers. --- src/lib/kafka.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/kafka.ts b/src/lib/kafka.ts index c8c3220bc..3e25eae4d 100644 --- a/src/lib/kafka.ts +++ b/src/lib/kafka.ts @@ -47,7 +47,7 @@ function getClient() { username && password ? { ssl: { - rejectUnauthorized: false, + rejectUnauthorized: process.env.KAFKA_SSL_ALLOW_UNAUTHORIZED !== 'true', }, sasl: { mechanism, From 71f1745111cfc63bc32dbc21b5b05f8c07529c55 Mon Sep 17 00:00:00 2001 From: Aleksey Kopaev Date: Mon, 13 Jul 2026 10:11:58 +0200 Subject: [PATCH 2/8] i18n(ru-RU): add 21 missing Russian translations Several keys present in en-US were missing from ru-RU, so the UI showed raw keys (e.g. label.heatmaps) on the Russian locale. Adds translations for the missing label.* and message.* keys, including heatmap, replay recorder, board, LLM, and upgrade/plan strings. --- public/intl/messages/ru-RU.json | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/public/intl/messages/ru-RU.json b/public/intl/messages/ru-RU.json index 37b443086..8b7776040 100644 --- a/public/intl/messages/ru-RU.json +++ b/public/intl/messages/ru-RU.json @@ -33,6 +33,7 @@ "behavior": "Поведение", "block-selector": "Выбор блока", "boards": "Доски", + "board-type": "Тип доски", "bounce-rate": "Отказы", "breakdown": "Авария", "browser": "Браузер", @@ -70,6 +71,7 @@ "created": "Создано", "created-by": "Создано", "criteria": "Критерии", + "cumulative": "Накопительно", "currency": "Валюта", "current": "Текущий", "current-password": "Текущий пароль", @@ -126,6 +128,8 @@ "filter-raw": "Сырые данные", "filters": "Фильтры", "filters-enabled": "Фильтры включены", + "property-filter": "Фильтр по свойству", + "activity-by-property": "Активность по свойству", "first-click": "Первый клик", "first-seen": "Первый вход", "funnel": "Воронка", @@ -139,6 +143,9 @@ "greater-than-equals": "Больше или равно", "grouped": "Группировано", "growth": "Рост", + "heatmap": "Тепловая карта", + "heatmap-description": "Визуализируйте, где посетители кликают и как далеко прокручивают ваши страницы.", + "heatmaps": "Тепловые карты", "hostname": "Имя хоста", "hour": "Час", "includes": "Включает", @@ -175,6 +182,7 @@ "links": "Ссылки", "location": "Местоположение", "login": "Войти", + "llm": "LLM", "logout": "Выйти", "manage": "Управление", "manager": "Менеджер", @@ -203,6 +211,7 @@ "number-of-records": "{x} {x, plural, one {запись} other {записи}}", "ok": "ОК", "online": "Онлайн", + "open": "Смешанный", "organic-search": "Органический поиск", "organic-shopping": "Органические покупки", "organic-social": "Органические соцсети", @@ -216,6 +225,7 @@ "page-views": "Просмотры страниц", "pages": "Страницы", "pageTitle": "Название страницы", + "period": "Период", "paid-ads": "Платная реклама", "paid-search": "Платный поиск", "paid-shopping": "Платные покупки", @@ -258,6 +268,7 @@ "replay": "Запись сессии", "replay-enabled": "Запись сессий включена", "replay-id": "Replay ID", + "recorder-code": "Код записи", "replays": "Записи сессий", "reports": "Отчеты", "required": "Обязательное", @@ -274,6 +285,7 @@ "sample-size": "Размер выборки", "save": "Сохранить", "save-cohort": "Сохранить когорту", + "save-replay": "Сохранить запись", "save-segment": "Сохранить сегмент", "screen": "Экран", "screens": "Экраны", @@ -281,7 +293,10 @@ "segment": "Сегмент", "segments": "Сегменты", "select": "Выберите", + "select-link": "Выберите ссылку", + "select-pixel": "Выберите пиксель", "select-component": "Выберите компонент", + "select-event": "Выберите событие", "select-date": "Выберите дату", "select-filter": "Выберите фильтр", "select-role": "Выберите роль", @@ -342,8 +357,12 @@ "unique-events": "Уникальные события", "unique-visitors": "Уникальные посетители", "uniqueCustomers": "Уникальные клиенты", + "customers": "Клиенты", + "orders": "Заказы", + "saved": "Сохранено", "unknown": "Неизвестно", "untitled": "Без названия", + "upgrade": "Улучшить план", "update": "Обновление", "url": "URL", "user": "Пользователь", @@ -406,6 +425,7 @@ "reset-website": "Для сброса введите RESET", "reset-website-warning": "Вся статистика для этого сайта будет удалена, но ваш код отслеживания останется нетронутым.", "saved": "Успешно сохранено.", + "select-board-entity-first": "Сначала выберите сайт, пиксель или ссылку.", "select-component-preview": "Выберите компонент для предпросмотра", "select-website-first": "Сначала выберите сайт", "sever-error": "Ошибка сервера", @@ -422,6 +442,7 @@ "user-deleted": "Пользователь удален.", "replay-min-duration-description": "Показывать только воспроизведения с такой или большей продолжительностью.", "viewed-page": "Просмотренная страница", + "upgrade-required": "Для этой функции требуется подписка на план {plan}.", "visitor-log": "Посетитель из {country} используя {browser} на {os} {device}" } } From 712b32c7bfa5121b5d3ce744975dc485bae42ec2 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Tue, 14 Jul 2026 14:58:11 -0700 Subject: [PATCH 3/8] sparkline performance --- .../queries/useWebsiteListChartsQuery.ts | 3 +- src/queries/sql/getWebsiteListCharts.ts | 124 +++++------------- 2 files changed, 34 insertions(+), 93 deletions(-) diff --git a/src/components/hooks/queries/useWebsiteListChartsQuery.ts b/src/components/hooks/queries/useWebsiteListChartsQuery.ts index 967d29bf6..89aec198e 100644 --- a/src/components/hooks/queries/useWebsiteListChartsQuery.ts +++ b/src/components/hooks/queries/useWebsiteListChartsQuery.ts @@ -12,7 +12,7 @@ function useListChartsQuery(queryKey: string, path: string, idsInput: string[]) const { timezone, canonicalizeTimezone } = useTimezone(); const ids = useMemo( - () => Array.from(new Set(idsInput.map(id => id?.trim()).filter(Boolean))), + () => Array.from(new Set(idsInput.map(id => id?.trim()).filter(Boolean))).sort(), [idsInput], ); const resolvedTimezone = canonicalizeTimezone(timezone); @@ -25,6 +25,7 @@ function useListChartsQuery(queryKey: string, path: string, idsInput: string[]) timezone: resolvedTimezone, }), enabled: ids.length > 0, + staleTime: 5 * 60 * 1000, }); } diff --git a/src/queries/sql/getWebsiteListCharts.ts b/src/queries/sql/getWebsiteListCharts.ts index e97e70778..ac7a424a6 100644 --- a/src/queries/sql/getWebsiteListCharts.ts +++ b/src/queries/sql/getWebsiteListCharts.ts @@ -11,15 +11,10 @@ const BUCKET_HOURS = 12; interface WebsiteListChartPoint { websiteId: string; - x: string; + x: string | null; y: number; } -interface WebsiteListChartTotal { - websiteId: string; - total: number; -} - export interface WebsiteListChartData { values: number[]; total: number; @@ -45,20 +40,14 @@ export async function getWebsiteListCharts( return runQuery({ [PRISMA]: async () => { - const [points, totals] = await Promise.all([ - relationalQuery(websiteIds, startDate, endDate, timezone, eventType), - relationalTotalsQuery(websiteIds, startDate, endDate, eventType), - ]); + const points = await relationalQuery(websiteIds, startDate, endDate, timezone, eventType); - return formatResults({ points, totals, websiteIds, startDate, endDate, timezone }); + return formatResults({ points, websiteIds, startDate, endDate, timezone }); }, [CLICKHOUSE]: async () => { - const [points, totals] = await Promise.all([ - clickhouseQuery(websiteIds, startDate, endDate, timezone, eventType), - clickhouseTotalsQuery(websiteIds, startDate, endDate, eventType), - ]); + const points = await clickhouseQuery(websiteIds, startDate, endDate, timezone, eventType); - return formatResults({ points, totals, websiteIds, startDate, endDate, timezone }); + return formatResults({ points, websiteIds, startDate, endDate, timezone }); }, }); } @@ -95,14 +84,20 @@ async function relationalQuery( return rawQuery( ` select - website_event.website_id as "websiteId", - ${bucketSql} as x, - count(distinct website_event.session_id) as y - from website_event - where website_event.website_id = any({{websiteIds}}::uuid[]) - ${eventTypeQuery} - and website_event.created_at between {{startDate}} and {{endDate}} - group by 1, 2 + "websiteId", + x, + count(distinct session_id) as y + from ( + select + website_event.website_id as "websiteId", + ${bucketSql} as x, + website_event.session_id + from website_event + where website_event.website_id = any({{websiteIds}}::uuid[]) + ${eventTypeQuery} + and website_event.created_at between {{startDate}} and {{endDate}} + ) as events + group by grouping sets (("websiteId", x), ("websiteId")) order by 1, 2 `, { websiteIds, startDate, endDate }, @@ -110,35 +105,6 @@ async function relationalQuery( ); } -async function relationalTotalsQuery( - websiteIds: string[], - startDate: Date, - endDate: Date, - eventType?: number, -): Promise { - const { rawQuery } = prisma; - const eventTypeQuery = - eventType != null - ? `and website_event.event_type = ${eventType}` - : `and website_event.event_type NOT IN (${EVENT_TYPE.customEvent}, ${EVENT_TYPE.performance})`; - - return rawQuery( - ` - select - website_event.website_id as "websiteId", - count(distinct website_event.session_id) as total - from website_event - where website_event.website_id = any({{websiteIds}}::uuid[]) - ${eventTypeQuery} - and website_event.created_at between {{startDate}} and {{endDate}} - group by 1 - order by 1 - `, - { websiteIds, startDate, endDate }, - FUNCTION_NAME, - ); -} - async function clickhouseQuery( websiteIds: string[], startDate: Date, @@ -169,7 +135,7 @@ async function clickhouseQuery( where website_id in {websiteIds:Array(UUID)} ${eventTypeQuery} and created_at between {startDate:DateTime64} and {endDate:DateTime64} - group by website_id, x + group by grouping sets ((website_id, x), (website_id)) order by websiteId, x `, { websiteIds, startDate, endDate }, @@ -177,46 +143,15 @@ async function clickhouseQuery( ); } -async function clickhouseTotalsQuery( - websiteIds: string[], - startDate: Date, - endDate: Date, - eventType?: number, -): Promise { - const { rawQuery } = clickhouse; - const eventTypeQuery = - eventType != null - ? `and event_type = ${eventType}` - : `and event_type NOT IN (${EVENT_TYPE.customEvent}, ${EVENT_TYPE.performance})`; - - return rawQuery( - ` - select - website_id as websiteId, - uniq(session_id) as total - from website_event_stats_hourly as website_event - where website_id in {websiteIds:Array(UUID)} - ${eventTypeQuery} - and created_at between {startDate:DateTime64} and {endDate:DateTime64} - group by website_id - order by websiteId - `, - { websiteIds, startDate, endDate }, - FUNCTION_NAME, - ); -} - function formatResults( { points, - totals, websiteIds, startDate, endDate, timezone, }: { points: WebsiteListChartPoint[]; - totals: WebsiteListChartTotal[]; websiteIds: string[]; startDate: Date; endDate: Date; @@ -243,18 +178,23 @@ function formatResults( }, {}); points.forEach(({ websiteId, x, y }) => { + if (!charts[websiteId]) { + return; + } + + // Subtotal rows from GROUPING SETS (null x on Postgres, '' on ClickHouse) + // carry the window-wide distinct total per website + if (!x) { + charts[websiteId].total = Number(y); + return; + } + const index = bucketIndex.get(String(x).slice(0, 19)); - if (index !== undefined && charts[websiteId]) { + if (index !== undefined) { charts[websiteId].values[index] = Number(y); } }); - totals.forEach(({ websiteId, total }) => { - if (charts[websiteId]) { - charts[websiteId].total = Number(total); - } - }); - return charts; } From 8a75208d5b4c3709251ff3b74bb7af4119c2437d Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Tue, 14 Jul 2026 15:23:32 -0700 Subject: [PATCH 4/8] fix permissions loop for charts route --- src/app/api/websites/charts/route.ts | 10 +--- src/permissions/website.ts | 71 ++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 8 deletions(-) diff --git a/src/app/api/websites/charts/route.ts b/src/app/api/websites/charts/route.ts index b213e4fc4..76d3d1fdc 100644 --- a/src/app/api/websites/charts/route.ts +++ b/src/app/api/websites/charts/route.ts @@ -1,10 +1,10 @@ import { z } from 'zod'; import { fromZonedTime } from 'date-fns-tz'; import { parseDateRange } from '@/lib/date'; +import { canViewBatchWebsites } from '@/permissions/website'; import { parseRequest } from '@/lib/request'; import { json } from '@/lib/response'; import { timezoneParam } from '@/lib/schema'; -import { canViewWebsite } from '@/permissions'; import { getWebsiteListCharts } from '@/queries/sql'; const schema = z.object({ @@ -32,13 +32,7 @@ export async function GET(request: Request) { : fromZonedTime(defaultRange.startDate, timezone); const endDate = hasDateRange ? new Date(query.endAt) : fromZonedTime(defaultRange.endDate, timezone); - const websiteIds = ( - await Promise.all( - query.ids.map(async (websiteId: string) => - (await canViewWebsite(auth, websiteId)) ? websiteId : null, - ), - ) - ).filter(Boolean); + const websiteIds = await canViewBatchWebsites(auth, query.ids); const data = await getWebsiteListCharts(websiteIds, { startDate, diff --git a/src/permissions/website.ts b/src/permissions/website.ts index cf8e8d82d..e549b615e 100644 --- a/src/permissions/website.ts +++ b/src/permissions/website.ts @@ -1,6 +1,7 @@ import { hasPermission } from '@/lib/auth'; import { PERMISSIONS } from '@/lib/constants'; import { getEntity } from '@/lib/entity'; +import prisma from '@/lib/prisma'; import type { Auth } from '@/lib/types'; import { getTeamUser, getWebsite } from '@/queries/prisma'; @@ -39,6 +40,76 @@ export async function canViewWebsite({ user, shareToken }: Auth, websiteId: stri return false; } +export async function canViewBatchWebsites({ user, shareToken }: Auth, websiteIds: string[]) { + if (!websiteIds.length) { + return []; + } + + const requestedIds = Array.from(new Set(websiteIds)); + + if (user?.isAdmin) { + return requestedIds; + } + + const shareAllowedIds = new Set( + [ + shareToken?.websiteId, + shareToken?.pixelId, + shareToken?.linkId, + ...(shareToken?.websiteIds ?? []), + ...(shareToken?.pixelIds ?? []), + ...(shareToken?.linkIds ?? []), + ].filter((id): id is string => Boolean(id)), + ); + + if (!user) { + return requestedIds.filter(id => shareAllowedIds.has(id)); + } + + const websites = await prisma.client.website.findMany({ + where: { + id: { + in: requestedIds, + }, + }, + select: { + id: true, + userId: true, + teamId: true, + }, + }); + + const ownedIds = new Set( + websites.filter(website => website.userId === user.id).map(website => website.id), + ); + const teamIds = Array.from( + new Set(websites.map(website => website.teamId).filter((teamId): teamId is string => Boolean(teamId))), + ); + const teamUsers = teamIds.length + ? await prisma.client.teamUser.findMany({ + where: { + userId: user.id, + teamId: { + in: teamIds, + }, + }, + select: { + teamId: true, + }, + }) + : []; + const allowedTeamIds = new Set(teamUsers.map(teamUser => teamUser.teamId)); + const teamOwnedIds = new Set( + websites + .filter(website => website.teamId && allowedTeamIds.has(website.teamId)) + .map(website => website.id), + ); + + return requestedIds.filter( + id => shareAllowedIds.has(id) || ownedIds.has(id) || teamOwnedIds.has(id), + ); +} + export async function canViewAllWebsites({ user }: Auth) { return user?.isAdmin ?? false; } From 7afc4ccf6b29e2fe6c2b02c26154da4aa9d0c98f Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Wed, 15 Jul 2026 11:20:27 -0700 Subject: [PATCH 5/8] session activity identify stitching --- .../migrations/13_add_session_link.sql | 12 +++ db/clickhouse/schema.sql | 13 +++ .../21_add_session_link/migration.sql | 11 +++ prisma/schema.prisma | 11 +++ .../[websiteId]/sessions/SessionActivity.tsx | 3 + .../[websiteId]/sessions/SessionProfile.tsx | 1 + src/app/api/send/route.ts | 36 ++++++++- .../sessions/[sessionId]/activity/route.ts | 45 ++++++++--- .../hooks/queries/useSessionActivityQuery.ts | 4 +- src/queries/sql/index.ts | 4 + .../sql/sessions/getLinkedDistinctIds.ts | 44 +++++++++++ .../sql/sessions/getLinkedSessionIds.ts | 50 ++++++++++++ .../sql/sessions/getSessionActivity.ts | 22 +++--- .../sql/sessions/getSessionActivityBounds.ts | 62 +++++++++++++++ src/queries/sql/sessions/saveSessionLink.ts | 79 +++++++++++++++++++ 15 files changed, 374 insertions(+), 23 deletions(-) create mode 100644 db/clickhouse/migrations/13_add_session_link.sql create mode 100644 prisma/migrations/21_add_session_link/migration.sql create mode 100644 src/queries/sql/sessions/getLinkedDistinctIds.ts create mode 100644 src/queries/sql/sessions/getLinkedSessionIds.ts create mode 100644 src/queries/sql/sessions/getSessionActivityBounds.ts create mode 100644 src/queries/sql/sessions/saveSessionLink.ts diff --git a/db/clickhouse/migrations/13_add_session_link.sql b/db/clickhouse/migrations/13_add_session_link.sql new file mode 100644 index 000000000..2455c05e7 --- /dev/null +++ b/db/clickhouse/migrations/13_add_session_link.sql @@ -0,0 +1,12 @@ +-- Create session_link +CREATE TABLE umami.session_link +( + website_id UUID, + session_id UUID, + distinct_id String, + created_at DateTime('UTC'), + INDEX idx_session_id session_id TYPE bloom_filter GRANULARITY 1 +) +ENGINE = ReplacingMergeTree + ORDER BY (website_id, distinct_id, session_id) + SETTINGS index_granularity = 8192; diff --git a/db/clickhouse/schema.sql b/db/clickhouse/schema.sql index abcbe1434..1030538c1 100644 --- a/db/clickhouse/schema.sql +++ b/db/clickhouse/schema.sql @@ -424,3 +424,16 @@ ENGINE = MergeTree PARTITION BY toYYYYMM(created_at) ORDER BY (website_id, url_path, event_type, created_at) SETTINGS index_granularity = 8192; + +-- Create session_link +CREATE TABLE umami.session_link +( + website_id UUID, + session_id UUID, + distinct_id String, + created_at DateTime('UTC'), + INDEX idx_session_id session_id TYPE bloom_filter GRANULARITY 1 +) +ENGINE = ReplacingMergeTree + ORDER BY (website_id, distinct_id, session_id) + SETTINGS index_granularity = 8192; diff --git a/prisma/migrations/21_add_session_link/migration.sql b/prisma/migrations/21_add_session_link/migration.sql new file mode 100644 index 000000000..1be077332 --- /dev/null +++ b/prisma/migrations/21_add_session_link/migration.sql @@ -0,0 +1,11 @@ +-- CreateTable +CREATE TABLE "session_link" ( + "website_id" UUID NOT NULL, + "session_id" UUID NOT NULL, + "distinct_id" VARCHAR(50) NOT NULL, + "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "session_link_pkey" PRIMARY KEY ("website_id","distinct_id","session_id") +); + +CREATE INDEX "session_link_website_id_session_id_idx" ON "session_link"("website_id", "session_id"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 1c285de47..2a7c49e99 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -63,6 +63,17 @@ model Session { @@map("session") } +model SessionLink { + websiteId String @map("website_id") @db.Uuid + sessionId String @map("session_id") @db.Uuid + distinctId String @map("distinct_id") @db.VarChar(50) + createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6) + + @@id([websiteId, distinctId, sessionId]) + @@index([websiteId, sessionId]) + @@map("session_link") +} + model Website { id String @id() @map("website_id") @db.Uuid name String @db.VarChar(100) diff --git a/src/app/(main)/websites/[websiteId]/sessions/SessionActivity.tsx b/src/app/(main)/websites/[websiteId]/sessions/SessionActivity.tsx index 1a54f506a..78a62815d 100644 --- a/src/app/(main)/websites/[websiteId]/sessions/SessionActivity.tsx +++ b/src/app/(main)/websites/[websiteId]/sessions/SessionActivity.tsx @@ -22,11 +22,13 @@ export function SessionActivity({ sessionId, startDate, endDate, + distinctId, }: { websiteId: string; sessionId: string; startDate: Date; endDate: Date; + distinctId?: string; }) { const { t, labels } = useMessages(); const { formatTimezoneDate } = useTimezone(); @@ -35,6 +37,7 @@ export function SessionActivity({ sessionId, startDate, endDate, + distinctId, ); const { isMobile } = useMobile(); let lastDay = null; diff --git a/src/app/(main)/websites/[websiteId]/sessions/SessionProfile.tsx b/src/app/(main)/websites/[websiteId]/sessions/SessionProfile.tsx index ffc6ce7f1..1c0405472 100644 --- a/src/app/(main)/websites/[websiteId]/sessions/SessionProfile.tsx +++ b/src/app/(main)/websites/[websiteId]/sessions/SessionProfile.tsx @@ -81,6 +81,7 @@ export function SessionProfile({ sessionId={sessionId} startDate={data?.firstAt} endDate={data?.lastAt} + distinctId={data?.distinctId} /> diff --git a/src/app/api/send/route.ts b/src/app/api/send/route.ts index 6d2086176..e07ba2971 100644 --- a/src/app/api/send/route.ts +++ b/src/app/api/send/route.ts @@ -11,13 +11,14 @@ import { parseRequest } from '@/lib/request'; import { badRequest, forbidden, json, serverError } from '@/lib/response'; import { anyObjectParam, urlOrPathParam } from '@/lib/schema'; import { safeDecodeURI, safeDecodeURIComponent } from '@/lib/url'; -import { createSession, saveEvent, saveSessionData } from '@/queries/sql'; +import { createSession, saveEvent, saveSessionData, saveSessionLink } from '@/queries/sql'; interface Cache { websiteId: string; sessionId: string; visitId: string; iat: number; + sessionLinkId?: string; } // Reject strings whose first character is a spreadsheet formula trigger to @@ -128,6 +129,9 @@ export async function POST(request: Request) { } } + // Carried forward in the cache token so repeat identify calls skip the link write + let sessionLinkId = cache?.sessionLinkId; + // Client info const { ip, userAgent, device, browser, os, country, region, city } = await getClientInfo( request, @@ -277,6 +281,34 @@ export async function POST(request: Request) { twclid, }); } else if (type === COLLECTION_TYPE.identify) { + if (websiteId && id) { + // Persist both memberships so stitched activity can be resolved from + // either the anonymous session or the identified session. + const anonymousSessionId = uuid(sourceId, ip, userAgent, sessionSalt); + const linkedSessionIds = [...new Set([anonymousSessionId, sessionId])]; + const newLinkId = hash(...linkedSessionIds, id); + + if (sessionLinkId !== newLinkId) { + // Best-effort: a link failure must not block the session data write below + try { + await Promise.all( + linkedSessionIds.map(linkedSessionId => + saveSessionLink({ + websiteId, + sessionId: linkedSessionId, + distinctId: id, + createdAt, + }), + ), + ); + sessionLinkId = newLinkId; + } catch (e) { + // eslint-disable-next-line no-console + console.error('Failed to save session link:', e); + } + } + } + if (data) { await saveSessionData({ websiteId, @@ -316,7 +348,7 @@ export async function POST(request: Request) { } const token = createToken( - { websiteId, sessionId, visitId, iat, type: CACHE_TOKEN_TYPE }, + { websiteId, sessionId, visitId, iat, sessionLinkId, type: CACHE_TOKEN_TYPE }, secret(), ); diff --git a/src/app/api/websites/[websiteId]/sessions/[sessionId]/activity/route.ts b/src/app/api/websites/[websiteId]/sessions/[sessionId]/activity/route.ts index 23eb78ab8..5af7660b7 100644 --- a/src/app/api/websites/[websiteId]/sessions/[sessionId]/activity/route.ts +++ b/src/app/api/websites/[websiteId]/sessions/[sessionId]/activity/route.ts @@ -1,8 +1,15 @@ import { z } from 'zod'; +import { FIELD_LENGTH } from '@/lib/constants'; +import { uuid } from '@/lib/crypto'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; import { canViewWebsiteSection } from '@/permissions'; -import { getSessionActivity } from '@/queries/sql'; +import { + getLinkedDistinctIds, + getLinkedSessionIds, + getSessionActivity, + getSessionActivityBounds, +} from '@/queries/sql'; export async function GET( request: Request, @@ -11,6 +18,7 @@ export async function GET( const schema = z.object({ startAt: z.coerce.number().int(), endAt: z.coerce.number().int(), + distinctId: z.string().max(FIELD_LENGTH.distinctId).optional(), }); const { auth, query, error } = await parseRequest(request, schema); @@ -22,19 +30,38 @@ export async function GET( const { websiteId, sessionId } = await params; if ( - !(await canViewWebsiteSection(auth, websiteId, [ - 'sessions', - 'events', - 'realtime', - 'revenue', - ])) + !(await canViewWebsiteSection(auth, websiteId, ['sessions', 'events', 'realtime', 'revenue'])) ) { return unauthorized(); } - const filters = await getQueryFilters(query, websiteId); + let sessionIds = [sessionId]; + let startAt = query.startAt; + let endAt = query.endAt; + const distinctIds = query.distinctId + ? [query.distinctId] + : await getLinkedDistinctIds(websiteId, sessionId); - const data = await getSessionActivity(websiteId, sessionId, filters); + if (distinctIds.length) { + const links = await Promise.all(distinctIds.map(distinctId => getLinkedSessionIds(websiteId, distinctId))); + const linkedIds = links.flatMap(group => group.map(link => link.sessionId)); + const identifiedIds = distinctIds.map(distinctId => uuid(websiteId, distinctId)); + + sessionIds = Array.from(new Set([sessionId, ...identifiedIds, ...linkedIds])); + + if (sessionIds.length > 1) { + const bounds = await getSessionActivityBounds(websiteId, sessionIds); + + if (bounds?.firstAt && bounds?.lastAt) { + startAt = Math.min(startAt, +new Date(bounds.firstAt)); + endAt = Math.max(endAt, +new Date(bounds.lastAt)); + } + } + } + + const filters = await getQueryFilters({ ...query, startAt, endAt }, websiteId); + + const data = await getSessionActivity(websiteId, sessionIds, filters); return json(data); } diff --git a/src/components/hooks/queries/useSessionActivityQuery.ts b/src/components/hooks/queries/useSessionActivityQuery.ts index d8d34aca6..08f1a3b87 100644 --- a/src/components/hooks/queries/useSessionActivityQuery.ts +++ b/src/components/hooks/queries/useSessionActivityQuery.ts @@ -5,15 +5,17 @@ export function useSessionActivityQuery( sessionId: string, startDate: Date, endDate: Date, + distinctId?: string, ) { const { get, useQuery } = useApi(); return useQuery({ - queryKey: ['session:activity', { websiteId, sessionId, startDate, endDate }], + queryKey: ['session:activity', { websiteId, sessionId, startDate, endDate, distinctId }], queryFn: () => { return get(`/websites/${websiteId}/sessions/${sessionId}/activity`, { startAt: +new Date(startDate), endAt: +new Date(endDate), + ...(distinctId && { distinctId }), }); }, enabled: Boolean(websiteId && sessionId && startDate && endDate), diff --git a/src/queries/sql/index.ts b/src/queries/sql/index.ts index a4be400d0..2139e58af 100644 --- a/src/queries/sql/index.ts +++ b/src/queries/sql/index.ts @@ -43,7 +43,10 @@ export * from './reports/getJourney'; export * from './reports/getRetention'; export * from './reports/getUTM'; export * from './sessions/createSession'; +export * from './sessions/getLinkedDistinctIds'; +export * from './sessions/getLinkedSessionIds'; export * from './sessions/getSessionActivity'; +export * from './sessions/getSessionActivityBounds'; export * from './sessions/getSessionData'; export * from './sessions/getSessionDataActivityStats'; export * from './sessions/getSessionDataArraySeries'; @@ -61,3 +64,4 @@ export * from './sessions/getWebsiteSession'; export * from './sessions/getWebsiteSessionStats'; export * from './sessions/getWebsiteSessions'; export * from './sessions/saveSessionData'; +export * from './sessions/saveSessionLink'; diff --git a/src/queries/sql/sessions/getLinkedDistinctIds.ts b/src/queries/sql/sessions/getLinkedDistinctIds.ts new file mode 100644 index 000000000..d3d9953cb --- /dev/null +++ b/src/queries/sql/sessions/getLinkedDistinctIds.ts @@ -0,0 +1,44 @@ +import clickhouse from '@/lib/clickhouse'; +import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db'; +import prisma from '@/lib/prisma'; + +const FUNCTION_NAME = 'getLinkedDistinctIds'; + +export async function getLinkedDistinctIds( + ...args: [websiteId: string, sessionId: string] +): Promise { + return runQuery({ + [PRISMA]: () => relationalQuery(...args), + [CLICKHOUSE]: () => clickhouseQuery(...args), + }); +} + +async function relationalQuery(websiteId: string, sessionId: string): Promise { + const { rawQuery } = prisma; + + return rawQuery( + ` + select distinct distinct_id as "distinctId" + from session_link + where website_id = {{websiteId::uuid}} + and session_id = {{sessionId::uuid}} + `, + { websiteId, sessionId }, + FUNCTION_NAME, + ).then(result => (result as { distinctId: string }[]).map(({ distinctId }) => distinctId)); +} + +async function clickhouseQuery(websiteId: string, sessionId: string): Promise { + const { rawQuery } = clickhouse; + + return rawQuery( + ` + select distinct distinct_id as distinctId + from session_link + where website_id = {websiteId:UUID} + and session_id = {sessionId:UUID} + `, + { websiteId, sessionId }, + FUNCTION_NAME, + ).then(result => (result as { distinctId: string }[]).map(({ distinctId }) => distinctId)); +} diff --git a/src/queries/sql/sessions/getLinkedSessionIds.ts b/src/queries/sql/sessions/getLinkedSessionIds.ts new file mode 100644 index 000000000..58f67651f --- /dev/null +++ b/src/queries/sql/sessions/getLinkedSessionIds.ts @@ -0,0 +1,50 @@ +import clickhouse from '@/lib/clickhouse'; +import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db'; +import prisma from '@/lib/prisma'; + +const FUNCTION_NAME = 'getLinkedSessionIds'; + +export async function getLinkedSessionIds( + ...args: [websiteId: string, distinctId: string] +): Promise<{ sessionId: string; createdAt: string }[]> { + return runQuery({ + [PRISMA]: () => relationalQuery(...args), + [CLICKHOUSE]: () => clickhouseQuery(...args), + }); +} + +async function relationalQuery(websiteId: string, distinctId: string) { + const { rawQuery } = prisma; + + return rawQuery( + ` + select + session_id as "sessionId", + min(created_at) as "createdAt" + from session_link + where website_id = {{websiteId::uuid}} + and distinct_id = {{distinctId}} + group by session_id + `, + { websiteId, distinctId }, + FUNCTION_NAME, + ); +} + +async function clickhouseQuery(websiteId: string, distinctId: string) { + const { rawQuery } = clickhouse; + + return rawQuery( + ` + select + session_id as sessionId, + min(created_at) as createdAt + from session_link + where website_id = {websiteId:UUID} + and distinct_id = {distinctId:String} + group by session_id + `, + { websiteId, distinctId }, + FUNCTION_NAME, + ); +} diff --git a/src/queries/sql/sessions/getSessionActivity.ts b/src/queries/sql/sessions/getSessionActivity.ts index f8cff7f39..c71b251b9 100644 --- a/src/queries/sql/sessions/getSessionActivity.ts +++ b/src/queries/sql/sessions/getSessionActivity.ts @@ -7,7 +7,7 @@ import type { QueryFilters } from '@/lib/types'; const FUNCTION_NAME = 'getSessionActivity'; export async function getSessionActivity( - ...args: [websiteId: string, sessionId: string, filters: QueryFilters] + ...args: [websiteId: string, sessionIds: string[], filters: QueryFilters] ) { return runQuery({ [PRISMA]: () => relationalQuery(...args), @@ -15,7 +15,7 @@ export async function getSessionActivity( }); } -async function relationalQuery(websiteId: string, sessionId: string, filters: QueryFilters) { +async function relationalQuery(websiteId: string, sessionIds: string[], filters: QueryFilters) { const { rawQuery } = prisma; const { startDate, endDate } = filters; @@ -37,18 +37,18 @@ async function relationalQuery(websiteId: string, sessionId: string, filters: Qu and created_at between {{startDate}} and {{endDate}}) AS "hasData" from website_event where website_id = {{websiteId::uuid}} - and session_id = {{sessionId::uuid}} + and session_id = any({{sessionIds}}::uuid[]) and event_type != ${EVENT_TYPE.performance} and created_at between {{startDate}} and {{endDate}} order by created_at desc limit 500 `, - { websiteId, sessionId, startDate, endDate }, + { websiteId, sessionIds, startDate, endDate }, FUNCTION_NAME, ); } -async function clickhouseQuery(websiteId: string, sessionId: string, filters: QueryFilters) { +async function clickhouseQuery(websiteId: string, sessionIds: string[], filters: QueryFilters) { const { rawQuery } = clickhouse; const { startDate, endDate } = filters; @@ -64,20 +64,20 @@ async function clickhouseQuery(websiteId: string, sessionId: string, filters: Qu event_name as eventName, visit_id as visitId, hostname, - event_id IN (select event_id - from event_data - where website_id = {websiteId:UUID} - and session_id = {sessionId:UUID} + event_id IN (select event_id + from event_data + where website_id = {websiteId:UUID} + and session_id in {sessionIds:Array(UUID)} and created_at between {startDate:DateTime64} and {endDate:DateTime64}) AS hasData from website_event where website_id = {websiteId:UUID} - and session_id = {sessionId:UUID} + and session_id in {sessionIds:Array(UUID)} and event_type != ${EVENT_TYPE.performance} and created_at between {startDate:DateTime64} and {endDate:DateTime64} order by created_at desc limit 500 `, - { websiteId, sessionId, startDate, endDate }, + { websiteId, sessionIds, startDate, endDate }, FUNCTION_NAME, ); } diff --git a/src/queries/sql/sessions/getSessionActivityBounds.ts b/src/queries/sql/sessions/getSessionActivityBounds.ts new file mode 100644 index 000000000..02debf8eb --- /dev/null +++ b/src/queries/sql/sessions/getSessionActivityBounds.ts @@ -0,0 +1,62 @@ +import clickhouse from '@/lib/clickhouse'; +import { EVENT_TYPE } from '@/lib/constants'; +import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db'; +import prisma from '@/lib/prisma'; + +const FUNCTION_NAME = 'getSessionActivityBounds'; + +interface SessionActivityBounds { + firstAt: string | Date; + lastAt: string | Date; +} + +export async function getSessionActivityBounds( + ...args: [websiteId: string, sessionIds: string[]] +): Promise { + return runQuery({ + [PRISMA]: () => relationalQuery(...args), + [CLICKHOUSE]: () => clickhouseQuery(...args), + }); +} + +async function relationalQuery( + websiteId: string, + sessionIds: string[], +): Promise { + const { rawQuery } = prisma; + + return rawQuery( + ` + select + min(created_at) as "firstAt", + max(created_at) as "lastAt" + from website_event + where website_id = {{websiteId::uuid}} + and session_id = any({{sessionIds}}::uuid[]) + and event_type != ${EVENT_TYPE.performance} + `, + { websiteId, sessionIds }, + FUNCTION_NAME, + ).then(result => (result?.[0]?.firstAt && result?.[0]?.lastAt ? result[0] : null)); +} + +async function clickhouseQuery( + websiteId: string, + sessionIds: string[], +): Promise { + const { rawQuery, getDateStringSQL } = clickhouse; + + return rawQuery( + ` + select + ${getDateStringSQL('min(created_at)')} as firstAt, + ${getDateStringSQL('max(created_at)')} as lastAt + from website_event + where website_id = {websiteId:UUID} + and session_id in {sessionIds:Array(UUID)} + and event_type != ${EVENT_TYPE.performance} + `, + { websiteId, sessionIds }, + FUNCTION_NAME, + ).then(result => (result?.[0]?.firstAt && result?.[0]?.lastAt ? result[0] : null)); +} diff --git a/src/queries/sql/sessions/saveSessionLink.ts b/src/queries/sql/sessions/saveSessionLink.ts new file mode 100644 index 000000000..7fcabe000 --- /dev/null +++ b/src/queries/sql/sessions/saveSessionLink.ts @@ -0,0 +1,79 @@ +import clickhouse from '@/lib/clickhouse'; +import { FIELD_LENGTH } from '@/lib/constants'; +import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db'; +import { truncateString } from '@/lib/format'; +import kafka from '@/lib/kafka'; +import prisma from '@/lib/prisma'; + +const FUNCTION_NAME = 'saveSessionLink'; + +export interface SaveSessionLinkArgs { + websiteId: string; + sessionId: string; + distinctId: string; + createdAt?: Date; +} + +export async function saveSessionLink(data: SaveSessionLinkArgs) { + return runQuery({ + [PRISMA]: () => relationalQuery(data), + [CLICKHOUSE]: () => clickhouseQuery(data), + }); +} + +async function relationalQuery({ + websiteId, + sessionId, + distinctId, + createdAt, +}: SaveSessionLinkArgs) { + const { writeRawQuery } = prisma; + + await writeRawQuery( + ` + insert into session_link ( + website_id, + session_id, + distinct_id, + created_at + ) + values ( + {{websiteId}}, + {{sessionId}}, + {{distinctId}}, + {{createdAt}} + ) + on conflict (website_id, distinct_id, session_id) do nothing + `, + { + websiteId, + sessionId, + distinctId: truncateString(distinctId, FIELD_LENGTH.distinctId), + createdAt, + }, + FUNCTION_NAME, + ); +} + +async function clickhouseQuery({ + websiteId, + sessionId, + distinctId, + createdAt, +}: SaveSessionLinkArgs) { + const { insert, getUTCString } = clickhouse; + const { sendMessage } = kafka; + + const message = { + website_id: websiteId, + session_id: sessionId, + distinct_id: truncateString(distinctId, FIELD_LENGTH.distinctId), + created_at: getUTCString(createdAt), + }; + + if (kafka.enabled) { + await sendMessage('session_link', [message]); + } else { + await insert('session_link', [message]); + } +} From f7b94c259bcc714d580d6c952757c41846267e69 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Thu, 16 Jul 2026 11:32:32 -0700 Subject: [PATCH 6/8] add tracking code workflow for Add website. Add linked ID to session modal. --- public/intl/messages/ar-SA.json | 1 + public/intl/messages/be-BY.json | 1 + public/intl/messages/bg-BG.json | 1 + public/intl/messages/bn-BD.json | 1 + public/intl/messages/bs-BA.json | 1 + public/intl/messages/ca-ES.json | 1 + public/intl/messages/cs-CZ.json | 1 + public/intl/messages/da-DK.json | 1 + public/intl/messages/de-CH.json | 1 + public/intl/messages/de-DE.json | 1 + public/intl/messages/el-GR.json | 1 + public/intl/messages/en-GB.json | 1 + public/intl/messages/en-US.json | 1 + public/intl/messages/es-ES.json | 1 + public/intl/messages/fa-IR.json | 1 + public/intl/messages/fi-FI.json | 1 + public/intl/messages/fo-FO.json | 1 + public/intl/messages/fr-FR.json | 1 + public/intl/messages/ga-ES.json | 1 + public/intl/messages/he-IL.json | 1 + public/intl/messages/hi-IN.json | 1 + public/intl/messages/hr-HR.json | 1 + public/intl/messages/hu-HU.json | 1 + public/intl/messages/id-ID.json | 1 + public/intl/messages/it-IT.json | 1 + public/intl/messages/ja-JP.json | 1 + public/intl/messages/km-KH.json | 1 + public/intl/messages/ko-KR.json | 1 + public/intl/messages/lt-LT.json | 1 + public/intl/messages/mn-MN.json | 1 + public/intl/messages/ms-MY.json | 1 + public/intl/messages/my-MM.json | 1 + public/intl/messages/nb-NO.json | 1 + public/intl/messages/nl-NL.json | 1 + public/intl/messages/pl-PL.json | 1 + public/intl/messages/pt-BR.json | 1 + public/intl/messages/pt-PT.json | 1 + public/intl/messages/ro-RO.json | 1 + public/intl/messages/ru-RU.json | 1 + public/intl/messages/si-LK.json | 1 + public/intl/messages/sk-SK.json | 1 + public/intl/messages/sl-SI.json | 1 + public/intl/messages/sv-SE.json | 1 + public/intl/messages/ta-IN.json | 1 + public/intl/messages/th-TH.json | 1 + public/intl/messages/tr-TR.json | 1 + public/intl/messages/uk-UA.json | 1 + public/intl/messages/ur-PK.json | 1 + public/intl/messages/uz-UZ.json | 1 + public/intl/messages/vi-VN.json | 1 + public/intl/messages/zh-CN.json | 1 + public/intl/messages/zh-TW.json | 1 + src/app/(main)/websites/WebsiteAddButton.tsx | 66 +++++++++++++++++-- src/app/(main)/websites/WebsiteAddForm.tsx | 17 +++-- .../[websiteId]/sessions/SessionInfo.tsx | 13 +++- .../settings/WebsiteTrackingCode.tsx | 4 +- .../[websiteId]/sessions/[sessionId]/route.ts | 29 +++++++- src/components/messages.ts | 1 + 58 files changed, 163 insertions(+), 19 deletions(-) diff --git a/public/intl/messages/ar-SA.json b/public/intl/messages/ar-SA.json index 493bad789..b924fb2a7 100644 --- a/public/intl/messages/ar-SA.json +++ b/public/intl/messages/ar-SA.json @@ -40,6 +40,7 @@ "campaign": "حملة", "campaigns": "حملات", "cancel": "إلغاء", + "close": "إغلاق", "change-password": "تغيير كلمة المرور", "channel": "قناة", "channels": "قنوات", diff --git a/public/intl/messages/be-BY.json b/public/intl/messages/be-BY.json index 95ec22916..c849d4aa2 100644 --- a/public/intl/messages/be-BY.json +++ b/public/intl/messages/be-BY.json @@ -40,6 +40,7 @@ "campaign": "Кампанія", "campaigns": "Кампаніі", "cancel": "Адмена", + "close": "Закрыць", "change-password": "Змяніць пароль", "channel": "Канал", "channels": "Каналы", diff --git a/public/intl/messages/bg-BG.json b/public/intl/messages/bg-BG.json index 0e48e4c6b..8d6653551 100644 --- a/public/intl/messages/bg-BG.json +++ b/public/intl/messages/bg-BG.json @@ -40,6 +40,7 @@ "campaign": "Кампания", "campaigns": "Кампании", "cancel": "Отмени", + "close": "Затвори", "change-password": "Смени парола", "channel": "Канал", "channels": "Канали", diff --git a/public/intl/messages/bn-BD.json b/public/intl/messages/bn-BD.json index b30a21887..31cc7c8d8 100644 --- a/public/intl/messages/bn-BD.json +++ b/public/intl/messages/bn-BD.json @@ -40,6 +40,7 @@ "campaign": "প্রচারণা", "campaigns": "প্রচারণা", "cancel": "বাতিল", + "close": "বন্ধ করুন", "change-password": "পাসওয়ার্ড পরিবর্তন করুন", "channel": "চ্যানেল", "channels": "চ্যানেলসমূহ", diff --git a/public/intl/messages/bs-BA.json b/public/intl/messages/bs-BA.json index 69474c7c9..719655505 100644 --- a/public/intl/messages/bs-BA.json +++ b/public/intl/messages/bs-BA.json @@ -39,6 +39,7 @@ "campaign": "Kampanja", "campaigns": "Kampanje", "cancel": "Otkaži", + "close": "Zatvori", "change-password": "Promijeni šifru", "channel": "Kanal", "channels": "Kanali", diff --git a/public/intl/messages/ca-ES.json b/public/intl/messages/ca-ES.json index c5c556ee9..ca7612100 100644 --- a/public/intl/messages/ca-ES.json +++ b/public/intl/messages/ca-ES.json @@ -39,6 +39,7 @@ "campaign": "Campanya", "campaigns": "Campanyes", "cancel": "Cancel·la", + "close": "Tanca", "change-password": "Canvia la contrasenya", "channel": "Canal", "channels": "Canals", diff --git a/public/intl/messages/cs-CZ.json b/public/intl/messages/cs-CZ.json index 9d92813d9..de6b859f3 100644 --- a/public/intl/messages/cs-CZ.json +++ b/public/intl/messages/cs-CZ.json @@ -39,6 +39,7 @@ "campaign": "Kampaň", "campaigns": "Kampaně", "cancel": "Zrušit", + "close": "Zavřít", "change-password": "Změnit heslo", "channel": "Kanál", "channels": "Kanály", diff --git a/public/intl/messages/da-DK.json b/public/intl/messages/da-DK.json index 4ba211f1a..52f3d7523 100644 --- a/public/intl/messages/da-DK.json +++ b/public/intl/messages/da-DK.json @@ -39,6 +39,7 @@ "campaign": "Kampagne", "campaigns": "Kampagner", "cancel": "Afvis", + "close": "Luk", "change-password": "Skift adgangskode", "channel": "Kanal", "channels": "Kanaler", diff --git a/public/intl/messages/de-CH.json b/public/intl/messages/de-CH.json index 634305e39..42f9389df 100644 --- a/public/intl/messages/de-CH.json +++ b/public/intl/messages/de-CH.json @@ -39,6 +39,7 @@ "campaign": "Kampagne", "campaigns": "Kampagne", "cancel": "Abbreche", + "close": "Schliessen", "change-password": "Passwort ändere", "channel": "Kanal", "channels": "Kanäle", diff --git a/public/intl/messages/de-DE.json b/public/intl/messages/de-DE.json index dfc1b3bfe..9e750a4ca 100644 --- a/public/intl/messages/de-DE.json +++ b/public/intl/messages/de-DE.json @@ -39,6 +39,7 @@ "campaign": "Kampagne", "campaigns": "Kampagnen", "cancel": "Abbrechen", + "close": "Schliessen", "change-password": "Passwort ändern", "channel": "Kanal", "channels": "Kanäle", diff --git a/public/intl/messages/el-GR.json b/public/intl/messages/el-GR.json index f7680c38a..67dfe0636 100644 --- a/public/intl/messages/el-GR.json +++ b/public/intl/messages/el-GR.json @@ -40,6 +40,7 @@ "campaign": "Καμπάνια", "campaigns": "Καμπάνιες", "cancel": "Ακύρωση", + "close": "Κλείσιμο", "change-password": "Αλλαγή κωδικού", "channel": "Κανάλι", "channels": "Κανάλια", diff --git a/public/intl/messages/en-GB.json b/public/intl/messages/en-GB.json index 905df7987..eaff629f9 100644 --- a/public/intl/messages/en-GB.json +++ b/public/intl/messages/en-GB.json @@ -39,6 +39,7 @@ "campaign": "Campaign", "campaigns": "Campaigns", "cancel": "Cancel", + "close": "Close", "change-password": "Change password", "channel": "Channel", "channels": "Channels", diff --git a/public/intl/messages/en-US.json b/public/intl/messages/en-US.json index 0bed55aa6..b8d65d9fa 100644 --- a/public/intl/messages/en-US.json +++ b/public/intl/messages/en-US.json @@ -39,6 +39,7 @@ "campaign": "Campaign", "campaigns": "Campaigns", "cancel": "Cancel", + "close": "Close", "change-password": "Change password", "channel": "Channel", "channels": "Channels", diff --git a/public/intl/messages/es-ES.json b/public/intl/messages/es-ES.json index e54439eae..45829b4af 100644 --- a/public/intl/messages/es-ES.json +++ b/public/intl/messages/es-ES.json @@ -39,6 +39,7 @@ "campaign": "Campaña", "campaigns": "Campañas", "cancel": "Cancelar", + "close": "Cerrar", "change-password": "Cambiar contraseña", "channel": "Canal", "channels": "Canales", diff --git a/public/intl/messages/fa-IR.json b/public/intl/messages/fa-IR.json index 62d280d24..ba661436a 100644 --- a/public/intl/messages/fa-IR.json +++ b/public/intl/messages/fa-IR.json @@ -40,6 +40,7 @@ "campaign": "کمپین", "campaigns": "کمپین‌ها", "cancel": "انصراف", + "close": "بستن", "change-password": "تغییر رمز", "channel": "کانال", "channels": "کانال‌ها", diff --git a/public/intl/messages/fi-FI.json b/public/intl/messages/fi-FI.json index 4c6ab8fb4..9188dc051 100644 --- a/public/intl/messages/fi-FI.json +++ b/public/intl/messages/fi-FI.json @@ -39,6 +39,7 @@ "campaign": "Kampanja", "campaigns": "Kampanjat", "cancel": "Peruuta", + "close": "Sulje", "change-password": "Vaihda salasana", "channel": "Kanava", "channels": "Kanavat", diff --git a/public/intl/messages/fo-FO.json b/public/intl/messages/fo-FO.json index 5266b3d00..df4bd5ccd 100644 --- a/public/intl/messages/fo-FO.json +++ b/public/intl/messages/fo-FO.json @@ -39,6 +39,7 @@ "campaign": "Herferð", "campaigns": "Herferðir", "cancel": "Strika", + "close": "Lat aftur", "change-password": "Skift loyniorð", "channel": "Rás", "channels": "Rásir", diff --git a/public/intl/messages/fr-FR.json b/public/intl/messages/fr-FR.json index 465d4fd72..dca620921 100644 --- a/public/intl/messages/fr-FR.json +++ b/public/intl/messages/fr-FR.json @@ -41,6 +41,7 @@ "campaign": "Campagne", "campaigns": "Campagnes", "cancel": "Annuler", + "close": "Fermer", "change-password": "Changer le mot de passe", "channel": "Canal", "channels": "Canaux", diff --git a/public/intl/messages/ga-ES.json b/public/intl/messages/ga-ES.json index f525961f5..6543fae9e 100644 --- a/public/intl/messages/ga-ES.json +++ b/public/intl/messages/ga-ES.json @@ -39,6 +39,7 @@ "campaign": "Campaña", "campaigns": "Campañas", "cancel": "Cancelar", + "close": "Pechar", "change-password": "Mudar contrasinal", "channel": "Canle", "channels": "Canles", diff --git a/public/intl/messages/he-IL.json b/public/intl/messages/he-IL.json index ff3daa0a1..5652890ce 100644 --- a/public/intl/messages/he-IL.json +++ b/public/intl/messages/he-IL.json @@ -40,6 +40,7 @@ "campaign": "מסע פרסום", "campaigns": "קמפיינים", "cancel": "ביטול", + "close": "סגור", "change-password": "שינוי סיסמה", "channel": "ערוץ", "channels": "ערוצים", diff --git a/public/intl/messages/hi-IN.json b/public/intl/messages/hi-IN.json index 8b3a9ff6e..f82a61f54 100644 --- a/public/intl/messages/hi-IN.json +++ b/public/intl/messages/hi-IN.json @@ -40,6 +40,7 @@ "campaign": "अभियान", "campaigns": "अभियान", "cancel": "रद्द करें", + "close": "बंद करें", "change-password": "पासवर्ड बदलें", "channel": "चैनल", "channels": "चैनल", diff --git a/public/intl/messages/hr-HR.json b/public/intl/messages/hr-HR.json index 0089df553..61df82a75 100644 --- a/public/intl/messages/hr-HR.json +++ b/public/intl/messages/hr-HR.json @@ -39,6 +39,7 @@ "campaign": "Kampanja", "campaigns": "Kampanje", "cancel": "Odustani", + "close": "Zatvori", "change-password": "Promijeni lozinku", "channel": "Kanal", "channels": "Kanali", diff --git a/public/intl/messages/hu-HU.json b/public/intl/messages/hu-HU.json index d8dfc9712..92211f4d4 100644 --- a/public/intl/messages/hu-HU.json +++ b/public/intl/messages/hu-HU.json @@ -39,6 +39,7 @@ "campaign": "Kampány", "campaigns": "Kampányok", "cancel": "Mégsem", + "close": "Bezár", "change-password": "Jelszó módosítása", "channel": "Csatorna", "channels": "Csatornák", diff --git a/public/intl/messages/id-ID.json b/public/intl/messages/id-ID.json index 829f54864..31990559a 100644 --- a/public/intl/messages/id-ID.json +++ b/public/intl/messages/id-ID.json @@ -39,6 +39,7 @@ "campaign": "Kampanye", "campaigns": "Kampanye", "cancel": "Batal", + "close": "Tutup", "change-password": "Ganti kata sandi", "channel": "Saluran", "channels": "Saluran", diff --git a/public/intl/messages/it-IT.json b/public/intl/messages/it-IT.json index 4f9724df1..b2b6e4f2d 100644 --- a/public/intl/messages/it-IT.json +++ b/public/intl/messages/it-IT.json @@ -39,6 +39,7 @@ "campaign": "Campagna", "campaigns": "Campagne", "cancel": "Annulla", + "close": "Chiudi", "change-password": "Modifica password", "channel": "Canale", "channels": "Canali", diff --git a/public/intl/messages/ja-JP.json b/public/intl/messages/ja-JP.json index c7c46f867..656d06266 100644 --- a/public/intl/messages/ja-JP.json +++ b/public/intl/messages/ja-JP.json @@ -40,6 +40,7 @@ "campaign": "キャンペーン", "campaigns": "キャンペーン", "cancel": "キャンセル", + "close": "閉じる", "change-password": "パスワードの変更", "channel": "チャネル", "channels": "チャンネル", diff --git a/public/intl/messages/km-KH.json b/public/intl/messages/km-KH.json index 617bd6b96..00ec515b4 100644 --- a/public/intl/messages/km-KH.json +++ b/public/intl/messages/km-KH.json @@ -40,6 +40,7 @@ "campaign": "យុទ្ធនាការ", "campaigns": "យុទ្ធនាការ", "cancel": "បោះបង់", + "close": "បិទ", "change-password": "ផ្លាស់ប្តូរពាក្យសម្ងាត់", "channel": "ឆានែល", "channels": "ឆានែល", diff --git a/public/intl/messages/ko-KR.json b/public/intl/messages/ko-KR.json index b92cccb6f..db2cae5e0 100644 --- a/public/intl/messages/ko-KR.json +++ b/public/intl/messages/ko-KR.json @@ -42,6 +42,7 @@ "campaign": "캠페인", "campaigns": "캠페인", "cancel": "취소", + "close": "닫기", "change-password": "비밀번호 변경", "channel": "채널", "channels": "채널", diff --git a/public/intl/messages/lt-LT.json b/public/intl/messages/lt-LT.json index 1940d3caf..c3d8bd4d8 100644 --- a/public/intl/messages/lt-LT.json +++ b/public/intl/messages/lt-LT.json @@ -39,6 +39,7 @@ "campaign": "Kampanija", "campaigns": "Kampanijos", "cancel": "Atšaukti", + "close": "Uždaryti", "change-password": "Pakeisti slaptažodį", "channel": "Kanalas", "channels": "Kanalai", diff --git a/public/intl/messages/mn-MN.json b/public/intl/messages/mn-MN.json index d4c7f2b28..9a9556714 100644 --- a/public/intl/messages/mn-MN.json +++ b/public/intl/messages/mn-MN.json @@ -40,6 +40,7 @@ "campaign": "Кампанит ажил", "campaigns": "Аянууд", "cancel": "Цуцлах", + "close": "Хаах", "change-password": "Нууц үг солих", "channel": "Суваг", "channels": "Суваг", diff --git a/public/intl/messages/ms-MY.json b/public/intl/messages/ms-MY.json index b14b36f43..e399ebf17 100644 --- a/public/intl/messages/ms-MY.json +++ b/public/intl/messages/ms-MY.json @@ -39,6 +39,7 @@ "campaign": "Kempen", "campaigns": "Kempen", "cancel": "Batal", + "close": "Tutup", "change-password": "Tukar kata laluan", "channel": "Saluran", "channels": "Saluran", diff --git a/public/intl/messages/my-MM.json b/public/intl/messages/my-MM.json index 97b6dd3c2..e57c23e35 100644 --- a/public/intl/messages/my-MM.json +++ b/public/intl/messages/my-MM.json @@ -40,6 +40,7 @@ "campaign": "ကမ်ပိန်း", "campaigns": "ကမ်ပိန်းများ", "cancel": "မလုပ်တော့ပါ", + "close": "ပိတ်", "change-password": "စကားဝှက် ပြောင်းမည်", "channel": "ချန်နယ်", "channels": "ချန်နယ်များ", diff --git a/public/intl/messages/nb-NO.json b/public/intl/messages/nb-NO.json index a0b01a98b..f40ac99f0 100644 --- a/public/intl/messages/nb-NO.json +++ b/public/intl/messages/nb-NO.json @@ -39,6 +39,7 @@ "campaign": "Kampanje", "campaigns": "Kampanjer", "cancel": "Avvis", + "close": "Lukk", "change-password": "Bytt passord", "channel": "Kanal", "channels": "Kanaler", diff --git a/public/intl/messages/nl-NL.json b/public/intl/messages/nl-NL.json index 39b062093..6565f0494 100644 --- a/public/intl/messages/nl-NL.json +++ b/public/intl/messages/nl-NL.json @@ -39,6 +39,7 @@ "campaign": "Campagne", "campaigns": "Campagnes", "cancel": "Annuleren", + "close": "Sluiten", "change-password": "Wachtwoord wijzigen", "channel": "Kanaal", "channels": "Kanalen", diff --git a/public/intl/messages/pl-PL.json b/public/intl/messages/pl-PL.json index 67439d40c..677891bc6 100644 --- a/public/intl/messages/pl-PL.json +++ b/public/intl/messages/pl-PL.json @@ -39,6 +39,7 @@ "campaign": "Kampania", "campaigns": "Kampanie", "cancel": "Anuluj", + "close": "Zamknij", "change-password": "Zmień hasło", "channel": "Kanał", "channels": "Kanały", diff --git a/public/intl/messages/pt-BR.json b/public/intl/messages/pt-BR.json index 990b9f8ca..cebd3b437 100644 --- a/public/intl/messages/pt-BR.json +++ b/public/intl/messages/pt-BR.json @@ -39,6 +39,7 @@ "campaign": "Campanha", "campaigns": "Campanhas", "cancel": "Cancelar", + "close": "Fechar", "change-password": "Alterar senha", "channel": "Canal", "channels": "Canais", diff --git a/public/intl/messages/pt-PT.json b/public/intl/messages/pt-PT.json index 814e4a8a0..46d7d83a2 100644 --- a/public/intl/messages/pt-PT.json +++ b/public/intl/messages/pt-PT.json @@ -39,6 +39,7 @@ "campaign": "Campanha", "campaigns": "Campanhas", "cancel": "Cancelar", + "close": "Fechar", "change-password": "Alterar senha", "channel": "Canal", "channels": "Canais", diff --git a/public/intl/messages/ro-RO.json b/public/intl/messages/ro-RO.json index 8b3de7c88..7dbea81c1 100644 --- a/public/intl/messages/ro-RO.json +++ b/public/intl/messages/ro-RO.json @@ -39,6 +39,7 @@ "campaign": "Campanie", "campaigns": "Campanii", "cancel": "Anulează", + "close": "Închide", "change-password": "Schimbare parolă", "channel": "Canal", "channels": "Canale", diff --git a/public/intl/messages/ru-RU.json b/public/intl/messages/ru-RU.json index 8b7776040..212691a49 100644 --- a/public/intl/messages/ru-RU.json +++ b/public/intl/messages/ru-RU.json @@ -41,6 +41,7 @@ "campaign": "Кампания", "campaigns": "Кампании", "cancel": "Отменить", + "close": "Закрыть", "change-password": "Изменить пароль", "channel": "Канал", "channels": "Каналы", diff --git a/public/intl/messages/si-LK.json b/public/intl/messages/si-LK.json index 57d5f37a9..5da1a216e 100644 --- a/public/intl/messages/si-LK.json +++ b/public/intl/messages/si-LK.json @@ -40,6 +40,7 @@ "campaign": "ව්‍යාපාරය", "campaigns": "ව්‍යාපාර", "cancel": "අවලංගු කරන්න", + "close": "වසන්න", "change-password": "මුරපදය වෙනස් කරන්න", "channel": "නාලිකාව", "channels": "නාලිකා", diff --git a/public/intl/messages/sk-SK.json b/public/intl/messages/sk-SK.json index 0efd8ac66..6fe246347 100644 --- a/public/intl/messages/sk-SK.json +++ b/public/intl/messages/sk-SK.json @@ -39,6 +39,7 @@ "campaign": "Kampaň", "campaigns": "Kampane", "cancel": "Zrušiť", + "close": "Zavrieť", "change-password": "Zmeniť heslo", "channel": "Kanál", "channels": "Kanály", diff --git a/public/intl/messages/sl-SI.json b/public/intl/messages/sl-SI.json index d43a37a15..93a55117f 100644 --- a/public/intl/messages/sl-SI.json +++ b/public/intl/messages/sl-SI.json @@ -39,6 +39,7 @@ "campaign": "Kampanja", "campaigns": "Kampanje", "cancel": "Prekliči", + "close": "Zapri", "change-password": "Zamenjaj geslo", "channel": "Kanal", "channels": "Kanali", diff --git a/public/intl/messages/sv-SE.json b/public/intl/messages/sv-SE.json index 47936592e..6594cf1aa 100644 --- a/public/intl/messages/sv-SE.json +++ b/public/intl/messages/sv-SE.json @@ -39,6 +39,7 @@ "campaign": "Kampanj", "campaigns": "Kampanjer", "cancel": "Avbryt", + "close": "Stäng", "change-password": "Byt lösenord", "channel": "Kanal", "channels": "Kanaler", diff --git a/public/intl/messages/ta-IN.json b/public/intl/messages/ta-IN.json index 14380e89d..d72270303 100644 --- a/public/intl/messages/ta-IN.json +++ b/public/intl/messages/ta-IN.json @@ -40,6 +40,7 @@ "campaign": "பிரச்சாரம்", "campaigns": "பிரச்சாரங்கள்", "cancel": "ரத்துசெய்", + "close": "மூடு", "change-password": "கடவுச்சொல்லை மாற்று", "channel": "சேனல்", "channels": "சேனல்கள்", diff --git a/public/intl/messages/th-TH.json b/public/intl/messages/th-TH.json index 9334629e3..0a32d7914 100644 --- a/public/intl/messages/th-TH.json +++ b/public/intl/messages/th-TH.json @@ -40,6 +40,7 @@ "campaign": "แคมเปญ", "campaigns": "แคมเปญ", "cancel": "ยกเลิก", + "close": "ปิด", "change-password": "เปลี่ยนรหัสผ่าน", "channel": "ช่องทาง", "channels": "ช่องทาง", diff --git a/public/intl/messages/tr-TR.json b/public/intl/messages/tr-TR.json index b68df7843..9c4506ce8 100644 --- a/public/intl/messages/tr-TR.json +++ b/public/intl/messages/tr-TR.json @@ -39,6 +39,7 @@ "campaign": "Kampanya", "campaigns": "Kampanyalar", "cancel": "İptal", + "close": "Kapat", "change-password": "Şifre değiştir", "channel": "Kanal", "channels": "Kanallar", diff --git a/public/intl/messages/uk-UA.json b/public/intl/messages/uk-UA.json index 467b744c5..b4bd0e0f2 100644 --- a/public/intl/messages/uk-UA.json +++ b/public/intl/messages/uk-UA.json @@ -40,6 +40,7 @@ "campaign": "Кампанія", "campaigns": "Кампанії", "cancel": "Відмінити", + "close": "Закрити", "change-password": "Змінити пароль", "channel": "Канал", "channels": "Канали", diff --git a/public/intl/messages/ur-PK.json b/public/intl/messages/ur-PK.json index 511995ba4..9a081723e 100644 --- a/public/intl/messages/ur-PK.json +++ b/public/intl/messages/ur-PK.json @@ -40,6 +40,7 @@ "campaign": "مہم", "campaigns": "مہمات", "cancel": "منسوخ", + "close": "بند کریں", "change-password": "پاس ورڈ تبدیل کریں", "channel": "چینل", "channels": "چینلز", diff --git a/public/intl/messages/uz-UZ.json b/public/intl/messages/uz-UZ.json index 134614492..ddb0473dd 100644 --- a/public/intl/messages/uz-UZ.json +++ b/public/intl/messages/uz-UZ.json @@ -39,6 +39,7 @@ "campaign": "Kampaniya", "campaigns": "Kampaniyalar", "cancel": "Bekor qilish", + "close": "Yopish", "change-password": "Parolni oʻzgartirish", "channel": "Kanal", "channels": "Kanallar", diff --git a/public/intl/messages/vi-VN.json b/public/intl/messages/vi-VN.json index 1cef1d9a9..dd21b0448 100644 --- a/public/intl/messages/vi-VN.json +++ b/public/intl/messages/vi-VN.json @@ -40,6 +40,7 @@ "campaign": "Chiến dịch", "campaigns": "Các chiến dịch", "cancel": "Hủy bỏ", + "close": "Đóng", "change-password": "Đổi mật khẩu", "channel": "Kênh", "channels": "Các kênh", diff --git a/public/intl/messages/zh-CN.json b/public/intl/messages/zh-CN.json index 5e6111f72..befc6197a 100644 --- a/public/intl/messages/zh-CN.json +++ b/public/intl/messages/zh-CN.json @@ -40,6 +40,7 @@ "campaign": "推广活动", "campaigns": "活动", "cancel": "取消", + "close": "关闭", "change-password": "修改密码", "channel": "渠道", "channels": "渠道", diff --git a/public/intl/messages/zh-TW.json b/public/intl/messages/zh-TW.json index ab8b5fd4a..bc5fda797 100644 --- a/public/intl/messages/zh-TW.json +++ b/public/intl/messages/zh-TW.json @@ -40,6 +40,7 @@ "campaign": "活動", "campaigns": "活動", "cancel": "取消", + "close": "關閉", "change-password": "更改密碼", "channel": "頻道", "channels": "頻道", diff --git a/src/app/(main)/websites/WebsiteAddButton.tsx b/src/app/(main)/websites/WebsiteAddButton.tsx index 340c6fdc0..7d26b2e3c 100644 --- a/src/app/(main)/websites/WebsiteAddButton.tsx +++ b/src/app/(main)/websites/WebsiteAddButton.tsx @@ -1,23 +1,77 @@ -import { useToast } from '@umami/react-zen'; -import { useMessages, useModified } from '@/components/hooks'; +import { Button, Column, Row, useToast } from '@umami/react-zen'; +import { useState } from 'react'; +import { IconLabel } from '@/components/common/IconLabel'; +import { useConfig, useMessages, useModified } from '@/components/hooks'; import { Plus } from '@/components/icons'; import { DialogButton } from '@/components/input/DialogButton'; +import { WebsiteTrackingCode } from './[websiteId]/settings/WebsiteTrackingCode'; import { WebsiteAddForm } from './WebsiteAddForm'; export function WebsiteAddButton({ teamId, onSave }: { teamId: string; onSave?: () => void }) { const { t, labels, messages } = useMessages(); const { toast } = useToast(); const { touch } = useModified(); + const { cloudMode } = useConfig(); + const [isOpen, setIsOpen] = useState(false); + const [createdWebsite, setCreatedWebsite] = useState<{ id: string } | null>(null); - const handleSave = async () => { + const handleSave = async (website: { id: string }) => { toast(t(messages.saved)); touch('websites'); onSave?.(); + + if (cloudMode) { + setCreatedWebsite(website); + } else { + setIsOpen(false); + } + }; + + const handleOpenChange = (open: boolean) => { + setIsOpen(open); + + if (!open) { + setCreatedWebsite(null); + } }; return ( - } label={t(labels.addWebsite)} variant="primary" width="400px"> - {({ close }) => } - + <> + + + {({ close }) => + createdWebsite ? ( + handleOpenChange(false)} /> + ) : ( + + ) + } + + + ); +} + +function TrackingCodeStep({ websiteId, onClose }: { websiteId: string; onClose: () => void }) { + const { t, labels } = useMessages(); + + return ( + + + + + + ); } diff --git a/src/app/(main)/websites/WebsiteAddForm.tsx b/src/app/(main)/websites/WebsiteAddForm.tsx index 7f28651fc..b4f98b44f 100644 --- a/src/app/(main)/websites/WebsiteAddForm.tsx +++ b/src/app/(main)/websites/WebsiteAddForm.tsx @@ -6,21 +6,24 @@ export function WebsiteAddForm({ teamId, onSave, onClose, + closeOnSave = true, }: { teamId?: string; - onSave?: () => void; + onSave?: (website: any) => void | Promise; onClose?: () => void; + closeOnSave?: boolean; }) { const { t, labels, messages } = useMessages(); const { mutateAsync, error, isPending } = useUpdateQuery('/websites', { teamId }); const handleSubmit = async (data: any) => { - await mutateAsync(data, { - onSuccess: async () => { - onSave?.(); - onClose?.(); - }, - }); + const website = await mutateAsync(data); + + await onSave?.(website); + + if (closeOnSave) { + onClose?.(); + } }; return ( diff --git a/src/app/(main)/websites/[websiteId]/sessions/SessionInfo.tsx b/src/app/(main)/websites/[websiteId]/sessions/SessionInfo.tsx index 6041bde81..39e90ca9a 100644 --- a/src/app/(main)/websites/[websiteId]/sessions/SessionInfo.tsx +++ b/src/app/(main)/websites/[websiteId]/sessions/SessionInfo.tsx @@ -4,19 +4,20 @@ import { DateDistance } from '@/components/common/DateDistance'; import { TypeIcon } from '@/components/common/TypeIcon'; import { useFormat, useLocale, useMessages, useRegionNames } from '@/components/hooks'; import { Calendar, KeyRound, Landmark, MapPin } from '@/components/icons'; +import { Network } from '@/components/svg'; export function SessionInfo({ data }) { const { locale } = useLocale(); const { t, labels } = useMessages(); const { formatValue } = useFormat(); const { getRegionName } = useRegionNames(locale); + const distinctId = data?.distinctId?.trim(); + const stitchedSessionCount = data?.stitchedSessionCount; return ( }> - - {data?.distinctId} - + {distinctId ? {distinctId} : '—'} }> @@ -53,6 +54,12 @@ export function SessionInfo({ data }) { }> {formatValue(data?.device, 'device')} + + {distinctId && stitchedSessionCount > 1 && ( + }> + {stitchedSessionCount} + + )} ); } diff --git a/src/app/(main)/websites/[websiteId]/settings/WebsiteTrackingCode.tsx b/src/app/(main)/websites/[websiteId]/settings/WebsiteTrackingCode.tsx index 7696161c9..6910aa445 100644 --- a/src/app/(main)/websites/[websiteId]/settings/WebsiteTrackingCode.tsx +++ b/src/app/(main)/websites/[websiteId]/settings/WebsiteTrackingCode.tsx @@ -6,9 +6,11 @@ const SCRIPT_NAME = 'script.js'; export function WebsiteTrackingCode({ websiteId, hostUrl, + showHeader = true, }: { websiteId: string; hostUrl?: string; + showHeader?: boolean; }) { const { t, messages, labels } = useMessages(); const config = useConfig(); @@ -32,7 +34,7 @@ export function WebsiteTrackingCode({ return ( - + {showHeader && } {t(messages.trackingCode)} getLinkedSessionIds(websiteId, distinctId)), + ); + const linkedIds = links.flatMap(group => group.map(link => link.sessionId)); + const identifiedIds = distinctIds.map(distinctId => uuid(websiteId, distinctId)); + + sessionIds = Array.from(new Set([sessionId, ...identifiedIds, ...linkedIds])); + } + + stitchedSessionCount = sessionIds.length; + } + + return json({ + ...data, + stitchedSessionCount, + }); } diff --git a/src/components/messages.ts b/src/components/messages.ts index 401284b34..90ad01f8d 100644 --- a/src/components/messages.ts +++ b/src/components/messages.ts @@ -4,6 +4,7 @@ export const labels: Record = { required: 'label.required', save: 'label.save', cancel: 'label.cancel', + close: 'label.close', continue: 'label.continue', delete: 'label.delete', leave: 'label.leave', From b47847958afeb370c459877eeffed7707878a699 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Thu, 16 Jul 2026 11:58:49 -0700 Subject: [PATCH 7/8] fix code-textarea css --- src/app/global.css | 1 + 1 file changed, 1 insertion(+) diff --git a/src/app/global.css b/src/app/global.css index 189a464e0..33d94711c 100644 --- a/src/app/global.css +++ b/src/app/global.css @@ -65,6 +65,7 @@ select:is(:-webkit-autofill, :autofill):focus { /* Code snippet textareas */ .code-textarea textarea { min-height: 100px; + padding-right: 36px; } /* rrweb-player overrides */ From 8004afe63d598a09b5d86166f1c568dd39855339 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Fri, 17 Jul 2026 10:22:37 -0700 Subject: [PATCH 8/8] Punycode support. Closes #2170 --- package.json | 1 + pnpm-lock.yaml | 3 +++ .../(main)/admin/websites/AdminWebsitesTable.tsx | 3 ++- src/app/(main)/websites/WebsitesTable.tsx | 9 +++++++-- .../[websiteId]/settings/WebsiteSettingsHeader.tsx | 7 ++++++- src/components/metrics/MetricLabel.tsx | 3 ++- src/lib/format.test.ts | 6 ++++++ src/lib/format.ts | 13 +++++++++++++ 8 files changed, 40 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index e9a286bca..0d701db8b 100644 --- a/package.json +++ b/package.json @@ -100,6 +100,7 @@ "pg": "^8.22.0", "prisma": "^7.8.0", "prop-types": "^15.8.1", + "punycode": "^2.3.1", "react": "^19.2.7", "react-aria-components": "^1.19.0", "react-dom": "^19.2.7", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a52e43b2e..da88a5ce2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -149,6 +149,9 @@ importers: prop-types: specifier: ^15.8.1 version: 15.8.1 + punycode: + specifier: ^2.3.1 + version: 2.3.1 react: specifier: ^19.2.7 version: 19.2.7 diff --git a/src/app/(main)/admin/websites/AdminWebsitesTable.tsx b/src/app/(main)/admin/websites/AdminWebsitesTable.tsx index 12698e730..f33b4c35d 100644 --- a/src/app/(main)/admin/websites/AdminWebsitesTable.tsx +++ b/src/app/(main)/admin/websites/AdminWebsitesTable.tsx @@ -7,6 +7,7 @@ import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages } from '@/components/hooks'; import { Edit, Trash, Users } from '@/components/icons'; import { MenuButton } from '@/components/input/MenuButton'; +import { decodePunycodeDomain } from '@/lib/format'; export function AdminWebsitesTable({ data = [], ...props }: { data: any[] }) { const { t, labels } = useMessages(); @@ -23,7 +24,7 @@ export function AdminWebsitesTable({ data = [], ...props }: { data: any[] }) { )} }> - {(row: any) => {row.domain}} + {(row: any) => {decodePunycodeDomain(row.domain)}} {(row: any) => { diff --git a/src/app/(main)/websites/WebsitesTable.tsx b/src/app/(main)/websites/WebsitesTable.tsx index e6716f9e4..4b3e13ce3 100644 --- a/src/app/(main)/websites/WebsitesTable.tsx +++ b/src/app/(main)/websites/WebsitesTable.tsx @@ -5,6 +5,7 @@ import { LinkButton } from '@/components/common/LinkButton'; import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages, useNavigation, useWebsiteListChartsQuery } from '@/components/hooks'; import { SquarePen } from '@/components/icons'; +import { decodePunycodeDomain } from '@/lib/format'; import { WebsiteSparkline } from './WebsiteSparkline'; export interface WebsitesTableProps extends DataTableProps { @@ -42,8 +43,12 @@ export function WebsitesTable({ style={{ minWidth: 0 }} > {(row: any) => ( - - {row.domain} + + {decodePunycodeDomain(row.domain)} )} diff --git a/src/app/(main)/websites/[websiteId]/settings/WebsiteSettingsHeader.tsx b/src/app/(main)/websites/[websiteId]/settings/WebsiteSettingsHeader.tsx index b96d3c6e7..16a81edff 100644 --- a/src/app/(main)/websites/[websiteId]/settings/WebsiteSettingsHeader.tsx +++ b/src/app/(main)/websites/[websiteId]/settings/WebsiteSettingsHeader.tsx @@ -4,6 +4,7 @@ import Link from '@/components/common/Link'; import { PageHeader } from '@/components/common/PageHeader'; import { useMessages, useNavigation, useWebsite } from '@/components/hooks'; import { ArrowLeft, Globe } from '@/components/icons'; +import { decodePunycodeDomain } from '@/lib/format'; export function WebsiteSettingsHeader() { const website = useWebsite(); @@ -17,7 +18,11 @@ export function WebsiteSettingsHeader() { } label={t(labels.website)} /> - } /> + } + /> ); } diff --git a/src/components/metrics/MetricLabel.tsx b/src/components/metrics/MetricLabel.tsx index 21618b90d..c0b9857d5 100644 --- a/src/components/metrics/MetricLabel.tsx +++ b/src/components/metrics/MetricLabel.tsx @@ -10,6 +10,7 @@ import { useRegionNames, } from '@/components/hooks'; import { GROUPED_DOMAINS } from '@/lib/constants'; +import { decodePunycodeDomain } from '@/lib/format'; export interface MetricLabelProps { type: string; @@ -113,7 +114,7 @@ export function MetricLabel({ type, data }: MetricLabelProps) { type="referrer" value={label} externalUrl={`https://${label}`} - label={!label && t(labels.none)} + label={!label ? t(labels.none) : decodePunycodeDomain(label)} icon={} /> ); diff --git a/src/lib/format.test.ts b/src/lib/format.test.ts index 4f9b192a2..b70b5f2e1 100644 --- a/src/lib/format.test.ts +++ b/src/lib/format.test.ts @@ -42,3 +42,9 @@ test('truncateString', () => { expect(format.truncateString('hello', 3)).toBe('hel'); expect(format.truncateString(undefined, 3)).toBeUndefined(); }); + +test('decodePunycodeDomain', () => { + expect(format.decodePunycodeDomain('xn--bcher-kva.example')).toBe('bücher.example'); + expect(format.decodePunycodeDomain('example.com')).toBe('example.com'); + expect(format.decodePunycodeDomain(undefined)).toBeUndefined(); +}); diff --git a/src/lib/format.ts b/src/lib/format.ts index a92fb4423..07110d935 100644 --- a/src/lib/format.ts +++ b/src/lib/format.ts @@ -1,3 +1,4 @@ +import { toUnicode } from 'punycode'; import { DEFAULT_CURRENCY } from './constants'; export function parseTime(val: number) { @@ -119,6 +120,18 @@ export function formatLongCurrency(value: number, currency: string, locale = 'en return formatCurrency(n, currency, locale); } +export function decodePunycodeDomain(domain?: string | null) { + if (!domain) { + return domain; + } + + try { + return toUnicode(domain); + } catch { + return domain; + } +} + export function truncateString( value: T, maxLength: number,