Add sparklines to Website, Pixel, Link tables
This commit is contained in:
1 parent
1fb565bc27
commit
86b35475c0
11 files changed
+625
-20
No files matched your search
@@ -1,9 +1,11 @@
|
||||
import { DataColumn, DataTable, type DataTableProps, Row } from '@umami/react-zen';
|
||||
import { useMemo } from 'react';
|
||||
import { WebsiteSparkline } from '@/app/(main)/websites/WebsiteSparkline';
|
||||
import { DateDistance } from '@/components/common/DateDistance';
|
||||
import { ExternalLink } from '@/components/common/ExternalLink';
|
||||
import Link from '@/components/common/Link';
|
||||
import { SortableLabel } from '@/components/common/SortableLabel';
|
||||
import { useMessages, useNavigation, useSlug } from '@/components/hooks';
|
||||
import { useLinkListChartsQuery, useMessages, useNavigation, useSlug } from '@/components/hooks';
|
||||
import { LinkDeleteButton } from './LinkDeleteButton';
|
||||
import { LinkEditButton } from './LinkEditButton';
|
||||
|
||||
@@ -11,13 +13,17 @@ export interface LinksTableProps extends DataTableProps {
|
||||
showActions?: boolean;
|
||||
}
|
||||
|
||||
export function LinksTable({ showActions, ...props }: LinksTableProps) {
|
||||
export function LinksTable({ showActions, data = [], ...props }: LinksTableProps & { data?: any[] }) {
|
||||
const { t, labels } = useMessages();
|
||||
const { websiteId, renderUrl } = useNavigation();
|
||||
const { getSlugUrl } = useSlug('link');
|
||||
const linkIds = useMemo(() => data.map(row => row.id), [data]);
|
||||
const chartsQuery = useLinkListChartsQuery(linkIds);
|
||||
const charts = chartsQuery.data?.data || {};
|
||||
const isChartLoading = chartsQuery.isLoading && !chartsQuery.data;
|
||||
|
||||
return (
|
||||
<DataTable {...props}>
|
||||
<DataTable {...props} data={data}>
|
||||
<DataColumn id="name" label={<SortableLabel label={t(labels.name)} sortKey="name" />}>
|
||||
{({ id, name }: any) => {
|
||||
return <Link href={renderUrl(`/links/${id}`)}>{name}</Link>;
|
||||
@@ -26,7 +32,6 @@ export function LinksTable({ showActions, ...props }: LinksTableProps) {
|
||||
<DataColumn
|
||||
id="slug"
|
||||
label={<SortableLabel label={t(labels.link)} sortKey="slug" />}
|
||||
width="25%"
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
{({ slug }: any) => {
|
||||
@@ -37,27 +42,43 @@ export function LinksTable({ showActions, ...props }: LinksTableProps) {
|
||||
<DataColumn
|
||||
id="url"
|
||||
label={<SortableLabel label={t(labels.destinationUrl)} sortKey="url" />}
|
||||
width="30%"
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
{({ url }: any) => {
|
||||
return <ExternalLink href={url}>{url}</ExternalLink>;
|
||||
}}
|
||||
</DataColumn>
|
||||
<DataColumn
|
||||
id="chart"
|
||||
label={<span style={{ whiteSpace: 'normal' }}>{`${t(labels.visitors)} (7d)`}</span>}
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
{(row: any) => {
|
||||
const chart = charts[row.id];
|
||||
|
||||
return (
|
||||
<WebsiteSparkline
|
||||
values={chart?.values}
|
||||
total={chart?.total}
|
||||
isLoading={isChartLoading}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</DataColumn>
|
||||
<DataColumn
|
||||
id="created"
|
||||
label={
|
||||
<SortableLabel label={t(labels.created)} sortKey="createdAt" defaultDirection="desc" />
|
||||
}
|
||||
width="200px"
|
||||
width="180px"
|
||||
>
|
||||
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
|
||||
</DataColumn>
|
||||
{showActions && (
|
||||
<DataColumn id="action" align="end" width="100px">
|
||||
<DataColumn id="action" align="end" width="72px">
|
||||
{({ id, name }: any) => {
|
||||
return (
|
||||
<Row>
|
||||
<Row gap="2">
|
||||
<LinkEditButton linkId={id} />
|
||||
<LinkDeleteButton linkId={id} websiteId={websiteId} name={name} />
|
||||
</Row>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { DataColumn, DataTable, type DataTableProps, Row } from '@umami/react-zen';
|
||||
import { useMemo } from 'react';
|
||||
import { WebsiteSparkline } from '@/app/(main)/websites/WebsiteSparkline';
|
||||
import { DateDistance } from '@/components/common/DateDistance';
|
||||
import { ExternalLink } from '@/components/common/ExternalLink';
|
||||
import Link from '@/components/common/Link';
|
||||
import { SortableLabel } from '@/components/common/SortableLabel';
|
||||
import { useMessages, useNavigation, useSlug } from '@/components/hooks';
|
||||
import { useMessages, useNavigation, usePixelListChartsQuery, useSlug } from '@/components/hooks';
|
||||
import { PixelDeleteButton } from './PixelDeleteButton';
|
||||
import { PixelEditButton } from './PixelEditButton';
|
||||
|
||||
@@ -11,13 +13,21 @@ export interface PixelsTableProps extends DataTableProps {
|
||||
showActions?: boolean;
|
||||
}
|
||||
|
||||
export function PixelsTable({ showActions, ...props }: PixelsTableProps) {
|
||||
export function PixelsTable({
|
||||
showActions,
|
||||
data = [],
|
||||
...props
|
||||
}: PixelsTableProps & { data?: any[] }) {
|
||||
const { t, labels } = useMessages();
|
||||
const { renderUrl } = useNavigation();
|
||||
const { getSlugUrl } = useSlug('pixel');
|
||||
const pixelIds = useMemo(() => data.map(row => row.id), [data]);
|
||||
const chartsQuery = usePixelListChartsQuery(pixelIds);
|
||||
const charts = chartsQuery.data?.data || {};
|
||||
const isChartLoading = chartsQuery.isLoading && !chartsQuery.data;
|
||||
|
||||
return (
|
||||
<DataTable {...props}>
|
||||
<DataTable {...props} data={data}>
|
||||
<DataColumn id="name" label={<SortableLabel label={t(labels.name)} sortKey="name" />}>
|
||||
{({ id, name }: any) => {
|
||||
return <Link href={renderUrl(`/pixels/${id}`)}>{name}</Link>;
|
||||
@@ -33,21 +43,39 @@ export function PixelsTable({ showActions, ...props }: PixelsTableProps) {
|
||||
);
|
||||
}}
|
||||
</DataColumn>
|
||||
<DataColumn
|
||||
id="chart"
|
||||
label={<span style={{ whiteSpace: 'normal' }}>{`${t(labels.visitors)} (7d)`}</span>}
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
{(row: any) => {
|
||||
const chart = charts[row.id];
|
||||
|
||||
return (
|
||||
<WebsiteSparkline
|
||||
values={chart?.values}
|
||||
total={chart?.total}
|
||||
isLoading={isChartLoading}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</DataColumn>
|
||||
<DataColumn
|
||||
id="created"
|
||||
label={
|
||||
<SortableLabel label={t(labels.created)} sortKey="createdAt" defaultDirection="desc" />
|
||||
}
|
||||
width="180px"
|
||||
>
|
||||
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
|
||||
</DataColumn>
|
||||
{showActions && (
|
||||
<DataColumn id="action" align="end" width="100px">
|
||||
<DataColumn id="action" align="end" width="72px">
|
||||
{(row: any) => {
|
||||
const { id, name } = row;
|
||||
|
||||
return (
|
||||
<Row>
|
||||
<Row gap="2">
|
||||
<PixelEditButton pixelId={id} />
|
||||
<PixelDeleteButton pixelId={id} name={name} />
|
||||
</Row>
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useTheme } from '@umami/react-zen';
|
||||
import { useMemo } from 'react';
|
||||
import { useMessages } from '@/components/hooks';
|
||||
import { getThemeColors } from '@/lib/colors';
|
||||
|
||||
export function WebsiteSparkline({
|
||||
values = [],
|
||||
total = 0,
|
||||
isLoading = false,
|
||||
}: {
|
||||
values?: number[];
|
||||
total?: number;
|
||||
isLoading?: boolean;
|
||||
}) {
|
||||
const { theme } = useTheme();
|
||||
const { t, labels } = useMessages();
|
||||
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
|
||||
const tooltipLabel = `${total.toLocaleString()} ${t(labels.visitors).toLocaleLowerCase()}`;
|
||||
|
||||
const points = useMemo(() => {
|
||||
if (!values.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const width = 96;
|
||||
const height = 24;
|
||||
const padding = 2;
|
||||
const max = Math.max(...values, 0);
|
||||
const min = Math.min(...values, 0);
|
||||
const range = max - min || 1;
|
||||
|
||||
return values
|
||||
.map((value, index) => {
|
||||
const x = values.length === 1 ? width / 2 : (index / (values.length - 1)) * width;
|
||||
const y =
|
||||
height - padding - ((value - min) / range) * Math.max(height - padding * 2, 1);
|
||||
|
||||
return `${x},${y}`;
|
||||
})
|
||||
.join(' ');
|
||||
}, [values]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
maxWidth: 88,
|
||||
height: 24,
|
||||
borderRadius: 9999,
|
||||
background: 'var(--surface-sunken)',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ width: '100%', maxWidth: 88, cursor: 'default' }} title={tooltipLabel}>
|
||||
<svg
|
||||
width="100%"
|
||||
height="24"
|
||||
viewBox="0 0 96 24"
|
||||
preserveAspectRatio="none"
|
||||
role="img"
|
||||
aria-label={tooltipLabel}
|
||||
style={{ display: 'block' }}
|
||||
>
|
||||
<polyline
|
||||
points={points}
|
||||
fill="none"
|
||||
stroke={colors.chart.visitors.borderColor}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { DataColumn, DataTable, type DataTableProps, Icon, Text } from '@umami/react-zen';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useMemo, type ReactNode } from 'react';
|
||||
import { DateDistance } from '@/components/common/DateDistance';
|
||||
import { LinkButton } from '@/components/common/LinkButton';
|
||||
import { SortableLabel } from '@/components/common/SortableLabel';
|
||||
import { useMessages, useNavigation } from '@/components/hooks';
|
||||
import { useMessages, useNavigation, useWebsiteListChartsQuery } from '@/components/hooks';
|
||||
import { SquarePen } from '@/components/icons';
|
||||
import { WebsiteSparkline } from './WebsiteSparkline';
|
||||
|
||||
export interface WebsitesTableProps extends DataTableProps {
|
||||
showActions?: boolean;
|
||||
@@ -13,13 +14,26 @@ export interface WebsitesTableProps extends DataTableProps {
|
||||
renderLink?: (row: any) => ReactNode;
|
||||
}
|
||||
|
||||
export function WebsitesTable({ showActions, renderLink, ...props }: WebsitesTableProps) {
|
||||
export function WebsitesTable({
|
||||
showActions,
|
||||
renderLink,
|
||||
data = [],
|
||||
...props
|
||||
}: WebsitesTableProps & { data?: any[] }) {
|
||||
const { t, labels } = useMessages();
|
||||
const { renderUrl } = useNavigation();
|
||||
const websiteIds = useMemo(() => data.map(row => row.id), [data]);
|
||||
const chartsQuery = useWebsiteListChartsQuery(websiteIds);
|
||||
const charts = chartsQuery.data?.data || {};
|
||||
const isChartLoading = chartsQuery.isLoading && !chartsQuery.data;
|
||||
|
||||
return (
|
||||
<DataTable {...props}>
|
||||
<DataColumn id="name" label={<SortableLabel label={t(labels.name)} sortKey="name" />}>
|
||||
<DataTable {...props} data={data}>
|
||||
<DataColumn
|
||||
id="name"
|
||||
label={<SortableLabel label={t(labels.name)} sortKey="name" />}
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
{renderLink}
|
||||
</DataColumn>
|
||||
<DataColumn
|
||||
@@ -33,17 +47,34 @@ export function WebsitesTable({ showActions, renderLink, ...props }: WebsitesTab
|
||||
</Text>
|
||||
)}
|
||||
</DataColumn>
|
||||
<DataColumn
|
||||
id="chart"
|
||||
label={<span style={{ whiteSpace: 'normal' }}>{`${t(labels.visitors)} (7d)`}</span>}
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
{(row: any) => {
|
||||
const chart = charts[row.id];
|
||||
|
||||
return (
|
||||
<WebsiteSparkline
|
||||
values={chart?.values}
|
||||
total={chart?.total}
|
||||
isLoading={isChartLoading}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</DataColumn>
|
||||
<DataColumn
|
||||
id="created"
|
||||
label={
|
||||
<SortableLabel label={t(labels.created)} sortKey="createdAt" defaultDirection="desc" />
|
||||
}
|
||||
width="200px"
|
||||
width="180px"
|
||||
>
|
||||
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
|
||||
</DataColumn>
|
||||
{showActions && (
|
||||
<DataColumn id="action" label=" " align="end" width="60px">
|
||||
<DataColumn id="action" label=" " align="end" width="48px">
|
||||
{(row: any) => {
|
||||
const websiteId = row.id;
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from 'zod';
|
||||
import { EVENT_TYPE } from '@/lib/constants';
|
||||
import { parseDateRange } from '@/lib/date';
|
||||
import { parseRequest } from '@/lib/request';
|
||||
import { json } from '@/lib/response';
|
||||
import { timezoneParam } from '@/lib/schema';
|
||||
import { canViewLink } from '@/permissions';
|
||||
import { getWebsiteListCharts } from '@/queries/sql';
|
||||
|
||||
const schema = z.object({
|
||||
ids: z
|
||||
.string()
|
||||
.transform(value => value.split(',').map(item => item.trim()).filter(Boolean))
|
||||
.pipe(z.array(z.uuid()).min(1).max(20)),
|
||||
startAt: z.coerce.number().int().optional(),
|
||||
endAt: z.coerce.number().int().optional(),
|
||||
timezone: timezoneParam.optional(),
|
||||
});
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { auth, query, error } = await parseRequest(request, schema);
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const timezone = query.timezone || 'UTC';
|
||||
const defaultRange = parseDateRange('7day', undefined, undefined, timezone);
|
||||
const hasDateRange = query.startAt != null && query.endAt != null;
|
||||
const startDate = hasDateRange ? new Date(query.startAt) : defaultRange.startDate;
|
||||
const endDate = hasDateRange ? new Date(query.endAt) : defaultRange.endDate;
|
||||
|
||||
const linkIds = (
|
||||
await Promise.all(
|
||||
query.ids.map(async (linkId: string) => ((await canViewLink(auth, linkId)) ? linkId : null)),
|
||||
)
|
||||
).filter(Boolean);
|
||||
|
||||
const data = await getWebsiteListCharts(linkIds, {
|
||||
startDate,
|
||||
endDate,
|
||||
timezone,
|
||||
eventType: EVENT_TYPE.linkEvent,
|
||||
});
|
||||
|
||||
return json({ data });
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { z } from 'zod';
|
||||
import { EVENT_TYPE } from '@/lib/constants';
|
||||
import { parseDateRange } from '@/lib/date';
|
||||
import { parseRequest } from '@/lib/request';
|
||||
import { json } from '@/lib/response';
|
||||
import { timezoneParam } from '@/lib/schema';
|
||||
import { canViewPixel } from '@/permissions';
|
||||
import { getWebsiteListCharts } from '@/queries/sql';
|
||||
|
||||
const schema = z.object({
|
||||
ids: z
|
||||
.string()
|
||||
.transform(value => value.split(',').map(item => item.trim()).filter(Boolean))
|
||||
.pipe(z.array(z.uuid()).min(1).max(20)),
|
||||
startAt: z.coerce.number().int().optional(),
|
||||
endAt: z.coerce.number().int().optional(),
|
||||
timezone: timezoneParam.optional(),
|
||||
});
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { auth, query, error } = await parseRequest(request, schema);
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const timezone = query.timezone || 'UTC';
|
||||
const defaultRange = parseDateRange('7day', undefined, undefined, timezone);
|
||||
const hasDateRange = query.startAt != null && query.endAt != null;
|
||||
const startDate = hasDateRange ? new Date(query.startAt) : defaultRange.startDate;
|
||||
const endDate = hasDateRange ? new Date(query.endAt) : defaultRange.endDate;
|
||||
|
||||
const pixelIds = (
|
||||
await Promise.all(
|
||||
query.ids.map(async (pixelId: string) =>
|
||||
(await canViewPixel(auth, pixelId)) ? pixelId : null,
|
||||
),
|
||||
)
|
||||
).filter(Boolean);
|
||||
|
||||
const data = await getWebsiteListCharts(pixelIds, {
|
||||
startDate,
|
||||
endDate,
|
||||
timezone,
|
||||
eventType: EVENT_TYPE.pixelEvent,
|
||||
});
|
||||
|
||||
return json({ data });
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from 'zod';
|
||||
import { parseDateRange } from '@/lib/date';
|
||||
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({
|
||||
ids: z
|
||||
.string()
|
||||
.transform(value => value.split(',').map(item => item.trim()).filter(Boolean))
|
||||
.pipe(z.array(z.uuid()).min(1).max(20)),
|
||||
startAt: z.coerce.number().int().optional(),
|
||||
endAt: z.coerce.number().int().optional(),
|
||||
timezone: timezoneParam.optional(),
|
||||
});
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { auth, query, error } = await parseRequest(request, schema);
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const timezone = query.timezone || 'UTC';
|
||||
const defaultRange = parseDateRange('7day', undefined, undefined, timezone);
|
||||
const hasDateRange = query.startAt != null && query.endAt != null;
|
||||
const startDate = hasDateRange ? new Date(query.startAt) : defaultRange.startDate;
|
||||
const endDate = hasDateRange ? new Date(query.endAt) : defaultRange.endDate;
|
||||
|
||||
const websiteIds = (
|
||||
await Promise.all(
|
||||
query.ids.map(async (websiteId: string) =>
|
||||
(await canViewWebsite(auth, websiteId)) ? websiteId : null,
|
||||
),
|
||||
)
|
||||
).filter(Boolean);
|
||||
|
||||
const data = await getWebsiteListCharts(websiteIds, {
|
||||
startDate,
|
||||
endDate,
|
||||
timezone,
|
||||
});
|
||||
|
||||
return json({ data });
|
||||
}
|
||||
@@ -70,6 +70,7 @@ export * from './queries/useWebsiteEventsSeriesQuery';
|
||||
export * from './queries/useWebsiteExpandedMetricsQuery';
|
||||
export * from './queries/useWebsiteMetricsQuery';
|
||||
export * from './queries/useWebsitePageviewsQuery';
|
||||
export * from './queries/useWebsiteListChartsQuery';
|
||||
export * from './queries/useWebsiteQuery';
|
||||
export * from './queries/useWebsiteSegmentQuery';
|
||||
export * from './queries/useWebsiteSegmentsQuery';
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useMemo } from 'react';
|
||||
import type { WebsiteListChartData } from '@/queries/sql/getWebsiteListCharts';
|
||||
import { useApi } from '../useApi';
|
||||
import { useTimezone } from '../useTimezone';
|
||||
|
||||
export interface WebsiteListChartsResponse {
|
||||
data: Record<string, WebsiteListChartData>;
|
||||
}
|
||||
|
||||
function useListChartsQuery(queryKey: string, path: string, idsInput: string[]) {
|
||||
const { get, useQuery } = useApi();
|
||||
const { timezone, canonicalizeTimezone } = useTimezone();
|
||||
|
||||
const ids = useMemo(
|
||||
() => Array.from(new Set(idsInput.map(id => id?.trim()).filter(Boolean))),
|
||||
[idsInput],
|
||||
);
|
||||
const resolvedTimezone = canonicalizeTimezone(timezone);
|
||||
|
||||
return useQuery<WebsiteListChartsResponse>({
|
||||
queryKey: [queryKey, { ids, timezone: resolvedTimezone }],
|
||||
queryFn: () =>
|
||||
get(path, {
|
||||
ids: ids.join(','),
|
||||
timezone: resolvedTimezone,
|
||||
}),
|
||||
enabled: ids.length > 0,
|
||||
});
|
||||
}
|
||||
|
||||
export function useWebsiteListChartsQuery(websiteIds: string[]) {
|
||||
return useListChartsQuery('websites:list:charts', '/websites/charts', websiteIds);
|
||||
}
|
||||
|
||||
export function useLinkListChartsQuery(linkIds: string[]) {
|
||||
return useListChartsQuery('links:list:charts', '/links/charts', linkIds);
|
||||
}
|
||||
|
||||
export function usePixelListChartsQuery(pixelIds: string[]) {
|
||||
return useListChartsQuery('pixels:list:charts', '/pixels/charts', pixelIds);
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import { addHours } from 'date-fns';
|
||||
import { formatInTimeZone } from 'date-fns-tz';
|
||||
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 = 'getWebsiteListCharts';
|
||||
const DEFAULT_TIMEZONE = 'UTC';
|
||||
const BUCKET_HOURS = 12;
|
||||
|
||||
interface WebsiteListChartPoint {
|
||||
websiteId: string;
|
||||
x: string;
|
||||
y: number;
|
||||
}
|
||||
|
||||
interface WebsiteListChartTotal {
|
||||
websiteId: string;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface WebsiteListChartData {
|
||||
values: number[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export async function getWebsiteListCharts(
|
||||
websiteIds: string[],
|
||||
{
|
||||
startDate,
|
||||
endDate,
|
||||
timezone = DEFAULT_TIMEZONE,
|
||||
eventType,
|
||||
}: {
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
timezone?: string;
|
||||
eventType?: number;
|
||||
},
|
||||
): Promise<Record<string, WebsiteListChartData>> {
|
||||
if (!websiteIds.length) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return runQuery({
|
||||
[PRISMA]: async () => {
|
||||
const [points, totals] = await Promise.all([
|
||||
relationalQuery(websiteIds, startDate, endDate, timezone, eventType),
|
||||
relationalTotalsQuery(websiteIds, startDate, endDate, eventType),
|
||||
]);
|
||||
|
||||
return formatResults({ points, totals, websiteIds, startDate, endDate, timezone });
|
||||
},
|
||||
[CLICKHOUSE]: async () => {
|
||||
const [points, totals] = await Promise.all([
|
||||
clickhouseQuery(websiteIds, startDate, endDate, timezone, eventType),
|
||||
clickhouseTotalsQuery(websiteIds, startDate, endDate, eventType),
|
||||
]);
|
||||
|
||||
return formatResults({ points, totals, websiteIds, startDate, endDate, timezone });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function relationalQuery(
|
||||
websiteIds: string[],
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
timezone: string,
|
||||
eventType?: number,
|
||||
): Promise<WebsiteListChartPoint[]> {
|
||||
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})`;
|
||||
const bucketSql =
|
||||
timezone.toLowerCase() === 'utc'
|
||||
? `
|
||||
to_char(
|
||||
date_trunc('day', website_event.created_at)
|
||||
+ floor(extract(hour from website_event.created_at) / ${BUCKET_HOURS}) * interval '${BUCKET_HOURS} hour',
|
||||
'YYYY-MM-DD HH24:00:00'
|
||||
)
|
||||
`
|
||||
: `
|
||||
to_char(
|
||||
date_trunc('day', website_event.created_at at time zone '${timezone}')
|
||||
+ floor(extract(hour from website_event.created_at at time zone '${timezone}') / ${BUCKET_HOURS}) * interval '${BUCKET_HOURS} hour',
|
||||
'YYYY-MM-DD HH24:00:00'
|
||||
)
|
||||
`;
|
||||
|
||||
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
|
||||
order by 1, 2
|
||||
`,
|
||||
{ websiteIds, startDate, endDate },
|
||||
FUNCTION_NAME,
|
||||
);
|
||||
}
|
||||
|
||||
async function relationalTotalsQuery(
|
||||
websiteIds: string[],
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
eventType?: number,
|
||||
): Promise<WebsiteListChartTotal[]> {
|
||||
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,
|
||||
endDate: Date,
|
||||
timezone: string,
|
||||
eventType?: number,
|
||||
): Promise<WebsiteListChartPoint[]> {
|
||||
const { rawQuery } = clickhouse;
|
||||
const eventTypeQuery =
|
||||
eventType != null
|
||||
? `and event_type = ${eventType}`
|
||||
: `and event_type NOT IN (${EVENT_TYPE.customEvent}, ${EVENT_TYPE.performance})`;
|
||||
const localTime = `toTimeZone(website_event.created_at, '${timezone}')`;
|
||||
const bucketSql = `
|
||||
formatDateTime(
|
||||
toStartOfDay(${localTime}) + toIntervalHour(intDiv(toHour(${localTime}), ${BUCKET_HOURS}) * ${BUCKET_HOURS}),
|
||||
'%Y-%m-%d %H:00:00'
|
||||
)
|
||||
`;
|
||||
|
||||
return rawQuery(
|
||||
`
|
||||
select
|
||||
website_id as websiteId,
|
||||
${bucketSql} as x,
|
||||
uniq(session_id) as y
|
||||
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, x
|
||||
order by websiteId, x
|
||||
`,
|
||||
{ websiteIds, startDate, endDate },
|
||||
FUNCTION_NAME,
|
||||
);
|
||||
}
|
||||
|
||||
async function clickhouseTotalsQuery(
|
||||
websiteIds: string[],
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
eventType?: number,
|
||||
): Promise<WebsiteListChartTotal[]> {
|
||||
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;
|
||||
timezone: string;
|
||||
},
|
||||
) {
|
||||
const buckets: string[] = [];
|
||||
|
||||
for (
|
||||
let current = new Date(startDate);
|
||||
current <= endDate;
|
||||
current = addHours(current, BUCKET_HOURS)
|
||||
) {
|
||||
buckets.push(formatInTimeZone(current, timezone, 'yyyy-MM-dd HH:00:00'));
|
||||
}
|
||||
|
||||
const bucketIndex = new Map(buckets.map((bucket, index) => [bucket, index]));
|
||||
const charts = websiteIds.reduce<Record<string, WebsiteListChartData>>((result, websiteId) => {
|
||||
result[websiteId] = {
|
||||
values: Array.from({ length: buckets.length }, () => 0),
|
||||
total: 0,
|
||||
};
|
||||
return result;
|
||||
}, {});
|
||||
|
||||
points.forEach(({ websiteId, x, y }) => {
|
||||
const index = bucketIndex.get(String(x).slice(0, 19));
|
||||
|
||||
if (index !== undefined && charts[websiteId]) {
|
||||
charts[websiteId].values[index] = Number(y);
|
||||
}
|
||||
});
|
||||
|
||||
totals.forEach(({ websiteId, total }) => {
|
||||
if (charts[websiteId]) {
|
||||
charts[websiteId].total = Number(total);
|
||||
}
|
||||
});
|
||||
|
||||
return charts;
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export * from './getChannelExpandedMetrics';
|
||||
export * from './getChannelMetrics';
|
||||
export * from './getRealtimeActivity';
|
||||
export * from './getRealtimeData';
|
||||
export * from './getWebsiteListCharts';
|
||||
export * from './getValues';
|
||||
export * from './getWebsiteDateRange';
|
||||
export * from './getWebsiteStats';
|
||||
|
||||
Reference in new issue
Block a user