Skip to content

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

Add jszip dependency and implement standalone fetch functions for ana… (#756)

Bill Yange39875417398
diff --git a/client/package-lock.json b/client/package-lock.json
index 007740bbe..d6c4ddfc0 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -55,6 +55,7 @@
"geojson": "0.5.0",
"ip-address": "^10.0.1",
"jotai": "2.12.4",
+ "jszip": "^3.10.1",
"ldrs": "1.1.7",
"lodash": "4.17.21",
"lucide-react": "0.510.0",
@@ -6906,6 +6907,12 @@
"integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
"license": "MIT"
},
+ "node_modules/core-util-is": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
+ "license": "MIT"
+ },
"node_modules/cosmiconfig": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz",
@@ -8973,6 +8980,12 @@
"node": ">= 4"
}
},
+ "node_modules/immediate": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
+ "license": "MIT"
+ },
"node_modules/import-fresh": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@@ -8999,6 +9012,12 @@
"node": ">=0.8.19"
}
},
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
"node_modules/internal-slot": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
@@ -9595,6 +9614,24 @@
"node": ">=4.0"
}
},
+ "node_modules/jszip": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
+ "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",
+ "license": "(MIT OR GPL-3.0-or-later)",
+ "dependencies": {
+ "lie": "~3.3.0",
+ "pako": "~1.0.2",
+ "readable-stream": "~2.3.6",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/jszip/node_modules/pako": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
+ "license": "(MIT AND Zlib)"
+ },
"node_modules/kdbush": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.0.2.tgz",
@@ -9732,6 +9769,15 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/lie": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "immediate": "~3.0.5"
+ }
+ },
"node_modules/lightningcss": {
"version": "1.30.2",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz",
@@ -10900,6 +10946,12 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
+ "node_modules/process-nextick-args": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
+ "license": "MIT"
+ },
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
@@ -11233,6 +11285,27 @@
"react-dom": ">=16.6.0"
}
},
+ "node_modules/readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "license": "MIT",
+ "dependencies": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "node_modules/readable-stream/node_modules/isarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
+ "license": "MIT"
+ },
"node_modules/reflect-metadata": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
@@ -11448,6 +11521,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
+ "license": "MIT"
+ },
"node_modules/safe-push-apply": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",
@@ -11572,6 +11651,12 @@
"node": ">= 0.4"
}
},
+ "node_modules/setimmediate": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
+ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",
+ "license": "MIT"
+ },
"node_modules/sharp": {
"version": "0.34.5",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
@@ -11788,6 +11873,15 @@
"node": ">= 0.4"
}
},
+ "node_modules/string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
"node_modules/string.prototype.includes": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/string.prototype.includes/-/string.prototype.includes-2.0.1.tgz",
@@ -12484,6 +12578,12 @@
}
}
},
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "license": "MIT"
+ },
"node_modules/walk-up-path": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz",
diff --git a/client/package.json b/client/package.json
index 9df45a34e..612b1c752 100644
--- a/client/package.json
+++ b/client/package.json
@@ -59,6 +59,7 @@
"geojson": "0.5.0",
"ip-address": "^10.0.1",
"jotai": "2.12.4",
+ "jszip": "^3.10.1",
"ldrs": "1.1.7",
"lodash": "4.17.21",
"lucide-react": "0.510.0",
diff --git a/client/src/api/analytics/events/useGetEventNames.ts b/client/src/api/analytics/events/useGetEventNames.ts
index 7d6c9edec..31e846a55 100644
--- a/client/src/api/analytics/events/useGetEventNames.ts
+++ b/client/src/api/analytics/events/useGetEventNames.ts
@@ -1,6 +1,8 @@
+import { Filter } from "@rybbit/shared";
import { useQuery } from "@tanstack/react-query";
-import { getFilteredFilters, useStore } from "../../../lib/store";
+import { Time } from "../../../components/DateSelector/types";
import { EVENT_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../lib/store";
import { authedFetch, getQueryParams } from "../../utils";
export type EventName = {
@@ -27,3 +29,23 @@ export function useGetEventNames() {
},
});
}
+
+/**
+ * Standalone fetch function for event names (used for exports)
+ */
+export async function fetchEventNames(
+ site: number | string,
+ time: Time,
+ filters: Filter[] = []
+): Promise<EventName[]> {
+ const timeParams = getQueryParams(time);
+ const params = {
+ ...timeParams,
+ filters: filters.length > 0 ? filters : undefined,
+ };
+ const response = await authedFetch<{ data: EventName[] }>(
+ `/events/names/${site}`,
+ params
+ );
+ return response.data;
+}
diff --git a/client/src/api/analytics/events/useGetOutboundLinks.ts b/client/src/api/analytics/events/useGetOutboundLinks.ts
index 4fbfcef5c..b7a607d3a 100644
--- a/client/src/api/analytics/events/useGetOutboundLinks.ts
+++ b/client/src/api/analytics/events/useGetOutboundLinks.ts
@@ -1,6 +1,8 @@
+import { Filter } from "@rybbit/shared";
import { useQuery } from "@tanstack/react-query";
-import { getFilteredFilters, useStore } from "../../../lib/store";
+import { Time } from "../../../components/DateSelector/types";
import { EVENT_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../lib/store";
import { authedFetch, getQueryParams } from "../../utils";
export type OutboundLink = {
@@ -28,3 +30,23 @@ export function useGetOutboundLinks() {
},
});
}
+
+/**
+ * Standalone fetch function for outbound links (used for exports)
+ */
+export async function fetchOutboundLinks(
+ site: number | string,
+ time: Time,
+ filters: Filter[] = []
+): Promise<OutboundLink[]> {
+ const timeParams = getQueryParams(time);
+ const params = {
+ ...timeParams,
+ filters: filters.length > 0 ? filters : undefined,
+ };
+ const response = await authedFetch<{ data: OutboundLink[] }>(
+ `/events/outbound/${site}`,
+ params
+ );
+ return response.data;
+}
diff --git a/client/src/api/analytics/useGetMetric.ts b/client/src/api/analytics/useGetMetric.ts
index cbbd2d6dc..8460cf88e 100644
--- a/client/src/api/analytics/useGetMetric.ts
+++ b/client/src/api/analytics/useGetMetric.ts
@@ -176,3 +176,26 @@ export function useInfiniteMetric({
staleTime: 60_000,
});
}
+
+/**
+ * Standalone fetch function for metric data (used for exports)
+ */
+export async function fetchMetric(
+ site: number | string,
+ parameter: FilterParameter,
+ time: Time,
+ filters: Filter[] = [],
+ limit = 100
+): Promise<MetricResponse[]> {
+ const queryParams = {
+ ...getQueryParams(time),
+ parameter,
+ limit,
+ filters: filters.length > 0 ? filters : undefined,
+ };
+ const response = await authedFetch<{ data: { data: MetricResponse[] } }>(
+ `/metric/${site}`,
+ queryParams
+ );
+ return response.data.data;
+}
diff --git a/client/src/api/analytics/useGetOverviewBucketed.ts b/client/src/api/analytics/useGetOverviewBucketed.ts
index 3952114b7..c692959f1 100644
--- a/client/src/api/analytics/useGetOverviewBucketed.ts
+++ b/client/src/api/analytics/useGetOverviewBucketed.ts
@@ -1,4 +1,5 @@
import { Filter, TimeBucket } from "@rybbit/shared";
+import { Time } from "../../components/DateSelector/types";
import { UseQueryOptions, UseQueryResult, useQuery } from "@tanstack/react-query";
import { useStore } from "../../lib/store";
import { APIResponse } from "../types";
@@ -82,3 +83,20 @@ export function useGetOverviewBucketed({
...props,
});
}
+
+/**
+ * Standalone fetch function for overview bucketed data (used for exports)
+ */
+export async function fetchOverviewBucketed(
+ site: number | string,
+ time: Time,
+ bucket: TimeBucket = "day",
+ filters: Filter[] = []
+): Promise<GetOverviewBucketedResponse> {
+ const queryParams = getQueryParams(time, { bucket, filters });
+ const response = await authedFetch<APIResponse<GetOverviewBucketedResponse>>(
+ `/overview-bucketed/${site}`,
+ queryParams
+ );
+ return response.data;
+}
diff --git a/client/src/api/gsc/useGSCConnection.ts b/client/src/api/gsc/useGSCConnection.ts
index 18bfa0d6c..43fa72d0a 100644
--- a/client/src/api/gsc/useGSCConnection.ts
+++ b/client/src/api/gsc/useGSCConnection.ts
@@ -60,3 +60,12 @@ export function useDisconnectGSC() {
},
});
}
+
+/**
+ * Standalone fetch function for GSC connection status (used for exports)
+ */
+export async function fetchGSCConnectionStatus(
+ site: number | string
+): Promise<GSCConnectionStatus> {
+ return authedFetch<GSCConnectionStatus>(`/gsc/status/${site}`);
+}
diff --git a/client/src/api/gsc/useGSCData.ts b/client/src/api/gsc/useGSCData.ts
index e1a5ed180..490b48775 100644
--- a/client/src/api/gsc/useGSCData.ts
+++ b/client/src/api/gsc/useGSCData.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { Time } from "../../components/DateSelector/types";
import { useStore } from "../../lib/store";
import { authedFetch, getQueryParams } from "../utils";
@@ -33,3 +34,19 @@ export function useGSCData(dimension: GSCDimension) {
staleTime: 5 * 60 * 1000, // 5 minutes
});
}
+
+/**
+ * Standalone fetch function for GSC data (used for exports)
+ */
+export async function fetchGSCData(
+ site: number | string,
+ dimension: GSCDimension,
+ time: Time
+): Promise<GSCData[]> {
+ const timeParams = getQueryParams(time);
+ const response = await authedFetch<{ data: GSCData[] }>(`/gsc/data/${site}`, {
+ ...timeParams,
+ dimension,
+ });
+ return response.data;
+}
diff --git a/client/src/app/[site]/components/SubHeader/ShareSite.tsx b/client/src/app/[site]/components/SubHeader/ShareSite.tsx
index c73469c49..821648e09 100644
--- a/client/src/app/[site]/components/SubHeader/ShareSite.tsx
+++ b/client/src/app/[site]/components/SubHeader/ShareSite.tsx
@@ -1,37 +1,34 @@
-import { Copy, Share, Trash } from "lucide-react";
-import { Button } from "../../../../components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuItem,
- DropdownMenuContent,
- DropdownMenuTrigger,
-} from "../../../../components/ui/dropdown-menu";
-import { Input } from "../../../../components/ui/input";
+import { Copy, Share } from "lucide-react";
+import { useParams } from "next/navigation";
+import { toast } from "sonner";
import {
useGeneratePrivateLinkKey,
useGetPrivateLinkConfig,
useRevokePrivateLinkKey,
} from "../../../../api/admin/privateLink";
-import { useParams } from "next/navigation";
-import { toast } from "sonner";
+import { Button } from "../../../../components/ui/button";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from "../../../../components/ui/dropdown-menu";
+import { Input } from "../../../../components/ui/input";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
export function ShareSite() {
const { site } = useParams();
- const {
- data: privateLink,
- isLoading: isLoadingPrivateLink,
- refetch: refetchPrivateLink,
- } = useGetPrivateLinkConfig(Number(site));
+ const { data: privateLink, isLoading: isLoadingPrivateLink } = useGetPrivateLinkConfig(Number(site));
const { mutate: generatePrivateLinkKey, isPending: isGeneratingPrivateLink } = useGeneratePrivateLinkKey();
const { mutate: revokePrivateLinkKey } = useRevokePrivateLinkKey();
return (
<DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="secondary" size="icon" onClick={() => {}} className="h-8 w-8">
- <Share />
- </Button>
- </DropdownMenuTrigger>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" size="icon" onClick={() => {}} className="h-8 w-8">
+ <Share />
+ </Button>
+ </DropdownMenuTrigger>
+ </TooltipTrigger>
+ <TooltipContent>Share a private link</TooltipContent>
+ </Tooltip>
<DropdownMenuContent align="end" className="flex flex-col p-3 max-w-[400px]">
<span className="text-sm font-medium pb-2">Share this dashboard</span>
{!isLoadingPrivateLink && !privateLink?.privateLinkKey && (
diff --git a/client/src/app/[site]/main/components/ExportButton.tsx b/client/src/app/[site]/main/components/ExportButton.tsx
new file mode 100644
index 000000000..be9064755
--- /dev/null
+++ b/client/src/app/[site]/main/components/ExportButton.tsx
@@ -0,0 +1,258 @@
+"use client";
+
+import { FilterParameter } from "@rybbit/shared";
+import { Download, Loader2 } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { fetchEventNames } from "../../../../api/analytics/events/useGetEventNames";
+import { fetchOutboundLinks } from "../../../../api/analytics/events/useGetOutboundLinks";
+import { fetchMetric } from "../../../../api/analytics/useGetMetric";
+import { fetchOverviewBucketed } from "../../../../api/analytics/useGetOverviewBucketed";
+import { fetchGSCConnectionStatus } from "../../../../api/gsc/useGSCConnection";
+import { fetchGSCData, GSCDimension } from "../../../../api/gsc/useGSCData";
+import { Button } from "../../../../components/ui/button";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "../../../../components/ui/tooltip";
+import { IS_CLOUD } from "../../../../lib/const";
+import { CSVFile, downloadZip, formatDateForFilename } from "../../../../lib/export";
+import { useStore } from "../../../../lib/store";
+
+// Metric parameters for each section
+const REFERRER_METRICS: { param: FilterParameter; filename: string }[] = [
+ { param: "referrer", filename: "referrers.csv" },
+ { param: "channel", filename: "channels.csv" },
+ { param: "utm_source", filename: "utm-source.csv" },
+ { param: "utm_medium", filename: "utm-medium.csv" },
+ { param: "utm_campaign", filename: "utm-campaign.csv" },
+ { param: "utm_term", filename: "utm-term.csv" },
+ { param: "utm_content", filename: "utm-content.csv" },
+];
+
+const PAGE_METRICS: { param: FilterParameter; filename: string }[] = [
+ { param: "pathname", filename: "pages.csv" },
+ { param: "page_title", filename: "page-titles.csv" },
+ { param: "entry_page", filename: "entry-pages.csv" },
+ { param: "exit_page", filename: "exit-pages.csv" },
+ { param: "hostname", filename: "hostnames.csv" },
+];
+
+const DEVICE_METRICS: { param: FilterParameter; filename: string }[] = [
+ { param: "browser", filename: "browsers.csv" },
+ { param: "device_type", filename: "devices.csv" },
+ { param: "operating_system", filename: "operating-systems.csv" },
+ { param: "dimensions", filename: "screen-dimensions.csv" },
+];
+
+const COUNTRY_METRICS: { param: FilterParameter; filename: string }[] = [
+ { param: "country", filename: "countries.csv" },
+ { param: "region", filename: "regions.csv" },
+ { param: "city", filename: "cities.csv" },
+ { param: "language", filename: "languages.csv" },
+ { param: "timezone", filename: "timezones.csv" },
+];
+
+const NETWORK_METRICS: { param: FilterParameter; filename: string }[] = [
+ { param: "vpn", filename: "vpn.csv" },
+ { param: "crawler", filename: "crawlers.csv" },
+ { param: "datacenter", filename: "datacenters.csv" },
+ { param: "company", filename: "companies.csv" },
+ { param: "company_type", filename: "company-types.csv" },
+ { param: "company_domain", filename: "company-domains.csv" },
+ { param: "asn_org", filename: "asn-orgs.csv" },
+ { param: "asn_type", filename: "asn-types.csv" },
+ { param: "asn_domain", filename: "asn-domains.csv" },
+];
+
+const GSC_DIMENSIONS: { dimension: GSCDimension; filename: string }[] = [
+ { dimension: "query", filename: "gsc-queries.csv" },
+ { dimension: "page", filename: "gsc-pages.csv" },
+ { dimension: "country", filename: "gsc-countries.csv" },
+ { dimension: "device", filename: "gsc-devices.csv" },
+];
+
+export function ExportButton() {
+ const [isExporting, setIsExporting] = useState(false);
+ const { site, time, filters } = useStore();
+
+ const handleExport = async () => {
+ if (!site) {
+ toast.error("No site selected");
+ return;
+ }
+
+ setIsExporting(true);
+ const csvFiles: CSVFile[] = [];
+
+ try {
+ // Fetch all metrics in parallel
+ const allMetrics = [
+ ...REFERRER_METRICS,
+ ...PAGE_METRICS,
+ ...DEVICE_METRICS,
+ ...COUNTRY_METRICS,
+ ...(IS_CLOUD ? NETWORK_METRICS : []),
+ ];
+
+ const metricPromises = allMetrics.map(async ({ param, filename }) => {
+ try {
+ const data = await fetchMetric(site, param, time, filters);
+ return { filename, data: data as Record<string, unknown>[] };
+ } catch {
+ console.warn(`Failed to fetch ${param}`);
+ return { filename, data: [] };
+ }
+ });
+
+ // Fetch overview bucketed data
+ const overviewPromise = (async () => {
+ try {
+ const data = await fetchOverviewBucketed(site, time, "day", filters);
+ return {
+ filename: "overview-timeseries.csv",
+ data: data as unknown as Record<string, unknown>[],
+ };
+ } catch {
+ console.warn("Failed to fetch overview bucketed");
+ return { filename: "overview-timeseries.csv", data: [] };
+ }
+ })();
+
+ // Fetch weekdays heatmap data (hourly bucketed)
+ const weekdaysPromise = (async () => {
+ try {
+ const data = await fetchOverviewBucketed(site, time, "hour", filters);
+ return {
+ filename: "weekdays-heatmap.csv",
+ data: data as unknown as Record<string, unknown>[],
+ };
+ } catch {
+ console.warn("Failed to fetch weekdays data");
+ return { filename: "weekdays-heatmap.csv", data: [] };
+ }
+ })();
+
+ // Fetch events data
+ const eventsPromise = (async () => {
+ try {
+ const data = await fetchEventNames(site, time, filters);
+ return {
+ filename: "events.csv",
+ data: data as unknown as Record<string, unknown>[],
+ };
+ } catch {
+ console.warn("Failed to fetch events");
+ return { filename: "events.csv", data: [] };
+ }
+ })();
+
+ // Fetch outbound links
+ const outboundPromise = (async () => {
+ try {
+ const data = await fetchOutboundLinks(site, time, filters);
+ return {
+ filename: "outbound-links.csv",
+ data: data as unknown as Record<string, unknown>[],
+ };
+ } catch {
+ console.warn("Failed to fetch outbound links");
+ return { filename: "outbound-links.csv", data: [] };
+ }
+ })();
+
+ // Check GSC connection and fetch if connected
+ const gscPromises = (async () => {
+ try {
+ const status = await fetchGSCConnectionStatus(site);
+ if (!status.connected) {
+ return [];
+ }
+
+ const gscResults = await Promise.all(
+ GSC_DIMENSIONS.map(async ({ dimension, filename }) => {
+ try {
+ const data = await fetchGSCData(site, dimension, time);
+ return {
+ filename,
+ data: data as unknown as Record<string, unknown>[],
+ };
+ } catch {
+ console.warn(`Failed to fetch GSC ${dimension}`);
+ return { filename, data: [] };
+ }
+ })
+ );
+ return gscResults;
+ } catch {
+ console.warn("Failed to check GSC connection");
+ return [];
+ }
+ })();
+
+ // Wait for all fetches to complete
+ const [metricResults, overview, weekdays, events, outbound, gscResults] =
+ await Promise.all([
+ Promise.all(metricPromises),
+ overviewPromise,
+ weekdaysPromise,
+ eventsPromise,
+ outboundPromise,
+ gscPromises,
+ ]);
+
+ // Collect all CSV files
+ csvFiles.push(...metricResults);
+ csvFiles.push(overview);
+ csvFiles.push(weekdays);
+ csvFiles.push(events);
+ csvFiles.push(outbound);
+ csvFiles.push(...gscResults);
+
+ // Filter out empty files
+ const nonEmptyFiles = csvFiles.filter((f) => f.data.length > 0);
+
+ if (nonEmptyFiles.length === 0) {
+ toast.error("No data to export");
+ return;
+ }
+
+ // Generate ZIP filename
+ const dateStr = formatDateForFilename();
+ const zipFilename = `rybbit-export-${site}-${dateStr}.zip`;
+
+ // Download the ZIP
+ await downloadZip(nonEmptyFiles, zipFilename);
+
+ toast.success(`Exported ${nonEmptyFiles.length} files`);
+ } catch (error) {
+ console.error("Export failed:", error);
+ toast.error("Export failed. Please try again.");
+ } finally {
+ setIsExporting(false);
+ }
+ };
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="smIcon"
+ onClick={handleExport}
+ disabled={isExporting}
+ >
+ {isExporting ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Download className="h-4 w-4" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Export all data as CSV (ZIP)</p>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
index 12086496f..514387a9e 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -1,18 +1,18 @@
"use client";
import { Card, CardContent, CardLoader } from "@/components/ui/card";
import { Tilt_Warp } from "next/font/google";
-import Image from "next/image";
import Link from "next/link";
import { useGetOverview } from "../../../../../api/analytics/useGetOverview";
import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";
+import { BucketSelection } from "../../../../../components/BucketSelection";
+import { RybbitLogo } from "../../../../../components/RybbitLogo";
import { authClient } from "../../../../../lib/auth";
import { useStore } from "../../../../../lib/store";
import { cn } from "../../../../../lib/utils";
-import { BucketSelection } from "../../../../../components/BucketSelection";
+import { ExportButton } from "../ExportButton";
import { Chart } from "./Chart";
import { Overview } from "./Overview";
import { PreviousChart } from "./PreviousChart";
-import { RybbitLogo } from "../../../../../components/RybbitLogo";
const SELECTED_STAT_MAP = {
pageviews: "Pageviews",
@@ -83,7 +83,10 @@ export function MainSection() {
</Link>
</div>
<span className="text-sm text-neutral-700 dark:text-neutral-200">{SELECTED_STAT_MAP[selectedStat]}</span>
- <BucketSelection />
+ <div className="flex items-center gap-2">
+ <ExportButton />
+ <BucketSelection />
+ </div>
</div>
<div className="h-[200px] md:h-[290px] relative">
<div className="absolute top-0 left-0 w-full h-full">
diff --git a/client/src/components/BucketSelection.tsx b/client/src/components/BucketSelection.tsx
index bc241f05e..b31a990bf 100644
--- a/client/src/components/BucketSelection.tsx
+++ b/client/src/components/BucketSelection.tsx
@@ -160,7 +160,7 @@ export function BucketSelection() {
<Select value={bucket} onValueChange={setBucket}>
<SelectTrigger className="w-[90px]" size="sm">
<div className="flex items-center gap-1">
- <TimerReset className="w-4 h-4" />
+ <TimerReset className="w-3 h-3" />
<SelectValue />
</div>
</SelectTrigger>
diff --git a/client/src/components/ui/tooltip.tsx b/client/src/components/ui/tooltip.tsx
index 41f800d6c..851755f64 100644
--- a/client/src/components/ui/tooltip.tsx
+++ b/client/src/components/ui/tooltip.tsx
@@ -22,7 +22,7 @@ const TooltipContent = React.forwardRef<
ref={ref}
sideOffset={sideOffset}
className={cn(
- "z-50 overflow-hidden rounded-md bg-white border border-neutral-100 px-2 py-2 text-xs text-neutral-900 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:bg-neutral-800 dark:border-neutral-750 dark:text-neutral-50",
+ "z-50 overflow-hidden shadow-lg rounded-md bg-white border border-neutral-100 px-2 py-2 text-xs text-neutral-900 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:bg-neutral-800 dark:border-neutral-750 dark:text-neutral-50",
className
)}
{...props}
diff --git a/client/src/lib/export.ts b/client/src/lib/export.ts
new file mode 100644
index 000000000..75660e22e
--- /dev/null
+++ b/client/src/lib/export.ts
@@ -0,0 +1,53 @@
+import JSZip from "jszip";
+import Papa from "papaparse";
+
+export type CSVFile = {
+ filename: string;
+ data: Record<string, unknown>[];
+};
+
+/**
+ * Generate a CSV string from an array of objects
+ */
+export function generateCSV(data: Record<string, unknown>[]): string {
+ if (data.length === 0) {
+ return "";
+ }
+ return Papa.unparse(data);
+}
+
+/**
+ * Create a ZIP file containing multiple CSVs and trigger download
+ */
+export async function downloadZip(
+ files: CSVFile[],
+ zipFilename: string
+): Promise<void> {
+ const zip = new JSZip();
+
+ for (const file of files) {
+ if (file.data.length > 0) {
+ const csvContent = generateCSV(file.data);
+ zip.file(file.filename, csvContent);
+ }
+ }
+
+ const blob = await zip.generateAsync({ type: "blob" });
+
+ // Create download link and trigger download
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = zipFilename;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
+
+/**
+ * Format a date for use in filenames
+ */
+export function formatDateForFilename(date: Date = new Date()): string {
+ return date.toISOString().split("T")[0];
+}
diff --git a/docs/content/docs/api/stats/errors.mdx b/docs/content/docs/api/stats/errors.mdx
index aced99ab4..6cab269c2 100644
--- a/docs/content/docs/api/stats/errors.mdx
+++ b/docs/content/docs/api/stats/errors.mdx
@@ -53,7 +53,7 @@ Returns a list of unique error messages with occurrence counts and affected sess
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -284,7 +284,7 @@ Returns individual error occurrences for a specific error message, with full con
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -557,7 +557,7 @@ Returns error occurrence counts over time for a specific error message. Useful f
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
diff --git a/docs/content/docs/api/stats/events.mdx b/docs/content/docs/api/stats/events.mdx
index 7ab8db5fd..afb42ce3d 100644
--- a/docs/content/docs/api/stats/events.mdx
+++ b/docs/content/docs/api/stats/events.mdx
@@ -57,7 +57,7 @@ Returns a paginated list of events (pageviews, custom events, and outbound click
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -341,7 +341,7 @@ Returns a list of unique custom event names with their occurrence counts.
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) (time and filters).
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) (time and filters).
### Response
@@ -540,7 +540,7 @@ Returns property key-value pairs for a specific event name with their occurrence
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -763,7 +763,7 @@ Returns a list of outbound link clicks with their occurrence counts.
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) (time and filters).
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) (time and filters).
### Response
diff --git a/docs/content/docs/api/stats/funnels.mdx b/docs/content/docs/api/stats/funnels.mdx
index 25b47a1d4..5bb418e62 100644
--- a/docs/content/docs/api/stats/funnels.mdx
+++ b/docs/content/docs/api/stats/funnels.mdx
@@ -295,7 +295,7 @@ Analyzes a funnel and returns step-by-step conversion data. Sessions must comple
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) (time and filters).
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) (time and filters).
### Request Body
@@ -710,7 +710,7 @@ Returns sessions that either reached or dropped off at a specific funnel step. U
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
diff --git a/docs/content/docs/api/stats/goals.mdx b/docs/content/docs/api/stats/goals.mdx
index 0c159b989..f8f1a8299 100644
--- a/docs/content/docs/api/stats/goals.mdx
+++ b/docs/content/docs/api/stats/goals.mdx
@@ -61,7 +61,7 @@ Returns a paginated list of goals with their conversion metrics.
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -421,7 +421,7 @@ Returns sessions that completed a specific goal. Useful for analyzing the behavi
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
diff --git a/docs/content/docs/api/stats/misc.mdx b/docs/content/docs/api/stats/misc.mdx
index 88f49efcd..385b19a91 100644
--- a/docs/content/docs/api/stats/misc.mdx
+++ b/docs/content/docs/api/stats/misc.mdx
@@ -328,7 +328,7 @@ Returns the most common page navigation paths (user journeys) within sessions. U
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
diff --git a/docs/content/docs/api/stats/overview.mdx b/docs/content/docs/api/stats/overview.mdx
index 271b2a104..95b30b56f 100644
--- a/docs/content/docs/api/stats/overview.mdx
+++ b/docs/content/docs/api/stats/overview.mdx
@@ -57,7 +57,7 @@ Returns high-level analytics metrics for a site.
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) (time and filters).
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) (time and filters).
### Response
@@ -253,7 +253,7 @@ Returns time-series analytics data broken down by configurable time buckets. Use
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -498,7 +498,7 @@ Returns dimensional analytics data broken down by a specific parameter. Supports
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
diff --git a/docs/content/docs/api/stats/performance.mdx b/docs/content/docs/api/stats/performance.mdx
index 065edcb7c..aa5ad9ebb 100644
--- a/docs/content/docs/api/stats/performance.mdx
+++ b/docs/content/docs/api/stats/performance.mdx
@@ -65,7 +65,7 @@ Returns aggregate performance metrics with percentile breakdowns for all Core We
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) (time and filters).
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) (time and filters).
### Response
@@ -287,7 +287,7 @@ Returns performance metrics over time, broken down by configurable time buckets.
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -518,7 +518,7 @@ Returns performance metrics broken down by a specific dimension (page, country,
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
diff --git a/docs/content/docs/api/stats/sessions.mdx b/docs/content/docs/api/stats/sessions.mdx
index 71db7e96a..542957a84 100644
--- a/docs/content/docs/api/stats/sessions.mdx
+++ b/docs/content/docs/api/stats/sessions.mdx
@@ -53,7 +53,7 @@ Returns a paginated list of sessions with their analytics data.
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -653,7 +653,7 @@ Returns aggregated session locations with coordinates for map visualization.
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) (time and filters).
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) (time and filters).
### Response
diff --git a/docs/content/docs/api/stats/users.mdx b/docs/content/docs/api/stats/users.mdx
index 6f07fd1ea..b8da00d34 100644
--- a/docs/content/docs/api/stats/users.mdx
+++ b/docs/content/docs/api/stats/users.mdx
@@ -57,7 +57,7 @@ Returns a paginated list of users with their analytics data. Supports filtering
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) plus the following:
<TypeTable
type={{
@@ -374,7 +374,7 @@ Returns all sessions for a specific user, grouped with their pageviews. Useful f
### Query Parameters
-Accepts all [Common Parameters](/docs/api/stats/reference#common-parameters) (time and filters).
+Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) (time and filters).
### Response