Skip to content

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

♻️ Replace poll_views table with activity-based poll cleanup (#2469)

Luke Vella4fc3036b82b2
diff --git a/apps/docs/faq.mdx b/apps/docs/faq.mdx
index a649c18d5..e030724e1 100644
--- a/apps/docs/faq.mdx
+++ b/apps/docs/faq.mdx
@@ -24,8 +24,9 @@ description: "Frequently asked questions about Rallly."
</Accordion>
<Accordion title="How long will Rallly keep my poll?">
- Polls are automatically deleted when all date options are in the past AND the
- poll has not been accessed for over 30 days. This does not apply to Pro users.
+ Polls are automatically deleted when all date options are in the past AND there
+ has been no activity for over 30 days. Activity includes new votes, comments, or
+ changes to the poll. This does not apply to Pro users.
</Accordion>
<Accordion title="Can I limit the number of participants that can vote for an option?">
diff --git a/apps/landing/public/locales/en/pricing.json b/apps/landing/public/locales/en/pricing.json
index c81b72e0b..0f686a21b 100644
--- a/apps/landing/public/locales/en/pricing.json
+++ b/apps/landing/public/locales/en/pricing.json
@@ -25,7 +25,7 @@
"upgrade": "Upgrade",
"upgradeNowSaveLater": "Upgrade now, save later",
"whenPollInactive": "When does a poll become inactive?",
- "whenPollInactiveAnswer": "Polls become inactive when all date options are in the past AND the poll has not been accessed for over 30 days. Inactive polls are automatically deleted if you do not have a paid subscription.",
+ "whenPollInactiveAnswer": "Polls become inactive when all date options are in the past AND there has been no activity for over 30 days. Activity includes new votes, comments, or changes to the poll. Inactive polls are automatically deleted if you do not have a paid subscription.",
"whyUpgrade": "Why should I upgrade?",
"whyUpgradeAnswer2": "Upgrading to a paid plan makes sense if you use Rallly often or use it for work. The current subscription rate is a special early adopter rate and will increase in the future. By upgrading now, you will get early access to new, high-quality scheduling tools as they are released and lock in your subscription rate so you won't be affected by future price increases.",
"yearlyBillingDescription": "per year"
diff --git a/apps/web/src/actions/track-poll-view.ts b/apps/web/src/actions/track-poll-view.ts
deleted file mode 100644
index 893e8ea5a..000000000
--- a/apps/web/src/actions/track-poll-view.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-"use server";
-
-import { prisma } from "@rallly/database";
-import { createLogger } from "@rallly/logger";
-import { headers } from "next/headers";
-import { getUserIdIfLoggedIn } from "@/lib/auth";
-
-const logger = createLogger("actions/track-poll-view");
-
-/**
- * Server action to track a poll view
- * Records information about the view in the database
- */
-export async function trackPollView(pollId: string) {
- try {
- const headersList = await headers();
- const userAgent = headersList.get("user-agent");
- const ip = headersList.get("x-forwarded-for") || "unknown";
-
- const userId = await getUserIdIfLoggedIn();
-
- await prisma.pollView.create({
- data: {
- pollId,
- userId,
- ipAddress: ip,
- userAgent,
- },
- });
-
- return { success: true };
- } catch (error) {
- logger.error({ error, pollId }, "Failed to record poll view");
- return { success: false, error: "Failed to record view" };
- }
-}
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/admin-page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/admin-page.tsx
index e5431fb1f..9edf27a2b 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/admin-page.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/admin-page.tsx
@@ -2,20 +2,13 @@
import Discussion from "@/components/discussion";
import { EventCard } from "@/components/event-card";
import { PollFooter } from "@/components/poll/poll-footer";
-import { PollViewTracker } from "@/components/poll/poll-view-tracker";
import { ResponsiveResults } from "@/components/poll/responsive-results";
import { VotingForm } from "@/components/poll/voting-form";
-import { usePoll } from "@/contexts/poll";
import { GuestPollAlert } from "./guest-poll-alert";
export function AdminPage() {
- // Get the poll ID from the context
- const poll = usePoll();
-
return (
<div className="space-y-3 lg:space-y-4">
- {/* Track poll views */}
- <PollViewTracker pollId={poll.id} />
<GuestPollAlert />
<EventCard />
<VotingForm>
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
index dd9614988..551c4592d 100644
--- a/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
+++ b/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
@@ -5,7 +5,6 @@ import Link from "next/link";
import Discussion from "@/components/discussion";
import { EventCard } from "@/components/event-card";
import { PollFooter } from "@/components/poll/poll-footer";
-import { PollViewTracker } from "@/components/poll/poll-view-tracker";
import { ResponsiveResults } from "@/components/poll/responsive-results";
import { VotingForm } from "@/components/poll/voting-form";
import { usePoll } from "@/contexts/poll";
@@ -47,11 +46,8 @@ const GoToApp = () => {
};
export function InvitePage() {
- const poll = usePoll();
-
return (
<div className="page-bg-gray-100 h-dvh overflow-auto p-3 lg:p-6 dark:bg-gray-900">
- <PollViewTracker pollId={poll.id} />
<div className="mx-auto w-full max-w-4xl space-y-3">
<GoToApp />
<EventCard />
diff --git a/apps/web/src/app/api/house-keeping/[...method]/route.ts b/apps/web/src/app/api/house-keeping/[...method]/route.ts
index 623d4a074..907a432e1 100644
--- a/apps/web/src/app/api/house-keeping/[...method]/route.ts
+++ b/apps/web/src/app/api/house-keeping/[...method]/route.ts
@@ -51,12 +51,14 @@ app.get("/delete-inactive-polls", async (c) => {
},
},
],
- // Poll is inactive (not updated AND not viewed in the last 30 days)
+ // Poll is inactive: not edited, and no participant activity (new or
+ // updated responses) or new comments in the last 30 days
updatedAt: { lt: thirtyDaysAgo },
- views: {
- none: {
- viewedAt: { gte: thirtyDaysAgo },
- },
+ participants: {
+ none: { updatedAt: { gte: thirtyDaysAgo } },
+ },
+ comments: {
+ none: { createdAt: { gte: thirtyDaysAgo } },
},
},
data: {
diff --git a/apps/web/src/components/poll/poll-view-tracker.tsx b/apps/web/src/components/poll/poll-view-tracker.tsx
deleted file mode 100644
index fdf14bd4d..000000000
--- a/apps/web/src/components/poll/poll-view-tracker.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-"use client";
-
-import { safeSessionStorage } from "@rallly/utils/safe-session-storage";
-import { useDebounce } from "react-use";
-
-import { trackPollView } from "@/actions/track-poll-view";
-
-// Global tracking state to prevent duplicate tracking across re-renders and strict mode
-const trackedPolls = new Set<string>();
-
-const VIEW_DELAY = 5000;
-
-/**
- * Component that tracks poll views
- * This should be included in poll pages to automatically record views
- */
-export function PollViewTracker({ pollId }: { pollId: string }) {
- // Use debounce to handle the view tracking
- // This will only execute after VIEW_DELAY milliseconds
- // and will automatically handle cleanup if the component unmounts
- useDebounce(
- () => {
- // Only track views in the browser
- if (typeof window === "undefined") return;
-
- // Check if this poll has already been tracked in this session
- if (trackedPolls.has(pollId)) {
- return;
- }
-
- // Mark as tracked immediately to prevent duplicate tracking
- trackedPolls.add(pollId);
-
- // Avoid duplicate view tracking within the same browser session
- const viewKey = `poll-view-${pollId}`;
- const lastView = safeSessionStorage.get(viewKey);
- const now = Date.now();
-
- // Only track a view if it's been more than 30 minutes since the last view
- // or if this is the first view in this session
- if (!lastView || now - Number.parseInt(lastView, 10) > 30 * 60 * 1000) {
- // Record the view using server action
- trackPollView(pollId)
- .then(() => {
- // Update the last view timestamp
- safeSessionStorage.set(viewKey, now.toString());
- })
- .catch(() => {
- trackedPolls.delete(pollId);
- });
- }
- },
- VIEW_DELAY,
- [pollId],
- );
-
- // This component doesn't render anything
- return null;
-}
diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.ts
index b5fa49119..8c6eb662d 100644
--- a/apps/web/src/trpc/routers/polls/participants.ts
+++ b/apps/web/src/trpc/routers/polls/participants.ts
@@ -442,11 +442,14 @@ export const participants = router({
})),
});
- // Return updated participant with votes
- return tx.participant.findUniqueOrThrow({
+ // Bump `updatedAt` so it reflects this vote change; the poll cleanup
+ // job uses it to detect recent activity. An empty `data: {}` update is
+ // a no-op for `@updatedAt`, so set it explicitly.
+ return tx.participant.update({
where: {
id: participantId,
},
+ data: { updatedAt: new Date() },
include: {
votes: {
select: {
diff --git a/apps/web/tests/house-keeping.spec.ts b/apps/web/tests/house-keeping.spec.ts
index 473d5af60..78fa00da7 100644
--- a/apps/web/tests/house-keeping.spec.ts
+++ b/apps/web/tests/house-keeping.spec.ts
@@ -120,14 +120,38 @@ test.describe("House-keeping API", () => {
});
createdPollIds.push(oldPollWithFutureOptions.id);
- const oldPollWithRecentViews = await createTestPoll({
- id: "old-poll-recent-views",
- title: "Old Poll with Recent Views",
+ // Protected: old/unedited, but a participant responded (or changed their
+ // vote) recently
+ const oldPollWithRecentParticipant = await createTestPoll({
+ id: "old-poll-recent-participant",
+ title: "Old Poll with Recent Participant",
userId: freeUser.id,
updatedAt: dayjs().subtract(35, "day").toDate(),
- hasRecentViews: true,
+ participantActiveAt: dayjs().subtract(15, "day").toDate(),
});
- createdPollIds.push(oldPollWithRecentViews.id);
+ createdPollIds.push(oldPollWithRecentParticipant.id);
+
+ // Protected: old/unedited, but someone commented recently
+ const oldPollWithRecentComment = await createTestPoll({
+ id: "old-poll-recent-comment",
+ title: "Old Poll with Recent Comment",
+ userId: freeUser.id,
+ updatedAt: dayjs().subtract(35, "day").toDate(),
+ commentCreatedAt: dayjs().subtract(15, "day").toDate(),
+ });
+ createdPollIds.push(oldPollWithRecentComment.id);
+
+ // Should be deleted: has activity, but all of it is older than 30 days
+ // (proves the check is recency-based, not mere existence)
+ const oldPollWithOldActivity = await createTestPoll({
+ id: "old-poll-old-activity",
+ title: "Old Poll with Old Activity",
+ userId: freeUser.id,
+ updatedAt: dayjs().subtract(35, "day").toDate(),
+ participantActiveAt: dayjs().subtract(35, "day").toDate(),
+ commentCreatedAt: dayjs().subtract(40, "day").toDate(),
+ });
+ createdPollIds.push(oldPollWithOldActivity.id);
// Call the delete-inactive-polls endpoint
const response = await request.get(
@@ -143,10 +167,11 @@ test.describe("House-keeping API", () => {
const responseData = await response.json();
expect(responseData.success).toBeTruthy();
- // We expect 2 polls to be marked as deleted:
+ // We expect 3 polls to be marked as deleted:
// - Old poll from free user (not in a paid space)
// - Old poll without a user
- expect(responseData.summary.markedDeleted).toBe(2);
+ // - Old poll whose only participant/comment activity is also older than 30 days
+ expect(responseData.summary.markedDeleted).toBe(3);
// Verify polls that should be marked as deleted
const deletedPollFromFreeUser = await prisma.poll.findUnique({
@@ -180,11 +205,24 @@ test.describe("House-keeping API", () => {
expect(protectedPollWithFutureOptions?.deleted).toBe(false);
expect(protectedPollWithFutureOptions?.deletedAt).toBeNull();
- const protectedPollWithRecentViews = await prisma.poll.findUnique({
- where: { id: oldPollWithRecentViews.id },
+ const protectedPollWithRecentParticipant = await prisma.poll.findUnique({
+ where: { id: oldPollWithRecentParticipant.id },
+ });
+ expect(protectedPollWithRecentParticipant?.deleted).toBe(false);
+ expect(protectedPollWithRecentParticipant?.deletedAt).toBeNull();
+
+ const protectedPollWithRecentComment = await prisma.poll.findUnique({
+ where: { id: oldPollWithRecentComment.id },
+ });
+ expect(protectedPollWithRecentComment?.deleted).toBe(false);
+ expect(protectedPollWithRecentComment?.deletedAt).toBeNull();
+
+ // The poll whose activity is all older than 30 days should be deleted
+ const deletedPollWithOldActivity = await prisma.poll.findUnique({
+ where: { id: oldPollWithOldActivity.id },
});
- expect(protectedPollWithRecentViews?.deleted).toBe(false);
- expect(protectedPollWithRecentViews?.deletedAt).toBeNull();
+ expect(deletedPollWithOldActivity?.deleted).toBe(true);
+ expect(deletedPollWithOldActivity?.deletedAt).not.toBeNull();
});
test("should permanently remove polls that have been marked as deleted for more than 7 days", async ({
diff --git a/apps/web/tests/test-utils.ts b/apps/web/tests/test-utils.ts
index 258e34171..e30ee959e 100644
--- a/apps/web/tests/test-utils.ts
+++ b/apps/web/tests/test-utils.ts
@@ -69,16 +69,18 @@ export async function createTestPoll({
userId,
spaceId,
updatedAt,
- hasRecentViews = false,
hasFutureOptions = false,
+ participantActiveAt,
+ commentCreatedAt,
}: {
id: string;
title: string;
userId?: string;
spaceId?: string;
updatedAt: Date;
- hasRecentViews?: boolean;
hasFutureOptions?: boolean;
+ participantActiveAt?: Date;
+ commentCreatedAt?: Date;
}) {
const pollData = {
id,
@@ -88,10 +90,21 @@ export async function createTestPoll({
userId,
spaceId,
updatedAt,
- ...(hasRecentViews && {
- views: {
+ ...(participantActiveAt && {
+ participants: {
create: {
- viewedAt: dayjs().subtract(15, "day").toDate(),
+ name: "Test Participant",
+ createdAt: participantActiveAt,
+ updatedAt: participantActiveAt,
+ },
+ },
+ }),
+ ...(commentCreatedAt && {
+ comments: {
+ create: {
+ content: "Test comment",
+ authorName: "Test Commenter",
+ createdAt: commentCreatedAt,
},
},
}),
diff --git a/packages/database/prisma/migrations/20260619111500_drop_poll_views/migration.sql b/packages/database/prisma/migrations/20260619111500_drop_poll_views/migration.sql
new file mode 100644
index 000000000..b42086944
--- /dev/null
+++ b/packages/database/prisma/migrations/20260619111500_drop_poll_views/migration.sql
@@ -0,0 +1,6 @@
+-- DropForeignKey
+ALTER TABLE "poll_views" DROP CONSTRAINT IF EXISTS "poll_views_poll_id_fkey";
+ALTER TABLE "poll_views" DROP CONSTRAINT IF EXISTS "poll_views_user_id_fkey";
+
+-- DropTable
+DROP TABLE "poll_views";
diff --git a/packages/database/prisma/models/poll.prisma b/packages/database/prisma/models/poll.prisma
index f595eced9..69987c932 100644
--- a/packages/database/prisma/models/poll.prisma
+++ b/packages/database/prisma/models/poll.prisma
@@ -53,7 +53,6 @@ model Poll {
participants Participant[]
comments Comment[]
votes Vote[]
- views PollView[]
space Space? @relation(fields: [spaceId], references: [id], onDelete: SetNull)
spaceId String? @map("space_id")
@@ -143,20 +142,3 @@ model Comment {
@@index([pollId])
@@map("comments")
}
-
-model PollView {
- id String @id @default(cuid())
- pollId String @map("poll_id")
- ipAddress String? @map("ip_address")
- userId String? @map("user_id")
- userAgent String? @map("user_agent")
- viewedAt DateTime @default(now()) @map("viewed_at")
-
- poll Poll @relation(fields: [pollId], references: [id], onDelete: Cascade)
- user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
-
- @@index([pollId], type: Hash)
- @@index([userId], type: Hash)
- @@index([viewedAt])
- @@map("poll_views")
-}
diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prisma
index 91f8ca4de..8aca8ee20 100644
--- a/packages/database/prisma/models/user.prisma
+++ b/packages/database/prisma/models/user.prisma
@@ -70,7 +70,6 @@ model User {
spaces Space[] @relation("UserSpaces")
memberOf SpaceMember[]
- pollViews PollView[]
scheduledEvents ScheduledEvent[]
scheduledEventInvites ScheduledEventInvite[]
hostedEventTypes EventType[]