Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions app/api/projects/[projectId]/tasks/[taskId]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { getProjectTaskHandler } from "@/lib/projects/getProjectTaskHandler";
import { updateProjectTaskHandler } from "@/lib/projects/updateProjectTaskHandler";
import { deleteProjectTaskHandler } from "@/lib/projects/deleteProjectTaskHandler";

/**
* OPTIONS handler for CORS preflight requests.
Expand Down Expand Up @@ -31,4 +33,42 @@ export async function GET(
return getProjectTaskHandler(request, projectId, taskId);
}

/**
* PATCH /api/projects/{projectId}/tasks/{taskId}
*
* Update a task, including the completion toggle (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 200 with the updated task; 400 on a bad body; 401 unauthenticated;
* 404 when the caller is not a collaborator or no such task exists; 500.
*/
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ projectId: string; taskId: string }> },
): Promise<NextResponse> {
const { projectId, taskId } = await params;
return updateProjectTaskHandler(request, projectId, taskId);
}

/**
* DELETE /api/projects/{projectId}/tasks/{taskId}
*
* Delete a task and its comments (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 200 with the deleted id; 401 unauthenticated; 404 when the caller is
* not a collaborator or no such task exists; 500 on a database failure.
*/
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ projectId: string; taskId: string }> },
): Promise<NextResponse> {
const { projectId, taskId } = await params;
return deleteProjectTaskHandler(request, projectId, taskId);
}

export const dynamic = "force-dynamic";
33 changes: 33 additions & 0 deletions app/api/projects/[projectId]/tasks/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { createProjectTaskHandler } from "@/lib/projects/createProjectTaskHandler";

/**
* 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() });
}

/**
* POST /api/projects/{projectId}/tasks
*
* Add a task to a client project (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` path parameter.
* @returns 201 with the created task; 400 on a bad body; 401 unauthenticated;
* 404 when the caller is not a collaborator; 500 on a database failure.
*/
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ projectId: string }> },
): Promise<NextResponse> {
const { projectId } = await params;
return createProjectTaskHandler(request, projectId);
}

export const dynamic = "force-dynamic";
27 changes: 27 additions & 0 deletions lib/projects/__tests__/toTaskUpdates.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { describe, it, expect } from "vitest";
import { toTaskUpdates } from "@/lib/projects/toTaskUpdates";

describe("toTaskUpdates", () => {
it("stamps completion from the server clock and the acting account", () => {
const updates = toTaskUpdates({ completed: true }, "acct-1");
expect(updates.completed_by).toBe("acct-1");
expect(typeof updates.completed_at).toBe("string");
});

it("clears both fields when reopening", () => {
expect(toTaskUpdates({ completed: false }, "acct-1")).toEqual({
completed_at: null,
completed_by: null,
});
});

it("leaves completion alone when the body does not mention it", () => {
const updates = toTaskUpdates({ title: "Renamed" }, "acct-1");
expect(updates).toEqual({ title: "Renamed" });
});

it("maps an explicit null through instead of dropping the field", () => {
// Clearing a due date has to be distinguishable from not touching it.
expect(toTaskUpdates({ due_date: null }, "acct-1")).toEqual({ due_date: null });
});
});
28 changes: 28 additions & 0 deletions lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
import { validateCreateProjectTaskRequest } from "@/lib/projects/validateCreateProjectTaskRequest";

vi.mock("@/lib/supabase/serverClient", () => ({ default: {} }));
vi.mock("@/lib/projects/requireProjectAccess", () => ({
requireProjectAccess: vi.fn(),
}));

const url = "https://api.recoupable.dev/api/projects/x/tasks";
const post = (body: unknown) =>
new NextRequest(url, {
method: "POST",
body: JSON.stringify(body),
headers: { "content-type": "application/json" },
});

describe("validateCreateProjectTaskRequest", () => {
it("rejects a malformed projectId with 400 before the body is read", async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The test name claims the 400 is returned "before the body is read", but the assertions only check the 400 status and error message using a valid { title: "x" } body. If body parsing/validation were moved ahead of the id check, this test would still pass, silently losing the documented ordering guarantee. To actually pin the ordering, assert that the body is never parsed (e.g., mock request.json or validateCreateProjectTaskBody and assert it was not called). Note this case is already covered end-to-end by validateProjectRequest.test.ts, so the wrapper test adds little new coverage.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts, line 19:

<comment>The test name claims the 400 is returned "before the body is read", but the assertions only check the 400 status and error message using a valid `{ title: "x" }` body. If body parsing/validation were moved ahead of the id check, this test would still pass, silently losing the documented ordering guarantee. To actually pin the ordering, assert that the body is never parsed (e.g., mock `request.json` or `validateCreateProjectTaskBody` and assert it was not called). Note this case is already covered end-to-end by `validateProjectRequest.test.ts`, so the wrapper test adds little new coverage.</comment>

<file context>
@@ -0,0 +1,28 @@
+  });
+
+describe("validateCreateProjectTaskRequest", () => {
+  it("rejects a malformed projectId with 400 before the body is read", async () => {
+    const result = await validateCreateProjectTaskRequest(post({ title: "x" }), "not-a-uuid");
+
</file context>

const result = await validateCreateProjectTaskRequest(post({ title: "x" }), "not-a-uuid");

expect(result).toMatchObject({ status: 400 });
await expect((result as Response).json()).resolves.toEqual({
status: "error",
error: "projectId must be a valid UUID",
});
});
});
36 changes: 36 additions & 0 deletions lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, it, expect } from "vitest";
import { NextResponse } from "next/server";
import { validateUpdateProjectTaskBody } from "@/lib/projects/validateUpdateProjectTaskBody";

