seperate revenue queries for better api/performance. Fix realtime css/ui issues.
This commit is contained in:
1 parent
c6ec8385c9
commit
b7e1d902f4
18 files changed
+755
-355
No files matched your search
@@ -1,6 +1,5 @@
|
||||
import { Column, Grid, Heading, ListItem, Row, Select, Tab, TabList, TabPanel, Tabs } from '@umami/react-zen';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { DataGrid } from '@/components/common/DataGrid';
|
||||
import { GridRow } from '@/components/common/GridRow';
|
||||
import { LoadingPanel } from '@/components/common/LoadingPanel';
|
||||
import { Panel } from '@/components/common/Panel';
|
||||
@@ -8,43 +7,21 @@ import {
|
||||
useDateRange,
|
||||
useMessages,
|
||||
useNavigation,
|
||||
useResultQuery,
|
||||
useRevenueSessionsQuery,
|
||||
useRevenueChartQuery,
|
||||
useRevenueStatsQuery,
|
||||
} from '@/components/hooks';
|
||||
import { CurrencySelect } from '@/components/input/CurrencySelect';
|
||||
import { ListTable } from '@/components/metrics/ListTable';
|
||||
import { MetricCard } from '@/components/metrics/MetricCard';
|
||||
import { MetricLabel } from '@/components/metrics/MetricLabel';
|
||||
import { MetricsBar } from '@/components/metrics/MetricsBar';
|
||||
import { RevenueChart } from '@/components/metrics/RevenueChart';
|
||||
import { CURRENCY_CONFIG, DEFAULT_CURRENCY } from '@/lib/constants';
|
||||
import { formatLongCurrency, formatLongNumber } from '@/lib/format';
|
||||
import { getItem, setItem } from '@/lib/storage';
|
||||
import { SessionModal } from '../../sessions/SessionModal';
|
||||
import { SessionsTable } from '../../sessions/SessionsTable';
|
||||
import { RevenueChart } from './RevenueChart';
|
||||
import { RevenueMetricsBar } from './RevenueMetricsBar';
|
||||
import { RevenueMetricsTable } from './RevenueMetricsTable';
|
||||
import { RevenueSessionsDataTable } from './RevenueSessionsDataTable';
|
||||
|
||||
function RevenueSessionsDataTable({
|
||||
websiteId,
|
||||
currency,
|
||||
}: {
|
||||
websiteId: string;
|
||||
currency: string;
|
||||
}) {
|
||||
const { updateParams } = useNavigation();
|
||||
const queryResult = useRevenueSessionsQuery(websiteId, currency);
|
||||
|
||||
return (
|
||||
<DataGrid query={queryResult} allowPaging allowSearch>
|
||||
{({ data }) => (
|
||||
<SessionsTable
|
||||
data={data}
|
||||
websiteId={websiteId}
|
||||
getSessionHref={row => updateParams({ session: row.id })}
|
||||
/>
|
||||
)}
|
||||
</DataGrid>
|
||||
);
|
||||
}
|
||||
type RevenueChartMode = 'period' | 'cumulative';
|
||||
type SourceTab = 'referrer' | 'channel';
|
||||
type LocationTab = 'country' | 'region';
|
||||
|
||||
export interface RevenueProps {
|
||||
websiteId: string;
|
||||
@@ -53,9 +30,9 @@ export interface RevenueProps {
|
||||
unit: string;
|
||||
}
|
||||
|
||||
type RevenueChartMode = 'period' | 'cumulative';
|
||||
|
||||
export function Revenue({ websiteId, startDate, endDate, unit }: RevenueProps) {
|
||||
const [sourceTab, setSourceTab] = useState<SourceTab>('referrer');
|
||||
const [locationTab, setLocationTab] = useState<LocationTab>('country');
|
||||
const [currency, setCurrency] = useState(
|
||||
getItem(CURRENCY_CONFIG) || process.env.defaultCurrency || DEFAULT_CURRENCY,
|
||||
);
|
||||
@@ -77,100 +54,29 @@ export function Revenue({ websiteId, startDate, endDate, unit }: RevenueProps) {
|
||||
};
|
||||
|
||||
const { t, labels } = useMessages();
|
||||
const { compare, isAllTime } = useDateRange();
|
||||
const { data, error, isLoading } = useResultQuery<any>('revenue', {
|
||||
websiteId,
|
||||
startDate,
|
||||
endDate,
|
||||
currency,
|
||||
compare,
|
||||
});
|
||||
|
||||
const metrics = useMemo(() => {
|
||||
if (!data) return [];
|
||||
|
||||
const { sum, count, average, unique_count, arpu, comparison } = data.total;
|
||||
|
||||
return [
|
||||
{
|
||||
value: sum,
|
||||
label: t(labels.total),
|
||||
change: comparison ? sum - comparison.sum : 0,
|
||||
formatValue: (n: number) => formatLongCurrency(n, currency),
|
||||
},
|
||||
{
|
||||
value: average,
|
||||
label: t(labels.aov),
|
||||
tooltip: (
|
||||
<>
|
||||
<div>Average Order Value</div>
|
||||
<div>(Total Revenue / Orders)</div>
|
||||
</>
|
||||
),
|
||||
change: comparison ? average - comparison.average : 0,
|
||||
formatValue: (n: number) => formatLongCurrency(n, currency),
|
||||
},
|
||||
{
|
||||
value: arpu,
|
||||
label: t(labels.arpu),
|
||||
tooltip: (
|
||||
<>
|
||||
<div>Average Revenue Per User</div>
|
||||
<div>(Total Revenue / All Sessions)</div>
|
||||
</>
|
||||
),
|
||||
change: comparison ? arpu - (comparison.arpu ?? 0) : 0,
|
||||
formatValue: (n: number) => formatLongCurrency(n, currency),
|
||||
},
|
||||
{
|
||||
value: count,
|
||||
label: t(labels.orders),
|
||||
change: comparison ? count - comparison.count : 0,
|
||||
formatValue: formatLongNumber,
|
||||
},
|
||||
{
|
||||
value: unique_count,
|
||||
label: t(labels.uniqueCustomers),
|
||||
change: comparison ? unique_count - comparison.unique_count : 0,
|
||||
formatValue: formatLongNumber,
|
||||
},
|
||||
] as any;
|
||||
}, [
|
||||
data,
|
||||
currency,
|
||||
t,
|
||||
labels.total,
|
||||
labels.aov,
|
||||
labels.arpu,
|
||||
labels.orders,
|
||||
labels.uniqueCustomers,
|
||||
]);
|
||||
|
||||
const renderLabel = (type: string) => (data: any) => <MetricLabel type={type} data={data} />;
|
||||
const { compare } = useDateRange();
|
||||
const chartQuery = useRevenueChartQuery(websiteId, currency);
|
||||
const statsQuery = useRevenueStatsQuery({ websiteId, currency, compare });
|
||||
const data = useMemo(
|
||||
() =>
|
||||
chartQuery.data && statsQuery.data
|
||||
? { chart: chartQuery.data.chart, total: statsQuery.data }
|
||||
: null,
|
||||
[chartQuery.data, statsQuery.data],
|
||||
);
|
||||
const error = chartQuery.error || statsQuery.error;
|
||||
const isFetching = chartQuery.isFetching || statsQuery.isFetching;
|
||||
const isLoading = chartQuery.isLoading || statsQuery.isLoading;
|
||||
|
||||
return (
|
||||
<Column gap>
|
||||
<Grid columns="280px" gap>
|
||||
<CurrencySelect value={currency} onChange={handleCurrencyChange} />
|
||||
</Grid>
|
||||
<LoadingPanel data={data} isLoading={isLoading} error={error}>
|
||||
<LoadingPanel data={data} isLoading={isLoading} isFetching={isFetching} error={error}>
|
||||
{data && (
|
||||
<Column gap>
|
||||
<MetricsBar>
|
||||
{metrics?.map(({ label, value, change, formatValue, tooltip }) => {
|
||||
return (
|
||||
<MetricCard
|
||||
key={label}
|
||||
value={value}
|
||||
label={label}
|
||||
tooltip={tooltip}
|
||||
change={change}
|
||||
formatValue={formatValue}
|
||||
showChange={!isAllTime}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</MetricsBar>
|
||||
<RevenueMetricsBar data={data.total} currency={currency} />
|
||||
<Panel>
|
||||
<Row justifyContent="end">
|
||||
<Select
|
||||
@@ -196,87 +102,64 @@ export function Revenue({ websiteId, startDate, endDate, unit }: RevenueProps) {
|
||||
<GridRow layout="two">
|
||||
<Panel>
|
||||
<Heading size="2xl">{t(labels.sources)}</Heading>
|
||||
<Tabs>
|
||||
<Tabs
|
||||
selectedKey={sourceTab}
|
||||
onSelectionChange={key => setSourceTab(String(key) as SourceTab)}
|
||||
>
|
||||
<TabList>
|
||||
<Tab id="referrer">{t(labels.referrers)}</Tab>
|
||||
<Tab id="channel">{t(labels.channels)}</Tab>
|
||||
</TabList>
|
||||
<TabPanel id="referrer">
|
||||
<ListTable
|
||||
<RevenueMetricsTable
|
||||
websiteId={websiteId}
|
||||
currency={currency}
|
||||
type="referrer"
|
||||
title={t(labels.referrer)}
|
||||
metric={t(labels.revenue)}
|
||||
data={data?.referrer.map(
|
||||
({ name, value }: { name: string; value: number }) => ({
|
||||
label: name,
|
||||
count: Number(value),
|
||||
percent: (value / data?.total.sum) * 100,
|
||||
}),
|
||||
)}
|
||||
formatCount={(n: number) => formatLongCurrency(n, currency)}
|
||||
renderLabel={renderLabel('referrer')}
|
||||
totalRevenue={Number(data?.total.sum) || 0}
|
||||
enabled={sourceTab === 'referrer'}
|
||||
/>
|
||||
</TabPanel>
|
||||
<TabPanel id="channel">
|
||||
<ListTable
|
||||
<RevenueMetricsTable
|
||||
websiteId={websiteId}
|
||||
currency={currency}
|
||||
type="channel"
|
||||
title={t(labels.channel)}
|
||||
metric={t(labels.revenue)}
|
||||
data={data?.channel.map(
|
||||
({ name, value }: { name: string; value: number }) => ({
|
||||
label: name,
|
||||
count: Number(value),
|
||||
percent: (value / data?.total.sum) * 100,
|
||||
}),
|
||||
)}
|
||||
formatCount={(n: number) => formatLongCurrency(n, currency)}
|
||||
renderLabel={renderLabel('channel')}
|
||||
totalRevenue={Number(data?.total.sum) || 0}
|
||||
enabled={sourceTab === 'channel'}
|
||||
/>
|
||||
</TabPanel>
|
||||
</Tabs>
|
||||
</Panel>
|
||||
<Panel>
|
||||
<Heading size="2xl">{t(labels.location)}</Heading>
|
||||
<Tabs>
|
||||
<Tabs
|
||||
selectedKey={locationTab}
|
||||
onSelectionChange={key => setLocationTab(String(key) as LocationTab)}
|
||||
>
|
||||
<TabList>
|
||||
<Tab id="country">{t(labels.countries)}</Tab>
|
||||
<Tab id="region">{t(labels.regions)}</Tab>
|
||||
</TabList>
|
||||
<TabPanel id="country">
|
||||
<ListTable
|
||||
<RevenueMetricsTable
|
||||
websiteId={websiteId}
|
||||
currency={currency}
|
||||
type="country"
|
||||
title={t(labels.country)}
|
||||
metric={t(labels.revenue)}
|
||||
data={data?.country.map(
|
||||
({ name, value }: { name: string; value: number }) => ({
|
||||
label: name,
|
||||
count: Number(value),
|
||||
percent: (value / data?.total.sum) * 100,
|
||||
}),
|
||||
)}
|
||||
formatCount={(n: number) => formatLongCurrency(n, currency)}
|
||||
renderLabel={renderLabel('country')}
|
||||
totalRevenue={Number(data?.total.sum) || 0}
|
||||
enabled={locationTab === 'country'}
|
||||
/>
|
||||
</TabPanel>
|
||||
<TabPanel id="region">
|
||||
<ListTable
|
||||
<RevenueMetricsTable
|
||||
websiteId={websiteId}
|
||||
currency={currency}
|
||||
type="region"
|
||||
title={t(labels.region)}
|
||||
metric={t(labels.revenue)}
|
||||
data={data?.region.map(
|
||||
({
|
||||
name,
|
||||
value,
|
||||
country,
|
||||
}: {
|
||||
name: string;
|
||||
value: number;
|
||||
country: string;
|
||||
}) => ({
|
||||
label: name,
|
||||
country,
|
||||
count: Number(value),
|
||||
percent: (value / data?.total.sum) * 100,
|
||||
}),
|
||||
)}
|
||||
formatCount={(n: number) => formatLongCurrency(n, currency)}
|
||||
renderLabel={renderLabel('region')}
|
||||
totalRevenue={Number(data?.total.sum) || 0}
|
||||
enabled={locationTab === 'region'}
|
||||
/>
|
||||
</TabPanel>
|
||||
</Tabs>
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { colord } from 'colord';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { BarChart } from '@/components/charts/BarChart';
|
||||
import { useLocale, useMessages } from '@/components/hooks';
|
||||
import { renderDateLabels } from '@/lib/charts';
|
||||
import { CHART_COLORS } from '@/lib/constants';
|
||||
import { DATE_FORMATS, DATE_FUNCTIONS, formatDate, generateTimeSeries } from '@/lib/date';
|
||||
|
||||
export interface RevenueChartProps {
|
||||
data: { x: string; t: string; y: number; count: number }[];
|
||||
mode?: 'period' | 'cumulative';
|
||||
unit: string;
|
||||
minDate: Date;
|
||||
maxDate: Date;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
export function RevenueChart({
|
||||
data,
|
||||
mode = 'period',
|
||||
unit,
|
||||
minDate,
|
||||
maxDate,
|
||||
currency,
|
||||
}: RevenueChartProps) {
|
||||
const { t, labels } = useMessages();
|
||||
const { locale, dateLocale } = useLocale();
|
||||
const isCumulative = mode === 'cumulative';
|
||||
|
||||
const chartData: any = useMemo(() => {
|
||||
if (!data?.length) return { datasets: [] };
|
||||
|
||||
if (isCumulative) {
|
||||
const cumulativeMaxDate = maxDate > new Date() ? new Date() : maxDate;
|
||||
const cutoff = formatDate(cumulativeMaxDate, DATE_FORMATS[unit], dateLocale);
|
||||
const bucketDates = getBucketDates(minDate, maxDate, unit, dateLocale);
|
||||
const totals = data.reduce(
|
||||
(obj, { t, y }) => {
|
||||
obj[t] = (obj[t] || 0) + y;
|
||||
return obj;
|
||||
},
|
||||
{} as Record<string, number>,
|
||||
);
|
||||
|
||||
let total = 0;
|
||||
const timeseries = generateTimeSeries(
|
||||
Object.entries(totals).map(([x, y]) => ({ x, y })),
|
||||
minDate,
|
||||
maxDate,
|
||||
unit,
|
||||
dateLocale,
|
||||
).map(point => {
|
||||
const d = point.d ?? bucketDates.get(point.x);
|
||||
|
||||
if (point.x > cutoff) {
|
||||
return {
|
||||
...point,
|
||||
d,
|
||||
y: null,
|
||||
};
|
||||
}
|
||||
|
||||
total += point.y || 0;
|
||||
|
||||
return {
|
||||
...point,
|
||||
d,
|
||||
y: total,
|
||||
};
|
||||
});
|
||||
|
||||
const color = colord(CHART_COLORS[0]);
|
||||
|
||||
return {
|
||||
datasets: [
|
||||
{
|
||||
type: 'line',
|
||||
label: t(labels.revenue),
|
||||
data: timeseries,
|
||||
backgroundColor: (context: any) => {
|
||||
const { chart } = context;
|
||||
const { ctx, chartArea } = chart;
|
||||
|
||||
if (!chartArea) {
|
||||
return color.alpha(0.18).toRgbString();
|
||||
}
|
||||
|
||||
const gradient = ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
|
||||
gradient.addColorStop(0, color.alpha(0.22).toRgbString());
|
||||
gradient.addColorStop(1, color.alpha(0.02).toRgbString());
|
||||
|
||||
return gradient;
|
||||
},
|
||||
borderColor: color.alpha(0.95).toRgbString(),
|
||||
borderWidth: 2,
|
||||
pointRadius: 2,
|
||||
tension: 0.25,
|
||||
fill: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const map = data.reduce(
|
||||
(obj, { x, t, y }) => {
|
||||
if (!obj[x]) obj[x] = [];
|
||||
obj[x].push({ x: t, y });
|
||||
return obj;
|
||||
},
|
||||
{} as Record<string, { x: string; y: number }[]>,
|
||||
);
|
||||
|
||||
return {
|
||||
datasets: Object.keys(map).map((key, index) => {
|
||||
const color = colord(CHART_COLORS[index % CHART_COLORS.length]);
|
||||
return {
|
||||
label: key,
|
||||
data: generateTimeSeries(map[key], minDate, maxDate, unit, dateLocale),
|
||||
backgroundColor: color.alpha(0.6).toRgbString(),
|
||||
borderColor: color.alpha(0.7).toRgbString(),
|
||||
borderWidth: 1,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}, [data, minDate, maxDate, unit, dateLocale, isCumulative, t, labels.revenue]);
|
||||
|
||||
const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]);
|
||||
|
||||
return (
|
||||
<BarChart
|
||||
chartData={chartData}
|
||||
unit={unit}
|
||||
minDate={minDate}
|
||||
maxDate={maxDate}
|
||||
currency={currency}
|
||||
stacked={!isCumulative}
|
||||
renderXLabel={renderXLabel}
|
||||
height="400px"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function getBucketDates(minDate: Date, maxDate: Date, unit: string, locale: string) {
|
||||
const add = DATE_FUNCTIONS[unit].add;
|
||||
const start = DATE_FUNCTIONS[unit].start;
|
||||
const fmt = DATE_FORMATS[unit];
|
||||
const dates = new Map<string, Date>();
|
||||
|
||||
let current = start(minDate);
|
||||
const end = start(maxDate);
|
||||
|
||||
while (current <= end) {
|
||||
dates.set(formatDate(current, fmt, locale), current);
|
||||
current = add(current, 1);
|
||||
}
|
||||
|
||||
return dates;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { useDateRange, useMessages } from '@/components/hooks';
|
||||
import { MetricCard } from '@/components/metrics/MetricCard';
|
||||
import { MetricsBar } from '@/components/metrics/MetricsBar';
|
||||
import { formatLongCurrency, formatLongNumber } from '@/lib/format';
|
||||
import type { RevenueStatsData } from '@/components/hooks/queries/useRevenueStatsQuery';
|
||||
|
||||
export interface RevenueMetricsBarProps {
|
||||
data: RevenueStatsData;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
interface RevenueMetricItem {
|
||||
value: number;
|
||||
label: string;
|
||||
change: number;
|
||||
formatValue: (n: number) => string;
|
||||
tooltip?: ReactNode;
|
||||
}
|
||||
|
||||
export function RevenueMetricsBar({ data, currency }: RevenueMetricsBarProps) {
|
||||
const { t, labels } = useMessages();
|
||||
const { isAllTime } = useDateRange();
|
||||
const { sum, count, average, unique_count, arpu, comparison } = data;
|
||||
|
||||
const metrics: RevenueMetricItem[] = [
|
||||
{
|
||||
value: sum,
|
||||
label: t(labels.total),
|
||||
change: comparison ? sum - comparison.sum : 0,
|
||||
formatValue: (n: number) => formatLongCurrency(n, currency),
|
||||
},
|
||||
{
|
||||
value: average,
|
||||
label: t(labels.aov),
|
||||
tooltip: (
|
||||
<>
|
||||
<div>Average Order Value</div>
|
||||
<div>(Total Revenue / Orders)</div>
|
||||
</>
|
||||
),
|
||||
change: comparison ? average - comparison.average : 0,
|
||||
formatValue: (n: number) => formatLongCurrency(n, currency),
|
||||
},
|
||||
{
|
||||
value: arpu,
|
||||
label: t(labels.arpu),
|
||||
tooltip: (
|
||||
<>
|
||||
<div>Average Revenue Per User</div>
|
||||
<div>(Total Revenue / All Sessions)</div>
|
||||
</>
|
||||
),
|
||||
change: comparison ? arpu - (comparison.arpu ?? 0) : 0,
|
||||
formatValue: (n: number) => formatLongCurrency(n, currency),
|
||||
},
|
||||
{
|
||||
value: count,
|
||||
label: t(labels.orders),
|
||||
change: comparison ? count - comparison.count : 0,
|
||||
formatValue: formatLongNumber,
|
||||
},
|
||||
{
|
||||
value: unique_count,
|
||||
label: t(labels.uniqueCustomers),
|
||||
change: comparison ? unique_count - comparison.unique_count : 0,
|
||||
formatValue: formatLongNumber,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<MetricsBar>
|
||||
{metrics.map(({ label, value, change, formatValue, tooltip }) => {
|
||||
return (
|
||||
<MetricCard
|
||||
key={label}
|
||||
value={value}
|
||||
label={label}
|
||||
tooltip={tooltip}
|
||||
change={change}
|
||||
formatValue={formatValue}
|
||||
showChange={!isAllTime}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</MetricsBar>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Grid } from '@umami/react-zen';
|
||||
import { useMemo } from 'react';
|
||||
import { LoadingPanel } from '@/components/common/LoadingPanel';
|
||||
import {
|
||||
useMessages,
|
||||
useRevenueMetricsQuery,
|
||||
type RevenueMetricType,
|
||||
} from '@/components/hooks';
|
||||
import { ListTable } from '@/components/metrics/ListTable';
|
||||
import { MetricLabel } from '@/components/metrics/MetricLabel';
|
||||
import { formatLongCurrency } from '@/lib/format';
|
||||
|
||||
const MAX_ROWS = 10;
|
||||
|
||||
export interface RevenueMetricsTableProps {
|
||||
websiteId: string;
|
||||
currency: string;
|
||||
type: RevenueMetricType;
|
||||
title: string;
|
||||
totalRevenue: number;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export function RevenueMetricsTable({
|
||||
websiteId,
|
||||
currency,
|
||||
type,
|
||||
title,
|
||||
totalRevenue,
|
||||
enabled,
|
||||
}: RevenueMetricsTableProps) {
|
||||
const { t, labels } = useMessages();
|
||||
const { data, isLoading, isFetching, error } = useRevenueMetricsQuery(
|
||||
websiteId,
|
||||
{ type, currency },
|
||||
{ enabled },
|
||||
);
|
||||
|
||||
const tableData = useMemo(
|
||||
() =>
|
||||
data
|
||||
?.map(({ name, value, country }) => ({
|
||||
label: name,
|
||||
country,
|
||||
count: Number(value),
|
||||
percent: totalRevenue > 0 ? (value / totalRevenue) * 100 : 0,
|
||||
}))
|
||||
.slice(0, MAX_ROWS) || [],
|
||||
[data, totalRevenue],
|
||||
);
|
||||
|
||||
return (
|
||||
<LoadingPanel
|
||||
data={data}
|
||||
isFetching={isFetching}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
minHeight="400px"
|
||||
>
|
||||
<Grid padding="2">
|
||||
{data && (
|
||||
<ListTable
|
||||
title={title}
|
||||
metric={t(labels.revenue)}
|
||||
data={tableData}
|
||||
formatCount={(n: number) => formatLongCurrency(n, currency)}
|
||||
renderLabel={(row: any) => <MetricLabel type={type} data={row} />}
|
||||
/>
|
||||
)}
|
||||
</Grid>
|
||||
</LoadingPanel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { DataGrid } from '@/components/common/DataGrid';
|
||||
import { useNavigation, useRevenueSessionsQuery } from '@/components/hooks';
|
||||
import { SessionsTable } from '../../sessions/SessionsTable';
|
||||
|
||||
export interface RevenueSessionsDataTableProps {
|
||||
websiteId: string;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
export function RevenueSessionsDataTable({
|
||||
websiteId,
|
||||
currency,
|
||||
}: RevenueSessionsDataTableProps) {
|
||||
const { updateParams } = useNavigation();
|
||||
const queryResult = useRevenueSessionsQuery(websiteId, currency);
|
||||
|
||||
return (
|
||||
<DataGrid query={queryResult} allowPaging allowSearch>
|
||||
{({ data }) => (
|
||||
<SessionsTable
|
||||
data={data}
|
||||
websiteId={websiteId}
|
||||
getSessionHref={row => updateParams({ session: row.id })}
|
||||
/>
|
||||
)}
|
||||
</DataGrid>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,20 @@
|
||||
import { useMessages } from '@/components/hooks';
|
||||
import { useMessages, useMobile } from '@/components/hooks';
|
||||
import { MetricCard } from '@/components/metrics/MetricCard';
|
||||
import { MetricsBar } from '@/components/metrics/MetricsBar';
|
||||
|
||||
export function RealtimeHeader({ data }: { data: any }) {
|
||||
const { t, labels } = useMessages();
|
||||
const { isPhone } = useMobile();
|
||||
const { totals }: any = data || {};
|
||||
|
||||
return (
|
||||
<MetricsBar>
|
||||
<MetricsBar
|
||||
columns={
|
||||
isPhone
|
||||
? 'repeat(2, minmax(0, 1fr))'
|
||||
: 'repeat(auto-fit, minmax(160px, 1fr))'
|
||||
}
|
||||
>
|
||||
<MetricCard label={t(labels.views)} value={totals.views} />
|
||||
<MetricCard label={t(labels.visitors)} value={totals.visitors} />
|
||||
<MetricCard label={t(labels.events)} value={totals.events} />
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
import { Column, Heading, Row, SearchField, Text } from '@umami/react-zen';
|
||||
import Link from '@/components/common/Link';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { List, type RowComponentProps } from 'react-window';
|
||||
import { SessionModal } from '@/app/(main)/websites/[websiteId]/sessions/SessionModal';
|
||||
import { useFormat } from '@/components//hooks/useFormat';
|
||||
import { Avatar } from '@/components/common/Avatar';
|
||||
import { Empty } from '@/components/common/Empty';
|
||||
import { IconLabel } from '@/components/common/IconLabel';
|
||||
import Link from '@/components/common/Link';
|
||||
import {
|
||||
useCountryNames,
|
||||
useLocale,
|
||||
@@ -16,15 +12,21 @@ import {
|
||||
useTimezone,
|
||||
useWebsite,
|
||||
} from '@/components/hooks';
|
||||
import { useFormat } from '@/components/hooks/useFormat';
|
||||
import { Eye, User } from '@/components/icons';
|
||||
import { FilterButtons } from '@/components/input/FilterButtons';
|
||||
import { Lightning } from '@/components/svg';
|
||||
import { BROWSERS, OS_NAMES } from '@/lib/constants';
|
||||
import { Column, Heading, Row, SearchField, Text } from '@umami/react-zen';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { List, type RowComponentProps } from 'react-window';
|
||||
|
||||
const TYPE_ALL = 'all';
|
||||
const TYPE_PAGEVIEW = 'pageview';
|
||||
const TYPE_SESSION = 'session';
|
||||
const TYPE_EVENT = 'event';
|
||||
const MAX_LIST_HEIGHT = 500;
|
||||
const ROW_HEIGHT = 50;
|
||||
|
||||
const icons = {
|
||||
[TYPE_PAGEVIEW]: <Eye />,
|
||||
@@ -124,7 +126,7 @@ export function RealtimeLog({ data }: { data: any }) {
|
||||
const TableRow = ({ index, style, logs }: RowComponentProps<{ logs: any[] }>) => {
|
||||
const row = logs[index];
|
||||
return (
|
||||
<Row alignItems="center" style={style} gap>
|
||||
<Row alignItems="center" style={{ ...style, minWidth: 0 }} gap>
|
||||
<Row minWidth="30px">
|
||||
<Link href={updateParams({ session: row.sessionId })}>
|
||||
<Avatar seed={row.sessionId} size={32} />
|
||||
@@ -133,8 +135,8 @@ export function RealtimeLog({ data }: { data: any }) {
|
||||
<Row minWidth="100px">
|
||||
<Text wrap="nowrap">{getTime(row)}</Text>
|
||||
</Row>
|
||||
<IconLabel icon={getIcon(row)}>
|
||||
<Text style={{ maxWidth: isPhone ? '400px' : null }} truncate>
|
||||
<IconLabel icon={getIcon(row)} style={{ minWidth: 0, flex: 1 }}>
|
||||
<Text truncate>
|
||||
{getDetail(row)}
|
||||
</Text>
|
||||
</IconLabel>
|
||||
@@ -173,12 +175,14 @@ export function RealtimeLog({ data }: { data: any }) {
|
||||
return logs;
|
||||
}, [data, filter, formatValue, search]);
|
||||
|
||||
const listHeight = Math.min(logs.length * ROW_HEIGHT, MAX_LIST_HEIGHT);
|
||||
|
||||
return (
|
||||
<Column gap>
|
||||
<Column gap="3">
|
||||
<Heading size="base">{t(labels.activity)}</Heading>
|
||||
{isPhone ? (
|
||||
<>
|
||||
<Row>
|
||||
<Row marginBottom="1">
|
||||
<SearchField value={search} onSearch={setSearch} />
|
||||
</Row>
|
||||
<Row>
|
||||
@@ -192,16 +196,16 @@ export function RealtimeLog({ data }: { data: any }) {
|
||||
</Row>
|
||||
)}
|
||||
|
||||
<Column>
|
||||
<Column gap="3">
|
||||
{logs?.length === 0 && <Empty />}
|
||||
{logs?.length > 0 && (
|
||||
{logs.length > 0 && (
|
||||
<List
|
||||
rowComponent={TableRow}
|
||||
rowCount={logs.length}
|
||||
rowHeight={50}
|
||||
rowHeight={ROW_HEIGHT}
|
||||
rowProps={{ logs }}
|
||||
defaultHeight={500}
|
||||
style={{ width: '100%' }}
|
||||
defaultHeight={listHeight}
|
||||
style={{ width: '100%', height: listHeight }}
|
||||
/>
|
||||
)}
|
||||
</Column>
|
||||
|
||||
@@ -3,8 +3,14 @@ import { getQueryFilters, parseRequest, setWebsiteDate } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { reportResultSchema } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getRevenue, type RevenuParameters } from '@/queries/sql/reports/getRevenue';
|
||||
import { getRevenueMetrics } from '@/queries/sql/reports/getRevenueMetrics';
|
||||
import {
|
||||
getRevenueChart,
|
||||
type RevenuParameters,
|
||||
} from '@/queries/sql/reports/getRevenueChart';
|
||||
import {
|
||||
getRevenueMetrics,
|
||||
type RevenueMetricsResult,
|
||||
} from '@/queries/sql/reports/getRevenueMetrics';
|
||||
import { getRevenueStats } from '@/queries/sql/reports/getRevenueStats';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
@@ -22,20 +28,39 @@ export async function POST(request: Request) {
|
||||
|
||||
const parameters = await setWebsiteDate(websiteId, body.parameters);
|
||||
const filters = await getQueryFilters(body.filters, websiteId);
|
||||
|
||||
const [{ chart }, total, metrics] = await Promise.all([
|
||||
getRevenue(websiteId, parameters as RevenuParameters, filters),
|
||||
getRevenueStats(websiteId, parameters as RevenuParameters, filters),
|
||||
getRevenueMetrics(websiteId, parameters as RevenuParameters, filters),
|
||||
]);
|
||||
|
||||
const { compare = 'prev' } = parameters as RevenuParameters;
|
||||
const { startDate, endDate } = getCompareDate(compare, parameters.startDate, parameters.endDate);
|
||||
const comparison = await getRevenueStats(
|
||||
websiteId,
|
||||
{ ...(parameters as RevenuParameters), startDate, endDate },
|
||||
filters,
|
||||
);
|
||||
const comparisonParameters = { ...(parameters as RevenuParameters), startDate, endDate };
|
||||
|
||||
return json({ chart, total: { ...total, comparison }, ...metrics });
|
||||
const [{ chart }, total, comparison, country, region, referrer, channel] = await Promise.all([
|
||||
getRevenueChart(websiteId, parameters as RevenuParameters, filters),
|
||||
getRevenueStats(websiteId, parameters as RevenuParameters, filters),
|
||||
getRevenueStats(websiteId, comparisonParameters, filters),
|
||||
getRevenueMetrics(
|
||||
websiteId,
|
||||
parameters as RevenuParameters,
|
||||
filters,
|
||||
'country',
|
||||
) as Promise<RevenueMetricsResult['country']>,
|
||||
getRevenueMetrics(
|
||||
websiteId,
|
||||
parameters as RevenuParameters,
|
||||
filters,
|
||||
'region',
|
||||
) as Promise<RevenueMetricsResult['region']>,
|
||||
getRevenueMetrics(
|
||||
websiteId,
|
||||
parameters as RevenuParameters,
|
||||
filters,
|
||||
'referrer',
|
||||
) as Promise<RevenueMetricsResult['referrer']>,
|
||||
getRevenueMetrics(
|
||||
websiteId,
|
||||
parameters as RevenuParameters,
|
||||
filters,
|
||||
'channel',
|
||||
) as Promise<RevenueMetricsResult['channel']>,
|
||||
]);
|
||||
|
||||
return json({ chart, total: { ...total, comparison }, country, region, referrer, channel });
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { z } from 'zod';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { filterParams, withDateRange } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import {
|
||||
getRevenueChart,
|
||||
type RevenuParameters,
|
||||
} from '@/queries/sql/reports/getRevenueChart';
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ websiteId: string }> },
|
||||
) {
|
||||
const schema = withDateRange({
|
||||
currency: 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 { currency } = query;
|
||||
const filters = await getQueryFilters(query, websiteId);
|
||||
const parameters = { ...filters, currency } as RevenuParameters;
|
||||
|
||||
return json(await getRevenueChart(websiteId, parameters, filters));
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { z } from 'zod';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { badRequest, json, unauthorized } from '@/lib/response';
|
||||
import { filterParams, withDateRange } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import {
|
||||
getRevenueMetrics,
|
||||
type RevenueMetricType,
|
||||
} from '@/queries/sql/reports/getRevenueMetrics';
|
||||
import type { RevenuParameters } from '@/queries/sql/reports/getRevenueChart';
|
||||
|
||||
const revenueMetricType = z.enum(['country', 'region', 'referrer', 'channel']);
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ websiteId: string }> },
|
||||
) {
|
||||
const schema = withDateRange({
|
||||
type: revenueMetricType,
|
||||
currency: 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 { type, currency } = query;
|
||||
const filters = await getQueryFilters(query, websiteId);
|
||||
|
||||
if (!type) {
|
||||
return badRequest();
|
||||
}
|
||||
|
||||
const parameters = { ...filters, currency } as RevenuParameters;
|
||||
|
||||
return json(
|
||||
await getRevenueMetrics(websiteId, parameters, filters, type as RevenueMetricType),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { z } from 'zod';
|
||||
import { getCompareDate } from '@/lib/date';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { filterParams, withDateRange } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { type RevenuParameters } from '@/queries/sql/reports/getRevenueChart';
|
||||
import { getRevenueStats } from '@/queries/sql/reports/getRevenueStats';
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ websiteId: string }> },
|
||||
) {
|
||||
const schema = withDateRange({
|
||||
currency: 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 { currency } = query;
|
||||
const filters = await getQueryFilters(query, websiteId);
|
||||
const parameters = { ...filters, currency } as RevenuParameters;
|
||||
const { compare = 'prev' } = parameters;
|
||||
const { startDate, endDate } = getCompareDate(compare, parameters.startDate, parameters.endDate);
|
||||
const comparisonParameters = { ...parameters, startDate, endDate };
|
||||
|
||||
const [stats, comparison] = await Promise.all([
|
||||
getRevenueStats(websiteId, parameters, filters),
|
||||
getRevenueStats(websiteId, comparisonParameters, filters),
|
||||
]);
|
||||
|
||||
return json({ ...stats, comparison });
|
||||
}
|
||||
Reference in new issue
Block a user