v1 revenue report for clickhouse

This commit is contained in:
Francis Cao 2024-09-26 15:36:48 -07:00
parent e173f375c7
commit 2707b39473
19 changed files with 427 additions and 243 deletions

View file

@ -48,6 +48,46 @@ export function TestConsole({ websiteId }: { websiteId: string }) {
});
}
function handleRunRevenue() {
window['umami'].track(props => ({
...props,
url: '/checkout-cart',
referrer: 'https://www.google.com',
}));
window['umami'].track('checkout-cart', {
revenue: parseFloat((Math.random() * 100000).toFixed(2)),
currency: 'USD',
});
window['umami'].track('affiliate-link', {
revenue: parseFloat((Math.random() * 100000).toFixed(2)),
currency: 'USD',
});
window['umami'].track('promotion-link', {
revenue: parseFloat((Math.random() * 100000).toFixed(2)),
currency: 'USD',
});
window['umami'].track('checkout-cart', {
revenue: parseFloat((Math.random() * 100000).toFixed(2)),
currency: 'EUR',
});
window['umami'].track('promotion-link', {
revenue: parseFloat((Math.random() * 100000).toFixed(2)),
currency: 'EUR',
});
window['umami'].track('affiliate-link', {
item1: {
productIdentity: 'ABC424',
revenue: parseFloat((Math.random() * 100000).toFixed(2)),
currency: 'MXN',
},
item2: {
productIdentity: 'ZYW684',
revenue: parseFloat((Math.random() * 100000).toFixed(2)),
currency: 'MXN',
},
});
}
function handleRunIdentify() {
window['umami'].identify({
userId: 123,
@ -127,10 +167,18 @@ export function TestConsole({ websiteId }: { websiteId: string }) {
>
Send event with data
</Button>
<Button
id="generate-revenue-button"
data-umami-event="checkout-cart"
data-umami-event-revenue={(Math.random() * 100).toFixed(2).toString()}
variant="primary"
>
Generate revenue data
</Button>
<Button
id="button-with-div-button"
data-umami-event="button-click"
data-umami-event-name="bob"
data-umami-event-name={'bob'}
data-umami-event-id="123"
variant="primary"
>
@ -155,6 +203,9 @@ export function TestConsole({ websiteId }: { websiteId: string }) {
<Button id="manual-button" variant="primary" onClick={handleRunIdentify}>
Run identify
</Button>
<Button id="manual-button" variant="primary" onClick={handleRunRevenue}>
Revenue script
</Button>
</div>
</div>
<WebsiteChart websiteId={website.id} />

View file

@ -1,4 +1,5 @@
import Funnel from 'assets/funnel.svg';
import Money from 'assets/money.svg';
import Lightbulb from 'assets/lightbulb.svg';
import Magnet from 'assets/magnet.svg';
import Path from 'assets/path.svg';
@ -51,12 +52,12 @@ export function ReportTemplates({ showHeader = true }: { showHeader?: boolean })
url: renderTeamUrl('/reports/journey'),
icon: <Path />,
},
// {
// title: formatMessage(labels.revenue),
// description: formatMessage(labels.revenueDescription),
// url: renderTeamUrl('/reports/revenue'),
// icon: <Money />,
// },
{
title: formatMessage(labels.revenue),
description: formatMessage(labels.revenueDescription),
url: renderTeamUrl('/reports/revenue'),
icon: <Money />,
},
];
return (

View file

@ -1,98 +0,0 @@
import BarChart, { BarChartProps } from 'components/charts/BarChart';
import { useLocale, useMessages } from 'components/hooks';
import MetricCard from 'components/metrics/MetricCard';
import MetricsBar from 'components/metrics/MetricsBar';
import { renderDateLabels } from 'lib/charts';
import { formatLongNumber } from 'lib/format';
import { useContext, useMemo } from 'react';
import { ReportContext } from '../[reportId]/Report';
export interface PageviewsChartProps extends BarChartProps {
isLoading?: boolean;
}
export function RevenueChart({ isLoading, ...props }: PageviewsChartProps) {
const { formatMessage, labels } = useMessages();
const { locale } = useLocale();
const { report } = useContext(ReportContext);
const { data, parameters } = report || {};
const chartData = useMemo(() => {
if (!data) {
return {};
}
return {
datasets: [
{
label: formatMessage(labels.average),
data: data?.chart.map(a => ({ x: a.time, y: a.avg })),
borderWidth: 2,
backgroundColor: '#8601B0',
borderColor: '#8601B0',
order: 1,
},
{
label: formatMessage(labels.total),
data: data?.chart.map(a => ({ x: a.time, y: a.sum })),
borderWidth: 2,
backgroundColor: '#f15bb5',
borderColor: '#f15bb5',
order: 2,
},
],
};
}, [data, locale]);
const metricData = useMemo(() => {
if (!data) {
return [];
}
const { sum, avg, count, uniqueCount } = data.total;
return [
{
value: sum,
label: formatMessage(labels.total),
formatValue: formatLongNumber,
},
{
value: avg,
label: formatMessage(labels.average),
formatValue: formatLongNumber,
},
{
value: count,
label: formatMessage(labels.transactions),
formatValue: formatLongNumber,
},
{
value: uniqueCount,
label: formatMessage(labels.uniqueCustomers),
formatValue: formatLongNumber,
},
] as any;
}, [data, locale]);
return (
<>
<MetricsBar isFetched={data}>
{metricData?.map(({ label, value, formatValue }) => {
return <MetricCard key={label} value={value} label={label} formatValue={formatValue} />;
})}
</MetricsBar>
{data && (
<BarChart
{...props}
data={chartData}
unit={parameters?.dateRange.unit}
isLoading={isLoading}
renderXLabel={renderDateLabels(parameters?.dateRange.unit, locale)}
/>
)}
</>
);
}
export default RevenueChart;

View file

@ -1,46 +1,35 @@
import { useMessages } from 'components/hooks';
import { useContext } from 'react';
import { Form, FormButtons, FormInput, FormRow, SubmitButton, TextField } from 'react-basics';
import { Dropdown, Form, FormButtons, FormInput, FormRow, Item, SubmitButton } from 'react-basics';
import BaseParameters from '../[reportId]/BaseParameters';
import { ReportContext } from '../[reportId]/Report';
export function RevenueParameters() {
const { report, runReport, isRunning } = useContext(ReportContext);
const { formatMessage, labels } = useMessages();
const { id, parameters } = report || {};
const { websiteId, dateRange } = parameters || {};
const queryDisabled = !websiteId || !dateRange;
const queryEnabled = websiteId && dateRange;
const handleSubmit = (data: any, e: any) => {
e.stopPropagation();
e.preventDefault();
if (!queryDisabled) {
runReport(data);
}
runReport(data);
};
return (
<Form values={parameters} onSubmit={handleSubmit} preventSubmit={true}>
<BaseParameters showDateSelect={true} allowWebsiteSelect={!id} />
<FormRow label={formatMessage(labels.event)}>
<FormInput name="eventName" rules={{ required: formatMessage(labels.required) }}>
<TextField autoComplete="off" />
</FormInput>
</FormRow>
<FormRow label={formatMessage(labels.revenueProperty)}>
<FormInput name="revenueProperty" rules={{ required: formatMessage(labels.required) }}>
<TextField autoComplete="off" />
</FormInput>
</FormRow>
<FormRow label={formatMessage(labels.userProperty)}>
<FormInput name="userProperty">
<TextField autoComplete="off" />
<FormRow label={formatMessage(labels.currency)}>
<FormInput name="currency" rules={{ required: formatMessage(labels.required) }}>
<Dropdown items={['USD', 'EUR', 'MXN']}>
{item => <Item key={item}>{item}</Item>}
</Dropdown>
</FormInput>
</FormRow>
<FormButtons>
<SubmitButton variant="primary" disabled={queryDisabled} isLoading={isRunning}>
<SubmitButton variant="primary" disabled={!queryEnabled} isLoading={isRunning}>
{formatMessage(labels.runQuery)}
</SubmitButton>
</FormButtons>

View file

@ -1,10 +0,0 @@
.filters {
display: flex;
flex-direction: column;
justify-content: space-between;
border: 1px solid var(--base400);
border-radius: var(--border-radius);
line-height: 32px;
padding: 10px;
overflow: hidden;
}

View file

@ -1,15 +1,15 @@
import RevenueChart from './RevenueChart';
import RevenueParameters from './RevenueParameters';
import Report from '../[reportId]/Report';
import ReportHeader from '../[reportId]/ReportHeader';
import ReportMenu from '../[reportId]/ReportMenu';
import ReportBody from '../[reportId]/ReportBody';
import Money from 'assets/money.svg';
import { REPORT_TYPES } from 'lib/constants';
import Report from '../[reportId]/Report';
import ReportBody from '../[reportId]/ReportBody';
import ReportHeader from '../[reportId]/ReportHeader';
import ReportMenu from '../[reportId]/ReportMenu';
import RevenueParameters from './RevenueParameters';
import RevenueView from './RevenueView';
const defaultParameters = {
type: REPORT_TYPES.revenue,
parameters: { Revenue: [] },
parameters: {},
};
export default function RevenueReport({ reportId }: { reportId?: string }) {
@ -20,7 +20,7 @@ export default function RevenueReport({ reportId }: { reportId?: string }) {
<RevenueParameters />
</ReportMenu>
<ReportBody>
<RevenueChart unit="day" />
<RevenueView />
</ReportBody>
</Report>
);

View file

@ -0,0 +1,38 @@
import EmptyPlaceholder from 'components/common/EmptyPlaceholder';
import { useMessages } from 'components/hooks';
import { useContext } from 'react';
import { GridColumn, GridTable } from 'react-basics';
import { ReportContext } from '../[reportId]/Report';
import { formatLongCurrency } from 'lib/format';
export function RevenueTable() {
const { report } = useContext(ReportContext);
const { formatMessage, labels } = useMessages();
const { data } = report || {};
if (!data) {
return <EmptyPlaceholder />;
}
return (
<GridTable data={data.table || []}>
<GridColumn name="currency" label={formatMessage(labels.currency)} alignment="end">
{row => row.currency}
</GridColumn>
<GridColumn name="currency" label={formatMessage(labels.total)} width="300px" alignment="end">
{row => formatLongCurrency(row.sum, row.currency)}
</GridColumn>
<GridColumn name="currency" label={formatMessage(labels.average)} alignment="end">
{row => formatLongCurrency(row.avg, row.currency)}
</GridColumn>
<GridColumn name="currency" label={formatMessage(labels.transactions)} alignment="end">
{row => row.count}
</GridColumn>
<GridColumn name="currency" label={formatMessage(labels.uniqueCustomers)} alignment="end">
{row => row.uniqueCount}
</GridColumn>
</GridTable>
);
}
export default RevenueTable;

View file

@ -0,0 +1,5 @@
.container {
display: grid;
gap: 20px;
margin-bottom: 40px;
}

View file

@ -0,0 +1,140 @@
import { colord } from 'colord';
import BarChart from 'components/charts/BarChart';
import PieChart from 'components/charts/PieChart';
import { useLocale, useMessages } from 'components/hooks';
import { GridRow } from 'components/layout/Grid';
import ListTable from 'components/metrics/ListTable';
import MetricCard from 'components/metrics/MetricCard';
import MetricsBar from 'components/metrics/MetricsBar';
import { renderDateLabels } from 'lib/charts';
import { CHART_COLORS } from 'lib/constants';
import { formatLongCurrency, formatLongNumber } from 'lib/format';
import { useContext, useMemo } from 'react';
import { ReportContext } from '../[reportId]/Report';
import RevenueTable from './RevenueTable';
import styles from './RevenueView.module.css';
export interface RevenueViewProps {
isLoading?: boolean;
}
export function RevenueView({ isLoading }: RevenueViewProps) {
const { formatMessage, labels } = useMessages();
const { locale } = useLocale();
const { report } = useContext(ReportContext);
const {
data,
parameters: { dateRange, currency },
} = report || {};
const showTable = data?.table.length > 1;
const chartData = useMemo(() => {
if (!data) return [];
const map = (data.chart as any[]).reduce((obj, { x, t, y }) => {
if (!obj[x]) {
obj[x] = [];
}
obj[x].push({ x: t, y });
return obj;
}, {});
return {
datasets: Object.keys(map).map((key, index) => {
const color = colord(CHART_COLORS[index % CHART_COLORS.length]);
return {
label: key,
data: map[key],
lineTension: 0,
backgroundColor: color.alpha(0.6).toRgbString(),
borderColor: color.alpha(0.7).toRgbString(),
borderWidth: 1,
};
}),
};
}, [data]);
const countryData = useMemo(() => {
if (!data) return [];
const labels = data.country.map(({ name }) => name);
const datasets = [
{
data: data.country.map(({ value }) => value),
backgroundColor: CHART_COLORS,
borderWidth: 0,
},
];
return { labels, datasets };
}, [data]);
const metricData = useMemo(() => {
if (!data) return [];
const { sum, avg, count, uniqueCount } = data.total;
return [
{
value: sum,
label: formatMessage(labels.total),
formatValue: n => formatLongCurrency(n, currency),
},
{
value: avg,
label: formatMessage(labels.average),
formatValue: n => formatLongCurrency(n, currency),
},
{
value: count,
label: formatMessage(labels.transactions),
formatValue: formatLongNumber,
},
{
value: uniqueCount,
label: formatMessage(labels.uniqueCustomers),
formatValue: formatLongNumber,
},
] as any;
}, [data, locale]);
return (
<>
<div className={styles.container}>
<MetricsBar isFetched={data}>
{metricData?.map(({ label, value, formatValue }) => {
return <MetricCard key={label} value={value} label={label} formatValue={formatValue} />;
})}
</MetricsBar>
<BarChart
minDate={dateRange?.startDate}
maxDate={dateRange?.endDate}
data={chartData}
unit={dateRange?.unit}
stacked={true}
currency={currency}
renderXLabel={renderDateLabels(dateRange?.unit, locale)}
isLoading={isLoading}
/>
{data && (
<GridRow columns="one-two">
<ListTable
metric={formatMessage(labels.country)}
data={data?.country.map(({ name, value }) => ({
x: name,
y: value,
z: (value / data?.total.sum) * 100,
}))}
/>
<PieChart type="doughnut" data={countryData} />
</GridRow>
)}
{showTable && <RevenueTable />}
</div>
</>
);
}
export default RevenueView;

View file

@ -54,7 +54,7 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
{propertyName && (
<div className={styles.chart}>
<div className={styles.title}>{propertyName}</div>
<PieChart key={propertyName} type="doughnut" data={chartData} />
<PieChart key={propertyName + eventName} type="doughnut" data={chartData} />
</div>
)}
</div>