Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Align the /api/v1 poll resource shape and status codes (#3233)
Luke Vella00fa5b4cd134
diff --git a/apps/web/src/app/api/v1/[...route]/route.test.ts b/apps/web/src/app/api/v1/[...route]/route.test.tsindex 30be8744b..46aa388e1 100644--- a/apps/web/src/app/api/v1/[...route]/route.test.ts+++ b/apps/web/src/app/api/v1/[...route]/route.test.ts@@ -77,6 +77,7 @@ vi.mock("@/lib/posthog", () => ({import { logger } from "@rallly/logger";import { after } from "next/server";import { hashApiKey, verifyApiKey } from "@/features/api-keys/utils";+import { MAX_POLL_TITLE_LENGTH } from "@/features/poll/schema";import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";import { redis } from "@/lib/kv";import type { FakeRedis } from "../../middleware/fake-redis";@@ -169,8 +170,16 @@ describe("API v1 - /polls", () => {status: "open",kind: "date",createdAt: new Date("2025-01-10T12:00:00Z"),+ updatedAt: new Date("2025-01-10T12:00:00Z"),+ requireParticipantEmail: false,+ hideParticipants: false,+ hideScores: false,+ disableComments: true,+ participantCount: 0,user: {+ id: "test-user-id",name: "Test User",+ email: "[email protected]",image: null,},options: [],@@ -317,7 +326,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);});});@@ -424,7 +433,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);await flushAfterCallbacks();expect(prisma.spaceApiKey.update).toHaveBeenCalledWith({@@ -457,7 +466,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);await flushAfterCallbacks();expect(prisma.spaceApiKey.update).toHaveBeenCalledWith({@@ -481,7 +490,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);const json = await res.json();expectMatchesContract(pollResponseSchema, json);expect(json.data.id).toBe("test-poll-id");@@ -511,6 +520,76 @@ describe("API v1 - /polls", () => {);});+ it("should respond 201 with the settings, organizer and participantCount round-tripped", async () => {+ mockCreatePoll.mockResolvedValueOnce({+ id: "test-poll-id",+ title: "Team offsite",+ description: null,+ location: null,+ timeZone: null,+ status: "open",+ kind: "date",+ createdAt: new Date("2025-01-10T12:00:00Z"),+ updatedAt: new Date("2025-01-10T12:00:00Z"),+ requireParticipantEmail: true,+ hideParticipants: true,+ hideScores: true,+ disableComments: false,+ participantCount: 0,+ user: {+ id: "test-user-id",+ name: "Test User",+ email: "[email protected]",+ image: null,+ },+ options: [],+ });++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team offsite",+ dates: ["2025-01-15"],+ requireEmail: true,+ hideParticipants: true,+ hideScores: true,+ disableComments: false,+ }),+ });++ expect(res.status).toBe(201);+ const json = await res.json();+ expectMatchesContract(pollResponseSchema, json);+ expect(json.data).toMatchObject({+ requireEmail: true,+ hideParticipants: true,+ hideScores: true,+ disableComments: false,+ participantCount: 0,+ updatedAt: "2025-01-10T12:00:00.000Z",+ organizer: {+ id: "test-user-id",+ name: "Test User",+ email: "[email protected]",+ image: null,+ },+ });+ expect(json).not.toHaveProperty("data.user");++ expect(mockCreatePoll).toHaveBeenCalledWith(+ expect.objectContaining({+ requireParticipantEmail: true,+ hideParticipants: true,+ hideScores: true,+ disableComments: false,+ }),+ );+ });+it("should track poll creation with source api and kind date", async () => {const res = await app.request("/api/v1/polls", {method: "POST",@@ -524,7 +603,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);expect(mockTrack).toHaveBeenCalledWith({ id: "test-user-id", isGuest: false },expect.objectContaining({@@ -559,7 +638,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);expect(mockCreatePoll).toHaveBeenCalledWith(expect.objectContaining({title: "Team offsite",@@ -629,7 +708,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);const json = await res.json();expectMatchesContract(pollResponseSchema, json);expect(json.data.id).toBe("test-poll-id");@@ -652,7 +731,18 @@ describe("API v1 - /polls", () => {status: "open",kind: "time",createdAt: new Date("2025-01-10T12:00:00Z"),- user: { name: "Test User", image: null },+ updatedAt: new Date("2025-01-10T12:00:00Z"),+ requireParticipantEmail: false,+ hideParticipants: false,+ hideScores: false,+ disableComments: true,+ participantCount: 0,+ user: {+ id: "test-user-id",+ name: "Test User",+ email: "[email protected]",+ image: null,+ },options: [{id: "opt-1",@@ -678,7 +768,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);expect(mockTrack).toHaveBeenCalledWith({ id: "test-user-id", isGuest: false },expect.objectContaining({@@ -712,7 +802,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);expect(mockCreatePoll).toHaveBeenCalledWith(expect.objectContaining({timeZone: undefined,@@ -765,7 +855,7 @@ describe("API v1 - /polls", () => {}),});- expect(res.status).toBe(200);+ expect(res.status).toBe(201);expect(mockCreatePoll).toHaveBeenCalled();});@@ -933,6 +1023,130 @@ describe("API v1 - /polls", () => {expect(res.status).toBe(400);});+ it("should reject unknown fields such as spaceId instead of ignoring them", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ spaceId: "some-other-space",+ }),+ });++ const json = await expectErrorEnvelope(res, {+ status: 400,+ code: "VALIDATION_ERROR",+ });+ expect(json.error.message).toContain("spaceId");+ expect(mockCreatePoll).not.toHaveBeenCalled();+ });++ it.each([+ {+ level: "organizer",+ body: {+ title: "Test Poll",+ dates: ["2025-01-15"],+ organizer: { email: "[email protected]", name: "Ann" },+ },+ message: 'organizer: Unrecognized key: "name"',+ },+ {+ level: "slots",+ body: {+ title: "Test Poll",+ slots: {+ duration: 30,+ times: ["2025-01-15T09:00:00Z"],+ timeZone: "Europe/London",+ },+ },+ message: 'slots: Unrecognized key: "timeZone"',+ },+ {+ level: "slot generator",+ body: {+ title: "Test Poll",+ slots: {+ duration: 30,+ times: [+ {+ startDate: "2025-01-13",+ endDate: "2025-01-17",+ days: ["mon"],+ startTime: "09:00",+ endTime: "12:00",+ step: 60,+ },+ ],+ },+ },+ // The generator sits in a union with the datetime string, so zod+ // reports the failing entry rather than the offending key.+ message: "slots.times.0: Invalid input",+ },+ ])("should reject unknown fields nested in the $level object", async ({+ body,+ message,+ }) => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify(body),+ });++ const json = await expectErrorEnvelope(res, {+ status: 400,+ code: "VALIDATION_ERROR",+ });+ expect(json.error.message).toContain(message);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ });++ it("should reject a title longer than the maximum length", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "x".repeat(MAX_POLL_TITLE_LENGTH + 1),+ dates: ["2025-01-15"],+ }),+ });++ const json = await expectErrorEnvelope(res, {+ status: 400,+ code: "VALIDATION_ERROR",+ });+ expect(json.error.message).toMatch(/^title: /);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ });++ it("should accept a title at the maximum length", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "x".repeat(MAX_POLL_TITLE_LENGTH),+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(201);+ });+it("should return error when dates array is empty", async () => {const res = await app.request("/api/v1/polls", {method: "POST",@@ -1082,6 +1296,66 @@ describe("API v1 - /polls", () => {}});+ it("should document 201 for create, strict inputs and realistic ID examples", async () => {+ const res = await app.request("/api/v1/openapi");++ expect(res.status).toBe(200);+ const json = await res.json();+ const schemas = json.components.schemas;+ const createResponses = json.paths["/api/v1/polls"].post.responses;++ expect(createResponses["201"]).toBeDefined();+ expect(createResponses["200"]).toBeUndefined();++ expect(schemas.CreatePollInput.additionalProperties).toBe(false);+ expect(schemas.CreatePollInput.properties.spaceId).toBeUndefined();+ expect(schemas.CreatePollInput.properties.title.maxLength).toBe(+ MAX_POLL_TITLE_LENGTH,+ );+ expect(schemas.PatchPollInput.additionalProperties).toBe(false);++ // Input and output use the same setting names and organizer field.+ for (const key of [+ "requireEmail",+ "hideParticipants",+ "hideScores",+ "disableComments",+ ]) {+ expect(schemas.CreatePollInput.properties[key]).toBeDefined();+ expect(schemas.Poll.properties[key]).toBeDefined();+ }+ expect(schemas.Poll.properties.user).toBeUndefined();+ expect(schemas.Poll.properties.organizer).toMatchObject({+ anyOf: expect.arrayContaining([+ { $ref: "#/components/schemas/PollOrganizer" },+ ]),+ });+ expect(schemas.PollOrganizer.properties.email).toBeDefined();+ expect(schemas.Poll.properties.participantCount).toBeDefined();+ expect(schemas.Poll.properties.updatedAt.format).toBe("date-time");+ expect(schemas.ListPollItem).toBeUndefined();+ expect(schemas.ListPollsResponse.properties.data.items).toEqual({+ $ref: "#/components/schemas/Poll",+ });++ // Real IDs carry no prefix: polls are 12-char nanoids, everything else a cuid.+ const nanoidExample = /^[0-9A-Za-z]{12}$/;+ const cuidExample = /^c[a-z0-9]{24}$/;+ expect(schemas.Poll.properties.id.example).toMatch(nanoidExample);+ expect(+ schemas.DeletePollResponse.properties.data.properties.id.example,+ ).toMatch(nanoidExample);+ expect(schemas.TimeOption.properties.id.example).toMatch(cuidExample);+ expect(schemas.DateOption.properties.id.example).toMatch(cuidExample);+ expect(schemas.Participant.properties.id.example).toMatch(cuidExample);+ expect(schemas.ParticipantVote.properties.optionId.example).toMatch(+ cuidExample,+ );+ expect(JSON.stringify(json)).not.toMatch(+ /p_123abc|opt_abc123|participant_abc123|space_abc123/,+ );+ });+it("should serve the spec without a no-store header", async () => {const res = await app.request("/api/v1/openapi");@@ -1106,7 +1380,18 @@ describe("API v1 - /polls", () => {status: "closed",kind: "date",createdAt: new Date("2025-01-10T12:00:00Z"),- user: { name: "Test User", image: null },+ updatedAt: new Date("2025-01-10T12:00:00Z"),+ requireParticipantEmail: false,+ hideParticipants: false,+ hideScores: false,+ disableComments: true,+ participantCount: 4,+ user: {+ id: "test-user-id",+ name: "Test User",+ email: "[email protected]",+ image: null,+ },options: [],};@@ -1189,6 +1474,24 @@ describe("API v1 - /polls", () => {expect(mockClosePoll).not.toHaveBeenCalled();});+ it("should reject unknown fields in the patch body", async () => {+ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed", title: "Renamed" }),+ });++ const json = await expectErrorEnvelope(res, {+ status: 400,+ code: "VALIDATION_ERROR",+ });+ expect(json.error.message).toContain("title");+ expect(mockClosePoll).not.toHaveBeenCalled();+ });+it("should return 400 for an unknown status value", async () => {const res = await app.request("/api/v1/polls/test-poll-id", {method: "PATCH",@@ -1304,8 +1607,16 @@ describe("API v1 - /polls", () => {status: "open",kind: "time",createdAt: new Date("2025-01-10T12:00:00Z"),+ updatedAt: new Date("2025-01-12T08:30:00Z"),+ requireParticipantEmail: true,+ hideParticipants: false,+ hideScores: true,+ disableComments: false,+ participantCount: 5,user: {+ id: "user-1",name: "John Doe",+ email: "[email protected]",image: "https://example.com/avatar.jpg",},options: [@@ -1343,10 +1654,19 @@ describe("API v1 - /polls", () => {expect(json.data.status).toBe("open");expect(json.data.kind).toBe("time");expect(json.data.createdAt).toBe("2025-01-10T12:00:00.000Z");- expect(json.data.user).toEqual({+ expect(json.data.updatedAt).toBe("2025-01-12T08:30:00.000Z");+ expect(json.data.organizer).toEqual({+ id: "user-1",name: "John Doe",+ email: "[email protected]",image: "https://example.com/avatar.jpg",});+ expect(json).not.toHaveProperty("data.user");+ expect(json.data.participantCount).toBe(5);+ expect(json.data.requireEmail).toBe(true);+ expect(json.data.hideParticipants).toBe(false);+ expect(json.data.hideScores).toBe(true);+ expect(json.data.disableComments).toBe(false);expect(json.data.options).toHaveLength(2);expect(json.data.options[0]).toEqual({id: "opt-1",@@ -1400,7 +1720,7 @@ describe("API v1 - /polls", () => {]);});- it("should return poll without user when user is null", async () => {+ it("should return a null organizer when the organizer account is gone", async () => {mockGetPollWithOptions.mockResolvedValue({...mockPoll,user: null,@@ -1415,7 +1735,7 @@ describe("API v1 - /polls", () => {expect(res.status).toBe(200);const json = await res.json();- expect(json.data.user).toBeNull();+ expect(json.data.organizer).toBeNull();});it("should return 404 when poll not found", async () => {@@ -1467,8 +1787,15 @@ describe("API v1 - /polls", () => {status: "open",kind: "time",createdAt: new Date("2025-01-10T12:00:00Z"),+ updatedAt: new Date("2025-01-10T12:00:00Z"),+ requireParticipantEmail: false,+ hideParticipants: false,+ hideScores: false,+ disableComments: true,user: {+ id: "user-1",name: "John Doe",+ email: "[email protected]",image: null,},options: [@@ -1503,6 +1830,8 @@ describe("API v1 - /polls", () => {expect(json.data[0].title).toBe("Team sync");expect(json.data[0].status).toBe("open");expect(json.data[0].participantCount).toBe(3);+ expect(json.data[0].updatedAt).toBe("2025-01-10T12:00:00.000Z");+ expect(json.data[0].organizer.email).toBe("[email protected]");expect(json.data[0].kind).toBe("time");expect(json.data[0].createdAt).toBe("2025-01-10T12:00:00.000Z");expect(json.data[0].options).toEqual([diff --git a/apps/web/src/app/api/v1/[...route]/route.ts b/apps/web/src/app/api/v1/[...route]/route.tsindex 3e85c9526..3e93f33fc 100644--- a/apps/web/src/app/api/v1/[...route]/route.ts+++ b/apps/web/src/app/api/v1/[...route]/route.ts@@ -103,7 +103,18 @@ function toPollResponseBody(poll: {status: string;kind: PollKind;createdAt: Date;- user: { name: string; image: string | null } | null;+ updatedAt: Date;+ requireParticipantEmail: boolean;+ hideParticipants: boolean;+ hideScores: boolean;+ disableComments: boolean;+ participantCount: number;+ user: {+ id: string;+ name: string;+ email: string;+ image: string | null;+ } | null;options: { id: string; startTime: Date; duration: number }[];}) {return {@@ -116,12 +127,20 @@ function toPollResponseBody(poll: {status: poll.status,kind: poll.kind,createdAt: poll.createdAt.toISOString(),- user: poll.user+ updatedAt: poll.updatedAt.toISOString(),+ organizer: poll.user? {+ id: poll.user.id,name: poll.user.name,+ email: poll.user.email,image: poll.user.image,}: null,+ requireEmail: poll.requireParticipantEmail,+ hideParticipants: poll.hideParticipants,+ hideScores: poll.hideScores,+ disableComments: poll.disableComments,+ participantCount: poll.participantCount,options: poll.options.map((option) =>toOptionResponse(poll.kind, option),),@@ -242,7 +261,11 @@ async function buildOpenApiSpec() {"","## Dates and times","",- "Every poll has a `kind`. A `date` poll offers calendar days: each option carries a `date` in `YYYY-MM-DD` format, which is a floating date with no time component and no timezone, so never convert it through a timezone. A `time` poll offers time slots: each option carries a `startTime` as an ISO 8601 instant in UTC and a `duration` in minutes; convert `startTime` into the poll's `timezone` (or the viewer's) for display. Timestamps such as `createdAt` are always ISO 8601 instants in UTC.",+ "Every poll has a `kind`. A `date` poll offers calendar days: each option carries a `date` in `YYYY-MM-DD` format, which is a floating date with no time component and no timezone, so never convert it through a timezone. A `time` poll offers time slots: each option carries a `startTime` as an ISO 8601 instant in UTC and a `duration` in minutes; convert `startTime` into the poll's `timezone` (or the viewer's) for display. Timestamps such as `createdAt` and `updatedAt` are always ISO 8601 instants in UTC.",+ "",+ "## Request bodies",+ "",+ "Request bodies are validated strictly: a field that is not part of the documented schema is rejected with `VALIDATION_ERROR` rather than ignored, so a misspelt setting never silently falls back to its default.","","## Enums","",@@ -258,7 +281,7 @@ async function buildOpenApiSpec() {"","| Status | Code | When |","| --- | --- | --- |",- "| 400 | `VALIDATION_ERROR` | The body or query string did not match the schema, or the body was not valid JSON |",+ "| 400 | `VALIDATION_ERROR` | The body or query string did not match the schema, contained an unknown field, or the body was not valid JSON |","| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` |","| 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space |","| 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |",@@ -330,11 +353,13 @@ app.post("- `slots` — time-based options that share a fixed `duration` in minutes. Each entry in `slots.times` is either an ISO datetime for an explicit slot, or a slot generator that expands into recurring slots within a time window across a date range. Generated slots start every `interval` minutes (defaults to `duration`) and must fit entirely between `startTime` and `endTime`.","","`dates` and `slots` are mutually exclusive, and a poll can have at most 100 options. See the request examples for common scenarios.",+ "",+ "Responds with `201 Created` and the full poll, including the settings and organizer exactly as `GET /polls/:pollId` returns them.",].join("\n"),security: [{ bearerAuth: [] }],responses: {- 200: {- description: "Successful response",+ 201: {+ description: "Poll created",content: {"application/json": {schema: resolver(pollResponseSchema),@@ -473,7 +498,7 @@ app.post(trackPollCreated(poll);- return c.json(pollResponseSchema.parse(toPollResponseBody(poll)));+ return c.json(pollResponseSchema.parse(toPollResponseBody(poll)), 201);}// Process slots (time-based options)@@ -546,7 +571,7 @@ app.post(trackPollCreated(poll);- return c.json(pollResponseSchema.parse(toPollResponseBody(poll)));+ return c.json(pollResponseSchema.parse(toPollResponseBody(poll)), 201);},);@@ -599,10 +624,7 @@ app.get(return c.json(listPollsSuccessResponseSchema.parse({- data: polls.map((poll) => ({- ...toPollResponseBody(poll).data,- participantCount: poll.participantCount,- })),+ data: polls.map((poll) => toPollResponseBody(poll).data),nextCursor,}),);@@ -617,7 +639,7 @@ app.get(tags: ["Polls"],summary: "Get a poll",description:- "Retrieves poll metadata by ID. The poll must belong to the space associated with the API key.",+ "Retrieves a poll by ID with its options, settings, organizer and `participantCount`. The poll must belong to the space associated with the API key. Compare `updatedAt` between reads to notice changes.",security: [{ bearerAuth: [] }],responses: {200: {diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.tsindex 4aad26a97..729264c9f 100644--- a/apps/web/src/app/api/v1/schemas.ts+++ b/apps/web/src/app/api/v1/schemas.ts@@ -1,4 +1,5 @@import * as z from "zod";+import { MAX_POLL_TITLE_LENGTH } from "@/features/poll/schema";import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";import { timezoneSchema } from "@/lib/utils/timezone-schema";@@ -13,7 +14,7 @@ export const timeSchema = z.iso.time().meta({});export const slotGeneratorSchema = z- .object({+ .strictObject({startDate: dateSchema,endDate: dateSchema,days: z.array(z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"])),@@ -41,7 +42,7 @@ export const slotGeneratorSchema = z.meta({ id: "SlotGenerator" });const slotsInputSchema = z- .object({+ .strictObject({duration: z.number().int().min(15).max(1440).meta({description: "Duration in minutes for each time slot",example: 30,@@ -78,9 +79,16 @@ const datesInputSchema = zexample: ["2025-01-15", "2025-01-16", "2025-01-17"],});+// Strict so a misspelt or unsupported field fails loudly instead of being+// silently ignored.export const createPollInputSchema = z- .object({- title: z.string().trim().min(1).meta({ example: "Team sync" }),+ .strictObject({+ title: z+ .string()+ .trim()+ .min(1)+ .max(MAX_POLL_TITLE_LENGTH)+ .meta({ example: "Team sync" }),description: z.string().trim()@@ -105,13 +113,8 @@ export const createPollInputSchema = z"Disable the comments section. Defaults to true: new polls have comments disabled unless this is set to false.",example: false,}),- spaceId: z.string().optional().meta({- description:- "ID of the space to create the poll in. Defaults to user's most recently used space.",- example: "space_abc123",- }),organizer: z- .object({+ .strictObject({email: z.email().meta({description: "Email address of the organizer",example: "[email protected]",@@ -153,7 +156,7 @@ export const errorResponseSchema = zexport const deletePollSuccessResponseSchema = z.object({data: z.object({- id: z.string().meta({ example: "p_123abc" }),+ id: z.string().meta({ example: "Xk3pQ9vLm2Ab" }),deleted: z.literal(true).meta({ example: true }),}),})@@ -172,7 +175,7 @@ export const pollKindSchema = z.enum(["date", "time"]).meta({export const dateOptionSchema = z.object({- id: z.string().meta({ example: "opt_abc123" }),+ id: z.string().meta({ example: "cm5h8x2k40000q9l4f7e2d3an" }),date: z.iso.date().meta({description:"Calendar date in YYYY-MM-DD format. All-day options are floating dates with no time component and no timezone.",@@ -186,7 +189,7 @@ export const dateOptionSchema = zexport const timeOptionSchema = z.object({- id: z.string().meta({ example: "opt_abc123" }),+ id: z.string().meta({ example: "cm5h8x2k40000q9l4f7e2d3an" }),startTime: z.iso.datetime().meta({description: "Start of the slot as an ISO 8601 instant in UTC.",example: "2025-01-15T09:00:00.000Z",@@ -209,19 +212,21 @@ export const pollOptionSchema = z"A poll option. The shape follows the poll's `kind`: a `DateOption` for `date` polls, a `TimeOption` for `time` polls.",});-export const pollUserSchema = z+export const pollOrganizerSchema = z.object({+ id: z.string().meta({ example: "cm3f7d1qa0000t2k9c6b8h4jr" }),name: z.string().meta({ example: "John Doe" }),+ email: z.email().meta({ example: "[email protected]" }),image: z.string().nullable().meta({ example: "https://example.com/avatar.jpg" }),})- .meta({ id: "PollUser" });+ .meta({ id: "PollOrganizer" });const pollSchema = z.object({- id: z.string().meta({ example: "p_123abc" }),+ id: z.string().meta({ example: "Xk3pQ9vLm2Ab" }),title: z.string().meta({ example: "Team sync" }),description: z.string().nullable().meta({example: "Pick a time that works for everyone",@@ -230,15 +235,44 @@ const pollSchema = ztimezone: z.string().nullable().meta({ example: "Europe/London" }),status: pollStatusSchema,kind: pollKindSchema,- createdAt: z.string().datetime().meta({ example: "2025-01-10T12:00:00Z" }),- user: pollUserSchema.nullable().meta({- description: "The poll organizer",+ createdAt: z.iso.datetime().meta({ example: "2025-01-10T12:00:00.000Z" }),+ updatedAt: z.iso.datetime().meta({+ description:+ "When the poll was last modified. Changes when the poll's details, settings or status change.",+ example: "2025-01-12T08:30:00.000Z",+ }),+ organizer: pollOrganizerSchema.nullable().meta({+ description:+ "The space member the poll belongs to. `null` when the organizer's account no longer exists.",+ }),+ requireEmail: z.boolean().meta({+ description: "Whether participants must provide their email address",+ example: false,+ }),+ hideParticipants: z.boolean().meta({+ description:+ "Whether participant names are hidden from other participants",+ example: false,+ }),+ hideScores: z.boolean().meta({+ description: "Whether vote counts are hidden from participants",+ example: false,+ }),+ disableComments: z.boolean().meta({+ description: "Whether the comments section is disabled",+ example: true,+ }),+ participantCount: z.int().nonnegative().meta({+ description: "Number of participants who have responded to the poll",+ example: 3,}),options: z.array(pollOptionSchema),- adminUrl: z.string().meta({ example: "https://example.com/poll/p_123abc" }),+ adminUrl: z+ .string()+ .meta({ example: "https://example.com/poll/Xk3pQ9vLm2Ab" }),inviteUrl: z.string()- .meta({ example: "https://example.com/invite/p_123abc" }),+ .meta({ example: "https://example.com/invite/Xk3pQ9vLm2Ab" }),}).meta({ id: "Poll" });@@ -249,7 +283,7 @@ export const pollResponseSchema = z.meta({ id: "PollResponse" });export const patchPollInputSchema = z- .object({+ .strictObject({status: pollStatusSchema.meta({description:"The status to transition the poll to. Only `closed` is currently accepted; the other statuses are reserved for future transitions.",@@ -266,7 +300,7 @@ export const listPollsQuerySchema = z.object({cursor: z.string().optional().meta({description:"Cursor for pagination. Pass the `nextCursor` value from the previous response to fetch the next page.",- example: "p_123abc",+ example: "Xk3pQ9vLm2Ab",}),limit: z.coerce.number().int().min(1).max(100).default(20).meta({description: "Number of polls to return per page (1-100).",@@ -274,22 +308,13 @@ export const listPollsQuerySchema = z.object({}),});-export const listPollItemSchema = pollSchema- .extend({- participantCount: z.int().nonnegative().meta({- description: "Number of participants who have responded to the poll",- example: 3,- }),- })- .meta({ id: "ListPollItem" });-export const listPollsSuccessResponseSchema = z.object({- data: z.array(listPollItemSchema),+ data: z.array(pollSchema),nextCursor: z.string().nullable().meta({description:"Cursor to fetch the next page. `null` when there are no more results.",- example: "p_123abc",+ example: "Xk3pQ9vLm2Ab",}),}).meta({ id: "ListPollsResponse" });@@ -357,7 +382,7 @@ export const optionResultSchema = zexport const getPollResultsSuccessResponseSchema = z.object({data: z.object({- pollId: z.string().meta({ example: "p_123abc" }),+ pollId: z.string().meta({ example: "Xk3pQ9vLm2Ab" }),kind: pollKindSchema,status: pollStatusSchema.meta({description:@@ -380,17 +405,17 @@ export const getPollResultsSuccessResponseSchema = zexport const participantVoteSchema = z.object({- optionId: z.string().meta({ example: "opt_abc123" }),+ optionId: z.string().meta({ example: "cm5h8x2k40000q9l4f7e2d3an" }),type: voteTypeSchema,}).meta({ id: "ParticipantVote" });export const participantSchema = z.object({- id: z.string().meta({ example: "participant_abc123" }),+ id: z.string().meta({ example: "cm5j2r8wb0003q9l4a1x6p0zt" }),name: z.string().meta({ example: "Jane Smith" }),email: z.string().nullable().meta({ example: "[email protected]" }),- createdAt: z.iso.datetime().meta({ example: "2025-01-10T12:00:00Z" }),+ createdAt: z.iso.datetime().meta({ example: "2025-01-10T12:00:00.000Z" }),votes: z.array(participantVoteSchema).meta({description:"The participant's vote for each option, keyed by `optionId`. An option missing from the list has no recorded vote from this participant.",@@ -402,7 +427,7 @@ export const listParticipantsQuerySchema = z.object({cursor: z.string().optional().meta({description:"Cursor for pagination. Pass the `nextCursor` value from the previous response to fetch the next page.",- example: "participant_abc123",+ example: "cm5j2r8wb0003q9l4a1x6p0zt",}),limit: z.coerce.number().int().min(1).max(100).default(50).meta({description: "Number of participants to return per page (1-100).",@@ -416,7 +441,7 @@ export const getPollParticipantsSuccessResponseSchema = znextCursor: z.string().nullable().meta({description:"Cursor to fetch the next page. `null` when there are no more results.",- example: "participant_abc123",+ example: "cm5j2r8wb0003q9l4a1x6p0zt",}),}).meta({ id: "GetPollParticipantsResponse" });diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.tsindex 0f8c05d26..d4a8cd8a7 100644--- a/apps/web/src/features/poll/data.ts+++ b/apps/web/src/features/poll/data.ts@@ -218,9 +218,16 @@ export async function listPolls({status: true,kind: true,createdAt: true,+ updatedAt: true,+ requireParticipantEmail: true,+ hideParticipants: true,+ hideScores: true,+ disableComments: true,user: {select: {+ id: true,name: true,+ email: true,image: true,},},@@ -521,7 +528,7 @@ export async function getPollWithOptions({pollId: string;spaceId: AuthorizedSpaceId;}) {- return prisma.poll.findFirst({+ const poll = await prisma.poll.findFirst({where: {id: pollId,spaceId,@@ -536,9 +543,16 @@ export async function getPollWithOptions({status: true,kind: true,createdAt: true,+ updatedAt: true,+ requireParticipantEmail: true,+ hideParticipants: true,+ hideScores: true,+ disableComments: true,user: {select: {+ id: true,name: true,+ email: true,image: true,},},@@ -552,6 +566,18 @@ export async function getPollWithOptions({startTime: "asc",},},+ _count: {+ select: {+ participants: true,+ },+ },},});++ if (!poll) {+ return null;+ }++ const { _count, ...rest } = poll;+ return { ...rest, participantCount: _count.participants };}diff --git a/apps/web/src/features/poll/mutations.test.ts b/apps/web/src/features/poll/mutations.test.tsindex 9fe751ae9..d712138d9 100644--- a/apps/web/src/features/poll/mutations.test.ts+++ b/apps/web/src/features/poll/mutations.test.ts@@ -177,9 +177,16 @@ describe("closePoll", () => {expect(mockUpdate).not.toHaveBeenCalled();});+ const openPoll = { id: "p1", status: "open", _count: { participants: 2 } };+ const closedPoll = {+ id: "p1",+ status: "closed",+ _count: { participants: 2 },+ };+it("closes an open poll with closedReason manual", async () => {- mockFindFirst.mockResolvedValue({ id: "p1", status: "open" });- mockUpdate.mockResolvedValue({ id: "p1", status: "closed" });+ mockFindFirst.mockResolvedValue(openPoll);+ mockUpdate.mockResolvedValue(closedPoll);const result = await closePoll({ pollId: "p1", spaceId });@@ -189,23 +196,22 @@ describe("closePoll", () => {data: { status: "closed", closedReason: "manual" },}),);- expect(result).toEqual({ id: "p1", status: "closed" });+ expect(result).toEqual({ id: "p1", status: "closed", participantCount: 2 });});it("is idempotent and does not update an already-closed poll", async () => {- const closed = { id: "p1", status: "closed" };- mockFindFirst.mockResolvedValue(closed);+ mockFindFirst.mockResolvedValue(closedPoll);const result = await closePoll({ pollId: "p1", spaceId });expect(mockUpdate).not.toHaveBeenCalled();expect(mockActivityCreateMany).not.toHaveBeenCalled();- expect(result).toBe(closed);+ expect(result).toEqual({ id: "p1", status: "closed", participantCount: 2 });});it("records a poll_closed activity alongside the close", async () => {- mockFindFirst.mockResolvedValue({ id: "p1", status: "open" });- mockUpdate.mockResolvedValue({ id: "p1", status: "closed" });+ mockFindFirst.mockResolvedValue(openPoll);+ mockUpdate.mockResolvedValue(closedPoll);await closePoll({ pollId: "p1", spaceId, userId: "u1" });diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.tsindex e2567abaa..4fc24c231 100644--- a/apps/web/src/features/poll/mutations.ts+++ b/apps/web/src/features/poll/mutations.ts@@ -25,6 +25,52 @@ export type CreatePollParams = {spaceId: AuthorizedSpaceId;};+// The shape the API routes serialize; keep it in sync with+// `getPollWithOptions` in data.ts so create, close and get return one poll.+const pollResponseSelect = {+ id: true,+ title: true,+ description: true,+ location: true,+ timeZone: true,+ status: true,+ kind: true,+ createdAt: true,+ updatedAt: true,+ requireParticipantEmail: true,+ hideParticipants: true,+ hideScores: true,+ disableComments: true,+ user: {+ select: {+ id: true,+ name: true,+ email: true,+ image: true,+ },+ },+ options: {+ select: {+ id: true,+ startTime: true,+ duration: true,+ },+ orderBy: {+ startTime: "asc",+ },+ },+ _count: {+ select: {+ participants: true,+ },+ },+} satisfies Prisma.PollSelect;++const toPollResponse = <T extends { _count: { participants: number } }>({+ _count,+ ...poll+}: T) => ({ ...poll, participantCount: _count.participants });+export const createPoll = async ({userId,title,@@ -57,33 +103,7 @@ export const createPoll = async ({kind,options: { createMany: { data: options } },},- select: {- id: true,- title: true,- description: true,- location: true,- timeZone: true,- status: true,- kind: true,- createdAt: true,- disableComments: true,- user: {- select: {- name: true,- image: true,- },- },- options: {- select: {- id: true,- startTime: true,- duration: true,- },- orderBy: {- startTime: "asc",- },- },- },+ select: pollResponseSelect,});await recordPollActivities(tx, [@@ -98,36 +118,9 @@ export const createPoll = async ({return poll;});- return poll;+ return toPollResponse(poll);};-const pollResponseSelect = {- id: true,- title: true,- description: true,- location: true,- timeZone: true,- status: true,- kind: 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@@ -161,7 +154,7 @@ export const closePoll = async ({}if (poll.status === "closed") {- return poll;+ return toPollResponse(poll);}const closedPoll = await tx.poll.update({@@ -179,7 +172,7 @@ export const closePoll = async ({},]);- return closedPoll;+ return toPollResponse(closedPoll);});};diff --git a/apps/web/src/features/poll/schema.ts b/apps/web/src/features/poll/schema.tsindex 7e73ab32a..da8239b2b 100644--- a/apps/web/src/features/poll/schema.ts+++ b/apps/web/src/features/poll/schema.ts@@ -5,6 +5,7 @@ import * as z from "zod";// DESCRIPTION around 8192 chars. 8000 sits just under that and covers every// existing poll — including long institutional event invites — so no real// content is rejected.+export const MAX_POLL_TITLE_LENGTH = 255;export const MAX_POLL_DESCRIPTION_LENGTH = 8000;// Comment content ships in the new-comment notification email, so it must be