diff --git a/app/api/projects/[projectId]/tasks/[taskId]/comments/route.ts b/app/api/projects/[projectId]/tasks/[taskId]/comments/route.ts new file mode 100644 index 000000000..47c2e5bd5 --- /dev/null +++ b/app/api/projects/[projectId]/tasks/[taskId]/comments/route.ts @@ -0,0 +1,53 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { getProjectCommentsHandler } from "@/lib/projects/getProjectCommentsHandler"; +import { createProjectCommentHandler } from "@/lib/projects/createProjectCommentHandler"; + +/** + * OPTIONS handler for CORS preflight requests. + * + * @returns A 204 NextResponse carrying the CORS headers. + */ +export async function OPTIONS() { + return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); +} + +/** + * GET /api/projects/{projectId}/tasks/{taskId}/comments + * + * A task's comments, oldest first (app#2048, contract: recoupable/docs#326). + * + * @param request - The incoming request, carrying the Bearer credential. + * @param root0 - The route context. + * @param root0.params - The resolved `projectId` and `taskId` parameters. + * @returns 200 with the comments; 401 unauthenticated; 404 when the caller is + * not a collaborator or no such task exists; 500 on a database failure. + */ +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ projectId: string; taskId: string }> }, +): Promise { + const { projectId, taskId } = await params; + return getProjectCommentsHandler(request, projectId, taskId); +} + +/** + * POST /api/projects/{projectId}/tasks/{taskId}/comments + * + * Post a comment attributed to the caller (app#2048). + * + * @param request - The incoming request, carrying the Bearer credential. + * @param root0 - The route context. + * @param root0.params - The resolved `projectId` and `taskId` parameters. + * @returns 201 with the comment; 400 on a bad body; 401 unauthenticated; 404 + * when the caller is not a collaborator or no such task exists; 500. + */ +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ projectId: string; taskId: string }> }, +): Promise { + const { projectId, taskId } = await params; + return createProjectCommentHandler(request, projectId, taskId); +} + +export const dynamic = "force-dynamic"; diff --git a/lib/projects/__tests__/validateCreateProjectCommentBody.test.ts b/lib/projects/__tests__/validateCreateProjectCommentBody.test.ts new file mode 100644 index 000000000..5489ceff6 --- /dev/null +++ b/lib/projects/__tests__/validateCreateProjectCommentBody.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect } from "vitest"; +import { NextResponse } from "next/server"; +import { + validateCreateProjectCommentBody, + COMMENT_MAX_LENGTH, +} from "@/lib/projects/validateCreateProjectCommentBody"; + +describe("validateCreateProjectCommentBody", () => { + it("accepts and trims a comment", () => { + expect(validateCreateProjectCommentBody({ body: " hello " })).toEqual({ + body: "hello", + }); + }); + + it("rejects whitespace only, which the database CHECK would also reject", () => { + expect(validateCreateProjectCommentBody({ body: " " })).toBeInstanceOf(NextResponse); + }); + + it("rejects a missing body", () => { + expect(validateCreateProjectCommentBody({})).toBeInstanceOf(NextResponse); + }); + + it("rejects a comment past the column's length cap", () => { + const tooLong = { body: "x".repeat(COMMENT_MAX_LENGTH + 1) }; + expect(validateCreateProjectCommentBody(tooLong)).toBeInstanceOf(NextResponse); + }); + + it("accepts a comment exactly at the cap", () => { + const atCap = { body: "x".repeat(COMMENT_MAX_LENGTH) }; + expect(validateCreateProjectCommentBody(atCap)).toEqual(atCap); + }); +}); diff --git a/lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts b/lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts new file mode 100644 index 000000000..d0d56ccdb --- /dev/null +++ b/lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { validateCreateProjectCommentRequest } from "@/lib/projects/validateCreateProjectCommentRequest"; + +vi.mock("@/lib/supabase/serverClient", () => ({ default: {} })); +vi.mock("@/lib/projects/requireProjectAccess", () => ({ + requireProjectAccess: vi.fn(), +})); + +const PROJECT_ID = "60a9a3e7-b7b2-466f-91d3-59b96e875bf6"; +const url = "https://api.recoupable.dev/api/projects/x/tasks/y/comments"; +const post = (body: unknown) => + new NextRequest(url, { + method: "POST", + body: JSON.stringify(body), + headers: { "content-type": "application/json" }, + }); + +const read = (result: unknown) => (result as Response).json(); + +describe("validateCreateProjectCommentRequest", () => { + it("rejects a malformed projectId with 400", async () => { + const result = await validateCreateProjectCommentRequest( + post({ body: "hi" }), + "not-a-uuid", + PROJECT_ID, + ); + + expect(result).toMatchObject({ status: 400 }); + await expect(read(result)).resolves.toEqual({ + status: "error", + error: "projectId must be a valid UUID", + }); + }); + + it("rejects a malformed taskId with 400 rather than letting it reach Postgres", async () => { + const result = await validateCreateProjectCommentRequest( + post({ body: "hi" }), + PROJECT_ID, + "not-a-uuid", + ); + + expect(result).toMatchObject({ status: 400 }); + await expect(read(result)).resolves.toEqual({ + status: "error", + error: "taskId must be a valid UUID", + }); + }); +}); diff --git a/lib/projects/createProjectCommentHandler.ts b/lib/projects/createProjectCommentHandler.ts new file mode 100644 index 000000000..575b0421e --- /dev/null +++ b/lib/projects/createProjectCommentHandler.ts @@ -0,0 +1,44 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { errorResponse } from "@/lib/networking/errorResponse"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { validateCreateProjectCommentRequest } from "@/lib/projects/validateCreateProjectCommentRequest"; +import { selectProjectTask } from "@/lib/supabase/project_tasks/selectProjectTask"; +import { insertProjectTaskComment } from "@/lib/supabase/project_task_comments/insertProjectTaskComment"; +import { toProjectComment } from "@/lib/projects/toProjectComment"; + +/** + * POST /api/projects/{projectId}/tasks/{taskId}/comments + * + * Post a comment, attributed to the authenticated account. Append-only: there + * is no edit and no delete. Contract: recoupable/docs#326. + * + * @param request - The incoming request. + * @param projectId - The project the task belongs to. + * @param taskId - The task to comment on. + * @returns 201 with the comment, 400, 401, 404 or 500. + */ +export async function createProjectCommentHandler( + request: NextRequest, + projectId: string, + taskId: string, +): Promise { + const validated = await validateCreateProjectCommentRequest(request, projectId, taskId); + if (validated instanceof NextResponse) return validated; + const { accountId, body } = validated; + + try { + const task = await selectProjectTask(projectId, taskId); + if (!task) return errorResponse("Task not found", 404); + + const comment = await insertProjectTaskComment(taskId, accountId, body.body); + + return NextResponse.json( + { status: "success", comment: toProjectComment(comment) }, + { status: 201, headers: getCorsHeaders() }, + ); + } catch (error) { + console.error("Error creating project task comment:", error); + return errorResponse("Internal server error", 500); + } +} diff --git a/lib/projects/getProjectCommentsHandler.ts b/lib/projects/getProjectCommentsHandler.ts new file mode 100644 index 000000000..60b6ae028 --- /dev/null +++ b/lib/projects/getProjectCommentsHandler.ts @@ -0,0 +1,41 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { errorResponse } from "@/lib/networking/errorResponse"; +import { successResponse } from "@/lib/networking/successResponse"; +import { validateProjectTaskRequest } from "@/lib/projects/validateProjectTaskRequest"; +import { selectProjectTask } from "@/lib/supabase/project_tasks/selectProjectTask"; +import { selectProjectTaskComments } from "@/lib/supabase/project_task_comments/selectProjectTaskComments"; +import { toProjectComment } from "@/lib/projects/toProjectComment"; + +/** + * GET /api/projects/{projectId}/tasks/{taskId}/comments + * + * A task's comments, oldest first. Contract: recoupable/docs#326. + * + * @param request - The incoming request. + * @param projectId - The project the task belongs to. + * @param taskId - The task whose comments to read. + * @returns 200 with the comments, 401, 404 or 500. + */ +export async function getProjectCommentsHandler( + request: NextRequest, + projectId: string, + taskId: string, +): Promise { + const access = await validateProjectTaskRequest(request, projectId, taskId); + if (access instanceof NextResponse) return access; + + try { + // Confirms the task belongs to this project before reading its comments, + // so a task id from elsewhere cannot be read through a project the caller + // does collaborate on. + const task = await selectProjectTask(projectId, taskId); + if (!task) return errorResponse("Task not found", 404); + + const comments = await selectProjectTaskComments([taskId]); + return successResponse({ comments: comments.map(toProjectComment) }); + } catch (error) { + console.error("Error fetching project task comments:", error); + return errorResponse("Internal server error", 500); + } +} diff --git a/lib/projects/validateCreateProjectCommentBody.ts b/lib/projects/validateCreateProjectCommentBody.ts new file mode 100644 index 000000000..cd0f89fa4 --- /dev/null +++ b/lib/projects/validateCreateProjectCommentBody.ts @@ -0,0 +1,45 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { z } from "zod"; + +/** Matches the `length(body) <= 4000` CHECK on project_task_comments. */ +export const COMMENT_MAX_LENGTH = 4000; + +export const createProjectCommentBodySchema = z.object({ + body: z + .string({ message: "body is required" }) + .trim() + .min(1, "body cannot be empty") + .max(COMMENT_MAX_LENGTH, `body cannot exceed ${COMMENT_MAX_LENGTH} characters`), +}); + +export type CreateProjectCommentBody = z.infer; + +/** + * Validates the body for POST /api/projects/{projectId}/tasks/{taskId}/comments. + * + * The length cap mirrors the database CHECK rather than trusting it: a 400 + * naming the field beats a 500 from a constraint violation. + * + * @param body - The request body. + * @returns The validated body, or a 400 NextResponse naming the first problem. + */ +export function validateCreateProjectCommentBody( + body: unknown, +): NextResponse | CreateProjectCommentBody { + const result = createProjectCommentBodySchema.safeParse(body); + + if (!result.success) { + const firstError = result.error.issues[0]; + return NextResponse.json( + { + status: "error", + missing_fields: firstError.path, + error: firstError.message, + }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + return result.data; +} diff --git a/lib/projects/validateCreateProjectCommentRequest.ts b/lib/projects/validateCreateProjectCommentRequest.ts new file mode 100644 index 000000000..e4ec20a76 --- /dev/null +++ b/lib/projects/validateCreateProjectCommentRequest.ts @@ -0,0 +1,42 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { validateProjectTaskRequest } from "@/lib/projects/validateProjectTaskRequest"; +import { + validateCreateProjectCommentBody, + type CreateProjectCommentBody, +} from "@/lib/projects/validateCreateProjectCommentBody"; + +export interface CreateProjectCommentRequest { + accountId: string; + body: CreateProjectCommentBody; +} + +/** + * Everything `POST /api/projects/{projectId}/tasks/{taskId}/comments` requires: + * both path ids well formed, a caller with a collaborator row on the project, + * and a valid body — in that order, so an unauthorised caller never learns + * whether their body would have been accepted. + * + * The id checks are not tidiness: an unguarded `taskId` reaches Postgres as + * `invalid input syntax for type uuid` and surfaces as a 500 rather than the + * 400 the contract documents. + * + * @param request - The incoming request, carrying the Bearer credential. + * @param projectId - The `projectId` path segment, unvalidated. + * @param taskId - The `taskId` path segment, unvalidated. + * @returns The authenticated account and validated body, or the response to + * return instead. + */ +export async function validateCreateProjectCommentRequest( + request: NextRequest, + projectId: string, + taskId: string, +): Promise { + const access = await validateProjectTaskRequest(request, projectId, taskId); + if (access instanceof NextResponse) return access; + + const body = validateCreateProjectCommentBody(await request.json().catch(() => null)); + if (body instanceof NextResponse) return body; + + return { accountId: access, body }; +} diff --git a/lib/supabase/project_task_comments/insertProjectTaskComment.ts b/lib/supabase/project_task_comments/insertProjectTaskComment.ts new file mode 100644 index 000000000..2c2d5ecfd --- /dev/null +++ b/lib/supabase/project_task_comments/insertProjectTaskComment.ts @@ -0,0 +1,19 @@ +import supabase from "../serverClient"; + +/** + * Post a comment on a task, returning it with its author's account name so the + * caller can render the new row without a second read. + */ +export async function insertProjectTaskComment(taskId: string, accountId: string, body: string) { + const { data, error } = await supabase + .from("project_task_comments") + .insert({ task_id: taskId, account_id: accountId, body }) + .select("id, task_id, account_id, body, created_at, accounts(name)") + .single(); + + if (error) { + throw new Error(`Failed to insert project_task_comments: ${error.message}`); + } + + return data; +}