add event-data support and charts for arrays, booleans, dates
This commit is contained in:
1 parent
43fb351ac7
commit
5a1ef5e674
25 files changed
+1205
-62
No files matched your search
@@ -0,0 +1,373 @@
|
||||
'use client';
|
||||
import { Column, Grid, Text, useTheme } from '@umami/react-zen';
|
||||
import { colord } from 'colord';
|
||||
import {
|
||||
differenceInCalendarDays,
|
||||
format,
|
||||
formatDistance,
|
||||
isValid,
|
||||
startOfDay,
|
||||
startOfMonth,
|
||||
startOfWeek,
|
||||
startOfYear,
|
||||
type Locale,
|
||||
} from 'date-fns';
|
||||
import { toZonedTime } from 'date-fns-tz';
|
||||
import { type ReactNode, useCallback, useMemo } from 'react';
|
||||
import { BarChart } from '@/components/charts/BarChart';
|
||||
import { PieChart } from '@/components/charts/PieChart';
|
||||
import { LoadingPanel } from '@/components/common/LoadingPanel';
|
||||
import { useEventDataDateSeriesQuery, useLocale, useMessages, useTimezone } from '@/components/hooks';
|
||||
import { ListTable } from '@/components/metrics/ListTable';
|
||||
import { MetricsBar } from '@/components/metrics/MetricsBar';
|
||||
import { renderDateLabels } from '@/lib/charts';
|
||||
import { getThemeColors } from '@/lib/colors';
|
||||
import { CHART_COLORS } from '@/lib/constants';
|
||||
import { formatDate, generateTimeSeries } from '@/lib/date';
|
||||
import { formatLongNumber } from '@/lib/format';
|
||||
import type { EventDataDateSeriesPoint, EventPropertyFilter } from '@/lib/types';
|
||||
|
||||
type DateChartUnit = 'day' | 'week' | 'month' | 'year';
|
||||
type ParsedDateRow = EventDataDateSeriesPoint & { date: Date };
|
||||
|
||||
function parseDateValue(value: string) {
|
||||
const normalized = value?.trim().replace(' ', 'T').replace(/Z$/, '').replace(/\.\d+$/, '');
|
||||
const [datePart = '', timePart = '00:00:00'] = normalized.split('T');
|
||||
const [year = 0, month = 1, day = 1] = datePart.split('-').map(Number);
|
||||
const [hour = 0, minute = 0, second = 0] = timePart.split(':').map(Number);
|
||||
const date = new Date(year, month - 1, day, hour, minute, second);
|
||||
|
||||
return isValid(date) ? date : null;
|
||||
}
|
||||
|
||||
function InsightCard({
|
||||
label,
|
||||
value,
|
||||
hint,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
hint?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Column
|
||||
justifyContent="center"
|
||||
paddingX="6"
|
||||
paddingY="4"
|
||||
borderRadius
|
||||
backgroundColor="surface-base"
|
||||
border
|
||||
gap="2"
|
||||
height="100%"
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
<Text weight="bold" style={{ overflowWrap: 'anywhere' }}>
|
||||
{label}
|
||||
</Text>
|
||||
<Text weight="bold" style={{ overflowWrap: 'anywhere' }}>
|
||||
{value}
|
||||
</Text>
|
||||
{hint && (
|
||||
<Text color="muted" style={{ overflowWrap: 'anywhere' }}>
|
||||
{hint}
|
||||
</Text>
|
||||
)}
|
||||
</Column>
|
||||
);
|
||||
}
|
||||
|
||||
function getChartUnit(minDate: Date, maxDate: Date): DateChartUnit {
|
||||
const spanDays = differenceInCalendarDays(maxDate, minDate);
|
||||
|
||||
if (spanDays <= 45) return 'day';
|
||||
if (spanDays <= 180) return 'week';
|
||||
if (spanDays <= 730) return 'month';
|
||||
|
||||
return 'year';
|
||||
}
|
||||
|
||||
function getBucketStart(date: Date, unit: DateChartUnit, dateLocale: Locale) {
|
||||
switch (unit) {
|
||||
case 'week':
|
||||
return startOfWeek(date, { locale: dateLocale });
|
||||
case 'month':
|
||||
return startOfMonth(date);
|
||||
case 'year':
|
||||
return startOfYear(date);
|
||||
default:
|
||||
return startOfDay(date);
|
||||
}
|
||||
}
|
||||
|
||||
export function EventDataDateChart({
|
||||
websiteId,
|
||||
eventName,
|
||||
propertyName,
|
||||
eventFilters = [],
|
||||
}: {
|
||||
websiteId: string;
|
||||
eventName: string;
|
||||
propertyName: string;
|
||||
eventFilters?: EventPropertyFilter[];
|
||||
}) {
|
||||
const { theme } = useTheme();
|
||||
const { t, labels } = useMessages();
|
||||
const { locale, dateLocale } = useLocale();
|
||||
const { timezone } = useTimezone();
|
||||
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
|
||||
const query = useEventDataDateSeriesQuery(websiteId, eventName, propertyName, eventFilters);
|
||||
|
||||
const rows = useMemo(() => query.data ?? [], [query.data]);
|
||||
const total = useMemo(() => rows.reduce((sum, { y }) => sum + y, 0), [rows]);
|
||||
const zonedNow = useMemo(() => toZonedTime(new Date(), timezone), [timezone]);
|
||||
|
||||
const exactDateRows = useMemo(() => {
|
||||
return rows
|
||||
.map(row => {
|
||||
const date = parseDateValue(row.t);
|
||||
|
||||
return date ? { ...row, date } : null;
|
||||
})
|
||||
.filter((row): row is ParsedDateRow => row !== null)
|
||||
.sort((a, b) => a.date.getTime() - b.date.getTime());
|
||||
}, [rows]);
|
||||
|
||||
const minPropertyDate = exactDateRows[0]?.date ?? null;
|
||||
const lastExactDateRow = exactDateRows[exactDateRows.length - 1];
|
||||
const maxPropertyDate = lastExactDateRow?.date ?? null;
|
||||
|
||||
const chartUnit = useMemo(
|
||||
() =>
|
||||
minPropertyDate && maxPropertyDate
|
||||
? getChartUnit(minPropertyDate, maxPropertyDate)
|
||||
: 'day',
|
||||
[minPropertyDate, maxPropertyDate],
|
||||
);
|
||||
|
||||
const chartRows = useMemo(() => {
|
||||
if (!exactDateRows.length) return [];
|
||||
|
||||
const buckets = exactDateRows.reduce(
|
||||
(obj, row) => {
|
||||
const bucketStart = getBucketStart(row.date, chartUnit, dateLocale);
|
||||
const bucketKey = format(bucketStart, "yyyy-MM-dd'T'HH:mm:ss");
|
||||
const existing = obj[bucketKey];
|
||||
|
||||
obj[bucketKey] = {
|
||||
t: bucketKey,
|
||||
y: (existing?.y ?? 0) + row.y,
|
||||
};
|
||||
|
||||
return obj;
|
||||
},
|
||||
{} as Record<string, EventDataDateSeriesPoint>,
|
||||
);
|
||||
|
||||
return Object.values(buckets).sort(
|
||||
(a, b) => (parseDateValue(a.t)?.getTime() ?? 0) - (parseDateValue(b.t)?.getTime() ?? 0),
|
||||
);
|
||||
}, [exactDateRows, chartUnit, dateLocale]);
|
||||
|
||||
const chartData: any = useMemo(() => {
|
||||
if (!rows.length || !minPropertyDate || !maxPropertyDate) return null;
|
||||
|
||||
return {
|
||||
datasets: [
|
||||
{
|
||||
label: t(labels.count),
|
||||
data: generateTimeSeries(
|
||||
chartRows.map(({ t, y }) => ({ x: t, y })),
|
||||
minPropertyDate,
|
||||
maxPropertyDate,
|
||||
chartUnit,
|
||||
dateLocale,
|
||||
),
|
||||
barPercentage: 0.9,
|
||||
categoryPercentage: 0.9,
|
||||
...colors.chart.visitors,
|
||||
borderWidth: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [
|
||||
rows,
|
||||
minPropertyDate,
|
||||
maxPropertyDate,
|
||||
chartRows,
|
||||
chartUnit,
|
||||
dateLocale,
|
||||
colors,
|
||||
t,
|
||||
labels.count,
|
||||
]);
|
||||
|
||||
const renderXLabel = useCallback(renderDateLabels(chartUnit, locale), [chartUnit, locale]);
|
||||
|
||||
const weekdayTableData = useMemo(() => {
|
||||
if (!exactDateRows.length || total === 0) return [];
|
||||
|
||||
const weekStartsOn = dateLocale.options?.weekStartsOn ?? 0;
|
||||
const weekdayOrder = Array.from(
|
||||
{ length: 7 },
|
||||
(_, index) => (weekStartsOn + index) % 7,
|
||||
);
|
||||
const weekdayTotals = exactDateRows.reduce(
|
||||
(obj, { date, y }) => {
|
||||
const day = date.getDay();
|
||||
obj[day] = (obj[day] ?? 0) + y;
|
||||
return obj;
|
||||
},
|
||||
{} as Record<number, number>,
|
||||
);
|
||||
|
||||
return weekdayOrder.map(day => {
|
||||
const referenceDate = new Date(2026, 0, 4 + day);
|
||||
const count = weekdayTotals[day] ?? 0;
|
||||
|
||||
return {
|
||||
label: format(referenceDate, 'EEEE', { locale: dateLocale }),
|
||||
count,
|
||||
percent: total ? 100 * (count / total) : 0,
|
||||
};
|
||||
});
|
||||
}, [exactDateRows, total, dateLocale]);
|
||||
|
||||
const topWeekday = useMemo(
|
||||
() => [...weekdayTableData].sort((a, b) => b.count - a.count)[0],
|
||||
[weekdayTableData],
|
||||
);
|
||||
const weekdayLabels = useMemo(
|
||||
() => weekdayTableData.map(({ label }) => label),
|
||||
[weekdayTableData],
|
||||
);
|
||||
const weekdayColorMap = useMemo(() => {
|
||||
return weekdayLabels.reduce(
|
||||
(obj, label, index) => {
|
||||
const color = colord(CHART_COLORS[index % CHART_COLORS.length]);
|
||||
obj[label] = color.alpha(0.7).toRgbString();
|
||||
return obj;
|
||||
},
|
||||
{} as Record<string, string>,
|
||||
);
|
||||
}, [weekdayLabels]);
|
||||
const weekdayPieChartData = useMemo(() => {
|
||||
if (!weekdayTableData.length) return null;
|
||||
|
||||
return {
|
||||
labels: weekdayLabels,
|
||||
datasets: [
|
||||
{
|
||||
data: weekdayTableData.map(({ count }) => count),
|
||||
backgroundColor: weekdayLabels.map(label => weekdayColorMap[label]),
|
||||
borderWidth: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [weekdayTableData, weekdayLabels, weekdayColorMap]);
|
||||
const spanDays = useMemo(
|
||||
() =>
|
||||
minPropertyDate && maxPropertyDate
|
||||
? differenceInCalendarDays(maxPropertyDate, minPropertyDate) + 1
|
||||
: 0,
|
||||
[minPropertyDate, maxPropertyDate],
|
||||
);
|
||||
|
||||
return (
|
||||
<Column gap="6">
|
||||
<LoadingPanel
|
||||
data={rows}
|
||||
isLoading={query.isLoading}
|
||||
isFetching={query.isFetching}
|
||||
error={query.error}
|
||||
minHeight="300px"
|
||||
>
|
||||
<Column gap="4">
|
||||
<MetricsBar padding="2">
|
||||
<InsightCard
|
||||
label="Top weekday"
|
||||
value={topWeekday?.count ? topWeekday.label : t(labels.none)}
|
||||
hint={
|
||||
topWeekday?.count
|
||||
? `${formatLongNumber(topWeekday.count)} ${t(labels.count).toLowerCase()} - ${Math.round(
|
||||
topWeekday.percent,
|
||||
)}%`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<InsightCard
|
||||
label="Date span"
|
||||
value={spanDays ? `${formatLongNumber(spanDays)} days` : t(labels.none)}
|
||||
hint={
|
||||
minPropertyDate && maxPropertyDate
|
||||
? `${formatDate(minPropertyDate, 'PP', locale)} - ${formatDate(maxPropertyDate, 'PP', locale)}`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<InsightCard
|
||||
label="Earliest value"
|
||||
value={minPropertyDate ? formatDate(minPropertyDate, 'PPpp', locale) : t(labels.none)}
|
||||
hint={
|
||||
minPropertyDate
|
||||
? formatDistance(minPropertyDate, zonedNow, {
|
||||
addSuffix: true,
|
||||
locale: dateLocale,
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<InsightCard
|
||||
label="Latest value"
|
||||
value={maxPropertyDate ? formatDate(maxPropertyDate, 'PPpp', locale) : t(labels.none)}
|
||||
hint={
|
||||
maxPropertyDate
|
||||
? formatDistance(maxPropertyDate, zonedNow, {
|
||||
addSuffix: true,
|
||||
locale: dateLocale,
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</MetricsBar>
|
||||
</Column>
|
||||
</LoadingPanel>
|
||||
<LoadingPanel
|
||||
data={rows}
|
||||
isLoading={query.isLoading}
|
||||
isFetching={query.isFetching}
|
||||
error={query.error}
|
||||
minHeight="400px"
|
||||
>
|
||||
{chartData && minPropertyDate && maxPropertyDate && (
|
||||
<BarChart
|
||||
chartData={chartData}
|
||||
minDate={minPropertyDate}
|
||||
maxDate={maxPropertyDate}
|
||||
unit={chartUnit}
|
||||
stacked={false}
|
||||
renderXLabel={renderXLabel}
|
||||
renderYLabel={(value: string | number) => formatLongNumber(Number(value))}
|
||||
height="400px"
|
||||
/>
|
||||
)}
|
||||
</LoadingPanel>
|
||||
<LoadingPanel
|
||||
data={rows}
|
||||
isLoading={query.isLoading}
|
||||
isFetching={query.isFetching}
|
||||
error={query.error}
|
||||
minHeight="300px"
|
||||
>
|
||||
<Grid columns={{ base: '1fr', md: '1fr 1fr' }} gap padding="2" alignItems="start">
|
||||
<Column style={{ minWidth: 0 }} width="100%">
|
||||
<ListTable title="Weekdays" metric={t(labels.count)} data={weekdayTableData} />
|
||||
</Column>
|
||||
<Column style={{ minWidth: 0 }} width="100%">
|
||||
{weekdayPieChartData && (
|
||||
<PieChart type="doughnut" chartData={weekdayPieChartData} height="280px" />
|
||||
)}
|
||||
</Column>
|
||||
</Grid>
|
||||
</LoadingPanel>
|
||||
</Column>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
import { Button, Icon, Row, Text, Tooltip, TooltipTrigger } from '@umami/react-zen';
|
||||
import { useMessages } from '@/components/hooks';
|
||||
import { X } from '@/components/icons';
|
||||
import { OPERATORS } from '@/lib/constants';
|
||||
import type { EventPropertyFilter } from '@/lib/types';
|
||||
import { Button, Icon, Row, Text, Tooltip, TooltipTrigger } from '@umami/react-zen';
|
||||
|
||||
export function EventDataFilterBar({
|
||||
filters,
|
||||
@@ -18,17 +18,28 @@ export function EventDataFilterBar({
|
||||
|
||||
const operatorLabel = (op: string) => {
|
||||
switch (op) {
|
||||
case OPERATORS.equals: return t(labels.is);
|
||||
case OPERATORS.notEquals: return t(labels.isNot);
|
||||
case OPERATORS.contains: return t(labels.contains);
|
||||
case OPERATORS.doesNotContain: return t(labels.doesNotContain);
|
||||
case OPERATORS.regex: return t(labels.regexMatch);
|
||||
case OPERATORS.notRegex: return t(labels.regexNotMatch);
|
||||
case OPERATORS.greaterThan: return t(labels.greaterThan);
|
||||
case OPERATORS.lessThan: return t(labels.lessThan);
|
||||
case OPERATORS.greaterThanEquals: return t(labels.greaterThanEquals);
|
||||
case OPERATORS.lessThanEquals: return t(labels.lessThanEquals);
|
||||
default: return op;
|
||||
case OPERATORS.equals:
|
||||
return t(labels.is);
|
||||
case OPERATORS.notEquals:
|
||||
return t(labels.isNot);
|
||||
case OPERATORS.contains:
|
||||
return t(labels.contains);
|
||||
case OPERATORS.doesNotContain:
|
||||
return t(labels.doesNotContain);
|
||||
case OPERATORS.regex:
|
||||
return t(labels.regexMatch);
|
||||
case OPERATORS.notRegex:
|
||||
return t(labels.regexNotMatch);
|
||||
case OPERATORS.greaterThan:
|
||||
return t(labels.greaterThan);
|
||||
case OPERATORS.lessThan:
|
||||
return t(labels.lessThan);
|
||||
case OPERATORS.greaterThanEquals:
|
||||
return t(labels.greaterThanEquals);
|
||||
case OPERATORS.lessThanEquals:
|
||||
return t(labels.lessThanEquals);
|
||||
default:
|
||||
return op;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -37,7 +48,15 @@ export function EventDataFilterBar({
|
||||
};
|
||||
|
||||
return (
|
||||
<Row gap alignItems="center" justifyContent="space-between" padding="2" backgroundColor="surface-sunken" wrap="wrap">
|
||||
<Row
|
||||
gap
|
||||
alignItems="center"
|
||||
justifyContent="space-between"
|
||||
padding="2"
|
||||
border
|
||||
borderRadius
|
||||
wrap="wrap"
|
||||
>
|
||||
<Row alignItems="center" gap="2" wrap="wrap" width={{ base: '100%', md: 'auto' }}>
|
||||
{filters.map((filter, index) => (
|
||||
<FilterPill
|
||||
@@ -75,8 +94,21 @@ function FilterPill({
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Row border padding="2" color backgroundColor borderRadius alignItems="center" gap="4" theme="dark">
|
||||
<Row alignItems="center" gap="2" style={{ maxWidth: 'min(500px, calc(100vw - 10rem))', minWidth: 0, overflow: 'hidden' }}>
|
||||
<Row
|
||||
border
|
||||
padding="2"
|
||||
color
|
||||
backgroundColor
|
||||
borderRadius
|
||||
alignItems="center"
|
||||
gap="4"
|
||||
theme="dark"
|
||||
>
|
||||
<Row
|
||||
alignItems="center"
|
||||
gap="2"
|
||||
style={{ maxWidth: 'min(500px, calc(100vw - 10rem))', minWidth: 0, overflow: 'hidden' }}
|
||||
>
|
||||
<Text color="primary" weight="bold">
|
||||
{label}
|
||||
</Text>
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
'use client';
|
||||
import { Column } from '@umami/react-zen';
|
||||
import { useTheme } from '@umami/react-zen';
|
||||
import { Column, 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,
|
||||
useEventDataNumericStatsQuery,
|
||||
useLocale,
|
||||
useMessages,
|
||||
useTimezone,
|
||||
} from '@/components/hooks';
|
||||
import { MetricCard } from '@/components/metrics/MetricCard';
|
||||
import { MetricsBar } from '@/components/metrics/MetricsBar';
|
||||
import { renderDateLabels } from '@/lib/charts';
|
||||
import { getThemeColors } from '@/lib/colors';
|
||||
import { generateTimeSeries } from '@/lib/date';
|
||||
import { formatLongNumber } from '@/lib/format';
|
||||
import type { EventPropertyFilter } from '@/lib/types';
|
||||
|
||||
export function EventDataNumericChart({
|
||||
@@ -48,13 +51,35 @@ export function EventDataNumericChart({
|
||||
'avg',
|
||||
eventFilters,
|
||||
);
|
||||
const statsQuery = useEventDataNumericStatsQuery(
|
||||
websiteId,
|
||||
eventName,
|
||||
propertyName,
|
||||
eventFilters,
|
||||
);
|
||||
|
||||
const sumRows = useMemo(
|
||||
() => (sumQuery.data as { t: string; y: number }[] | undefined) ?? [],
|
||||
[sumQuery.data],
|
||||
);
|
||||
const avgRows = useMemo(
|
||||
() => (avgQuery.data as { t: string; y: number }[] | undefined) ?? [],
|
||||
[avgQuery.data],
|
||||
);
|
||||
const stats = statsQuery.data;
|
||||
|
||||
const formatMetricValue = useCallback(
|
||||
(n: number) =>
|
||||
Number(n).toLocaleString(locale, {
|
||||
maximumFractionDigits: 2,
|
||||
minimumFractionDigits: Number.isInteger(Number(n)) ? 0 : 2,
|
||||
}),
|
||||
[locale],
|
||||
);
|
||||
|
||||
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: [
|
||||
{
|
||||
@@ -89,15 +114,50 @@ export function EventDataNumericChart({
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [sumQuery.data, avgQuery.data, t, labels, startDate, endDate, unit, dateLocale, colors]);
|
||||
}, [sumQuery.data, avgQuery.data, t, labels, startDate, endDate, unit, dateLocale, colors, sumRows, avgRows]);
|
||||
|
||||
const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]);
|
||||
|
||||
return (
|
||||
<Column gap="4">
|
||||
<LoadingPanel
|
||||
isLoading={sumQuery.isLoading || avgQuery.isLoading}
|
||||
error={sumQuery.error || avgQuery.error}
|
||||
data={stats}
|
||||
isLoading={sumQuery.isLoading || avgQuery.isLoading || statsQuery.isLoading}
|
||||
isFetching={sumQuery.isFetching || avgQuery.isFetching || statsQuery.isFetching}
|
||||
error={sumQuery.error || avgQuery.error || statsQuery.error}
|
||||
minHeight="100px"
|
||||
>
|
||||
<MetricsBar padding="2">
|
||||
<MetricCard
|
||||
label={t(labels.total)}
|
||||
value={stats?.total ?? 0}
|
||||
formatValue={formatLongNumber}
|
||||
/>
|
||||
<MetricCard
|
||||
label={t(labels.average)}
|
||||
value={stats?.average ?? 0}
|
||||
formatValue={formatMetricValue}
|
||||
/>
|
||||
<MetricCard
|
||||
label="Median"
|
||||
value={stats?.median ?? 0}
|
||||
formatValue={formatMetricValue}
|
||||
/>
|
||||
<MetricCard
|
||||
label={t(labels.max)}
|
||||
value={stats?.max ?? 0}
|
||||
formatValue={formatMetricValue}
|
||||
/>
|
||||
<MetricCard
|
||||
label={t(labels.min)}
|
||||
value={stats?.min ?? 0}
|
||||
formatValue={formatMetricValue}
|
||||
/>
|
||||
</MetricsBar>
|
||||
</LoadingPanel>
|
||||
<LoadingPanel
|
||||
isLoading={sumQuery.isLoading || avgQuery.isLoading || statsQuery.isLoading}
|
||||
error={sumQuery.error || avgQuery.error || statsQuery.error}
|
||||
minHeight="400px"
|
||||
>
|
||||
{chartData && (
|
||||
|
||||
@@ -6,6 +6,7 @@ import { BarChart } from '@/components/charts/BarChart';
|
||||
import { PieChart } from '@/components/charts/PieChart';
|
||||
import { LoadingPanel } from '@/components/common/LoadingPanel';
|
||||
import {
|
||||
useEventDataArraySeriesQuery,
|
||||
useDateRange,
|
||||
useEventDataPropertySeriesQuery,
|
||||
useLocale,
|
||||
@@ -16,34 +17,46 @@ import { ListTable } from '@/components/metrics/ListTable';
|
||||
import { renderDateLabels } from '@/lib/charts';
|
||||
import { CHART_COLORS } from '@/lib/constants';
|
||||
import { generateTimeSeries } from '@/lib/date';
|
||||
import type { EventPropertyFilter } from '@/lib/types';
|
||||
import type { EventDataSeriesPoint, EventPropertyFilter } from '@/lib/types';
|
||||
|
||||
export function EventDataPropertyChart({
|
||||
websiteId,
|
||||
eventName,
|
||||
propertyName,
|
||||
eventFilters = [],
|
||||
seriesType = 'property',
|
||||
}: {
|
||||
websiteId: string;
|
||||
eventName: string;
|
||||
propertyName: string;
|
||||
eventFilters?: EventPropertyFilter[];
|
||||
seriesType?: 'property' | 'array';
|
||||
}) {
|
||||
const { t, labels } = useMessages();
|
||||
const { timezone } = useTimezone();
|
||||
const { dateRange: { startDate, endDate, unit } } = useDateRange({ timezone });
|
||||
const { locale, dateLocale } = useLocale();
|
||||
const { data, isLoading, isFetching, error } = useEventDataPropertySeriesQuery(
|
||||
const propertySeriesQuery = useEventDataPropertySeriesQuery(
|
||||
websiteId,
|
||||
eventName,
|
||||
propertyName,
|
||||
eventFilters,
|
||||
{ enabled: seriesType === 'property' },
|
||||
);
|
||||
const arraySeriesQuery = useEventDataArraySeriesQuery(
|
||||
websiteId,
|
||||
eventName,
|
||||
propertyName,
|
||||
eventFilters,
|
||||
{ enabled: seriesType === 'array' },
|
||||
);
|
||||
const { data, isLoading, isFetching, error } =
|
||||
seriesType === 'array' ? arraySeriesQuery : propertySeriesQuery;
|
||||
|
||||
// Aggregate totals per value from the already-filtered time series
|
||||
const aggregated = useMemo(() => {
|
||||
if (!data) return [];
|
||||
const totals = (data as any[]).reduce((obj: Record<string, number>, { x, y }) => {
|
||||
const totals = data.reduce((obj: Record<string, number>, { x, y }) => {
|
||||
obj[x] = (obj[x] ?? 0) + y;
|
||||
return obj;
|
||||
}, {});
|
||||
@@ -64,12 +77,12 @@ export function EventDataPropertyChart({
|
||||
);
|
||||
}, [valueLabels]);
|
||||
|
||||
const chartData: any = useMemo(() => {
|
||||
const chartData = useMemo(() => {
|
||||
if (!data) return;
|
||||
|
||||
const map = (data as any[]).reduce((obj: Record<string, { x: string; y: number }[]>, { x, t, y }) => {
|
||||
const map = data.reduce((obj: Record<string, EventDataSeriesPoint[]>, { x, t, y }) => {
|
||||
if (!obj[x]) obj[x] = [];
|
||||
obj[x].push({ x: t, y });
|
||||
obj[x].push({ x, t, y });
|
||||
return obj;
|
||||
}, {});
|
||||
|
||||
@@ -95,7 +108,13 @@ export function EventDataPropertyChart({
|
||||
const color = colord(colorMap[key] || CHART_COLORS[index % CHART_COLORS.length]);
|
||||
return {
|
||||
label: key,
|
||||
data: generateTimeSeries(map[key], startDate, endDate, unit, dateLocale),
|
||||
data: generateTimeSeries(
|
||||
map[key].map(({ t, y }) => ({ x: t, y })),
|
||||
startDate,
|
||||
endDate,
|
||||
unit,
|
||||
dateLocale,
|
||||
),
|
||||
lineTension: 0,
|
||||
backgroundColor: color.alpha(0.6).toRgbString(),
|
||||
borderColor: color.alpha(0.7).toRgbString(),
|
||||
@@ -121,7 +140,7 @@ export function EventDataPropertyChart({
|
||||
}));
|
||||
}, [aggregated, propertySum]);
|
||||
|
||||
const pieChartData: any = useMemo(() => {
|
||||
const pieChartData = useMemo(() => {
|
||||
if (!aggregated.length) return null;
|
||||
return {
|
||||
labels: valueLabels,
|
||||
|
||||
@@ -3,7 +3,9 @@ import { Column, ComboBox, Grid, Label, ListItem, Row, Select } from '@umami/rea
|
||||
import { useMemo, useState } from 'react';
|
||||
import { LoadingPanel } from '@/components/common/LoadingPanel';
|
||||
import { useEventDataPropertiesQuery, useMessages } from '@/components/hooks';
|
||||
import { DATA_TYPE } from '@/lib/constants';
|
||||
import type { EventPropertyFilter } from '@/lib/types';
|
||||
import { EventDataDateChart } from '../event-data/EventDataDateChart';
|
||||
import { EventDataFilterBar } from '../event-data/EventDataFilterBar';
|
||||
import { EventDataFilterButton } from '../event-data/EventDataFilterButton';
|
||||
import { EventDataNumericChart } from '../event-data/EventDataNumericChart';
|
||||
@@ -62,8 +64,20 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
|
||||
>
|
||||
<Column gap="6" minWidth="0">
|
||||
{data && (
|
||||
<Row gap alignItems="end" marginBottom="3" wrap="wrap">
|
||||
<Grid columns="repeat(auto-fill, minmax(300px, 1fr))" gap style={{ flex: 1 }}>
|
||||
<Grid
|
||||
columns={{ base: '1fr', md: '1fr auto' }}
|
||||
gap
|
||||
alignItems="end"
|
||||
marginBottom="3"
|
||||
width="100%"
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
<Grid
|
||||
columns={{ base: '1fr', md: 'repeat(auto-fill, minmax(300px, 1fr))' }}
|
||||
gap
|
||||
width="100%"
|
||||
style={{ flex: 1, minWidth: 0 }}
|
||||
>
|
||||
<Column gap="1" style={{ minWidth: 0 }}>
|
||||
<Label>{t(labels.event)}</Label>
|
||||
<Select
|
||||
@@ -97,21 +111,28 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
|
||||
</Column>
|
||||
</Grid>
|
||||
{eventName && (
|
||||
<EventDataFilterButton
|
||||
websiteId={websiteId}
|
||||
eventName={eventName}
|
||||
eventFilters={eventFilters}
|
||||
onApply={setEventFilters}
|
||||
/>
|
||||
<Row
|
||||
width={{ base: '100%', md: 'auto' }}
|
||||
marginTop={{ base: '2', md: '0' }}
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
<EventDataFilterButton
|
||||
websiteId={websiteId}
|
||||
eventName={eventName}
|
||||
eventFilters={eventFilters}
|
||||
onApply={setEventFilters}
|
||||
/>
|
||||
</Row>
|
||||
)}
|
||||
</Row>
|
||||
</Grid>
|
||||
)}
|
||||
{eventName && (
|
||||
<EventDataFilterBar filters={eventFilters} onChange={setEventFilters} />
|
||||
)}
|
||||
{eventName && propertyName && (
|
||||
<Column border="bottom" paddingBottom="6">
|
||||
{selectedProperty?.dataType === 1 && (
|
||||
{(selectedProperty?.dataType === DATA_TYPE.string ||
|
||||
selectedProperty?.dataType === DATA_TYPE.boolean) && (
|
||||
<EventDataPropertyChart
|
||||
websiteId={websiteId}
|
||||
eventName={eventName}
|
||||
@@ -119,7 +140,7 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
|
||||
eventFilters={eventFilters}
|
||||
/>
|
||||
)}
|
||||
{selectedProperty?.dataType === 2 && (
|
||||
{selectedProperty?.dataType === DATA_TYPE.number && (
|
||||
<EventDataNumericChart
|
||||
websiteId={websiteId}
|
||||
eventName={eventName}
|
||||
@@ -127,6 +148,23 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
|
||||
eventFilters={eventFilters}
|
||||
/>
|
||||
)}
|
||||
{selectedProperty?.dataType === DATA_TYPE.date && (
|
||||
<EventDataDateChart
|
||||
websiteId={websiteId}
|
||||
eventName={eventName}
|
||||
propertyName={propertyName}
|
||||
eventFilters={eventFilters}
|
||||
/>
|
||||
)}
|
||||
{selectedProperty?.dataType === DATA_TYPE.array && (
|
||||
<EventDataPropertyChart
|
||||
websiteId={websiteId}
|
||||
eventName={eventName}
|
||||
propertyName={propertyName}
|
||||
eventFilters={eventFilters}
|
||||
seriesType="array"
|
||||
/>
|
||||
)}
|
||||
</Column>
|
||||
)}
|
||||
{eventName && (
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { z } from 'zod';
|
||||
import { parseEventPropertyFilters } from '@/lib/params';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { filterParams, timezoneParam, unitParam } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getEventDataArraySeries } from '@/queries/sql/events/getEventDataArraySeries';
|
||||
|
||||
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(),
|
||||
timezone: timezoneParam.optional(),
|
||||
unit: unitParam.optional(),
|
||||
...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 eventFilters = parseEventPropertyFilters(query);
|
||||
const data = await getEventDataArraySeries(websiteId, eventName, propertyName, filters, eventFilters);
|
||||
|
||||
return json(data);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from 'zod';
|
||||
import { parseEventPropertyFilters } from '@/lib/params';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { filterParams, timezoneParam } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getEventDataDateSeries } from '@/queries/sql/events/getEventDataDateSeries';
|
||||
|
||||
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(),
|
||||
timezone: timezoneParam.optional(),
|
||||
...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 eventFilters = parseEventPropertyFilters(query);
|
||||
const data = await getEventDataDateSeries(websiteId, eventName, propertyName, filters, eventFilters);
|
||||
|
||||
return json(data);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { z } from 'zod';
|
||||
import { parseEventPropertyFilters } from '@/lib/params';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { filterParams } from '@/lib/schema';
|
||||
import { filterParams, timezoneParam, unitParam } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getEventDataNumericSeries } from '@/queries/sql/events/getEventDataNumericSeries';
|
||||
|
||||
@@ -15,7 +15,9 @@ export async function GET(
|
||||
endAt: z.coerce.number().int(),
|
||||
eventName: z.string(),
|
||||
propertyName: z.string(),
|
||||
metric: z.enum(['sum', 'avg']).default('sum'),
|
||||
metric: z.enum(['sum', 'avg', 'count']).default('sum'),
|
||||
timezone: timezoneParam.optional(),
|
||||
unit: unitParam.optional(),
|
||||
...filterParams,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { z } from 'zod';
|
||||
import { parseEventPropertyFilters } from '@/lib/params';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { filterParams } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getEventDataNumericStats } from '@/queries/sql/events/getEventDataNumericStats';
|
||||
|
||||
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 eventFilters = parseEventPropertyFilters(query);
|
||||
const data = await getEventDataNumericStats(websiteId, eventName, propertyName, filters, eventFilters);
|
||||
|
||||
return json(data);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { z } from 'zod';
|
||||
import { parseEventPropertyFilters } from '@/lib/params';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { filterParams } from '@/lib/schema';
|
||||
import { filterParams, timezoneParam, unitParam } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getEventDataPropertySeries } from '@/queries/sql/events/getEventDataPropertySeries';
|
||||
|
||||
@@ -15,6 +15,8 @@ export async function GET(
|
||||
endAt: z.coerce.number().int(),
|
||||
eventName: z.string(),
|
||||
propertyName: z.string(),
|
||||
timezone: timezoneParam.optional(),
|
||||
unit: unitParam.optional(),
|
||||
...filterParams,
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user