Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Deliver the full poll lifecycle as webhook events (#3338)
Luke Vella1002c03521b8
diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.tsindex 2fbffee1f..ddceb1d94 100644--- a/apps/web/src/app/api/v1/schemas.ts+++ b/apps/web/src/app/api/v1/schemas.ts@@ -7,8 +7,14 @@ import { timezoneSchema } from "@/lib/utils/timezone-schema";// owns them: the dispatcher builds exactly these shapes.export {pollClosedEventSchema,+ pollCreatedEventSchema,+ pollDeletedEventSchema,+ pollParticipantCreatedEventSchema,+ pollParticipantDeletedEventSchema,+ pollParticipantUpdatedEventSchema,pollReopenedEventSchema,pollScheduledEventSchema,+ pollUpdatedEventSchema,webhookEventSchema,webhookEventTypeSchema,} from "@/features/webhook/schema";diff --git a/apps/web/src/features/poll/activity/schema.ts b/apps/web/src/features/poll/activity/schema.tsindex 25c7f83bf..a9ea03627 100644--- a/apps/web/src/features/poll/activity/schema.ts+++ b/apps/web/src/features/poll/activity/schema.ts@@ -54,6 +54,11 @@ export const pollActivitySchema = z.discriminatedUnion("type", [...actor,payload: z.object({}),}),+ z.object({+ type: z.literal("poll_deleted"),+ ...actor,+ payload: z.object({}),+ }),z.object({type: z.literal("poll_scheduled"),...actor,diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.tsindex 1dca9f1ea..4774fdb8c 100644--- a/apps/web/src/features/poll/mutations.ts+++ b/apps/web/src/features/poll/mutations.ts@@ -214,25 +214,24 @@ export const deletePoll = async (pollId: string,spaceId: AuthorizedSpaceId,) => {- const poll = await prisma.poll.findFirst({- where: {- id: pollId,- spaceId,- deletedAt: null,- },- select: { id: true },- });+ return prisma.$transaction(async (tx) => {+ // Conditional so two concurrent deletes record one transition, not two.+ const { count } = await tx.poll.updateMany({+ where: { id: pollId, spaceId, deletedAt: null },+ data: { deleted: true, deletedAt: new Date() },+ });- if (!poll) {- return null;- }+ if (count === 0) {+ return null;+ }- await prisma.poll.update({- where: { id: pollId },- data: { deleted: true, deletedAt: new Date() },- });+ // API keys are space credentials, not a person, so the actor is unknown.+ await recordPollActivities(tx, [+ { pollId, type: "poll_deleted", userId: null, payload: {} },+ ]);- return { id: pollId };+ return { id: pollId };+ });};/**diff --git a/apps/web/src/features/webhook/data.ts b/apps/web/src/features/webhook/data.tsindex d305a8885..54090778c 100644--- a/apps/web/src/features/webhook/data.ts+++ b/apps/web/src/features/webhook/data.ts@@ -82,10 +82,12 @@ export async function listEnabledWebhooks() {}/**- * Status transition activities in a space's polls after the `(createdAt, id)`- * keyset and up to `until`, oldest first. Keyset rather than offset so a run- * of equal timestamps larger than one page still advances. Deleted polls are- * excluded: their links no longer resolve and the poll is on its way out.+ * Webhook activities in a space's polls after the `(createdAt, id)` keyset+ * and up to `until`, oldest first. Keyset rather than offset so a run of+ * equal timestamps larger than one page still advances. Deleted polls are+ * not filtered out: `poll_deleted` is written in the same transaction as the+ * soft delete, and anything recorded just before it happened and is still+ * worth telling.*/export async function listWebhookActivities({spaceId,@@ -108,15 +110,16 @@ export async function listWebhookActivities({{ createdAt: after.createdAt, id: { gt: after.id } },]: [{ createdAt: { gt: after.createdAt } }],- poll: { spaceId, deleted: false },+ poll: { spaceId },},select: {id: true,type: true,+ participantId: true,optionId: true,payload: true,createdAt: true,- poll: { select: { id: true, title: true, kind: true, timeZone: true } },+ poll: { select: { id: true, kind: true } },},orderBy: [{ createdAt: "asc" }, { id: "asc" }],take: limit,diff --git a/apps/web/src/features/webhook/schema.ts b/apps/web/src/features/webhook/schema.tsindex b36eb2ef4..d258acc17 100644--- a/apps/web/src/features/webhook/schema.ts+++ b/apps/web/src/features/webhook/schema.ts@@ -4,10 +4,20 @@ import { WEBHOOK_VERSION } from "./constants";import { getWebhookUrlRejection } from "./utils";export const webhookEventTypeSchema = z- .enum(["poll.closed", "poll.reopened", "poll.scheduled"])+ .enum([+ "poll.created",+ "poll.updated",+ "poll.closed",+ "poll.reopened",+ "poll.scheduled",+ "poll.deleted",+ "poll.participant.created",+ "poll.participant.updated",+ "poll.participant.deleted",+ ]).meta({id: "WebhookEventType",- description: "The poll lifecycle transition the event records.",+ description: "The poll or participant change the event records.",example: "poll.closed",});@@ -15,25 +25,62 @@ export type WebhookEventType = z.infer<typeof webhookEventTypeSchema>;export const WEBHOOK_EVENT_TYPES = webhookEventTypeSchema.options;-const webhookPollSchema = (status: "open" | "closed" | "scheduled") =>- z- .object({- id: z.string().meta({ example: "Xk3pQ9vLm2Ab" }),- title: z.string().meta({ example: "Team sync" }),- status: z.literal(status).meta({- description:- "The status the transition moved the poll to. Reflects this event, not the poll's current state: a later transition arrives as its own event.",- }),- kind: z.enum(["date", "time"]).meta({ example: "time" }),- timeZone: z.string().nullable().meta({ example: "Europe/London" }),- adminUrl: z- .string()- .meta({ example: "https://app.rallly.co/poll/Xk3pQ9vLm2Ab" }),- inviteUrl: z- .string()- .meta({ example: "https://rallly.co/invite/Xk3pQ9vLm2Ab" }),- })- .meta({ id: `WebhookPoll${status[0]?.toUpperCase()}${status.slice(1)}` });+/**+ * Events reference the poll, they do not describe it: every other poll+ * field is either derivable, or mutable and stale by the time a retry lands,+ * and `GET /polls/{pollId}` returns the current truth in one call. The+ * participant is carried in full for the opposite reason: nothing in the+ * API returns a participant's availability.+ */+export const webhookPollRefSchema = z+ .object({+ id: z.string().meta({+ description:+ "The poll's id. Fetch `GET /polls/{pollId}` for its title, options, settings and current status.",+ example: "Xk3pQ9vLm2Ab",+ }),+ })+ .meta({ id: "WebhookPollRef" });++/**+ * The span of time a poll was scheduled as. There is no option id and no+ * poll `kind`: the span is the fact, and `allDay` says all a receiver needs+ * about its kind.+ */+const timeRangeFields = {+ start: z.iso.datetime().meta({+ description: "Start of the span, inclusive, as a UTC instant.",+ example: "2025-01-15T09:00:00.000Z",+ }),+ end: z.iso.datetime().meta({+ description:+ "End of the span, exclusive, as a UTC instant: a 30 minute slot starting at 09:00 ends at 09:30, and the instant 09:30 is not in it.",+ example: "2025-01-15T09:30:00.000Z",+ }),+ allDay: z.boolean().meta({+ description:+ "True for a whole calendar day. The day is a floating date with no timezone, given as `start` at 00:00:00Z on that date and `end` at 00:00:00Z on the next; read the date from `start` and ignore the time of day.",+ example: false,+ }),+};++export const webhookScheduledEventSchema = z+ .object(timeRangeFields)+ .meta({ id: "WebhookScheduledEvent" });++/**+ * Events reference the participant the same way they reference the poll:+ * by id. Fetch `GET /polls/{pollId}/participants` for the rest.+ */+export const webhookParticipantRefSchema = z+ .object({+ id: z.string().meta({+ description:+ "The participant's id. Fetch `GET /polls/{pollId}/participants` for their details. After `poll.participant.deleted` the participant is no longer listed.",+ example: "cm5h8x2k40000q9l4f7e2d3an",+ }),+ })+ .meta({ id: "WebhookParticipantRef" });const envelope = {version: z.string().meta({@@ -52,61 +99,138 @@ const envelope = {}),};+export const pollCreatedEventSchema = z+ .object({+ ...envelope,+ type: z.literal("poll.created"),+ data: z.object({ poll: webhookPollRefSchema }),+ })+ .meta({+ id: "PollCreatedEvent",+ description:+ "A poll was created in the space, from the app or the API. It starts open.",+ });++export const pollUpdatedEventSchema = z+ .object({+ ...envelope,+ type: z.literal("poll.updated"),+ data: z.object({ poll: webhookPollRefSchema }),+ })+ .meta({+ id: "PollUpdatedEvent",+ description:+ "The poll's details, options or settings changed. The event says that something changed, not what: fetch the poll for its current state.",+ });+export const pollClosedEventSchema = z.object({...envelope,type: z.literal("poll.closed"),data: z.object({- poll: webhookPollSchema("closed"),+ poll: webhookPollRefSchema,reason: pollClosedReasonSchema.meta({description:"`manual` when the organizer closed the poll, `auto` when it closed because every option had passed.",}),}),})- .meta({ id: "PollClosedEvent" });+ .meta({+ id: "PollClosedEvent",+ description:+ "The poll stopped accepting responses, either because the organizer closed it or because every option had passed. Reopening arrives as `poll.reopened`; scheduling arrives as `poll.scheduled`, not as a close.",+ });export const pollReopenedEventSchema = z.object({...envelope,type: z.literal("poll.reopened"),- data: z.object({ poll: webhookPollSchema("open") }),+ data: z.object({ poll: webhookPollRefSchema }),})- .meta({ id: "PollReopenedEvent" });+ .meta({+ id: "PollReopenedEvent",+ description: "A closed poll accepts responses again.",+ });export const pollScheduledEventSchema = z.object({...envelope,type: z.literal("poll.scheduled"),data: z.object({- poll: webhookPollSchema("scheduled"),- option: z- .union([- z.object({- id: z.string().meta({ example: "cm5h8x2k40000q9l4f7e2d3an" }),- date: z.iso.date().meta({ example: "2025-01-15" }),- }),- z.object({- id: z.string().meta({ example: "cm5h8x2k40000q9l4f7e2d3an" }),- startTime: z.iso- .datetime()- .meta({ example: "2025-01-15T09:00:00.000Z" }),- duration: z.int().positive().meta({ example: 30 }),- }),- ])- .meta({- description:- "The option the poll was scheduled on. Its shape follows the poll's `kind`: a date for `date` polls, a start time and duration for `time` polls.",- }),+ poll: webhookPollRefSchema,+ event: webhookScheduledEventSchema.meta({+ description: "The calendar event the poll was scheduled as.",+ }),}),})- .meta({ id: "PollScheduledEvent" });+ .meta({+ id: "PollScheduledEvent",+ description:+ "The organizer picked a time. The poll stops accepting responses and `data.event` is the span that was chosen.",+ });++export const pollDeletedEventSchema = z+ .object({+ ...envelope,+ type: z.literal("poll.deleted"),+ data: z.object({ poll: webhookPollRefSchema }),+ })+ .meta({+ id: "PollDeletedEvent",+ description:+ "The poll was deleted. `GET /polls/{pollId}` returns 404 from now on, so anything you need about it must already be stored.",+ });++const participantEventData = z.object({+ poll: webhookPollRefSchema,+ participant: webhookParticipantRefSchema,+});++export const pollParticipantCreatedEventSchema = z+ .object({+ ...envelope,+ type: z.literal("poll.participant.created"),+ data: participantEventData,+ })+ .meta({+ id: "PollParticipantCreatedEvent",+ description: "Someone responded to the poll.",+ });++export const pollParticipantUpdatedEventSchema = z+ .object({+ ...envelope,+ type: z.literal("poll.participant.updated"),+ data: participantEventData,+ })+ .meta({+ id: "PollParticipantUpdatedEvent",+ description: "The participant changed their response or their name.",+ });++export const pollParticipantDeletedEventSchema = z+ .object({+ ...envelope,+ type: z.literal("poll.participant.deleted"),+ data: participantEventData,+ })+ .meta({+ id: "PollParticipantDeletedEvent",+ description:+ "A response was removed, by the participant or the organizer. `data.participant` is a reference to the removed response; fetching it returns 404.",+ });export const webhookEventSchema = z.discriminatedUnion("type", [+ pollCreatedEventSchema,+ pollUpdatedEventSchema,pollClosedEventSchema,pollReopenedEventSchema,pollScheduledEventSchema,+ pollDeletedEventSchema,+ pollParticipantCreatedEventSchema,+ pollParticipantUpdatedEventSchema,+ pollParticipantDeletedEventSchema,]).meta({ id: "WebhookEvent" });diff --git a/apps/web/src/features/webhook/utils.test.ts b/apps/web/src/features/webhook/utils.test.tsindex 82597f348..434e23ded 100644--- a/apps/web/src/features/webhook/utils.test.ts+++ b/apps/web/src/features/webhook/utils.test.ts@@ -46,32 +46,43 @@ describe("getRetryDelayMs", () => {});describe("toWebhookEventType", () => {- it("maps status transition activities to their event names", () => {+ it("maps poll lifecycle activities to their event names", () => {+ expect(toWebhookEventType("poll_created")).toBe("poll.created");+ expect(toWebhookEventType("poll_updated")).toBe("poll.updated");expect(toWebhookEventType("poll_closed")).toBe("poll.closed");expect(toWebhookEventType("poll_reopened")).toBe("poll.reopened");expect(toWebhookEventType("poll_scheduled")).toBe("poll.scheduled");+ expect(toWebhookEventType("poll_deleted")).toBe("poll.deleted");+ });++ it("files response activities under the poll resource", () => {+ expect(toWebhookEventType("response_created")).toBe(+ "poll.participant.created",+ );+ expect(toWebhookEventType("response_updated")).toBe(+ "poll.participant.updated",+ );+ expect(toWebhookEventType("response_deleted")).toBe(+ "poll.participant.deleted",+ );});it("returns null for activities that are not webhook events", () => {- expect(toWebhookEventType("response_created")).toBeNull();- expect(toWebhookEventType("poll_created")).toBeNull();+ expect(toWebhookEventType("invite_sent")).toBeNull();+ expect(toWebhookEventType("option_added")).toBeNull();});});describe("buildWebhookPayload", () => {- const poll = {- id: "Xk3pQ9vLm2Ab",- title: "Team sync",- kind: "time" as const,- timeZone: "Europe/London",- };+ const poll = { id: "Xk3pQ9vLm2Ab", kind: "time" as const };const createdAt = new Date("2026-09-15T10:00:00.000Z");- it("derives the status from the event, not the live poll", () => {+ it("references the poll by id and carries the event's own facts", () => {const payload = buildWebhookPayload({activity: {id: "act_1",type: "poll_closed",+ participantId: null,optionId: null,payload: { reason: "manual" },createdAt,@@ -79,30 +90,21 @@ describe("buildWebhookPayload", () => {poll,});- expect(payload).toMatchObject({+ expect(payload).toEqual({+ version: expect.any(String),id: "act_1",type: "poll.closed",createdAt: "2026-09-15T10:00:00.000Z",- data: {- poll: {- id: "Xk3pQ9vLm2Ab",- title: "Team sync",- status: "closed",- kind: "time",- timeZone: "Europe/London",- },- reason: "manual",- },+ data: { poll: { id: "Xk3pQ9vLm2Ab" }, reason: "manual" },});- expect(payload?.data.poll.adminUrl).toMatch(/\/poll\/Xk3pQ9vLm2Ab$/);- expect(payload?.data.poll.inviteUrl).toMatch(/\/invite\/Xk3pQ9vLm2Ab$/);});- it("marks a reopened poll as open", () => {+ it("builds a reopened poll", () => {const payload = buildWebhookPayload({activity: {id: "act_2",type: "poll_reopened",+ participantId: null,optionId: null,payload: {},createdAt,@@ -111,7 +113,7 @@ describe("buildWebhookPayload", () => {});expect(payload?.type).toBe("poll.reopened");- expect(payload?.data.poll.status).toBe("open");+ expect(payload?.data).toEqual({ poll: { id: "Xk3pQ9vLm2Ab" } });});it("carries the scheduled slot for a time poll", () => {@@ -119,6 +121,7 @@ describe("buildWebhookPayload", () => {activity: {id: "act_3",type: "poll_scheduled",+ participantId: null,optionId: "opt_1",payload: { start: "2026-10-01T09:00:00.000Z", duration: 30 },createdAt,@@ -129,21 +132,22 @@ describe("buildWebhookPayload", () => {expect(payload).toMatchObject({type: "poll.scheduled",data: {- poll: { status: "scheduled" },- option: {- id: "opt_1",- startTime: "2026-10-01T09:00:00.000Z",- duration: 30,+ poll: { id: "Xk3pQ9vLm2Ab" },+ event: {+ start: "2026-10-01T09:00:00.000Z",+ end: "2026-10-01T09:30:00.000Z",+ allDay: false,},},});});- it("carries the scheduled date for a date poll", () => {+ it("spans the whole day for a scheduled date poll", () => {const payload = buildWebhookPayload({activity: {id: "act_4",type: "poll_scheduled",+ participantId: null,optionId: "opt_2",payload: { start: "2026-10-01T00:00:00.000Z", duration: 0 },createdAt,@@ -152,16 +156,69 @@ describe("buildWebhookPayload", () => {});expect(payload?.data).toMatchObject({- option: { id: "opt_2", date: "2026-10-01" },+ event: {+ start: "2026-10-01T00:00:00.000Z",+ end: "2026-10-02T00:00:00.000Z",+ allDay: true,+ },});});- it("returns null for activities that are not webhook events", () => {+ it.each([+ ["poll_created", "poll.created", { title: "Team sync" }],+ ["poll_updated", "poll.updated", {}],+ ["poll_deleted", "poll.deleted", {}],+ ] as const)("builds %s as a bare reference to the poll", (type, eventType, activityPayload) => {+ const payload = buildWebhookPayload({+ activity: {+ id: "act_8",+ type,+ participantId: null,+ optionId: null,+ payload: activityPayload,+ createdAt,+ },+ poll,+ });++ expect(payload?.type).toBe(eventType);+ expect(payload?.data).toEqual({ poll: { id: poll.id } });+ });++ it.each([+ ["response_created", "poll.participant.created"],+ ["response_updated", "poll.participant.updated"],+ ["response_deleted", "poll.participant.deleted"],+ ] as const)("builds %s from the response snapshot", (type, eventType) => {+ const payload = buildWebhookPayload({+ activity: {+ id: "act_9",+ type,+ participantId: "part_1",+ optionId: null,+ // response_deleted requires the vote snapshot; the others ignore it+ payload: { name: "Jessie", votes: [] },+ createdAt,+ },+ poll,+ });++ expect(payload).toEqual({+ version: expect.any(String),+ id: "act_9",+ createdAt: "2026-09-15T10:00:00.000Z",+ type: eventType,+ data: { poll: { id: poll.id }, participant: { id: "part_1" } },+ });+ });++ it("returns null when a response row lost its participant ref", () => {expect(buildWebhookPayload({activity: {- id: "act_5",+ id: "act_11",type: "response_created",+ participantId: null,optionId: null,payload: { name: "Jessie" },createdAt,@@ -171,12 +228,29 @@ describe("buildWebhookPayload", () => {).toBeNull();});+ it("returns null for activities that are not webhook events", () => {+ expect(+ buildWebhookPayload({+ activity: {+ id: "act_5",+ type: "invite_sent",+ participantId: null,+ optionId: null,+ payload: { email: "[email protected]" },+ createdAt,+ },+ poll,+ }),+ ).toBeNull();+ });+it("returns null when the activity payload is malformed", () => {expect(buildWebhookPayload({activity: {id: "act_6",type: "poll_scheduled",+ participantId: null,optionId: "opt_1",payload: {},createdAt,diff --git a/apps/web/src/features/webhook/utils.ts b/apps/web/src/features/webhook/utils.tsindex a77bbf719..9b7ce761b 100644--- a/apps/web/src/features/webhook/utils.ts+++ b/apps/web/src/features/webhook/utils.ts@@ -1,4 +1,3 @@-import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";import { pollActivitySchema } from "@/features/poll/activity/schema";import { RETRY_DELAYS_MS, WEBHOOK_VERSION } from "./constants";import type { WebhookEvent, WebhookEventType } from "./schema";@@ -78,10 +77,23 @@ export function getRetryDelayMs(attempts: number) {return RETRY_DELAYS_MS[attempts - 1] ?? null;}+/**+ * Activity type to public event name. The activity log is internal and its+ * `type` column carries history, so the mapping is the seam: an activity is+ * never renamed to match its event, and the event name is the contract.+ * Participant events take three segments so the picker, which groups on the+ * first, files them under the poll.+ */const ACTIVITY_EVENTS: Record<string, WebhookEventType> = {+ poll_created: "poll.created",+ poll_updated: "poll.updated",poll_closed: "poll.closed",poll_reopened: "poll.reopened",poll_scheduled: "poll.scheduled",+ poll_deleted: "poll.deleted",+ response_created: "poll.participant.created",+ response_updated: "poll.participant.updated",+ response_deleted: "poll.participant.deleted",};export const WEBHOOK_ACTIVITY_TYPES = Object.keys(ACTIVITY_EVENTS);@@ -90,24 +102,31 @@ export function toWebhookEventType(activityType: string) {return ACTIVITY_EVENTS[activityType] ?? null;}-// All-day options are stored as UTC midnight of the calendar date, so the-// date is the first ten characters of the ISO string.-function toOptionPayload(+const DAY_MS = 24 * 60 * 60 * 1000;+const MINUTE_MS = 60 * 1000;++/**+ * An option snapshot as a span of time. All-day options are stored as UTC+ * midnight with a zero duration, so they span their UTC day.+ */+function toTimeRange(kind: "date" | "time",- option: { id: string; start: string; duration: number },+ option: { start: string; duration: number },) {- if (kind === "date") {- return { id: option.id, date: option.start.slice(0, 10) };- }- return { id: option.id, startTime: option.start, duration: option.duration };+ const start = new Date(option.start);+ const allDay = kind === "date";+ const end = new Date(+ start.getTime() + (allDay ? DAY_MS : option.duration * MINUTE_MS),+ );+ return { start: start.toISOString(), end: end.toISOString(), allDay };}/**- * Builds the event envelope for an activity row. The poll's status comes from- * the transition the activity records, never from the live poll: by the time- * a delivery is retried the poll may have moved on, and each transition is- * its own event. Returns null for activities that are not webhook events or- * whose payload this version can't interpret.+ * Builds the event envelope for an activity row. The poll is referenced by+ * id only; everything else comes from the activity's own snapshot, so a+ * retried delivery says what happened, not what the poll looks like now.+ * Returns null for activities that are not webhook events or whose payload+ * this version can't interpret.*/export function buildWebhookPayload({activity,@@ -116,20 +135,22 @@ export function buildWebhookPayload({activity: {id: string;type: string;+ participantId: string | null;optionId: string | null;payload: unknown;createdAt: Date;};poll: {id: string;- title: string;kind: "date" | "time";- timeZone: string | null;};}): WebhookEvent | null {+ // Every subject ref the vocabulary can require is passed: a missing one+ // fails the parse and the event is dropped without a trace.const parsed = pollActivitySchema.safeParse({type: activity.type,userId: null,+ participantId: activity.participantId ?? undefined,optionId: activity.optionId ?? undefined,payload: activity.payload,});@@ -144,40 +165,74 @@ export function buildWebhookPayload({id: activity.id,createdAt: activity.createdAt.toISOString(),};- const pollPayload = (status: "open" | "closed" | "scheduled") => ({- id: poll.id,- title: poll.title,- status,- kind: poll.kind,- timeZone: poll.timeZone,- adminUrl: absoluteUrl(`/poll/${poll.id}`),- inviteUrl: shortUrl(`/invite/${poll.id}`),- });+ const pollRef = { id: poll.id };+ const participantRef = (participantId: string) => ({ id: participantId });switch (event.type) {+ case "poll_created":+ return {+ ...base,+ type: "poll.created",+ data: { poll: pollRef },+ };+ case "poll_updated":+ return {+ ...base,+ type: "poll.updated",+ data: { poll: pollRef },+ };+ case "poll_deleted":+ return {+ ...base,+ type: "poll.deleted",+ data: { poll: pollRef },+ };+ case "response_created":+ return {+ ...base,+ type: "poll.participant.created",+ data: {+ poll: pollRef,+ participant: participantRef(event.participantId),+ },+ };+ case "response_updated":+ return {+ ...base,+ type: "poll.participant.updated",+ data: {+ poll: pollRef,+ participant: participantRef(event.participantId),+ },+ };+ case "response_deleted":+ return {+ ...base,+ type: "poll.participant.deleted",+ data: {+ poll: pollRef,+ participant: participantRef(event.participantId),+ },+ };case "poll_closed":return {...base,type: "poll.closed",- data: { poll: pollPayload("closed"), reason: event.payload.reason },+ data: { poll: pollRef, reason: event.payload.reason },};case "poll_reopened":return {...base,type: "poll.reopened",- data: { poll: pollPayload("open") },+ data: { poll: pollRef },};case "poll_scheduled":return {...base,type: "poll.scheduled",data: {- poll: pollPayload("scheduled"),- option: toOptionPayload(poll.kind, {- id: event.optionId,- start: event.payload.start,- duration: event.payload.duration,- }),+ poll: pollRef,+ event: toTimeRange(poll.kind, event.payload),},};default:diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex 1477cd476..22ef41775 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -709,9 +709,23 @@ export const polls = router({});}- await prisma.poll.update({- where: { id: pollId },- data: { deleted: true, deletedAt: new Date() },+ await prisma.$transaction(async (tx) => {+ // Guarded so a repeated delete records one transition, not two.+ const { count } = await tx.poll.updateMany({+ where: { id: pollId, deleted: false },+ data: { deleted: true, deletedAt: new Date() },+ });+ if (count === 0) {+ return;+ }+ await recordPollActivities(tx, [+ {+ pollId,+ type: "poll_deleted",+ userId: ctx.user.id,+ payload: {},+ },+ ]);});// Track poll deletion analyticsdiff --git a/apps/web/tests/create-delete-poll.spec.ts b/apps/web/tests/create-delete-poll.spec.tsindex 2f2bc9286..00f61eb66 100644--- a/apps/web/tests/create-delete-poll.spec.ts+++ b/apps/web/tests/create-delete-poll.spec.ts@@ -1,10 +1,12 @@import type { Page } from "@playwright/test";import { expect, test } from "@playwright/test";+import { prisma } from "@rallly/database";import { deleteAllMessages } from "@rallly/test-helpers";import { NewPollPage } from "./new-poll-page";test.describe.serial(() => {let page: Page;+ let pollId: string;test.beforeAll(async ({ browser }) => {page = await browser.newPage();@@ -20,6 +22,8 @@ test.describe.serial(() => {await expect(page.getByRole("heading", { name: "Monthly Meetup" }),).toBeVisible();+ pollId = page.url().match(/\/poll\/([a-zA-Z0-9]+)/)?.[1] ?? "";+ expect(pollId).not.toBe("");});// delete the poll we just created@@ -38,5 +42,13 @@ test.describe.serial(() => {await expect(page).toHaveURL("/login?redirectTo=%2Fpolls", {timeout: 15_000,});++ // The soft delete records the transition the poll's webhooks are built+ // from.+ expect(+ await prisma.pollActivity.count({+ where: { pollId, type: "poll_deleted" },+ }),+ ).toBe(1);});});diff --git a/apps/web/tests/webhooks-settings.spec.ts b/apps/web/tests/webhooks-settings.spec.tsindex 511531f18..52001f3ae 100644--- a/apps/web/tests/webhooks-settings.spec.ts+++ b/apps/web/tests/webhooks-settings.spec.ts@@ -2,6 +2,7 @@ import type { Page } from "@playwright/test";import { expect, test } from "@playwright/test";import { prisma } from "@rallly/database";import { decrypt, encrypt } from "@rallly/utils/encryption";+import { WEBHOOK_EVENT_TYPES } from "@/features/webhook/schema";import {createUserInDb,loginWithEmail,@@ -113,11 +114,8 @@ test.describe("Webhooks settings", () => {});expect(webhook.url).toBe(url);expect(webhook.enabled).toBe(true);- expect(webhook.events.sort()).toEqual([- "poll.closed",- "poll.reopened",- "poll.scheduled",- ]);+ // The form starts with every event selected.+ expect([...webhook.events].sort()).toEqual([...WEBHOOK_EVENT_TYPES].sort());expect(decryptSecret(webhook.secret)).toBe(revealed);// Never replays history: a new endpoint starts at now.expect(webhook.cursor.getTime()).toBeGreaterThan(Date.now() - 60_000);@@ -127,7 +125,9 @@ test.describe("Webhooks settings", () => {const row = endpointRow(page, url);await expect(row).toBeVisible();// The row summarises the subscription rather than listing it.- await expect(row.getByText("3 events")).toBeVisible();+ await expect(+ row.getByText(`${WEBHOOK_EVENT_TYPES.length} events`),+ ).toBeVisible();// Closing the reveal is the only chance to copy it — reloading must not// surface the secret again.await page.reload();diff --git a/apps/web/tests/webhooks.spec.ts b/apps/web/tests/webhooks.spec.tsindex c35160b79..3f5533e36 100644--- a/apps/web/tests/webhooks.spec.ts+++ b/apps/web/tests/webhooks.spec.ts@@ -7,6 +7,7 @@ import { expect, test } from "@playwright/test";import { prisma } from "@rallly/database";import { encrypt } from "@rallly/utils/encryption";import { WEBHOOK_VERSION } from "@/features/webhook/constants";+import { WEBHOOK_EVENT_TYPES } from "@/features/webhook/schema";import { createUserInDb } from "./test-utils";/**@@ -90,11 +91,7 @@ test.describe("Webhook delivery", () => {spaceId,url: receiver.url,secret: encrypt(WEBHOOK_SECRET, SECRET_PASSWORD),- events: overrides.events ?? [- "poll.closed",- "poll.reopened",- "poll.scheduled",- ],+ events: overrides.events ?? [...WEBHOOK_EVENT_TYPES],cursor: secondsAgo(120),},});@@ -105,14 +102,16 @@ test.describe("Webhook delivery", () => {payload,createdAt,optionId,+ participantId,}: {type: string;payload: object;createdAt: Date;optionId?: string;+ participantId?: string;}) {return prisma.pollActivity.create({- data: { pollId, type, payload, createdAt, optionId },+ data: { pollId, type, payload, createdAt, optionId, participantId },});}@@ -148,6 +147,10 @@ test.describe("Webhook delivery", () => {receiver.status = 200;await prisma.spaceWebhook.deleteMany({ where: { spaceId } });await prisma.pollActivity.deleteMany({ where: { pollId } });+ await prisma.poll.update({+ where: { id: pollId },+ data: { status: "open", deleted: false, deletedAt: null },+ });});test.afterAll(async () => {@@ -166,8 +169,9 @@ test.describe("Webhook delivery", () => {});// Not a webhook event: must not produce a deliveryawait createActivity({- type: "response_created",- payload: { name: "Jessie" },+ type: "option_added",+ optionId: "webhook-delivery-option",+ payload: { start: "2026-10-01T09:00:00.000Z", duration: 30 },createdAt: secondsAgo(30),});@@ -189,16 +193,7 @@ test.describe("Webhook delivery", () => {id: activity.id,type: "poll.closed",createdAt: activity.createdAt.toISOString(),- data: {- poll: {- id: pollId,- title: "Webhook poll",- status: "closed",- kind: "time",- timeZone: "Europe/London",- },- reason: "manual",- },+ data: { poll: { id: pollId }, reason: "manual" },});const delivery = await prisma.webhookDelivery.findUniqueOrThrow({@@ -253,7 +248,7 @@ test.describe("Webhook delivery", () => {).toBe(0);});- test("carries the scheduled option for a scheduled poll", async ({+ test("carries the calendar event for a scheduled poll", async ({request,}) => {await createWebhook();@@ -270,16 +265,108 @@ test.describe("Webhook delivery", () => {expect(JSON.parse(receiver.requests[0]?.body ?? "{}")).toMatchObject({type: "poll.scheduled",data: {- poll: { status: "scheduled" },- option: {- id: "webhook-delivery-option",- startTime: "2026-10-01T09:00:00.000Z",- duration: 30,+ poll: { id: pollId },+ event: {+ start: "2026-10-01T09:00:00.000Z",+ end: "2026-10-01T09:30:00.000Z",+ allDay: false,},},});});+ test("delivers a created poll as open", async ({ request }) => {+ await createWebhook();+ await createActivity({+ type: "poll_created",+ payload: { title: "Webhook poll" },+ createdAt: secondsAgo(30),+ });++ await runCron(request);++ expect(receiver.requests).toHaveLength(1);+ expect(receiver.requests[0]?.headers["x-rallly-event"]).toBe(+ "poll.created",+ );+ expect(JSON.parse(receiver.requests[0]?.body ?? "{}")).toMatchObject({+ type: "poll.created",+ data: { poll: { id: pollId } },+ });+ });++ test("delivers an updated poll as a bare reference", async ({ request }) => {+ await createWebhook();+ await createActivity({+ type: "poll_updated",+ payload: {},+ createdAt: secondsAgo(30),+ });++ await runCron(request);++ expect(receiver.requests).toHaveLength(1);+ expect(JSON.parse(receiver.requests[0]?.body ?? "{}")).toMatchObject({+ type: "poll.updated",+ data: { poll: { id: pollId } },+ });+ });++ test("delivers a deleted poll although the poll row is soft deleted", async ({+ request,+ }) => {+ await createWebhook();+ await prisma.poll.update({+ where: { id: pollId },+ data: { deleted: true, deletedAt: new Date() },+ });+ await createActivity({+ type: "poll_deleted",+ payload: {},+ createdAt: secondsAgo(30),+ });++ const summary = await runCron(request);+ expect(summary.fannedOut).toBe(1);++ expect(receiver.requests).toHaveLength(1);+ expect(JSON.parse(receiver.requests[0]?.body ?? "{}")).toMatchObject({+ type: "poll.deleted",+ data: { poll: { id: pollId } },+ });+ });++ for (const [activityType, eventType] of [+ ["response_created", "poll.participant.created"],+ ["response_updated", "poll.participant.updated"],+ ["response_deleted", "poll.participant.deleted"],+ ] as const) {+ test(`delivers ${eventType} as a reference to the participant`, async ({+ request,+ }) => {+ await createWebhook();+ await createActivity({+ type: activityType,+ participantId: "webhook-delivery-participant",+ payload: { name: "Jessie", votes: [] },+ createdAt: secondsAgo(30),+ });++ const summary = await runCron(request);+ expect(summary.fannedOut).toBe(1);++ expect(receiver.requests).toHaveLength(1);+ expect(receiver.requests[0]?.headers["x-rallly-event"]).toBe(eventType);+ expect(JSON.parse(receiver.requests[0]?.body ?? "{}")).toMatchObject({+ type: eventType,+ data: {+ poll: { id: pollId },+ participant: { id: "webhook-delivery-participant" },+ },+ });+ });+ }+test("picks up an activity that committed behind the cursor", async ({request,}) => {