Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add GET /polls/{pollId}/participants/{participantId} with availability (#3342)
Luke Vellac4aa04f5f7cc
diff --git a/apps/docs/api-reference/changelog.mdx b/apps/docs/api-reference/changelog.mdxindex 9bb3d7161..61f4e4200 100644--- a/apps/docs/api-reference/changelog.mdx+++ b/apps/docs/api-reference/changelog.mdx@@ -3,6 +3,11 @@ title: "Changelog"description: "Changes to the API, newest first."---+<Update label="2026-09-22">+- `GET /polls/{pollId}/participants/{participantId}` returns one participant. A missing participant on an existing poll is `404` with `PARTICIPANT_NOT_FOUND`.+- Participants now carry `availability`: one `{ start, end, allDay, modifiers }` span per option they can make, in start order, on both the list and the single-participant endpoint. A span matches an option of the poll by its time; `end` is exclusive; `ifNeedBe` is a modifier.+</Update>+<Update label="v1">Initial stable release under `/v1`.diff --git a/apps/docs/api-reference/errors.mdx b/apps/docs/api-reference/errors.mdxindex 6c3eb41ea..06bbc52d6 100644--- a/apps/docs/api-reference/errors.mdx+++ b/apps/docs/api-reference/errors.mdx@@ -29,6 +29,7 @@ Every failure is `application/json` with the same shape:| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription || 404 | `NOT_FOUND` | No route matches the method and path || 404 | `POLL_NOT_FOUND` | The poll does not exist or belongs to another space |+| 404 | `PARTICIPANT_NOT_FOUND` | The participant does not exist or belongs to another poll || 429 | `RATE_LIMIT_EXCEEDED` | A rate limit window is exhausted; see [Rate limits](/api-reference/rate-limits) || 503 | `SERVICE_UNAVAILABLE` | Maintenance, or the rate limit store cannot be reached || 500 | `INTERNAL_ERROR` | Unexpected failure; the request id is logged |diff --git a/apps/docs/api-reference/introduction.mdx b/apps/docs/api-reference/introduction.mdxindex cdc766961..461842465 100644--- a/apps/docs/api-reference/introduction.mdx+++ b/apps/docs/api-reference/introduction.mdx@@ -24,8 +24,9 @@ https://api.rallly.co/v1## Conventions- Requests and responses are JSON. Send `Content-Type: application/json` with a body.-- List endpoints return the items in `data`. `GET /polls` is paginated: it returns a `nextCursor` beside `data`; pass it as the `cursor` query parameter for the next page, and it is `null` on the last page. `GET /polls/:pollId/participants` returns every participant in one response.+- List endpoints return the items in `data`. `GET /polls` is paginated: it returns a `nextCursor` beside `data`; pass it as the `cursor` query parameter for the next page, and it is `null` on the last page. `GET /polls/:pollId/participants` returns every participant in one response, and `GET /polls/:pollId/participants/:participantId` returns one.- Timestamps are ISO 8601 instants in UTC. A `date` poll's options carry a floating `YYYY-MM-DD` date with no timezone; a `time` poll's options carry a `startTime` instant and a `duration` in minutes.+- A participant's `availability` is a list of spans, `{ start, end, allDay, modifiers }`. A span matches an option by its time: `start` is the option's `startTime`, or midnight UTC of its `date` with `allDay: true`. `end` is exclusive.- Request bodies are validated strictly. A field that is not in the schema is rejected rather than ignored, so a misspelt setting never silently falls back to its default.## Machine readable specdiff --git a/apps/docs/api-reference/openapi.json b/apps/docs/api-reference/openapi.jsonindex 356327494..5b8debf3a 100644--- a/apps/docs/api-reference/openapi.json+++ b/apps/docs/api-reference/openapi.json@@ -2,7 +2,7 @@"openapi": "3.1.0","info": {"title": "Rallly API",- "description": "## Versioning\n\n`v1` is stable. Additive changes (new endpoints, new optional fields) may land on this path at any time; breaking changes only arrive under a new version prefix.\n\n## Rate limits\n\nAll endpoints share two limits per space: **60 requests per minute** and **5000 requests per day**. Both are fixed windows that open with the first request and reset when they expire. Both limits are per space, not per API key, so creating additional keys does not increase throughput.\n\nEvery response from an authenticated request includes the standard `RateLimit-*` headers. Responses sent before the limiter runs (`401`, `403`, and the maintenance `503`) do not. `RateLimit-Policy` lists both limits; `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` describe whichever limit is closest to being exhausted. When either limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.\n\nIf the rate limit store cannot be reached the API fails closed and responds with `503 Service Unavailable`, a `SERVICE_UNAVAILABLE` error body, and a `Retry-After` header.\n\n## Dates and times\n\nEvery 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.\n\n## Request bodies\n\nRequest 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.\n\n## Enums\n\nVote types are an open set. The built-in values are `yes`, `ifNeedBe` and `no`; new types may be added without a version change, so clients must tolerate values they do not recognise. `status` and `kind` are closed sets.\n\n## Lists\n\nList endpoints return the items in `data`. `GET /polls` is paginated: it returns a `nextCursor` beside `data`; pass it as the `cursor` query parameter to fetch the next page, and it is `null` on the last page. `GET /polls/:pollId/participants` returns every participant in one response.\n\n## Errors\n\nEvery failure is `application/json` with the shape `{ \"error\": { \"code\", \"message\" } }`. `code` is stable and safe to branch on; `message` is human-readable and may change. `VALIDATION_ERROR` messages name each offending field.\n\n| Status | Code | When |\n| --- | --- | --- |\n| 400 | `VALIDATION_ERROR` | The body or query string did not match the schema, contained an unknown field, or the body was not valid JSON |\n| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` |\n| 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space |\n| 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |\n| 400 | `INAPPROPRIATE_CONTENT` | The title, description or location was flagged by content moderation |\n| 401 | `UNAUTHORIZED` | The API key is missing, invalid, expired or revoked, or its owner is banned |\n| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription |\n| 404 | `NOT_FOUND` | No route matches the method and path |\n| 404 | `POLL_NOT_FOUND` | The poll does not exist or belongs to another space |\n| 429 | `RATE_LIMIT_EXCEEDED` | A rate limit window is exhausted |\n| 503 | `SERVICE_UNAVAILABLE` | Maintenance, or the rate limit store cannot be reached |\n| 500 | `INTERNAL_ERROR` | Unexpected failure; the request id is logged |",+ "description": "## Versioning\n\n`v1` is stable. Additive changes (new endpoints, new optional fields) may land on this path at any time; breaking changes only arrive under a new version prefix.\n\n## Rate limits\n\nAll endpoints share two limits per space: **60 requests per minute** and **5000 requests per day**. Both are fixed windows that open with the first request and reset when they expire. Both limits are per space, not per API key, so creating additional keys does not increase throughput.\n\nEvery response from an authenticated request includes the standard `RateLimit-*` headers. Responses sent before the limiter runs (`401`, `403`, and the maintenance `503`) do not. `RateLimit-Policy` lists both limits; `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` describe whichever limit is closest to being exhausted. When either limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.\n\nIf the rate limit store cannot be reached the API fails closed and responds with `503 Service Unavailable`, a `SERVICE_UNAVAILABLE` error body, and a `Retry-After` header.\n\n## Dates and times\n\nEvery 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.\n\n## Request bodies\n\nRequest 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.\n\n## Enums\n\nVote types are an open set. The built-in values are `yes`, `ifNeedBe` and `no`; new types may be added without a version change, so clients must tolerate values they do not recognise. `status` and `kind` are closed sets.\n\n## Lists\n\nList endpoints return the items in `data`. `GET /polls` is paginated: it returns a `nextCursor` beside `data`; pass it as the `cursor` query parameter to fetch the next page, and it is `null` on the last page. `GET /polls/:pollId/participants` returns every participant in one response.\n\n## Errors\n\nEvery failure is `application/json` with the shape `{ \"error\": { \"code\", \"message\" } }`. `code` is stable and safe to branch on; `message` is human-readable and may change. `VALIDATION_ERROR` messages name each offending field.\n\n| Status | Code | When |\n| --- | --- | --- |\n| 400 | `VALIDATION_ERROR` | The body or query string did not match the schema, contained an unknown field, or the body was not valid JSON |\n| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` |\n| 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space |\n| 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |\n| 400 | `INAPPROPRIATE_CONTENT` | The title, description or location was flagged by content moderation |\n| 401 | `UNAUTHORIZED` | The API key is missing, invalid, expired or revoked, or its owner is banned |\n| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription |\n| 404 | `NOT_FOUND` | No route matches the method and path |\n| 404 | `POLL_NOT_FOUND` | The poll does not exist or belongs to another space |\n| 404 | `PARTICIPANT_NOT_FOUND` | The participant does not exist or belongs to another poll |\n| 429 | `RATE_LIMIT_EXCEEDED` | A rate limit window is exhausted |\n| 503 | `SERVICE_UNAVAILABLE` | Maintenance, or the rate limit store cannot be reached |\n| 500 | `INTERNAL_ERROR` | Unexpected failure; the request id is logged |","version": "1.0.0"},"servers": [@@ -862,13 +862,59 @@"type": "string","format": "date-time","example": "2025-01-10T12:00:00.000Z"+ },+ "availability": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/AvailabilitySpan"+ },+ "description": "When the participant is available: one span per option they can make, in start order, not merged. Options they cannot make, or did not answer, are absent. Each span matches an option of the poll by its time."}},"required": ["id","name","email",- "createdAt"+ "createdAt",+ "availability"+ ]+ },+ "AvailabilitySpan": {+ "type": "object",+ "properties": {+ "start": {+ "type": "string",+ "format": "date-time",+ "description": "Start of the span, inclusive, as a UTC instant.",+ "example": "2025-01-15T09:00:00.000Z"+ },+ "end": {+ "type": "string",+ "format": "date-time",+ "description": "End of the span, exclusive, as a UTC instant: a 30 minute slot starting at 09:00 ends at 09:30, and the instant 09:30 is not in it.",+ "example": "2025-01-15T09:30:00.000Z"+ },+ "allDay": {+ "type": "boolean",+ "description": "True for a whole calendar day. The day is a floating date with no timezone, given as `start` at 00:00:00Z on that date and `end` at 00:00:00Z on the next; read the date from `start` and ignore the time of day.",+ "example": false+ },+ "modifiers": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Qualifiers on the availability. `ifNeedBe` means the participant can make it but would rather not. New modifiers may be added without a version change; one you do not recognise still leaves the span available.",+ "example": [+ "ifNeedBe"+ ]+ }+ },+ "required": [+ "start",+ "end",+ "allDay",+ "modifiers"]},"GetPollParticipantsResponse": {@@ -885,6 +931,17 @@"data"]},+ "GetPollParticipantResponse": {+ "type": "object",+ "properties": {+ "data": {+ "$ref": "#/components/schemas/Participant"+ }+ },+ "required": [+ "data"+ ]+ },"DeletePollResponse": {"type": "object","properties": {@@ -1588,7 +1645,7 @@"Polls"],"summary": "List poll participants",- "description": "Lists every participant of a poll in one response, oldest response first. The poll must belong to the space associated with the API key.\n\nPer-option answers are not included; use the results endpoint for aggregate availability.",+ "description": "Lists every participant of a poll in one response, oldest response first, each with their availability. The poll must belong to the space associated with the API key.\n\nFor aggregate counts per option use the results endpoint.","security": [{"bearerAuth": []@@ -1691,6 +1748,125 @@}]}+ },+ "/v1/polls/{pollId}/participants/{participantId}": {+ "get": {+ "operationId": "getV1PollsByPollIdParticipantsByParticipantId",+ "tags": [+ "Polls"+ ],+ "summary": "Get a poll participant",+ "description": "Returns one participant of a poll with their availability. The poll must belong to the space associated with the API key. This is the endpoint to call from a `poll.participant.*` webhook.",+ "security": [+ {+ "bearerAuth": []+ }+ ],+ "responses": {+ "200": {+ "description": "Successful response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetPollParticipantResponse"+ }+ }+ }+ },+ "401": {+ "description": "The API key is missing, invalid, expired or revoked, or its owner is banned. Includes a `WWW-Authenticate` header.",+ "headers": {+ "WWW-Authenticate": {+ "description": "The bearer challenge, per RFC 6750.",+ "schema": {+ "type": "string"+ }+ }+ },+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "The space associated with the API key does not have a Pro subscription",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "Poll not found (`POLL_NOT_FOUND`) or participant not found (`PARTICIPANT_NOT_FOUND`)",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "429": {+ "description": "Rate limit exceeded. Includes a `Retry-After` header indicating how many seconds to wait before retrying.",+ "headers": {+ "Retry-After": {+ "description": "Seconds to wait before retrying the request.",+ "schema": {+ "type": "integer"+ }+ }+ },+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "503": {+ "description": "The API is temporarily unavailable, for maintenance or because the rate limit store cannot be reached. Includes a `Retry-After` header. Maintenance responses are sent before the rate limiter runs and carry no `RateLimit-*` headers.",+ "headers": {+ "Retry-After": {+ "description": "Seconds to wait before retrying the request.",+ "schema": {+ "type": "integer"+ }+ }+ },+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ },+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "in": "path",+ "name": "pollId",+ "required": true+ },+ {+ "schema": {+ "type": "string"+ },+ "in": "path",+ "name": "participantId",+ "required": true+ }+ ]+ }}}}diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 8334e7309..ca0d50036 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -96,7 +96,8 @@"GET /v1/polls/{pollId}","DELETE /v1/polls/{pollId}","GET /v1/polls/{pollId}/results",- "GET /v1/polls/{pollId}/participants"+ "GET /v1/polls/{pollId}/participants",+ "GET /v1/polls/{pollId}/participants/{participantId}"]}]diff --git a/apps/web/src/app/api/v1/[...route]/route.test.ts b/apps/web/src/app/api/v1/[...route]/route.test.tsindex e67228788..0b0bb1ee1 100644--- a/apps/web/src/app/api/v1/[...route]/route.test.ts+++ b/apps/web/src/app/api/v1/[...route]/route.test.ts@@ -7,6 +7,7 @@ const mockDeletePoll = vi.fn();const mockCreatePoll = vi.fn();const mockGetPollResults = vi.fn();const mockGetPollParticipants = vi.fn();+const mockGetPollParticipant = vi.fn();const mockListPolls = vi.fn();const mockGetPollWithOptions = vi.fn();const mockGetSpaceMemberByEmail = vi.fn();@@ -25,6 +26,7 @@ vi.mock("@/features/poll/mutations", () => ({vi.mock("@/features/poll/data", () => ({getPollResults: (...args: unknown[]) => mockGetPollResults(...args),getPollParticipants: (...args: unknown[]) => mockGetPollParticipants(...args),+ getPollParticipant: (...args: unknown[]) => mockGetPollParticipant(...args),listPolls: (...args: unknown[]) => mockListPolls(...args),getPollWithOptions: (...args: unknown[]) => mockGetPollWithOptions(...args),}));@@ -90,6 +92,7 @@ import {createPollInputSchema,deletePollSuccessResponseSchema,errorResponseSchema,+ getPollParticipantSuccessResponseSchema,getPollParticipantsSuccessResponseSchema,getPollResultsSuccessResponseSchema,listPollsSuccessResponseSchema,@@ -2682,6 +2685,7 @@ describe("API v1 - /polls", () => {it("should mark every key-scoped response no-store", async () => {mockGetPollParticipants.mockResolvedValue({pollId: "test-poll-id",+ kind: "time",participants: [],});mockListPolls.mockResolvedValue({ polls: [], nextCursor: null });@@ -2709,18 +2713,57 @@ describe("API v1 - /polls", () => {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: "ifNeedBe",+ option: {+ startTime: new Date("2025-01-16T09:00:00Z"),+ duration: 30,+ },+ },+ {+ type: "no",+ option: {+ startTime: new Date("2025-01-17T09:00:00Z"),+ duration: 30,+ },+ },+ ],},{id: "participant-2",name: "Bob",email: null,createdAt: new Date("2025-01-10T11:00:00Z"),+ votes: [],+ },+ ];+ const aliceAvailability = [+ {+ start: "2025-01-15T09:00:00.000Z",+ end: "2025-01-15T09:30:00.000Z",+ allDay: false,+ modifiers: [],+ },+ {+ start: "2025-01-16T09:00:00.000Z",+ end: "2025-01-16T09:30:00.000Z",+ allDay: false,+ modifiers: ["ifNeedBe"],},];it("should return participants in the list shape", async () => {mockGetPollParticipants.mockResolvedValue({pollId: "test-poll-id",+ kind: "time",participants,});@@ -2741,7 +2784,9 @@ describe("API v1 - /polls", () => {name: "Alice",email: "[email protected]",createdAt: "2025-01-10T10:00:00.000Z",+ availability: aliceAvailability,});+ expect(json.data[1].availability).toEqual([]);expect(json.data[1].email).toBeNull();expect(json).not.toHaveProperty("nextCursor");@@ -2754,6 +2799,7 @@ describe("API v1 - /polls", () => {it("should return every participant and ignore pagination query parameters", async () => {mockGetPollParticipants.mockResolvedValue({pollId: "test-poll-id",+ kind: "time",participants,});@@ -2784,6 +2830,7 @@ describe("API v1 - /polls", () => {it("should return empty array when no participants", async () => {mockGetPollParticipants.mockResolvedValue({pollId: "test-poll-id",+ kind: "time",participants: [],});@@ -2824,6 +2871,96 @@ describe("API v1 - /polls", () => {});});+ describe("Get poll participant", () => {+ const participant = {+ 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-15T00:00:00Z"), duration: 0 },+ },+ ],+ };+ const authed = { Authorization: `Bearer ${testApiKey}` };++ it("should return the participant with their availability", async () => {+ mockGetPollParticipant.mockResolvedValue({+ poll: { id: "test-poll-id", kind: "date" },+ participant,+ });++ const res = await app.request(+ "/v1/polls/test-poll-id/participants/participant-1",+ { method: "GET", headers: authed },+ );++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(getPollParticipantSuccessResponseSchema, json);+ expect(json.data).toEqual({+ id: "participant-1",+ name: "Alice",+ email: "[email protected]",+ createdAt: "2025-01-10T10:00:00.000Z",+ availability: [+ {+ start: "2025-01-15T00:00:00.000Z",+ end: "2025-01-16T00:00:00.000Z",+ allDay: true,+ modifiers: [],+ },+ ],+ });+ expect(mockGetPollParticipant).toHaveBeenCalledWith({+ pollId: "test-poll-id",+ participantId: "participant-1",+ spaceId: "test-space-id",+ });+ });++ it("should return POLL_NOT_FOUND when the poll is missing", async () => {+ mockGetPollParticipant.mockResolvedValue({+ poll: null,+ participant: null,+ });++ const res = await app.request(+ "/v1/polls/nonexistent-poll/participants/participant-1",+ { method: "GET", headers: authed },+ );++ expect(res.status).toBe(404);+ expect((await res.json()).error.code).toBe("POLL_NOT_FOUND");+ });++ it("should return PARTICIPANT_NOT_FOUND when the poll exists but the participant does not", async () => {+ mockGetPollParticipant.mockResolvedValue({+ poll: { id: "test-poll-id", kind: "time" },+ participant: null,+ });++ const res = await app.request(+ "/v1/polls/test-poll-id/participants/nonexistent",+ { method: "GET", headers: authed },+ );++ expect(res.status).toBe(404);+ expect((await res.json()).error.code).toBe("PARTICIPANT_NOT_FOUND");+ });++ it("should return 401 without authorization", async () => {+ const res = await app.request(+ "/v1/polls/test-poll-id/participants/participant-1",+ { method: "GET" },+ );++ expect(res.status).toBe(401);+ });+ });+describe("Error envelope", () => {const authed = { Authorization: `Bearer ${testApiKey}` };diff --git a/apps/web/src/app/api/v1/[...route]/route.ts b/apps/web/src/app/api/v1/[...route]/route.tsindex 36c536bbe..28931e9c4 100644--- a/apps/web/src/app/api/v1/[...route]/route.ts+++ b/apps/web/src/app/api/v1/[...route]/route.ts@@ -12,12 +12,14 @@ import { after } from "next/server";import { moderateContent } from "@/features/moderation/mutations";import { MAX_POLL_OPTIONS } from "@/features/poll/constants";import {+ getPollParticipant,getPollParticipants,getPollResults,getPollWithOptions,listPolls,} from "@/features/poll/data";import { createPoll, deletePoll } from "@/features/poll/mutations";+import { toAvailabilitySpans } from "@/features/poll/utils";import { getSpaceMemberByEmail } from "@/features/space/member/data";import type { SpaceTier } from "@/features/space/schema";import type { AuthorizedSpaceId } from "@/features/space/types";@@ -43,6 +45,7 @@ import {createPollInputSchema,deletePollSuccessResponseSchema,errorResponseSchema,+ getPollParticipantSuccessResponseSchema,getPollParticipantsSuccessResponseSchema,getPollResultsSuccessResponseSchema,listPollsQuerySchema,@@ -306,6 +309,7 @@ async function buildOpenApiSpec() {"| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription |","| 404 | `NOT_FOUND` | No route matches the method and path |","| 404 | `POLL_NOT_FOUND` | The poll does not exist or belongs to another space |",+ "| 404 | `PARTICIPANT_NOT_FOUND` | The participant does not exist or belongs to another poll |","| 429 | `RATE_LIMIT_EXCEEDED` | A rate limit window is exhausted |","| 503 | `SERVICE_UNAVAILABLE` | Maintenance, or the rate limit store cannot be reached |","| 500 | `INTERNAL_ERROR` | Unexpected failure; the request id is logged |",@@ -837,6 +841,23 @@ app.get(},);+const toParticipantResponse = (+ kind: "date" | "time",+ participant: {+ id: string;+ name: string;+ email: string | null;+ createdAt: Date;+ votes: Parameters<typeof toAvailabilitySpans>[0]["votes"];+ },+) => ({+ id: participant.id,+ name: participant.name,+ email: participant.email,+ createdAt: participant.createdAt.toISOString(),+ availability: toAvailabilitySpans({ kind, votes: participant.votes }),+});+app.get("/polls/:pollId/participants",spaceApiKeyAuth,@@ -845,9 +866,9 @@ app.get(tags: ["Polls"],summary: "List poll participants",description: [- "Lists every participant of a poll in one response, oldest response first. The poll must belong to the space associated with the API key.",+ "Lists every participant of a poll in one response, oldest response first, each with their availability. The poll must belong to the space associated with the API key.","",- "Per-option answers are not included; use the results endpoint for aggregate availability.",+ "For aggregate counts per option use the results endpoint.",].join("\n"),security: [{ bearerAuth: [] }],responses: {@@ -891,12 +912,81 @@ app.get(return c.json(getPollParticipantsSuccessResponseSchema.parse({- data: data.participants.map((participant) => ({- id: participant.id,- name: participant.name,- email: participant.email,- createdAt: participant.createdAt.toISOString(),- })),+ data: data.participants.map((participant) =>+ toParticipantResponse(data.kind, participant),+ ),+ }),+ );+ },+);++app.get(+ "/polls/:pollId/participants/:participantId",+ spaceApiKeyAuth,+ rateLimit,+ describeRoute({+ tags: ["Polls"],+ summary: "Get a poll participant",+ description:+ "Returns one participant of a poll with their availability. The poll must belong to the space associated with the API key. This is the endpoint to call from a `poll.participant.*` webhook.",+ security: [{ bearerAuth: [] }],+ responses: {+ 200: {+ description: "Successful response",+ content: {+ "application/json": {+ schema: resolver(getPollParticipantSuccessResponseSchema),+ },+ },+ },+ 401: unauthorizedResponse,+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,+ 404: {+ description:+ "Poll not found (`POLL_NOT_FOUND`) or participant not found (`PARTICIPANT_NOT_FOUND`)",+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+ },+ },+ }),+ async (c) => {+ const { pollId, participantId } = c.req.param();+ const { spaceId } = c.get("apiAuth");++ const { poll, participant } = await getPollParticipant({+ pollId,+ participantId,+ spaceId,+ });++ if (!poll) {+ return c.json(+ apiError(+ "POLL_NOT_FOUND",+ "Poll not found or does not belong to this space.",+ ),+ 404,+ );+ }++ if (!participant) {+ return c.json(+ apiError(+ "PARTICIPANT_NOT_FOUND",+ "Participant not found or does not belong to this poll.",+ ),+ 404,+ );+ }++ return c.json(+ getPollParticipantSuccessResponseSchema.parse({+ data: toParticipantResponse(poll.kind, participant),}),);},diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.tsindex 734880d71..2fbffee1f 100644--- a/apps/web/src/app/api/v1/schemas.ts+++ b/apps/web/src/app/api/v1/schemas.ts@@ -586,12 +586,40 @@ export const getPollResultsSuccessResponseSchema = z}).meta({ id: "GetPollResultsResponse" });+export const availabilitySpanSchema = z+ .object({+ start: z.iso.datetime().meta({+ description: "Start of the span, inclusive, as a UTC instant.",+ example: "2025-01-15T09:00:00.000Z",+ }),+ end: z.iso.datetime().meta({+ description:+ "End of the span, exclusive, as a UTC instant: a 30 minute slot starting at 09:00 ends at 09:30, and the instant 09:30 is not in it.",+ example: "2025-01-15T09:30:00.000Z",+ }),+ allDay: z.boolean().meta({+ description:+ "True for a whole calendar day. The day is a floating date with no timezone, given as `start` at 00:00:00Z on that date and `end` at 00:00:00Z on the next; read the date from `start` and ignore the time of day.",+ example: false,+ }),+ modifiers: z.array(z.string()).meta({+ description:+ "Qualifiers on the availability. `ifNeedBe` means the participant can make it but would rather not. New modifiers may be added without a version change; one you do not recognise still leaves the span available.",+ example: ["ifNeedBe"],+ }),+ })+ .meta({ id: "AvailabilitySpan" });+export const participantSchema = z.object({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:00.000Z" }),+ availability: z.array(availabilitySpanSchema).meta({+ description:+ "When the participant is available: one span per option they can make, in start order, not merged. Options they cannot make, or did not answer, are absent. Each span matches an option of the poll by its time.",+ }),}).meta({ id: "Participant" });@@ -600,3 +628,9 @@ export const getPollParticipantsSuccessResponseSchema = zdata: z.array(participantSchema),}).meta({ id: "GetPollParticipantsResponse" });++export const getPollParticipantSuccessResponseSchema = z+ .object({+ data: participantSchema,+ })+ .meta({ id: "GetPollParticipantResponse" });diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.tsindex 76e5022b6..044f68dc9 100644--- a/apps/web/src/features/poll/data.ts+++ b/apps/web/src/features/poll/data.ts@@ -147,6 +147,20 @@ export async function getPollResults({/*** Every participant in response order (oldest first).*/+// Votes with their option's time, for the availability conversion.+const apiParticipantSelect = {+ id: true,+ name: true,+ email: true,+ createdAt: true,+ votes: {+ select: {+ type: true,+ option: { select: { startTime: true, duration: true } },+ },+ },+} satisfies Prisma.ParticipantSelect;+export async function getPollParticipants({pollId,spaceId,@@ -162,13 +176,9 @@ export async function getPollParticipants({},select: {id: true,+ kind: true,participants: {- select: {- id: true,- name: true,- email: true,- createdAt: true,- },+ select: apiParticipantSelect,orderBy: [{ createdAt: "asc" }, { id: "asc" }],},},@@ -180,10 +190,52 @@ export async function getPollParticipants({return {pollId: poll.id,+ kind: poll.kind,participants: poll.participants,};}+/**+ * One participant of a poll. Distinguishes a missing poll from a missing+ * participant so the API can say which, and never returns a participant+ * from another poll: the participant filter is nested under the poll's own+ * scope check.+ */+export async function getPollParticipant({+ pollId,+ participantId,+ spaceId,+}: {+ pollId: string;+ participantId: string;+ spaceId: AuthorizedSpaceId;+}) {+ const poll = await prisma.poll.findFirst({+ where: {+ id: pollId,+ spaceId,+ deleted: false,+ },+ select: {+ id: true,+ kind: true,+ participants: {+ where: { id: participantId },+ select: apiParticipantSelect,+ },+ },+ });++ if (!poll) {+ return { poll: null, participant: null };+ }++ return {+ poll: { id: poll.id, kind: poll.kind },+ participant: poll.participants[0] ?? null,+ };+}+export async function listPolls({spaceId,status,diff --git a/apps/web/src/features/poll/utils.test.ts b/apps/web/src/features/poll/utils.test.tsindex 97db8a115..9506aa537 100644--- a/apps/web/src/features/poll/utils.test.ts+++ b/apps/web/src/features/poll/utils.test.ts@@ -3,6 +3,7 @@ import {filterCommentsForViewer,filterParticipantsByVote,maskParticipantsForViewer,+ toAvailabilitySpans,} from "./utils";const participant = (@@ -141,3 +142,63 @@ describe("filterParticipantsByVote", () => {expect(result.map((p) => p.id)).toEqual(["a"]);});});++describe("toAvailabilitySpans", () => {+ const at = (iso: string) => new Date(iso);++ it("drops no, makes ifNeedBe a modifier, and orders by option start", () => {+ expect(+ toAvailabilitySpans({+ kind: "time",+ votes: [+ {+ type: "no",+ option: { startTime: at("2026-10-03T09:00:00Z"), duration: 30 },+ },+ {+ type: "ifNeedBe",+ option: { startTime: at("2026-10-02T09:00:00Z"), duration: 45 },+ },+ {+ type: "yes",+ option: { startTime: at("2026-10-01T09:00:00Z"), duration: 30 },+ },+ ],+ }),+ ).toEqual([+ {+ start: "2026-10-01T09:00:00.000Z",+ end: "2026-10-01T09:30:00.000Z",+ allDay: false,+ modifiers: [],+ },+ {+ start: "2026-10-02T09:00:00.000Z",+ end: "2026-10-02T09:45:00.000Z",+ allDay: false,+ modifiers: ["ifNeedBe"],+ },+ ]);+ });++ it("spans the whole UTC day for a date poll", () => {+ expect(+ toAvailabilitySpans({+ kind: "date",+ votes: [+ {+ type: "yes",+ option: { startTime: at("2026-10-01T00:00:00Z"), duration: 0 },+ },+ ],+ }),+ ).toEqual([+ {+ start: "2026-10-01T00:00:00.000Z",+ end: "2026-10-02T00:00:00.000Z",+ allDay: true,+ modifiers: [],+ },+ ]);+ });+});diff --git a/apps/web/src/features/poll/utils.ts b/apps/web/src/features/poll/utils.tsindex 151b79232..22e07a185 100644--- a/apps/web/src/features/poll/utils.ts+++ b/apps/web/src/features/poll/utils.ts@@ -94,3 +94,44 @@ export function filterCommentsForViewer({}return comments.filter((comment) => comment.userId === viewerUserId);}++const DAY_MS = 24 * 60 * 60 * 1000;+const MINUTE_MS = 60 * 1000;++export type AvailabilitySpan = {+ start: string;+ end: string;+ allDay: boolean;+ modifiers: string[];+};++/**+ * A participant's votes as availability: one span per option they can+ * make, in option order. A "no" is absence, as in a free/busy listing, and+ * "ifNeedBe" is a modifier on an available span. All-day options are stored+ * as UTC midnight with a zero duration, so they span their UTC day.+ */+export function toAvailabilitySpans({+ kind,+ votes,+}: {+ kind: "date" | "time";+ votes: {+ type: VoteType;+ option: { startTime: Date; duration: number };+ }[];+}): AvailabilitySpan[] {+ const allDay = kind === "date";+ return votes+ .filter((vote) => vote.type !== "no")+ .sort((a, b) => a.option.startTime.getTime() - b.option.startTime.getTime())+ .map(({ type, option }) => ({+ start: option.startTime.toISOString(),+ end: new Date(+ option.startTime.getTime() ++ (allDay ? DAY_MS : option.duration * MINUTE_MS),+ ).toISOString(),+ allDay,+ modifiers: type === "ifNeedBe" ? ["ifNeedBe"] : [],+ }));+}