session activity identify stitching
This commit is contained in:
1 parent
8a75208d5b
commit
7afc4ccf6b
15 files changed
+374
-23
No files matched your search
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user