Skip to content

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

✨ Activity log: event vocabulary + writes from every poll mutation (#3076)

Luke Vella67918171b69a
diff --git a/apps/web/src/features/auth/mutations.ts b/apps/web/src/features/auth/mutations.ts
index b2d08e9d6..ce99b2f3c 100644
--- a/apps/web/src/features/auth/mutations.ts
+++ b/apps/web/src/features/auth/mutations.ts
@@ -99,6 +99,20 @@ export const linkAnonymousUser = async (
userId: authenticatedUserId,
},
}),
+
+ // Transfer poll activity actor refs. They are soft references (no
+ // FK), so nothing else migrates them; without this the guest's
+ // events would point at the anonymous user forever, which is
+ // deleted after linking. Account deletion leaves refs inert on
+ // purpose — linking is the opposite case: the person still exists.
+ tx.pollActivity.updateMany({
+ where: {
+ userId: anonymousUserId,
+ },
+ data: {
+ userId: authenticatedUserId,
+ },
+ }),
]);
});
diff --git a/apps/web/src/features/poll/activity/data.ts b/apps/web/src/features/poll/activity/data.ts
new file mode 100644
index 000000000..242ae230c
--- /dev/null
+++ b/apps/web/src/features/poll/activity/data.ts
@@ -0,0 +1,37 @@
+import "server-only";
+
+import { prisma } from "@rallly/database";
+import type { AuthorizedSpaceId } from "@/features/space/types";
+import { parsePollActivity } from "./schema";
+
+/**
+ * Latest activity for a poll, newest first. Rows whose type or payload this
+ * version of the vocabulary can't interpret are skipped rather than failing
+ * the feed.
+ */
+export async function listPollActivity({
+ pollId,
+ spaceId,
+ limit,
+}: {
+ pollId: string;
+ spaceId: AuthorizedSpaceId;
+ limit: number;
+}) {
+ const rows = await prisma.pollActivity.findMany({
+ where: {
+ pollId,
+ poll: {
+ spaceId,
+ deleted: false,
+ },
+ },
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
+ take: limit,
+ });
+
+ return rows.flatMap((row) => {
+ const event = parsePollActivity(row);
+ return event ? [{ id: row.id, createdAt: row.createdAt, event }] : [];
+ });
+}
diff --git a/apps/web/src/features/poll/activity/mutations.ts b/apps/web/src/features/poll/activity/mutations.ts
new file mode 100644
index 000000000..349ac0b1d
--- /dev/null
+++ b/apps/web/src/features/poll/activity/mutations.ts
@@ -0,0 +1,38 @@
+import "server-only";
+
+import type { Prisma } from "@rallly/database";
+import type { PollActivityEvent } from "./schema";
+import { pollActivitySchema } from "./schema";
+
+export type PollActivityWrite = { pollId: string } & PollActivityEvent;
+
+/**
+ * Appends activity events to a poll's log. Takes the caller's transaction
+ * client because an event must commit atomically with the mutation it
+ * records: activity cannot be backfilled, so a mutation committing without
+ * its event is a permanent hole in the poll's history, and an event without
+ * its mutation records something that never happened.
+ */
+export async function recordPollActivities(
+ tx: Prisma.TransactionClient,
+ activities: PollActivityWrite[],
+) {
+ if (activities.length === 0) {
+ return;
+ }
+
+ await tx.pollActivity.createMany({
+ data: activities.map(({ pollId, ...event }) => {
+ const parsed = pollActivitySchema.parse(event);
+ return {
+ pollId,
+ type: parsed.type,
+ userId: ("userId" in parsed ? parsed.userId : null) ?? null,
+ participantId: "participantId" in parsed ? parsed.participantId : null,
+ inviteId: "inviteId" in parsed ? parsed.inviteId : null,
+ optionId: "optionId" in parsed ? parsed.optionId : null,
+ payload: parsed.payload as Prisma.InputJsonObject,
+ };
+ }),
+ });
+}
diff --git a/apps/web/src/features/poll/activity/schema.test.ts b/apps/web/src/features/poll/activity/schema.test.ts
new file mode 100644
index 000000000..3725a147e
--- /dev/null
+++ b/apps/web/src/features/poll/activity/schema.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "vitest";
+import { parsePollActivity, pollActivitySchema } from "./schema";
+
+const emptyRefs = {
+ userId: null,
+ participantId: null,
+ inviteId: null,
+ optionId: null,
+};
+
+describe("pollActivitySchema", () => {
+ it("accepts a system event with no actor", () => {
+ const result = pollActivitySchema.safeParse({
+ type: "poll_closed",
+ userId: null,
+ payload: { reason: "auto" },
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it("rejects an unknown closed reason", () => {
+ const result = pollActivitySchema.safeParse({
+ type: "poll_closed",
+ userId: "u1",
+ payload: { reason: "deadline" },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("requires the subject ref of a response event", () => {
+ const result = pollActivitySchema.safeParse({
+ type: "response_created",
+ userId: "u1",
+ payload: { name: "Jessie Smith" },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("requires the vote snapshot on response_deleted", () => {
+ const result = pollActivitySchema.safeParse({
+ type: "response_deleted",
+ userId: "u1",
+ participantId: "part1",
+ payload: { name: "Jessie Smith" },
+ });
+
+ expect(result.success).toBe(false);
+ });
+});
+
+describe("parsePollActivity", () => {
+ it("rehydrates a stored row into a typed event", () => {
+ const event = parsePollActivity({
+ ...emptyRefs,
+ type: "response_deleted",
+ userId: "u1",
+ participantId: "part1",
+ payload: {
+ name: "Jessie Smith",
+ votes: [
+ {
+ optionId: "opt1",
+ start: "2026-09-01T10:00:00.000Z",
+ duration: 60,
+ type: "yes",
+ },
+ ],
+ },
+ });
+
+ expect(event).toMatchObject({
+ type: "response_deleted",
+ participantId: "part1",
+ payload: { name: "Jessie Smith" },
+ });
+ });
+
+ it("returns null for a type outside this version's vocabulary", () => {
+ const event = parsePollActivity({
+ ...emptyRefs,
+ type: "poll_broadcast",
+ payload: {},
+ });
+
+ expect(event).toBeNull();
+ });
+
+ it("returns null when a required subject ref was lost", () => {
+ const event = parsePollActivity({
+ ...emptyRefs,
+ type: "option_added",
+ userId: "u1",
+ payload: { start: "2026-09-01T10:00:00.000Z", duration: 60 },
+ });
+
+ expect(event).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/poll/activity/schema.ts b/apps/web/src/features/poll/activity/schema.ts
new file mode 100644
index 000000000..25c7f83bf
--- /dev/null
+++ b/apps/web/src/features/poll/activity/schema.ts
@@ -0,0 +1,154 @@
+import * as z from "zod";
+import { pollClosedReasonSchema } from "@/features/poll/schema";
+
+/**
+ * Poll activity vocabulary v1. The `type` column is a plain string in the
+ * database so the vocabulary grows by extending this union, without a
+ * migration. Subject ids are soft references that outlive their subjects;
+ * payloads carry the display snapshot (names, dates) so an event still
+ * renders after the participant, option or account it refers to is gone.
+ *
+ * Invite events are defined ahead of their write sites: email invites ship in
+ * phase 2, and defining the vocabulary now keeps it in one place.
+ */
+
+const actor = {
+ /** The acting user. Null for system events (e.g. the auto-close cron). */
+ userId: z.string().nullish(),
+};
+
+const optionSnapshotSchema = z.object({
+ start: z.iso.datetime(),
+ duration: z.number().int().nonnegative(),
+});
+
+const voteSnapshotSchema = z.object({
+ optionId: z.string(),
+ start: z.iso.datetime(),
+ duration: z.number().int().nonnegative(),
+ type: z.enum(["yes", "no", "ifNeedBe"]),
+});
+
+const inviteePayloadSchema = z.object({
+ email: z.string(),
+});
+
+export const pollActivitySchema = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("poll_created"),
+ ...actor,
+ payload: z.object({ title: z.string() }),
+ }),
+ z.object({
+ type: z.literal("poll_updated"),
+ ...actor,
+ payload: z.object({}),
+ }),
+ z.object({
+ type: z.literal("poll_closed"),
+ ...actor,
+ payload: z.object({ reason: pollClosedReasonSchema }),
+ }),
+ z.object({
+ type: z.literal("poll_reopened"),
+ ...actor,
+ payload: z.object({}),
+ }),
+ z.object({
+ type: z.literal("poll_scheduled"),
+ ...actor,
+ optionId: z.string(),
+ payload: optionSnapshotSchema,
+ }),
+ z.object({
+ type: z.literal("invite_sent"),
+ ...actor,
+ inviteId: z.string(),
+ payload: inviteePayloadSchema,
+ }),
+ z.object({
+ // Opening is the invitee's own act, and invitees are not users.
+ type: z.literal("invite_opened"),
+ inviteId: z.string(),
+ payload: inviteePayloadSchema,
+ }),
+ z.object({
+ type: z.literal("invite_reminded"),
+ ...actor,
+ inviteId: z.string(),
+ payload: inviteePayloadSchema,
+ }),
+ z.object({
+ type: z.literal("invite_revoked"),
+ ...actor,
+ inviteId: z.string(),
+ payload: inviteePayloadSchema,
+ }),
+ z.object({
+ type: z.literal("invites_revoked_bulk"),
+ ...actor,
+ payload: z.object({ count: z.number().int().positive() }),
+ }),
+ z.object({
+ type: z.literal("response_created"),
+ ...actor,
+ participantId: z.string(),
+ payload: z.object({ name: z.string() }),
+ }),
+ z.object({
+ type: z.literal("response_updated"),
+ ...actor,
+ participantId: z.string(),
+ payload: z.object({ name: z.string() }),
+ }),
+ z.object({
+ type: z.literal("response_deleted"),
+ ...actor,
+ participantId: z.string(),
+ payload: z.object({
+ name: z.string(),
+ votes: z.array(voteSnapshotSchema),
+ }),
+ }),
+ z.object({
+ type: z.literal("option_added"),
+ ...actor,
+ optionId: z.string(),
+ payload: optionSnapshotSchema,
+ }),
+ z.object({
+ type: z.literal("option_deleted"),
+ ...actor,
+ optionId: z.string(),
+ payload: optionSnapshotSchema,
+ }),
+]);
+
+export type PollActivityEvent = z.infer<typeof pollActivitySchema>;
+
+export type PollActivityType = PollActivityEvent["type"];
+
+/**
+ * Rehydrates a stored activity row into a typed event. Returns null for rows
+ * this version of the vocabulary can't interpret (e.g. a type written by a
+ * newer deploy) so readers skip them instead of failing the whole feed.
+ */
+export function parsePollActivity(row: {
+ type: string;
+ userId: string | null;
+ participantId: string | null;
+ inviteId: string | null;
+ optionId: string | null;
+ payload: unknown;
+}) {
+ const result = pollActivitySchema.safeParse({
+ type: row.type,
+ userId: row.userId,
+ participantId: row.participantId ?? undefined,
+ inviteId: row.inviteId ?? undefined,
+ optionId: row.optionId ?? undefined,
+ payload: row.payload,
+ });
+
+ return result.success ? result.data : null;
+}
diff --git a/apps/web/src/features/poll/mutations.test.ts b/apps/web/src/features/poll/mutations.test.ts
index 8ed5afc96..9fe751ae9 100644
--- a/apps/web/src/features/poll/mutations.test.ts
+++ b/apps/web/src/features/poll/mutations.test.ts
@@ -2,21 +2,32 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AuthorizedSpaceId } from "@/features/space/types";
import { closePoll, deleteInactivePolls, setPollMuted } from "./mutations";
-const { mockUpdateMany, mockFindFirst, mockUpdate } = vi.hoisted(() => ({
- mockUpdateMany: vi.fn(),
- mockFindFirst: vi.fn(),
- mockUpdate: vi.fn(),
-}));
-
-vi.mock("@rallly/database", () => ({
- prisma: {
+const { mockUpdateMany, mockFindFirst, mockUpdate, mockActivityCreateMany } =
+ vi.hoisted(() => ({
+ mockUpdateMany: vi.fn(),
+ mockFindFirst: vi.fn(),
+ mockUpdate: vi.fn(),
+ mockActivityCreateMany: vi.fn(),
+ }));
+
+vi.mock("@rallly/database", () => {
+ const client = {
poll: {
updateMany: mockUpdateMany,
findFirst: mockFindFirst,
update: mockUpdate,
},
- },
-}));
+ pollActivity: {
+ createMany: mockActivityCreateMany,
+ },
+ };
+ return {
+ prisma: {
+ ...client,
+ $transaction: (fn: (tx: typeof client) => unknown) => fn(client),
+ },
+ };
+});
const NOW = new Date("2026-07-21T12:00:00Z");
@@ -188,9 +199,28 @@ describe("closePoll", () => {
const result = await closePoll({ pollId: "p1", spaceId });
expect(mockUpdate).not.toHaveBeenCalled();
+ expect(mockActivityCreateMany).not.toHaveBeenCalled();
expect(result).toBe(closed);
});
+ it("records a poll_closed activity alongside the close", async () => {
+ mockFindFirst.mockResolvedValue({ id: "p1", status: "open" });
+ mockUpdate.mockResolvedValue({ id: "p1", status: "closed" });
+
+ await closePoll({ pollId: "p1", spaceId, userId: "u1" });
+
+ expect(mockActivityCreateMany).toHaveBeenCalledWith({
+ data: [
+ expect.objectContaining({
+ pollId: "p1",
+ type: "poll_closed",
+ userId: "u1",
+ payload: { reason: "manual" },
+ }),
+ ],
+ });
+ });
+
it("scopes the lookup to the space and excludes deleted polls", async () => {
mockFindFirst.mockResolvedValue(null);
diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.ts
index 30095409f..0b1c33cf5 100644
--- a/apps/web/src/features/poll/mutations.ts
+++ b/apps/web/src/features/poll/mutations.ts
@@ -3,6 +3,7 @@ import "server-only";
import type { Prisma } from "@rallly/database";
import { prisma } from "@rallly/database";
import { nanoid } from "@rallly/utils/nanoid";
+import { recordPollActivities } from "@/features/poll/activity/mutations";
import type { AuthorizedSpaceId } from "@/features/space/types";
export type PollOption = {
@@ -39,48 +40,61 @@ export const createPoll = async ({
}: CreatePollParams) => {
const kind = options.some((o) => o.duration > 0) ? "time" : "date";
- const poll = await prisma.poll.create({
- data: {
- id: nanoid(),
- title,
- description,
- location,
- timeZone,
- requireParticipantEmail,
- hideParticipants,
- hideScores,
- disableComments,
- userId,
- spaceId,
- kind,
- options: { createMany: { data: options } },
- },
- select: {
- id: true,
- title: true,
- description: true,
- location: true,
- timeZone: true,
- status: true,
- createdAt: true,
- disableComments: true,
- user: {
- select: {
- name: true,
- image: true,
- },
+ const poll = await prisma.$transaction(async (tx) => {
+ const poll = await tx.poll.create({
+ data: {
+ id: nanoid(),
+ title,
+ description,
+ location,
+ timeZone,
+ requireParticipantEmail,
+ hideParticipants,
+ hideScores,
+ disableComments,
+ userId,
+ spaceId,
+ kind,
+ options: { createMany: { data: options } },
},
- options: {
- select: {
- id: true,
- startTime: true,
- duration: true,
+ select: {
+ id: true,
+ title: true,
+ description: true,
+ location: true,
+ timeZone: true,
+ status: true,
+ createdAt: true,
+ disableComments: true,
+ user: {
+ select: {
+ name: true,
+ image: true,
+ },
},
- orderBy: {
- startTime: "asc",
+ options: {
+ select: {
+ id: true,
+ startTime: true,
+ duration: true,
+ },
+ orderBy: {
+ startTime: "asc",
+ },
},
},
- },
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId: poll.id,
+ type: "poll_created",
+ userId,
+ payload: { title },
+ },
+ ]);
+
+ return poll;
});
return poll;
@@ -117,35 +131,53 @@ const pollResponseSelect = {
* the poll unchanged without altering its `closedReason` (so a poll auto-closed
* by the cron job keeps `closedReason: "auto"`). Returns `null` when the poll
* does not exist in the space, letting the caller surface a 404.
+ *
+ * `userId` attributes the activity event when the actor is known; API key
+ * callers act as the space rather than a user and leave it unset.
*/
export const closePoll = async ({
pollId,
spaceId,
+ userId,
}: {
pollId: string;
spaceId: AuthorizedSpaceId;
+ userId?: string;
}) => {
- const poll = await prisma.poll.findFirst({
- where: {
- id: pollId,
- spaceId,
- deletedAt: null,
- },
- select: pollResponseSelect,
- });
+ return prisma.$transaction(async (tx) => {
+ const poll = await tx.poll.findFirst({
+ where: {
+ id: pollId,
+ spaceId,
+ deletedAt: null,
+ },
+ select: pollResponseSelect,
+ });
- if (!poll) {
- return null;
- }
+ if (!poll) {
+ return null;
+ }
- if (poll.status === "closed") {
- return poll;
- }
+ if (poll.status === "closed") {
+ return poll;
+ }
- return prisma.poll.update({
- where: { id: pollId },
- data: { status: "closed", closedReason: "manual" },
- select: pollResponseSelect,
+ const closedPoll = await tx.poll.update({
+ where: { id: pollId },
+ data: { status: "closed", closedReason: "manual" },
+ select: pollResponseSelect,
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "poll_closed",
+ userId: userId ?? null,
+ payload: { reason: "manual" },
+ },
+ ]);
+
+ return closedPoll;
});
};
@@ -289,25 +321,44 @@ export async function deleteInactivePolls() {
* Raw SQL because the option-end comparison (start_time + duration) can't be
* expressed in a Prisma `where`. It also deliberately does not touch
* `updated_at`, so closing a poll doesn't reset the inactivity clock that
- * delete-inactive-polls keys off.
+ * delete-inactive-polls keys off. RETURNING feeds the activity writes, which
+ * commit in the same transaction as the closes.
*/
export async function autoClosePolls() {
- const closed = await prisma.$executeRaw`
- UPDATE polls p
- SET status = 'closed', closed_reason = 'auto'
- WHERE p.status = 'open'
- AND p.deleted = false
- AND EXISTS (SELECT 1 FROM options o WHERE o.poll_id = p.id)
- AND NOT EXISTS (
- SELECT 1 FROM options o
- WHERE o.poll_id = p.id
- AND o.start_time + (CASE WHEN o.duration_minutes = 0
- THEN interval '24 hours'
- ELSE make_interval(mins => o.duration_minutes) END) > (now() AT TIME ZONE 'UTC')
- )
- `;
-
- return closed;
+ return prisma.$transaction(
+ async (tx) => {
+ const closed = await tx.$queryRaw<{ id: string }[]>`
+ UPDATE polls p
+ SET status = 'closed', closed_reason = 'auto'
+ WHERE p.status = 'open'
+ AND p.deleted = false
+ AND EXISTS (SELECT 1 FROM options o WHERE o.poll_id = p.id)
+ AND NOT EXISTS (
+ SELECT 1 FROM options o
+ WHERE o.poll_id = p.id
+ AND o.start_time + (CASE WHEN o.duration_minutes = 0
+ THEN interval '24 hours'
+ ELSE make_interval(mins => o.duration_minutes) END) > (now() AT TIME ZONE 'UTC')
+ )
+ RETURNING p.id
+ `;
+
+ await recordPollActivities(
+ tx,
+ closed.map(({ id }) => ({
+ pollId: id,
+ type: "poll_closed" as const,
+ userId: null,
+ payload: { reason: "auto" as const },
+ })),
+ );
+
+ return closed.length;
+ },
+ // The UPDATE scans every open poll's options, which can outlast Prisma's
+ // 5s default on large instances or after cron downtime.
+ { timeout: 30_000 },
+ );
}
const REMOVE_DELETED_POLLS_BATCH_SIZE = 100;
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index d4bd70dfb..bc2dbc315 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -9,6 +9,7 @@ import { after } from "next/server";
import * as z from "zod";
import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";
import { moderateContent } from "@/features/moderation/mutations";
+import { recordPollActivities } from "@/features/poll/activity/mutations";
import {
canUserManagePoll,
getPolls,
@@ -184,33 +185,46 @@ export const polls = router({
const kind = isTimePoll ? "time" : "date";
- const poll = await prisma.poll.create({
- include: {
- options: {
- select: {
- id: true,
+ const poll = await prisma.$transaction(async (tx) => {
+ const poll = await tx.poll.create({
+ include: {
+ options: {
+ select: {
+ id: true,
+ },
},
},
- },
- data: {
- id: pollId,
- title,
- timeZone,
- location,
- description,
- userId: ctx.user.id,
- kind,
- options: {
- createMany: {
- data: optionsData,
+ data: {
+ id: pollId,
+ title,
+ timeZone,
+ location,
+ description,
+ userId: ctx.user.id,
+ kind,
+ options: {
+ createMany: {
+ data: optionsData,
+ },
},
+ hideParticipants: input.hideParticipants,
+ disableComments: input.disableComments,
+ hideScores: input.hideScores,
+ requireParticipantEmail: input.requireParticipantEmail,
+ spaceId,
},
- hideParticipants: input.hideParticipants,
- disableComments: input.disableComments,
- hideScores: input.hideScores,
- requireParticipantEmail: input.requireParticipantEmail,
- spaceId,
- },
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "poll_created",
+ userId: ctx.user.id,
+ payload: { title },
+ },
+ ]);
+
+ return poll;
});
const pollLink = absoluteUrl(`/poll/${pollId}`);
@@ -377,33 +391,73 @@ export const polls = router({
}
}) ?? [];
+ // Prior persisted values, read before the update so poll_updated is
+ // recorded only when a detail or setting actually changes (the edit
+ // forms always send some fields, e.g. timeZone on option-only edits).
+ const prior = await tx.poll.findUnique({
+ where: { id: pollId },
+ select: {
+ title: true,
+ location: true,
+ description: true,
+ timeZone: true,
+ hideParticipants: true,
+ hideScores: true,
+ disableComments: true,
+ requireParticipantEmail: true,
+ },
+ });
+
+ if (!prior) {
+ throw new TRPCError({ code: "NOT_FOUND" });
+ }
+
// Reopen an auto-closed poll when new future dates are added. Manually
- // closed polls stay closed — that was the organizer's decision.
- let reopen = false;
+ // closed polls stay closed — that was the organizer's decision. The
+ // transition is conditional so concurrent modifies can't both record
+ // a poll_reopened event.
+ let reopened = false;
if (newOptions.some(optionEndsInFuture)) {
- const poll = await tx.poll.findUnique({
- where: { id: pollId },
- select: { status: true, closedReason: true },
+ const { count } = await tx.poll.updateMany({
+ where: { id: pollId, status: "closed", closedReason: "auto" },
+ data: { status: "open", closedReason: null },
});
- reopen = poll?.status === "closed" && poll.closedReason === "auto";
+ reopened = count === 1;
}
- if (input.optionsToDelete && input.optionsToDelete.length > 0) {
+ // Snapshot before the delete: option_deleted events carry the dates
+ // they removed, since the rows are gone once the activity renders.
+ const deletedOptions =
+ input.optionsToDelete && input.optionsToDelete.length > 0
+ ? await tx.option.findMany({
+ where: {
+ pollId,
+ id: {
+ in: input.optionsToDelete,
+ },
+ },
+ select: { id: true, startTime: true, duration: true },
+ })
+ : [];
+
+ if (deletedOptions.length > 0) {
await tx.option.deleteMany({
where: {
pollId,
id: {
- in: input.optionsToDelete,
+ in: deletedOptions.map((option) => option.id),
},
},
});
}
- if (newOptions.length > 0) {
- await tx.option.createMany({
- data: newOptions,
- });
- }
+ const addedOptions =
+ newOptions.length > 0
+ ? await tx.option.createManyAndReturn({
+ data: newOptions,
+ select: { id: true, startTime: true, duration: true },
+ })
+ : [];
const remainingOptions = await tx.option.count({ where: { pollId } });
if (remainingOptions === 0) {
@@ -436,9 +490,78 @@ export const polls = router({
disableComments: input.disableComments,
requireParticipantEmail: input.requireParticipantEmail,
kind,
- ...(reopen ? { status: "open" as const, closedReason: null } : {}),
},
});
+
+ // The effective persisted timeZone: forced null for date-only polls,
+ // untouched when the input omits it.
+ const nextTimeZone =
+ kind === "time"
+ ? input.timeZone === undefined
+ ? prior.timeZone
+ : input.timeZone
+ : null;
+
+ // Empty strings and null are the same absent value to the reader, so
+ // normalize before comparing.
+ const detailsOrSettingsChanged =
+ (input.title !== undefined && input.title !== prior.title) ||
+ (input.location !== undefined &&
+ (input.location || null) !== (prior.location || null)) ||
+ (input.description !== undefined &&
+ (input.description || null) !== (prior.description || null)) ||
+ nextTimeZone !== prior.timeZone ||
+ (input.hideParticipants !== undefined &&
+ input.hideParticipants !== prior.hideParticipants) ||
+ (input.disableComments !== undefined &&
+ input.disableComments !== prior.disableComments) ||
+ (input.hideScores !== undefined &&
+ input.hideScores !== prior.hideScores) ||
+ (input.requireParticipantEmail !== undefined &&
+ input.requireParticipantEmail !== prior.requireParticipantEmail);
+
+ await recordPollActivities(tx, [
+ ...deletedOptions.map((option) => ({
+ pollId,
+ type: "option_deleted" as const,
+ userId: ctx.user.id,
+ optionId: option.id,
+ payload: {
+ start: option.startTime.toISOString(),
+ duration: option.duration,
+ },
+ })),
+ ...addedOptions.map((option) => ({
+ pollId,
+ type: "option_added" as const,
+ userId: ctx.user.id,
+ optionId: option.id,
+ payload: {
+ start: option.startTime.toISOString(),
+ duration: option.duration,
+ },
+ })),
+ ...(detailsOrSettingsChanged
+ ? [
+ {
+ pollId,
+ type: "poll_updated" as const,
+ userId: ctx.user.id,
+ payload: {},
+ },
+ ]
+ : []),
+ ...(reopened
+ ? [
+ {
+ pollId,
+ type: "poll_reopened" as const,
+ userId: ctx.user.id,
+ payload: {},
+ },
+ ]
+ : []),
+ ]);
});
// Get updated poll data for group update
@@ -812,9 +935,13 @@ export const polls = router({
}
// create event in database
- const option = await prisma.option.findUnique({
+ const option = await prisma.option.findFirst({
where: {
id: input.optionId,
+ // Admin access was proven for input.pollId, so the option must
+ // belong to that poll — an unscoped lookup would let an admin
+ // schedule one poll with another poll's option.
+ pollId: input.pollId,
},
select: {
startTime: true,
@@ -949,6 +1076,19 @@ export const polls = router({
},
});
+ await recordPollActivities(tx, [
+ {
+ pollId: poll.id,
+ type: "poll_scheduled",
+ userId: ctx.user.id,
+ optionId: input.optionId,
+ payload: {
+ start: option.startTime.toISOString(),
+ duration: option.duration,
+ },
+ },
+ ]);
+
return event;
});
@@ -1108,10 +1248,14 @@ export const polls = router({
});
}
- await prisma.$transaction(async () => {
- const poll = await prisma.poll.update({
+ await prisma.$transaction(async (tx) => {
+ // Conditional transition: only the call that actually flips the
+ // status appends a lifecycle event, so repeated or concurrent calls
+ // can't record a reopen that didn't happen.
+ const { count } = await tx.poll.updateMany({
where: {
id: input.pollId,
+ status: { not: "open" },
},
data: {
status: "open",
@@ -1119,13 +1263,33 @@ export const polls = router({
},
});
- if (poll.scheduledEventId) {
- await prisma.scheduledEvent.delete({
+ if (count === 0) {
+ return;
+ }
+
+ const poll = await tx.poll.findUnique({
+ where: {
+ id: input.pollId,
+ },
+ select: { scheduledEventId: true },
+ });
+
+ if (poll?.scheduledEventId) {
+ await tx.scheduledEvent.delete({
where: {
id: poll.scheduledEventId,
},
});
}
+
+ await recordPollActivities(tx, [
+ {
+ pollId: input.pollId,
+ type: "poll_reopened",
+ userId: ctx.user.id,
+ payload: {},
+ },
+ ]);
});
track(
@@ -1155,14 +1319,35 @@ export const polls = router({
});
}
- await prisma.poll.update({
- where: {
- id: input.pollId,
- },
- data: {
- status: "closed",
- closedReason: "manual",
- },
+ await prisma.$transaction(async (tx) => {
+ // Conditional transition, matching closePoll in features/poll/
+ // mutations: an already-closed poll keeps its closedReason (so an
+ // auto-close stays "auto"), and only the call that actually flips
+ // the status appends a lifecycle event — repeated or concurrent
+ // calls can't record a close that didn't happen.
+ const { count } = await tx.poll.updateMany({
+ where: {
+ id: input.pollId,
+ status: { not: "closed" },
+ },
+ data: {
+ status: "closed",
+ closedReason: "manual",
+ },
+ });
+
+ if (count === 0) {
+ return;
+ }
+
+ await recordPollActivities(tx, [
+ {
+ pollId: input.pollId,
+ type: "poll_closed",
+ userId: ctx.user.id,
+ payload: { reason: "manual" },
+ },
+ ]);
});
track(
@@ -1219,27 +1404,40 @@ export const polls = router({
throw new TRPCError({ code: "NOT_FOUND", message: "Poll not found" });
}
- const newPoll = await prisma.poll.create({
- select: {
- id: true,
- },
- data: {
- id: nanoid(),
- title: input.newTitle,
- userId: ctx.user.id,
- timeZone: poll.timeZone,
- location: poll.location,
- spaceId: poll.spaceId,
- requireParticipantEmail: poll.requireParticipantEmail,
- description: poll.description,
- hideParticipants: poll.hideParticipants,
- hideScores: poll.hideScores,
- disableComments: poll.disableComments,
- kind: poll.kind,
- options: {
- create: poll.options,
+ const newPoll = await prisma.$transaction(async (tx) => {
+ const newPoll = await tx.poll.create({
+ select: {
+ id: true,
},
- },
+ data: {
+ id: nanoid(),
+ title: input.newTitle,
+ userId: ctx.user.id,
+ timeZone: poll.timeZone,
+ location: poll.location,
+ spaceId: poll.spaceId,
+ requireParticipantEmail: poll.requireParticipantEmail,
+ description: poll.description,
+ hideParticipants: poll.hideParticipants,
+ hideScores: poll.hideScores,
+ disableComments: poll.disableComments,
+ kind: poll.kind,
+ options: {
+ create: poll.options,
+ },
+ },
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId: newPoll.id,
+ type: "poll_created",
+ userId: ctx.user.id,
+ payload: { title: input.newTitle },
+ },
+ ]);
+
+ return newPoll;
});
return newPoll;
diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.ts
index bd8645f7a..0e17471a2 100644
--- a/apps/web/src/trpc/routers/polls/participants.ts
+++ b/apps/web/src/trpc/routers/polls/participants.ts
@@ -9,6 +9,7 @@ import { after } from "next/server";
import * as z from "zod";
import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";
import { getNotificationRecipient } from "@/features/notifications/data";
+import { recordPollActivities } from "@/features/poll/activity/mutations";
import { hasPollAdminAccess } from "@/features/poll/data";
import { AppError } from "@/lib/errors/app-error";
import { track } from "@/lib/posthog";
@@ -222,14 +223,52 @@ export const participants = router({
const participant = await canModifyParticipant(participantId, actor.id);
- await prisma.participant.update({
- where: {
- id: participantId,
- },
- data: {
- deleted: true,
- deletedAt: new Date(),
- },
+ await prisma.$transaction(async (tx) => {
+ // Snapshot before the delete: the activity payload is the historical
+ // record of the removed response, so it carries the name and votes.
+ const snapshot = await tx.participant.findUniqueOrThrow({
+ where: { id: participantId },
+ select: {
+ name: true,
+ votes: {
+ select: {
+ optionId: true,
+ type: true,
+ option: {
+ select: { startTime: true, duration: true },
+ },
+ },
+ },
+ },
+ });
+
+ await tx.participant.update({
+ where: {
+ id: participantId,
+ },
+ data: {
+ deleted: true,
+ deletedAt: new Date(),
+ },
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId: participant.pollId,
+ type: "response_deleted",
+ userId: actor.id,
+ participantId,
+ payload: {
+ name: snapshot.name,
+ votes: snapshot.votes.map((vote) => ({
+ optionId: vote.optionId,
+ start: vote.option.startTime.toISOString(),
+ duration: vote.option.duration,
+ type: vote.type,
+ })),
+ },
+ },
+ ]);
});
track(
@@ -301,54 +340,68 @@ export const participants = router({
existingOptionIds.has(optionId),
);
- const participant = await prisma.participant.create({
- data: {
- pollId: pollId,
- name: name,
- email,
- note,
- timeZone,
- userId: ctx.user.id,
- locale: ctx.locale,
- votes: {
- createMany: {
- data: validVotes.map(({ optionId, type }) => ({
- pollId,
- optionId,
- type,
- })),
+ const participant = await prisma.$transaction(async (tx) => {
+ const participant = await tx.participant.create({
+ data: {
+ pollId: pollId,
+ name: name,
+ email,
+ note,
+ timeZone,
+ userId: ctx.user.id,
+ locale: ctx.locale,
+ votes: {
+ createMany: {
+ data: validVotes.map(({ optionId, type }) => ({
+ pollId,
+ optionId,
+ type,
+ })),
+ },
},
},
- },
- include: {
- votes: {
- select: {
- optionId: true,
- type: true,
+ include: {
+ votes: {
+ select: {
+ optionId: true,
+ type: true,
+ },
},
- },
- user: {
- select: {
- image: true,
+ user: {
+ select: {
+ image: true,
+ },
},
- },
- poll: {
- select: {
- id: true,
- title: true,
- space: {
- select: {
- id: true,
- tier: true,
- showBranding: true,
- hideAttribution: true,
- primaryColor: true,
- image: true,
+ poll: {
+ select: {
+ id: true,
+ title: true,
+ space: {
+ select: {
+ id: true,
+ tier: true,
+ showBranding: true,
+ hideAttribution: true,
+ primaryColor: true,
+ image: true,
+ },
},
},
},
},
- },
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "response_created",
+ userId: ctx.user.id,
+ participantId: participant.id,
+ payload: { name: participant.name },
+ },
+ ]);
+
+ return participant;
});
const totalResponses = participantCount + 1;
@@ -422,16 +475,28 @@ export const participants = router({
.mutation(async ({ input: { participantId, newName, token }, ctx }) => {
const { id: userId } = await resolveActor(token, ctx.user);
- await canModifyParticipant(participantId, userId);
+ const participant = await canModifyParticipant(participantId, userId);
- await prisma.participant.update({
- where: {
- id: participantId,
- },
- data: {
- name: newName,
- },
- select: null,
+ await prisma.$transaction(async (tx) => {
+ await tx.participant.update({
+ where: {
+ id: participantId,
+ },
+ data: {
+ name: newName,
+ },
+ select: null,
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId: participant.pollId,
+ type: "response_updated",
+ userId,
+ participantId,
+ payload: { name: newName },
+ },
+ ]);
});
}),
update: publicProcedure
@@ -494,7 +559,7 @@ export const participants = router({
// 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({
+ const updatedParticipant = await tx.participant.update({
where: {
id: participantId,
},
@@ -513,6 +578,18 @@ export const participants = router({
},
},
});
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "response_updated",
+ userId: actor.id,
+ participantId,
+ payload: { name: updatedParticipant.name },
+ },
+ ]);
+
+ return updatedParticipant;
});
track(