describe("validateUpdateProjectTaskBody", () => {
it("accepts a single field", () => {
expect(validateUpdateProjectTaskBody({ completed: true })).toEqual({
completed: true,
});
});

it("rejects an empty body rather than treating it as a no-op success", () => {
expect(validateUpdateProjectTaskBody({})).toBeInstanceOf(NextResponse);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The error-path tests only assert the response is a NextResponse, never the error envelope that validateUpdateProjectTaskBody builds. If the envelope later regressed (e.g. missing status/error or an empty missing_fields), these tests would still pass. Assert status: "error", a string error, and missing_fields for each 400 case, as done for the other validators in this codebase.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts, line 13:

<comment>The error-path tests only assert the response is a NextResponse, never the error envelope that validateUpdateProjectTaskBody builds. If the envelope later regressed (e.g. missing status/error or an empty missing_fields), these tests would still pass. Assert `status: "error"`, a string `error`, and `missing_fields` for each 400 case, as done for the other validators in this codebase.</comment>

<file context>
@@ -0,0 +1,36 @@
+  });
+
+  it("rejects an empty body rather than treating it as a no-op success", () => {
+    expect(validateUpdateProjectTaskBody({})).toBeInstanceOf(NextResponse);
+  });
+
</file context>

});

it("rejects a due_date that is not a calendar date", () => {
expect(validateUpdateProjectTaskBody({ due_date: "2026-09-12T00:00:00Z" })).toBeInstanceOf(
NextResponse,
);
});

it("rejects a non-UUID assignee", () => {
expect(validateUpdateProjectTaskBody({ assignee_account_id: "nope" })).toBeInstanceOf(
NextResponse,
);
});

it("does not accept completed_at or completed_by from the caller", () => {
const result = validateUpdateProjectTaskBody({
completed: true,
completed_at: "1999-01-01T00:00:00Z",
completed_by: "11111111-1111-1111-1111-111111111111",
});
expect(result).toEqual({ completed: true });
});
});
49 changes: 49 additions & 0 deletions lib/projects/__tests__/validateUpdateProjectTaskRequest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
import { validateUpdateProjectTaskRequest } from "@/lib/projects/validateUpdateProjectTaskRequest";

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";
const patch = (body: unknown) =>
new NextRequest(url, {
method: "PATCH",
body: JSON.stringify(body),
headers: { "content-type": "application/json" },
});

const body = (result: unknown) => (result as Response).json();

