Skip to content

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

🚧 Fix vote aggregation and update API responses (#2130)

Luke Vella86e59767d796
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 4103d71b8..00c4c4aee 100644
--- a/apps/web/src/app/api/private/[...route]/route.test.ts
+++ b/apps/web/src/app/api/private/[...route]/route.test.ts
@@ -1,13 +1,23 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
+// Mock server-only before any imports that might need it
+vi.mock("server-only", () => ({}));
+
const mockDeletePoll = vi.fn();
const mockCreatePoll = vi.fn();
+const mockGetPollResults = vi.fn();
+const mockGetPollParticipants = vi.fn();
vi.mock("@/features/poll/mutations", () => ({
deletePoll: (...args: unknown[]) => mockDeletePoll(...args),
createPoll: (...args: unknown[]) => mockCreatePoll(...args),
}));
+vi.mock("@/features/poll/data", () => ({
+ getPollResults: (...args: unknown[]) => mockGetPollResults(...args),
+ getPollParticipants: (...args: unknown[]) => mockGetPollParticipants(...args),
+}));
+
vi.mock("@rallly/database", () => ({
prisma: {
spaceApiKey: {
@@ -692,36 +702,44 @@ describe("Private API - /polls", () => {
describe("Get poll results", () => {
it("should return aggregated vote results", async () => {
- vi.mocked(prisma.poll.findFirst).mockResolvedValue({
- id: "test-poll-id",
+ mockGetPollResults.mockResolvedValue({
+ pollId: "test-poll-id",
+ participantCount: 5,
+ highScore: 4003,
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" },
+ { type: "yes", count: 3 },
+ { type: "ifNeedBe", count: 1 },
+ { type: "no", count: 1 },
],
+ score: 4003,
+ isTopChoice: true,
},
{
id: "opt-2",
startTime: new Date("2025-01-15T10:00:00Z"),
duration: 30,
- votes: [{ type: "yes" }, { type: "no" }, { type: "no" }],
+ votes: [
+ { type: "yes", count: 1 },
+ { type: "no", count: 2 },
+ ],
+ score: 1001,
+ isTopChoice: false,
},
{
id: "opt-3",
startTime: new Date("2025-01-15T11:00:00Z"),
duration: 30,
votes: [],
+ score: 0,
+ isTopChoice: false,
},
],
- _count: { participants: 5 },
- } as never);
+ });
const res = await app.request("/api/private/polls/test-poll-id/results", {
method: "GET",
@@ -735,59 +753,39 @@ describe("Private API - /polls", () => {
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.highScore).toBe(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,
+ expect(mockGetPollResults).toHaveBeenCalledWith({
+ pollId: "test-poll-id",
+ spaceId: "test-space-id",
});
});
it("should handle ties for top choice", async () => {
- vi.mocked(prisma.poll.findFirst).mockResolvedValue({
- id: "test-poll-id",
+ mockGetPollResults.mockResolvedValue({
+ pollId: "test-poll-id",
+ participantCount: 2,
+ highScore: 2002,
options: [
{
id: "opt-1",
startTime: new Date("2025-01-15T09:00:00Z"),
duration: 30,
- votes: [{ type: "yes" }, { type: "yes" }],
+ votes: [{ type: "yes", count: 2 }],
+ score: 2002,
+ isTopChoice: true,
},
{
id: "opt-2",
startTime: new Date("2025-01-15T10:00:00Z"),
duration: 30,
- votes: [{ type: "yes" }, { type: "yes" }],
+ votes: [{ type: "yes", count: 2 }],
+ score: 2002,
+ isTopChoice: true,
},
],
- _count: { participants: 2 },
- } as never);
+ });
const res = await app.request("/api/private/polls/test-poll-id/results", {
method: "GET",
@@ -806,37 +804,32 @@ describe("Private API - /polls", () => {
});
it("should prioritize total availability over yes votes", async () => {
- vi.mocked(prisma.poll.findFirst).mockResolvedValue({
- id: "test-poll-id",
+ mockGetPollResults.mockResolvedValue({
+ pollId: "test-poll-id",
+ participantCount: 5,
+ highScore: 5003,
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" },
- ],
+ votes: [{ type: "yes", count: 4 }],
+ score: 4004,
+ isTopChoice: false,
},
{
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" },
+ { type: "yes", count: 3 },
+ { type: "ifNeedBe", count: 2 },
],
+ score: 5003,
+ isTopChoice: true,
},
],
- _count: { participants: 5 },
- } as never);
+ });
const res = await app.request("/api/private/polls/test-poll-id/results", {
method: "GET",
@@ -856,36 +849,32 @@ describe("Private API - /polls", () => {
});
it("should use yes votes as tiebreaker when availability is equal", async () => {
- vi.mocked(prisma.poll.findFirst).mockResolvedValue({
- id: "test-poll-id",
+ mockGetPollResults.mockResolvedValue({
+ pollId: "test-poll-id",
+ participantCount: 4,
+ highScore: 4004,
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" },
+ { type: "yes", count: 3 },
+ { type: "ifNeedBe", count: 1 },
],
+ score: 4003,
+ isTopChoice: false,
},
{
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" },
- ],
+ votes: [{ type: "yes", count: 4 }],
+ score: 4004,
+ isTopChoice: true,
},
],
- _count: { participants: 4 },
- } as never);
+ });
const res = await app.request("/api/private/polls/test-poll-id/results", {
method: "GET",
@@ -905,7 +894,7 @@ describe("Private API - /polls", () => {
});
it("should return 404 when poll not found", async () => {
- vi.mocked(prisma.poll.findFirst).mockResolvedValue(null);
+ mockGetPollResults.mockResolvedValue(null);
const res = await app.request(
"/api/private/polls/nonexistent-poll/results",
@@ -932,56 +921,24 @@ describe("Private API - /polls", () => {
});
describe("Get poll participants", () => {
- it("should return participants with their votes", async () => {
- vi.mocked(prisma.poll.findFirst).mockResolvedValue({
- id: "test-poll-id",
+ it("should return participants", async () => {
+ mockGetPollParticipants.mockResolvedValue({
+ pollId: "test-poll-id",
participants: [
{
id: "participant-1",
name: "Alice",
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",
@@ -999,38 +956,17 @@ describe("Private API - /polls", () => {
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" },
- ],
+ expect(mockGetPollParticipants).toHaveBeenCalledWith({
+ pollId: "test-poll-id",
+ spaceId: "test-space-id",
});
});
it("should return empty array when no participants", async () => {
- vi.mocked(prisma.poll.findFirst).mockResolvedValue({
- id: "test-poll-id",
+ mockGetPollParticipants.mockResolvedValue({
+ pollId: "test-poll-id",
participants: [],
- } as never);
+ });
const res = await app.request(
"/api/private/polls/test-poll-id/participants",
@@ -1050,7 +986,7 @@ describe("Private API - /polls", () => {
});
it("should return 404 when poll not found", async () => {
- vi.mocked(prisma.poll.findFirst).mockResolvedValue(null);
+ mockGetPollParticipants.mockResolvedValue(null);
const res = await app.request(
"/api/private/polls/nonexistent-poll/participants",
diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.ts
index 349f9c8c9..1522621a3 100644
--- a/apps/web/src/app/api/private/[...route]/route.ts
+++ b/apps/web/src/app/api/private/[...route]/route.ts
@@ -11,6 +11,7 @@ import {
validator,
} from "hono-openapi";
import { rateLimiter } from "hono-rate-limiter";
+import { getPollParticipants, getPollResults } from "@/features/poll/data";
import { createPoll, deletePoll } from "@/features/poll/mutations";
import { isKvEnabled, kv } from "@/lib/kv";
import { isSupportedTimeZone } from "@/utils/supported-time-zones";
@@ -470,40 +471,9 @@ app.get(
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 },
- },
- },
- },
- },
- });
+ const data = await getPollResults({ pollId, spaceId });
- if (!poll) {
+ if (!data) {
return c.json(
apiError(
"POLL_NOT_FOUND",
@@ -513,43 +483,8 @@ app.get(
);
}
- // 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,
- },
+ data,
});
},
);
@@ -595,41 +530,9 @@ app.get(
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",
- },
- },
- },
- });
+ const data = await getPollParticipants({ pollId, spaceId });
- if (!poll) {
+ if (!data) {
return c.json(
apiError(
"POLL_NOT_FOUND",
@@ -640,20 +543,7 @@ app.get(
}
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,
- })),
- })),
- },
+ data,
});
},
);
diff --git a/apps/web/src/app/api/private/schemas.ts b/apps/web/src/app/api/private/schemas.ts
index d57803d41..930529399 100644
--- a/apps/web/src/app/api/private/schemas.ts
+++ b/apps/web/src/app/api/private/schemas.ts
@@ -205,13 +205,18 @@ export const getPollSuccessResponseSchema = z
export const createPollSuccessResponseSchema =
getPollSuccessResponseSchema.openapi("CreatePollResponse");
-export const voteCountsSchema = z
+export const voteCountSchema = z
.object({
- yes: z.int().nonnegative().openapi({ example: 5 }),
- ifNeedBe: z.int().nonnegative().openapi({ example: 2 }),
- no: z.int().nonnegative().openapi({ example: 1 }),
+ type: z.string().openapi({
+ description: "The vote type (e.g., yes, ifNeedBe, no)",
+ example: "yes",
+ }),
+ count: z.int().nonnegative().openapi({
+ description: "Number of votes of this type",
+ example: 5,
+ }),
})
- .openapi("VoteCounts");
+ .openapi("VoteCount");
export const optionResultSchema = z
.object({
@@ -221,7 +226,9 @@ export const optionResultSchema = z
description: "Duration in minutes. 0 indicates an all-day option.",
example: 30,
}),
- votes: voteCountsSchema,
+ votes: z.array(voteCountSchema).openapi({
+ description: "Array of vote counts by type",
+ }),
score: z.int().nonnegative().openapi({
description:
"Ranking score: (yes + ifNeedBe) * 1000 + yes. Total availability is primary, yes votes break ties.",
@@ -251,31 +258,12 @@ export const getPollResultsSuccessResponseSchema = z
})
.openapi("GetPollResultsResponse");
-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),
+ createdAt: z.iso.datetime().openapi({ example: "2025-01-10T12:00:00Z" }),
})
.openapi("Participant");
diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.ts
index c4f83d831..ec31172d4 100644
--- a/apps/web/src/features/poll/data.ts
+++ b/apps/web/src/features/poll/data.ts
@@ -3,6 +3,152 @@ import { prisma } from "@rallly/database";
import { shortUrl } from "@rallly/utils/absolute-url";
import { requireSpace } from "@/auth/data";
+export async function getPollResults({
+ pollId,
+ spaceId,
+}: {
+ pollId: string;
+ spaceId: string;
+}) {
+ // Run poll query and vote aggregation in parallel
+ const [poll, voteCounts] = await Promise.all([
+ prisma.poll.findFirst({
+ where: {
+ id: pollId,
+ spaceId,
+ deleted: false,
+ },
+ select: {
+ id: true,
+ options: {
+ select: {
+ id: true,
+ startTime: true,
+ duration: true,
+ },
+ orderBy: {
+ startTime: "asc",
+ },
+ },
+ _count: {
+ select: {
+ participants: {
+ where: { deleted: false },
+ },
+ },
+ },
+ },
+ }),
+ prisma.vote.groupBy({
+ by: ["optionId", "type"],
+ where: {
+ pollId,
+ participant: { deleted: false },
+ },
+ _count: true,
+ }),
+ ]);
+
+ if (!poll) {
+ return null;
+ }
+
+ // Build vote counts map from groupBy results
+ const votesByOption = new Map<
+ string,
+ Array<{ type: string; count: number }>
+ >();
+
+ for (const row of voteCounts) {
+ let votes = votesByOption.get(row.optionId);
+ if (!votes) {
+ votes = [];
+ votesByOption.set(row.optionId, votes);
+ }
+ votes.push({ type: row.type, count: row._count });
+ }
+
+ // Helper to get count for a specific vote type
+ const getCount = (
+ votes: Array<{ type: string; count: number }>,
+ type: string,
+ ) => votes.find((v) => v.type === type)?.count ?? 0;
+
+ // 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 = votesByOption.get(option.id) ?? [];
+ const yesCount = getCount(votes, "yes");
+ const ifNeedBeCount = getCount(votes, "ifNeedBe");
+ const score = (yesCount + ifNeedBeCount) * 1000 + yesCount;
+
+ return {
+ id: option.id,
+ startTime: option.startTime,
+ 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 {
+ pollId: poll.id,
+ participantCount: poll._count.participants,
+ options,
+ highScore,
+ };
+}
+
+export async function getPollParticipants({
+ pollId,
+ spaceId,
+}: {
+ pollId: string;
+ spaceId: string;
+}) {
+ 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,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ },
+ },
+ });
+
+ if (!poll) {
+ return null;
+ }
+
+ return {
+ pollId: poll.id,
+ participants: poll.participants,
+ };
+}
+
type PollFilters = {
status?: PollStatus;
page?: number;