Skip to content

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

Remove unused goal API and related hooks from the analytics module. This cleanup enhances code maintainability by eliminating deprecated functionality and streamlining the API structure.

Bill Yang7f1242bc4c58
diff --git a/client/src/api/analytics/goals/useGetGoal.ts b/client/src/api/analytics/goals/useGetGoal.ts
deleted file mode 100644
index 0858a9abe..000000000
--- a/client/src/api/analytics/goals/useGetGoal.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { Filter } from "@rybbit/shared";
-import { useQuery } from "@tanstack/react-query";
-import { timeZone } from "../../../lib/dateTimeUtils";
-import { useStore } from "../../../lib/store";
-import { authedFetch } from "../../utils";
-import { Goal } from "./useGetGoals";
-
-interface GetGoalResponse {
- data: Goal;
-}
-
-export function useGetGoal({
- goalId,
- startDate,
- endDate,
- filters,
- enabled = true,
-}: {
- goalId: number;
- startDate: string;
- endDate: string;
- filters?: Filter[];
- enabled?: boolean;
-}) {
- const { site } = useStore();
-
- return useQuery({
- queryKey: ["goal", site, goalId, startDate, endDate, timeZone, filters],
- queryFn: async () => {
- return authedFetch<GetGoalResponse>(`/goal/${goalId}/${site}`, {
- startDate,
- endDate,
- timeZone,
- filters,
- });
- },
- enabled: !!site && !!goalId && enabled,
- });
-}
diff --git a/server/src/api/analytics/getOverview.ts b/server/src/api/analytics/getOverview.ts
index 33d87bb64..4a28d5455 100644
--- a/server/src/api/analytics/getOverview.ts
+++ b/server/src/api/analytics/getOverview.ts
@@ -82,7 +82,7 @@ const getQuery = ({
) AS page_stats`;
};
-export interface GenericRequest {
+export interface OverviewRequest {
Params: {
site: string;
};
@@ -99,7 +99,7 @@ export interface GenericRequest {
}
export async function getOverview(
- req: FastifyRequest<GenericRequest>,
+ req: FastifyRequest<OverviewRequest>,
res: FastifyReply
) {
const {
diff --git a/server/src/api/analytics/goals/getGoal.ts b/server/src/api/analytics/goals/getGoal.ts
deleted file mode 100644
index d3b546d2d..000000000
--- a/server/src/api/analytics/goals/getGoal.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../../db/postgres/postgres.js";
-import { goals } from "../../../db/postgres/schema.js";
-import clickhouse from "../../../db/clickhouse/clickhouse.js";
-import { getUserHasAccessToSitePublic } from "../../../lib/auth-utils.js";
-import { eq } from "drizzle-orm";
-import {
- getFilterStatement,
- getTimeStatement,
- processResults,
- patternToRegex,
-} from "../utils.js";
-import SqlString from "sqlstring";
-
-export async function getGoal(
- request: FastifyRequest<{
- Params: {
- goalId: string;
- site: string;
- };
- Querystring: {
- startDate: string;
- endDate: string;
- timeZone: string;
- filters?: string;
- };
- }>,
- reply: FastifyReply
-) {
- const { goalId, site } = request.params;
- const { startDate, endDate, timeZone, filters } = request.query;
-
- // Check user access to site
- const userHasAccessToSite = await getUserHasAccessToSitePublic(request, site);
- if (!userHasAccessToSite) {
- return reply.status(403).send({ error: "Forbidden" });
- }
-
- try {
- // Fetch the goal from PostgreSQL
- const goal = await db.query.goals.findFirst({
- where: eq(goals.goalId, parseInt(goalId, 10)),
- });
-
- if (!goal) {
- return reply.status(404).send({ error: "Goal not found" });
- }
-
- // Ensure the goal belongs to the specified site
- if (goal.siteId !== parseInt(site, 10)) {
- return reply
- .status(403)
- .send({ error: "Goal does not belong to the specified site" });
- }
-
- // Build filter and time clauses for ClickHouse queries
- const filterStatement = filters ? getFilterStatement(filters) : "";
- const timeStatement = getTimeStatement({
- date: { startDate, endDate, timeZone },
- });
-
- // First, get the total number of unique sessions (denominator for conversion rate)
- const totalSessionsQuery = `
- SELECT COUNT(DISTINCT session_id) AS total_sessions
- FROM events
- WHERE site_id = ${SqlString.escape(Number(site))}
- ${timeStatement}
- ${filterStatement}
- `;
-
- const totalSessionsResult = await clickhouse.query({
- query: totalSessionsQuery,
- format: "JSONEachRow",
- });
-
- const totalSessionsData = await processResults<{ total_sessions: number }>(
- totalSessionsResult
- );
- const totalSessions = totalSessionsData[0]?.total_sessions || 0;
-
- // Build a query specific to this goal type to calculate conversions
- let conversionQuery = "";
-
- if (goal.goalType === "path") {
- const pathPattern = goal.config.pathPattern;
- if (!pathPattern) {
- return reply.status(400).send({ error: "Invalid goal configuration" });
- }
-
- const regex = patternToRegex(pathPattern);
- conversionQuery = `
- SELECT COUNT(DISTINCT session_id) AS total_conversions
- FROM events
- WHERE site_id = ${SqlString.escape(Number(site))}
- AND type = 'pageview'
- AND match(pathname, ${SqlString.escape(regex)})
- ${timeStatement}
- ${filterStatement}
- `;
- } else if (goal.goalType === "event") {
- const eventName = goal.config.eventName;
- const eventPropertyKey = goal.config.eventPropertyKey;
- const eventPropertyValue = goal.config.eventPropertyValue;
-
- if (!eventName) {
- return reply.status(400).send({ error: "Invalid goal configuration" });
- }
-
- let eventClause = `type = 'custom_event' AND event_name = ${SqlString.escape(
- eventName
- )}`;
-
- // Add property matching if needed
- if (eventPropertyKey && eventPropertyValue !== undefined) {
- // Access the sub-column directly for native JSON type
- const propValueAccessor = `props.${SqlString.escapeId(
- eventPropertyKey
- )}`;
-
- // Comparison needs to handle the Dynamic type returned
- // Let ClickHouse handle the comparison based on the provided value type
- if (typeof eventPropertyValue === "string") {
- eventClause += ` AND toString(${propValueAccessor}) = ${SqlString.escape(
- eventPropertyValue
- )}`;
- } else if (typeof eventPropertyValue === "number") {
- // Use toFloat64 or toInt* depending on expected number type
- eventClause += ` AND toFloat64OrNull(${propValueAccessor}) = ${SqlString.escape(
- eventPropertyValue
- )}`;
- } else if (typeof eventPropertyValue === "boolean") {
- // Booleans might be stored as 0/1 or true/false in JSON
- // Comparing toUInt8 seems robust
- eventClause += ` AND toUInt8OrNull(${propValueAccessor}) = ${
- eventPropertyValue ? 1 : 0
- }`;
- }
- }
-
- conversionQuery = `
- SELECT COUNT(DISTINCT session_id) AS total_conversions
- FROM events
- WHERE site_id = ${SqlString.escape(Number(site))}
- AND ${eventClause}
- ${timeStatement}
- ${filterStatement}
- `;
- } else {
- return reply.status(400).send({ error: "Invalid goal type" });
- }
-
- // Execute the conversion query
- const conversionResult = await clickhouse.query({
- query: conversionQuery,
- format: "JSONEachRow",
- });
-
- const conversionData = await processResults<{ total_conversions: number }>(
- conversionResult
- );
- const totalConversions = conversionData[0]?.total_conversions || 0;
- const conversionRate =
- totalSessions > 0 ? totalConversions / totalSessions : 0;
-
- // Return the goal with conversion metrics
- return reply.send({
- data: {
- ...goal,
- total_conversions: totalConversions,
- total_sessions: totalSessions,
- conversion_rate: conversionRate,
- },
- });
- } catch (error) {
- console.error("Error fetching goal:", error);
- return reply.status(500).send({ error: "Failed to fetch goal data" });
- }
-}
diff --git a/server/src/index.ts b/server/src/index.ts
index b65ea834a..a35c889a4 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -4,19 +4,15 @@ import { toNodeHandler } from "better-auth/node";
import Fastify from "fastify";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
-import { getAdminSites } from "./api/admin/getAdminSites.js";
import { getAdminOrganizations } from "./api/admin/getAdminOrganizations.js";
-import { createFunnel } from "./api/analytics/funnels/createFunnel.js";
-import { createGoal } from "./api/analytics/goals/createGoal.js";
-import { deleteFunnel } from "./api/analytics/funnels/deleteFunnel.js";
-import { deleteGoal } from "./api/analytics/goals/deleteGoal.js";
+import { getAdminSites } from "./api/admin/getAdminSites.js";
import { getEventNames } from "./api/analytics/events/getEventNames.js";
import { getEventProperties } from "./api/analytics/events/getEventProperties.js";
import { getEvents } from "./api/analytics/events/getEvents.js";
+import { createFunnel } from "./api/analytics/funnels/createFunnel.js";
+import { deleteFunnel } from "./api/analytics/funnels/deleteFunnel.js";
import { getFunnel } from "./api/analytics/funnels/getFunnel.js";
import { getFunnels } from "./api/analytics/funnels/getFunnels.js";
-import { getGoal } from "./api/analytics/goals/getGoal.js";
-import { getGoals } from "./api/analytics/goals/getGoals.js";
import { getJourneys } from "./api/analytics/getJourneys.js";
import { getLiveSessionLocations } from "./api/analytics/getLiveSessionLocations.js";
import { getLiveUsercount } from "./api/analytics/getLiveUsercount.js";
@@ -24,9 +20,6 @@ import { getOrgEventCount } from "./api/analytics/getOrgEventCount.js";
import { getOverview } from "./api/analytics/getOverview.js";
import { getOverviewBucketed } from "./api/analytics/getOverviewBucketed.js";
import { getPageTitles } from "./api/analytics/getPageTitles.js";
-import { getPerformanceByDimension } from "./api/analytics/performance/getPerformanceByDimension.js";
-import { getPerformanceOverview } from "./api/analytics/performance/getPerformanceOverview.js";
-import { getPerformanceTimeSeries } from "./api/analytics/performance/getPerformanceTimeSeries.js";
import { getRetention } from "./api/analytics/getRetention.js";
import { getSession } from "./api/analytics/getSession.js";
import { getSessions } from "./api/analytics/getSessions.js";
@@ -35,7 +28,13 @@ import { getUserInfo } from "./api/analytics/getUserInfo.js";
import { getUserSessionCount } from "./api/analytics/getUserSessionCount.js";
import { getUserSessions } from "./api/analytics/getUserSessions.js";
import { getUsers } from "./api/analytics/getUsers.js";
+import { createGoal } from "./api/analytics/goals/createGoal.js";
+import { deleteGoal } from "./api/analytics/goals/deleteGoal.js";
+import { getGoals } from "./api/analytics/goals/getGoals.js";
import { updateGoal } from "./api/analytics/goals/updateGoal.js";
+import { getPerformanceByDimension } from "./api/analytics/performance/getPerformanceByDimension.js";
+import { getPerformanceOverview } from "./api/analytics/performance/getPerformanceOverview.js";
+import { getPerformanceTimeSeries } from "./api/analytics/performance/getPerformanceTimeSeries.js";
import { getConfig } from "./api/getConfig.js";
import { addSite } from "./api/sites/addSite.js";
import { changeSiteBlockBots } from "./api/sites/changeSiteBlockBots.js";
@@ -236,7 +235,6 @@ server.post("/api/funnel/:site", getFunnel);
server.post("/api/funnel/create/:site", createFunnel);
server.delete("/api/funnel/:funnelId", deleteFunnel);
server.get("/api/goals/:site", getGoals);
-server.get("/api/goal/:goalId/:site", getGoal);
server.post("/api/goal/create", createGoal);
server.delete("/api/goal/:goalId", deleteGoal);
server.put("/api/goal/update", updateGoal);