describe("validateUpdateProjectTaskRequest", () => {
it("rejects a malformed projectId with 400", async () => {
const result = await validateUpdateProjectTaskRequest(
patch({ title: "x" }),
"not-a-uuid",
PROJECT_ID,
);

expect(result).toMatchObject({ status: 400 });
await expect(body(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 validateUpdateProjectTaskRequest(
patch({ title: "x" }),
PROJECT_ID,
"not-a-uuid",
);

expect(result).toMatchObject({ status: 400 });
await expect(body(result)).resolves.toEqual({
status: "error",
error: "taskId must be a valid UUID",
});
});
});
44 changes: 44 additions & 0 deletions lib/projects/createProjectTaskHandler.ts
Original file line number Diff line number Diff line change
@@ -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 { validateCreateProjectTaskRequest } from "@/lib/projects/validateCreateProjectTaskRequest";
import { insertProjectTask } from "@/lib/supabase/project_tasks/insertProjectTask";

/**
* POST /api/projects/{projectId}/tasks
*
* Create a task. New tasks are always incomplete; completion moves through the
* PATCH endpoint so the server owns the timestamp and the actor.
* Contract: recoupable/docs#326.
*
* @param request - The incoming request.
* @param projectId - The project to add the task to.
* @returns 201 with the created task, 400, 401, 404 or 500.
*/
export async function createProjectTaskHandler(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This new handler has no tests for its authentication, malformed JSON, validation, success, or database-error branches. Add handler tests before merging so response status/envelopes and the 201 insert contract cannot regress.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/createProjectTaskHandler.ts, line 20:

<comment>This new handler has no tests for its authentication, malformed JSON, validation, success, or database-error branches. Add handler tests before merging so response status/envelopes and the 201 insert contract cannot regress.</comment>

<file context>
@@ -0,0 +1,48 @@
+ * @param projectId - The project to add the task to.
+ * @returns 201 with the created task, 400, 401, 404 or 500.
+ */
+export async function createProjectTaskHandler(
+  request: NextRequest,
+  projectId: string,
</file context>

request: NextRequest,
projectId: string,
): Promise<NextResponse> {
const validated = await validateCreateProjectTaskRequest(request, projectId);
if (validated instanceof NextResponse) return validated;
const { body } = validated;

try {
const task = await insertProjectTask({
project_id: projectId,
title: body.title,
description: body.description ?? null,
due_date: body.due_date ?? null,
assignee_account_id: body.assignee_account_id ?? null,
});

return NextResponse.json(
{ status: "success", task },
{ status: 201, headers: getCorsHeaders() },
);
} catch (error) {
console.error("Error creating project task:", error);
return errorResponse("Internal server error", 500);
}
}
36 changes: 36 additions & 0 deletions lib/projects/deleteProjectTaskHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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 { deleteProjectTask } from "@/lib/supabase/project_tasks/deleteProjectTask";

/**
* DELETE /api/projects/{projectId}/tasks/{taskId}
*
* Permanently delete a task and, by cascade, its comments. No soft delete.
* Contract: recoupable/docs#326.
*
* @param request - The incoming request.
* @param projectId - The project the task belongs to.
* @param taskId - The task to delete.
* @returns 200 with the deleted id, 401, 404 or 500.
*/
export async function deleteProjectTaskHandler(
request: NextRequest,
projectId: string,
taskId: string,
): Promise<NextResponse> {
const access = await validateProjectTaskRequest(request, projectId, taskId);
if (access instanceof NextResponse) return access;

try {
const deleted = await deleteProjectTask(projectId, taskId);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
if (!deleted) return errorResponse("Task not found", 404);

return successResponse({ id: taskId });
} catch (error) {
console.error("Error deleting project task:", error);
return errorResponse("Internal server error", 500);
}
}
38 changes: 38 additions & 0 deletions lib/projects/toTaskUpdates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { TablesUpdate } from "@/types/database.types";
import type { UpdateProjectTaskBody } from "@/lib/projects/validateUpdateProjectTaskBody";

/**
* Turn a validated PATCH body into a row update (app#2048).
*
* `completed` is the only way completion moves: true stamps `completed_at` from
* the server clock and records the acting account, false clears both. The
* caller never supplies either, so who closed an item and when is never the
* client's word for it.
*
* @param body - The validated request body.
* @param accountId - The authenticated account, recorded as `completed_by`.
* @returns The columns to write.
*/
export function toTaskUpdates(
body: UpdateProjectTaskBody,
accountId: string,
): TablesUpdate<"project_tasks"> {
const updates: TablesUpdate<"project_tasks"> = {};

if (body.title !== undefined) updates.title = body.title;
if (body.description !== undefined) updates.description = body.description ?? null;
if (body.due_date !== undefined) updates.due_date = body.due_date ?? null;
if (body.assignee_account_id !== undefined) {
updates.assignee_account_id = body.assignee_account_id ?? null;
}

if (body.completed === true) {
updates.completed_at = new Date().toISOString();
updates.completed_by = accountId;
} else if (body.completed === false) {
updates.completed_at = null;
updates.completed_by = null;
}

return updates;
}
39 changes: 39 additions & 0 deletions lib/projects/updateProjectTaskHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { errorResponse } from "@/lib/networking/errorResponse";
import { successResponse } from "@/lib/networking/successResponse";
import { validateUpdateProjectTaskRequest } from "@/lib/projects/validateUpdateProjectTaskRequest";
import { toTaskUpdates } from "@/lib/projects/toTaskUpdates";
import { updateProjectTask } from "@/lib/supabase/project_tasks/updateProjectTask";

/**
* PATCH /api/projects/{projectId}/tasks/{taskId}
*
* Update a task, including the completion toggle. Any collaborator may close or
* reopen any task, the client included; the row records which one did.
* Contract: recoupable/docs#326.
*
* @param request - The incoming request.
* @param projectId - The project the task belongs to.
* @param taskId - The task to update.
* @returns 200 with the updated task, 400, 401, 404 or 500.
*/
export async function updateProjectTaskHandler(
request: NextRequest,
projectId: string,
taskId: string,
): Promise<NextResponse> {
const validated = await validateUpdateProjectTaskRequest(request, projectId, taskId);
if (validated instanceof NextResponse) return validated;
const { accountId, body } = validated;

try {
const task = await updateProjectTask(projectId, taskId, toTaskUpdates(body, accountId));
if (!task) return errorResponse("Task not found", 404);

return successResponse({ task });
} catch (error) {
console.error("Error updating project task:", error);
return errorResponse("Internal server error", 500);
}
}
Loading
Loading