Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add close poll endpoint to private API (#2738)
Luke Vellab1634e75192c
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.tsindex aa240709d..ac3b80d71 100644--- a/apps/web/src/app/api/private/[...route]/route.test.ts+++ b/apps/web/src/app/api/private/[...route]/route.test.ts@@ -5,6 +5,7 @@ vi.mock("server-only", () => ({}));const mockDeletePoll = vi.fn();const mockCreatePoll = vi.fn();+const mockClosePoll = vi.fn();const mockGetPollResults = vi.fn();const mockGetPollParticipants = vi.fn();const mockListPolls = vi.fn();@@ -12,6 +13,7 @@ const mockListPolls = vi.fn();vi.mock("@/features/poll/mutations", () => ({deletePoll: (...args: unknown[]) => mockDeletePoll(...args),createPoll: (...args: unknown[]) => mockCreatePoll(...args),+ closePoll: (...args: unknown[]) => mockClosePoll(...args),}));vi.mock("@/features/poll/data", () => ({@@ -60,7 +62,10 @@ vi.mock("@/lib/kv", () => ({import { prisma } from "@rallly/database";import { after } from "next/server";import { hashApiKey, verifyApiKey } from "@/features/api-keys/utils";-import { createPollRequestExamples } from "../examples";+import {+ createPollRequestExamples,+ patchPollRequestExamples,+} from "../examples";import {createPollInputSchema,createPollSuccessResponseSchema,@@ -69,6 +74,7 @@ import {getPollResultsSuccessResponseSchema,getPollSuccessResponseSchema,listPollsSuccessResponseSchema,+ patchPollSuccessResponseSchema,} from "../schemas";import { RATE_LIMIT_PER_MINUTE } from "../utils/rate-limit";import { app } from "./route";@@ -735,6 +741,25 @@ describe("Private API - /polls", () => {}});+ it("should document the close poll transition on PATCH /polls/{pollId}", async () => {+ const res = await app.request("/api/private/openapi");++ expect(res.status).toBe(200);+ const json = await res.json();+ const operation = json.paths["/api/private/polls/{pollId}"].patch;++ expect(operation.summary).toBeDefined();+ expect(operation.description).toContain("closed");+ expect(Object.keys(operation.responses)).toEqual(+ expect.arrayContaining(["200", "403", "404", "422", "429"]),+ );++ const media = operation.requestBody.content["application/json"];+ expect(Object.keys(media.examples)).toEqual(+ Object.keys(patchPollRequestExamples),+ );+ });+it("should return docs page", async () => {const res = await app.request("/api/private/docs");@@ -743,6 +768,126 @@ describe("Private API - /polls", () => {});});+ describe("Patch poll (close)", () => {+ const closedPoll = {+ id: "test-poll-id",+ title: "Test Poll",+ description: null,+ location: null,+ timeZone: null,+ status: "closed",+ createdAt: new Date("2025-01-10T12:00:00Z"),+ user: { name: "Test User", image: null },+ options: [],+ };++ it("should close an open poll", async () => {+ mockClosePoll.mockResolvedValue(closedPoll);++ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed" }),+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(patchPollSuccessResponseSchema, json);+ expect(json.data.id).toBe("test-poll-id");+ expect(json.data.status).toBe("closed");++ expect(mockClosePoll).toHaveBeenCalledWith({+ pollId: "test-poll-id",+ spaceId: "test-space-id",+ });+ });++ it("should be idempotent when the poll is already closed", async () => {+ mockClosePoll.mockResolvedValue(closedPoll);++ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed" }),+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expect(json.data.status).toBe("closed");+ });++ it("should return 404 when the poll is not found", async () => {+ mockClosePoll.mockResolvedValue(null);++ const res = await app.request("/api/private/polls/nonexistent-poll", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed" }),+ });++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ expect(mockClosePoll).toHaveBeenCalled();+ });++ it.each([+ "open",+ "scheduled",+ "canceled",+ ])("should return 422 when transitioning to %s", async (status) => {+ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status }),+ });++ expect(res.status).toBe(422);+ const json = await res.json();+ expect(json.error.code).toBe("TRANSITION_NOT_AVAILABLE");+ expect(mockClosePoll).not.toHaveBeenCalled();+ });++ it("should return 400 for an unknown status value", async () => {+ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "archived" }),+ });++ expect(res.status).toBe(400);+ expect(mockClosePoll).not.toHaveBeenCalled();+ });++ it("should return 401 without authorization", async () => {+ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed" }),+ });++ expect(res.status).toBe(401);+ expect(mockClosePoll).not.toHaveBeenCalled();+ });+ });+describe("Delete poll", () => {it("should delete a poll", async () => {mockDeletePoll.mockResolvedValue({ id: "test-poll-id" });diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.tsindex ffcc97cee..def4af933 100644--- a/apps/web/src/app/api/private/[...route]/route.ts+++ b/apps/web/src/app/api/private/[...route]/route.ts@@ -15,10 +15,13 @@ import {getPollResults,listPolls,} from "@/features/poll/data";-import { createPoll, deletePoll } from "@/features/poll/mutations";+import { closePoll, createPoll, deletePoll } from "@/features/poll/mutations";import type { AuthorizedSpaceId } from "@/features/space/types";import { isMaintenanceModeEnabled } from "@/lib/maintenance";-import { createPollRequestExamples } from "../examples";+import {+ createPollRequestExamples,+ patchPollRequestExamples,+} from "../examples";import {createPollInputSchema,createPollSuccessResponseSchema,@@ -29,6 +32,8 @@ import {getPollSuccessResponseSchema,listPollsQuerySchema,listPollsSuccessResponseSchema,+ patchPollInputSchema,+ patchPollSuccessResponseSchema,} from "../schemas";import { spaceApiKeyAuth } from "../utils/api-key";import { apiError } from "../utils/poll";@@ -163,6 +168,15 @@ async function buildOpenApiSpec() {}}+ const patchPollRequestBody =+ spec.paths["/api/private/polls/{pollId}"]?.patch?.requestBody;+ if (patchPollRequestBody && "content" in patchPollRequestBody) {+ const media = patchPollRequestBody.content?.["application/json"];+ if (media) {+ media.examples = patchPollRequestExamples;+ }+ }+return spec;}@@ -513,6 +527,84 @@ app.get(},);+app.patch(+ "/polls/:pollId",+ spaceApiKeyAuth,+ rateLimit,+ describeRoute({+ tags: ["Polls"],+ summary: "Update a poll",+ description: [+ 'Updates a poll\'s status. Currently the only supported transition is closing a poll by sending `{ "status": "closed" }`.',+ "",+ "Close a poll once you have picked a date or the poll is no longer needed. Closing is non-destructive — the poll and its responses are preserved — but the results become final and participants can no longer vote. Consumers polling `GET /polls/:pollId/results` should remove closed polls from their queues.",+ "",+ "Closing is idempotent: closing an already-closed poll returns a `200` with the poll unchanged. The other statuses (`open`, `scheduled`, `canceled`) are not available via the API and return `422`.",+ ].join("\n"),+ security: [{ bearerAuth: [] }],+ responses: {+ 200: {+ description: "Poll updated successfully",+ content: {+ "application/json": {+ schema: resolver(patchPollSuccessResponseSchema),+ },+ },+ },+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 404: {+ description: "Poll not found",+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+ },+ 422: {+ description: "The requested status transition is not available",+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+ },+ },+ }),+ validator("json", patchPollInputSchema),+ async (c) => {+ const { pollId } = c.req.param();+ const { status } = c.req.valid("json");+ const { spaceId } = c.get("apiAuth");++ if (status !== "closed") {+ return c.json(+ apiError(+ "TRANSITION_NOT_AVAILABLE",+ `Transitioning a poll to "${status}" is not available via the API. Only "closed" is supported.`,+ ),+ 422,+ );+ }++ const poll = await closePoll({ pollId, spaceId });++ if (!poll) {+ return c.json(+ apiError(+ "POLL_NOT_FOUND",+ "Poll not found or does not belong to this space.",+ ),+ 404,+ );+ }++ return c.json(+ patchPollSuccessResponseSchema.parse(toPollResponseBody(poll)),+ );+ },+);+app.get("/polls/:pollId/results",spaceApiKeyAuth,@@ -697,4 +789,5 @@ export { app };export const GET = handle(app);export const POST = handle(app);+export const PATCH = handle(app);export const DELETE = handle(app);diff --git a/apps/web/src/app/api/private/examples.ts b/apps/web/src/app/api/private/examples.tsindex fa57b5251..87d86f9fd 100644--- a/apps/web/src/app/api/private/examples.ts+++ b/apps/web/src/app/api/private/examples.ts@@ -1,7 +1,8 @@import type * as z from "zod";-import type { createPollInputSchema } from "./schemas";+import type { createPollInputSchema, patchPollInputSchema } from "./schemas";type CreatePollInput = z.input<typeof createPollInputSchema>;+type PatchPollInput = z.input<typeof patchPollInputSchema>;export const createPollRequestExamples = {datePoll: {@@ -77,3 +78,14 @@ export const createPollRequestExamples = {} satisfies CreatePollInput,},};++export const patchPollRequestExamples = {+ close: {+ summary: "Close a poll",+ description:+ "Set `status` to `closed` once you have picked a date or no longer need the poll. Closing is idempotent and makes the results final.",+ value: {+ status: "closed",+ } satisfies PatchPollInput,+ },+};diff --git a/apps/web/src/app/api/private/schemas.ts b/apps/web/src/app/api/private/schemas.tsindex 54ea213d9..785dba9cc 100644--- a/apps/web/src/app/api/private/schemas.ts+++ b/apps/web/src/app/api/private/schemas.ts@@ -200,6 +200,20 @@ export const getPollSuccessResponseSchema = z}).openapi("GetPollResponse");+export const patchPollInputSchema = z+ .object({+ status: pollStatusSchema.openapi({+ description:+ "The status to transition the poll to. Only `closed` is currently accepted; the other statuses are reserved for future transitions.",+ example: "closed",+ }),+ })+ .openapi("PatchPollInput");++// Updating a poll returns the same shape as get poll+export const patchPollSuccessResponseSchema =+ getPollSuccessResponseSchema.openapi("PatchPollResponse");+// Create poll returns the same shape as get pollexport const createPollSuccessResponseSchema =getPollSuccessResponseSchema.openapi("CreatePollResponse");diff --git a/apps/web/src/features/poll/mutations.test.ts b/apps/web/src/features/poll/mutations.test.tsindex d521d35d7..f6df36ba1 100644--- a/apps/web/src/features/poll/mutations.test.ts+++ b/apps/web/src/features/poll/mutations.test.ts@@ -1,12 +1,19 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { deleteInactivePolls } from "./mutations";+import type { AuthorizedSpaceId } from "@/features/space/types";+import { closePoll, deleteInactivePolls } from "./mutations";-const { mockUpdateMany } = vi.hoisted(() => ({ mockUpdateMany: vi.fn() }));+const { mockUpdateMany, mockFindFirst, mockUpdate } = vi.hoisted(() => ({+ mockUpdateMany: vi.fn(),+ mockFindFirst: vi.fn(),+ mockUpdate: vi.fn(),+}));vi.mock("@rallly/database", () => ({prisma: {poll: {updateMany: mockUpdateMany,+ findFirst: mockFindFirst,+ update: mockUpdate,},},}));@@ -142,3 +149,57 @@ describe("deleteInactivePolls", () => {);});});++describe("closePoll", () => {+ const spaceId = "space-1" as AuthorizedSpaceId;++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns null and does not update when the poll is not found", async () => {+ mockFindFirst.mockResolvedValue(null);++ const result = await closePoll({ pollId: "missing", spaceId });++ expect(result).toBeNull();+ expect(mockUpdate).not.toHaveBeenCalled();+ });++ it("closes an open poll with closedReason manual", async () => {+ mockFindFirst.mockResolvedValue({ id: "p1", status: "open" });+ mockUpdate.mockResolvedValue({ id: "p1", status: "closed" });++ const result = await closePoll({ pollId: "p1", spaceId });++ expect(mockUpdate).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { id: "p1" },+ data: { status: "closed", closedReason: "manual" },+ }),+ );+ expect(result).toEqual({ id: "p1", status: "closed" });+ });++ it("is idempotent and does not update an already-closed poll", async () => {+ const closed = { id: "p1", status: "closed" };+ mockFindFirst.mockResolvedValue(closed);++ const result = await closePoll({ pollId: "p1", spaceId });++ expect(mockUpdate).not.toHaveBeenCalled();+ expect(result).toBe(closed);+ });++ it("scopes the lookup to the space and excludes deleted polls", async () => {+ mockFindFirst.mockResolvedValue(null);++ await closePoll({ pollId: "p1", spaceId });++ expect(mockFindFirst).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { id: "p1", spaceId, deletedAt: null },+ }),+ );+ });+});diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.tsindex 899757b31..ca66b4564 100644--- a/apps/web/src/features/poll/mutations.ts+++ b/apps/web/src/features/poll/mutations.ts@@ -1,5 +1,6 @@import "server-only";+import type { Prisma } from "@rallly/database";import { prisma } from "@rallly/database";import { nanoid } from "@rallly/utils/nanoid";import type { AuthorizedSpaceId } from "@/features/space/types";@@ -86,6 +87,69 @@ export const createPoll = async ({return poll;};+const pollResponseSelect = {+ 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",+ },+ },+} satisfies Prisma.PollSelect;++/**+ * Closes a poll manually. Idempotent: closing an already-closed poll returns+ * 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.+ */+export const closePoll = async ({+ pollId,+ spaceId,+}: {+ pollId: string;+ spaceId: AuthorizedSpaceId;+}) => {+ const poll = await prisma.poll.findFirst({+ where: {+ id: pollId,+ spaceId,+ deletedAt: null,+ },+ select: pollResponseSelect,+ });++ if (!poll) {+ return null;+ }++ if (poll.status === "closed") {+ return poll;+ }++ return prisma.poll.update({+ where: { id: pollId },+ data: { status: "closed", closedReason: "manual" },+ select: pollResponseSelect,+ });+};+export const deletePoll = async (pollId: string,spaceId: AuthorizedSpaceId,