Skip to content

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

Refactor analytics API to support funnel management

Bill Yang9b38ed2e2351
diff --git a/client/src/api/analytics/useDeleteFunnel.ts b/client/src/api/analytics/useDeleteFunnel.ts
index d1a3eaaf8..89226c329 100644
--- a/client/src/api/analytics/useDeleteFunnel.ts
+++ b/client/src/api/analytics/useDeleteFunnel.ts
@@ -12,7 +12,7 @@ export function useDeleteFunnel() {
mutationFn: async (reportId) => {
try {
return await authedFetchWithError<{ success: boolean }>(
- `${BACKEND_URL}/report/${reportId}`,
+ `${BACKEND_URL}/funnel/${reportId}`,
{
method: "DELETE",
}
diff --git a/server/src/api/analytics/createFunnel.ts b/server/src/api/analytics/createFunnel.ts
index 78d45b484..a5f668786 100644
--- a/server/src/api/analytics/createFunnel.ts
+++ b/server/src/api/analytics/createFunnel.ts
@@ -1,7 +1,7 @@
import { eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
-import { reports } from "../../db/postgres/schema.js";
+import { funnels as funnelsTable } from "../../db/postgres/schema.js";
import { getUserHasAccessToSite } from "../../lib/auth-utils.js";
type FunnelStep = {
@@ -57,24 +57,24 @@ export async function createFunnel(
let result;
if (reportId) {
- // Check if the report exists and user has access to it
- const existingReport = await db.query.reports.findFirst({
- where: eq(reports.reportId, reportId),
+ // Check if the funnel exists and user has access to it
+ const existingFunnel = await db.query.funnels.findFirst({
+ where: eq(funnelsTable.reportId, reportId),
});
- if (!existingReport) {
- return reply.status(404).send({ error: "Report not found" });
+ if (!existingFunnel) {
+ return reply.status(404).send({ error: "Funnel not found" });
}
- if (existingReport.siteId !== Number(site)) {
+ if (existingFunnel.siteId !== Number(site)) {
return reply
.status(403)
- .send({ error: "Report does not belong to this site" });
+ .send({ error: "Funnel does not belong to this site" });
}
// Update existing funnel
result = await db
- .update(reports)
+ .update(funnelsTable)
.set({
data: {
name,
@@ -83,8 +83,8 @@ export async function createFunnel(
},
updatedAt: new Date().toISOString(),
})
- .where(eq(reports.reportId, reportId))
- .returning({ reportId: reports.reportId });
+ .where(eq(funnelsTable.reportId, reportId))
+ .returning({ reportId: funnelsTable.reportId });
if (!result || result.length === 0) {
return reply.status(500).send({ error: "Failed to update funnel" });
@@ -92,18 +92,17 @@ export async function createFunnel(
} else {
// Create new funnel
result = await db
- .insert(reports)
+ .insert(funnelsTable)
.values({
siteId: Number(site),
userId,
- reportType: "funnel",
data: {
name,
steps,
filters,
},
})
- .returning({ reportId: reports.reportId });
+ .returning({ reportId: funnelsTable.reportId });
}
return reply.status(201).send({
diff --git a/server/src/api/analytics/deleteFunnel.ts b/server/src/api/analytics/deleteFunnel.ts
new file mode 100644
index 000000000..34ee56e4d
--- /dev/null
+++ b/server/src/api/analytics/deleteFunnel.ts
@@ -0,0 +1,52 @@
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { db } from "../../db/postgres/postgres.js";
+import { funnels as funnelsTable } from "../../db/postgres/schema.js";
+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";
+
+export async function deleteFunnel(
+ request: FastifyRequest<{
+ Params: {
+ funnelId: string;
+ };
+ }>,
+ reply: FastifyReply
+) {
+ const { funnelId } = request.params;
+
+ try {
+ // First get the funnel to check ownership
+ const funnel = await db.query.funnels.findFirst({
+ where: eq(funnelsTable.reportId, parseInt(funnelId)),
+ });
+
+ if (!funnel) {
+ return reply.status(404).send({ error: "Funnel not found" });
+ }
+
+ if (!funnel.siteId) {
+ return reply
+ .status(400)
+ .send({ error: "Invalid funnel: missing site ID" });
+ }
+
+ // Check user access to site
+ const userHasAccessToSite = await getUserHasAccessToSite(
+ request,
+ funnel.siteId.toString()
+ );
+ if (!userHasAccessToSite) {
+ return reply.status(403).send({ error: "Forbidden" });
+ }
+
+ // Delete the funnel
+ await db
+ .delete(funnelsTable)
+ .where(eq(funnelsTable.reportId, parseInt(funnelId)));
+
+ return reply.status(200).send({ success: true });
+ } catch (error) {
+ console.error("Error deleting funnel:", error);
+ return reply.status(500).send({ error: "Failed to delete funnel" });
+ }
+}
diff --git a/server/src/api/analytics/deleteReport.ts b/server/src/api/analytics/deleteReport.ts
deleted file mode 100644
index 70c3bb484..000000000
--- a/server/src/api/analytics/deleteReport.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { reports } from "../../db/postgres/schema.js";
-import { getUserHasAccessToSite } from "../../lib/auth-utils.js";
-
-export async function deleteReport(
- request: FastifyRequest<{
- Params: {
- reportId: string;
- };
- }>,
- reply: FastifyReply
-) {
- const { reportId } = request.params;
-
- try {
- // First get the report to check ownership
- const report = await db.query.reports.findFirst({
- where: eq(reports.reportId, parseInt(reportId)),
- });
-
- if (!report) {
- return reply.status(404).send({ error: "Report not found" });
- }
-
- if (!report.siteId) {
- return reply
- .status(400)
- .send({ error: "Invalid report: missing site ID" });
- }
-
- // Check user access to site
- const userHasAccessToSite = await getUserHasAccessToSite(
- request,
- report.siteId.toString()
- );
- if (!userHasAccessToSite) {
- return reply.status(403).send({ error: "Forbidden" });
- }
-
- // Delete the report
- await db.delete(reports).where(eq(reports.reportId, parseInt(reportId)));
-
- return reply.status(200).send({ success: true });
- } catch (error) {
- console.error("Error deleting report:", error);
- return reply.status(500).send({ error: "Failed to delete report" });
- }
-}
diff --git a/server/src/api/analytics/getFunnels.ts b/server/src/api/analytics/getFunnels.ts
index b402897ad..37cc93f93 100644
--- a/server/src/api/analytics/getFunnels.ts
+++ b/server/src/api/analytics/getFunnels.ts
@@ -1,6 +1,6 @@
import { FastifyRequest, FastifyReply } from "fastify";
import { db } from "../../db/postgres/postgres.js";
-import { reports } from "../../db/postgres/schema.js";
+import { funnels as funnelsTable } from "../../db/postgres/schema.js";
import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";
import { eq, and } from "drizzle-orm";
@@ -21,26 +21,24 @@ export async function getFunnels(
}
try {
- // Fetch all funnel reports for the site
- const funnelReports = await db
+ // Fetch all funnels for the site
+ const funnelRecords = await db
.select()
- .from(reports)
- .where(
- and(eq(reports.siteId, Number(site)), eq(reports.reportType, "funnel"))
- )
- .orderBy(reports.createdAt);
+ .from(funnelsTable)
+ .where(eq(funnelsTable.siteId, Number(site)))
+ .orderBy(funnelsTable.createdAt);
- // Transform the reports to a more frontend-friendly structure
- const funnels = funnelReports.map((report) => {
- const data = report.data as any;
+ // Transform the records to a more frontend-friendly structure
+ const funnels = funnelRecords.map((record) => {
+ const data = record.data as any;
return {
- id: report.reportId,
+ id: record.reportId,
name: data.name || "Unnamed Funnel",
steps: data.steps || [],
filters: data.filters || [],
configuration: data.configuration || {},
- createdAt: report.createdAt,
- updatedAt: report.updatedAt,
+ createdAt: record.createdAt,
+ updatedAt: record.updatedAt,
// Include any additional analytics data that might be stored
conversionRate: data.lastResult?.conversionRate || null,
totalVisitors: data.lastResult?.totalVisitors || null,
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index 50b599ff1..5c570bbea 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -98,13 +98,12 @@ export const activeSessions = pgTable("active_sessions", {
referrer: text("referrer"),
});
-export const reports = pgTable(
- "reports",
+export const funnels = pgTable(
+ "funnels",
{
reportId: serial("report_id").primaryKey().notNull(),
siteId: integer("site_id"),
userId: text("user_id"),
- reportType: text("report_type"),
data: jsonb(),
createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
@@ -113,12 +112,12 @@ export const reports = pgTable(
foreignKey({
columns: [table.siteId],
foreignColumns: [sites.siteId],
- name: "reports_site_id_sites_site_id_fk",
+ name: "funnels_site_id_sites_site_id_fk",
}),
foreignKey({
columns: [table.userId],
foreignColumns: [user.id],
- name: "reports_user_id_user_id_fk",
+ name: "funnels_user_id_user_id_fk",
}),
]
);
diff --git a/server/src/index.ts b/server/src/index.ts
index 4db13ade2..94964026e 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -8,7 +8,7 @@ import { fileURLToPath } from "url";
import { createFunnel } from "./api/analytics/createFunnel.js";
import { createGoal } from "./api/analytics/createGoal.js";
import { deleteGoal } from "./api/analytics/deleteGoal.js";
-import { deleteReport } from "./api/analytics/deleteReport.js";
+import { deleteFunnel } from "./api/analytics/deleteFunnel.js";
import { getEvents } from "./api/analytics/getEvents.js";
import { getFunnel } from "./api/analytics/getFunnel.js";
import { getFunnels } from "./api/analytics/getFunnels.js";
@@ -211,7 +211,7 @@ server.get("/funnels/:site", getFunnels);
server.get("/journeys/:site", getJourneys);
server.post("/funnel/:site", getFunnel);
server.post("/funnel/create/:site", createFunnel);
-server.delete("/report/:reportId", deleteReport);
+server.delete("/funnel/:funnelId", deleteFunnel);
server.get("/goals/:site", getGoals);
server.get("/goal/:goalId/:site", getGoal);
server.post("/goal/create", createGoal);