Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

add filter ability

Bill Yang90d52dda0fd0
diff --git a/client/src/app/[site]/components/Filters/Filters.tsx b/client/src/app/[site]/components/Filters/Filters.tsx
new file mode 100644
index 000000000..284709c8a
--- /dev/null
+++ b/client/src/app/[site]/components/Filters/Filters.tsx
@@ -0,0 +1,20 @@
+import { useStore } from "../../../../lib/store";
+
+export function Filters() {
+ const { filters } = useStore();
+ if (filters.length === 0) return null;
+
+ return (
+ <div className="flex gap-2">
+ {filters.map((filter) => (
+ <div
+ key={filter.parameter}
+ className="p-1 rounded-md bg-neutral-850 text-neutral-400 flex items-center gap-1"
+ >
+ <div className="text-xs">{filter.parameter}</div>
+ <div className="text-xs">{filter.value}</div>
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/components/sections/Browsers/Browsers.tsx b/client/src/app/[site]/components/sections/Browsers/Browsers.tsx
index d13bf4ad8..3e13339f0 100644
--- a/client/src/app/[site]/components/sections/Browsers/Browsers.tsx
+++ b/client/src/app/[site]/components/sections/Browsers/Browsers.tsx
@@ -78,6 +78,8 @@ export function Browsers() {
{e.browser || "Other"}
</div>
)}
+ getValue={(e) => e.browser}
+ filterParameter="browser"
/>
);
}
diff --git a/client/src/app/[site]/components/sections/Countries/Countries.tsx b/client/src/app/[site]/components/sections/Countries/Countries.tsx
index 7d25dfe8e..f15b782f3 100644
--- a/client/src/app/[site]/components/sections/Countries/Countries.tsx
+++ b/client/src/app/[site]/components/sections/Countries/Countries.tsx
@@ -36,6 +36,8 @@ export function Countries() {
)}
</span>
)}
+ getValue={(e) => e.country}
+ filterParameter="country"
/>
);
}
diff --git a/client/src/app/[site]/components/sections/Devices/Devices.tsx b/client/src/app/[site]/components/sections/Devices/Devices.tsx
index c2268258c..2652f6a22 100644
--- a/client/src/app/[site]/components/sections/Devices/Devices.tsx
+++ b/client/src/app/[site]/components/sections/Devices/Devices.tsx
@@ -7,9 +7,11 @@ export function Devices() {
const { data, isLoading } = useGetDevices();
return (
<StandardCard
+ filterParameter="device_type"
isLoading={isLoading}
title="Devices"
data={data}
+ getValue={(e) => e.device_type}
getKey={(e) => e.device_type}
getLabel={(e) => e.device_type || "Other"}
/>
diff --git a/client/src/app/[site]/components/sections/OperatingSystems/OperatingSystems.tsx b/client/src/app/[site]/components/sections/OperatingSystems/OperatingSystems.tsx
index be176e5c3..8b3f710a8 100644
--- a/client/src/app/[site]/components/sections/OperatingSystems/OperatingSystems.tsx
+++ b/client/src/app/[site]/components/sections/OperatingSystems/OperatingSystems.tsx
@@ -27,6 +27,7 @@ export function OperatingSystems() {
title="Operating Systems"
data={data}
isLoading={isLoading}
+ getValue={(e) => e.operating_system}
getKey={(e) => e.operating_system}
getLabel={(e) => (
<div className="flex gap-2 items-center">
@@ -44,6 +45,7 @@ export function OperatingSystems() {
{e.operating_system || "Other"}
</div>
)}
+ filterParameter="operating_system"
/>
);
}
diff --git a/client/src/app/[site]/components/sections/Pages/Pages.tsx b/client/src/app/[site]/components/sections/Pages/Pages.tsx
index 7666110c6..8d2e3abad 100644
--- a/client/src/app/[site]/components/sections/Pages/Pages.tsx
+++ b/client/src/app/[site]/components/sections/Pages/Pages.tsx
@@ -7,9 +7,11 @@ export function Pages() {
const { data, isLoading } = useGetPages();
return (
<StandardCard
+ filterParameter="pathname"
title="Pages"
data={data}
isLoading={isLoading}
+ getValue={(e) => e.pathname}
getKey={(e) => e.pathname}
getLabel={(e) => e.pathname || "Other"}
/>
diff --git a/client/src/app/[site]/components/sections/Referrers/Referrers.tsx b/client/src/app/[site]/components/sections/Referrers/Referrers.tsx
index 28e63da8e..e91aa9c09 100644
--- a/client/src/app/[site]/components/sections/Referrers/Referrers.tsx
+++ b/client/src/app/[site]/components/sections/Referrers/Referrers.tsx
@@ -7,6 +7,7 @@ export function Referrers() {
const { data, isLoading } = useGetReferrers();
return (
<StandardCard
+ filterParameter="referrer"
title="Referrers"
data={data}
getKey={(e) => e.referrer}
@@ -30,6 +31,7 @@ export function Referrers() {
)}
</div>
)}
+ getValue={(e) => e.referrer}
/>
);
}
diff --git a/client/src/app/[site]/components/shared/StandardCard.tsx b/client/src/app/[site]/components/shared/StandardCard.tsx
index e05842987..92fcfaa70 100644
--- a/client/src/app/[site]/components/shared/StandardCard.tsx
+++ b/client/src/app/[site]/components/shared/StandardCard.tsx
@@ -16,13 +16,16 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
+import { addFilter, FilterParameter, useStore } from "../../../../lib/store";
export function StandardCard<T extends { percentage: number; count: number }>({
title,
data,
getKey,
getLabel,
+ getValue,
isLoading,
+ filterParameter,
}: {
title: string;
data:
@@ -34,7 +37,11 @@ export function StandardCard<T extends { percentage: number; count: number }>({
isLoading?: boolean;
getKey: (item: T) => string;
getLabel: (item: T) => ReactNode;
+ getValue: (item: T) => string;
+ filterParameter: FilterParameter;
}) {
+ const { filters, setFilters } = useStore();
+
return (
<Card>
{isLoading && <CardLoader />}
@@ -43,7 +50,17 @@ export function StandardCard<T extends { percentage: number; count: number }>({
</CardHeader>
<CardContent className="flex flex-col gap-2">
{data?.data?.slice(0, 10).map((e) => (
- <div key={getKey(e)} className="relative h-7 flex items-center">
+ <div
+ key={getKey(e)}
+ className="relative h-7 flex items-center cursor-pointer hover:bg-neutral-850 "
+ onClick={() =>
+ addFilter({
+ parameter: filterParameter,
+ value: getValue(e),
+ type: "equals",
+ })
+ }
+ >
<div
className="absolute inset-0 bg-fuchsia-400 py-2 opacity-30 rounded-md"
style={{ width: `${e.percentage}%` }}
diff --git a/client/src/app/[site]/page.tsx b/client/src/app/[site]/page.tsx
index bcfb6ffee..6a6945f9d 100644
--- a/client/src/app/[site]/page.tsx
+++ b/client/src/app/[site]/page.tsx
@@ -13,6 +13,7 @@ import { Map } from "./components/sections/Map/Map";
import { OperatingSystems } from "./components/sections/OperatingSystems/OperatingSystems";
import { Pages } from "./components/sections/Pages/Pages";
import { Referrers } from "./components/sections/Referrers/Referrers";
+import { Filters } from "./components/Filters/Filters";
export default function SitePage() {
const pathname = usePathname();
@@ -48,6 +49,7 @@ function SitePageInner({ site }: { site: string }) {
return (
<>
<Header />
+ <Filters />
<MainSection />
<div className="grid grid-cols-2 gap-4 mt-4">
<OperatingSystems />
diff --git a/client/src/hooks/api.ts b/client/src/hooks/api.ts
index 8ee2d4ee7..f4a7f98d2 100644
--- a/client/src/hooks/api.ts
+++ b/client/src/hooks/api.ts
@@ -22,15 +22,29 @@ export function useGetLiveUsercount() {
type PeriodTime = "current" | "previous";
export function useGenericQuery<T>(
+ endpoint: string
+): UseQueryResult<APIResponse<T>> {
+ return useQuery({
+ queryKey: [endpoint],
+ queryFn: () => {
+ return authedFetch(`${BACKEND_URL}/${endpoint}`).then((res) =>
+ res.json()
+ );
+ },
+ staleTime: Infinity,
+ });
+}
+
+export function useGenericSiteDataQuery<T>(
endpoint: string,
periodTime?: PeriodTime
): UseQueryResult<APIResponse<T>> {
- const { time, previousTime, site } = useStore();
+ const { time, previousTime, site, filters } = useStore();
const timeToUse = periodTime === "previous" ? previousTime : time;
const { startDate, endDate } = getStartAndEndDate(timeToUse);
return useQuery({
- queryKey: [endpoint, timeToUse, site],
+ queryKey: [endpoint, timeToUse, site, filters],
queryFn: () => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return authedFetch(
@@ -38,7 +52,7 @@ export function useGenericQuery<T>(
startDate ? `startDate=${startDate}&` : ""
}${
endDate ? `endDate=${endDate}&` : ""
- }timezone=${timezone}&site=${site}`
+ }timezone=${timezone}&site=${site}&filters=${JSON.stringify(filters)}`
).then((res) => res.json());
},
staleTime: Infinity,
@@ -62,7 +76,7 @@ export type GetCountriesResponse = {
}[];
export function useGetCountries() {
- return useGenericQuery<GetCountriesResponse>("countries");
+ return useGenericSiteDataQuery<GetCountriesResponse>("countries");
}
export type GetDevicesResponse = {
@@ -72,7 +86,7 @@ export type GetDevicesResponse = {
}[];
export function useGetDevices() {
- return useGenericQuery<GetDevicesResponse>("devices");
+ return useGenericSiteDataQuery<GetDevicesResponse>("devices");
}
export type GetOperatingSystemsResponse = {
@@ -82,7 +96,9 @@ export type GetOperatingSystemsResponse = {
}[];
export function useGetOperatingSystems() {
- return useGenericQuery<GetOperatingSystemsResponse>("operating-systems");
+ return useGenericSiteDataQuery<GetOperatingSystemsResponse>(
+ "operating-systems"
+ );
}
export type GetBrowsersResponse = {
@@ -92,7 +108,7 @@ export type GetBrowsersResponse = {
}[];
export function useGetBrowsers() {
- return useGenericQuery<GetBrowsersResponse>("browsers");
+ return useGenericSiteDataQuery<GetBrowsersResponse>("browsers");
}
export type GetPagesResponse = {
@@ -102,7 +118,7 @@ export type GetPagesResponse = {
}[];
export function useGetPages() {
- return useGenericQuery<GetPagesResponse>("pages");
+ return useGenericSiteDataQuery<GetPagesResponse>("pages");
}
export type GetReferrersResponse = {
@@ -112,7 +128,7 @@ export type GetReferrersResponse = {
}[];
export function useGetReferrers() {
- return useGenericQuery<GetReferrersResponse>("referrers");
+ return useGenericSiteDataQuery<GetReferrersResponse>("referrers");
}
export type GetOverviewBucketedResponse = {
@@ -128,13 +144,13 @@ export type GetOverviewBucketedResponse = {
export function useGetOverviewBucketed(
periodTime?: PeriodTime
): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {
- const { time, previousTime, bucket, site } = useStore();
+ const { time, previousTime, bucket, site, filters } = useStore();
const timeToUse = periodTime === "previous" ? previousTime : time;
const { startDate, endDate } = getStartAndEndDate(timeToUse);
return useQuery({
- queryKey: ["overview-bucketed", timeToUse, bucket, site],
+ queryKey: ["overview-bucketed", timeToUse, bucket, site, filters],
queryFn: () => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return authedFetch(
@@ -142,7 +158,9 @@ export function useGetOverviewBucketed(
startDate ? `startDate=${startDate}&` : ""
}${
endDate ? `endDate=${endDate}&` : ""
- }timezone=${timezone}&bucket=${bucket}&site=${site}`
+ }timezone=${timezone}&bucket=${bucket}&site=${site}&filters=${JSON.stringify(
+ filters
+ )}`
).then((res) => res.json());
},
placeholderData: (_, query: any) => {
@@ -169,7 +187,7 @@ export type GetOverviewResponse = {
};
export function useGetOverview(periodTime?: PeriodTime) {
- return useGenericQuery<GetOverviewResponse>("overview", periodTime);
+ return useGenericSiteDataQuery<GetOverviewResponse>("overview", periodTime);
}
export type GetSitesResponse = {
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index 7209a6bdd..d5777db78 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -55,6 +55,22 @@ export type StatType =
| "bounce_rate"
| "session_duration";
+export type FilterType = "equals" | "not_equals" | "contains" | "not_contains";
+
+export type FilterParameter =
+ | "browser"
+ | "operating_system"
+ | "country"
+ | "device_type"
+ | "referrer"
+ | "pathname";
+
+export type Filter = {
+ parameter: FilterParameter;
+ value: string;
+ type: FilterType;
+};
+
type Store = {
site: string;
setSite: (site: string) => void;
@@ -65,6 +81,8 @@ type Store = {
setBucket: (bucket: TimeBucket) => void;
selectedStat: StatType;
setSelectedStat: (stat: StatType) => void;
+ filters: Filter[];
+ setFilters: (filters: Filter[]) => void;
};
export const useStore = create<Store>((set) => ({
@@ -163,6 +181,8 @@ export const useStore = create<Store>((set) => ({
setBucket: (bucket) => set({ bucket }),
selectedStat: "users",
setSelectedStat: (stat) => set({ selectedStat: stat }),
+ filters: [],
+ setFilters: (filters) => set({ filters }),
}));
export const goBack = () => {
@@ -274,3 +294,13 @@ export const goForward = () => {
);
}
};
+
+export const addFilter = (filter: Filter) => {
+ const { filters, setFilters } = useStore.getState();
+ setFilters([...filters, filter]);
+};
+
+export const removeFilter = (filter: Filter) => {
+ const { filters, setFilters } = useStore.getState();
+ setFilters(filters.filter((f) => f !== filter));
+};
diff --git a/server/src/api/getBrowsers.ts b/server/src/api/getBrowsers.ts
index 4c4413d8d..b11675d8e 100644
--- a/server/src/api/getBrowsers.ts
+++ b/server/src/api/getBrowsers.ts
@@ -1,7 +1,11 @@
import { FastifyReply, FastifyRequest } from "fastify";
import clickhouse from "../db/clickhouse/clickhouse.js";
import { GenericRequest } from "./types.js";
-import { getTimeStatement, processResults } from "./utils.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
type GetBrowsersResponse = {
browser: string;
@@ -11,10 +15,12 @@ type GetBrowsersResponse = {
export async function getBrowsers(
{
- query: { startDate, endDate, timezone, site },
+ query: { startDate, endDate, timezone, site, filters },
}: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
+ const filterStatement = getFilterStatement(filters);
+
const query = `
SELECT
browser,
@@ -23,6 +29,7 @@ export async function getBrowsers(
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY browser ORDER BY count desc;
`;
diff --git a/server/src/api/getCountries.ts b/server/src/api/getCountries.ts
index dcb2d9ff9..9525dc3ea 100644
--- a/server/src/api/getCountries.ts
+++ b/server/src/api/getCountries.ts
@@ -1,7 +1,11 @@
import { FastifyReply, FastifyRequest } from "fastify";
import clickhouse from "../db/clickhouse/clickhouse.js";
import { GenericRequest } from "./types.js";
-import { getTimeStatement, processResults } from "./utils.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
type GetCountriesResponse = {
country: string;
@@ -11,10 +15,12 @@ type GetCountriesResponse = {
export async function getCountries(
{
- query: { startDate, endDate, timezone, site },
+ query: { startDate, endDate, timezone, site, filters },
}: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
+ const filterStatement = getFilterStatement(filters);
+
const query = `
SELECT
country,
@@ -23,6 +29,7 @@ export async function getCountries(
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY country ORDER BY count desc;
`;
diff --git a/server/src/api/getDevices.ts b/server/src/api/getDevices.ts
index 3ee89cf02..90348b950 100644
--- a/server/src/api/getDevices.ts
+++ b/server/src/api/getDevices.ts
@@ -1,7 +1,11 @@
import { FastifyReply, FastifyRequest } from "fastify";
import clickhouse from "../db/clickhouse/clickhouse.js";
import { GenericRequest } from "./types.js";
-import { getTimeStatement, processResults } from "./utils.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
type GetDevicesResponse = {
device_type: string;
@@ -11,10 +15,12 @@ type GetDevicesResponse = {
export async function getDevices(
{
- query: { startDate, endDate, timezone, site },
+ query: { startDate, endDate, timezone, site, filters },
}: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
+ const filterStatement = getFilterStatement(filters);
+
const query = `
SELECT
device_type,
@@ -23,6 +29,7 @@ export async function getDevices(
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY device_type ORDER BY count desc;
`;
diff --git a/server/src/api/getOperatingSystems.ts b/server/src/api/getOperatingSystems.ts
index 2cc28f4d5..27c934043 100644
--- a/server/src/api/getOperatingSystems.ts
+++ b/server/src/api/getOperatingSystems.ts
@@ -1,7 +1,11 @@
import { FastifyReply, FastifyRequest } from "fastify";
import clickhouse from "../db/clickhouse/clickhouse.js";
import { GenericRequest } from "./types.js";
-import { getTimeStatement, processResults } from "./utils.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
type GetOperatingSystemsResponse = {
operating_system: string;
@@ -11,10 +15,12 @@ type GetOperatingSystemsResponse = {
export async function getOperatingSystems(
{
- query: { startDate, endDate, timezone, site },
+ query: { startDate, endDate, timezone, site, filters },
}: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
+ const filterStatement = getFilterStatement(filters);
+
const query = `
SELECT
operating_system,
@@ -23,6 +29,7 @@ export async function getOperatingSystems(
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY operating_system ORDER BY count desc;
`;
diff --git a/server/src/api/getOverview.ts b/server/src/api/getOverview.ts
index 78bee1514..5e4be2e72 100644
--- a/server/src/api/getOverview.ts
+++ b/server/src/api/getOverview.ts
@@ -1,7 +1,11 @@
import { FastifyReply, FastifyRequest } from "fastify";
import clickhouse from "../db/clickhouse/clickhouse.js";
import { GenericRequest } from "./types.js";
-import { getTimeStatement, processResults } from "./utils.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
type GetOverviewResponse = {
sessions: number;
@@ -14,10 +18,11 @@ type GetOverviewResponse = {
export async function getOverview(
{
- query: { startDate, endDate, timezone, site },
+ query: { startDate, endDate, timezone, site, filters },
}: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
+ const filterStatement = getFilterStatement(filters);
const query = `SELECT
session_stats.sessions,
session_stats.pages_per_session,
@@ -44,6 +49,7 @@ export async function getOverview(
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY session_id
)
@@ -57,6 +63,7 @@ export async function getOverview(
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
) AS page_stats`;
diff --git a/server/src/api/getOverviewBucketed.ts b/server/src/api/getOverviewBucketed.ts
index 6d51a45e1..994b6d21c 100644
--- a/server/src/api/getOverviewBucketed.ts
+++ b/server/src/api/getOverviewBucketed.ts
@@ -1,6 +1,10 @@
import { FastifyReply, FastifyRequest } from "fastify";
import clickhouse from "../db/clickhouse/clickhouse.js";
-import { getTimeStatement, processResults } from "./utils.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
const TimeBucketToFn = {
hour: "toStartOfHour",
@@ -42,7 +46,7 @@ type getOverviewBucketed = { time: string; pageviews: number }[];
export async function getOverviewBucketed(
{
- query: { startDate, endDate, timezone, bucket, site },
+ query: { startDate, endDate, timezone, bucket, site, filters },
}: FastifyRequest<{
Querystring: {
startDate: string;
@@ -50,11 +54,13 @@ export async function getOverviewBucketed(
timezone: string;
bucket: TimeBucket;
site: string;
+ filters: string;
};
}>,
res: FastifyReply
) {
const isAllTime = !startDate && !endDate;
+ const filterStatement = getFilterStatement(filters);
const query = `SELECT
session_stats.time AS time,
@@ -85,6 +91,7 @@ FROM
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY session_id
)
@@ -105,6 +112,7 @@ FULL JOIN
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY time ORDER BY time ${
isAllTime
@@ -115,8 +123,6 @@ FULL JOIN
USING time
ORDER BY time`;
- console.info(query);
-
try {
const result = await clickhouse.query({
query,
diff --git a/server/src/api/getPages.ts b/server/src/api/getPages.ts
index c29fcfbeb..b411c69de 100644
--- a/server/src/api/getPages.ts
+++ b/server/src/api/getPages.ts
@@ -1,7 +1,11 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement, processResults } from "./utils.js";
import clickhouse from "../db/clickhouse/clickhouse.js";
import { GenericRequest } from "./types.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
type GetPagesResponse = {
pathname: string;
@@ -11,10 +15,12 @@ type GetPagesResponse = {
export async function getPages(
{
- query: { startDate, endDate, timezone, site },
+ query: { startDate, endDate, timezone, site, filters },
}: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
+ const filterStatement = getFilterStatement(filters);
+
const query = `
SELECT
pathname,
@@ -23,6 +29,7 @@ export async function getPages(
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY pathname
ORDER BY count desc
diff --git a/server/src/api/getReferrers.ts b/server/src/api/getReferrers.ts
index 34100e8a0..2625a5a41 100644
--- a/server/src/api/getReferrers.ts
+++ b/server/src/api/getReferrers.ts
@@ -1,7 +1,11 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement, processResults } from "./utils.js";
import clickhouse from "../db/clickhouse/clickhouse.js";
import { GenericRequest } from "./types.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
type GetReferrersResponse = {
referrer: string;
@@ -11,10 +15,12 @@ type GetReferrersResponse = {
export async function getReferrers(
{
- query: { startDate, endDate, timezone, site },
+ query: { startDate, endDate, timezone, site, filters },
}: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
+ const filterStatement = getFilterStatement(filters);
+
const query = `
SELECT
domainWithoutWWW(referrer) AS referrer,
@@ -23,6 +29,7 @@ export async function getReferrers(
FROM pageviews
WHERE
site_id = ${site}
+ ${filterStatement}
${getTimeStatement(startDate, endDate, timezone)}
GROUP BY referrer
ORDER BY count desc
diff --git a/server/src/api/types.ts b/server/src/api/types.ts
index 32ab153fc..bf2352780 100644
--- a/server/src/api/types.ts
+++ b/server/src/api/types.ts
@@ -1,8 +1,25 @@
+export type FilterType = "equals" | "not_equals" | "contains" | "not_contains";
+
+export type FilterParameter =
+ | "browser"
+ | "operating_system"
+ | "country"
+ | "device_type"
+ | "referrer"
+ | "pathname";
+
+export type Filter = {
+ parameter: FilterParameter;
+ value: string;
+ type: FilterType;
+};
+
export interface GenericRequest {
Querystring: {
startDate: string;
endDate: string;
timezone: string;
site: string;
+ filters: string;
};
}
diff --git a/server/src/api/utils.ts b/server/src/api/utils.ts
index 5a820ce24..479fc68d8 100644
--- a/server/src/api/utils.ts
+++ b/server/src/api/utils.ts
@@ -1,4 +1,5 @@
import { ResultSet } from "@clickhouse/client";
+import { Filter } from "./types.js";
export function getTimeStatement(
startDate: string,
@@ -35,3 +36,29 @@ export async function processResults<T>(
}
return data;
}
+
+export function getFilterStatement(filters: string) {
+ const filtersArray = JSON.parse(filters);
+ if (filtersArray.length === 0) {
+ return "";
+ }
+ return (
+ "AND " +
+ filtersArray
+ .map((filter: Filter) => {
+ if (filter.type === "equals") {
+ return `${filter.parameter} = '${filter.value}'`;
+ }
+ if (filter.type === "not_equals") {
+ return `${filter.parameter} != '${filter.value}'`;
+ }
+ if (filter.type === "contains") {
+ return `${filter.parameter} LIKE '${filter.value}'`;
+ }
+ if (filter.type === "not_contains") {
+ return `${filter.parameter} NOT LIKE '${filter.value}'`;
+ }
+ })
+ .join(" AND ")
+ );
+}