🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
gsc (#670)
Bill Yangd2be386163d5
diff --git a/client/package-lock.json b/client/package-lock.jsonindex 26ed70eb2..42acad91e 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -23,6 +23,7 @@"@radix-ui/react-label": "2.1.6","@radix-ui/react-navigation-menu": "1.2.12","@radix-ui/react-popover": "1.1.13",+ "@radix-ui/react-radio-group": "^1.3.8","@radix-ui/react-scroll-area": "^1.2.9","@radix-ui/react-select": "2.2.4","@radix-ui/react-separator": "1.1.6",@@ -4948,17 +4949,18 @@}},"node_modules/@radix-ui/react-radio-group": {- "version": "1.3.7",- "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.3.7.tgz",- "integrity": "sha512-9w5XhD0KPOrm92OTTE0SysH3sYzHsSTHNvZgUBo/VZ80VdYyB5RneDbc0dKpURS24IxkoFRu/hI0i4XyfFwY6g==",+ "version": "1.3.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.3.8.tgz",+ "integrity": "sha512-VBKYIYImA5zsxACdisNQ3BjCBfmbGH3kQlnFVqlWU4tXwjy7cGX8ta80BcrO+WJXIn5iBylEH3K6ZTlee//lgQ==",+ "license": "MIT","dependencies": {- "@radix-ui/primitive": "1.1.2",+ "@radix-ui/primitive": "1.1.3","@radix-ui/react-compose-refs": "1.1.2","@radix-ui/react-context": "1.1.2","@radix-ui/react-direction": "1.1.1",- "@radix-ui/react-presence": "1.1.4",+ "@radix-ui/react-presence": "1.1.5","@radix-ui/react-primitive": "2.1.3",- "@radix-ui/react-roving-focus": "1.1.10",+ "@radix-ui/react-roving-focus": "1.1.11","@radix-ui/react-use-controllable-state": "1.2.2","@radix-ui/react-use-previous": "1.1.1","@radix-ui/react-use-size": "1.1.1"@@ -4978,10 +4980,17 @@}}},+ "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/primitive": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",+ "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",+ "license": "MIT"+ },"node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-collection": {"version": "1.1.7","resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz","integrity": "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==",+ "license": "MIT","dependencies": {"@radix-ui/react-compose-refs": "1.1.2","@radix-ui/react-context": "1.1.2",@@ -5003,10 +5012,35 @@}}},+ "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-presence": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",+ "integrity": "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-primitive": {"version": "2.1.3","resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz","integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",+ "license": "MIT","dependencies": {"@radix-ui/react-slot": "1.2.3"},@@ -5026,11 +5060,12 @@}},"node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-roving-focus": {- "version": "1.1.10",- "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.10.tgz",- "integrity": "sha512-dT9aOXUen9JSsxnMPv/0VqySQf5eDQ6LCk5Sw28kamz8wSOW2bJdlX2Bg5VUIIcV+6XlHpWTIuTPCf/UNIyq8Q==",+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz",+ "integrity": "sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==",+ "license": "MIT","dependencies": {- "@radix-ui/primitive": "1.1.2",+ "@radix-ui/primitive": "1.1.3","@radix-ui/react-collection": "1.1.7","@radix-ui/react-compose-refs": "1.1.2","@radix-ui/react-context": "1.1.2",@@ -5059,6 +5094,7 @@"version": "1.2.3","resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz","integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT","dependencies": {"@radix-ui/react-compose-refs": "1.1.2"},@@ -10291,6 +10327,38 @@}}},+ "node_modules/radix-ui/node_modules/@radix-ui/react-radio-group": {+ "version": "1.3.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.3.7.tgz",+ "integrity": "sha512-9w5XhD0KPOrm92OTTE0SysH3sYzHsSTHNvZgUBo/VZ80VdYyB5RneDbc0dKpURS24IxkoFRu/hI0i4XyfFwY6g==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.2",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-presence": "1.1.4",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-roving-focus": "1.1.10",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-use-previous": "1.1.1",+ "@radix-ui/react-use-size": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"node_modules/radix-ui/node_modules/@radix-ui/react-roving-focus": {"version": "1.1.10","resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.10.tgz",diff --git a/client/package.json b/client/package.jsonindex cb3a3dcae..18c02c507 100644--- a/client/package.json+++ b/client/package.json@@ -27,6 +27,7 @@"@radix-ui/react-label": "2.1.6","@radix-ui/react-navigation-menu": "1.2.12","@radix-ui/react-popover": "1.1.13",+ "@radix-ui/react-radio-group": "^1.3.8","@radix-ui/react-scroll-area": "^1.2.9","@radix-ui/react-select": "2.2.4","@radix-ui/react-separator": "1.1.6",diff --git a/client/src/api/gsc/useGSCConnection.ts b/client/src/api/gsc/useGSCConnection.tsnew file mode 100644index 000000000..18bfa0d6c--- /dev/null+++ b/client/src/api/gsc/useGSCConnection.ts@@ -0,0 +1,62 @@+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useStore } from "../../lib/store";+import { authedFetch } from "../utils";++export type GSCConnectionStatus = {+ connected: boolean;+ gscPropertyUrl: string | null;+};++/**+ * Hook to check if the current site has a GSC connection+ */+export function useGSCConnection() {+ const { site } = useStore();++ return useQuery({+ queryKey: ["gsc-status", site],+ enabled: !!site,+ queryFn: () => {+ return authedFetch<GSCConnectionStatus>(`/gsc/status/${site}`);+ },+ });+}++/**+ * Hook to initiate GSC connection (get OAuth URL)+ */+export function useConnectGSC() {+ const { site } = useStore();++ return useMutation({+ mutationFn: async () => {+ const response = await authedFetch<{ authUrl: string }>(`/gsc/connect/${site}`);+ // Redirect to Google OAuth+ window.location.href = response.authUrl;+ return response;+ },+ });+}++/**+ * Hook to disconnect GSC from a site+ */+export function useDisconnectGSC() {+ const { site } = useStore();+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async () => {+ return authedFetch<{ success: boolean }>(`/gsc/disconnect/${site}`, undefined, {+ method: "DELETE",+ });+ },+ onSuccess: () => {+ // Invalidate connection status query+ queryClient.invalidateQueries({ queryKey: ["gsc-status", site] });+ // Invalidate data queries+ queryClient.invalidateQueries({ queryKey: ["gsc-queries", site] });+ queryClient.invalidateQueries({ queryKey: ["gsc-pages", site] });+ },+ });+}diff --git a/client/src/api/gsc/useGSCData.ts b/client/src/api/gsc/useGSCData.tsnew file mode 100644index 000000000..e1a5ed180--- /dev/null+++ b/client/src/api/gsc/useGSCData.ts@@ -0,0 +1,35 @@+import { useQuery } from "@tanstack/react-query";+import { useStore } from "../../lib/store";+import { authedFetch, getQueryParams } from "../utils";++export type GSCDimension = "query" | "page" | "country" | "device";++export type GSCData = {+ name: string;+ clicks: number;+ impressions: number;+ ctr: number;+ position: number;+};++/**+ * Hook to fetch data from Google Search Console for a specific dimension+ */+export function useGSCData(dimension: GSCDimension) {+ const { site, time } = useStore();++ const timeParams = getQueryParams(time);++ return useQuery({+ queryKey: ["gsc-data", dimension, site, timeParams],+ enabled: !!site,+ queryFn: () => {+ return authedFetch<{ data: GSCData[] }>(`/gsc/data/${site}`, {+ ...timeParams,+ dimension,+ }).then((res) => res.data);+ },+ // Refetch less frequently since GSC data updates slowly+ staleTime: 5 * 60 * 1000, // 5 minutes+ });+}diff --git a/client/src/app/[site]/components/shared/StandardSection/Skeleton.tsx b/client/src/app/[site]/components/shared/StandardSection/Skeleton.tsxindex 4392a0426..9a73fffe6 100644--- a/client/src/app/[site]/components/shared/StandardSection/Skeleton.tsx+++ b/client/src/app/[site]/components/shared/StandardSection/Skeleton.tsx@@ -1,6 +1,6 @@import { memo } from "react";-export const Skeleton = memo(() => {+export const StandardSkeleton = memo(() => {// Generate widths following Pareto principle with top item at 100%const widths = Array.from({ length: 10 }, (_, i) => {if (i === 0) {@@ -29,10 +29,6 @@ export const Skeleton = memo(() => {return (<>- <div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-400">- <div className="h-4 bg-neutral-800 rounded animate-pulse w-16"></div>- <div className="h-4 bg-neutral-800 rounded animate-pulse w-12"></div>- </div>{Array.from({ length: 10 }).map((_, index) => (<div key={index} className="relative h-6 flex items-center"><divdiff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsxindex f80cdd434..5bb8b2529 100644--- a/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx+++ b/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx@@ -3,16 +3,15 @@import { Button } from "@/components/ui/button";import { FilterParameter } from "@rybbit/shared";import { AlertCircle, Info, RefreshCcw } from "lucide-react";+import Link from "next/link";import { ReactNode } from "react";-import { usePaginatedSingleCol } from "../../../../../api/analytics/useSingleCol";-import { SingleColResponse } from "../../../../../api/analytics/useSingleCol";+import { SingleColResponse, usePaginatedSingleCol } from "../../../../../api/analytics/useSingleCol";import { CardLoader } from "../../../../../components/ui/card";-import { Row } from "./Row";-import { Skeleton } from "./Skeleton";-import { StandardSectionDialog } from "./StandardSectionDialog";import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";-import Link from "next/link";import { IS_CLOUD } from "../../../../../lib/const";+import { Row } from "./Row";+import { StandardSkeleton } from "./Skeleton";+import { StandardSectionDialog } from "./StandardSectionDialog";const MAX_ITEMS_TO_DISPLAY = 10;@@ -60,9 +59,28 @@ export function StandardSection({<CardLoader /></div>)}- <div className="flex flex-col gap-2 max-h-[344px] overflow-y-auto">+ <div className="flex flex-col gap-2 max-h-[344px] overflow-y-auto overflow-x-hidden">+ <div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-400">+ <div className="flex flex-row gap-1 items-center">+ {title}+ {IS_CLOUD && ["Countries", "Regions", "Cities"].includes(title) && (+ <Tooltip>+ <TooltipTrigger>+ <Info className="w-3 h-3" />+ </TooltipTrigger>+ <TooltipContent>+ Geolocation by{" "}+ <Link href="https://ipapi.is/" target="_blank" className="text-emerald-400 hover:text-emerald-300">+ ipapi.is+ </Link>+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ <div>{countLabel || "Sessions"}</div>+ </div>{isLoading ? (- <Skeleton />+ <StandardSkeleton />) : error ? (<div className="py-6 flex-1 flex flex-col items-center justify-center gap-3 transition-all"><AlertCircle className="text-amber-400 w-8 h-8" />@@ -82,30 +100,7 @@ export function StandardSection({</Button></div>) : (- <div className="flex flex-col gap-2 overflow-x-hidden">- <div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-400">- <div className="flex flex-row gap-1 items-center">- {title}- {IS_CLOUD && ["Countries", "Regions", "Cities"].includes(title) && (- <Tooltip>- <TooltipTrigger>- <Info className="w-3 h-3" />- </TooltipTrigger>- <TooltipContent>- Geolocation by{" "}- <Link- href="https://ipapi.is/"- target="_blank"- className="text-emerald-400 hover:text-emerald-300"- >- ipapi.is- </Link>- </TooltipContent>- </Tooltip>- )}- </div>- <div>{countLabel || "Sessions"}</div>- </div>+ <>{itemsForDisplay?.length ? (itemsForDisplay.slice(0, MAX_ITEMS_TO_DISPLAY)@@ -129,7 +124,7 @@ export function StandardSection({No Data</div>)}- </div>+ </>)}{!isLoading && !error && itemsForDisplay?.length ? (<div className="flex flex-row gap-2 justify-between items-center">diff --git a/client/src/app/[site]/events/components/EventList.tsx b/client/src/app/[site]/events/components/EventList.tsxindex 68040947e..7ea845be1 100644--- a/client/src/app/[site]/events/components/EventList.tsx+++ b/client/src/app/[site]/events/components/EventList.tsx@@ -94,7 +94,7 @@ export function EventList({ events, isLoading, size = "small" }: EventListProps)if (!events || events.length === 0) {return size === "small" ? (<div className="flex flex-col gap-2">- <div className="text-neutral-100 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">+ <div className="text-neutral-300 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center"><Info className="w-5 h-5" />No Data</div>diff --git a/client/src/app/[site]/gsc/select-property/page.tsx b/client/src/app/[site]/gsc/select-property/page.tsxnew file mode 100644index 000000000..096a158e6--- /dev/null+++ b/client/src/app/[site]/gsc/select-property/page.tsx@@ -0,0 +1,114 @@+"use client";++import { useSearchParams, useParams, useRouter } from "next/navigation";+import { useState } from "react";+import { Button } from "@/components/ui/button";+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { Label } from "@/components/ui/label";+import { toast } from "sonner";+import { authedFetch } from "@/api/utils";++export default function SelectGSCPropertyPage() {+ const searchParams = useSearchParams();+ const params = useParams();+ const router = useRouter();+ const site = params.site as string;++ const [selectedProperty, setSelectedProperty] = useState<string>("");+ const [isSubmitting, setIsSubmitting] = useState(false);++ // Parse properties from query params+ const propertiesParam = searchParams.get("properties");+ const properties: string[] = propertiesParam ? JSON.parse(decodeURIComponent(propertiesParam)) : [];++ const handleSubmit = async () => {+ if (!selectedProperty) {+ toast.error("Please select a property");+ return;+ }++ setIsSubmitting(true);+ try {+ await authedFetch(`/gsc/select-property/${site}`, undefined, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ data: {+ propertyUrl: selectedProperty,+ },+ });++ toast.success("Google Search Console connected successfully");+ // Redirect to main page+ router.push(`/${site}/main`);+ } catch (error) {+ console.error("Error selecting property:", error);+ toast.error("Failed to connect property");+ } finally {+ setIsSubmitting(false);+ }+ };++ if (properties.length === 0) {+ return (+ <div className="min-h-screen flex items-center justify-center p-4">+ <Card className="w-full max-w-md">+ <CardHeader>+ <CardTitle>No Properties Found</CardTitle>+ <CardDescription>No Google Search Console properties were found for your account.</CardDescription>+ </CardHeader>+ <CardContent>+ <Button onClick={() => router.push(`/${site}/main`)}>Go to Dashboard</Button>+ </CardContent>+ </Card>+ </div>+ );+ }++ return (+ <div className="min-h-screen flex items-center justify-center p-4">+ <Card className="w-full max-w-2xl">+ <CardHeader>+ <CardTitle>Select Google Search Console Property</CardTitle>+ <CardDescription>Choose which Search Console property you want to connect to this site</CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <RadioGroup value={selectedProperty} onValueChange={setSelectedProperty}>+ {properties.map(property => (+ <div+ key={property}+ className="flex items-center space-x-2 border-neutral-200 rounded-lg p-4 hover:bg-neutral-800/30"+ >+ <RadioGroupItem value={property} id={property} />+ <Label htmlFor={property} className="flex-1 cursor-pointer">+ <div className="font-medium text-white">+ {property.startsWith("sc-domain:") ? property.replace("sc-domain:", "") : property}+ </div>+ <div className="text-xs text-muted-foreground">+ {property.startsWith("sc-domain:") ? "Domain property" : "URL prefix property"}+ </div>+ </Label>+ </div>+ ))}+ </RadioGroup>++ <div className="flex gap-2 pt-4">+ <Button+ onClick={handleSubmit}+ disabled={!selectedProperty || isSubmitting}+ className="flex-1"+ variant="success"+ >+ {isSubmitting ? "Connecting..." : "Connect Property"}+ </Button>+ <Button variant="outline" onClick={() => router.push(`/${site}/main`)} disabled={isSubmitting}>+ Cancel+ </Button>+ </div>+ </CardContent>+ </Card>+ </div>+ );+}diff --git a/client/src/app/[site]/main/components/sections/Events.tsx b/client/src/app/[site]/main/components/sections/Events.tsxindex 416bf1764..9757da518 100644--- a/client/src/app/[site]/main/components/sections/Events.tsx+++ b/client/src/app/[site]/main/components/sections/Events.tsx@@ -21,7 +21,7 @@ function Events_() {<CardLoader /></div>)}- <div className="relative max-h-[344px] overflow-y-auto">+ <div className="relative max-h-[420px] overflow-y-auto"><div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-400 mb-2"><div>Custom Events</div><div>Count</div>@@ -59,7 +59,7 @@ export function Events() {const [expandedOutbound, setExpandedOutbound] = useState(false);return (- <Card className="h-[405px]">+ <Card className="h-[483px]"><CardContent className="mt-2"><Tabs defaultValue="events" value={tab} onValueChange={value => setTab(value as Tab)}><div className="flex flex-row gap-2 justify-between items-center">diff --git a/client/src/app/[site]/main/components/sections/SearchConsole.tsx b/client/src/app/[site]/main/components/sections/SearchConsole.tsxnew file mode 100644index 000000000..bc86a01c7--- /dev/null+++ b/client/src/app/[site]/main/components/sections/SearchConsole.tsx@@ -0,0 +1,223 @@+import { Expand, Info, Monitor, Smartphone, SquareArrowOutUpRight, Tablet } from "lucide-react";+import { useState } from "react";+import { useConnectGSC, useGSCConnection } from "../../../../../api/gsc/useGSCConnection";+import { GSCDimension, useGSCData } from "../../../../../api/gsc/useGSCData";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";+import { Button } from "../../../../../components/ui/button";+import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";+import { formatter, getCountryName } from "../../../../../lib/utils";+import { CountryFlag } from "../../../components/shared/icons/CountryFlag";+import { StandardSkeleton } from "../../../components/shared/StandardSection/Skeleton";+import { SearchConsoleDialog } from "./SearchConsoleDialog";+import { SiGoogle } from "@icons-pack/react-simple-icons";+import { round } from "lodash";++type Tab = "queries" | "pages" | "countries" | "devices";++function ConnectPrompt() {+ const { mutate: connect, isPending } = useConnectGSC();++ return (+ <div className="flex flex-col items-center justify-center mt-12 gap-4">+ <div className="text-sm text-neutral-400 text-center max-w-sm">+ Connect your Google Search Console account to view search performance data including top keywords and pages.+ </div>+ <Button onClick={() => connect()} disabled={isPending}>+ <SiGoogle />+ {isPending ? "Connecting..." : "Connect Google Search Console"}+ </Button>+ </div>+ );+}++interface DataListProps {+ dimension: GSCDimension;+ label: string;+ renderName?: (name: string) => React.ReactNode;+ expanded: boolean;+ close: () => void;+}++function DataList({ dimension, label, renderName, expanded, close }: DataListProps) {+ const { data, isLoading, isFetching } = useGSCData(dimension);++ const totalClicks = data?.reduce((acc, item) => acc + item.clicks, 0) || 0;++ const ratio = data?.[0]?.clicks ? 100 / (data[0].clicks / totalClicks) : 1;++ return (+ <>+ {isFetching && (+ <div className="absolute top-[-8px] left-0 w-full h-full">+ <CardLoader />+ </div>+ )}+ <div className="flex flex-col gap-2 max-h-[344px] overflow-y-auto z-10">+ <div className="flex flex-col gap-2 overflow-x-hidden">+ <div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-400">+ <div className="flex flex-row gap-1 items-center">{label}</div>+ <div className="flex flex-row gap-2">+ <div className="w-20 text-right">Clicks</div>+ <div className="w-24 text-right">Impressions</div>+ </div>+ </div>+ {data && data.length > 0 ? (+ data.slice(0, 10).map((item, index) => {+ const percentage = item.clicks / totalClicks;+ return (+ <div+ key={index}+ className="relative flex flex-row gap-2 justify-between pr-1 text-xs py-1 hover:bg-neutral-850 rounded px-2 group"+ >+ <div+ className="absolute inset-0 bg-dataviz py-2 opacity-25 rounded-md"+ style={{ width: `${percentage * ratio}%` }}+ />+ <div className="flex-1 truncate overflow-x-hidden z-10">+ {renderName ? renderName(item.name) : item.name}+ </div>+ <div className="flex flex-row gap-2 z-10">+ <div className="w-28 text-right pr-1 flex flex-row gap-2 items-center justify-end">+ <div className="hidden group-hover:block text-neutral-400">{round(percentage * 100, 1)}%</div>+ {formatter(item.clicks)}+ </div>+ <div className="w-24 text-right pr-1">{formatter(item.impressions)}</div>+ </div>+ </div>+ );+ })+ ) : isLoading ? (+ <StandardSkeleton />+ ) : (+ <div className="text-neutral-300 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">+ <div className="text-neutral-500">+ <div className="text-neutral-300 w-full text-center flex flex-row gap-2 items-center justify-center">+ <Info className="w-5 h-5" />+ No Data+ </div>+ <div className="text-sm mt-2">+ Google Search Console data has a 2-3 day delay. Try selecting a wider date range.+ </div>+ </div>+ </div>+ )}+ </div>+ </div>+ <SearchConsoleDialog+ title={label}+ dimension={dimension}+ renderName={renderName}+ expanded={expanded}+ close={close}+ />+ </>+ );+}++export function SearchConsole() {+ const [tab, setTab] = useState<Tab>("queries");+ const [expanded, setExpanded] = useState(false);+ const close = () => setExpanded(false);+ const { data: connection, isLoading: isLoadingConnection } = useGSCConnection();++ const topSection = (+ <div className="flex flex-row gap-2 justify-between items-center">+ <div className="overflow-x-auto">+ <TabsList>+ <TabsTrigger value="queries">Keywords</TabsTrigger>+ <TabsTrigger value="pages">Pages</TabsTrigger>+ <TabsTrigger value="countries">Countries</TabsTrigger>+ <TabsTrigger value="devices">Devices</TabsTrigger>+ </TabsList>+ </div>+ <div className="w-8">+ <Button size="smIcon" onClick={() => setExpanded(!expanded)}>+ <Expand className="w-4 h-4" />+ </Button>+ </div>+ </div>+ );++ if (isLoadingConnection) {+ return (+ <Card className="h-[405px]">+ <CardLoader />+ <CardContent className="mt-2">+ <Tabs defaultValue="queries" value={tab} onValueChange={value => setTab(value as Tab)}>+ {topSection}+ </Tabs>+ </CardContent>+ </Card>+ );+ }++ const isConnected = connection?.connected;++ return (+ <Card className="h-[405px]">+ <CardContent className="mt-2">+ <Tabs defaultValue="queries" value={tab} onValueChange={value => setTab(value as Tab)}>+ {topSection}+ {!isConnected ? (+ <ConnectPrompt />+ ) : (+ <>+ <TabsContent value="queries">+ <DataList dimension="query" label="Keyword" expanded={expanded} close={close} />+ </TabsContent>+ <TabsContent value="pages">+ <DataList+ dimension="page"+ label="Page"+ renderName={name => (+ <div className="flex items-center gap-1">+ <span className="truncate">{new URL(name).pathname || "/"}</span>+ <a href={name} target="_blank" rel="noopener noreferrer" className="flex-shrink-0">+ <SquareArrowOutUpRight+ className="ml-0.5 w-3.5 h-3.5 text-neutral-300 hover:text-neutral-100"+ strokeWidth={3}+ />+ </a>+ </div>+ )}+ expanded={expanded}+ close={close}+ />+ </TabsContent>+ <TabsContent value="countries">+ <DataList+ dimension="country"+ label="Country"+ renderName={name => (+ <div className="flex items-center gap-2">+ <CountryFlag country={name} />+ {getCountryName(name)}+ </div>+ )}+ expanded={expanded}+ close={close}+ />+ </TabsContent>+ <TabsContent value="devices">+ <DataList+ dimension="device"+ label="Device"+ expanded={expanded}+ close={close}+ renderName={e => (+ <div className="flex gap-2 items-center">+ {e === "DESKTOP" && <Monitor className="w-4 h-4" />}+ {e === "MOBILE" && <Smartphone className="w-4 h-4" />}+ {e === "TABLET" && <Tablet className="w-4 h-4" />}+ {e === "DESKTOP" ? "Desktop" : e === "MOBILE" ? "Mobile" : e === "TABLET" ? "Tablet" : "Other"}+ </div>+ )}+ />+ </TabsContent>+ </>+ )}+ </Tabs>+ </CardContent>+ </Card>+ );+}diff --git a/client/src/app/[site]/main/components/sections/SearchConsoleDialog.tsx b/client/src/app/[site]/main/components/sections/SearchConsoleDialog.tsxnew file mode 100644index 000000000..863b33c42--- /dev/null+++ b/client/src/app/[site]/main/components/sections/SearchConsoleDialog.tsx@@ -0,0 +1,185 @@+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import {+ createColumnHelper,+ flexRender,+ getCoreRowModel,+ getSortedRowModel,+ SortingState,+ useReactTable,+} from "@tanstack/react-table";+import { useDebounce } from "@uidotdev/usehooks";+import { ChevronDown, ChevronUp, Loader2, Search } from "lucide-react";+import { ReactNode, useMemo, useState } from "react";+import { GSCData, GSCDimension, useGSCData } from "../../../../../api/gsc/useGSCData";+import { cn } from "../../../../../lib/utils";++interface SearchConsoleDialogProps {+ title: string;+ dimension: GSCDimension;+ renderName?: (name: string) => ReactNode;+ expanded?: boolean;+ close: () => void;+}++const columnHelper = createColumnHelper<GSCData>();++export function SearchConsoleDialog({ title, dimension, renderName, expanded, close }: SearchConsoleDialogProps) {+ const { data, isLoading } = useGSCData(dimension);++ const [searchTerm, setSearchTerm] = useState("");+ const debouncedSearchTerm = useDebounce(searchTerm, 200);+ const [sorting, setSorting] = useState<SortingState>([{ id: "clicks", desc: true }]);++ // Filter data based on search term+ const filteredData = useMemo(() => {+ if (!data) return [];++ return data.filter((item: GSCData) => {+ return String(item.name).toLowerCase().includes(debouncedSearchTerm.toLowerCase());+ });+ }, [data, debouncedSearchTerm]);++ const columns = useMemo(() => {+ const cols = [+ columnHelper.accessor("name", {+ header: title,+ cell: ({ row }) => (+ <div className="flex flex-row gap-1 items-center text-left">+ {renderName ? renderName(row.original.name) : row.original.name}+ </div>+ ),+ }),+ columnHelper.accessor("clicks", {+ header: "Clicks",+ cell: info => (+ <div className="flex flex-row gap-1 items-center sm:justify-end">{info.getValue().toLocaleString()}</div>+ ),+ }),+ columnHelper.accessor("impressions", {+ header: "Impressions",+ cell: info => (+ <div className="flex flex-row gap-1 items-center sm:justify-end">{info.getValue().toLocaleString()}</div>+ ),+ }),+ columnHelper.accessor("ctr", {+ header: "CTR",+ cell: info => (+ <div className="flex flex-row gap-1 items-center sm:justify-end">{(info.getValue() * 100).toFixed(1)}%</div>+ ),+ }),+ columnHelper.accessor("position", {+ header: "Position",+ cell: info => (+ <div className="flex flex-row gap-1 items-center sm:justify-end">{info.getValue().toFixed(1)}</div>+ ),+ }),+ ];++ return cols;+ }, [title, dimension, renderName]);++ // Set up table instance+ const table = useReactTable({+ data: filteredData || [],+ columns,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ state: {+ sorting,+ },+ onSortingChange: setSorting,+ manualSorting: false,+ sortDescFirst: true,+ });++ if (isLoading || !data) {+ return (+ <Dialog open={expanded} onOpenChange={close}>+ <DialogContent className="max-w-[1000px] w-[calc(100vw-2rem)] p-2 sm:p-4">+ <div className="flex justify-center items-center h-40">+ <Loader2 className="h-8 w-8 animate-spin text-neutral-400" />+ </div>+ </DialogContent>+ </Dialog>+ );+ }++ return (+ <Dialog open={expanded} onOpenChange={close}>+ <DialogContent className="max-w-[1000px] w-[calc(100vw-2rem)] p-2 sm:p-4">+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ </DialogHeader>+ <div className="relative">+ <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-neutral-400" />+ <Input+ type="text"+ placeholder={`Filter ${data.length} items...`}+ className="pl-9 bg-neutral-900 border-neutral-700 text-xs"+ value={searchTerm}+ onChange={e => setSearchTerm(e.target.value)}+ />+ </div>+ <div className="flex flex-col gap-2 overflow-x-auto">+ <div className="max-h-[80vh] overflow-y-auto">+ <table className="w-full text-xs text-left min-w-max">+ <thead className="bg-neutral-900 text-neutral-400 sticky top-0 z-10">+ {table.getHeaderGroups().map(headerGroup => (+ <tr key={headerGroup.id}>+ {headerGroup.headers.map((header, index) => (+ <th+ key={header.id}+ scope="col"+ className={cn(+ "px-2 py-1 font-medium whitespace-nowrap cursor-pointer select-none",+ index === 0 ? "text-left" : "text-right"+ )}+ onClick={header.column.getToggleSortingHandler()}+ >+ <div className={cn("flex items-center gap-1", index !== 0 && "justify-end")}>+ {header.isPlaceholder+ ? null+ : flexRender(header.column.columnDef.header, header.getContext())}+ {{+ asc: <ChevronUp className="h-3 w-3" />,+ desc: <ChevronDown className="h-3 w-3" />,+ }[header.column.getIsSorted() as string] ?? null}+ </div>+ </th>+ ))}+ </tr>+ ))}+ </thead>+ <tbody>+ {table.getRowModel().rows.map((row, rowIndex) => {+ return (+ <tr+ key={row.id}+ className={cn(+ "border-b border-neutral-800 hover:bg-neutral-850",+ rowIndex % 2 === 0 ? "bg-neutral-900" : "bg-neutral-950"+ )}+ >+ {row.getVisibleCells().map((cell, cellIndex) => (+ <td key={cell.id} className={cn("px-2 py-2 relative", cellIndex !== 0 && "text-right")}>+ <span className="relative z-0">+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </span>+ </td>+ ))}+ </tr>+ );+ })}+ </tbody>+ </table>++ {filteredData.length === 0 && (+ <div className="py-8 text-center text-neutral-500 text-xs">No results found</div>+ )}+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/client/src/app/[site]/main/page.tsx b/client/src/app/[site]/main/page.tsxindex 0708ee477..57b87e96f 100644--- a/client/src/app/[site]/main/page.tsx+++ b/client/src/app/[site]/main/page.tsx@@ -10,6 +10,7 @@ import { Events } from "./components/sections/Events";import { Network } from "./components/sections/Network";import { Pages } from "./components/sections/Pages";import { Referrers } from "./components/sections/Referrers";+import { SearchConsole } from "./components/sections/SearchConsole";import { Weekdays } from "./components/sections/Weekdays";export default function MainPage() {@@ -34,9 +35,10 @@ function MainPageContent() {<Pages /><Devices /><Countries />- {IS_CLOUD && <Network />}<Events /><Weekdays />+ {IS_CLOUD && <Network />}+ {IS_CLOUD && <SearchConsole />}</div></div>);diff --git a/client/src/app/globals.css b/client/src/app/globals.cssindex c9522b2d9..042f58dcb 100644--- a/client/src/app/globals.css+++ b/client/src/app/globals.css@@ -9,22 +9,22 @@ body {@layer base {:root {--background: 0 0% 100%;- --foreground: 240 10% 3.9%;+ --foreground: 0 0% 3.9%;--popover: 0 0% 100%;- --popover-foreground: 240 10% 3.9%;- --primary: 240 5.9% 10%;+ --popover-foreground: 0 0% 3.9%;+ --primary: 0 0% 10%;--primary-foreground: 0 0% 98%;- --secondary: 240 4.8% 95.9%;- --secondary-foreground: 240 5.9% 10%;- --muted: 240 4.8% 95.9%;- --muted-foreground: 240 3.8% 46.1%;- --accent: 240 4.8% 95.9%;- --accent-foreground: 240 5.9% 10%;+ --secondary: 0 0% 95.9%;+ --secondary-foreground: 0 0% 10%;+ --muted: 0 0% 95.9%;+ --muted-foreground: 0 0% 46.1%;+ --accent: 0 0% 95.9%;+ --accent-foreground: 0 0% 10%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 0 0% 98%;- --border: 240 5.9% 90%;- --input: 240 5.9% 90%;- --ring: 240 5.9% 10%;+ --border: 0 0% 90%;+ --input: 0 0% 90%;+ --ring: 0 0% 10%;--radius: 0.3rem;--dataviz: 230 100% 85%;diff --git a/client/src/components/SiteSettings/GSCManager.tsx b/client/src/components/SiteSettings/GSCManager.tsxnew file mode 100644index 000000000..b45481ffe--- /dev/null+++ b/client/src/components/SiteSettings/GSCManager.tsx@@ -0,0 +1,107 @@+"use client";++import { ExternalLink } from "lucide-react";+import { Button } from "@/components/ui/button";+import { useGSCConnection, useConnectGSC, useDisconnectGSC } from "@/api/gsc/useGSCConnection";+import { toast } from "sonner";+import { ConfirmationModal } from "@/components/ConfirmationModal";+import { useStore } from "@/lib/store";+import { useEffect, useState } from "react";+import { useSearchParams } from "next/navigation";+import { SiGoogle } from "@icons-pack/react-simple-icons";++interface GSCManagerProps {+ disabled?: boolean;+}++export function GSCManager({ disabled = false }: GSCManagerProps) {+ const searchParams = useSearchParams();+ const { data: connection, isLoading, refetch } = useGSCConnection();+ const { mutate: connect, isPending: isConnecting } = useConnectGSC();+ const { mutate: disconnect, isPending: isDisconnecting } = useDisconnectGSC();+ const [isDisconnectModalOpen, setIsDisconnectModalOpen] = useState(false);++ // Check for OAuth success/error in URL params+ useEffect(() => {+ const gscStatus = searchParams.get("gsc");+ if (gscStatus === "success") {+ toast.success("Google Search Console connected successfully");+ refetch();+ }+ }, [searchParams, refetch]);++ const handleDisconnect = async () => {+ return new Promise((resolve, reject) => {+ disconnect(undefined, {+ onSuccess: () => {+ toast.success("Google Search Console disconnected");+ resolve(undefined);+ },+ onError: error => {+ toast.error("Failed to disconnect Google Search Console");+ reject(error);+ },+ });+ });+ };++ if (isLoading) {+ return (+ <div className="space-y-3">+ <div>+ <h4 className="text-sm font-semibold text-foreground">Google Search Console</h4>+ <p className="text-xs text-muted-foreground">Loading...</p>+ </div>+ </div>+ );+ }++ const isConnected = connection?.connected;++ return (+ <div className="space-y-3">+ <div>+ <h4 className="text-sm font-semibold text-foreground">Google Search Console</h4>+ <p className="text-xs text-muted-foreground">+ Connect your Google Search Console account to view search performance data+ </p>+ </div>++ {isConnected ? (+ <div className="space-y-3">+ <div className="flex items-center gap-2 text-sm">+ <span className="text-green-500">●</span>+ <span className="text-muted-foreground">Connected to:</span>+ <a+ href={connection.gscPropertyUrl || "#"}+ target="_blank"+ rel="noopener noreferrer"+ className="text-foreground hover:underline flex items-center gap-1"+ >+ {connection.gscPropertyUrl?.replace("sc-domain:", "")}+ <ExternalLink className="w-3 h-3" />+ </a>+ </div>++ <ConfirmationModal+ title="Disconnect Google Search Console?"+ description="This will remove the connection to Google Search Console. You can reconnect at any time."+ isOpen={isDisconnectModalOpen}+ setIsOpen={setIsDisconnectModalOpen}+ onConfirm={handleDisconnect}+ primaryAction={{ variant: "destructive", children: "Disconnect" }}+ >+ <Button variant="outline" disabled={disabled || isDisconnecting}>+ {isDisconnecting ? "Disconnecting..." : "Disconnect"}+ </Button>+ </ConfirmationModal>+ </div>+ ) : (+ <Button onClick={() => connect()} disabled={disabled || isConnecting}>+ <SiGoogle />+ {isConnecting ? "Connecting..." : "Connect Google Search Console"}+ </Button>+ )}+ </div>+ );+}diff --git a/client/src/components/SiteSettings/SiteConfiguration.tsx b/client/src/components/SiteSettings/SiteConfiguration.tsxindex 4eaeef9c4..c367dbbf1 100644--- a/client/src/components/SiteSettings/SiteConfiguration.tsx+++ b/client/src/components/SiteSettings/SiteConfiguration.tsx@@ -25,6 +25,7 @@ import { deleteSite, SiteResponse, updateSiteConfig, useGetSitesFromOrg } from "import { normalizeDomain } from "@/lib/utils";import { IPExclusionManager } from "./IPExclusionManager";import { CountryExclusionManager } from "./CountryExclusionManager";+import { GSCManager } from "./GSCManager";import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";import { Badge } from "../ui/badge";import { IS_CLOUD } from "../../lib/const";@@ -305,6 +306,9 @@ export function SiteConfiguration({ siteMetadata, disabled = false, onClose }: S{/* Country Exclusions Section */}<CountryExclusionManager siteId={siteMetadata.siteId} disabled={disabled} />+ {/* Google Search Console Section */}+ {IS_CLOUD && <GSCManager disabled={disabled} />}+{/* Domain Settings Section */}<div className="space-y-3"><div>@@ -332,8 +336,8 @@ export function SiteConfiguration({ siteMetadata, disabled = false, onClose }: S<h4 className="text-sm font-semibold text-destructive">Danger Zone</h4><AlertDialog><AlertDialogTrigger asChild>- <Button variant="destructive" className="w-full" disabled={disabled}>- <AlertTriangle className="h-4 w-4 mr-2" />+ <Button variant="destructive" disabled={disabled}>+ <AlertTriangle className="h-4 w-4" />Delete Site</Button></AlertDialogTrigger>diff --git a/client/src/components/ui/radio-group.tsx b/client/src/components/ui/radio-group.tsxnew file mode 100644index 000000000..05db71d16--- /dev/null+++ b/client/src/components/ui/radio-group.tsx@@ -0,0 +1,33 @@+"use client";++import * as React from "react";+import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";+import { CircleIcon } from "lucide-react";++import { cn } from "@/lib/utils";++function RadioGroup({ className, ...props }: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {+ return <RadioGroupPrimitive.Root data-slot="radio-group" className={cn("grid gap-3", className)} {...props} />;+}++function RadioGroupItem({ className, ...props }: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {+ return (+ <RadioGroupPrimitive.Item+ data-slot="radio-group-item"+ className={cn(+ "border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-neutral-800 dark:border-neutral-700 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",+ className+ )}+ {...props}+ >+ <RadioGroupPrimitive.Indicator+ data-slot="radio-group-indicator"+ className="relative flex items-center justify-center"+ >+ <CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />+ </RadioGroupPrimitive.Indicator>+ </RadioGroupPrimitive.Item>+ );+}++export { RadioGroup, RadioGroupItem };diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.ymlindex 2ace992ca..27a76dd57 100644--- a/docker-compose.cloud.yml+++ b/docker-compose.cloud.yml@@ -129,6 +129,7 @@ services:- MAPBOX_TOKEN=${MAPBOX_TOKEN}- TURNSTILE_SECRET_KEY=${TURNSTILE_SECRET_KEY}- IPAPI_KEY=${IPAPI_KEY}+ - GOOGLE_REDIRECT_URI=${GOOGLE_REDIRECT_URI}depends_on:clickhouse:condition: service_healthydiff --git a/server/package-lock.json b/server/package-lock.jsonindex e2cba53aa..c063b8614 100644--- a/server/package-lock.json+++ b/server/package-lock.json@@ -26,6 +26,7 @@"drizzle-orm": "0.43.1","fastify": "5.3.3","fastify-better-auth": "1.1.0",+ "i18n-iso-countries": "^7.14.0","ip-address": "^10.0.1","isbot": "^5.1.28","luxon": "3.6.1",@@ -5232,6 +5233,12 @@"node": ">=8"}},+ "node_modules/diacritics": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/diacritics/-/diacritics-1.3.0.tgz",+ "integrity": "sha512-wlwEkqcsaxvPJML+rDh/2iS824jbREk6DUMUKkEaSlxdYHeS43cClJtsWglvw2RfeXGm6ohKDqsXteJ5sP5enA==",+ "license": "MIT"+ },"node_modules/dom-serializer": {"version": "2.0.0","resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",@@ -6205,6 +6212,18 @@"node": ">= 14"}},+ "node_modules/i18n-iso-countries": {+ "version": "7.14.0",+ "resolved": "https://registry.npmjs.org/i18n-iso-countries/-/i18n-iso-countries-7.14.0.tgz",+ "integrity": "sha512-nXHJZYtNrfsi1UQbyRqm3Gou431elgLjKl//CYlnBGt5aTWdRPH1PiS2T/p/n8Q8LnqYqzQJik3Q7mkwvLokeg==",+ "license": "MIT",+ "dependencies": {+ "diacritics": "1.3.0"+ },+ "engines": {+ "node": ">= 12"+ }+ },"node_modules/iconv-lite": {"version": "0.6.3","resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",diff --git a/server/package.json b/server/package.jsonindex 7221a484e..6d14bd6e1 100644--- a/server/package.json+++ b/server/package.json@@ -41,6 +41,7 @@"drizzle-orm": "0.43.1","fastify": "5.3.3","fastify-better-auth": "1.1.0",+ "i18n-iso-countries": "^7.14.0","ip-address": "^10.0.1","isbot": "^5.1.28","luxon": "3.6.1",diff --git a/server/src/api/gsc/callback.ts b/server/src/api/gsc/callback.tsnew file mode 100644index 000000000..74c772920--- /dev/null+++ b/server/src/api/gsc/callback.ts@@ -0,0 +1,121 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { GSCCallbackRequest } from "./types.js";+import { gscConnections } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { getGSCProperties } from "./utils.js";+import { getSessionFromReq } from "../../lib/auth-utils.js";+import { db } from "../../db/postgres/postgres.js";+import { logger } from "../../lib/logger/logger.js";++interface TokenResponse {+ access_token: string;+ refresh_token: string;+ expires_in: number;+ scope: string;+ token_type: string;+}++/**+ * Handles the OAuth callback from Google+ * Exchanges the code for tokens and stores them in the database+ */+export async function gscCallback(req: FastifyRequest<GSCCallbackRequest>, res: FastifyReply) {+ try {+ const { code, state, error } = req.query;++ if (error) {+ logger.info("OAuth cancelled or failed:", error);+ const siteId = state;+ return res.redirect(`${process.env.BASE_URL}/${siteId}/main`);+ }++ if (!code || !state) {+ return res.status(400).send({ error: "Missing code or state parameter" });+ }++ const siteId = Number(state);+ if (isNaN(siteId)) {+ return res.status(400).send({ error: "Invalid site ID in state" });+ }++ // Get session to retrieve userId+ const session = await getSessionFromReq(req);+ if (!session) {+ return res.status(401).send({ error: "Unauthorized" });+ }++ const clientId = process.env.GOOGLE_CLIENT_ID;+ const clientSecret = process.env.GOOGLE_CLIENT_SECRET;+ const redirectUri = process.env.GOOGLE_REDIRECT_URI || `${process.env.SERVER_URL}/api/gsc/callback`;++ if (!clientId || !clientSecret) {+ return res.status(500).send({ error: "Google OAuth not configured" });+ }++ // Exchange code for tokens+ const tokenResponse = await fetch("https://oauth2.googleapis.com/token", {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({+ code,+ client_id: clientId,+ client_secret: clientSecret,+ redirect_uri: redirectUri,+ grant_type: "authorization_code",+ }),+ });++ if (!tokenResponse.ok) {+ logger.error(await tokenResponse.text(), "Token exchange failed");+ return res.redirect(`${process.env.BASE_URL}/error?message=Token exchange failed`);+ }++ const tokens: TokenResponse = await tokenResponse.json();++ // Get available GSC properties+ const properties = await getGSCProperties(tokens.access_token);++ if (properties.length === 0) {+ return res.redirect(`${process.env.CLIENT_URL}/error?message=No GSC properties found`);+ }++ const expiresAt = new Date(Date.now() + tokens.expires_in * 1000);++ // Store tokens temporarily WITHOUT a property URL+ // We'll update with the selected property after user chooses+ const [existingConnection] = await db.select().from(gscConnections).where(eq(gscConnections.siteId, siteId));++ if (existingConnection) {+ // Update existing connection with new tokens (but keep old property if it exists)+ await db+ .update(gscConnections)+ .set({+ accessToken: tokens.access_token,+ refreshToken: tokens.refresh_token,+ expiresAt: expiresAt.toISOString(),+ updatedAt: new Date().toISOString(),+ })+ .where(eq(gscConnections.siteId, siteId));+ } else {+ // Create new connection with temporary placeholder+ await db.insert(gscConnections).values({+ siteId,+ accessToken: tokens.access_token,+ refreshToken: tokens.refresh_token,+ expiresAt: expiresAt.toISOString(),+ gscPropertyUrl: "PENDING_SELECTION", // Placeholder until user selects+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ });+ }++ // Redirect to property selection page with properties as query params+ const propertiesParam = encodeURIComponent(JSON.stringify(properties));+ return res.redirect(`${process.env.BASE_URL}/${siteId}/gsc/select-property?properties=${propertiesParam}`);+ } catch (error) {+ logger.error(error, "Error handling GSC callback");+ return res.redirect(`${process.env.BASE_URL}/error?message=Callback failed`);+ }+}diff --git a/server/src/api/gsc/connect.ts b/server/src/api/gsc/connect.tsnew file mode 100644index 000000000..75ebed1c1--- /dev/null+++ b/server/src/api/gsc/connect.ts@@ -0,0 +1,50 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { ConnectGSCRequest } from "./types.js";+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";+import { logger } from "../../lib/logger/logger.js";++/**+ * Initiates the OAuth flow for Google Search Console+ * Returns the OAuth URL to redirect the user to+ */+export async function connectGSC(req: FastifyRequest<ConnectGSCRequest>, res: FastifyReply) {+ try {+ const { site } = req.params;+ const siteId = Number(site);++ if (isNaN(siteId)) {+ return res.status(400).send({ error: "Invalid site ID" });+ }++ // Check if user has access to this site+ const hasAccess = await getUserHasAccessToSite(req, siteId);+ if (!hasAccess) {+ return res.status(403).send({ error: "Access denied" });+ }++ const clientId = process.env.GOOGLE_CLIENT_ID;+ const redirectUri = process.env.GOOGLE_REDIRECT_URI || `${process.env.SERVER_URL}/api/gsc/callback`;++ if (!clientId) {+ return res.status(500).send({ error: "Google OAuth not configured" });+ }++ // Build OAuth URL+ const scope = "https://www.googleapis.com/auth/webmasters.readonly";+ const state = siteId.toString(); // Pass siteId in state to retrieve after OAuth++ const authUrl = new URL("https://accounts.google.com/o/oauth2/v2/auth");+ authUrl.searchParams.set("client_id", clientId);+ authUrl.searchParams.set("redirect_uri", redirectUri);+ authUrl.searchParams.set("response_type", "code");+ authUrl.searchParams.set("scope", scope);+ authUrl.searchParams.set("access_type", "offline");+ authUrl.searchParams.set("prompt", "consent"); // Force consent to ensure we get refresh token+ authUrl.searchParams.set("state", state);++ return res.send({ authUrl: authUrl.toString() });+ } catch (error) {+ logger.error(error, "Error initiating GSC OAuth");+ return res.status(500).send({ error: "Failed to initiate OAuth" });+ }+}diff --git a/server/src/api/gsc/disconnect.ts b/server/src/api/gsc/disconnect.tsnew file mode 100644index 000000000..4201955fb--- /dev/null+++ b/server/src/api/gsc/disconnect.ts@@ -0,0 +1,36 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { DisconnectGSCRequest } from "./types.js";+import { gscConnections } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";+import { db } from "../../db/postgres/postgres.js";+import { logger } from "../../lib/logger/logger.js";++/**+ * Disconnects a site from Google Search Console+ * Removes the OAuth tokens from the database+ */+export async function disconnectGSC(req: FastifyRequest<DisconnectGSCRequest>, res: FastifyReply) {+ try {+ const { site } = req.params;+ const siteId = Number(site);++ if (isNaN(siteId)) {+ return res.status(400).send({ error: "Invalid site ID" });+ }++ // Check if user has access to this site+ const hasAccess = await getUserHasAccessToSite(req, siteId);+ if (!hasAccess) {+ return res.status(403).send({ error: "Access denied" });+ }++ // Delete the connection+ await db.delete(gscConnections).where(eq(gscConnections.siteId, siteId));++ return res.send({ success: true });+ } catch (error) {+ logger.error(error, "Error disconnecting GSC");+ return res.status(500).send({ error: "Failed to disconnect GSC" });+ }+}diff --git a/server/src/api/gsc/getData.ts b/server/src/api/gsc/getData.tsnew file mode 100644index 000000000..be877b1fd--- /dev/null+++ b/server/src/api/gsc/getData.ts@@ -0,0 +1,100 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { GetGSCDataRequest, GSCResponse } from "./types.js";+import { gscConnections } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { refreshGSCToken } from "./utils.js";+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";+import { db } from "../../db/postgres/postgres.js";+import countries from "i18n-iso-countries";+import { logger } from "../../lib/logger/logger.js";++/**+ * Fetches data from Google Search Console API with support for multiple dimensions+ */+export async function getGSCData(req: FastifyRequest<GetGSCDataRequest>, res: FastifyReply) {+ try {+ const { site } = req.params;+ const { startDate, endDate, dimension } = req.query;+ const siteId = Number(site);++ if (isNaN(siteId)) {+ return res.status(400).send({ error: "Invalid site ID" });+ }++ if (!startDate || !endDate) {+ return res.status(400).send({ error: "Missing startDate or endDate" });+ }++ if (!dimension) {+ return res.status(400).send({ error: "Missing dimension parameter" });+ }++ // Check if user has access to this site+ const hasAccess = await getUserHasAccessToSite(req, siteId);+ if (!hasAccess) {+ return res.status(403).send({ error: "Access denied" });+ }++ // Get connection+ const [connection] = await db.select().from(gscConnections).where(eq(gscConnections.siteId, siteId));++ if (!connection) {+ return res.status(404).send({ error: "GSC not connected for this site" });+ }++ // Refresh token if needed+ const accessToken = await refreshGSCToken(siteId);+ if (!accessToken) {+ return res.status(500).send({ error: "Failed to refresh access token" });+ }++ // Query GSC API+ const gscResponse = await fetch(+ `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(connection.gscPropertyUrl)}/searchAnalytics/query`,+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ startDate,+ endDate,+ dimensions: [dimension],+ rowLimit: 1000,+ }),+ }+ );++ if (!gscResponse.ok) {+ const errorText = await gscResponse.text();+ logger.error(errorText, "GSC API error");+ return res.status(gscResponse.status).send({ error: "Failed to fetch GSC data", details: errorText });+ }++ const data: GSCResponse = await gscResponse.json();++ // Transform the response to a simpler format with unified "name" field+ const results = (data.rows || []).map(row => {+ let name = row.keys[0];++ // Convert country codes from alpha-3 to alpha-2 for the "country" dimension+ if (dimension === "country" && name) {+ name = countries.alpha3ToAlpha2(name.toUpperCase()) || name;+ }++ return {+ name,+ clicks: row.clicks,+ impressions: row.impressions,+ ctr: row.ctr,+ position: row.position,+ };+ });++ return res.send({ data: results });+ } catch (error) {+ logger.error(error, "Error fetching GSC data");+ return res.status(500).send({ error: "Failed to fetch GSC data" });+ }+}diff --git a/server/src/api/gsc/selectProperty.ts b/server/src/api/gsc/selectProperty.tsnew file mode 100644index 000000000..8de08b00b--- /dev/null+++ b/server/src/api/gsc/selectProperty.ts@@ -0,0 +1,59 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { gscConnections } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";+import { db } from "../../db/postgres/postgres.js";+import { logger } from "../../lib/logger/logger.js";++interface SelectPropertyRequest {+ Params: {+ site: string;+ };+ Body: {+ propertyUrl: string;+ };+}++/**+ * Updates the GSC connection with the user-selected property+ */+export async function selectGSCProperty(req: FastifyRequest<SelectPropertyRequest>, res: FastifyReply) {+ try {+ const { site } = req.params;+ const { propertyUrl } = req.body;+ const siteId = Number(site);++ if (isNaN(siteId)) {+ return res.status(400).send({ error: "Invalid site ID" });+ }++ if (!propertyUrl || propertyUrl === "PENDING_SELECTION") {+ return res.status(400).send({ error: "Property URL is required" });+ }++ // Check if user has access to this site+ const hasAccess = await getUserHasAccessToSite(req, siteId);+ if (!hasAccess) {+ return res.status(403).send({ error: "Access denied" });+ }++ // Update the connection with the selected property+ const result = await db+ .update(gscConnections)+ .set({+ gscPropertyUrl: propertyUrl,+ updatedAt: new Date().toISOString(),+ })+ .where(eq(gscConnections.siteId, siteId))+ .returning();++ if (result.length === 0) {+ return res.status(404).send({ error: "GSC connection not found" });+ }++ return res.send({ success: true, property: propertyUrl });+ } catch (error) {+ logger.error(error, "Error selecting GSC property");+ return res.status(500).send({ error: "Failed to select property" });+ }+}diff --git a/server/src/api/gsc/status.ts b/server/src/api/gsc/status.tsnew file mode 100644index 000000000..5bc5b353a--- /dev/null+++ b/server/src/api/gsc/status.ts@@ -0,0 +1,44 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { GetGSCStatusRequest } from "./types.js";+import { gscConnections } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";+import { db } from "../../db/postgres/postgres.js";+import { logger } from "../../lib/logger/logger.js";++/**+ * Checks if a site has an active GSC connection+ */+export async function getGSCStatus(req: FastifyRequest<GetGSCStatusRequest>, res: FastifyReply) {+ try {+ const { site } = req.params;+ const siteId = Number(site);++ if (isNaN(siteId)) {+ return res.status(400).send({ error: "Invalid site ID" });+ }++ // Check if user has access to this site+ const hasAccess = await getUserHasAccessToSite(req, siteId);+ if (!hasAccess) {+ return res.status(403).send({ error: "Access denied" });+ }++ const [connection] = await db.select().from(gscConnections).where(eq(gscConnections.siteId, siteId));++ if (!connection) {+ return res.send({+ connected: false,+ gscPropertyUrl: null,+ });+ }++ return res.send({+ connected: true,+ gscPropertyUrl: connection.gscPropertyUrl,+ });+ } catch (error) {+ logger.error(error, "Error checking GSC status");+ return res.status(500).send({ error: "Failed to check GSC status" });+ }+}diff --git a/server/src/api/gsc/types.ts b/server/src/api/gsc/types.tsnew file mode 100644index 000000000..27a2e2b1a--- /dev/null+++ b/server/src/api/gsc/types.ts@@ -0,0 +1,50 @@+import { FastifyRequest } from "fastify";++export interface GSCQueryRow {+ keys: string[];+ clicks: number;+ impressions: number;+ ctr: number;+ position: number;+}++export interface GSCResponse {+ rows?: GSCQueryRow[];+}++export interface GetGSCDataRequest {+ Params: {+ site: string;+ };+ Querystring: {+ startDate: string;+ endDate: string;+ dimension: "query" | "page" | "country" | "device";+ };+}++export interface ConnectGSCRequest {+ Params: {+ site: string;+ };+}++export interface GSCCallbackRequest {+ Querystring: {+ code: string;+ state: string; // Contains siteId+ error?: string;+ };+}++export interface DisconnectGSCRequest {+ Params: {+ site: string;+ };+}++export interface GetGSCStatusRequest {+ Params: {+ site: string;+ };+}diff --git a/server/src/api/gsc/utils.ts b/server/src/api/gsc/utils.tsnew file mode 100644index 000000000..447a86be6--- /dev/null+++ b/server/src/api/gsc/utils.ts@@ -0,0 +1,99 @@+import { db } from "../../db/postgres/postgres.js";+import { gscConnections } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { logger } from "../../lib/logger/logger.js";++interface GSCTokens {+ access_token: string;+ refresh_token?: string; // Optional because refresh might not return a new refresh_token+ expires_in: number;+}++/**+ * Refresh the GSC OAuth token if it's expired+ */+export async function refreshGSCToken(siteId: number): Promise<string | null> {+ try {+ const [connection] = await db.select().from(gscConnections).where(eq(gscConnections.siteId, siteId));++ if (!connection) {+ return null;+ }++ // Check if token is expired (with 5 minute buffer)+ const expiresAt = new Date(connection.expiresAt);+ const now = new Date();+ const fiveMinutesFromNow = new Date(now.getTime() + 5 * 60 * 1000);++ // if (expiresAt > fiveMinutesFromNow) {+ // // Token is still valid+ // return connection.accessToken;+ // }++ // Token is expired or about to expire, refresh it+ const tokenResponse = await fetch("https://oauth2.googleapis.com/token", {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({+ client_id: process.env.GOOGLE_CLIENT_ID!,+ client_secret: process.env.GOOGLE_CLIENT_SECRET!,+ refresh_token: connection.refreshToken,+ grant_type: "refresh_token",+ }),+ });++ if (!tokenResponse.ok) {+ logger.error(await tokenResponse.text(), "Failed to refresh GSC token");+ return null;+ }++ const tokens: GSCTokens = await tokenResponse.json();++ // Update the connection with new access token+ const newExpiresAt = new Date(Date.now() + tokens.expires_in * 1000);++ // Only update refresh_token if a new one was provided+ const updateData: Partial<typeof gscConnections.$inferInsert> = {+ accessToken: tokens.access_token,+ expiresAt: newExpiresAt.toISOString(),+ updatedAt: new Date().toISOString(),+ };++ if (tokens.refresh_token) {+ updateData.refreshToken = tokens.refresh_token;+ }++ await db.update(gscConnections).set(updateData).where(eq(gscConnections.siteId, siteId));++ return tokens.access_token;+ } catch (error) {+ logger.error(error, "Error refreshing GSC token");+ return null;+ }+}++/**+ * Get available GSC properties for a given access token+ */+export async function getGSCProperties(accessToken: string): Promise<string[]> {+ try {+ const response = await fetch("https://www.googleapis.com/webmasters/v3/sites", {+ headers: {+ Authorization: `Bearer ${accessToken}`,+ },+ });++ if (!response.ok) {+ logger.error(await response.text(), "Failed to fetch GSC properties");+ return [];+ }++ const data = await response.json();+ return data.siteEntry?.map((site: { siteUrl: string }) => site.siteUrl) || [];+ } catch (error) {+ logger.error(error, "Error fetching GSC properties");+ return [];+ }+}diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 3ff738497..282257fff 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -598,3 +598,22 @@ export const notificationChannels = pgTable(}),]);++// Google Search Console connections table+export const gscConnections = pgTable("gsc_connections", {+ siteId: integer("site_id")+ .primaryKey()+ .notNull()+ .references(() => sites.siteId, { onDelete: "cascade" }),++ // OAuth tokens+ accessToken: text("access_token").notNull(),+ refreshToken: text("refresh_token").notNull(),+ expiresAt: timestamp("expires_at", { mode: "string" }).notNull(),++ // Which GSC property this connection is for+ gscPropertyUrl: text("gsc_property_url").notNull(),++ createdAt: timestamp("created_at", { mode: "string" }).defaultNow().notNull(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow().notNull(),+});diff --git a/server/src/index.ts b/server/src/index.tsindex f595aaa10..6ab88cfdf 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -80,6 +80,12 @@ import { extractSiteId } from "./utils.js";import { getTrackingConfig } from "./api/sites/getTrackingConfig.js";import { updateSitePrivateLinkConfig } from "./api/sites/updateSitePrivateLinkConfig.js";import { getSitePrivateLinkConfig } from "./api/sites/getSitePrivateLinkConfig.js";+import { connectGSC } from "./api/gsc/connect.js";+import { gscCallback } from "./api/gsc/callback.js";+import { getGSCStatus } from "./api/gsc/status.js";+import { disconnectGSC } from "./api/gsc/disconnect.js";+import { getGSCData } from "./api/gsc/getData.js";+import { selectGSCProperty } from "./api/gsc/selectProperty.js";const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -201,6 +207,7 @@ const PUBLIC_ROUTES: string[] = ["/api/auth","/api/auth/callback/google","/api/auth/callback/github",+ "/api/gsc/callback","/api/stripe/webhook","/api/as/webhook","/api/session-replay/record",@@ -243,6 +250,7 @@ const ANALYTICS_ROUTES = ["/api/error-events/","/api/error-bucketed/","/api/session-replay/",+ "/api/gsc/data/",];server.addHook("onRequest", async (request, reply) => {@@ -358,6 +366,14 @@ server.get("/api/user/organizations", getUserOrganizations);server.post("/api/add-user-to-organization", addUserToOrganization);server.post("/api/user/account-settings", updateAccountSettings);+// GOOGLE SEARCH CONSOLE+server.get("/api/gsc/connect/:site", connectGSC);+server.get("/api/gsc/callback", gscCallback);+server.get("/api/gsc/status/:site", getGSCStatus);+server.delete("/api/gsc/disconnect/:site", disconnectGSC);+server.post("/api/gsc/select-property/:site", selectGSCProperty);+server.get("/api/gsc/data/:site", getGSCData);+// UPTIME MONITORING// Only register uptime routes when IS_CLOUD is true (Redis is available)// if (IS_CLOUD) {