Skip to content

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

🚧 Add endpoints for fetching poll data (#2124)

Luke Vella40c11ce4da36
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.ts
index bff213680..4103d71b8 100644
--- a/apps/web/src/app/api/private/[...route]/route.test.ts
+++ b/apps/web/src/app/api/private/[...route]/route.test.ts
@@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mockDeletePoll = vi.fn();
+const mockCreatePoll = vi.fn();
vi.mock("@/features/poll/mutations", () => ({
deletePoll: (...args: unknown[]) => mockDeletePoll(...args),
+ createPoll: (...args: unknown[]) => mockCreatePoll(...args),
}));
vi.mock("@rallly/database", () => ({
@@ -21,6 +23,7 @@ vi.mock("@rallly/database", () => ({
},
poll: {
create: vi.fn(),
+ findFirst: vi.fn(),
},
},
}));
@@ -85,9 +88,24 @@ describe("Private API - /polls", () => {
id: "test-user-id",
} as never);
vi.mocked(prisma.spaceMember.findFirst).mockResolvedValue(null);
- vi.mocked(prisma.poll.create).mockResolvedValue({
+
+ // Mock createPoll mutation
+ mockCreatePoll.mockResolvedValue({
id: "test-poll-id",
- } as never);
+ title: "Test Poll",
+ description: null,
+ location: null,
+ timeZone: null,
+ status: "live",
+ createdAt: new Date("2025-01-10T12:00:00Z"),
+ user: {
+ name: "Test User",
+ image: null,
+ },
+ options: [],
+ adminUrl: "https://example.com/poll/test-poll-id",
+ inviteUrl: "https://example.com/invite/test-poll-id",
+ });
});
describe("Authentication", () => {
@@ -183,29 +201,23 @@ describe("Private API - /polls", () => {
"https://example.com/invite/test-poll-id",
);
- expect(prisma.poll.create).toHaveBeenCalledWith(
+ expect(mockCreatePoll).toHaveBeenCalledWith(
expect.objectContaining({
- data: expect.objectContaining({
- title: "Team offsite",
- options: {
- createMany: {
- data: [
- {
- startTime: new Date("2025-01-15T00:00:00.000Z"),
- duration: 0,
- },
- {
- startTime: new Date("2025-01-16T00:00:00.000Z"),
- duration: 0,
- },
- {
- startTime: new Date("2025-01-17T00:00:00.000Z"),
- duration: 0,
- },
- ],
- },
+ title: "Team offsite",
+ options: [
+ {
+ startTime: new Date("2025-01-15T00:00:00.000Z"),
+ duration: 0,
+ },
+ {
+ startTime: new Date("2025-01-16T00:00:00.000Z"),
+ duration: 0,
},
- }),
+ {
+ startTime: new Date("2025-01-17T00:00:00.000Z"),
+ duration: 0,
+ },
+ ],
}),
);
});
@@ -225,12 +237,10 @@ describe("Private API - /polls", () => {
});
expect(res.status).toBe(200);
- expect(prisma.poll.create).toHaveBeenCalledWith(
+ expect(mockCreatePoll).toHaveBeenCalledWith(
expect.objectContaining({
- data: expect.objectContaining({
- title: "Team offsite",
- location: "Conference Room A",
- }),
+ title: "Team offsite",
+ location: "Conference Room A",
}),
);
});
@@ -300,12 +310,10 @@ describe("Private API - /polls", () => {
const json = await res.json();
expect(json.data.id).toBe("test-poll-id");
- expect(prisma.poll.create).toHaveBeenCalledWith(
+ expect(mockCreatePoll).toHaveBeenCalledWith(
expect.objectContaining({
- data: expect.objectContaining({
- title: "Team sync",
- timeZone: "Europe/London",
- }),
+ title: "Team sync",
+ timeZone: "Europe/London",
}),
);
});
@@ -327,11 +335,9 @@ describe("Private API - /polls", () => {
});
expect(res.status).toBe(200);
- expect(prisma.poll.create).toHaveBeenCalledWith(
+ expect(mockCreatePoll).toHaveBeenCalledWith(
expect.objectContaining({
- data: expect.objectContaining({
- timeZone: undefined,
- }),
+ timeZone: undefined,
}),
);
});
@@ -380,7 +386,7 @@ describe("Private API - /polls", () => {
});
expect(res.status).toBe(200);
- expect(prisma.poll.create).toHaveBeenCalled();
+ expect(mockCreatePoll).toHaveBeenCalled();
});
});
@@ -545,4 +551,531 @@ describe("Private API - /polls", () => {
expect(json.error.code).toBe("POLL_NOT_FOUND");
});
});
+
+ describe("Get poll", () => {
+ const mockPoll = {
+ id: "test-poll-id",
+ title: "Team sync",
+ description: "Weekly team meeting",
+ location: "Zoom",
+ timeZone: "Europe/London",
+ status: "live",
+ createdAt: new Date("2025-01-10T12:00:00Z"),
+ user: {
+ name: "John Doe",
+ image: "https://example.com/avatar.jpg",
+ },
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T09:00:00Z"),
+ duration: 30,
+ },
+ {
+ id: "opt-2",
+ startTime: new Date("2025-01-15T10:00:00Z"),
+ duration: 30,
+ },
+ ],
+ };
+
+ it("should return poll data", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue(mockPoll as never);
+
+ const res = await app.request("/api/private/polls/test-poll-id", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expect(json.data.id).toBe("test-poll-id");
+ expect(json.data.title).toBe("Team sync");
+ expect(json.data.description).toBe("Weekly team meeting");
+ expect(json.data.location).toBe("Zoom");
+ expect(json.data.timezone).toBe("Europe/London");
+ expect(json.data.status).toBe("live");
+ expect(json.data.createdAt).toBe("2025-01-10T12:00:00.000Z");
+ expect(json.data.user).toEqual({
+ name: "John Doe",
+ image: "https://example.com/avatar.jpg",
+ });
+ expect(json.data.options).toHaveLength(2);
+ expect(json.data.options[0]).toEqual({
+ id: "opt-1",
+ startTime: "2025-01-15T09:00:00.000Z",
+ duration: 30,
+ });
+ expect(json.data.adminUrl).toBe("https://example.com/poll/test-poll-id");
+ expect(json.data.inviteUrl).toBe(
+ "https://example.com/invite/test-poll-id",
+ );
+
+ expect(prisma.poll.findFirst).toHaveBeenCalledWith({
+ where: {
+ id: "test-poll-id",
+ spaceId: "test-space-id",
+ deleted: false,
+ },
+ select: expect.objectContaining({
+ id: true,
+ title: true,
+ description: true,
+ location: true,
+ timeZone: true,
+ status: true,
+ createdAt: true,
+ user: expect.any(Object),
+ options: expect.any(Object),
+ }),
+ });
+ });
+
+ it("should return poll without user when user is null", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue({
+ ...mockPoll,
+ user: null,
+ } as never);
+
+ const res = await app.request("/api/private/polls/test-poll-id", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expect(json.data.user).toBeNull();
+ });
+
+ it("should return 404 when poll not found", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue(null);
+
+ const res = await app.request("/api/private/polls/nonexistent-poll", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(404);
+ const json = await res.json();
+ expect(json.error.code).toBe("POLL_NOT_FOUND");
+ });
+
+ it("should return 404 when poll belongs to different space", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue(null);
+
+ const res = await app.request("/api/private/polls/other-space-poll", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(404);
+ const json = await res.json();
+ expect(json.error.code).toBe("POLL_NOT_FOUND");
+ });
+
+ it("should return 401 without authorization", async () => {
+ const res = await app.request("/api/private/polls/test-poll-id", {
+ method: "GET",
+ });
+
+ expect(res.status).toBe(401);
+ });
+ });
+
+ describe("Get poll results", () => {
+ it("should return aggregated vote results", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue({
+ id: "test-poll-id",
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T09:00:00Z"),
+ duration: 30,
+ votes: [
+ { type: "yes" },
+ { type: "yes" },
+ { type: "yes" },
+ { type: "ifNeedBe" },
+ { type: "no" },
+ ],
+ },
+ {
+ id: "opt-2",
+ startTime: new Date("2025-01-15T10:00:00Z"),
+ duration: 30,
+ votes: [{ type: "yes" }, { type: "no" }, { type: "no" }],
+ },
+ {
+ id: "opt-3",
+ startTime: new Date("2025-01-15T11:00:00Z"),
+ duration: 30,
+ votes: [],
+ },
+ ],
+ _count: { participants: 5 },
+ } as never);
+
+ const res = await app.request("/api/private/polls/test-poll-id/results", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+
+ expect(json.data.pollId).toBe("test-poll-id");
+ expect(json.data.participantCount).toBe(5);
+ expect(json.data.highScore).toBe(4003); // (3+1)*1000 + 3 = 4003
+ expect(json.data.options).toHaveLength(3);
+
+ // First option: 3 yes, 1 ifNeedBe = (3+1)*1000 + 3 = 4003 (top choice)
+ expect(json.data.options[0]).toEqual({
+ id: "opt-1",
+ startTime: "2025-01-15T09:00:00.000Z",
+ duration: 30,
+ votes: { yes: 3, ifNeedBe: 1, no: 1 },
+ score: 4003,
+ isTopChoice: true,
+ });
+
+ // Second option: 1 yes = (1+0)*1000 + 1 = 1001
+ expect(json.data.options[1]).toEqual({
+ id: "opt-2",
+ startTime: "2025-01-15T10:00:00.000Z",
+ duration: 30,
+ votes: { yes: 1, ifNeedBe: 0, no: 2 },
+ score: 1001,
+ isTopChoice: false,
+ });
+
+ // Third option: no votes = score 0
+ expect(json.data.options[2]).toEqual({
+ id: "opt-3",
+ startTime: "2025-01-15T11:00:00.000Z",
+ duration: 30,
+ votes: { yes: 0, ifNeedBe: 0, no: 0 },
+ score: 0,
+ isTopChoice: false,
+ });
+ });
+
+ it("should handle ties for top choice", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue({
+ id: "test-poll-id",
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T09:00:00Z"),
+ duration: 30,
+ votes: [{ type: "yes" }, { type: "yes" }],
+ },
+ {
+ id: "opt-2",
+ startTime: new Date("2025-01-15T10:00:00Z"),
+ duration: 30,
+ votes: [{ type: "yes" }, { type: "yes" }],
+ },
+ ],
+ _count: { participants: 2 },
+ } as never);
+
+ const res = await app.request("/api/private/polls/test-poll-id/results", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+
+ // Both options have score 2002, both should be top choice
+ expect(json.data.options[0].isTopChoice).toBe(true);
+ expect(json.data.options[1].isTopChoice).toBe(true);
+ expect(json.data.highScore).toBe(2002);
+ });
+
+ it("should prioritize total availability over yes votes", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue({
+ id: "test-poll-id",
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T09:00:00Z"),
+ duration: 30,
+ // 4 yes = 4 available = (4)*1000 + 4 = 4004
+ votes: [
+ { type: "yes" },
+ { type: "yes" },
+ { type: "yes" },
+ { type: "yes" },
+ ],
+ },
+ {
+ id: "opt-2",
+ startTime: new Date("2025-01-15T10:00:00Z"),
+ duration: 30,
+ // 3 yes + 2 ifNeedBe = 5 available = (5)*1000 + 3 = 5003 (winner)
+ votes: [
+ { type: "yes" },
+ { type: "yes" },
+ { type: "yes" },
+ { type: "ifNeedBe" },
+ { type: "ifNeedBe" },
+ ],
+ },
+ ],
+ _count: { participants: 5 },
+ } as never);
+
+ const res = await app.request("/api/private/polls/test-poll-id/results", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+
+ // 5 available (5003) beats 4 available (4004) even though opt-1 has more yes votes
+ expect(json.data.options[0].score).toBe(4004);
+ expect(json.data.options[0].isTopChoice).toBe(false);
+ expect(json.data.options[1].score).toBe(5003);
+ expect(json.data.options[1].isTopChoice).toBe(true);
+ });
+
+ it("should use yes votes as tiebreaker when availability is equal", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue({
+ id: "test-poll-id",
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T09:00:00Z"),
+ duration: 30,
+ // 3 yes + 1 ifNeedBe = 4 available = (4)*1000 + 3 = 4003
+ votes: [
+ { type: "yes" },
+ { type: "yes" },
+ { type: "yes" },
+ { type: "ifNeedBe" },
+ ],
+ },
+ {
+ id: "opt-2",
+ startTime: new Date("2025-01-15T10:00:00Z"),
+ duration: 30,
+ // 4 yes = 4 available = (4)*1000 + 4 = 4004 (winner due to more yes)
+ votes: [
+ { type: "yes" },
+ { type: "yes" },
+ { type: "yes" },
+ { type: "yes" },
+ ],
+ },
+ ],
+ _count: { participants: 4 },
+ } as never);
+
+ const res = await app.request("/api/private/polls/test-poll-id/results", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+
+ // Same availability (4), but opt-2 has more yes votes
+ expect(json.data.options[0].score).toBe(4003);
+ expect(json.data.options[0].isTopChoice).toBe(false);
+ expect(json.data.options[1].score).toBe(4004);
+ expect(json.data.options[1].isTopChoice).toBe(true);
+ });
+
+ it("should return 404 when poll not found", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue(null);
+
+ const res = await app.request(
+ "/api/private/polls/nonexistent-poll/results",
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ },
+ );
+
+ expect(res.status).toBe(404);
+ const json = await res.json();
+ expect(json.error.code).toBe("POLL_NOT_FOUND");
+ });
+
+ it("should return 401 without authorization", async () => {
+ const res = await app.request("/api/private/polls/test-poll-id/results", {
+ method: "GET",
+ });
+
+ expect(res.status).toBe(401);
+ });
+ });
+
+ describe("Get poll participants", () => {
+ it("should return participants with their votes", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue({
+ id: "test-poll-id",
+ participants: [
+ {
+ id: "participant-1",
+ name: "Alice",
+ email: "[email protected]",
+ createdAt: new Date("2025-01-10T10:00:00Z"),
+ votes: [
+ {
+ type: "yes",
+ option: {
+ startTime: new Date("2025-01-15T09:00:00Z"),
+ duration: 30,
+ },
+ },
+ {
+ type: "no",
+ option: {
+ startTime: new Date("2025-01-15T10:00:00Z"),
+ duration: 30,
+ },
+ },
+ ],
+ },
+ {
+ id: "participant-2",
+ name: "Bob",
+ email: null,
+ createdAt: new Date("2025-01-10T11:00:00Z"),
+ votes: [
+ {
+ type: "ifNeedBe",
+ option: {
+ startTime: new Date("2025-01-15T09:00:00Z"),
+ duration: 30,
+ },
+ },
+ {
+ type: "yes",
+ option: {
+ startTime: new Date("2025-01-15T10:00:00Z"),
+ duration: 30,
+ },
+ },
+ ],
+ },
+ ],
+ } as never);
+
+ const res = await app.request(
+ "/api/private/polls/test-poll-id/participants",
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ },
+ );
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+
+ expect(json.data.pollId).toBe("test-poll-id");
+ expect(json.data.participants).toHaveLength(2);
+
+ expect(json.data.participants[0]).toEqual({
+ id: "participant-1",
+ name: "Alice",
+ email: "[email protected]",
+ createdAt: "2025-01-10T10:00:00.000Z",
+ votes: [
+ { startTime: "2025-01-15T09:00:00.000Z", duration: 30, type: "yes" },
+ { startTime: "2025-01-15T10:00:00.000Z", duration: 30, type: "no" },
+ ],
+ });
+
+ expect(json.data.participants[1]).toEqual({
+ id: "participant-2",
+ name: "Bob",
+ email: null,
+ createdAt: "2025-01-10T11:00:00.000Z",
+ votes: [
+ {
+ startTime: "2025-01-15T09:00:00.000Z",
+ duration: 30,
+ type: "ifNeedBe",
+ },
+ { startTime: "2025-01-15T10:00:00.000Z", duration: 30, type: "yes" },
+ ],
+ });
+ });
+
+ it("should return empty array when no participants", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue({
+ id: "test-poll-id",
+ participants: [],
+ } as never);
+
+ const res = await app.request(
+ "/api/private/polls/test-poll-id/participants",
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ },
+ );
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+
+ expect(json.data.pollId).toBe("test-poll-id");
+ expect(json.data.participants).toEqual([]);
+ });
+
+ it("should return 404 when poll not found", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue(null);
+
+ const res = await app.request(
+ "/api/private/polls/nonexistent-poll/participants",
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ },
+ );
+
+ expect(res.status).toBe(404);
+ const json = await res.json();
+ expect(json.error.code).toBe("POLL_NOT_FOUND");
+ });
+
+ it("should return 401 without authorization", async () => {
+ const res = await app.request(
+ "/api/private/polls/test-poll-id/participants",
+ {
+ method: "GET",
+ },
+ );
+
+ expect(res.status).toBe(401);
+ });
+ });
});
diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.ts
index 7f1320b18..349f9c8c9 100644
--- a/apps/web/src/app/api/private/[...route]/route.ts
+++ b/apps/web/src/app/api/private/[...route]/route.ts
@@ -1,5 +1,6 @@
import { RedisStore } from "@hono-rate-limiter/redis";
import { prisma } from "@rallly/database";
+import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
import { Scalar } from "@scalar/hono-api-reference";
import { Hono } from "hono";
import { handle } from "hono/vercel";
@@ -10,7 +11,7 @@ import {
validator,
} from "hono-openapi";
import { rateLimiter } from "hono-rate-limiter";
-import { deletePoll } from "@/features/poll/mutations";
+import { createPoll, deletePoll } from "@/features/poll/mutations";
import { isKvEnabled, kv } from "@/lib/kv";
import { isSupportedTimeZone } from "@/utils/supported-time-zones";
import {
@@ -18,9 +19,12 @@ import {
createPollSuccessResponseSchema,
deletePollSuccessResponseSchema,
errorResponseSchema,
+ getPollParticipantsSuccessResponseSchema,
+ getPollResultsSuccessResponseSchema,
+ getPollSuccessResponseSchema,
} from "../schemas";
import { spaceApiKeyAuth } from "../utils/api-key";
-import { apiError, createPoll } from "../utils/poll";
+import { apiError } from "../utils/poll";
import type { SlotGeneratorInput } from "../utils/time-slots";
import {
dedupeTimeSlots,
@@ -189,6 +193,23 @@ app.post(
return c.json({
data: {
id: poll.id,
+ title: poll.title,
+ description: poll.description,
+ location: poll.location,
+ timeZone: poll.timeZone,
+ status: poll.status,
+ createdAt: poll.createdAt.toISOString(),
+ user: poll.user
+ ? {
+ name: poll.user.name,
+ image: poll.user.image,
+ }
+ : null,
+ options: poll.options.map((option) => ({
+ id: option.id,
+ startTime: option.startTime.toISOString(),
+ duration: option.duration,
+ })),
adminUrl: poll.adminUrl,
inviteUrl: poll.inviteUrl,
},
@@ -273,6 +294,23 @@ app.post(
return c.json({
data: {
id: poll.id,
+ title: poll.title,
+ description: poll.description,
+ location: poll.location,
+ timezone: poll.timeZone,
+ status: poll.status,
+ createdAt: poll.createdAt.toISOString(),
+ user: poll.user
+ ? {
+ name: poll.user.name,
+ image: poll.user.image,
+ }
+ : null,
+ options: poll.options.map((option) => ({
+ id: option.id,
+ startTime: option.startTime.toISOString(),
+ duration: option.duration,
+ })),
adminUrl: poll.adminUrl,
inviteUrl: poll.inviteUrl,
},
@@ -280,6 +318,346 @@ app.post(
},
);
+app.get(
+ "/polls/:pollId",
+ spaceApiKeyAuth,
+ rateLimiter<Env>({
+ windowMs: 60 * 1000,
+ limit: 120,
+ keyGenerator: (c) => {
+ const { apiKeyId } = c.get("apiAuth");
+ return `private-api:polls-get:${apiKeyId}`;
+ },
+ store: isKvEnabled() ? new RedisStore({ client: kv }) : undefined,
+ }),
+ describeRoute({
+ tags: ["Polls"],
+ summary: "Get a poll",
+ description:
+ "Retrieves poll metadata by ID. The poll must belong to the space associated with the API key.",
+ security: [{ bearerAuth: [] }],
+ responses: {
+ 200: {
+ description: "Successful response",
+ content: {
+ "application/json": {
+ schema: resolver(getPollSuccessResponseSchema),
+ },
+ },
+ },
+ 404: {
+ description: "Poll not found",
+ content: {
+ "application/json": {
+ schema: resolver(errorResponseSchema),
+ },
+ },
+ },
+ },
+ }),
+ async (c) => {
+ const { pollId } = c.req.param();
+ const { spaceId } = c.get("apiAuth");
+
+ const poll = await prisma.poll.findFirst({
+ where: {
+ id: pollId,
+ spaceId,
+ deleted: false,
+ },
+ select: {
+ id: true,
+ title: true,
+ description: true,
+ location: true,
+ timeZone: true,
+ status: true,
+ createdAt: true,
+ user: {
+ select: {
+ name: true,
+ image: true,
+ },
+ },
+ options: {
+ select: {
+ id: true,
+ startTime: true,
+ duration: true,
+ },
+ orderBy: {
+ startTime: "asc",
+ },
+ },
+ },
+ });
+
+ if (!poll) {
+ return c.json(
+ apiError(
+ "POLL_NOT_FOUND",
+ "Poll not found or does not belong to this space.",
+ ),
+ 404,
+ );
+ }
+
+ return c.json({
+ data: {
+ id: poll.id,
+ title: poll.title,
+ description: poll.description,
+ location: poll.location,
+ timezone: poll.timeZone,
+ status: poll.status,
+ createdAt: poll.createdAt.toISOString(),
+ user: poll.user
+ ? {
+ name: poll.user.name,
+ image: poll.user.image,
+ }
+ : null,
+ options: poll.options.map((option) => ({
+ id: option.id,
+ startTime: option.startTime.toISOString(),
+ duration: option.duration,
+ })),
+ adminUrl: absoluteUrl(`/poll/${poll.id}`),
+ inviteUrl: shortUrl(`/invite/${poll.id}`),
+ },
+ });
+ },
+);
+
+app.get(
+ "/polls/:pollId/results",
+ spaceApiKeyAuth,
+ rateLimiter<Env>({
+ windowMs: 60 * 1000,
+ limit: 120,
+ keyGenerator: (c) => {
+ const { apiKeyId } = c.get("apiAuth");
+ return `private-api:polls-results:${apiKeyId}`;
+ },
+ store: isKvEnabled() ? new RedisStore({ client: kv }) : undefined,
+ }),
+ describeRoute({
+ tags: ["Polls"],
+ summary: "Get poll results",
+ description:
+ "Retrieves aggregated voting results for a poll. Returns vote counts per option without individual participant data.",
+ security: [{ bearerAuth: [] }],
+ responses: {
+ 200: {
+ description: "Successful response",
+ content: {
+ "application/json": {
+ schema: resolver(getPollResultsSuccessResponseSchema),
+ },
+ },
+ },
+ 404: {
+ description: "Poll not found",
+ content: {
+ "application/json": {
+ schema: resolver(errorResponseSchema),
+ },
+ },
+ },
+ },
+ }),
+ async (c) => {
+ const { pollId } = c.req.param();
+ const { spaceId } = c.get("apiAuth");
+
+ const poll = await prisma.poll.findFirst({
+ where: {
+ id: pollId,
+ spaceId,
+ deleted: false,
+ },
+ select: {
+ id: true,
+ options: {
+ select: {
+ id: true,
+ startTime: true,
+ duration: true,
+ votes: {
+ select: {
+ type: true,
+ },
+ },
+ },
+ orderBy: {
+ startTime: "asc",
+ },
+ },
+ _count: {
+ select: {
+ participants: {
+ where: { deleted: false },
+ },
+ },
+ },
+ },
+ });
+
+ if (!poll) {
+ return c.json(
+ apiError(
+ "POLL_NOT_FOUND",
+ "Poll not found or does not belong to this space.",
+ ),
+ 404,
+ );
+ }
+
+ // Calculate scores for each option
+ // Ranking: total availability (yes + ifNeedBe) is primary, yes votes as tiebreaker
+ // Score formula: (yes + ifNeedBe) * 1000 + yes
+ const optionResults = poll.options.map((option) => {
+ const votes = { yes: 0, ifNeedBe: 0, no: 0 };
+ for (const vote of option.votes) {
+ if (vote.type === "yes") votes.yes++;
+ else if (vote.type === "ifNeedBe") votes.ifNeedBe++;
+ else if (vote.type === "no") votes.no++;
+ }
+ const score = (votes.yes + votes.ifNeedBe) * 1000 + votes.yes;
+
+ return {
+ id: option.id,
+ startTime: option.startTime.toISOString(),
+ duration: option.duration,
+ votes,
+ score,
+ };
+ });
+
+ // Find the high score
+ const highScore = Math.max(...optionResults.map((o) => o.score), 0);
+
+ // Add isTopChoice flag
+ const options = optionResults.map((option) => ({
+ ...option,
+ isTopChoice: option.score === highScore && option.score > 0,
+ }));
+
+ return c.json({
+ data: {
+ pollId: poll.id,
+ participantCount: poll._count.participants,
+ options,
+ highScore,
+ },
+ });
+ },
+);
+
+app.get(
+ "/polls/:pollId/participants",
+ spaceApiKeyAuth,
+ rateLimiter<Env>({
+ windowMs: 60 * 1000,
+ limit: 120,
+ keyGenerator: (c) => {
+ const { apiKeyId } = c.get("apiAuth");
+ return `private-api:polls-participants:${apiKeyId}`;
+ },
+ store: isKvEnabled() ? new RedisStore({ client: kv }) : undefined,
+ }),
+ describeRoute({
+ tags: ["Polls"],
+ summary: "Get poll participants",
+ description:
+ "Retrieves all participants and their votes for a poll. The poll must belong to the space associated with the API key.",
+ security: [{ bearerAuth: [] }],
+ responses: {
+ 200: {
+ description: "Successful response",
+ content: {
+ "application/json": {
+ schema: resolver(getPollParticipantsSuccessResponseSchema),
+ },
+ },
+ },
+ 404: {
+ description: "Poll not found",
+ content: {
+ "application/json": {
+ schema: resolver(errorResponseSchema),
+ },
+ },
+ },
+ },
+ }),
+ async (c) => {
+ const { pollId } = c.req.param();
+ const { spaceId } = c.get("apiAuth");
+
+ const poll = await prisma.poll.findFirst({
+ where: {
+ id: pollId,
+ spaceId,
+ deleted: false,
+ },
+ select: {
+ id: true,
+ participants: {
+ where: { deleted: false },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ createdAt: true,
+ votes: {
+ select: {
+ type: true,
+ option: {
+ select: {
+ startTime: true,
+ duration: true,
+ },
+ },
+ },
+ },
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ },
+ },
+ });
+
+ if (!poll) {
+ return c.json(
+ apiError(
+ "POLL_NOT_FOUND",
+ "Poll not found or does not belong to this space.",
+ ),
+ 404,
+ );
+ }
+
+ return c.json({
+ data: {
+ pollId: poll.id,
+ participants: poll.participants.map((participant) => ({
+ id: participant.id,
+ name: participant.name,
+ email: participant.email,
+ createdAt: participant.createdAt.toISOString(),
+ votes: participant.votes.map((vote) => ({
+ startTime: vote.option.startTime.toISOString(),
+ duration: vote.option.duration,
+ type: vote.type,
+ })),
+ })),
+ },
+ });
+ },
+);
+
app.delete(
"/polls/:pollId",
spaceApiKeyAuth,
diff --git a/apps/web/src/app/api/private/schemas.ts b/apps/web/src/app/api/private/schemas.ts
index 158897e2e..d57803d41 100644
--- a/apps/web/src/app/api/private/schemas.ts
+++ b/apps/web/src/app/api/private/schemas.ts
@@ -126,47 +126,164 @@ export const createPollInputSchema = z
})
.openapi("CreatePollInput");
-export const createPollSuccessResponseSchema = z
+export const errorResponseSchema = z
+ .object({
+ error: z.object({
+ code: z.string().openapi({ example: "TIMEZONE_REQUIRED" }),
+ message: z.string().openapi({
+ example:
+ "Timezone is required. Either provide a timezone in the request or set one in your profile.",
+ }),
+ }),
+ })
+ .openapi("ErrorResponse");
+
+export const deletePollSuccessResponseSchema = z
+ .object({
+ data: z.object({
+ id: z.string().openapi({ example: "p_123abc" }),
+ deleted: z.literal(true).openapi({ example: true }),
+ }),
+ })
+ .openapi("DeletePollResponse");
+
+export const pollStatusSchema = z
+ .enum(["live", "paused", "finalized"])
+ .openapi("PollStatus");
+
+export const pollOptionSchema = z
+ .object({
+ id: z.string().openapi({ example: "opt_abc123" }),
+ startTime: z.iso.datetime().openapi({ example: "2025-01-15T09:00:00Z" }),
+ duration: z.number().int().openapi({
+ description: "Duration in minutes. 0 indicates an all-day option.",
+ example: 30,
+ }),
+ })
+ .openapi("PollOption");
+
+export const pollUserSchema = z
+ .object({
+ name: z.string().openapi({ example: "John Doe" }),
+ image: z
+ .string()
+ .nullable()
+ .openapi({ example: "https://example.com/avatar.jpg" }),
+ })
+ .openapi("PollUser");
+
+export const getPollSuccessResponseSchema = z
.object({
data: z.object({
id: z.string().openapi({ example: "p_123abc" }),
+ title: z.string().openapi({ example: "Team sync" }),
+ description: z.string().nullable().openapi({
+ example: "Pick a time that works for everyone",
+ }),
+ location: z.string().nullable().openapi({ example: "Zoom" }),
+ timezone: z.string().nullable().openapi({ example: "Europe/London" }),
+ status: pollStatusSchema,
+ createdAt: z
+ .string()
+ .datetime()
+ .openapi({ example: "2025-01-10T12:00:00Z" }),
+ user: pollUserSchema.nullable().openapi({
+ description: "The poll organizer",
+ }),
+ options: z.array(pollOptionSchema),
adminUrl: z
.string()
.openapi({ example: "https://example.com/poll/p_123abc" }),
inviteUrl: z
.string()
.openapi({ example: "https://example.com/invite/p_123abc" }),
- space: z
- .object({
- id: z.string(),
- name: z.string(),
- })
- .nullable()
- .openapi({
- description: "The space the poll was created in, or null if personal",
- example: { id: "space_abc123", name: "My Team" },
- }),
}),
})
- .openapi("CreatePollResponse");
+ .openapi("GetPollResponse");
-export const errorResponseSchema = z
+// Create poll returns the same shape as get poll
+export const createPollSuccessResponseSchema =
+ getPollSuccessResponseSchema.openapi("CreatePollResponse");
+
+export const voteCountsSchema = z
.object({
- error: z.object({
- code: z.string().openapi({ example: "TIMEZONE_REQUIRED" }),
- message: z.string().openapi({
- example:
- "Timezone is required. Either provide a timezone in the request or set one in your profile.",
+ yes: z.int().nonnegative().openapi({ example: 5 }),
+ ifNeedBe: z.int().nonnegative().openapi({ example: 2 }),
+ no: z.int().nonnegative().openapi({ example: 1 }),
+ })
+ .openapi("VoteCounts");
+
+export const optionResultSchema = z
+ .object({
+ id: z.string().openapi({ example: "opt_abc123" }),
+ startTime: z.iso.datetime().openapi({ example: "2025-01-15T09:00:00Z" }),
+ duration: z.int().nonnegative().openapi({
+ description: "Duration in minutes. 0 indicates an all-day option.",
+ example: 30,
+ }),
+ votes: voteCountsSchema,
+ score: z.int().nonnegative().openapi({
+ description:
+ "Ranking score: (yes + ifNeedBe) * 1000 + yes. Total availability is primary, yes votes break ties.",
+ example: 5004,
+ }),
+ isTopChoice: z.boolean().openapi({
+ description: "Whether this option has the highest score",
+ example: true,
+ }),
+ })
+ .openapi("OptionResult");
+
+export const getPollResultsSuccessResponseSchema = z
+ .object({
+ data: z.object({
+ pollId: z.string().openapi({ example: "p_123abc" }),
+ participantCount: z.int().nonnegative().openapi({
+ description: "Total number of participants",
+ example: 8,
+ }),
+ options: z.array(optionResultSchema),
+ highScore: z.int().nonnegative().openapi({
+ description: "Highest score across all options",
+ example: 7,
}),
}),
})
- .openapi("ErrorResponse");
+ .openapi("GetPollResultsResponse");
-export const deletePollSuccessResponseSchema = z
+export const voteTypeSchema = z
+ .enum(["yes", "ifNeedBe", "no"])
+ .openapi("VoteType");
+
+export const participantVoteSchema = z
+ .object({
+ startTime: z.iso.datetime().openapi({ example: "2025-01-15T09:00:00Z" }),
+ duration: z.number().int().openapi({
+ description: "Duration in minutes. 0 indicates an all-day option.",
+ example: 30,
+ }),
+ type: voteTypeSchema,
+ })
+ .openapi("ParticipantVote");
+
+export const participantSchema = z
+ .object({
+ id: z.string().openapi({ example: "participant_abc123" }),
+ name: z.string().openapi({ example: "Jane Smith" }),
+ email: z.string().nullable().openapi({ example: "[email protected]" }),
+ createdAt: z
+ .string()
+ .datetime()
+ .openapi({ example: "2025-01-10T12:00:00Z" }),
+ votes: z.array(participantVoteSchema),
+ })
+ .openapi("Participant");
+
+export const getPollParticipantsSuccessResponseSchema = z
.object({
data: z.object({
- id: z.string().openapi({ example: "p_123abc" }),
- deleted: z.literal(true).openapi({ example: true }),
+ pollId: z.string().openapi({ example: "p_123abc" }),
+ participants: z.array(participantSchema),
}),
})
- .openapi("DeletePollResponse");
+ .openapi("GetPollParticipantsResponse");
diff --git a/apps/web/src/app/api/private/utils/poll.ts b/apps/web/src/app/api/private/utils/poll.ts
index 351c626a8..2c6ad8936 100644
--- a/apps/web/src/app/api/private/utils/poll.ts
+++ b/apps/web/src/app/api/private/utils/poll.ts
@@ -1,67 +1,3 @@
-import { prisma } from "@rallly/database";
-import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
-import { nanoid } from "@rallly/utils/nanoid";
-
-export type PollOption = {
- startTime: Date;
- duration: number;
-};
-
-export type CreatePollParams = {
- userId: string;
- title: string;
- description?: string;
- location?: string;
- timeZone?: string;
- requireParticipantEmail?: boolean;
- hideParticipants?: boolean;
- hideScores?: boolean;
- disableComments?: boolean;
- options: PollOption[];
- spaceId: string;
-};
-
-export const createPoll = async ({
- userId,
- title,
- description,
- location,
- timeZone,
- requireParticipantEmail,
- hideParticipants,
- hideScores,
- disableComments,
- options,
- spaceId,
-}: CreatePollParams) => {
- const poll = await prisma.poll.create({
- data: {
- id: nanoid(),
- title,
- description,
- location,
- timeZone,
- requireParticipantEmail,
- hideParticipants,
- hideScores,
- disableComments,
- adminUrlId: nanoid(),
- participantUrlId: nanoid(),
- userId,
- watchers: { create: { userId } },
- spaceId,
- options: { createMany: { data: options } },
- },
- select: { id: true },
- });
-
- return {
- id: poll.id,
- adminUrl: absoluteUrl(`/poll/${poll.id}`),
- inviteUrl: shortUrl(`/invite/${poll.id}`),
- };
-};
-
export const apiError = (code: string, message: string) => ({
error: { code, message },
});
diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.ts
index 09ee736fb..8c123adb5 100644
--- a/apps/web/src/features/poll/mutations.ts
+++ b/apps/web/src/features/poll/mutations.ts
@@ -1,4 +1,90 @@
import { prisma } from "@rallly/database";
+import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
+import { nanoid } from "@rallly/utils/nanoid";
+
+export type PollOption = {
+ startTime: Date;
+ duration: number;
+};
+
+export type CreatePollParams = {
+ userId: string;
+ title: string;
+ description?: string;
+ location?: string;
+ timeZone?: string;
+ requireParticipantEmail?: boolean;
+ hideParticipants?: boolean;
+ hideScores?: boolean;
+ disableComments?: boolean;
+ options: PollOption[];
+ spaceId: string;
+};
+
+export const createPoll = async ({
+ userId,
+ title,
+ description,
+ location,
+ timeZone,
+ requireParticipantEmail,
+ hideParticipants,
+ hideScores,
+ disableComments,
+ options,
+ spaceId,
+}: CreatePollParams) => {
+ const poll = await prisma.poll.create({
+ data: {
+ id: nanoid(),
+ title,
+ description,
+ location,
+ timeZone,
+ requireParticipantEmail,
+ hideParticipants,
+ hideScores,
+ disableComments,
+ adminUrlId: nanoid(),
+ participantUrlId: nanoid(),
+ userId,
+ watchers: { create: { userId } },
+ spaceId,
+ options: { createMany: { data: options } },
+ },
+ select: {
+ id: true,
+ title: true,
+ description: true,
+ location: true,
+ timeZone: true,
+ status: true,
+ createdAt: true,
+ user: {
+ select: {
+ name: true,
+ image: true,
+ },
+ },
+ options: {
+ select: {
+ id: true,
+ startTime: true,
+ duration: true,
+ },
+ orderBy: {
+ startTime: "asc",
+ },
+ },
+ },
+ });
+
+ return {
+ ...poll,
+ adminUrl: absoluteUrl(`/poll/${poll.id}`),
+ inviteUrl: shortUrl(`/invite/${poll.id}`),
+ };
+};
export const deletePoll = async (pollId: string, spaceId: string) => {
const poll = await prisma.poll.findFirst({