Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

📈 Poll group analytics (#1899)

Luke Vellae4d9d41b83a6
diff --git a/apps/web/package.json b/apps/web/package.json
index 211872b98..9e4f35f64 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -64,6 +64,7 @@
"cookie": "^0.7.0",
"crypto": "^1.0.1",
"dayjs": "^1.11.13",
+ "es-toolkit": "^1.39.9",
"hono": "^4.7.10",
"hono-rate-limiter": "^0.2.1",
"i18next": "^24.2.2",
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/duplicate-dialog.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/duplicate-dialog.tsx
index fc43391ca..0da1d324b 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/duplicate-dialog.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/duplicate-dialog.tsx
@@ -1,5 +1,4 @@
"use client";
-import { usePostHog } from "@rallly/posthog/client";
import { Button } from "@rallly/ui/button";
import type { DialogProps } from "@rallly/ui/dialog";
import {
@@ -24,7 +23,6 @@ export function DuplicateDialog({
...props
}: DialogProps & { pollId: string; pollTitle: string }) {
const duplicate = trpc.polls.duplicate.useMutation();
- const posthog = usePostHog();
const router = useRouter();
return (
<Dialog {...props}>
@@ -47,10 +45,6 @@ export function DuplicateDialog({
{ pollId, newTitle: data.title },
{
onSuccess: async (res) => {
- posthog?.capture("duplicate poll", {
- pollId,
- newPollId: res.id,
- });
router.push(`/poll/${res.id}`);
},
},
diff --git a/apps/web/src/components/create-poll.tsx b/apps/web/src/components/create-poll.tsx
index 7d8994512..f0c42ea8a 100644
--- a/apps/web/src/components/create-poll.tsx
+++ b/apps/web/src/components/create-poll.tsx
@@ -1,5 +1,4 @@
"use client";
-import { usePostHog } from "@rallly/posthog/client";
import { Button } from "@rallly/ui/button";
import {
Card,
@@ -61,7 +60,6 @@ export const CreatePoll: React.FunctionComponent = () => {
useUnmount(clear);
- const posthog = usePostHog();
const createPoll = trpc.polls.create.useMutation({
networkMode: "always",
onError: (error) => {
@@ -94,14 +92,6 @@ export const CreatePoll: React.FunctionComponent = () => {
},
{
onSuccess: (res) => {
- posthog?.capture("created poll", {
- pollId: res.id,
- numberOfOptions: formData.options?.length,
- optionsView: formData?.view,
- $set: {
- last_poll_created_at: new Date().toISOString(),
- },
- });
router.push(`/poll/${res.id}`);
},
},
diff --git a/apps/web/src/components/poll/manage-poll/delete-poll-dialog.tsx b/apps/web/src/components/poll/manage-poll/delete-poll-dialog.tsx
index b50393ef3..b166cf8a7 100644
--- a/apps/web/src/components/poll/manage-poll/delete-poll-dialog.tsx
+++ b/apps/web/src/components/poll/manage-poll/delete-poll-dialog.tsx
@@ -1,4 +1,3 @@
-import { usePostHog } from "@rallly/posthog/client";
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -18,11 +17,9 @@ export const DeletePollDialog: React.FunctionComponent<{
onOpenChange: (open: boolean) => void;
urlId: string;
}> = ({ open, onOpenChange, urlId }) => {
- const posthog = usePostHog();
const router = useRouter();
const deletePoll = trpc.polls.delete.useMutation({
onSuccess: () => {
- posthog?.capture("deleted poll");
onOpenChange(false);
router.replace("/polls");
},
diff --git a/apps/web/src/components/poll/mutations.ts b/apps/web/src/components/poll/mutations.ts
index 8279f3b20..aef240bd2 100644
--- a/apps/web/src/components/poll/mutations.ts
+++ b/apps/web/src/components/poll/mutations.ts
@@ -1,4 +1,3 @@
-import { usePostHog } from "@rallly/posthog/client";
import { toast } from "@rallly/ui/sonner";
import { usePoll } from "@/components/poll-context";
import { trpc } from "@/trpc/client";
@@ -15,26 +14,13 @@ export const normalizeVotes = (
};
export const useAddParticipantMutation = () => {
- const posthog = usePostHog();
- return trpc.polls.participants.add.useMutation({
- onSuccess: async (_, input) => {
- posthog?.capture("add participant", {
- pollId: input.pollId,
- name: input.name,
- email: input.email,
- });
- },
- });
+ return trpc.polls.participants.add.useMutation();
};
export const useUpdateParticipantMutation = () => {
const queryClient = trpc.useUtils();
- const posthog = usePostHog();
return trpc.polls.participants.update.useMutation({
onSuccess: (participant) => {
- posthog?.capture("update participant", {
- name: participant.name,
- });
queryClient.polls.participants.list.setData(
{ pollId: participant.pollId },
(existingParticipants = []) => {
@@ -57,7 +43,6 @@ export const useUpdateParticipantMutation = () => {
export const useDeleteParticipantMutation = () => {
const queryClient = trpc.useUtils();
- const posthog = usePostHog();
const { poll } = usePoll();
return trpc.polls.participants.delete.useMutation({
onMutate: ({ participantId }) => {
@@ -68,23 +53,11 @@ export const useDeleteParticipantMutation = () => {
},
);
},
- onSuccess: (_, { participantId }) => {
- posthog?.capture("remove participant", {
- pollId: poll.id,
- participantId,
- });
- },
});
};
export const useUpdatePollMutation = () => {
- const posthog = usePostHog();
return trpc.polls.update.useMutation({
- onSuccess: (_data, { urlId }) => {
- posthog?.capture("updated poll", {
- id: urlId,
- });
- },
onError: (error) => {
if (error.data?.code === "BAD_REQUEST") {
toast.error(error.message);
diff --git a/apps/web/src/components/poll/notifications-toggle.tsx b/apps/web/src/components/poll/notifications-toggle.tsx
index ec0a11d52..b5e1a8e46 100644
--- a/apps/web/src/components/poll/notifications-toggle.tsx
+++ b/apps/web/src/components/poll/notifications-toggle.tsx
@@ -1,4 +1,3 @@
-import { usePostHog } from "@rallly/posthog/client";
import { Button } from "@rallly/ui/button";
import { Icon } from "@rallly/ui/icon";
import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";
@@ -30,17 +29,10 @@ const NotificationsToggle: React.FunctionComponent = () => {
const isWatching = watchers?.some(({ userId }) => userId === user?.id);
- const posthog = usePostHog();
-
const queryClient = trpc.useUtils();
const watch = trpc.polls.watch.useMutation({
onSuccess: () => {
- // TODO (Luke Vella) [2023-04-08]: We should have a separate query for getting watchers
- posthog?.capture("turned notifications on", {
- pollId: poll.id,
- source: "notifications-toggle",
- });
queryClient.polls.getWatchers.setData(
{ pollId: poll.id },
(oldWatchers) => {
@@ -55,10 +47,6 @@ const NotificationsToggle: React.FunctionComponent = () => {
const unwatch = trpc.polls.unwatch.useMutation({
onSuccess: () => {
- posthog?.capture("turned notifications off", {
- pollId: poll.id,
- source: "notifications-toggle",
- });
queryClient.polls.getWatchers.setData(
{ pollId: poll.id },
(oldWatchers) => {
diff --git a/apps/web/src/features/analytics/service.ts b/apps/web/src/features/analytics/service.ts
new file mode 100644
index 000000000..8f10c2c93
--- /dev/null
+++ b/apps/web/src/features/analytics/service.ts
@@ -0,0 +1,143 @@
+import { PostHog } from "@rallly/posthog/server";
+import { toSnakeCaseKeys } from "es-toolkit";
+import { env } from "@/env";
+import type { PollEvent, PollGroupProperties } from "@/features/poll/analytics";
+
+/**
+ * Analytics service that batches PostHog events for better performance
+ * Events are queued and sent in batches to avoid blocking mutations
+ */
+export class AnalyticsService {
+ private posthog: PostHog | null = null;
+
+ constructor() {
+ // Only initialize PostHog if we have the required environment variables
+ if (env.NEXT_PUBLIC_POSTHOG_API_HOST && env.NEXT_PUBLIC_POSTHOG_API_KEY) {
+ this.posthog = new PostHog(env.NEXT_PUBLIC_POSTHOG_API_KEY, {
+ host: env.NEXT_PUBLIC_POSTHOG_API_HOST,
+ flushAt: 20,
+ flushInterval: 10000,
+ });
+ }
+ }
+
+ /**
+ * Track a poll event
+ * Events are batched and will be sent when flush() is called or when batch limits are reached
+ */
+ trackEvent(event: PollEvent): void {
+ if (!this.posthog) return;
+
+ try {
+ // Handle automatic group updates based on event type
+ switch (event.type) {
+ case "poll_create":
+ // Set up initial group properties for new polls
+ this.setPoll(event.pollId, {
+ name: event.properties.title, // The PostHog UI identifies a group using the name property
+ title: event.properties.title,
+ status: "live", // New polls start as live
+ participant_count: 0, // New polls start with 0 participants
+ comment_count: 0, // New polls start with 0 comments
+ option_count: event.properties.optionCount,
+ has_location: event.properties.hasLocation,
+ has_description: event.properties.hasDescription,
+ timezone: event.properties.timezone,
+ });
+ break;
+
+ case "poll_finalize":
+ // Update status to finalized
+ this.setPoll(event.pollId, {
+ status: "finalized",
+ });
+ break;
+
+ case "poll_reopen":
+ case "poll_resume":
+ // Update status to live
+ this.setPoll(event.pollId, {
+ status: "live",
+ });
+ break;
+
+ case "poll_pause":
+ // Update status to paused
+ this.setPoll(event.pollId, {
+ status: "paused",
+ });
+ break;
+
+ case "poll_update_details":
+ case "poll_update_options":
+ case "poll_update_settings":
+ this.setPoll(event.pollId, toSnakeCaseKeys(event.properties));
+ break;
+
+ default:
+ break;
+ }
+
+ this.posthog.capture({
+ distinctId: event.userId,
+ event: event.type,
+ properties: {
+ poll_id: event.pollId,
+ ...toSnakeCaseKeys(event.properties ?? {}),
+ },
+ groups: {
+ poll: event.pollId,
+ },
+ });
+ } catch (error) {
+ // Log error but don't throw - analytics should never break the application
+ console.error("Failed to track analytics event:", error);
+ }
+ }
+
+ /**
+ * Update poll group properties with strong typing
+ * This is a strongly typed version of updateGroup specifically for polls
+ */
+ setPoll(pollId: string, properties: Partial<PollGroupProperties>): void {
+ if (!this.posthog) return;
+
+ try {
+ this.posthog.groupIdentify({
+ groupType: "poll",
+ groupKey: pollId,
+ properties,
+ });
+ } catch (error) {
+ console.error("Failed to update poll group:", error);
+ }
+ }
+
+ /**
+ * Flush all pending events to PostHog
+ * This should be called after mutations complete to ensure events are sent
+ */
+ async flush(): Promise<void> {
+ if (!this.posthog) return;
+
+ try {
+ await this.posthog.flush();
+ } catch (error) {
+ console.error("Failed to flush analytics events:", error);
+ }
+ }
+
+ /**
+ * Shutdown the PostHog client
+ * This should be called when the service is no longer needed
+ */
+ async shutdown(): Promise<void> {
+ if (!this.posthog) return;
+
+ try {
+ await this.posthog.shutdown();
+ } catch (error) {
+ console.error("Failed to shutdown analytics service:", error);
+ }
+ }
+}
diff --git a/apps/web/src/features/poll/analytics.ts b/apps/web/src/features/poll/analytics.ts
new file mode 100644
index 000000000..df64e2b7f
--- /dev/null
+++ b/apps/web/src/features/poll/analytics.ts
@@ -0,0 +1,165 @@
+import type { PollStatus } from "@/features/poll/schema";
+
+// Base event data that all events share
+interface BaseEventData {
+ userId: string;
+ pollId: string;
+ properties?: Record<string, unknown>;
+}
+
+export interface PollGroupProperties {
+ name: string; // PostHog group name (same as title)
+ title: string;
+ status: PollStatus;
+ created_at: string;
+ participant_count: number;
+ hide_participants: boolean;
+ require_participant_email: boolean;
+ hide_scores: boolean;
+ disable_comments: boolean;
+ comment_count: number;
+ option_count: number;
+ has_location: boolean;
+ has_description: boolean;
+ timezone?: string;
+}
+
+// Discriminated union of all possible poll events
+export type PollEvent =
+ | PollCreateEvent
+ | PollUpdateDetailsEvent
+ | PollUpdateOptionsEvent
+ | PollUpdateSettingsEvent
+ | PollDeleteEvent
+ | PollFinalizeEvent
+ | PollReopenEvent
+ | PollPauseEvent
+ | PollResumeEvent
+ | PollWatchEvent
+ | PollUnwatchEvent
+ | PollResponseSubmitEvent
+ | PollResponseUpdateEvent
+ | PollResponseDeleteEvent
+ | PollCommentAddEvent
+ | PollCommentDeleteEvent
+ | PollErrorEvent;
+
+// Poll events
+export interface PollCreateEvent extends BaseEventData {
+ type: "poll_create";
+ properties: {
+ title: string;
+ optionCount: number;
+ hasLocation: boolean;
+ hasDescription: boolean;
+ timezone?: string;
+ };
+}
+
+export interface PollUpdateDetailsEvent extends BaseEventData {
+ type: "poll_update_details";
+ properties: {
+ title: string;
+ hasDescription: boolean;
+ hasLocation: boolean;
+ };
+}
+
+export interface PollUpdateOptionsEvent extends BaseEventData {
+ type: "poll_update_options";
+ properties: {
+ optionCount: number;
+ };
+}
+
+export interface PollUpdateSettingsEvent extends BaseEventData {
+ type: "poll_update_settings";
+ properties: {
+ hideScores: boolean;
+ hideParticipants: boolean;
+ disableComments: boolean;
+ requireParticipantEmail: boolean;
+ };
+}
+
+export interface PollDeleteEvent extends BaseEventData {
+ type: "poll_delete";
+ properties?: Record<string, never>; // No additional properties
+}
+
+export interface PollFinalizeEvent extends BaseEventData {
+ type: "poll_finalize";
+ properties: {
+ participantCount: number;
+ attendeeCount: number;
+ daysSinceCreated: number;
+ };
+}
+
+export interface PollReopenEvent extends BaseEventData {
+ type: "poll_reopen";
+}
+
+export interface PollPauseEvent extends BaseEventData {
+ type: "poll_pause";
+}
+
+export interface PollResumeEvent extends BaseEventData {
+ type: "poll_resume";
+}
+
+export interface PollWatchEvent extends BaseEventData {
+ type: "poll_watch";
+}
+
+export interface PollUnwatchEvent extends BaseEventData {
+ type: "poll_unwatch";
+}
+
+export interface PollResponseSubmitEvent extends BaseEventData {
+ type: "poll_response_submit";
+ properties: {
+ participantId: string;
+ hasEmail: boolean;
+ };
+}
+
+export interface PollResponseUpdateEvent extends BaseEventData {
+ type: "poll_response_update";
+ properties: {
+ participantId: string;
+ };
+}
+
+export interface PollResponseDeleteEvent extends BaseEventData {
+ type: "poll_response_delete";
+ properties: {
+ participantId: string;
+ };
+}
+
+// Poll comment events
+export interface PollCommentAddEvent extends BaseEventData {
+ type: "poll_comment_add";
+ properties: {
+ commentId: string;
+ };
+}
+
+export interface PollCommentDeleteEvent extends BaseEventData {
+ type: "poll_comment_delete";
+ properties: {
+ commentId: string;
+ };
+}
+
+// Error events
+export interface PollErrorEvent extends BaseEventData {
+ type: "poll_error";
+ properties: {
+ operation: string;
+ errorMessage: string;
+ errorCode?: string;
+ errorStatus?: number;
+ };
+}
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index fde30a0f2..c4c9e18f0 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -301,6 +301,19 @@ export const polls = router({
}
}
+ ctx.analytics.trackEvent({
+ type: "poll_create",
+ userId: ctx.user.id,
+ pollId: poll.id,
+ properties: {
+ title: poll.title,
+ optionCount: poll.options.length,
+ hasLocation: !!input.location,
+ hasDescription: !!input.description,
+ timezone: input.timeZone,
+ },
+ });
+
revalidatePath("/", "layout");
return { id: poll.id };
@@ -346,7 +359,7 @@ export const polls = router({
return next();
})
- .mutation(async ({ input }) => {
+ .mutation(async ({ input, ctx }) => {
const pollId = await getPollIdFromAdminUrlId(input.urlId);
if (input.optionsToDelete && input.optionsToDelete.length > 0) {
@@ -399,6 +412,92 @@ export const polls = router({
requireParticipantEmail: input.requireParticipantEmail,
},
});
+
+ // Get updated poll data for group update
+ const updatedPoll = await prisma.poll.findUnique({
+ where: { id: pollId },
+ select: {
+ title: true,
+ status: true,
+ createdAt: true,
+ location: true,
+ description: true,
+ disableComments: true,
+ requireParticipantEmail: true,
+ hideParticipants: true,
+ hideScores: true,
+ timeZone: true,
+ _count: {
+ select: {
+ participants: {
+ where: { deleted: false },
+ },
+ comments: true,
+ options: true,
+ },
+ },
+ },
+ });
+
+ if (!updatedPoll) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ });
+ }
+
+ // Track specific poll update events based on what was changed
+ const hasDetailsUpdate =
+ input.title !== undefined ||
+ input.location !== undefined ||
+ input.description !== undefined;
+ const hasOptionsUpdate =
+ (input.optionsToDelete && input.optionsToDelete.length > 0) ||
+ (input.optionsToAdd && input.optionsToAdd.length > 0);
+ const hasSettingsUpdate =
+ input.timeZone !== undefined ||
+ input.hideParticipants !== undefined ||
+ input.disableComments !== undefined ||
+ input.hideScores !== undefined ||
+ input.requireParticipantEmail !== undefined;
+
+ if (hasDetailsUpdate) {
+ ctx.analytics.trackEvent({
+ type: "poll_update_details",
+ userId: ctx.user.id,
+ pollId,
+ properties: {
+ title: updatedPoll.title,
+ hasLocation: !!updatedPoll.location,
+ hasDescription: !!updatedPoll.description,
+ },
+ });
+ }
+
+ if (hasOptionsUpdate) {
+ ctx.analytics.trackEvent({
+ type: "poll_update_options",
+ userId: ctx.user.id,
+ pollId,
+ properties: {
+ optionCount: updatedPoll._count.options,
+ },
+ });
+ }
+
+ if (hasSettingsUpdate) {
+ ctx.analytics.trackEvent({
+ type: "poll_update_settings",
+ userId: ctx.user.id,
+ pollId,
+ properties: {
+ disableComments: !!updatedPoll.disableComments,
+ hideParticipants: !!updatedPoll.hideParticipants,
+ hideScores: !!updatedPoll.hideScores,
+ requireParticipantEmail: !!updatedPoll.requireParticipantEmail,
+ },
+ });
+ }
+
revalidatePath("/", "layout");
}),
delete: possiblyPublicProcedure
@@ -407,12 +506,21 @@ export const polls = router({
urlId: z.string(),
}),
)
- .mutation(async ({ input: { urlId } }) => {
+ .use(requireUserMiddleware)
+ .mutation(async ({ input: { urlId }, ctx }) => {
const pollId = await getPollIdFromAdminUrlId(urlId);
await prisma.poll.update({
where: { id: pollId },
data: { deleted: true, deletedAt: new Date() },
});
+
+ // Track poll deletion analytics
+ ctx.analytics.trackEvent({
+ type: "poll_delete",
+ userId: ctx.user.id,
+ pollId,
+ });
+
revalidatePath("/", "layout");
}),
// END LEGACY ROUTES
@@ -441,6 +549,13 @@ export const polls = router({
userId: ctx.user.id,
},
});
+
+ // Track poll watch analytics
+ ctx.analytics.trackEvent({
+ type: "poll_watch",
+ userId: ctx.user.id,
+ pollId: input.pollId,
+ });
}),
unwatch: privateProcedure
.input(z.object({ pollId: z.string() }))
@@ -461,6 +576,13 @@ export const polls = router({
id: watcher.id,
},
});
+
+ // Track poll unwatch analytics
+ ctx.analytics.trackEvent({
+ type: "poll_unwatch",
+ userId: ctx.user.id,
+ pollId: input.pollId,
+ });
}
}),
get: publicProcedure
@@ -882,28 +1004,27 @@ export const polls = router({
);
}
- posthog?.capture({
- distinctId: ctx.user.id,
- event: "finalize poll",
+ ctx.analytics.trackEvent({
+ type: "poll_finalize",
+ pollId: poll.id,
+ userId: ctx.user.id,
properties: {
- poll_id: poll.id,
- poll_time_zone: poll.timeZone,
- number_of_participants: poll.participants.length,
- number_of_attendees: attendees.length,
- days_since_created: dayjs().diff(poll.createdAt, "day"),
+ attendeeCount: attendees.length,
+ daysSinceCreated: dayjs().diff(poll.createdAt, "day"),
+ participantCount: poll.participants.length,
},
});
revalidatePath("/", "layout");
}
}),
- reopen: possiblyPublicProcedure
+ reopen: privateProcedure
.input(
z.object({
pollId: z.string(),
}),
)
- .mutation(async ({ input }) => {
+ .mutation(async ({ input, ctx }) => {
await prisma.$transaction(async () => {
const poll = await prisma.poll.update({
where: {
@@ -922,6 +1043,13 @@ export const polls = router({
});
}
});
+
+ ctx.analytics.trackEvent({
+ type: "poll_reopen",
+ pollId: input.pollId,
+ userId: ctx.user.id,
+ });
+
revalidatePath("/", "layout");
}),
pause: possiblyPublicProcedure
@@ -930,7 +1058,8 @@ export const polls = router({
pollId: z.string(),
}),
)
- .mutation(async ({ input }) => {
+ .use(requireUserMiddleware)
+ .mutation(async ({ input, ctx }) => {
await prisma.poll.update({
where: {
id: input.pollId,
@@ -939,6 +1068,12 @@ export const polls = router({
status: "paused",
},
});
+
+ ctx.analytics.trackEvent({
+ type: "poll_pause",
+ pollId: input.pollId,
+ userId: ctx.user.id,
+ });
}),
duplicate: proProcedure
.input(
@@ -1009,7 +1144,8 @@ export const polls = router({
pollId: z.string(),
}),
)
- .mutation(async ({ input }) => {
+ .use(requireUserMiddleware)
+ .mutation(async ({ input, ctx }) => {
await prisma.poll.update({
where: {
id: input.pollId,
@@ -1018,5 +1154,12 @@ export const polls = router({
status: "live",
},
});
+
+ // Track poll resume analytics
+ ctx.analytics.trackEvent({
+ type: "poll_resume",
+ userId: ctx.user.id,
+ pollId: input.pollId,
+ });
}),
});
diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.ts
index d541bfcbe..4cd19f237 100644
--- a/apps/web/src/trpc/routers/polls/comments.ts
+++ b/apps/web/src/trpc/routers/polls/comments.ts
@@ -1,10 +1,9 @@
import { prisma } from "@rallly/database";
import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { TRPCError } from "@trpc/server";
import { z } from "zod";
-
import { getEmailClient } from "@/utils/emails";
import { createToken } from "@/utils/session";
-
import {
createRateLimitMiddleware,
publicProcedure,
@@ -147,6 +146,16 @@ export const comments = router({
);
}
+ // Track comment addition analytics
+ ctx.analytics.trackEvent({
+ type: "poll_comment_add",
+ userId: ctx.user.id,
+ pollId,
+ properties: {
+ commentId: newComment.id,
+ },
+ });
+
return newComment;
}),
delete: publicProcedure
@@ -155,11 +164,36 @@ export const comments = router({
commentId: z.string(),
}),
)
- .mutation(async ({ input: { commentId } }) => {
+ .use(requireUserMiddleware)
+ .mutation(async ({ input: { commentId }, ctx }) => {
+ const comment = await prisma.comment.findUnique({
+ where: { id: commentId },
+ select: { pollId: true },
+ });
+
+ if (!comment) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Comment not found",
+ });
+ }
+
await prisma.comment.delete({
where: {
id: commentId,
},
});
+
+ // Track comment deletion analytics
+ if (comment) {
+ ctx.analytics.trackEvent({
+ type: "poll_comment_delete",
+ userId: ctx.user.id,
+ pollId: comment.pollId,
+ properties: {
+ commentId,
+ },
+ });
+ }
}),
});
diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.ts
index b19891e2f..872954657 100644
--- a/apps/web/src/trpc/routers/polls/participants.ts
+++ b/apps/web/src/trpc/routers/polls/participants.ts
@@ -110,8 +110,9 @@ export const participants = router({
participantId: z.string(),
}),
)
- .mutation(async ({ input: { participantId } }) => {
- await prisma.participant.update({
+ .use(requireUserMiddleware)
+ .mutation(async ({ input: { participantId }, ctx }) => {
+ const participant = await prisma.participant.update({
where: {
id: participantId,
},
@@ -120,6 +121,17 @@ export const participants = router({
deletedAt: new Date(),
},
});
+
+ if (participant) {
+ ctx.analytics.trackEvent({
+ type: "poll_response_delete",
+ userId: ctx.user.id,
+ pollId: participant.pollId,
+ properties: {
+ participantId,
+ },
+ });
+ }
}),
add: publicProcedure
.use(createRateLimitMiddleware("add_participant", 5, "1 m"))
@@ -233,6 +245,17 @@ export const participants = router({
}),
);
+ // Track participant addition analytics
+ ctx.analytics.trackEvent({
+ type: "poll_response_submit",
+ userId: user.id,
+ pollId,
+ properties: {
+ participantId: participant.id,
+ hasEmail: !!email,
+ },
+ });
+
return participant;
},
),
@@ -262,7 +285,8 @@ export const participants = router({
.array(),
}),
)
- .mutation(async ({ input: { pollId, participantId, votes } }) => {
+ .use(requireUserMiddleware)
+ .mutation(async ({ input: { pollId, participantId, votes }, ctx }) => {
const participant = await prisma.$transaction(async (tx) => {
// Delete existing votes
await tx.vote.deleteMany({
@@ -308,6 +332,15 @@ export const participants = router({
});
});
+ ctx.analytics.trackEvent({
+ type: "poll_response_update",
+ userId: ctx.user.id,
+ pollId,
+ properties: {
+ participantId,
+ },
+ });
+
return participant;
}),
});
diff --git a/apps/web/src/trpc/trpc.ts b/apps/web/src/trpc/trpc.ts
index b618a51b1..b57f44017 100644
--- a/apps/web/src/trpc/trpc.ts
+++ b/apps/web/src/trpc/trpc.ts
@@ -2,9 +2,11 @@ import { prisma } from "@rallly/database";
import { posthog } from "@rallly/posthog/server";
import { initTRPC, TRPCError } from "@trpc/server";
import { Ratelimit } from "@upstash/ratelimit";
+import { waitUntil } from "@vercel/functions";
import { kv } from "@vercel/kv";
import superjson from "superjson";
import { getCurrentUserSpace } from "@/auth/data";
+import { AnalyticsService } from "@/features/analytics/service";
import { isQuickCreateEnabled } from "@/features/quick-create";
import { isSelfHosted } from "@/utils/constants";
import type { TRPCContext } from "./context";
@@ -18,11 +20,29 @@ const t = initTRPC.context<TRPCContext>().create({
export const router = t.router;
-export const publicProcedure = t.procedure;
-
export const middleware = t.middleware;
-export const possiblyPublicProcedure = t.procedure.use(
+export const procedureWithAnalytics = t.procedure.use(
+ async ({ next, type }) => {
+ const analytics = new AnalyticsService();
+
+ const res = await next({
+ ctx: {
+ analytics,
+ },
+ });
+
+ if (type === "mutation") {
+ waitUntil(analytics.shutdown());
+ }
+
+ return res;
+ },
+);
+
+export const publicProcedure = procedureWithAnalytics;
+
+export const possiblyPublicProcedure = procedureWithAnalytics.use(
middleware(async ({ ctx, next }) => {
// These procedurs are public if Quick Create is enabled
const isGuest = !ctx.user || ctx.user.isGuest;
@@ -79,21 +99,23 @@ export const requireUserMiddleware = middleware(async ({ ctx, next }) => {
});
});
-export const privateProcedure = t.procedure.use(async ({ ctx, next }) => {
- const { user } = ctx;
- if (!user || user.isGuest !== false) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Login is required",
- });
- }
+export const privateProcedure = procedureWithAnalytics.use(
+ async ({ ctx, next }) => {
+ const { user } = ctx;
+ if (!user || user.isGuest !== false) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Login is required",
+ });
+ }
- return next({
- ctx: {
- user,
- },
- });
-});
+ return next({
+ ctx: {
+ user,
+ },
+ });
+ },
+);
export const proProcedure = privateProcedure.use(async ({ next }) => {
if (isSelfHosted) {
diff --git a/packages/posthog/src/server.ts b/packages/posthog/src/server.ts
index 971a18c7b..cb3789b26 100644
--- a/packages/posthog/src/server.ts
+++ b/packages/posthog/src/server.ts
@@ -11,4 +11,6 @@ function PostHogClient() {
return posthogClient;
}
+export { PostHog };
+
export const posthog = PostHogClient();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5da15a2e8..f94fe6d1c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -307,6 +307,9 @@ importers:
dayjs:
specifier: ^1.11.13
version: 1.11.13
+ es-toolkit:
+ specifier: ^1.39.9
+ version: 1.39.9
hono:
specifier: ^4.7.10
version: 4.7.10
@@ -5702,6 +5705,9 @@ packages:
resolution: {integrity: sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-9OtbkZmTA2Qc9groyA1PUNeb6knVTkvB2RSdr/LcJXDL8IdEakaxwXLHXa7VX/Wj0GmdMJPR3WhnPGhiP3E+qg==}
+
resolution: {integrity: sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ==}
@@ -14797,6 +14803,8 @@ snapshots:
is-date-object: 1.1.0
is-symbol: 1.1.1
+
dependencies:
'@types/estree-jsx': 1.0.5