Event data properties refactor and design

This commit is contained in:
Francis Cao committed 2026-04-23 11:15:59 -07:00
1 parent 93ed3cb89f
commit be6154cb68
22 files changed
+1211 -125

No files matched your search

@@ -0,0 +1,112 @@
'use client';
import { Column } from '@umami/react-zen';
import { useTheme } from '@umami/react-zen';
import { useCallback, useMemo } from 'react';
import { BarChart } from '@/components/charts/BarChart';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import {
useDateRange,
useEventDataNumericSeriesQuery,
useLocale,
useMessages,
useTimezone,
} from '@/components/hooks';
import { renderDateLabels } from '@/lib/charts';
import { getThemeColors } from '@/lib/colors';
import { generateTimeSeries } from '@/lib/date';
export function EventDataNumericChart({
websiteId,
eventName,
propertyName,
}: {
websiteId: string;
eventName: string;
propertyName: string;
}) {
const { t, labels } = useMessages();
const { theme } = useTheme();
const { timezone } = useTimezone();
const { dateRange: { startDate, endDate, unit } } = useDateRange({ timezone });
const { locale, dateLocale } = useLocale();
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
const sumQuery = useEventDataNumericSeriesQuery(
websiteId,
eventName,
propertyName,
'sum',
);
const avgQuery = useEventDataNumericSeriesQuery(
websiteId,
eventName,
propertyName,
'avg',
);
const chartData: any = useMemo(() => {
if (!sumQuery.data && !avgQuery.data) return;
const sumRows = (sumQuery.data as { t: string; y: number }[] | undefined) ?? [];
const avgRows = (avgQuery.data as { t: string; y: number }[] | undefined) ?? [];
return {
datasets: [
{
type: 'bar',
label: t(labels.sum),
data: generateTimeSeries(
sumRows.map(({ t, y }) => ({ x: t, y })),
startDate,
endDate,
unit,
dateLocale,
),
barPercentage: 0.9,
categoryPercentage: 0.9,
...colors.chart.visitors,
borderWidth: 1,
},
{
type: 'bar',
label: t(labels.average),
data: generateTimeSeries(
avgRows.map(({ t, y }) => ({ x: t, y })),
startDate,
endDate,
unit,
dateLocale,
),
barPercentage: 0.9,
categoryPercentage: 0.9,
...colors.chart.views,
borderWidth: 1,
},
],
};
}, [sumQuery.data, avgQuery.data, t, labels, startDate, endDate, unit, dateLocale, colors]);
const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]);
return (
<Column gap="4">
<LoadingPanel
isLoading={sumQuery.isLoading || avgQuery.isLoading}
error={sumQuery.error || avgQuery.error}
minHeight="400px"
>
{chartData && (
<BarChart
chartData={chartData}
minDate={startDate}
maxDate={endDate}
unit={unit}
stacked={false}
renderXLabel={renderXLabel}
height="400px"
/>
)}
</LoadingPanel>
</Column>
);
}
@@ -0,0 +1,119 @@
'use client';
import { Column, DataColumn, DataTable, Row, Text } from '@umami/react-zen';
import { useMemo } from 'react';
import { Avatar } from '@/components/common/Avatar';
import { DateDistance } from '@/components/common/DateDistance';
import { Empty } from '@/components/common/Empty';
import Link from '@/components/common/Link';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { Pager } from '@/components/common/Pager';
import { useEventDataPivotQuery, useEventDataPropertiesQuery, useMessages, useNavigation } from '@/components/hooks';
export function EventDataPivotTable({
websiteId,
eventName,
}: {
websiteId: string;
eventName: string;
}) {
const { t, labels } = useMessages();
const { router, updateParams } = useNavigation();
const propertiesQuery = useEventDataPropertiesQuery(websiteId);
const pivotQuery = useEventDataPivotQuery(websiteId, eventName);
const propertyKeys = useMemo(() => {
if (!propertiesQuery.data || !eventName) return [];
const keys = propertiesQuery.data
.filter((e: { eventName: string }) => e.eventName === eventName)
.map((e: { propertyName: string }) => e.propertyName);
return [...new Set<string>(keys)];
}, [propertiesQuery.data, eventName]);
const tableData = useMemo(() => {
if (!pivotQuery.data?.data) return [];
return pivotQuery.data.data.map(
(row: { eventId: string; sessionId: string; eventName: string; urlPath: string; createdAt: string; propertyKeys: string[]; propertyValues: string[] }) => {
const flat: Record<string, any> = {
eventId: row.eventId,
sessionId: row.sessionId,
urlPath: row.urlPath,
createdAt: row.createdAt,
};
row.propertyKeys.forEach((key, i) => {
flat[key] = row.propertyValues[i] ?? '';
});
return flat;
},
);
}, [pivotQuery.data]);
const tableQuery = useMemo(
() =>
pivotQuery.data
? { ...pivotQuery.data, data: tableData }
: undefined,
[pivotQuery.data, tableData],
);
const showPager = tableQuery && tableQuery.count > tableQuery.pageSize;
const handlePageChange = (page: number) => {
router.push(updateParams({ page }));
};
return (
<Column gap="4" minWidth="0" width="100%" maxWidth="100%">
<LoadingPanel
data={tableQuery?.data}
isLoading={pivotQuery.isLoading}
isFetching={pivotQuery.isFetching}
error={pivotQuery.error}
renderEmpty={() => <Empty />}
>
<Column gap="4" minWidth="0" width="100%" maxWidth="100%">
<Column minWidth="0" width="100%" maxWidth="100%" overflow="hidden">
<DataTable data={tableQuery?.data} style={{ width: '100%' }}>
<DataColumn id="session" label={t(labels.session)} width="0.75fr">
{(row: any) => (
<Link href={updateParams({ session: row.sessionId })}>
<Avatar seed={row.sessionId} size={32} />
</Link>
)}
</DataColumn>
<DataColumn id="urlPath" label={t(labels.path)} width="1.4fr">
{(row: any) => (
<Text truncate title={row.urlPath}>
{row.urlPath}
</Text>
)}
</DataColumn>
{propertyKeys.map(key => (
<DataColumn key={key} id={key} label={key} width="1fr">
{(row: any) => (
<Text truncate title={row[key]}>
{row[key] ?? ''}
</Text>
)}
</DataColumn>
))}
<DataColumn id="createdAt" label={t(labels.created)} width="1.1fr">
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
</DataColumn>
</DataTable>
</Column>
{showPager && tableQuery && (
<Row marginTop="6">
<Pager
page={tableQuery.page}
pageSize={tableQuery.pageSize}
count={tableQuery.count}
onPageChange={handlePageChange}
/>
</Row>
)}
</Column>
</LoadingPanel>
</Column>
);
}
@@ -0,0 +1,154 @@
'use client';
import { Column, Grid } from '@umami/react-zen';
import { colord } from 'colord';
import { useCallback, useMemo } from 'react';
import { BarChart } from '@/components/charts/BarChart';
import { PieChart } from '@/components/charts/PieChart';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import {
useDateRange,
useEventDataPropertySeriesQuery,
useEventDataValuesQuery,
useLocale,
useMessages,
useTimezone,
} from '@/components/hooks';
import { ListTable } from '@/components/metrics/ListTable';
import { renderDateLabels } from '@/lib/charts';
import { CHART_COLORS } from '@/lib/constants';
import { generateTimeSeries } from '@/lib/date';
export function EventDataPropertyChart({
websiteId,
eventName,
propertyName,
}: {
websiteId: string;
eventName: string;
propertyName: string;
}) {
const { t, labels } = useMessages();
const { timezone } = useTimezone();
const { dateRange: { startDate, endDate, unit } } = useDateRange({ timezone });
const { locale, dateLocale } = useLocale();
const { data, isLoading, error } = useEventDataPropertySeriesQuery(websiteId, eventName, propertyName);
const valuesQuery = useEventDataValuesQuery(websiteId, eventName, propertyName);
const valueLabels = useMemo(
() => valuesQuery.data?.map(({ value }) => value) ?? [],
[valuesQuery.data],
);
const colorMap = useMemo(() => {
return valueLabels.reduce(
(obj, label, index) => {
obj[label] = CHART_COLORS[index % CHART_COLORS.length];
return obj;
},
{} as Record<string, string>,
);
}, [valueLabels]);
const chartData: any = useMemo(() => {
if (!data) return;
const map = (data as any[]).reduce((obj, { x, t, y }) => {
if (!obj[x]) {
obj[x] = [];
}
obj[x].push({ x: t, y });
return obj;
}, {});
if (!map || Object.keys(map).length === 0) {
return {
datasets: [
{
data: generateTimeSeries([], startDate, endDate, unit, dateLocale),
lineTension: 0,
borderWidth: 1,
},
],
};
} else {
const keys = [
...valueLabels.filter(label => map[label]),
...Object.keys(map).filter(key => !valueLabels.includes(key)),
];
return {
datasets: keys.map((key, index) => {
const color = colord(colorMap[key] || CHART_COLORS[index % CHART_COLORS.length]);
return {
label: key,
data: generateTimeSeries(map[key], startDate, endDate, unit, dateLocale),
lineTension: 0,
backgroundColor: color.alpha(0.6).toRgbString(),
borderColor: color.alpha(0.7).toRgbString(),
borderWidth: 1,
};
}),
};
}
}, [data, startDate, endDate, unit, dateLocale, valueLabels, colorMap]);
const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]);
const propertySum = useMemo(() => {
return valuesQuery.data?.reduce((sum, { total }) => sum + total, 0) ?? 0;
}, [valuesQuery.data]);
const tableData = useMemo(() => {
if (!valuesQuery.data || propertySum === 0) return [];
return valuesQuery.data.map(({ value, total }) => ({
label: value,
count: total,
percent: 100 * (total / propertySum),
}));
}, [valuesQuery.data, propertySum]);
const pieChartData: any = useMemo(() => {
if (!valuesQuery.data?.length) return null;
return {
labels: valueLabels,
datasets: [
{
data: valuesQuery.data.map(({ total }) => total),
backgroundColor: valueLabels.map(label => colorMap[label]),
borderWidth: 0,
},
],
};
}, [valuesQuery.data, valueLabels, colorMap]);
return (
<Column gap="6">
<LoadingPanel isLoading={isLoading} error={error} minHeight="400px">
{chartData && (
<BarChart
chartData={chartData}
minDate={startDate}
maxDate={endDate}
unit={unit}
stacked={true}
renderXLabel={renderXLabel}
height="400px"
/>
)}
</LoadingPanel>
<LoadingPanel
data={tableData}
isLoading={valuesQuery.isLoading}
isFetching={valuesQuery.isFetching}
error={valuesQuery.error}
minHeight="300px"
>
<Grid columns="1fr 1fr" gap padding="2" alignItems="start">
<ListTable title={propertyName} metric={t(labels.count)} data={tableData} />
{pieChartData && <PieChart type="doughnut" chartData={pieChartData} />}
</Grid>
</LoadingPanel>
</Column>
);
}
@@ -1,30 +1,51 @@
import { Column, Grid, ListItem, Select } from '@umami/react-zen';
'use client';
import { Column, ComboBox, Grid, Label, ListItem, Select } from '@umami/react-zen';
import { useMemo, useState } from 'react';
import { PieChart } from '@/components/charts/PieChart';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import {
useEventDataPropertiesQuery,
useEventDataValuesQuery,
useMessages,
} from '@/components/hooks';
import { ListTable } from '@/components/metrics/ListTable';
import { CHART_COLORS } from '@/lib/constants';
import { useEventDataPropertiesQuery, useMessages } from '@/components/hooks';
import { EventDataNumericChart } from '../event-data/EventDataNumericChart';
import { EventDataPivotTable } from '../event-data/EventDataPivotTable';
import { EventDataPropertyChart } from '../event-data/EventDataPropertyChart';
export function EventProperties({ websiteId }: { websiteId: string }) {
const [propertyName, setPropertyName] = useState('');
const [eventName, setEventName] = useState('');
const [propertyName, setPropertyName] = useState('');
const { t, labels } = useMessages();
const { data, isLoading, isFetching, error } = useEventDataPropertiesQuery(websiteId);
const events: string[] = data
? data.reduce((arr: string | any[], e: { eventName: any }) => {
return !arr.includes(e.eventName) ? arr.concat(e.eventName) : arr;
}, [])
: [];
const properties: string[] = eventName
? data?.filter(e => e.eventName === eventName).map(e => e.propertyName)
: [];
const eventNames = useMemo<string[]>(() => {
if (!data) return [];
return [...new Set<string>(data.map((e: { eventName: string }) => e.eventName))];
}, [data]);
const properties = useMemo(() => {
if (!data || !eventName) return [];
const seen = new Set<string>();
return data
.filter((field: { eventName: string }) => field.eventName === eventName)
.filter((field: { propertyName: string; dataType: number }) => {
const key = `${field.propertyName}:${field.dataType}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}, [data, eventName]);
const selectedProperty = useMemo(() => {
return properties.find(
(field: { propertyName: string; dataType: number }) => field.propertyName === propertyName,
);
}, [properties, propertyName]);
const handleEventChange = (value: string) => {
setEventName(value);
setPropertyName('');
};
return (
<LoadingPanel
@@ -34,96 +55,62 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
error={error}
minHeight="300px"
>
<Column gap="6">
<Column gap="6" minWidth="0">
{data && (
<Grid columns="repeat(auto-fill, minmax(300px, 1fr))" marginBottom="3" gap>
<Select
label={t(labels.event)}
value={eventName}
onChange={setEventName}
placeholder=""
maxHeight={480}
>
{events?.map(p => (
<ListItem key={p} id={p}>
{p}
</ListItem>
))}
</Select>
<Select
label={t(labels.property)}
value={propertyName}
onChange={setPropertyName}
isDisabled={!eventName}
placeholder=""
maxHeight={480}
>
{properties?.map(p => (
<ListItem key={p} id={p}>
{p}
</ListItem>
))}
</Select>
<Column gap="1" style={{ minWidth: 0 }}>
<Label>{t(labels.event)}</Label>
<Select
value={eventName}
onChange={handleEventChange}
placeholder={t(labels.selectEvent)}
maxHeight={480}
>
{eventNames.map(name => (
<ListItem key={name} id={name}>
{name}
</ListItem>
))}
</Select>
</Column>
<Column gap="1" style={{ minWidth: 0 }}>
<Label>{t(labels.property)}</Label>
<ComboBox
inputValue={propertyName}
onInputChange={setPropertyName}
isDisabled={!eventName}
allowsCustomValue
allowsEmptyCollection
>
{properties.map((field: { propertyName: string }) => (
<ListItem key={field.propertyName} id={field.propertyName}>
{field.propertyName}
</ListItem>
))}
</ComboBox>
</Column>
</Grid>
)}
{eventName && propertyName && (
<EventValues websiteId={websiteId} eventName={eventName} propertyName={propertyName} />
<Column border="bottom" paddingBottom="6">
{selectedProperty?.dataType === 1 && (
<EventDataPropertyChart
websiteId={websiteId}
eventName={eventName}
propertyName={propertyName}
/>
)}
{selectedProperty?.dataType === 2 && (
<EventDataNumericChart
websiteId={websiteId}
eventName={eventName}
propertyName={propertyName}
/>
)}
</Column>
)}
{eventName && <EventDataPivotTable websiteId={websiteId} eventName={eventName} />}
</Column>
</LoadingPanel>
);
}
const EventValues = ({ websiteId, eventName, propertyName }) => {
const {
data: values,
isLoading,
isFetching,
error,
} = useEventDataValuesQuery(websiteId, eventName, propertyName);
const propertySum = useMemo(() => {
return values?.reduce((sum, { total }) => sum + total, 0) ?? 0;
}, [values]);
const chartData = useMemo(() => {
if (!propertyName || !values) return null;
return {
labels: values.map(({ value }) => value),
datasets: [
{
data: values.map(({ total }) => total),
backgroundColor: CHART_COLORS,
borderWidth: 0,
},
],
};
}, [propertyName, values]);
const tableData = useMemo(() => {
if (!propertyName || !values || propertySum === 0) return [];
return values.map(({ value, total }) => ({
label: value,
count: total,
percent: 100 * (total / propertySum),
}));
}, [propertyName, values, propertySum]);
return (
<LoadingPanel
isLoading={isLoading}
isFetching={isFetching}
data={values}
error={error}
minHeight="300px"
gap="6"
>
{values && (
<Grid columns="1fr 1fr" gap>
<ListTable title={propertyName} data={tableData} />
<PieChart type="doughnut" chartData={chartData} />
</Grid>
)}
</LoadingPanel>
);
};
@@ -0,0 +1,38 @@
import { z } from 'zod';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getEventDataNumericSeries } from '@/queries/sql/events/getEventDataNumericSeries';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
eventName: z.string(),
propertyName: z.string(),
metric: z.enum(['sum', 'avg']).default('sum'),
...filterParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { eventName, propertyName, metric, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const data = await getEventDataNumericSeries(websiteId, eventName, propertyName, metric, filters);
return json(data);
}
@@ -0,0 +1,37 @@
import { z } from 'zod';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getEventDataPropertySeries } from '@/queries/sql/events/getEventDataPropertySeries';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
eventName: z.string(),
propertyName: z.string(),
...filterParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { eventName, propertyName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const data = await getEventDataPropertySeries(websiteId, eventName, propertyName, filters);
return json(data);
}
@@ -0,0 +1,37 @@
import { z } from 'zod';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams, pagingParams } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getEventDataPivot } from '@/queries/sql/events/getEventDataPivot';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
eventName: z.string(),
...filterParams,
...pagingParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { eventName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const result = await getEventDataPivot(websiteId, eventName, filters);
return json(result);
}