mirror of
https://github.com/umami-software/umami.git
synced 2026-02-04 12:47:13 +01:00
Merge branch 'dev' into script-simplification
This commit is contained in:
commit
9101f8a478
109 changed files with 17911 additions and 11822 deletions
|
|
@ -1,6 +0,0 @@
|
|||
'use client';
|
||||
import TestConsole from './TestConsole';
|
||||
|
||||
export default function ConsolePage({ websiteId }) {
|
||||
return <TestConsole websiteId={websiteId} />;
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
'use client';
|
||||
import { Button } from 'react-basics';
|
||||
import Link from 'next/link';
|
||||
import Script from 'next/script';
|
||||
|
|
@ -9,7 +10,7 @@ import WebsiteChart from '../websites/[websiteId]/WebsiteChart';
|
|||
import { useApi, useNavigation } from '@/components/hooks';
|
||||
import styles from './TestConsole.module.css';
|
||||
|
||||
export function TestConsole({ websiteId }: { websiteId: string }) {
|
||||
export function TestConsole({ websiteId }: { websiteId?: string }) {
|
||||
const { get, useQuery } = useApi();
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['websites:me'],
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { Metadata } from 'next';
|
||||
import ConsolePage from '../ConsolePage';
|
||||
import TestConsole from '../TestConsole';
|
||||
|
||||
async function getEnabled() {
|
||||
return !!process.env.ENABLE_TEST_CONSOLE;
|
||||
}
|
||||
|
||||
export default async function ({ params }: { params: { websiteId: string } }) {
|
||||
export default async function ({ params }: { params: Promise<{ websiteId: string }> }) {
|
||||
const { websiteId } = await params;
|
||||
|
||||
const enabled = await getEnabled();
|
||||
|
|
@ -14,7 +14,7 @@ export default async function ({ params }: { params: { websiteId: string } }) {
|
|||
return null;
|
||||
}
|
||||
|
||||
return <ConsolePage websiteId={websiteId?.[0]} />;
|
||||
return <TestConsole websiteId={websiteId?.[0]} />;
|
||||
}
|
||||
|
||||
export const metadata: Metadata = {
|
||||
|
|
|
|||
|
|
@ -6,8 +6,9 @@ import GoalReport from '../goals/GoalsReport';
|
|||
import InsightsReport from '../insights/InsightsReport';
|
||||
import JourneyReport from '../journey/JourneyReport';
|
||||
import RetentionReport from '../retention/RetentionReport';
|
||||
import UTMReport from '../utm/UTMReport';
|
||||
import RevenueReport from '../revenue/RevenueReport';
|
||||
import UTMReport from '../utm/UTMReport';
|
||||
import AttributionReport from '../attribution/AttributionReport';
|
||||
|
||||
const reports = {
|
||||
funnel: FunnelReport,
|
||||
|
|
@ -18,6 +19,7 @@ const reports = {
|
|||
goals: GoalReport,
|
||||
journey: JourneyReport,
|
||||
revenue: RevenueReport,
|
||||
attribution: AttributionReport,
|
||||
};
|
||||
|
||||
export default function ReportPage({ reportId }: { reportId: string }) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
.item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.value {
|
||||
display: flex;
|
||||
align-self: center;
|
||||
gap: 20px;
|
||||
}
|
||||
188
src/app/(main)/reports/attribution/AttributionParameters.tsx
Normal file
188
src/app/(main)/reports/attribution/AttributionParameters.tsx
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import { useMessages } from '@/components/hooks';
|
||||
import Icons from '@/components/icons';
|
||||
import { useContext, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Dropdown,
|
||||
Form,
|
||||
FormButtons,
|
||||
FormInput,
|
||||
FormRow,
|
||||
Icon,
|
||||
Item,
|
||||
Popup,
|
||||
PopupTrigger,
|
||||
SubmitButton,
|
||||
Toggle,
|
||||
} from 'react-basics';
|
||||
import BaseParameters from '../[reportId]/BaseParameters';
|
||||
import ParameterList from '../[reportId]/ParameterList';
|
||||
import PopupForm from '../[reportId]/PopupForm';
|
||||
import { ReportContext } from '../[reportId]/Report';
|
||||
import FunnelStepAddForm from '../funnel/FunnelStepAddForm';
|
||||
import styles from './AttributionParameters.module.css';
|
||||
import AttributionStepAddForm from './AttributionStepAddForm';
|
||||
import useRevenueValues from '@/components/hooks/queries/useRevenueValues';
|
||||
|
||||
export function AttributionParameters() {
|
||||
const { report, runReport, updateReport, isRunning } = useContext(ReportContext);
|
||||
const { formatMessage, labels } = useMessages();
|
||||
const { id, parameters } = report || {};
|
||||
const { websiteId, dateRange, steps } = parameters || {};
|
||||
const queryEnabled = websiteId && dateRange && steps.length > 0;
|
||||
const [model, setModel] = useState('');
|
||||
const [revenueMode, setRevenueMode] = useState(false);
|
||||
|
||||
const { data: currencyValues = [] } = useRevenueValues(
|
||||
websiteId,
|
||||
dateRange?.startDate,
|
||||
dateRange?.endDate,
|
||||
);
|
||||
|
||||
const handleSubmit = (data: any, e: any) => {
|
||||
if (revenueMode === false) {
|
||||
delete data.currency;
|
||||
}
|
||||
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
runReport(data);
|
||||
};
|
||||
|
||||
const handleCheck = () => {
|
||||
setRevenueMode(!revenueMode);
|
||||
};
|
||||
|
||||
const handleAddStep = (step: { type: string; value: string }) => {
|
||||
if (step.type === 'url') {
|
||||
setRevenueMode(false);
|
||||
}
|
||||
updateReport({ parameters: { steps: parameters.steps.concat(step) } });
|
||||
};
|
||||
|
||||
const handleUpdateStep = (
|
||||
close: () => void,
|
||||
index: number,
|
||||
step: { type: string; value: string },
|
||||
) => {
|
||||
if (step.type === 'url') {
|
||||
setRevenueMode(false);
|
||||
}
|
||||
const steps = [...parameters.steps];
|
||||
steps[index] = step;
|
||||
updateReport({ parameters: { steps } });
|
||||
close();
|
||||
};
|
||||
|
||||
const handleRemoveStep = (index: number) => {
|
||||
const steps = [...parameters.steps];
|
||||
delete steps[index];
|
||||
updateReport({ parameters: { steps: steps.filter(n => n) } });
|
||||
};
|
||||
|
||||
const AddStepButton = () => {
|
||||
return (
|
||||
<PopupTrigger disabled={steps.length > 0}>
|
||||
<Button disabled={steps.length > 0}>
|
||||
<Icon>
|
||||
<Icons.Plus />
|
||||
</Icon>
|
||||
</Button>
|
||||
<Popup alignment="start">
|
||||
<PopupForm>
|
||||
<FunnelStepAddForm onChange={handleAddStep} />
|
||||
</PopupForm>
|
||||
</Popup>
|
||||
</PopupTrigger>
|
||||
);
|
||||
};
|
||||
|
||||
const items = [
|
||||
{ label: 'First-Click', value: 'firstClick' },
|
||||
{ label: 'Last-Click', value: 'lastClick' },
|
||||
];
|
||||
|
||||
const renderModelValue = (value: any) => {
|
||||
return items.find(item => item.value === value)?.label;
|
||||
};
|
||||
|
||||
const onModelChange = (value: any) => {
|
||||
setModel(value);
|
||||
updateReport({ parameters: { model } });
|
||||
};
|
||||
|
||||
return (
|
||||
<Form values={parameters} onSubmit={handleSubmit} preventSubmit={true}>
|
||||
<BaseParameters showDateSelect={true} allowWebsiteSelect={!id} />
|
||||
<FormRow label={formatMessage(labels.model)}>
|
||||
<FormInput name="model" rules={{ required: formatMessage(labels.required) }}>
|
||||
<Dropdown
|
||||
items={items}
|
||||
value={model}
|
||||
renderValue={renderModelValue}
|
||||
onChange={onModelChange}
|
||||
>
|
||||
{({ value, label }) => {
|
||||
return <Item key={value}>{label}</Item>;
|
||||
}}
|
||||
</Dropdown>
|
||||
</FormInput>
|
||||
</FormRow>
|
||||
<FormRow label={formatMessage(labels.conversionStep)} action={<AddStepButton />}>
|
||||
<ParameterList>
|
||||
{steps.map((step: { type: string; value: string }, index: number) => {
|
||||
return (
|
||||
<PopupTrigger key={index}>
|
||||
<ParameterList.Item
|
||||
className={styles.item}
|
||||
icon={step.type === 'url' ? <Icons.Eye /> : <Icons.Bolt />}
|
||||
onRemove={() => handleRemoveStep(index)}
|
||||
>
|
||||
<div className={styles.value}>
|
||||
<div>{step.value}</div>
|
||||
</div>
|
||||
</ParameterList.Item>
|
||||
<Popup alignment="start">
|
||||
{(close: () => void) => (
|
||||
<PopupForm>
|
||||
<AttributionStepAddForm
|
||||
type={step.type}
|
||||
value={step.value}
|
||||
onChange={handleUpdateStep.bind(null, close, index)}
|
||||
/>
|
||||
</PopupForm>
|
||||
)}
|
||||
</Popup>
|
||||
</PopupTrigger>
|
||||
);
|
||||
})}
|
||||
</ParameterList>
|
||||
</FormRow>
|
||||
<FormRow>
|
||||
<Toggle
|
||||
checked={revenueMode}
|
||||
onChecked={handleCheck}
|
||||
disabled={currencyValues.length === 0 || steps[0]?.type === 'url'}
|
||||
>
|
||||
<b>Revenue Mode</b>
|
||||
</Toggle>
|
||||
</FormRow>
|
||||
{revenueMode && (
|
||||
<FormRow label={formatMessage(labels.currency)}>
|
||||
<FormInput name="currency" rules={{ required: formatMessage(labels.required) }}>
|
||||
<Dropdown items={currencyValues.map(item => item.currency)}>
|
||||
{item => <Item key={item}>{item}</Item>}
|
||||
</Dropdown>
|
||||
</FormInput>
|
||||
</FormRow>
|
||||
)}
|
||||
<FormButtons>
|
||||
<SubmitButton variant="primary" disabled={!queryEnabled} isLoading={isRunning}>
|
||||
{formatMessage(labels.runQuery)}
|
||||
</SubmitButton>
|
||||
</FormButtons>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default AttributionParameters;
|
||||
27
src/app/(main)/reports/attribution/AttributionReport.tsx
Normal file
27
src/app/(main)/reports/attribution/AttributionReport.tsx
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
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 AttributionParameters from './AttributionParameters';
|
||||
import AttributionView from './AttributionView';
|
||||
|
||||
const defaultParameters = {
|
||||
type: REPORT_TYPES.attribution,
|
||||
parameters: { model: 'firstClick', steps: [] },
|
||||
};
|
||||
|
||||
export default function AttributionReport({ reportId }: { reportId?: string }) {
|
||||
return (
|
||||
<Report reportId={reportId} defaultParameters={defaultParameters}>
|
||||
<ReportHeader icon={<Money />} />
|
||||
<ReportMenu>
|
||||
<AttributionParameters />
|
||||
</ReportMenu>
|
||||
<ReportBody>
|
||||
<AttributionView />
|
||||
</ReportBody>
|
||||
</Report>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
'use client';
|
||||
import AttributionReport from './AttributionReport';
|
||||
|
||||
export default function AttributionReportPage() {
|
||||
return <AttributionReport />;
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
.dropdown {
|
||||
width: 140px;
|
||||
}
|
||||
|
||||
.input {
|
||||
width: 200px;
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
import { useState } from 'react';
|
||||
import { useMessages } from '@/components/hooks';
|
||||
import { Button, FormRow, TextField, Flexbox, Dropdown, Item } from 'react-basics';
|
||||
import styles from './AttributionStepAddForm.module.css';
|
||||
|
||||
export interface AttributionStepAddFormProps {
|
||||
type?: string;
|
||||
value?: string;
|
||||
onChange?: (step: { type: string; value: string }) => void;
|
||||
}
|
||||
|
||||
export function AttributionStepAddForm({
|
||||
type: defaultType = 'url',
|
||||
value: defaultValue = '',
|
||||
onChange,
|
||||
}: AttributionStepAddFormProps) {
|
||||
const [type, setType] = useState(defaultType);
|
||||
const [value, setValue] = useState(defaultValue);
|
||||
const { formatMessage, labels } = useMessages();
|
||||
const items = [
|
||||
{ label: formatMessage(labels.url), value: 'url' },
|
||||
{ label: formatMessage(labels.event), value: 'event' },
|
||||
];
|
||||
const isDisabled = !type || !value;
|
||||
|
||||
const handleSave = () => {
|
||||
onChange({ type, value });
|
||||
setValue('');
|
||||
};
|
||||
|
||||
const handleChange = e => {
|
||||
setValue(e.target.value);
|
||||
};
|
||||
|
||||
const handleKeyDown = e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.stopPropagation();
|
||||
handleSave();
|
||||
}
|
||||
};
|
||||
|
||||
const renderTypeValue = (value: any) => {
|
||||
return items.find(item => item.value === value)?.label;
|
||||
};
|
||||
|
||||
return (
|
||||
<Flexbox direction="column" gap={10}>
|
||||
<FormRow label={formatMessage(defaultValue ? labels.update : labels.add)}>
|
||||
<Flexbox gap={10}>
|
||||
<Dropdown
|
||||
className={styles.dropdown}
|
||||
items={items}
|
||||
value={type}
|
||||
renderValue={renderTypeValue}
|
||||
onChange={(value: any) => setType(value)}
|
||||
>
|
||||
{({ value, label }) => {
|
||||
return <Item key={value}>{label}</Item>;
|
||||
}}
|
||||
</Dropdown>
|
||||
<TextField
|
||||
className={styles.input}
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
autoFocus={true}
|
||||
autoComplete="off"
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
</Flexbox>
|
||||
</FormRow>
|
||||
<FormRow>
|
||||
<Button variant="primary" onClick={handleSave} disabled={isDisabled}>
|
||||
{formatMessage(defaultValue ? labels.update : labels.add)}
|
||||
</Button>
|
||||
</FormRow>
|
||||
</Flexbox>
|
||||
);
|
||||
}
|
||||
|
||||
export default AttributionStepAddForm;
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
.container {
|
||||
display: grid;
|
||||
gap: 20px;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 24px;
|
||||
line-height: 36px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 50% 50%;
|
||||
gap: 20px;
|
||||
border-top: 1px solid var(--base300);
|
||||
padding-top: 30px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
134
src/app/(main)/reports/attribution/AttributionView.tsx
Normal file
134
src/app/(main)/reports/attribution/AttributionView.tsx
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
import PieChart from '@/components/charts/PieChart';
|
||||
import { useMessages } from '@/components/hooks';
|
||||
import { Grid, GridRow } from '@/components/layout/Grid';
|
||||
import ListTable from '@/components/metrics/ListTable';
|
||||
import MetricCard from '@/components/metrics/MetricCard';
|
||||
import MetricsBar from '@/components/metrics/MetricsBar';
|
||||
import { CHART_COLORS } from '@/lib/constants';
|
||||
import { formatLongNumber } from '@/lib/format';
|
||||
import { useContext } from 'react';
|
||||
import { ReportContext } from '../[reportId]/Report';
|
||||
import styles from './AttributionView.module.css';
|
||||
|
||||
export interface AttributionViewProps {
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export function AttributionView({ isLoading }: AttributionViewProps) {
|
||||
const { formatMessage, labels } = useMessages();
|
||||
const { report } = useContext(ReportContext);
|
||||
const {
|
||||
data,
|
||||
parameters: { currency },
|
||||
} = report || {};
|
||||
const ATTRIBUTION_PARAMS = [
|
||||
{ value: 'referrer', label: formatMessage(labels.referrers) },
|
||||
{ value: 'paidAds', label: formatMessage(labels.paidAds) },
|
||||
];
|
||||
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { pageviews, visitors, visits } = data.total;
|
||||
|
||||
const metrics = data
|
||||
? [
|
||||
{
|
||||
value: pageviews,
|
||||
label: formatMessage(labels.views),
|
||||
formatValue: formatLongNumber,
|
||||
},
|
||||
{
|
||||
value: visits,
|
||||
label: formatMessage(labels.visits),
|
||||
formatValue: formatLongNumber,
|
||||
},
|
||||
{
|
||||
value: visitors,
|
||||
label: formatMessage(labels.visitors),
|
||||
formatValue: formatLongNumber,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
function UTMTable(UTMTableProps: { data: any; title: string; utm: string }) {
|
||||
const { data, title, utm } = UTMTableProps;
|
||||
const total = data[utm].reduce((sum, { value }) => {
|
||||
return +sum + +value;
|
||||
}, 0);
|
||||
|
||||
return (
|
||||
<ListTable
|
||||
title={title}
|
||||
metric={formatMessage(currency ? labels.revenue : labels.visitors)}
|
||||
currency={currency}
|
||||
data={data[utm].map(({ name, value }) => ({
|
||||
x: name,
|
||||
y: Number(value),
|
||||
z: (value / total) * 100,
|
||||
}))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<MetricsBar isFetched={data}>
|
||||
{metrics?.map(({ label, value, formatValue }) => {
|
||||
return <MetricCard key={label} value={value} label={label} formatValue={formatValue} />;
|
||||
})}
|
||||
</MetricsBar>
|
||||
{ATTRIBUTION_PARAMS.map(({ value, label }) => {
|
||||
const items = data[value];
|
||||
const total = items.reduce((sum, { value }) => {
|
||||
return +sum + +value;
|
||||
}, 0);
|
||||
|
||||
const chartData = {
|
||||
labels: items.map(({ name }) => name),
|
||||
datasets: [
|
||||
{
|
||||
data: items.map(({ value }) => value),
|
||||
backgroundColor: CHART_COLORS,
|
||||
borderWidth: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return (
|
||||
<div key={value} className={styles.row}>
|
||||
<div>
|
||||
<div className={styles.title}>{label}</div>
|
||||
<ListTable
|
||||
metric={formatMessage(currency ? labels.revenue : labels.visitors)}
|
||||
currency={currency}
|
||||
data={items.map(({ name, value }) => ({
|
||||
x: name,
|
||||
y: Number(value),
|
||||
z: (value / total) * 100,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<PieChart type="doughnut" data={chartData} isLoading={isLoading} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Grid>
|
||||
<GridRow columns="two">
|
||||
<UTMTable data={data} title={formatMessage(labels.sources)} utm={'utm_source'} />
|
||||
<UTMTable data={data} title={formatMessage(labels.medium)} utm={'utm_medium'} />
|
||||
</GridRow>
|
||||
<GridRow columns="three">
|
||||
<UTMTable data={data} title={formatMessage(labels.campaigns)} utm={'utm_campaign'} />
|
||||
<UTMTable data={data} title={formatMessage(labels.content)} utm={'utm_content'} />
|
||||
<UTMTable data={data} title={formatMessage(labels.terms)} utm={'utm_term'} />
|
||||
</GridRow>
|
||||
</Grid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AttributionView;
|
||||
10
src/app/(main)/reports/attribution/page.tsx
Normal file
10
src/app/(main)/reports/attribution/page.tsx
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import AttributionReportPage from './AttributionReportPage';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export default function () {
|
||||
return <AttributionReportPage />;
|
||||
}
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Attribution Report',
|
||||
};
|
||||
|
|
@ -5,6 +5,7 @@ import Magnet from '@/assets/magnet.svg';
|
|||
import Path from '@/assets/path.svg';
|
||||
import Tag from '@/assets/tag.svg';
|
||||
import Target from '@/assets/target.svg';
|
||||
import Network from '@/assets/network.svg';
|
||||
import { useMessages, useTeamUrl } from '@/components/hooks';
|
||||
import PageHeader from '@/components/layout/PageHeader';
|
||||
import Link from 'next/link';
|
||||
|
|
@ -58,6 +59,12 @@ export function ReportTemplates({ showHeader = true }: { showHeader?: boolean })
|
|||
url: renderTeamUrl('/reports/revenue'),
|
||||
icon: <Money />,
|
||||
},
|
||||
{
|
||||
title: formatMessage(labels.attribution),
|
||||
description: formatMessage(labels.attributionDescription),
|
||||
url: renderTeamUrl('/reports/attribution'),
|
||||
icon: <Network />,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -4,27 +4,33 @@ import EventsDataTable from './EventsDataTable';
|
|||
import EventsMetricsBar from './EventsMetricsBar';
|
||||
import EventsChart from '@/components/metrics/EventsChart';
|
||||
import { GridRow } from '@/components/layout/Grid';
|
||||
import MetricsTable from '@/components/metrics/MetricsTable';
|
||||
import EventsTable from '@/components/metrics/EventsTable';
|
||||
import { useMessages } from '@/components/hooks';
|
||||
import { Item, Tabs } from 'react-basics';
|
||||
import { useState } from 'react';
|
||||
import EventProperties from './EventProperties';
|
||||
|
||||
export default function EventsPage({ websiteId }) {
|
||||
const [label, setLabel] = useState(null);
|
||||
const [tab, setTab] = useState('activity');
|
||||
const { formatMessage, labels } = useMessages();
|
||||
|
||||
const handleLabelClick = (value: string) => {
|
||||
setLabel(value !== label ? value : '');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<WebsiteHeader websiteId={websiteId} />
|
||||
<EventsMetricsBar websiteId={websiteId} />
|
||||
<GridRow columns="two-one">
|
||||
<EventsChart websiteId={websiteId} />
|
||||
<MetricsTable
|
||||
<EventsChart websiteId={websiteId} focusLabel={label} />
|
||||
<EventsTable
|
||||
websiteId={websiteId}
|
||||
type="event"
|
||||
title={formatMessage(labels.events)}
|
||||
metric={formatMessage(labels.actions)}
|
||||
onLabelClick={handleLabelClick}
|
||||
/>
|
||||
</GridRow>
|
||||
<div>
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import RealtimeCountries from './RealtimeCountries';
|
|||
import WebsiteHeader from '../WebsiteHeader';
|
||||
import { percentFilter } from '@/lib/filters';
|
||||
|
||||
export function WebsiteRealtimePage({ websiteId }) {
|
||||
export function WebsiteRealtimePage({ websiteId }: { websiteId: string }) {
|
||||
const { data, isLoading, error } = useRealtime(websiteId);
|
||||
|
||||
if (isLoading || error) {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import WebsiteRealtimePage from './WebsiteRealtimePage';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export default async function ({ params }: { params: { websiteId: string } }) {
|
||||
export default async function ({ params }: { params: Promise<{ websiteId: string }> }) {
|
||||
const { websiteId } = await params;
|
||||
|
||||
return <WebsiteRealtimePage websiteId={websiteId} />;
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ export default function SessionsDataTable({
|
|||
const queryResult = useWebsiteSessions(websiteId);
|
||||
|
||||
return (
|
||||
<DataTable queryResult={queryResult} allowSearch={false} renderEmpty={() => children}>
|
||||
<DataTable queryResult={queryResult} allowSearch={true} renderEmpty={() => children}>
|
||||
{({ data }) => <SessionsTable data={data} showDomain={!websiteId} />}
|
||||
</DataTable>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -27,19 +27,19 @@ export function SessionActivity({
|
|||
|
||||
return (
|
||||
<div className={styles.timeline}>
|
||||
{data.map(({ eventId, createdAt, urlPath, eventName, visitId }) => {
|
||||
{data.map(({ id, createdAt, urlPath, eventName, visitId }) => {
|
||||
const showHeader = !lastDay || !isSameDay(new Date(lastDay), new Date(createdAt));
|
||||
lastDay = createdAt;
|
||||
|
||||
return (
|
||||
<Fragment key={eventId}>
|
||||
<Fragment key={id}>
|
||||
{showHeader && (
|
||||
<div className={styles.header}>{formatTimezoneDate(createdAt, 'PPPP')}</div>
|
||||
)}
|
||||
<div key={eventId} className={styles.row}>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.time}>
|
||||
<StatusLight color={`#${visitId?.substring(0, 6)}`}>
|
||||
{formatTimezoneDate(createdAt, 'h:mm:ss aaa')}
|
||||
{formatTimezoneDate(createdAt, 'pp')}
|
||||
</StatusLight>
|
||||
</div>
|
||||
<Icon>{eventName ? <Icons.Bolt /> : <Icons.Eye />}</Icon>
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@ export default function SessionInfo({ data }) {
|
|||
<dd>
|
||||
{data?.id} <CopyIcon value={data?.id} />
|
||||
</dd>
|
||||
|
||||
<dt>{formatMessage(labels.distinctId)}</dt>
|
||||
<dd>{data?.distinctId}</dd>
|
||||
<dt>{formatMessage(labels.lastSeen)}</dt>
|
||||
<dd>{formatTimezoneDate(data?.lastAt, 'PPPPpp')}</dd>
|
||||
|
||||
|
|
@ -36,7 +37,7 @@ export default function SessionInfo({ data }) {
|
|||
<Icon>
|
||||
<Icons.Location />
|
||||
</Icon>
|
||||
{getRegionName(data?.subdivision1)}
|
||||
{getRegionName(data?.region)}
|
||||
</dd>
|
||||
|
||||
<dt>{formatMessage(labels.city)}</dt>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { parseRequest } from '@/lib/request';
|
||||
import { json } from '@/lib/response';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
export async function POST(request: Request) {
|
||||
const { auth, error } = await parseRequest(request);
|
||||
|
||||
if (error) {
|
||||
|
|
|
|||
50
src/app/api/reports/attribution/route.ts
Normal file
50
src/app/api/reports/attribution/route.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { canViewWebsite } from '@/lib/auth';
|
||||
import { parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { reportParms } from '@/lib/schema';
|
||||
import { getAttribution } from '@/queries/sql/reports/getAttribution';
|
||||
import { z } from 'zod';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const schema = z.object({
|
||||
...reportParms,
|
||||
model: z.string().regex(/firstClick|lastClick/i),
|
||||
steps: z
|
||||
.array(
|
||||
z.object({
|
||||
type: z.string(),
|
||||
value: z.string(),
|
||||
}),
|
||||
)
|
||||
.min(1),
|
||||
currency: z.string().optional(),
|
||||
});
|
||||
|
||||
const { auth, body, error } = await parseRequest(request, schema);
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const {
|
||||
websiteId,
|
||||
model,
|
||||
steps,
|
||||
currency,
|
||||
dateRange: { startDate, endDate },
|
||||
} = body;
|
||||
|
||||
if (!(await canViewWebsite(auth, websiteId))) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
const data = await getAttribution(websiteId, {
|
||||
startDate: new Date(startDate),
|
||||
endDate: new Date(endDate),
|
||||
model: model,
|
||||
steps,
|
||||
currency,
|
||||
});
|
||||
|
||||
return json(data);
|
||||
}
|
||||
|
|
@ -29,16 +29,12 @@ const schema = z.object({
|
|||
ip: z.string().ip().optional(),
|
||||
userAgent: z.string().optional(),
|
||||
timestamp: z.coerce.number().int().optional(),
|
||||
id: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
// Bot check
|
||||
if (!process.env.DISABLE_BOT_CHECK && isbot(request.headers.get('user-agent'))) {
|
||||
return json({ beep: 'boop' });
|
||||
}
|
||||
|
||||
const { body, error } = await parseRequest(request, schema, { skipAuth: true });
|
||||
|
||||
if (error) {
|
||||
|
|
@ -59,6 +55,7 @@ export async function POST(request: Request) {
|
|||
title,
|
||||
tag,
|
||||
timestamp,
|
||||
id,
|
||||
} = payload;
|
||||
|
||||
// Cache check
|
||||
|
|
@ -83,8 +80,15 @@ export async function POST(request: Request) {
|
|||
}
|
||||
|
||||
// Client info
|
||||
const { ip, userAgent, device, browser, os, country, subdivision1, subdivision2, city } =
|
||||
await getClientInfo(request, payload);
|
||||
const { ip, userAgent, device, browser, os, country, region, city } = await getClientInfo(
|
||||
request,
|
||||
payload,
|
||||
);
|
||||
|
||||
// Bot check
|
||||
if (!process.env.DISABLE_BOT_CHECK && isbot(userAgent)) {
|
||||
return json({ beep: 'boop' });
|
||||
}
|
||||
|
||||
// IP block
|
||||
if (hasBlockedIp(ip)) {
|
||||
|
|
@ -97,7 +101,7 @@ export async function POST(request: Request) {
|
|||
const sessionSalt = hash(startOfMonth(createdAt).toUTCString());
|
||||
const visitSalt = hash(startOfHour(createdAt).toUTCString());
|
||||
|
||||
const sessionId = uuid(websiteId, ip, userAgent, sessionSalt);
|
||||
const sessionId = id ? uuid(websiteId, id) : uuid(websiteId, ip, userAgent, sessionSalt);
|
||||
|
||||
// Find session
|
||||
if (!clickhouse.enabled && !cache?.sessionId) {
|
||||
|
|
@ -109,16 +113,15 @@ export async function POST(request: Request) {
|
|||
await createSession({
|
||||
id: sessionId,
|
||||
websiteId,
|
||||
hostname,
|
||||
browser,
|
||||
os,
|
||||
device,
|
||||
screen,
|
||||
language,
|
||||
country,
|
||||
subdivision1,
|
||||
subdivision2,
|
||||
region,
|
||||
city,
|
||||
distinctId: id,
|
||||
});
|
||||
} catch (e: any) {
|
||||
if (!e.message.toLowerCase().includes('unique constraint')) {
|
||||
|
|
@ -142,18 +145,33 @@ export async function POST(request: Request) {
|
|||
const base = hostname ? `https://${hostname}` : 'https://localhost';
|
||||
const currentUrl = new URL(url, base);
|
||||
|
||||
let urlPath = currentUrl.pathname;
|
||||
let urlPath = currentUrl.pathname === '/undefined' ? '' : currentUrl.pathname;
|
||||
const urlQuery = currentUrl.search.substring(1);
|
||||
const urlDomain = currentUrl.hostname.replace(/^www./, '');
|
||||
|
||||
if (process.env.REMOVE_TRAILING_SLASH) {
|
||||
urlPath = urlPath.replace(/(.+)\/$/, '$1');
|
||||
}
|
||||
|
||||
let referrerPath: string;
|
||||
let referrerQuery: string;
|
||||
let referrerDomain: string;
|
||||
|
||||
// UTM Params
|
||||
const utmSource = currentUrl.searchParams.get('utm_source');
|
||||
const utmMedium = currentUrl.searchParams.get('utm_medium');
|
||||
const utmCampaign = currentUrl.searchParams.get('utm_campaign');
|
||||
const utmContent = currentUrl.searchParams.get('utm_content');
|
||||
const utmTerm = currentUrl.searchParams.get('utm_term');
|
||||
|
||||
// Click IDs
|
||||
const gclid = currentUrl.searchParams.get('gclid');
|
||||
const fbclid = currentUrl.searchParams.get('fbclid');
|
||||
const msclkid = currentUrl.searchParams.get('msclkid');
|
||||
const ttclid = currentUrl.searchParams.get('ttclid');
|
||||
const lifatid = currentUrl.searchParams.get('li_fat_id');
|
||||
const twclid = currentUrl.searchParams.get('twclid');
|
||||
|
||||
if (process.env.REMOVE_TRAILING_SLASH) {
|
||||
urlPath = urlPath.replace(/(.+)\/$/, '$1');
|
||||
}
|
||||
|
||||
if (referrer) {
|
||||
const referrerUrl = new URL(referrer, base);
|
||||
|
||||
|
|
@ -171,10 +189,21 @@ export async function POST(request: Request) {
|
|||
visitId,
|
||||
urlPath: safeDecodeURI(urlPath),
|
||||
urlQuery,
|
||||
utmSource,
|
||||
utmMedium,
|
||||
utmCampaign,
|
||||
utmContent,
|
||||
utmTerm,
|
||||
referrerPath: safeDecodeURI(referrerPath),
|
||||
referrerQuery,
|
||||
referrerDomain,
|
||||
pageTitle: safeDecodeURIComponent(title),
|
||||
gclid,
|
||||
fbclid,
|
||||
msclkid,
|
||||
ttclid,
|
||||
lifatid,
|
||||
twclid,
|
||||
eventName: name,
|
||||
eventData: data,
|
||||
hostname: hostname || urlDomain,
|
||||
|
|
@ -184,10 +213,10 @@ export async function POST(request: Request) {
|
|||
screen,
|
||||
language,
|
||||
country,
|
||||
subdivision1,
|
||||
subdivision2,
|
||||
region,
|
||||
city,
|
||||
tag,
|
||||
distinctId: id,
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
|
|
@ -201,6 +230,7 @@ export async function POST(request: Request) {
|
|||
websiteId,
|
||||
sessionId,
|
||||
sessionData: data,
|
||||
distinctId: id,
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,8 +28,8 @@ export async function GET(request: Request, { params }: { params: Promise<{ team
|
|||
|
||||
export async function POST(request: Request, { params }: { params: Promise<{ teamId: string }> }) {
|
||||
const schema = z.object({
|
||||
name: z.string().max(50),
|
||||
accessCode: z.string().max(50),
|
||||
name: z.string().max(50).optional(),
|
||||
accessCode: z.string().max(50).optional(),
|
||||
});
|
||||
|
||||
const { auth, body, error } = await parseRequest(request, schema);
|
||||
|
|
|
|||
|
|
@ -26,7 +26,10 @@ export async function POST(request: Request, { params }: { params: Promise<{ use
|
|||
const schema = z.object({
|
||||
username: z.string().max(255),
|
||||
password: z.string().max(255).optional(),
|
||||
role: z.string().regex(/admin|user|view-only/i),
|
||||
role: z
|
||||
.string()
|
||||
.regex(/admin|user|view-only/i)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const { auth, body, error } = await parseRequest(request, schema);
|
||||
|
|
|
|||
|
|
@ -1,6 +0,0 @@
|
|||
import { json } from '@/lib/response';
|
||||
import { CURRENT_VERSION } from '@/lib/constants';
|
||||
|
||||
export async function GET() {
|
||||
return json({ version: CURRENT_VERSION });
|
||||
}
|
||||
|
|
@ -136,7 +136,15 @@ function getChannels(data: { domain: string; query: string; visitors: number }[]
|
|||
|
||||
const prefix = /utm_medium=(.*cp.*|ppc|retargeting|paid.*)/.test(query) ? 'paid' : 'organic';
|
||||
|
||||
if (SEARCH_DOMAINS.some(match(domain)) || /utm_medium=organic/.test(query)) {
|
||||
if (PAID_AD_PARAMS.some(match(query))) {
|
||||
channels.paidAds += Number(visitors);
|
||||
} else if (/utm_medium=(referral|app|link)/.test(query)) {
|
||||
channels.referral += Number(visitors);
|
||||
} else if (/utm_medium=affiliate/.test(query)) {
|
||||
channels.affiliate += Number(visitors);
|
||||
} else if (/utm_(source|medium)=sms/.test(query)) {
|
||||
channels.sms += Number(visitors);
|
||||
} else if (SEARCH_DOMAINS.some(match(domain)) || /utm_medium=organic/.test(query)) {
|
||||
channels[`${prefix}Search`] += Number(visitors);
|
||||
} else if (
|
||||
SOCIAL_DOMAINS.some(match(domain)) ||
|
||||
|
|
@ -152,14 +160,6 @@ function getChannels(data: { domain: string; query: string; visitors: number }[]
|
|||
channels[`${prefix}Shopping`] += Number(visitors);
|
||||
} else if (VIDEO_DOMAINS.some(match(domain)) || /utm_medium=(.*video.*)/.test(query)) {
|
||||
channels[`${prefix}Video`] += Number(visitors);
|
||||
} else if (PAID_AD_PARAMS.some(match(query))) {
|
||||
channels.paidAds += Number(visitors);
|
||||
} else if (/utm_medium=(referral|app|link)/.test(query)) {
|
||||
channels.referral += Number(visitors);
|
||||
} else if (/utm_medium=affiliate/.test(query)) {
|
||||
channels.affiliate += Number(visitors);
|
||||
} else if (/utm_(source|medium)=sms/.test(query)) {
|
||||
channels.sms += Number(visitors);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export async function POST(
|
|||
const schema = z.object({
|
||||
name: z.string(),
|
||||
domain: z.string(),
|
||||
shareId: z.string().regex(SHARE_ID_REGEX).nullable(),
|
||||
shareId: z.string().regex(SHARE_ID_REGEX).nullable().optional(),
|
||||
});
|
||||
|
||||
const { auth, body, error } = await parseRequest(request, schema);
|
||||
|
|
|
|||
1
src/assets/network.svg
Normal file
1
src/assets/network.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg height="512" viewBox="0 0 32 32" width="512" xmlns="http://www.w3.org/2000/svg"><g id="_x30_6_network"><path d="m28 19c-.809 0-1.54.325-2.08.847l-6.011-3.01c.058-.271.091-.55.091-.837s-.033-.566-.091-.837l6.011-3.01c.54.522 1.271.847 2.08.847 1.654 0 3-1.346 3-3s-1.346-3-3-3-3 1.346-3 3c0 .123.022.24.036.359l-6.036 3.023c-.521-.597-1.21-1.035-2-1.24v-5.326c1.162-.415 2-1.514 2-2.816 0-1.654-1.346-3-3-3s-3 1.346-3 3c0 1.302.838 2.401 2 2.815v5.327c-.79.205-1.478.643-2 1.24l-6.037-3.022c.015-.12.037-.237.037-.36 0-1.654-1.346-3-3-3s-3 1.346-3 3 1.346 3 3 3c.809 0 1.54-.325 2.08-.847l6.011 3.01c-.058.271-.091.55-.091.837s.033.566.091.837l-6.011 3.01c-.54-.522-1.271-.847-2.08-.847-1.654 0-3 1.346-3 3s1.346 3 3 3 3-1.346 3-3c0-.123-.022-.24-.036-.359l6.036-3.023c.521.597 1.21 1.035 2 1.24v5.326c-1.162.415-2 1.514-2 2.816 0 1.654 1.346 3 3 3s3-1.346 3-3c0-1.302-.838-2.401-2-2.816v-5.326c.79-.205 1.478-.643 2-1.24l6.037 3.022c-.015.12-.037.237-.037.36 0 1.654 1.346 3 3 3s3-1.346 3-3-1.346-3-3-3zm0-10c.551 0 1 .449 1 1s-.449 1-1 1-1-.449-1-1 .449-1 1-1zm-24 2c-.551 0-1-.449-1-1s.449-1 1-1 1 .449 1 1-.449 1-1 1zm0 12c-.551 0-1-.449-1-1s.449-1 1-1 1 .449 1 1-.449 1-1 1zm12-20c.551 0 1 .449 1 1s-.449 1-1 1-1-.449-1-1 .449-1 1-1zm0 26c-.551 0-1-.449-1-1s.449-1 1-1 1 .449 1 1-.449 1-1 1zm0-11c-1.103 0-2-.897-2-2s.897-2 2-2 2 .897 2 2-.897 2-2 2zm12 5c-.551 0-1-.449-1-1s.449-1 1-1 1 .449 1 1-.449 1-1 1z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
|
|
@ -7,7 +7,7 @@ const formats = {
|
|||
millisecond: 'T',
|
||||
second: 'pp',
|
||||
minute: 'p',
|
||||
hour: 'h:mm aaa - PP',
|
||||
hour: 'p - PP',
|
||||
day: 'PPPP',
|
||||
week: 'PPPP',
|
||||
month: 'LLLL yyyy',
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ export function Chart({
|
|||
className,
|
||||
chartOptions,
|
||||
}: ChartProps) {
|
||||
const canvas = useRef();
|
||||
const canvas = useRef(null);
|
||||
const chart = useRef(null);
|
||||
const [legendItems, setLegendItems] = useState([]);
|
||||
|
||||
|
|
@ -86,7 +86,7 @@ export function Chart({
|
|||
dataset.data = data?.datasets[index]?.data;
|
||||
|
||||
if (chart.current.legend.legendItems[index]) {
|
||||
chart.current.legend.legendItems[index].text = data?.datasets[index]?.label;
|
||||
chart.current.legend.legendItems[index].text = data.datasets[index]?.label;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -95,6 +95,12 @@ export function Chart({
|
|||
}
|
||||
}
|
||||
|
||||
if (data.focusLabel !== null) {
|
||||
chart.current.data.datasets.forEach(ds => {
|
||||
ds.hidden = data.focusLabel ? ds.label !== data.focusLabel : false;
|
||||
});
|
||||
}
|
||||
|
||||
chart.current.options = options;
|
||||
|
||||
// Allow config changes before update
|
||||
|
|
@ -105,16 +111,6 @@ export function Chart({
|
|||
setLegendItems(chart.current.legend.legendItems);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
if (!chart.current) {
|
||||
createChart(data);
|
||||
} else {
|
||||
updateChart(data);
|
||||
}
|
||||
}
|
||||
}, [data, options]);
|
||||
|
||||
const handleLegendClick = (item: LegendItem) => {
|
||||
if (type === 'bar') {
|
||||
const { datasetIndex } = item;
|
||||
|
|
@ -136,6 +132,16 @@ export function Chart({
|
|||
setLegendItems(chart.current.legend.legendItems);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
if (!chart.current) {
|
||||
createChart(data);
|
||||
} else {
|
||||
updateChart(data);
|
||||
}
|
||||
}
|
||||
}, [data, options]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={classNames(styles.chart, className)}>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { GROUPED_DOMAINS } from '@/lib/constants';
|
||||
import { FAVICON_URL, GROUPED_DOMAINS } from '@/lib/constants';
|
||||
|
||||
function getHostName(url: string) {
|
||||
const match = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?([^:/\n?=]+)/im);
|
||||
|
|
@ -10,10 +10,10 @@ export function Favicon({ domain, ...props }) {
|
|||
return null;
|
||||
}
|
||||
|
||||
const url = process.env.faviconURL || FAVICON_URL;
|
||||
const hostName = domain ? getHostName(domain) : null;
|
||||
const src = hostName
|
||||
? `https://icons.duckduckgo.com/ip3/${GROUPED_DOMAINS[hostName]?.domain || hostName}.ico`
|
||||
: null;
|
||||
const domainName = GROUPED_DOMAINS[hostName]?.domain || hostName;
|
||||
const src = hostName ? url.replace(/\{\{\s*domain\s*}}/, domainName) : null;
|
||||
|
||||
return hostName ? <img src={src} width={16} height={16} alt="" {...props} /> : null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,13 +8,13 @@ export function useLogin(): {
|
|||
user: any;
|
||||
setUser: (data: any) => void;
|
||||
} & UseQueryResult {
|
||||
const { get, useQuery } = useApi();
|
||||
const { post, useQuery } = useApi();
|
||||
const user = useStore(selector);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['login'],
|
||||
queryFn: async () => {
|
||||
const data = await get('/auth/verify');
|
||||
const data = await post('/auth/verify');
|
||||
|
||||
setUser(data);
|
||||
|
||||
|
|
|
|||
|
|
@ -27,8 +27,8 @@ export function useFormat() {
|
|||
return countryNames[value] || value;
|
||||
};
|
||||
|
||||
const formatRegion = (value: string): string => {
|
||||
const [country] = value.split('-');
|
||||
const formatRegion = (value?: string): string => {
|
||||
const [country] = value?.split('-') || [];
|
||||
return regions[value] ? `${regions[value]}, ${countryNames[country]}` : value;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -131,6 +131,7 @@ export const labels = defineMessages({
|
|||
all: { id: 'label.all', defaultMessage: 'All' },
|
||||
session: { id: 'label.session', defaultMessage: 'Session' },
|
||||
sessions: { id: 'label.sessions', defaultMessage: 'Sessions' },
|
||||
distinctId: { id: 'label.distinct-id', defaultMessage: 'Distinct ID' },
|
||||
pageNotFound: { id: 'message.page-not-found', defaultMessage: 'Page not found' },
|
||||
activity: { id: 'label.activity', defaultMessage: 'Activity' },
|
||||
dismiss: { id: 'label.dismiss', defaultMessage: 'Dismiss' },
|
||||
|
|
@ -163,7 +164,13 @@ export const labels = defineMessages({
|
|||
id: 'label.revenue-description',
|
||||
defaultMessage: 'Look into your revenue data and how users are spending.',
|
||||
},
|
||||
attribution: { id: 'label.attribution', defaultMessage: 'Attribution' },
|
||||
attributionDescription: {
|
||||
id: 'label.attribution-description',
|
||||
defaultMessage: 'See how users engage with your marketing and what drives conversions.',
|
||||
},
|
||||
currency: { id: 'label.currency', defaultMessage: 'Currency' },
|
||||
model: { id: 'label.model', defaultMessage: 'Model' },
|
||||
url: { id: 'label.url', defaultMessage: 'URL' },
|
||||
urls: { id: 'label.urls', defaultMessage: 'URLs' },
|
||||
path: { id: 'label.path', defaultMessage: 'Path' },
|
||||
|
|
@ -257,6 +264,7 @@ export const labels = defineMessages({
|
|||
id: 'label.utm-description',
|
||||
defaultMessage: 'Track your campaigns through UTM parameters.',
|
||||
},
|
||||
conversionStep: { id: 'label.conversion-step', defaultMessage: 'Conversion Step' },
|
||||
steps: { id: 'label.steps', defaultMessage: 'Steps' },
|
||||
startStep: { id: 'label.start-step', defaultMessage: 'Start Step' },
|
||||
endStep: { id: 'label.end-step', defaultMessage: 'End Step' },
|
||||
|
|
@ -281,6 +289,11 @@ export const labels = defineMessages({
|
|||
firstSeen: { id: 'label.first-seen', defaultMessage: 'First seen' },
|
||||
properties: { id: 'label.properties', defaultMessage: 'Properties' },
|
||||
channels: { id: 'label.channels', defaultMessage: 'Channels' },
|
||||
sources: { id: 'label.sources', defaultMessage: 'Sources' },
|
||||
medium: { id: 'label.medium', defaultMessage: 'Medium' },
|
||||
campaigns: { id: 'label.campaigns', defaultMessage: 'Campaigns' },
|
||||
content: { id: 'label.content', defaultMessage: 'Content' },
|
||||
terms: { id: 'label.terms', defaultMessage: 'Terms' },
|
||||
direct: { id: 'label.direct', defaultMessage: 'Direct' },
|
||||
referral: { id: 'label.referral', defaultMessage: 'Referral' },
|
||||
affiliate: { id: 'label.affiliate', defaultMessage: 'Affiliate' },
|
||||
|
|
|
|||
|
|
@ -1,21 +1,23 @@
|
|||
import { useMemo, useState, useEffect } from 'react';
|
||||
import { colord } from 'colord';
|
||||
import BarChart from '@/components/charts/BarChart';
|
||||
import { useDateRange, useLocale, useWebsiteEventsSeries } from '@/components/hooks';
|
||||
import { renderDateLabels } from '@/lib/charts';
|
||||
import { CHART_COLORS } from '@/lib/constants';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
export interface EventsChartProps {
|
||||
websiteId: string;
|
||||
className?: string;
|
||||
focusLabel?: string;
|
||||
}
|
||||
|
||||
export function EventsChart({ websiteId, className }: EventsChartProps) {
|
||||
export function EventsChart({ websiteId, className, focusLabel }: EventsChartProps) {
|
||||
const {
|
||||
dateRange: { startDate, endDate, unit, value },
|
||||
} = useDateRange(websiteId);
|
||||
const { locale } = useLocale();
|
||||
const { data, isLoading } = useWebsiteEventsSeries(websiteId);
|
||||
const [label, setLabel] = useState<string>(focusLabel);
|
||||
|
||||
const chartData = useMemo(() => {
|
||||
if (!data) return [];
|
||||
|
|
@ -42,8 +44,15 @@ export function EventsChart({ websiteId, className }: EventsChartProps) {
|
|||
borderWidth: 1,
|
||||
};
|
||||
}),
|
||||
focusLabel,
|
||||
};
|
||||
}, [data, startDate, endDate, unit]);
|
||||
}, [data, startDate, endDate, unit, focusLabel]);
|
||||
|
||||
useEffect(() => {
|
||||
if (label !== focusLabel) {
|
||||
setLabel(focusLabel);
|
||||
}
|
||||
}, [focusLabel]);
|
||||
|
||||
return (
|
||||
<BarChart
|
||||
|
|
|
|||
|
|
@ -1,12 +1,28 @@
|
|||
import MetricsTable, { MetricsTableProps } from './MetricsTable';
|
||||
import { useMessages } from '@/components/hooks';
|
||||
|
||||
export function EventsTable(props: MetricsTableProps) {
|
||||
export interface EventsTableProps extends MetricsTableProps {
|
||||
onLabelClick?: (value: string) => void;
|
||||
}
|
||||
|
||||
export function EventsTable({ onLabelClick, ...props }: EventsTableProps) {
|
||||
const { formatMessage, labels } = useMessages();
|
||||
|
||||
function handleDataLoad(data: any) {
|
||||
const handleDataLoad = (data: any) => {
|
||||
props.onDataLoad?.(data);
|
||||
}
|
||||
};
|
||||
|
||||
const renderLabel = ({ x: label }) => {
|
||||
if (onLabelClick) {
|
||||
return (
|
||||
<div onClick={() => onLabelClick(label)} style={{ cursor: 'pointer' }}>
|
||||
{label}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return label;
|
||||
};
|
||||
|
||||
return (
|
||||
<MetricsTable
|
||||
|
|
@ -15,6 +31,7 @@ export function EventsTable(props: MetricsTableProps) {
|
|||
type="event"
|
||||
metric={formatMessage(labels.actions)}
|
||||
onDataLoad={handleDataLoad}
|
||||
renderLabel={renderLabel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { FixedSizeList } from 'react-window';
|
||||
import { useSpring, animated, config } from '@react-spring/web';
|
||||
import classNames from 'classnames';
|
||||
import Empty from '@/components/common/Empty';
|
||||
import { formatLongNumber } from '@/lib/format';
|
||||
import { useMessages } from '@/components/hooks';
|
||||
import styles from './ListTable.module.css';
|
||||
import { formatLongCurrency, formatLongNumber } from '@/lib/format';
|
||||
import { animated, config, useSpring } from '@react-spring/web';
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode } from 'react';
|
||||
import { FixedSizeList } from 'react-window';
|
||||
import styles from './ListTable.module.css';
|
||||
|
||||
const ITEM_SIZE = 30;
|
||||
|
||||
|
|
@ -20,6 +20,7 @@ export interface ListTableProps {
|
|||
virtualize?: boolean;
|
||||
showPercentage?: boolean;
|
||||
itemCount?: number;
|
||||
currency?: string;
|
||||
}
|
||||
|
||||
export function ListTable({
|
||||
|
|
@ -33,6 +34,7 @@ export function ListTable({
|
|||
virtualize = false,
|
||||
showPercentage = true,
|
||||
itemCount = 10,
|
||||
currency,
|
||||
}: ListTableProps) {
|
||||
const { formatMessage, labels } = useMessages();
|
||||
|
||||
|
|
@ -48,6 +50,7 @@ export function ListTable({
|
|||
animate={animate && !virtualize}
|
||||
showPercentage={showPercentage}
|
||||
change={renderChange ? renderChange(row, index) : null}
|
||||
currency={currency}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
|
@ -81,7 +84,15 @@ export function ListTable({
|
|||
);
|
||||
}
|
||||
|
||||
const AnimatedRow = ({ label, value = 0, percent, change, animate, showPercentage = true }) => {
|
||||
const AnimatedRow = ({
|
||||
label,
|
||||
value = 0,
|
||||
percent,
|
||||
change,
|
||||
animate,
|
||||
showPercentage = true,
|
||||
currency,
|
||||
}) => {
|
||||
const props = useSpring({
|
||||
width: percent,
|
||||
y: value,
|
||||
|
|
@ -95,7 +106,9 @@ const AnimatedRow = ({ label, value = 0, percent, change, animate, showPercentag
|
|||
<div className={styles.value}>
|
||||
{change}
|
||||
<animated.div className={styles.value} title={props?.y as any}>
|
||||
{props.y?.to(formatLongNumber)}
|
||||
{currency
|
||||
? props.y?.to(n => formatLongCurrency(n, currency))
|
||||
: props.y?.to(formatLongNumber)}
|
||||
</animated.div>
|
||||
</div>
|
||||
{showPercentage && (
|
||||
|
|
|
|||
|
|
@ -60,19 +60,24 @@ export function ReferrersTable({ allowFilter, ...props }: ReferrersTableProps) {
|
|||
);
|
||||
};
|
||||
|
||||
const getDomain = (x: string) => {
|
||||
for (const { domain, match } of GROUPED_DOMAINS) {
|
||||
if (Array.isArray(match) ? match.some(str => x.includes(str)) : x.includes(match)) {
|
||||
return domain;
|
||||
}
|
||||
}
|
||||
return '_other';
|
||||
};
|
||||
|
||||
const groupedFilter = (data: any[]) => {
|
||||
const groups = { _other: 0 };
|
||||
|
||||
for (const { x, y } of data) {
|
||||
for (const { domain, match } of GROUPED_DOMAINS) {
|
||||
if (Array.isArray(match) ? match.some(str => x.includes(str)) : x.includes(match)) {
|
||||
if (!groups[domain]) {
|
||||
groups[domain] = 0;
|
||||
}
|
||||
groups[domain] += +y;
|
||||
}
|
||||
const domain = getDomain(x);
|
||||
if (!groups[domain]) {
|
||||
groups[domain] = 0;
|
||||
}
|
||||
groups._other += +y;
|
||||
groups[domain] += +y;
|
||||
}
|
||||
|
||||
return Object.keys(groups)
|
||||
|
|
|
|||
|
|
@ -8,10 +8,13 @@
|
|||
"label.add-step": "Ajouter une étape",
|
||||
"label.add-website": "Ajouter un site",
|
||||
"label.admin": "Administrateur",
|
||||
"label.affiliate": "Affiliation",
|
||||
"label.after": "Après",
|
||||
"label.all": "Tout",
|
||||
"label.all-time": "Toutes les données",
|
||||
"label.analytics": "Analytics",
|
||||
"label.attribution": "Attribution",
|
||||
"label.attribution-description": "Découvrez comment les utilisateurs s'engagent avec votre marketing et ce qui génère des conversions.",
|
||||
"label.average": "Moyenne",
|
||||
"label.back": "Retour",
|
||||
"label.before": "Avant",
|
||||
|
|
@ -19,17 +22,21 @@
|
|||
"label.breakdown": "Répartition",
|
||||
"label.browser": "Navigateur",
|
||||
"label.browsers": "Navigateurs",
|
||||
"label.campaigns": "Campagnes",
|
||||
"label.cancel": "Annuler",
|
||||
"label.change-password": "Changer le mot de passe",
|
||||
"label.channels": "Canaux",
|
||||
"label.cities": "Villes",
|
||||
"label.city": "Ville",
|
||||
"label.clear-all": "Réinitialiser",
|
||||
"label.compare": "Compare",
|
||||
"label.compare": "Comparer",
|
||||
"label.confirm": "Confirmer",
|
||||
"label.confirm-password": "Confirmation du mot de passe",
|
||||
"label.contains": "Contient",
|
||||
"label.content": "Contenu",
|
||||
"label.continue": "Continuer",
|
||||
"label.count": "Count",
|
||||
"label.conversion-step": "Étape de conversion",
|
||||
"label.count": "Compte",
|
||||
"label.countries": "Pays",
|
||||
"label.country": "Pays",
|
||||
"label.create": "Créer",
|
||||
|
|
@ -37,8 +44,9 @@
|
|||
"label.create-team": "Créer une équipe",
|
||||
"label.create-user": "Créer un utilisateur",
|
||||
"label.created": "Créé",
|
||||
"label.created-by": "Crée par",
|
||||
"label.current": "Current",
|
||||
"label.created-by": "Créé par",
|
||||
"label.currency": "Devise",
|
||||
"label.current": "Actuel",
|
||||
"label.current-password": "Mot de passe actuel",
|
||||
"label.custom-range": "Période personnalisée",
|
||||
"label.dashboard": "Tableau de bord",
|
||||
|
|
@ -57,6 +65,7 @@
|
|||
"label.details": "Détails",
|
||||
"label.device": "Appareil",
|
||||
"label.devices": "Appareils",
|
||||
"label.direct": "Direct",
|
||||
"label.dismiss": "Ignorer",
|
||||
"label.does-not-contain": "Ne contient pas",
|
||||
"label.domain": "Domaine",
|
||||
|
|
@ -64,13 +73,14 @@
|
|||
"label.edit": "Modifier",
|
||||
"label.edit-dashboard": "Modifier le tableau de bord",
|
||||
"label.edit-member": "Modifier le membre",
|
||||
"label.email": "E-mail",
|
||||
"label.enable-share-url": "Activer l'URL de partage",
|
||||
"label.end-step": "End Step",
|
||||
"label.entry": "URL d'entrée",
|
||||
"label.end-step": "Étape de fin",
|
||||
"label.entry": "Chemin d'entrée",
|
||||
"label.event": "Évènement",
|
||||
"label.event-data": "Données d'évènements",
|
||||
"label.events": "Évènements",
|
||||
"label.exit": "Exit URL",
|
||||
"label.exit": "Chemin de sortie",
|
||||
"label.false": "Faux",
|
||||
"label.field": "Champ",
|
||||
"label.fields": "Champs",
|
||||
|
|
@ -80,31 +90,32 @@
|
|||
"label.filters": "Filtres",
|
||||
"label.first-seen": "Vu pour la première fois",
|
||||
"label.funnel": "Entonnoir",
|
||||
"label.funnel-description": "Suivi des conversions et des taux d'abandons.",
|
||||
"label.goal": "Goal",
|
||||
"label.goals": "Goals",
|
||||
"label.funnel-description": "Comprenez les taux de conversions et d'abandons des utilisateurs.",
|
||||
"label.goal": "Objectif",
|
||||
"label.goals": "Objectifs",
|
||||
"label.goals-description": "Suivez vos objectifs en matière de pages vues et d'événements.",
|
||||
"label.greater-than": "Supérieur à",
|
||||
"label.greater-than-equals": "Supérieur ou égal à",
|
||||
"label.host": "Host",
|
||||
"label.hosts": "Hosts",
|
||||
"label.grouped": "Groupé",
|
||||
"label.host": "Hôte",
|
||||
"label.hosts": "Hôtes",
|
||||
"label.insights": "Insights",
|
||||
"label.insights-description": "Analyse précise des données en utilisant des segments et des filtres.",
|
||||
"label.insights-description": "Analysez précisément vos données en utilisant des segments et des filtres.",
|
||||
"label.is": "Est",
|
||||
"label.is-not": "N'est pas",
|
||||
"label.is-not-set": "N'est pas défini",
|
||||
"label.is-set": "Est défini",
|
||||
"label.join": "Rejoindre",
|
||||
"label.join-team": "Rejoindre une équipe",
|
||||
"label.journey": "Journey",
|
||||
"label.journey-description": "Comprendre comment les utilisateurs naviguent sur votre site web.",
|
||||
"label.journey": "Parcours",
|
||||
"label.journey-description": "Comprennez comment les utilisateurs naviguent sur votre site.",
|
||||
"label.language": "Langue",
|
||||
"label.languages": "Langues",
|
||||
"label.laptop": "Portable",
|
||||
"label.last-days": "{x} derniers jours",
|
||||
"label.last-hours": "{x} dernières heures",
|
||||
"label.last-months": "{x} derniers mois",
|
||||
"label.last-seen": "Last seen",
|
||||
"label.last-seen": "Vu pour la dernière fois",
|
||||
"label.leave": "Quitter",
|
||||
"label.leave-team": "Quitter l'équipe",
|
||||
"label.less-than": "Inférieur à",
|
||||
|
|
@ -114,10 +125,12 @@
|
|||
"label.manage": "Gérer",
|
||||
"label.manager": "Manager",
|
||||
"label.max": "Max",
|
||||
"label.medium": "Support",
|
||||
"label.member": "Membre",
|
||||
"label.members": "Membres",
|
||||
"label.min": "Min",
|
||||
"label.mobile": "Téléphone",
|
||||
"label.model": "Modèle",
|
||||
"label.more": "Plus",
|
||||
"label.my-account": "Mon compte",
|
||||
"label.my-websites": "Mes sites",
|
||||
|
|
@ -126,16 +139,26 @@
|
|||
"label.none": "Aucun",
|
||||
"label.number-of-records": "{x} {x, plural, one {enregistrement} other {enregistrements}}",
|
||||
"label.ok": "OK",
|
||||
"label.organic-search": "Recherche organique",
|
||||
"label.organic-shopping": "E-commerce organique",
|
||||
"label.organic-social": "Réseau social organique",
|
||||
"label.organic-video": "Vidéo organique",
|
||||
"label.os": "OS",
|
||||
"label.other": "Autre",
|
||||
"label.overview": "Vue d'ensemble",
|
||||
"label.owner": "Propriétaire",
|
||||
"label.page-of": "Page {current} sur {total}",
|
||||
"label.page-views": "Pages vues",
|
||||
"label.pageTitle": "Titre de page",
|
||||
"label.pages": "Pages",
|
||||
"label.paid-ads": "Publicités payantes",
|
||||
"label.paid-search": "Recherche payante",
|
||||
"label.paid-shopping": "E-commerce payant",
|
||||
"label.paid-social": "Réseau social payant",
|
||||
"label.paid-video": "Vidéo payante",
|
||||
"label.password": "Mot de passe",
|
||||
"label.path": "Path",
|
||||
"label.paths": "Paths",
|
||||
"label.path": "Chemin",
|
||||
"label.paths": "Chemins",
|
||||
"label.powered-by": "Propulsé par {name}",
|
||||
"label.previous": "Précédent",
|
||||
"label.previous-period": "Période précédente",
|
||||
|
|
@ -147,6 +170,7 @@
|
|||
"label.query": "Requête",
|
||||
"label.query-parameters": "Paramètres de requête",
|
||||
"label.realtime": "Temps réel",
|
||||
"label.referral": "Référent",
|
||||
"label.referrer": "Site référent",
|
||||
"label.referrers": "Sites référents",
|
||||
"label.refresh": "Rafraîchir",
|
||||
|
|
@ -160,28 +184,32 @@
|
|||
"label.reset": "Réinitialiser",
|
||||
"label.reset-website": "Réinitialiser les statistiques",
|
||||
"label.retention": "Rétention",
|
||||
"label.retention-description": "Mesure de l'attractivité du site en visualisant les taux de visiteurs qui reviennent.",
|
||||
"label.revenue": "Revenue",
|
||||
"label.revenue-description": "Examinez vos revenus au fil du temps.",
|
||||
"label.revenue-property": "Propriétés des revenues",
|
||||
"label.retention-description": "Mesurez l'attractivité de votre site en suivant la fréquence de retour des utilisateurs.",
|
||||
"label.revenue": "Recettes",
|
||||
"label.revenue-description": "Examinez vos recettes et comment dépensent vos utilisateurs.",
|
||||
"label.role": "Rôle",
|
||||
"label.run-query": "Éxécuter la requête",
|
||||
"label.run-query": "Exécuter la requête",
|
||||
"label.save": "Enregistrer",
|
||||
"label.screens": "Résolutions d'écran",
|
||||
"label.search": "Rechercher",
|
||||
"label.select": "Selectionner",
|
||||
"label.select": "Sélectionner",
|
||||
"label.select-date": "Choisir une période",
|
||||
"label.select-role": "Choisir un rôle",
|
||||
"label.select-website": "Choisir un site",
|
||||
"label.session": "Session",
|
||||
"label.session-data": "Session data",
|
||||
"label.sessions": "Sessions",
|
||||
"label.settings": "Paramètres",
|
||||
"label.share-url": "URL de partage",
|
||||
"label.single-day": "Journée",
|
||||
"label.start-step": "Etape de démarrage",
|
||||
"label.sms": "SMS",
|
||||
"label.sources": "Sources",
|
||||
"label.start-step": "Étape de départ",
|
||||
"label.steps": "Étapes",
|
||||
"label.sum": "Somme",
|
||||
"label.tablet": "Tablette",
|
||||
"label.tag": "Tag",
|
||||
"label.tags": "Tags",
|
||||
"label.team": "Équipe",
|
||||
"label.team-id": "ID d'équipe",
|
||||
"label.team-manager": "Manager de l'équipe",
|
||||
|
|
@ -191,6 +219,7 @@
|
|||
"label.team-view-only": "Vue d'équipe uniquement",
|
||||
"label.team-websites": "Sites d'équipes",
|
||||
"label.teams": "Équipes",
|
||||
"label.terms": "Mots clés",
|
||||
"label.theme": "Thème",
|
||||
"label.this-month": "Ce mois",
|
||||
"label.this-week": "Cette semaine",
|
||||
|
|
@ -216,18 +245,17 @@
|
|||
"label.url": "URL",
|
||||
"label.urls": "URLs",
|
||||
"label.user": "Utilisateur",
|
||||
"label.user-property": "Propriétés d'utilisateurs",
|
||||
"label.username": "Nom d'utilisateur",
|
||||
"label.users": "Utilisateurs",
|
||||
"label.utm": "UTM",
|
||||
"label.utm-description": "Suivi de campagnes via les paramètres UTM.",
|
||||
"label.utm-description": "Suivez vos campagnes via les paramètres UTM.",
|
||||
"label.value": "Valeur",
|
||||
"label.view": "Voir",
|
||||
"label.view-details": "Voir les détails",
|
||||
"label.view-only": "Consultation",
|
||||
"label.views": "Vues",
|
||||
"label.views-per-visit": "Vues par visite",
|
||||
"label.visit-duration": "Temps de visite moyen",
|
||||
"label.visit-duration": "Temps de visite",
|
||||
"label.visitors": "Visiteurs",
|
||||
"label.visits": "Visites",
|
||||
"label.website": "Site",
|
||||
|
|
@ -237,7 +265,7 @@
|
|||
"label.yesterday": "Hier",
|
||||
"message.action-confirmation": "Taper {confirmation} ci-dessous pour confirmer.",
|
||||
"message.active-users": "{x} {x, plural, one {visiteur} other {visiteurs}} actuellement",
|
||||
"message.collected-data": "Collected data",
|
||||
"message.collected-data": "Donnée collectée",
|
||||
"message.confirm-delete": "Êtes-vous sûr de vouloir supprimer {target} ?",
|
||||
"message.confirm-leave": "Êtes-vous sûr de vouloir quitter {target} ?",
|
||||
"message.confirm-remove": "Êtes-vous sûr de vouloir retirer {target} ?",
|
||||
|
|
|
|||
|
|
@ -20,7 +20,8 @@
|
|||
"label.browser": "浏览器",
|
||||
"label.browsers": "浏览器",
|
||||
"label.cancel": "取消",
|
||||
"label.change-password": "更新密码",
|
||||
"label.change-password": "修改密码",
|
||||
"label.channels": "渠道",
|
||||
"label.cities": "市/县",
|
||||
"label.city": "市/县",
|
||||
"label.clear-all": "清除全部",
|
||||
|
|
@ -38,10 +39,10 @@
|
|||
"label.create-user": "创建用户",
|
||||
"label.created": "已创建",
|
||||
"label.created-by": "创建者",
|
||||
"label.current": "目前",
|
||||
"label.current-password": "目前密码",
|
||||
"label.current": "当前",
|
||||
"label.current-password": "当前密码",
|
||||
"label.custom-range": "自定义时间段",
|
||||
"label.dashboard": "仪表板",
|
||||
"label.dashboard": "仪表盘",
|
||||
"label.data": "统计数据",
|
||||
"label.date": "日期",
|
||||
"label.date-range": "时间段",
|
||||
|
|
@ -62,7 +63,7 @@
|
|||
"label.domain": "域名",
|
||||
"label.dropoff": "丢弃",
|
||||
"label.edit": "编辑",
|
||||
"label.edit-dashboard": "编辑仪表板",
|
||||
"label.edit-dashboard": "编辑仪表盘",
|
||||
"label.edit-member": "编辑成员",
|
||||
"label.enable-share-url": "启用共享链接",
|
||||
"label.end-step": "结束步骤",
|
||||
|
|
@ -80,7 +81,7 @@
|
|||
"label.filters": "筛选",
|
||||
"label.first-seen": "首次出现",
|
||||
"label.funnel": "分析",
|
||||
"label.funnel-description": "了解用户的转换率和退出率。",
|
||||
"label.funnel-description": "了解用户的转化率和跳出率。",
|
||||
"label.goal": "目标",
|
||||
"label.goals": "目标",
|
||||
"label.goals-description": "跟踪页面浏览量和事件的目标。",
|
||||
|
|
@ -141,7 +142,7 @@
|
|||
"label.previous-period": "上一时期",
|
||||
"label.previous-year": "上一年",
|
||||
"label.profile": "个人资料",
|
||||
"label.properties": "Properties",
|
||||
"label.properties": "属性",
|
||||
"label.property": "属性",
|
||||
"label.queries": "查询",
|
||||
"label.query": "查询",
|
||||
|
|
@ -160,9 +161,9 @@
|
|||
"label.reset": "重置",
|
||||
"label.reset-website": "重置统计数据",
|
||||
"label.retention": "保留",
|
||||
"label.retention-description": "通过跟踪用户返回的频率来衡量网站的用户粘性。",
|
||||
"label.retention-description": "通过追踪用户回访频率来衡量您网站的用户粘性。",
|
||||
"label.revenue": "收入",
|
||||
"label.revenue-description": "查看您的收入随时间的变化。",
|
||||
"label.revenue-description": "查看随时间变化的收入数据。",
|
||||
"label.revenue-property": "收入值",
|
||||
"label.role": "角色",
|
||||
"label.run-query": "查询",
|
||||
|
|
@ -170,7 +171,7 @@
|
|||
"label.screens": "屏幕尺寸",
|
||||
"label.search": "搜索",
|
||||
"label.select": "选择",
|
||||
"label.select-date": "选择数据",
|
||||
"label.select-date": "选择日期",
|
||||
"label.select-role": "选择角色",
|
||||
"label.select-website": "选择网站",
|
||||
"label.session": "Session",
|
||||
|
|
@ -184,7 +185,7 @@
|
|||
"label.tablet": "平板",
|
||||
"label.team": "团队",
|
||||
"label.team-id": "团队 ID",
|
||||
"label.team-manager": "团队管理者",
|
||||
"label.team-manager": "团队管理员",
|
||||
"label.team-member": "团队成员",
|
||||
"label.team-name": "团队名称",
|
||||
"label.team-owner": "团队所有者",
|
||||
|
|
@ -220,14 +221,14 @@
|
|||
"label.username": "用户名",
|
||||
"label.users": "用户",
|
||||
"label.utm": "UTM",
|
||||
"label.utm-description": "通过UTM参数追踪您的广告活动。",
|
||||
"label.utm-description": "通过 UTM 参数追踪您的广告活动。",
|
||||
"label.value": "值",
|
||||
"label.view": "查看",
|
||||
"label.view-details": "查看更多",
|
||||
"label.view-only": "仅浏览量",
|
||||
"label.view-only": "仅浏览",
|
||||
"label.views": "浏览量",
|
||||
"label.views-per-visit": "每次访问的浏览量",
|
||||
"label.visit-duration": "平均访问时间",
|
||||
"label.visit-duration": "平均访问时长",
|
||||
"label.visitors": "访客",
|
||||
"label.visits": "访问次数",
|
||||
"label.website": "网站",
|
||||
|
|
@ -235,41 +236,41 @@
|
|||
"label.websites": "网站",
|
||||
"label.window": "窗口",
|
||||
"label.yesterday": "昨天",
|
||||
"message.action-confirmation": "在下面的框中输入 {confirmation} 以确认。",
|
||||
"message.active-users": "当前在线 {x} 人",
|
||||
"message.action-confirmation": "请在下方输入框中输入 {confirmation} 以确认操作。",
|
||||
"message.active-users": "当前在线 {x} 位访客",
|
||||
"message.collected-data": "已收集的数据",
|
||||
"message.confirm-delete": "你确定要删除 {target} 吗?",
|
||||
"message.confirm-leave": "你确定要离开 {target} 吗?",
|
||||
"message.confirm-remove": "您确定要移除 {target} ?",
|
||||
"message.confirm-reset": "您确定要重置 {target} 的数据吗?",
|
||||
"message.delete-team-warning": "删除团队也会删除所有团队的网站。",
|
||||
"message.delete-team-warning": "删除团队也会删除所有团队网站。",
|
||||
"message.delete-website-warning": "所有相关数据将会被删除。",
|
||||
"message.error": "出现错误。",
|
||||
"message.error": "发生错误。",
|
||||
"message.event-log": "{url} 上的 {event}",
|
||||
"message.go-to-settings": "去设置",
|
||||
"message.incorrect-username-password": "用户名或密码不正确。",
|
||||
"message.invalid-domain": "无效域名",
|
||||
"message.min-password-length": "密码最短长度为 {n} 个字符",
|
||||
"message.new-version-available": "Umami 的新版本 {version} 已推出!",
|
||||
"message.no-data-available": "无可用数据。",
|
||||
"message.new-version-available": "Umami 新版本 {version} 已发布!",
|
||||
"message.no-data-available": "暂无数据。",
|
||||
"message.no-event-data": "无可用事件。",
|
||||
"message.no-match-password": "密码不一致",
|
||||
"message.no-results-found": "没有找到任何结果。",
|
||||
"message.no-team-websites": "这个团队没有任何网站。",
|
||||
"message.no-teams": "你还没有创建任何团队。",
|
||||
"message.no-users": "没有任何用户。",
|
||||
"message.no-results-found": "未找到结果。",
|
||||
"message.no-team-websites": "该团队暂无网站。",
|
||||
"message.no-teams": "您尚未创建任何团队。",
|
||||
"message.no-users": "暂无用户。",
|
||||
"message.no-websites-configured": "你还没有设置任何网站。",
|
||||
"message.page-not-found": "网页未找到。",
|
||||
"message.reset-website": "如果确定重置该网站,请在下面的输入框中输入 {confirmation} 进行二次确认。",
|
||||
"message.reset-website-warning": "本网站的所有统计数据将被删除,但您的跟踪代码将保持不变。",
|
||||
"message.page-not-found": "页面未找到。",
|
||||
"message.reset-website": "如确定要重置该网站,请在下面输入 {confirmation} 以确认。",
|
||||
"message.reset-website-warning": "此网站的所有统计数据将被删除,但您的跟踪代码将保持不变。",
|
||||
"message.saved": "保存成功。",
|
||||
"message.share-url": "这是 {target} 的共享链接。",
|
||||
"message.team-already-member": "你已经是该团队的成员。",
|
||||
"message.team-already-member": "你已是该团队的成员。",
|
||||
"message.team-not-found": "未找到团队。",
|
||||
"message.team-websites-info": "团队中的任何人都可查看网站。",
|
||||
"message.team-websites-info": "团队成员均可查看网站数据。",
|
||||
"message.tracking-code": "跟踪代码",
|
||||
"message.transfer-team-website-to-user": "将该网站转入您的账户?",
|
||||
"message.transfer-user-website-to-team": "选择要将该网站转移到哪个团队。",
|
||||
"message.transfer-team-website-to-user": "将此网站转移到您的账户?",
|
||||
"message.transfer-user-website-to-team": "选择要转移此网站的团队。",
|
||||
"message.transfer-website": "将网站所有权转移到您的账户或其他团队。",
|
||||
"message.triggered-event": "触发事件",
|
||||
"message.user-deleted": "用户已删除。",
|
||||
|
|
|
|||
41
src/lib/__tests__/charts.test.ts
Normal file
41
src/lib/__tests__/charts.test.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { renderNumberLabels } from '../charts';
|
||||
|
||||
// test for renderNumberLabels
|
||||
|
||||
describe('renderNumberLabels', () => {
|
||||
test.each([
|
||||
['1000000', '1.0m'],
|
||||
['2500000', '2.5m'],
|
||||
])("formats numbers ≥ 1 million as 'Xm' (%s → %s)", (input, expected) => {
|
||||
expect(renderNumberLabels(input)).toBe(expected);
|
||||
});
|
||||
|
||||
test.each([['150000', '150k']])("formats numbers ≥ 100K as 'Xk' (%s → %s)", (input, expected) => {
|
||||
expect(renderNumberLabels(input)).toBe(expected);
|
||||
});
|
||||
|
||||
test.each([['12500', '12.5k']])(
|
||||
"formats numbers ≥ 10K as 'X.Xk' (%s → %s)",
|
||||
(input, expected) => {
|
||||
expect(renderNumberLabels(input)).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
test.each([['1500', '1.50k']])("formats numbers ≥ 1K as 'X.XXk' (%s → %s)", (input, expected) => {
|
||||
expect(renderNumberLabels(input)).toBe(expected);
|
||||
});
|
||||
|
||||
test.each([['999', '999']])(
|
||||
'calls formatNumber for values < 1000 (%s → %s)',
|
||||
(input, expected) => {
|
||||
expect(renderNumberLabels(input)).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
['0', '0'],
|
||||
['-5000', '-5000'],
|
||||
])('handles edge cases correctly (%s → %s)', (input, expected) => {
|
||||
expect(renderNumberLabels(input)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
|
@ -11,15 +11,15 @@ export function renderDateLabels(unit: string, locale: string) {
|
|||
|
||||
switch (unit) {
|
||||
case 'minute':
|
||||
return formatDate(d, 'h:mm', locale);
|
||||
return formatDate(d, 'p', locale).split(' ')[0];
|
||||
case 'hour':
|
||||
return formatDate(d, 'p', locale);
|
||||
case 'day':
|
||||
return formatDate(d, 'MMM d', locale);
|
||||
return formatDate(d, 'PP', locale).replace(/\W*20\d{2}\W*/, ''); // Remove year
|
||||
case 'month':
|
||||
return formatDate(d, 'MMM', locale);
|
||||
case 'year':
|
||||
return formatDate(d, 'YYY', locale);
|
||||
return formatDate(d, 'yyyy', locale);
|
||||
default:
|
||||
return label;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
/* eslint-disable no-unused-vars */
|
||||
export const CURRENT_VERSION = process.env.currentVersion;
|
||||
export const AUTH_TOKEN = 'umami.auth';
|
||||
export const LOCALE_CONFIG = 'umami.locale';
|
||||
|
|
@ -12,6 +11,7 @@ export const HOMEPAGE_URL = 'https://umami.is';
|
|||
export const REPO_URL = 'https://github.com/umami-software/umami';
|
||||
export const UPDATES_URL = 'https://api.umami.is/v1/updates';
|
||||
export const TELEMETRY_PIXEL = 'https://i.umami.is/a.png';
|
||||
export const FAVICON_URL = 'https://icons.duckduckgo.com/ip3/{{domain}}.ico';
|
||||
|
||||
export const DEFAULT_LOCALE = process.env.defaultLocale || 'en-US';
|
||||
export const DEFAULT_THEME = 'light';
|
||||
|
|
@ -42,8 +42,8 @@ export const SESSION_COLUMNS = [
|
|||
'screen',
|
||||
'language',
|
||||
'country',
|
||||
'region',
|
||||
'city',
|
||||
'region',
|
||||
'host',
|
||||
];
|
||||
|
||||
|
|
@ -59,7 +59,7 @@ export const FILTER_COLUMNS = {
|
|||
browser: 'browser',
|
||||
device: 'device',
|
||||
country: 'country',
|
||||
region: 'subdivision1',
|
||||
region: 'region',
|
||||
city: 'city',
|
||||
language: 'language',
|
||||
event: 'event_name',
|
||||
|
|
@ -124,6 +124,7 @@ export const REPORT_TYPES = {
|
|||
utm: 'utm',
|
||||
journey: 'journey',
|
||||
revenue: 'revenue',
|
||||
attribution: 'attribution',
|
||||
} as const;
|
||||
|
||||
export const REPORT_PARAMETERS = {
|
||||
|
|
|
|||
|
|
@ -96,12 +96,12 @@ export async function getLocation(ip: string = '', headers: Headers, hasPayloadI
|
|||
// Cloudflare headers
|
||||
if (headers.get('cf-ipcountry')) {
|
||||
const country = decodeHeader(headers.get('cf-ipcountry'));
|
||||
const subdivision1 = decodeHeader(headers.get('cf-region-code'));
|
||||
const region = decodeHeader(headers.get('cf-region-code'));
|
||||
const city = decodeHeader(headers.get('cf-ipcity'));
|
||||
|
||||
return {
|
||||
country,
|
||||
subdivision1: getRegionCode(country, subdivision1),
|
||||
region: getRegionCode(country, region),
|
||||
city,
|
||||
};
|
||||
}
|
||||
|
|
@ -109,12 +109,12 @@ export async function getLocation(ip: string = '', headers: Headers, hasPayloadI
|
|||
// Vercel headers
|
||||
if (headers.get('x-vercel-ip-country')) {
|
||||
const country = decodeHeader(headers.get('x-vercel-ip-country'));
|
||||
const subdivision1 = decodeHeader(headers.get('x-vercel-ip-country-region'));
|
||||
const region = decodeHeader(headers.get('x-vercel-ip-country-region'));
|
||||
const city = decodeHeader(headers.get('x-vercel-ip-city'));
|
||||
|
||||
return {
|
||||
country,
|
||||
subdivision1: getRegionCode(country, subdivision1),
|
||||
region: getRegionCode(country, region),
|
||||
city,
|
||||
};
|
||||
}
|
||||
|
|
@ -131,14 +131,12 @@ export async function getLocation(ip: string = '', headers: Headers, hasPayloadI
|
|||
|
||||
if (result) {
|
||||
const country = result.country?.iso_code ?? result?.registered_country?.iso_code;
|
||||
const subdivision1 = result.subdivisions?.[0]?.iso_code;
|
||||
const subdivision2 = result.subdivisions?.[1]?.names?.en;
|
||||
const region = result.subdivisions?.[0]?.iso_code;
|
||||
const city = result.city?.names?.en;
|
||||
|
||||
return {
|
||||
country,
|
||||
subdivision1: getRegionCode(country, subdivision1),
|
||||
subdivision2,
|
||||
region: getRegionCode(country, region),
|
||||
city,
|
||||
};
|
||||
}
|
||||
|
|
@ -149,14 +147,13 @@ export async function getClientInfo(request: Request, payload: Record<string, an
|
|||
const ip = payload?.ip || getIpAddress(request.headers);
|
||||
const location = await getLocation(ip, request.headers, !!payload?.ip);
|
||||
const country = location?.country;
|
||||
const subdivision1 = location?.subdivision1;
|
||||
const subdivision2 = location?.subdivision2;
|
||||
const region = location?.region;
|
||||
const city = location?.city;
|
||||
const browser = browserName(userAgent);
|
||||
const os = detectOS(userAgent) as string;
|
||||
const device = getDevice(payload?.screen, os);
|
||||
|
||||
return { userAgent, browser, os, ip, country, subdivision1, subdivision2, city, device };
|
||||
return { userAgent, browser, os, ip, country, region, city, device };
|
||||
}
|
||||
|
||||
export function hasBlockedIp(clientIp: string) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import debug from 'debug';
|
||||
import prisma from '@umami/prisma-client';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { readReplicas } from '@prisma/extension-read-replicas';
|
||||
import { formatInTimeZone } from 'date-fns-tz';
|
||||
import { MYSQL, POSTGRESQL, getDatabaseType } from '@/lib/db';
|
||||
import { SESSION_COLUMNS, OPERATORS, DEFAULT_PAGE_SIZE } from './constants';
|
||||
|
|
@ -10,6 +11,16 @@ import { filtersToArray } from './params';
|
|||
|
||||
const log = debug('umami:prisma');
|
||||
|
||||
const PRISMA = 'prisma';
|
||||
const PRISMA_LOG_OPTIONS = {
|
||||
log: [
|
||||
{
|
||||
emit: 'event',
|
||||
level: 'query',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const MYSQL_DATE_FORMATS = {
|
||||
minute: '%Y-%m-%dT%H:%i:00',
|
||||
hour: '%Y-%m-%d %H:00:00',
|
||||
|
|
@ -151,7 +162,7 @@ function getFilterQuery(filters: QueryFilters = {}, options: QueryOptions = {}):
|
|||
|
||||
if (name === 'referrer') {
|
||||
arr.push(
|
||||
`and (website_event.referrer_domain != session.hostname or website_event.referrer_domain is null)`,
|
||||
`and (website_event.referrer_domain != website_event.hostname or website_event.referrer_domain is null)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -234,14 +245,16 @@ async function rawQuery(sql: string, data: object): Promise<any> {
|
|||
return db === MYSQL ? '?' : `$${params.length}${type ?? ''}`;
|
||||
});
|
||||
|
||||
return prisma.rawQuery(query, params);
|
||||
return process.env.DATABASE_REPLICA_URL
|
||||
? client.$replica().$queryRawUnsafe(query, ...params)
|
||||
: client.$queryRawUnsafe(query, ...params);
|
||||
}
|
||||
|
||||
async function pagedQuery<T>(model: string, criteria: T, pageParams: PageParams) {
|
||||
const { page = 1, pageSize, orderBy, sortDescending = false } = pageParams || {};
|
||||
const size = +pageSize || DEFAULT_PAGE_SIZE;
|
||||
|
||||
const data = await prisma.client[model].findMany({
|
||||
const data = await client[model].findMany({
|
||||
...criteria,
|
||||
...{
|
||||
...(size > 0 && { take: +size, skip: +size * (+page - 1) }),
|
||||
|
|
@ -255,7 +268,7 @@ async function pagedQuery<T>(model: string, criteria: T, pageParams: PageParams)
|
|||
},
|
||||
});
|
||||
|
||||
const count = await prisma.client[model].count({ where: (criteria as any).where });
|
||||
const count = await client[model].count({ where: (criteria as any).where });
|
||||
|
||||
return { data, count, page: +page, pageSize: size, orderBy };
|
||||
}
|
||||
|
|
@ -323,8 +336,55 @@ function getSearchParameters(query: string, filters: { [key: string]: any }[]) {
|
|||
};
|
||||
}
|
||||
|
||||
function transaction(input: any, options?: any) {
|
||||
return client.$transaction(input, options);
|
||||
}
|
||||
|
||||
function getClient(params?: {
|
||||
logQuery?: boolean;
|
||||
queryLogger?: () => void;
|
||||
replicaUrl?: string;
|
||||
options?: any;
|
||||
}): PrismaClient {
|
||||
const {
|
||||
logQuery = !!process.env.LOG_QUERY,
|
||||
queryLogger,
|
||||
replicaUrl = process.env.DATABASE_REPLICA_URL,
|
||||
options,
|
||||
} = params || {};
|
||||
|
||||
const prisma = new PrismaClient({
|
||||
errorFormat: 'pretty',
|
||||
...(logQuery && PRISMA_LOG_OPTIONS),
|
||||
...options,
|
||||
});
|
||||
|
||||
if (replicaUrl) {
|
||||
prisma.$extends(
|
||||
readReplicas({
|
||||
url: replicaUrl,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (logQuery) {
|
||||
prisma.$on('query' as never, queryLogger || log);
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
global[PRISMA] = prisma;
|
||||
}
|
||||
|
||||
log('Prisma initialized');
|
||||
|
||||
return prisma;
|
||||
}
|
||||
|
||||
const client = global[PRISMA] || getClient();
|
||||
|
||||
export default {
|
||||
...prisma,
|
||||
client,
|
||||
transaction,
|
||||
getAddIntervalQuery,
|
||||
getCastColumnQuery,
|
||||
getDayDiffQuery,
|
||||
|
|
|
|||
|
|
@ -3,13 +3,13 @@ import { REDIS, UmamiRedisClient } from '@umami/redis-client';
|
|||
const enabled = !!process.env.REDIS_URL;
|
||||
|
||||
function getClient() {
|
||||
const client = new UmamiRedisClient(process.env.REDIS_URL);
|
||||
const redis = new UmamiRedisClient(process.env.REDIS_URL);
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
global[REDIS] = client;
|
||||
global[REDIS] = redis;
|
||||
}
|
||||
|
||||
return client;
|
||||
return redis;
|
||||
}
|
||||
|
||||
const client = global[REDIS] || getClient();
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ export const reportTypeParam = z.enum([
|
|||
'goals',
|
||||
'journey',
|
||||
'revenue',
|
||||
'attribution',
|
||||
]);
|
||||
|
||||
export const reportParms = {
|
||||
|
|
|
|||
|
|
@ -197,8 +197,7 @@ export interface SessionData {
|
|||
screen: string;
|
||||
language: string;
|
||||
country: string;
|
||||
subdivision1: string;
|
||||
subdivision2: string;
|
||||
region: string;
|
||||
city: string;
|
||||
ip?: string;
|
||||
userAgent?: string;
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ async function relationalQuery(websiteId: string, filters: QueryFilters, pagePar
|
|||
limit 1000)
|
||||
select * from events
|
||||
`,
|
||||
{ ...params, query: `%${search}%` },
|
||||
{ ...params, search: `%${search}%` },
|
||||
pageParams,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,10 +12,21 @@ export async function saveEvent(args: {
|
|||
visitId: string;
|
||||
urlPath: string;
|
||||
urlQuery?: string;
|
||||
utmSource?: string;
|
||||
utmMedium?: string;
|
||||
utmCampaign?: string;
|
||||
utmContent?: string;
|
||||
utmTerm?: string;
|
||||
referrerPath?: string;
|
||||
referrerQuery?: string;
|
||||
referrerDomain?: string;
|
||||
pageTitle?: string;
|
||||
gclid?: string;
|
||||
fbclid?: string;
|
||||
msclkid?: string;
|
||||
ttclid?: string;
|
||||
lifatid?: string;
|
||||
twclid?: string;
|
||||
eventName?: string;
|
||||
eventData?: any;
|
||||
hostname?: string;
|
||||
|
|
@ -25,10 +36,10 @@ export async function saveEvent(args: {
|
|||
screen?: string;
|
||||
language?: string;
|
||||
country?: string;
|
||||
subdivision1?: string;
|
||||
subdivision2?: string;
|
||||
region?: string;
|
||||
city?: string;
|
||||
tag?: string;
|
||||
distinctId?: string;
|
||||
createdAt?: Date;
|
||||
}) {
|
||||
return runQuery({
|
||||
|
|
@ -43,13 +54,25 @@ async function relationalQuery(data: {
|
|||
visitId: string;
|
||||
urlPath: string;
|
||||
urlQuery?: string;
|
||||
utmSource?: string;
|
||||
utmMedium?: string;
|
||||
utmCampaign?: string;
|
||||
utmContent?: string;
|
||||
utmTerm?: string;
|
||||
referrerPath?: string;
|
||||
referrerQuery?: string;
|
||||
referrerDomain?: string;
|
||||
gclid?: string;
|
||||
fbclid?: string;
|
||||
msclkid?: string;
|
||||
ttclid?: string;
|
||||
lifatid?: string;
|
||||
twclid?: string;
|
||||
pageTitle?: string;
|
||||
eventName?: string;
|
||||
eventData?: any;
|
||||
tag?: string;
|
||||
hostname?: string;
|
||||
createdAt?: Date;
|
||||
}) {
|
||||
const {
|
||||
|
|
@ -58,13 +81,25 @@ async function relationalQuery(data: {
|
|||
visitId,
|
||||
urlPath,
|
||||
urlQuery,
|
||||
utmSource,
|
||||
utmMedium,
|
||||
utmCampaign,
|
||||
utmContent,
|
||||
utmTerm,
|
||||
referrerPath,
|
||||
referrerQuery,
|
||||
referrerDomain,
|
||||
eventName,
|
||||
eventData,
|
||||
pageTitle,
|
||||
gclid,
|
||||
fbclid,
|
||||
msclkid,
|
||||
ttclid,
|
||||
lifatid,
|
||||
twclid,
|
||||
tag,
|
||||
hostname,
|
||||
createdAt,
|
||||
} = data;
|
||||
const websiteEventId = uuid();
|
||||
|
|
@ -77,13 +112,25 @@ async function relationalQuery(data: {
|
|||
visitId,
|
||||
urlPath: urlPath?.substring(0, URL_LENGTH),
|
||||
urlQuery: urlQuery?.substring(0, URL_LENGTH),
|
||||
utmSource,
|
||||
utmMedium,
|
||||
utmCampaign,
|
||||
utmContent,
|
||||
utmTerm,
|
||||
referrerPath: referrerPath?.substring(0, URL_LENGTH),
|
||||
referrerQuery: referrerQuery?.substring(0, URL_LENGTH),
|
||||
referrerDomain: referrerDomain?.substring(0, URL_LENGTH),
|
||||
pageTitle: pageTitle?.substring(0, PAGE_TITLE_LENGTH),
|
||||
gclid,
|
||||
fbclid,
|
||||
msclkid,
|
||||
ttclid,
|
||||
lifatid,
|
||||
twclid,
|
||||
eventType: eventName ? EVENT_TYPE.customEvent : EVENT_TYPE.pageView,
|
||||
eventName: eventName ? eventName?.substring(0, EVENT_NAME_LENGTH) : null,
|
||||
tag,
|
||||
hostname,
|
||||
createdAt,
|
||||
},
|
||||
});
|
||||
|
|
@ -109,10 +156,21 @@ async function clickhouseQuery(data: {
|
|||
visitId: string;
|
||||
urlPath: string;
|
||||
urlQuery?: string;
|
||||
utmSource?: string;
|
||||
utmMedium?: string;
|
||||
utmCampaign?: string;
|
||||
utmContent?: string;
|
||||
utmTerm?: string;
|
||||
referrerPath?: string;
|
||||
referrerQuery?: string;
|
||||
referrerDomain?: string;
|
||||
pageTitle?: string;
|
||||
gclid?: string;
|
||||
fbclid?: string;
|
||||
msclkid?: string;
|
||||
ttclid?: string;
|
||||
lifatid?: string;
|
||||
twclid?: string;
|
||||
eventName?: string;
|
||||
eventData?: any;
|
||||
hostname?: string;
|
||||
|
|
@ -122,10 +180,10 @@ async function clickhouseQuery(data: {
|
|||
screen?: string;
|
||||
language?: string;
|
||||
country?: string;
|
||||
subdivision1?: string;
|
||||
subdivision2?: string;
|
||||
region?: string;
|
||||
city?: string;
|
||||
tag?: string;
|
||||
distinctId?: string;
|
||||
createdAt?: Date;
|
||||
}) {
|
||||
const {
|
||||
|
|
@ -134,17 +192,28 @@ async function clickhouseQuery(data: {
|
|||
visitId,
|
||||
urlPath,
|
||||
urlQuery,
|
||||
utmSource,
|
||||
utmMedium,
|
||||
utmCampaign,
|
||||
utmContent,
|
||||
utmTerm,
|
||||
referrerPath,
|
||||
referrerQuery,
|
||||
referrerDomain,
|
||||
gclid,
|
||||
fbclid,
|
||||
msclkid,
|
||||
ttclid,
|
||||
lifatid,
|
||||
twclid,
|
||||
pageTitle,
|
||||
eventName,
|
||||
eventData,
|
||||
country,
|
||||
subdivision1,
|
||||
subdivision2,
|
||||
region,
|
||||
city,
|
||||
tag,
|
||||
distinctId,
|
||||
createdAt,
|
||||
...args
|
||||
} = data;
|
||||
|
|
@ -159,23 +228,29 @@ async function clickhouseQuery(data: {
|
|||
visit_id: visitId,
|
||||
event_id: eventId,
|
||||
country: country,
|
||||
subdivision1:
|
||||
country && subdivision1
|
||||
? subdivision1.includes('-')
|
||||
? subdivision1
|
||||
: `${country}-${subdivision1}`
|
||||
: null,
|
||||
subdivision2: subdivision2,
|
||||
region: country && region ? (region.includes('-') ? region : `${country}-${region}`) : null,
|
||||
city: city,
|
||||
url_path: urlPath?.substring(0, URL_LENGTH),
|
||||
url_query: urlQuery?.substring(0, URL_LENGTH),
|
||||
utm_source: utmSource,
|
||||
utm_medium: utmMedium,
|
||||
utm_campaign: utmCampaign,
|
||||
utm_content: utmContent,
|
||||
utm_term: utmTerm,
|
||||
referrer_path: referrerPath?.substring(0, URL_LENGTH),
|
||||
referrer_query: referrerQuery?.substring(0, URL_LENGTH),
|
||||
referrer_domain: referrerDomain?.substring(0, URL_LENGTH),
|
||||
page_title: pageTitle?.substring(0, PAGE_TITLE_LENGTH),
|
||||
gclid: gclid,
|
||||
fbclid: fbclid,
|
||||
msclkid: msclkid,
|
||||
ttclid: ttclid,
|
||||
li_fat_id: lifatid,
|
||||
twclid: twclid,
|
||||
event_type: eventName ? EVENT_TYPE.customEvent : EVENT_TYPE.pageView,
|
||||
event_name: eventName ? eventName?.substring(0, EVENT_NAME_LENGTH) : null,
|
||||
tag: tag,
|
||||
distinct_id: distinctId,
|
||||
created_at: getUTCString(createdAt),
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ async function relationalQuery(websiteId: string, filters: QueryFilters) {
|
|||
where website_event.website_id = {{websiteId::uuid}}
|
||||
${filterQuery}
|
||||
${dateQuery}
|
||||
order by website_event.created_at desc
|
||||
order by website_event.created_at asc
|
||||
limit 100
|
||||
`,
|
||||
params,
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ async function relationalQuery(
|
|||
let excludeDomain = '';
|
||||
|
||||
if (column === 'referrer_domain') {
|
||||
excludeDomain = `and website_event.referrer_domain != session.hostname
|
||||
excludeDomain = `and website_event.referrer_domain != website_event.hostname
|
||||
and website_event.referrer_domain != ''`;
|
||||
}
|
||||
|
||||
|
|
|
|||
511
src/queries/sql/reports/getAttribution.ts
Normal file
511
src/queries/sql/reports/getAttribution.ts
Normal file
|
|
@ -0,0 +1,511 @@
|
|||
import clickhouse from '@/lib/clickhouse';
|
||||
import { EVENT_TYPE } from '@/lib/constants';
|
||||
import { CLICKHOUSE, getDatabaseType, POSTGRESQL, PRISMA, runQuery } from '@/lib/db';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
export async function getAttribution(
|
||||
...args: [
|
||||
websiteId: string,
|
||||
criteria: {
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
model: string;
|
||||
steps: { type: string; value: string }[];
|
||||
currency: string;
|
||||
},
|
||||
]
|
||||
) {
|
||||
return runQuery({
|
||||
[PRISMA]: () => relationalQuery(...args),
|
||||
[CLICKHOUSE]: () => clickhouseQuery(...args),
|
||||
});
|
||||
}
|
||||
|
||||
async function relationalQuery(
|
||||
websiteId: string,
|
||||
criteria: {
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
model: string;
|
||||
steps: { type: string; value: string }[];
|
||||
currency: string;
|
||||
},
|
||||
): Promise<{
|
||||
referrer: { name: string; value: number }[];
|
||||
paidAds: { name: string; value: number }[];
|
||||
utm_source: { name: string; value: number }[];
|
||||
utm_medium: { name: string; value: number }[];
|
||||
utm_campaign: { name: string; value: number }[];
|
||||
utm_content: { name: string; value: number }[];
|
||||
utm_term: { name: string; value: number }[];
|
||||
total: { pageviews: number; visitors: number; visits: number };
|
||||
}> {
|
||||
const { startDate, endDate, model, steps, currency } = criteria;
|
||||
const { rawQuery } = prisma;
|
||||
const conversionStep = steps[0].value;
|
||||
const eventType = steps[0].type === 'url' ? EVENT_TYPE.pageView : EVENT_TYPE.customEvent;
|
||||
const column = steps[0].type === 'url' ? 'url_path' : 'event_name';
|
||||
const db = getDatabaseType();
|
||||
const like = db === POSTGRESQL ? 'ilike' : 'like';
|
||||
|
||||
function getUTMQuery(utmColumn: string) {
|
||||
return `
|
||||
select
|
||||
coalesce(we.${utmColumn}, '') name,
|
||||
${currency ? 'sum(e.value)' : 'count(distinct we.session_id)'} value
|
||||
from model m
|
||||
join website_event we
|
||||
on we.created_at = m.created_at
|
||||
and we.session_id = m.session_id
|
||||
${currency ? 'join events e on e.session_id = m.session_id' : ''}
|
||||
where we.website_id = {{websiteId::uuid}}
|
||||
and we.created_at between {{startDate}} and {{endDate}}
|
||||
${currency ? '' : `and we.${utmColumn} != ''`}
|
||||
group by 1
|
||||
order by 2 desc
|
||||
limit 20`;
|
||||
}
|
||||
|
||||
const eventQuery = `WITH events AS (
|
||||
select distinct
|
||||
session_id,
|
||||
max(created_at) max_dt
|
||||
from website_event
|
||||
where website_id = {{websiteId::uuid}}
|
||||
and created_at between {{startDate}} and {{endDate}}
|
||||
and ${column} = {{conversionStep}}
|
||||
and event_type = {{eventType}}
|
||||
group by 1),`;
|
||||
|
||||
const revenueEventQuery = `WITH events AS (
|
||||
select
|
||||
we.session_id,
|
||||
max(ed.created_at) max_dt,
|
||||
sum(coalesce(cast(number_value as decimal(10,2)), cast(string_value as decimal(10,2)))) value
|
||||
from event_data ed
|
||||
join website_event we
|
||||
on we.event_id = ed.website_event_Id
|
||||
and we.website_id = ed.website_id
|
||||
join (select website_event_id
|
||||
from event_data
|
||||
where website_id = {{websiteId::uuid}}
|
||||
and created_at between {{startDate}} and {{endDate}}
|
||||
and data_key ${like} '%currency%'
|
||||
and string_value = {{currency}}) currency
|
||||
on currency.website_event_id = ed.website_event_id
|
||||
where ed.website_id = {{websiteId::uuid}}
|
||||
and ed.created_at between {{startDate}} and {{endDate}}
|
||||
and ${column} = {{conversionStep}}
|
||||
and ed.data_key ${like} '%revenue%'
|
||||
group by 1),`;
|
||||
|
||||
function getModelQuery(model: string) {
|
||||
return model === 'firstClick'
|
||||
? `\n
|
||||
model AS (select e.session_id,
|
||||
min(we.created_at) created_at
|
||||
from events e
|
||||
join website_event we
|
||||
on we.session_id = e.session_id
|
||||
where we.website_id = {{websiteId::uuid}}
|
||||
and we.created_at between {{startDate}} and {{endDate}}
|
||||
group by e.session_id)`
|
||||
: `\n
|
||||
model AS (select e.session_id,
|
||||
max(we.created_at) created_at
|
||||
from events e
|
||||
join website_event we
|
||||
on we.session_id = e.session_id
|
||||
where we.website_id = {{websiteId::uuid}}
|
||||
and we.created_at between {{startDate}} and {{endDate}}
|
||||
and we.created_at < e.max_dt
|
||||
group by e.session_id)`;
|
||||
}
|
||||
|
||||
const referrerRes = await rawQuery(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
select coalesce(we.referrer_domain, '') name,
|
||||
${currency ? 'sum(e.value)' : 'count(distinct we.session_id)'} value
|
||||
from model m
|
||||
join website_event we
|
||||
on we.created_at = m.created_at
|
||||
and we.session_id = m.session_id
|
||||
join session s
|
||||
on s.session_id = m.session_id
|
||||
${currency ? 'join events e on e.session_id = m.session_id' : ''}
|
||||
where we.website_id = {{websiteId::uuid}}
|
||||
and we.created_at between {{startDate}} and {{endDate}}
|
||||
${
|
||||
currency
|
||||
? ''
|
||||
: `and we.referrer_domain != hostname
|
||||
and we.referrer_domain != ''`
|
||||
}
|
||||
group by 1
|
||||
order by 2 desc
|
||||
limit 20
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const paidAdsres = await rawQuery(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)},
|
||||
|
||||
results AS (
|
||||
select case
|
||||
when coalesce(gclid, '') != '' then 'Google Ads'
|
||||
when coalesce(fbclid, '') != '' then 'Facebook / Meta'
|
||||
when coalesce(msclkid, '') != '' then 'Microsoft Ads'
|
||||
when coalesce(ttclid, '') != '' then 'TikTok Ads'
|
||||
when coalesce(li_fat_id, '') != '' then 'LinkedIn Ads'
|
||||
when coalesce(twclid, '') != '' then 'Twitter Ads (X)'
|
||||
else ''
|
||||
end name,
|
||||
${currency ? 'sum(e.value)' : 'count(distinct we.session_id)'} value
|
||||
from model m
|
||||
join website_event we
|
||||
on we.created_at = m.created_at
|
||||
and we.session_id = m.session_id
|
||||
${currency ? 'join events e on e.session_id = m.session_id' : ''}
|
||||
where we.website_id = {{websiteId::uuid}}
|
||||
and we.created_at between {{startDate}} and {{endDate}}
|
||||
group by 1
|
||||
order by 2 desc
|
||||
limit 20)
|
||||
SELECT *
|
||||
FROM results
|
||||
${currency ? '' : `WHERE name != ''`}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const sourceRes = await rawQuery(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_source')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const mediumRes = await rawQuery(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_medium')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const campaignRes = await rawQuery(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_campaign')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const contentRes = await rawQuery(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_content')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const termRes = await rawQuery(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_term')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const totalRes = await rawQuery(
|
||||
`
|
||||
select
|
||||
count(*) as "pageviews",
|
||||
count(distinct session_id) as "visitors",
|
||||
count(distinct visit_id) as "visits"
|
||||
from website_event
|
||||
where website_id = {{websiteId::uuid}}
|
||||
and created_at between {{startDate}} and {{endDate}}
|
||||
and ${column} = {{conversionStep}}
|
||||
and event_type = {{eventType}}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
).then(result => result?.[0]);
|
||||
|
||||
return {
|
||||
referrer: referrerRes,
|
||||
paidAds: paidAdsres,
|
||||
utm_source: sourceRes,
|
||||
utm_medium: mediumRes,
|
||||
utm_campaign: campaignRes,
|
||||
utm_content: contentRes,
|
||||
utm_term: termRes,
|
||||
total: totalRes,
|
||||
};
|
||||
}
|
||||
|
||||
async function clickhouseQuery(
|
||||
websiteId: string,
|
||||
criteria: {
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
model: string;
|
||||
steps: { type: string; value: string }[];
|
||||
currency: string;
|
||||
},
|
||||
): Promise<{
|
||||
referrer: { name: string; value: number }[];
|
||||
paidAds: { name: string; value: number }[];
|
||||
utm_source: { name: string; value: number }[];
|
||||
utm_medium: { name: string; value: number }[];
|
||||
utm_campaign: { name: string; value: number }[];
|
||||
utm_content: { name: string; value: number }[];
|
||||
utm_term: { name: string; value: number }[];
|
||||
total: { pageviews: number; visitors: number; visits: number };
|
||||
}> {
|
||||
const { startDate, endDate, model, steps, currency } = criteria;
|
||||
const { rawQuery } = clickhouse;
|
||||
const conversionStep = steps[0].value;
|
||||
const eventType = steps[0].type === 'url' ? EVENT_TYPE.pageView : EVENT_TYPE.customEvent;
|
||||
const column = steps[0].type === 'url' ? 'url_path' : 'event_name';
|
||||
|
||||
function getUTMQuery(utmColumn: string) {
|
||||
return `
|
||||
select
|
||||
we.${utmColumn} name,
|
||||
${currency ? 'sum(e.value)' : 'uniqExact(we.session_id)'} value
|
||||
from model m
|
||||
join website_event we
|
||||
on we.created_at = m.created_at
|
||||
and we.session_id = m.session_id
|
||||
${currency ? 'join events e on e.session_id = m.session_id' : ''}
|
||||
where we.website_id = {websiteId:UUID}
|
||||
and we.created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
${currency ? '' : `and we.${utmColumn} != ''`}
|
||||
group by 1
|
||||
order by 2 desc
|
||||
limit 20`;
|
||||
}
|
||||
|
||||
const eventQuery = `WITH events AS (
|
||||
select distinct
|
||||
session_id,
|
||||
max(created_at) max_dt
|
||||
from website_event
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and ${column} = {conversionStep:String}
|
||||
and event_type = {eventType:UInt32}
|
||||
group by 1),`;
|
||||
|
||||
const revenueEventQuery = `WITH events AS (
|
||||
select
|
||||
ed.session_id,
|
||||
max(ed.created_at) max_dt,
|
||||
sum(coalesce(toDecimal64(number_value, 2), toDecimal64(string_value, 2))) as value
|
||||
from event_data ed
|
||||
join (select event_id
|
||||
from event_data
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and positionCaseInsensitive(data_key, 'currency') > 0
|
||||
and string_value = {currency:String}) c
|
||||
on c.event_id = ed.event_id
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and ${column} = {conversionStep:String}
|
||||
and positionCaseInsensitive(ed.data_key, 'revenue') > 0
|
||||
group by 1),`;
|
||||
|
||||
function getModelQuery(model: string) {
|
||||
return model === 'firstClick'
|
||||
? `\n
|
||||
model AS (select e.session_id,
|
||||
min(we.created_at) created_at
|
||||
from events e
|
||||
join website_event we
|
||||
on we.session_id = e.session_id
|
||||
where we.website_id = {websiteId:UUID}
|
||||
and we.created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
group by e.session_id)`
|
||||
: `\n
|
||||
model AS (select e.session_id,
|
||||
max(we.created_at) created_at
|
||||
from events e
|
||||
join website_event we
|
||||
on we.session_id = e.session_id
|
||||
where we.website_id = {websiteId:UUID}
|
||||
and we.created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and we.created_at < e.max_dt
|
||||
group by e.session_id)`;
|
||||
}
|
||||
|
||||
const referrerRes = await rawQuery<
|
||||
{
|
||||
name: string;
|
||||
value: number;
|
||||
}[]
|
||||
>(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
select we.referrer_domain name,
|
||||
${currency ? 'sum(e.value)' : 'uniqExact(we.session_id)'} value
|
||||
from model m
|
||||
join website_event we
|
||||
on we.created_at = m.created_at
|
||||
and we.session_id = m.session_id
|
||||
${currency ? 'join events e on e.session_id = m.session_id' : ''}
|
||||
where we.website_id = {websiteId:UUID}
|
||||
and we.created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
${
|
||||
currency
|
||||
? ''
|
||||
: `and we.referrer_domain != hostname
|
||||
and we.referrer_domain != ''`
|
||||
}
|
||||
group by 1
|
||||
order by 2 desc
|
||||
limit 20
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const paidAdsres = await rawQuery<
|
||||
{
|
||||
name: string;
|
||||
value: number;
|
||||
}[]
|
||||
>(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
select multiIf(gclid != '', 'Google Ads',
|
||||
fbclid != '', 'Facebook / Meta',
|
||||
msclkid != '', 'Microsoft Ads',
|
||||
ttclid != '', 'TikTok Ads',
|
||||
li_fat_id != '', ' LinkedIn Ads',
|
||||
twclid != '', 'Twitter Ads (X)','') name,
|
||||
${currency ? 'sum(e.value)' : 'uniqExact(we.session_id)'} value
|
||||
from model m
|
||||
join website_event we
|
||||
on we.created_at = m.created_at
|
||||
and we.session_id = m.session_id
|
||||
${currency ? 'join events e on e.session_id = m.session_id' : ''}
|
||||
where we.website_id = {websiteId:UUID}
|
||||
and we.created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
${currency ? '' : `and name != ''`}
|
||||
group by 1
|
||||
order by 2 desc
|
||||
limit 20
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const sourceRes = await rawQuery<
|
||||
{
|
||||
name: string;
|
||||
value: number;
|
||||
}[]
|
||||
>(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_source')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const mediumRes = await rawQuery<
|
||||
{
|
||||
name: string;
|
||||
value: number;
|
||||
}[]
|
||||
>(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_medium')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const campaignRes = await rawQuery<
|
||||
{
|
||||
name: string;
|
||||
value: number;
|
||||
}[]
|
||||
>(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_campaign')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const contentRes = await rawQuery<
|
||||
{
|
||||
name: string;
|
||||
value: number;
|
||||
}[]
|
||||
>(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_content')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const termRes = await rawQuery<
|
||||
{
|
||||
name: string;
|
||||
value: number;
|
||||
}[]
|
||||
>(
|
||||
`
|
||||
${currency ? revenueEventQuery : eventQuery}
|
||||
${getModelQuery(model)}
|
||||
${getUTMQuery('utm_term')}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
);
|
||||
|
||||
const totalRes = await rawQuery<{ pageviews: number; visitors: number; visits: number }>(
|
||||
`
|
||||
select
|
||||
count(*) as "pageviews",
|
||||
uniqExact(session_id) as "visitors",
|
||||
uniqExact(visit_id) as "visits"
|
||||
from website_event
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and ${column} = {conversionStep:String}
|
||||
and event_type = {eventType:UInt32}
|
||||
`,
|
||||
{ websiteId, startDate, endDate, conversionStep, eventType, currency },
|
||||
).then(result => result?.[0]);
|
||||
|
||||
return {
|
||||
referrer: referrerRes,
|
||||
paidAds: paidAdsres,
|
||||
utm_source: sourceRes,
|
||||
utm_medium: mediumRes,
|
||||
utm_campaign: campaignRes,
|
||||
utm_content: contentRes,
|
||||
utm_term: termRes,
|
||||
total: totalRes,
|
||||
};
|
||||
}
|
||||
|
|
@ -56,7 +56,9 @@ async function relationalQuery(
|
|||
on we.event_id = ed.website_event_id
|
||||
join (select website_event_id
|
||||
from event_data
|
||||
where data_key ${like} '%currency%'
|
||||
where website_id = {{websiteId::uuid}}
|
||||
and created_at between {{startDate}} and {{endDate}}
|
||||
and data_key ${like} '%currency%'
|
||||
and string_value = {{currency}}) currency
|
||||
on currency.website_event_id = ed.website_event_id
|
||||
where ed.website_id = {{websiteId::uuid}}
|
||||
|
|
@ -80,7 +82,9 @@ async function relationalQuery(
|
|||
on s.session_id = we.session_id
|
||||
join (select website_event_id
|
||||
from event_data
|
||||
where data_key ${like} '%currency%'
|
||||
where website_id = {{websiteId::uuid}}
|
||||
and created_at between {{startDate}} and {{endDate}}
|
||||
and data_key ${like} '%currency%'
|
||||
and string_value = {{currency}}) currency
|
||||
on currency.website_event_id = ed.website_event_id
|
||||
where ed.website_id = {{websiteId::uuid}}
|
||||
|
|
@ -102,7 +106,9 @@ async function relationalQuery(
|
|||
on we.event_id = ed.website_event_id
|
||||
join (select website_event_id
|
||||
from event_data
|
||||
where data_key ${like} '%currency%'
|
||||
where website_id = {{websiteId::uuid}}
|
||||
and created_at between {{startDate}} and {{endDate}}
|
||||
and data_key ${like} '%currency%'
|
||||
and string_value = {{currency}}) currency
|
||||
on currency.website_event_id = ed.website_event_id
|
||||
where ed.website_id = {{websiteId::uuid}}
|
||||
|
|
@ -124,7 +130,9 @@ async function relationalQuery(
|
|||
on we.event_id = ed.website_event_id
|
||||
join (select website_event_id, string_value as currency
|
||||
from event_data
|
||||
where data_key ${like} '%currency%') c
|
||||
where website_id = {{websiteId::uuid}}
|
||||
and created_at between {{startDate}} and {{endDate}}
|
||||
and data_key ${like} '%currency%') c
|
||||
on c.website_event_id = ed.website_event_id
|
||||
where ed.website_id = {{websiteId::uuid}}
|
||||
and ed.created_at between {{startDate}} and {{endDate}}
|
||||
|
|
@ -176,7 +184,9 @@ async function clickhouseQuery(
|
|||
from event_data
|
||||
join (select event_id
|
||||
from event_data
|
||||
where positionCaseInsensitive(data_key, 'currency') > 0
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and positionCaseInsensitive(data_key, 'currency') > 0
|
||||
and string_value = {currency:String}) currency
|
||||
on currency.event_id = event_data.event_id
|
||||
where website_id = {websiteId:UUID}
|
||||
|
|
@ -201,7 +211,9 @@ async function clickhouseQuery(
|
|||
from event_data ed
|
||||
join (select event_id
|
||||
from event_data
|
||||
where positionCaseInsensitive(data_key, 'currency') > 0
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and positionCaseInsensitive(data_key, 'currency') > 0
|
||||
and string_value = {currency:String}) c
|
||||
on c.event_id = ed.event_id
|
||||
join (select distinct website_id, session_id, country
|
||||
|
|
@ -231,7 +243,9 @@ async function clickhouseQuery(
|
|||
from event_data
|
||||
join (select event_id
|
||||
from event_data
|
||||
where positionCaseInsensitive(data_key, 'currency') > 0
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and positionCaseInsensitive(data_key, 'currency') > 0
|
||||
and string_value = {currency:String}) currency
|
||||
on currency.event_id = event_data.event_id
|
||||
where website_id = {websiteId:UUID}
|
||||
|
|
@ -259,7 +273,9 @@ async function clickhouseQuery(
|
|||
from event_data ed
|
||||
join (select event_id, string_value as currency
|
||||
from event_data
|
||||
where positionCaseInsensitive(data_key, 'currency') > 0) c
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and positionCaseInsensitive(data_key, 'currency') > 0) c
|
||||
on c.event_id = ed.event_id
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
|
|
|
|||
|
|
@ -5,32 +5,30 @@ export async function createSession(data: Prisma.SessionCreateInput) {
|
|||
const {
|
||||
id,
|
||||
websiteId,
|
||||
hostname,
|
||||
browser,
|
||||
os,
|
||||
device,
|
||||
screen,
|
||||
language,
|
||||
country,
|
||||
subdivision1,
|
||||
subdivision2,
|
||||
region,
|
||||
city,
|
||||
distinctId,
|
||||
} = data;
|
||||
|
||||
return prisma.client.session.create({
|
||||
data: {
|
||||
id,
|
||||
websiteId,
|
||||
hostname,
|
||||
browser,
|
||||
os,
|
||||
device,
|
||||
screen,
|
||||
language,
|
||||
country,
|
||||
subdivision1,
|
||||
subdivision2,
|
||||
region,
|
||||
city,
|
||||
distinctId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ async function relationalQuery(
|
|||
joinSession: SESSION_COLUMNS.includes(type),
|
||||
},
|
||||
);
|
||||
const includeCountry = column === 'city' || column === 'subdivision1';
|
||||
const includeCountry = column === 'city' || column === 'region';
|
||||
|
||||
return rawQuery(
|
||||
`
|
||||
|
|
@ -75,7 +75,7 @@ async function clickhouseQuery(
|
|||
...filters,
|
||||
eventType: EVENT_TYPE.pageView,
|
||||
});
|
||||
const includeCountry = column === 'city' || column === 'subdivision1';
|
||||
const includeCountry = column === 'city' || column === 'region';
|
||||
|
||||
let sql = '';
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ async function relationalQuery(websiteId: string, sessionId: string) {
|
|||
return rawQuery(
|
||||
`
|
||||
select id,
|
||||
distinct_id as "distinctId",
|
||||
website_id as "websiteId",
|
||||
hostname,
|
||||
browser,
|
||||
|
|
@ -23,7 +24,7 @@ async function relationalQuery(websiteId: string, sessionId: string) {
|
|||
screen,
|
||||
language,
|
||||
country,
|
||||
subdivision1,
|
||||
region,
|
||||
city,
|
||||
min(min_time) as "firstAt",
|
||||
max(max_time) as "lastAt",
|
||||
|
|
@ -33,16 +34,17 @@ async function relationalQuery(websiteId: string, sessionId: string) {
|
|||
sum(${getTimestampDiffSQL('min_time', 'max_time')}) as "totaltime"
|
||||
from (select
|
||||
session.session_id as id,
|
||||
session.distinct_id,
|
||||
website_event.visit_id,
|
||||
session.website_id,
|
||||
session.hostname,
|
||||
website_event.hostname,
|
||||
session.browser,
|
||||
session.os,
|
||||
session.device,
|
||||
session.screen,
|
||||
session.language,
|
||||
session.country,
|
||||
session.subdivision1,
|
||||
session.region,
|
||||
session.city,
|
||||
min(website_event.created_at) as min_time,
|
||||
max(website_event.created_at) as max_time,
|
||||
|
|
@ -52,8 +54,8 @@ async function relationalQuery(websiteId: string, sessionId: string) {
|
|||
join website_event on website_event.session_id = session.session_id
|
||||
where session.website_id = {{websiteId::uuid}}
|
||||
and session.session_id = {{sessionId::uuid}}
|
||||
group by session.session_id, visit_id, session.website_id, session.hostname, session.browser, session.os, session.device, session.screen, session.language, session.country, session.subdivision1, session.city) t
|
||||
group by id, website_id, hostname, browser, os, device, screen, language, country, subdivision1, city;
|
||||
group by session.session_id, session.distinct_id, visit_id, session.website_id, website_event.hostname, session.browser, session.os, session.device, session.screen, session.language, session.country, session.region, session.city) t
|
||||
group by id, distinct_id, website_id, hostname, browser, os, device, screen, language, country, region, city;
|
||||
`,
|
||||
{ websiteId, sessionId },
|
||||
).then(result => result?.[0]);
|
||||
|
|
@ -66,6 +68,7 @@ async function clickhouseQuery(websiteId: string, sessionId: string) {
|
|||
`
|
||||
select id,
|
||||
websiteId,
|
||||
distinctId,
|
||||
hostname,
|
||||
browser,
|
||||
os,
|
||||
|
|
@ -73,7 +76,7 @@ async function clickhouseQuery(websiteId: string, sessionId: string) {
|
|||
screen,
|
||||
language,
|
||||
country,
|
||||
subdivision1,
|
||||
region,
|
||||
city,
|
||||
${getDateStringSQL('min(min_time)')} as firstAt,
|
||||
${getDateStringSQL('max(max_time)')} as lastAt,
|
||||
|
|
@ -83,6 +86,7 @@ async function clickhouseQuery(websiteId: string, sessionId: string) {
|
|||
sum(max_time-min_time) as totaltime
|
||||
from (select
|
||||
session_id as id,
|
||||
distinct_id as distinctId,
|
||||
visit_id,
|
||||
website_id as websiteId,
|
||||
hostname,
|
||||
|
|
@ -92,7 +96,7 @@ async function clickhouseQuery(websiteId: string, sessionId: string) {
|
|||
screen,
|
||||
language,
|
||||
country,
|
||||
subdivision1,
|
||||
region,
|
||||
city,
|
||||
min(min_time) as min_time,
|
||||
max(max_time) as max_time,
|
||||
|
|
@ -101,8 +105,8 @@ async function clickhouseQuery(websiteId: string, sessionId: string) {
|
|||
from website_event_stats_hourly
|
||||
where website_id = {websiteId:UUID}
|
||||
and session_id = {sessionId:UUID}
|
||||
group by session_id, visit_id, website_id, hostname, browser, os, device, screen, language, country, subdivision1, city) t
|
||||
group by id, websiteId, hostname, browser, os, device, screen, language, country, subdivision1, city;
|
||||
group by session_id, distinct_id, visit_id, website_id, hostname, browser, os, device, screen, language, country, region, city) t
|
||||
group by id, websiteId, distinctId, hostname, browser, os, device, screen, language, country, region, city;
|
||||
`,
|
||||
{ websiteId, sessionId },
|
||||
).then(result => result?.[0]);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import clickhouse from '@/lib/clickhouse';
|
||||
import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db';
|
||||
import { CLICKHOUSE, getDatabaseType, POSTGRESQL, PRISMA, runQuery } from '@/lib/db';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PageParams, QueryFilters } from '@/lib/types';
|
||||
|
||||
|
|
@ -14,24 +14,28 @@ export async function getWebsiteSessions(
|
|||
|
||||
async function relationalQuery(websiteId: string, filters: QueryFilters, pageParams: PageParams) {
|
||||
const { pagedRawQuery, parseFilters } = prisma;
|
||||
const { search } = pageParams;
|
||||
const { filterQuery, params } = await parseFilters(websiteId, {
|
||||
...filters,
|
||||
});
|
||||
|
||||
const db = getDatabaseType();
|
||||
const like = db === POSTGRESQL ? 'ilike' : 'like';
|
||||
|
||||
return pagedRawQuery(
|
||||
`
|
||||
with sessions as (
|
||||
select
|
||||
session.session_id as "id",
|
||||
session.website_id as "websiteId",
|
||||
session.hostname,
|
||||
website_event.hostname,
|
||||
session.browser,
|
||||
session.os,
|
||||
session.device,
|
||||
session.screen,
|
||||
session.language,
|
||||
session.country,
|
||||
session.subdivision1,
|
||||
session.region,
|
||||
session.city,
|
||||
min(website_event.created_at) as "firstAt",
|
||||
max(website_event.created_at) as "lastAt",
|
||||
|
|
@ -43,22 +47,31 @@ async function relationalQuery(websiteId: string, filters: QueryFilters, pagePar
|
|||
where website_event.website_id = {{websiteId::uuid}}
|
||||
and website_event.created_at between {{startDate}} and {{endDate}}
|
||||
${filterQuery}
|
||||
${
|
||||
search
|
||||
? `and (distinct_id ${like} {{search}}
|
||||
or city ${like} {{search}}
|
||||
or browser ${like} {{search}}
|
||||
or os ${like} {{search}}
|
||||
or device ${like} {{search}})`
|
||||
: ''
|
||||
}
|
||||
group by session.session_id,
|
||||
session.website_id,
|
||||
session.hostname,
|
||||
website_event.hostname,
|
||||
session.browser,
|
||||
session.os,
|
||||
session.device,
|
||||
session.screen,
|
||||
session.language,
|
||||
session.country,
|
||||
session.subdivision1,
|
||||
session.region,
|
||||
session.city
|
||||
order by max(website_event.created_at) desc
|
||||
limit 1000)
|
||||
select * from sessions
|
||||
`,
|
||||
params,
|
||||
{ ...params, search: `%${search}%` },
|
||||
pageParams,
|
||||
);
|
||||
}
|
||||
|
|
@ -66,6 +79,7 @@ async function relationalQuery(websiteId: string, filters: QueryFilters, pagePar
|
|||
async function clickhouseQuery(websiteId: string, filters: QueryFilters, pageParams?: PageParams) {
|
||||
const { pagedQuery, parseFilters, getDateStringSQL } = clickhouse;
|
||||
const { params, dateQuery, filterQuery } = await parseFilters(websiteId, filters);
|
||||
const { search } = pageParams;
|
||||
|
||||
return pagedQuery(
|
||||
`
|
||||
|
|
@ -80,7 +94,7 @@ async function clickhouseQuery(websiteId: string, filters: QueryFilters, pagePar
|
|||
screen,
|
||||
language,
|
||||
country,
|
||||
subdivision1,
|
||||
region,
|
||||
city,
|
||||
${getDateStringSQL('min(min_time)')} as firstAt,
|
||||
${getDateStringSQL('max(max_time)')} as lastAt,
|
||||
|
|
@ -91,12 +105,21 @@ async function clickhouseQuery(websiteId: string, filters: QueryFilters, pagePar
|
|||
where website_id = {websiteId:UUID}
|
||||
${dateQuery}
|
||||
${filterQuery}
|
||||
group by session_id, website_id, hostname, browser, os, device, screen, language, country, subdivision1, city
|
||||
${
|
||||
search
|
||||
? `and ((positionCaseInsensitive(distinct_id, {search:String}) > 0)
|
||||
or (positionCaseInsensitive(city, {search:String}) > 0)
|
||||
or (positionCaseInsensitive(browser, {search:String}) > 0)
|
||||
or (positionCaseInsensitive(os, {search:String}) > 0)
|
||||
or (positionCaseInsensitive(device, {search:String}) > 0))`
|
||||
: ''
|
||||
}
|
||||
group by session_id, website_id, hostname, browser, os, device, screen, language, country, region, city
|
||||
order by lastAt desc
|
||||
limit 1000)
|
||||
select * from sessions
|
||||
`,
|
||||
params,
|
||||
{ ...params, search },
|
||||
pageParams,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ export async function saveSessionData(data: {
|
|||
websiteId: string;
|
||||
sessionId: string;
|
||||
sessionData: DynamicData;
|
||||
distinctId?: string;
|
||||
createdAt?: Date;
|
||||
}) {
|
||||
return runQuery({
|
||||
|
|
@ -23,10 +24,11 @@ export async function relationalQuery(data: {
|
|||
websiteId: string;
|
||||
sessionId: string;
|
||||
sessionData: DynamicData;
|
||||
distinctId?: string;
|
||||
createdAt?: Date;
|
||||
}) {
|
||||
const { client } = prisma;
|
||||
const { websiteId, sessionId, sessionData, createdAt } = data;
|
||||
const { websiteId, sessionId, sessionData, distinctId, createdAt } = data;
|
||||
|
||||
const jsonKeys = flattenJSON(sessionData);
|
||||
|
||||
|
|
@ -39,6 +41,7 @@ export async function relationalQuery(data: {
|
|||
numberValue: a.dataType === DATA_TYPE.number ? a.value : null,
|
||||
dateValue: a.dataType === DATA_TYPE.date ? new Date(a.value) : null,
|
||||
dataType: a.dataType,
|
||||
distinctId,
|
||||
createdAt,
|
||||
}));
|
||||
|
||||
|
|
@ -80,9 +83,10 @@ async function clickhouseQuery(data: {
|
|||
websiteId: string;
|
||||
sessionId: string;
|
||||
sessionData: DynamicData;
|
||||
distinctId?: string;
|
||||
createdAt?: Date;
|
||||
}) {
|
||||
const { websiteId, sessionId, sessionData, createdAt } = data;
|
||||
const { websiteId, sessionId, sessionData, distinctId, createdAt } = data;
|
||||
|
||||
const { insert, getUTCString } = clickhouse;
|
||||
const { sendMessage } = kafka;
|
||||
|
|
@ -98,6 +102,7 @@ async function clickhouseQuery(data: {
|
|||
string_value: getStringValue(value, dataType),
|
||||
number_value: dataType === DATA_TYPE.number ? value : null,
|
||||
date_value: dataType === DATA_TYPE.date ? getUTCString(value) : null,
|
||||
distinct_id: distinctId,
|
||||
created_at: getUTCString(createdAt),
|
||||
};
|
||||
});
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@
|
|||
url: currentUrl,
|
||||
referrer: currentRef,
|
||||
tag,
|
||||
id: identity ? identity : undefined,
|
||||
});
|
||||
|
||||
const hasDoNotTrack = () => {
|
||||
|
|
@ -174,7 +175,20 @@
|
|||
return send(getPayload());
|
||||
};
|
||||
|
||||
const identify = data => send({ ...getPayload(), data }, 'identify');
|
||||
const identify = (id, data) => {
|
||||
if (typeof id === 'string') {
|
||||
identity = id;
|
||||
}
|
||||
|
||||
cache = '';
|
||||
return send(
|
||||
{
|
||||
...getPayload(),
|
||||
data: typeof id === 'object' ? id : data,
|
||||
},
|
||||
'identify',
|
||||
);
|
||||
};
|
||||
|
||||
/* Start */
|
||||
|
||||
|
|
@ -190,6 +204,7 @@
|
|||
let initialized = false;
|
||||
let disabled = false;
|
||||
let cache;
|
||||
let identity;
|
||||
|
||||
if (autoTrack && !trackingDisabled()) {
|
||||
if (document.readyState === 'complete') {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue