Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(api): create pull request links via the api

Andrejd4df89a0dbc3
diff --git a/apps/api/src/external-link/controllers/create-external-link.ts b/apps/api/src/external-link/controllers/create-external-link.ts
index 1e6242e0b..0d166412c 100644
--- a/apps/api/src/external-link/controllers/create-external-link.ts
+++ b/apps/api/src/external-link/controllers/create-external-link.ts
@@ -7,27 +7,46 @@ import {
taskTable,
} from "../../database/schema";
import { publishEvent } from "../../events";
+import { pullRequestNumber } from "../pull-request-number";
+
+type PullRequestMetadata = {
+ state: "open" | "closed";
+ merged: boolean;
+ draft: boolean;
+};
async function createExternalLink({
taskId,
url,
title,
+ resourceType = "url",
+ metadata,
userId,
}: {
taskId: string;
url: string;
title?: string;
+ resourceType?: "url" | "pull_request";
+ metadata?: PullRequestMetadata;
userId: string;
}) {
+ if (metadata && resourceType !== "pull_request") {
+ throw new HTTPException(400, {
+ message: "Metadata is only accepted for pull request links",
+ });
+ }
+
const [link] = await db
.insert(externalLinkTable)
.values({
taskId,
integrationId: null,
- resourceType: "url",
- externalId: url,
+ resourceType,
+ externalId:
+ resourceType === "pull_request" ? (pullRequestNumber(url) ?? url) : url,
url,
title: title ?? null,
+ ...(metadata ? { metadata: JSON.stringify(metadata) } : {}),
})
.returning();
diff --git a/apps/api/src/external-link/controllers/delete-external-link.ts b/apps/api/src/external-link/controllers/delete-external-link.ts
index b3667b431..6540dd116 100644
--- a/apps/api/src/external-link/controllers/delete-external-link.ts
+++ b/apps/api/src/external-link/controllers/delete-external-link.ts
@@ -1,8 +1,9 @@
-import { and, eq, isNull } from "drizzle-orm";
+import { and, eq, inArray, isNull } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { externalLinkTable, taskTable } from "../../database/schema";
import { publishEvent } from "../../events";
+import { MANUAL_RESOURCE_TYPES } from "../manual-resource-types";
export default async function deleteExternalLink({
taskId,
@@ -27,7 +28,7 @@ export default async function deleteExternalLink({
eq(externalLinkTable.id, id),
eq(externalLinkTable.taskId, taskId),
isNull(externalLinkTable.integrationId),
- eq(externalLinkTable.resourceType, "url"),
+ inArray(externalLinkTable.resourceType, MANUAL_RESOURCE_TYPES),
),
)
.returning({ id: externalLinkTable.id });
diff --git a/apps/api/src/external-link/controllers/update-external-link.ts b/apps/api/src/external-link/controllers/update-external-link.ts
new file mode 100644
index 000000000..2ea0c3273
--- /dev/null
+++ b/apps/api/src/external-link/controllers/update-external-link.ts
@@ -0,0 +1,58 @@
+import { and, eq, inArray, isNull } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { externalLinkTable, taskTable } from "../../database/schema";
+import { publishEvent } from "../../events";
+import { MANUAL_RESOURCE_TYPES } from "../manual-resource-types";
+
+export default async function updateExternalLink({
+ taskId,
+ id,
+ title,
+ metadata,
+ userId,
+}: {
+ taskId: string;
+ id: string;
+ title?: string;
+ metadata?: { state: "open" | "closed"; merged: boolean; draft: boolean };
+ userId: string;
+}) {
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, taskId),
+ columns: { projectId: true, title: true, status: true },
+ });
+ if (!task) throw new HTTPException(404, { message: "Task not found" });
+
+ const manualLink = and(
+ eq(externalLinkTable.id, id),
+ eq(externalLinkTable.taskId, taskId),
+ isNull(externalLinkTable.integrationId),
+ inArray(externalLinkTable.resourceType, MANUAL_RESOURCE_TYPES),
+ );
+ const existing = await db.query.externalLinkTable.findFirst({
+ where: manualLink,
+ columns: { resourceType: true },
+ });
+ if (!existing)
+ throw new HTTPException(404, { message: "Manual resource link not found" });
+ if (metadata && existing.resourceType !== "pull_request") {
+ throw new HTTPException(400, {
+ message: "Metadata is only accepted for pull request links",
+ });
+ }
+
+ const [updated] = await db
+ .update(externalLinkTable)
+ .set({
+ ...(title !== undefined ? { title } : {}),
+ ...(metadata ? { metadata: JSON.stringify(metadata) } : {}),
+ })
+ .where(manualLink)
+ .returning();
+ if (!updated)
+ throw new HTTPException(404, { message: "Manual resource link not found" });
+
+ await publishEvent("task.updated", { taskId, ...task, userId });
+ return updated;
+}
diff --git a/apps/api/src/external-link/index.ts b/apps/api/src/external-link/index.ts
index 5b211f053..f80905561 100644
--- a/apps/api/src/external-link/index.ts
+++ b/apps/api/src/external-link/index.ts
@@ -12,6 +12,7 @@ import { requireWorkspacePermission } from "../utils/require-workspace-permissio
import { workspaceAccess } from "../utils/workspace-access-middleware";
import createExternalLink from "./controllers/create-external-link";
import deleteExternalLink from "./controllers/delete-external-link";
+import updateExternalLink from "./controllers/update-external-link";
import {
createdExternalLinkSchema,
deletedExternalLinkSchema,
@@ -21,6 +22,7 @@ import {
createExternalLinkBody,
deleteExternalLinkParam,
taskIdParam,
+ updateExternalLinkBody,
} from "./schema";
const createExternalLinkRoute = createRoute({
@@ -29,7 +31,8 @@ const createExternalLinkRoute = createRoute({
path: "/task/{taskId}",
tags: ["External Links"],
summary: "Create an external link",
- description: "Add a resource link to a task",
+ description:
+ 'Add a resource link to a task. Pass `resourceType: "pull_request"` with `metadata` to show the link as a pull request with its status.',
middleware: [
workspaceAccess.fromTaskId("taskId"),
requireWorkspacePermission({ task: ["update"] }),
@@ -57,6 +60,34 @@ const createExternalLinkRoute = createRoute({
},
});
+const updateExternalLinkRoute = createRoute({
+ method: "patch",
+ operationId: "updateExternalLink",
+ path: "/task/{taskId}/{id}",
+ tags: ["External Links"],
+ summary: "Update a manual link",
+ description:
+ "Change the title of a manually added link, or the status of a manually added pull request link. Integration-managed links cannot be changed through this endpoint.",
+ middleware: [
+ workspaceAccess.fromTaskId("taskId"),
+ requireWorkspacePermission({ task: ["update"] }),
+ ] as const,
+ request: {
+ params: deleteExternalLinkParam,
+ body: {
+ required: true,
+ content: { "application/json": { schema: updateExternalLinkBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("Link updated", createdExternalLinkSchema),
+ 400: errorResponse("Invalid link data"),
+ 401: errorResponse("Unauthorized"),
+ 403: errorResponse("No permission to update the task"),
+ 404: errorResponse("Task or manual resource link not found"),
+ },
+});
+
const deleteExternalLinkRoute = createRoute({
method: "delete",
operationId: "deleteExternalLink",
@@ -102,12 +133,14 @@ const getExternalLinksByTaskRoute = createRoute({
const externalLink = apiRouter<BaseVariables & { workspaceId: string }>()
.openapi(createExternalLinkRoute, async (c) => {
const { taskId } = c.req.valid("param");
- const { url, title } = c.req.valid("json");
+ const { url, title, resourceType, metadata } = c.req.valid("json");
const link = await createExternalLink({
taskId,
url,
title,
+ resourceType,
+ metadata,
userId: c.get("userId"),
});
@@ -119,6 +152,21 @@ const externalLink = apiRouter<BaseVariables & { workspaceId: string }>()
200,
);
})
+ .openapi(updateExternalLinkRoute, async (c) => {
+ const { taskId, id } = c.req.valid("param");
+ const { title, metadata } = c.req.valid("json");
+ const link = await updateExternalLink({
+ taskId,
+ id,
+ title,
+ metadata,
+ userId: c.get("userId"),
+ });
+ return c.json(
+ { ...link, metadata: link.metadata ? JSON.parse(link.metadata) : null },
+ 200,
+ );
+ })
.openapi(deleteExternalLinkRoute, async (c) => {
const { taskId, id } = c.req.valid("param");
return c.json(
diff --git a/apps/api/src/external-link/manual-resource-types.ts b/apps/api/src/external-link/manual-resource-types.ts
new file mode 100644
index 000000000..45f8ea13d
--- /dev/null
+++ b/apps/api/src/external-link/manual-resource-types.ts
@@ -0,0 +1 @@
+export const MANUAL_RESOURCE_TYPES = ["url", "pull_request"];
diff --git a/apps/api/src/external-link/pull-request-number.ts b/apps/api/src/external-link/pull-request-number.ts
new file mode 100644
index 000000000..8f33fe7c1
--- /dev/null
+++ b/apps/api/src/external-link/pull-request-number.ts
@@ -0,0 +1,6 @@
+const NUMBERED_PATH =
+ /\/(?:pull|pulls|merge_requests|pull-requests)\/(\d+)(?:[/?#]|$)/i;
+
+export function pullRequestNumber(url: string): string | null {
+ return NUMBERED_PATH.exec(url)?.[1] ?? null;
+}
diff --git a/apps/api/src/external-link/schema.ts b/apps/api/src/external-link/schema.ts
index e42b40963..c0b42fd7b 100644
--- a/apps/api/src/external-link/schema.ts
+++ b/apps/api/src/external-link/schema.ts
@@ -2,6 +2,17 @@ import { z } from "../openapi";
export const taskIdParam = z.object({ taskId: z.string() });
+export const pullRequestMetadata = z
+ .object({
+ state: z.enum(["open", "closed"]),
+ merged: z.boolean().default(false),
+ draft: z.boolean().default(false),
+ })
+ .openapi("PullRequestLinkMetadata", {
+ description:
+ "Pull request status shown on the task: open, draft, merged or closed.",
+ });
+
export const createExternalLinkBody = z.object({
url: z
.string()
@@ -9,6 +20,26 @@ export const createExternalLinkBody = z.object({
.refine((url) => /^https?:\/\//i.test(url), "URL must use http or https")
.describe("An HTTP or HTTPS URL"),
title: z.string().max(200).optional(),
+ resourceType: z
+ .enum(["url", "pull_request"])
+ .default("url")
+ .describe(
+ "`url` for a resource link, or `pull_request` to show the link as a pull request with its status",
+ ),
+ metadata: pullRequestMetadata
+ .optional()
+ .describe("Pull request status. Only accepted for `pull_request` links."),
});
+export const updateExternalLinkBody = z
+ .object({
+ title: z.string().max(200).optional(),
+ metadata: pullRequestMetadata
+ .optional()
+ .describe("Pull request status. Only accepted for `pull_request` links."),
+ })
+ .refine((body) => body.title !== undefined || body.metadata !== undefined, {
+ message: "Provide a title or metadata to update",
+ });
+
export const deleteExternalLinkParam = taskIdParam.extend({ id: z.string() });
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index a0552a399..9e89ec299 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -4185,6 +4185,30 @@
"updatedAt"
]
},
+ "PullRequestLinkMetadata": {
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": [
+ "open",
+ "closed"
+ ]
+ },
+ "merged": {
+ "type": "boolean",
+ "default": false
+ },
+ "draft": {
+ "type": "boolean",
+ "default": false
+ }
+ },
+ "required": [
+ "state"
+ ],
+ "description": "Pull request status. Only accepted for `pull_request` links."
+ },
"DeletedExternalLink": {
"type": "object",
"properties": {
@@ -22917,7 +22941,7 @@
"External Links"
],
"summary": "Create an external link",
- "description": "Add a resource link to a task",
+ "description": "Add a resource link to a task. Pass `resourceType: \"pull_request\"` with `metadata` to show the link as a pull request with its status.",
"parameters": [
{
"schema": {
@@ -22943,6 +22967,18 @@
"title": {
"type": "string",
"maxLength": 200
+ },
+ "resourceType": {
+ "type": "string",
+ "enum": [
+ "url",
+ "pull_request"
+ ],
+ "default": "url",
+ "description": "`url` for a resource link, or `pull_request` to show the link as a pull request with its status"
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/PullRequestLinkMetadata"
}
},
"required": [
@@ -23076,6 +23112,106 @@
}
},
"/external-link/task/{taskId}/{id}": {
+ "patch": {
+ "operationId": "updateExternalLink",
+ "tags": [
+ "External Links"
+ ],
+ "summary": "Update a manual link",
+ "description": "Change the title of a manually added link, or the status of a manually added pull request link. Integration-managed links cannot be changed through this endpoint.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "taskId",
+ "in": "path"
+ },
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "id",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string",
+ "maxLength": 200
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/PullRequestLinkMetadata"
+ }
+ }
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Link updated",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreatedExternalLink"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid link data",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthorized",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "No permission to update the task",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Task or manual resource link not found",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "429": {
+ "$ref": "#/components/responses/ApiKeyRateLimited"
+ }
+ }
+ },
"delete": {
"operationId": "deleteExternalLink",
"tags": [
diff --git a/tests/api-integration/manual-external-links.test.ts b/tests/api-integration/manual-external-links.test.ts
index e66149248..da55748ff 100644
--- a/tests/api-integration/manual-external-links.test.ts
+++ b/tests/api-integration/manual-external-links.test.ts
@@ -237,4 +237,93 @@ describe("manual external resource links", () => {
expect(await db.query.externalLinkTable.findMany()).toHaveLength(0);
expect(m.publish).not.toHaveBeenCalled();
});
+
+ it("creates a pull request link that shows its status, then updates and removes it", async () => {
+ const own = await context();
+ mockAuthenticatedSession(own.user);
+ const created = await request(`/${own.task.id}`, "POST", {
+ url: "https://github.com/acme/app/pull/42",
+ title: "Fix payouts",
+ resourceType: "pull_request",
+ metadata: { state: "open", draft: true },
+ });
+ expect(created.status).toBe(200);
+ const entry = (await created.json()) as { id: string };
+ expect(
+ await (await request(`/${own.task.id}`, "GET")).json(),
+ ).toMatchObject([
+ {
+ id: entry.id,
+ resourceType: "pull_request",
+ externalId: "42",
+ integration: null,
+ metadata: { state: "open", merged: false, draft: true },
+ },
+ ]);
+
+ const updated = await request(`/${own.task.id}/${entry.id}`, "PATCH", {
+ metadata: { state: "closed", merged: true },
+ });
+ expect(updated.status).toBe(200);
+ expect(await updated.json()).toMatchObject({
+ title: "Fix payouts",
+ metadata: { state: "closed", merged: true, draft: false },
+ });
+
+ expect(
+ (await request(`/${own.task.id}/${entry.id}`, "DELETE")).status,
+ ).toBe(200);
+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(0);
+ expect(m.publish).toHaveBeenCalledTimes(3);
+ });
+
+ it("only accepts status metadata for pull request links", async () => {
+ const own = await context();
+ mockAuthenticatedSession(own.user);
+ expect(
+ (
+ await request(`/${own.task.id}`, "POST", {
+ url: "https://example.com",
+ metadata: { state: "open" },
+ })
+ ).status,
+ ).toBe(400);
+ const entry = await link(own.task.id);
+ expect(
+ (
+ await request(`/${own.task.id}/${entry.id}`, "PATCH", {
+ metadata: { state: "open" },
+ })
+ ).status,
+ ).toBe(400);
+ expect(
+ (
+ await request(`/${own.task.id}/${entry.id}`, "PATCH", {
+ title: "Renamed",
+ })
+ ).status,
+ ).toBe(200);
+ });
+
+ it("does not let the API change integration-managed pull requests", async () => {
+ const own = await context();
+ const [integration] = await db
+ .insert(schema.integrationTable)
+ .values({ projectId: own.project.id, type: "github", config: "{}" })
+ .returning();
+ const entry = await link(own.task.id, integration.id, "pull_request");
+ mockAuthenticatedSession(own.user);
+ expect(
+ (
+ await request(`/${own.task.id}/${entry.id}`, "PATCH", {
+ metadata: { state: "closed", merged: true },
+ })
+ ).status,
+ ).toBe(404);
+ expect(
+ (await request(`/${own.task.id}/${entry.id}`, "DELETE")).status,
+ ).toBe(404);
+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(1);
+ expect(m.publish).not.toHaveBeenCalled();
+ });
});
diff --git a/tests/api/external-link/create-external-link.test.ts b/tests/api/external-link/create-external-link.test.ts
index 2d05f17f1..5d6cc52df 100644
--- a/tests/api/external-link/create-external-link.test.ts
+++ b/tests/api/external-link/create-external-link.test.ts
@@ -138,4 +138,41 @@ describe("createExternalLink", () => {
expect(mockPublishEvent).not.toHaveBeenCalled();
});
+
+ it("stores a pull request link with its number and status", async () => {
+ const returning = vi.fn().mockResolvedValue([{ id: "link-3" }]);
+ const values = vi.fn().mockReturnValue({ returning });
+ mockInsert.mockReturnValue({ values });
+
+ await createExternalLink({
+ taskId: "task-1",
+ url: "https://github.com/acme/app/pull/42",
+ title: "Fix payouts",
+ resourceType: "pull_request",
+ metadata: { state: "closed", merged: true, draft: false },
+ userId: "user-1",
+ });
+
+ expect(values).toHaveBeenCalledWith({
+ taskId: "task-1",
+ integrationId: null,
+ resourceType: "pull_request",
+ externalId: "42",
+ url: "https://github.com/acme/app/pull/42",
+ title: "Fix payouts",
+ metadata: JSON.stringify({ state: "closed", merged: true, draft: false }),
+ });
+ });
+
+ it("rejects status metadata on a resource link", async () => {
+ await expect(
+ createExternalLink({
+ taskId: "task-1",
+ url: "https://example.com",
+ metadata: { state: "open", merged: false, draft: false },
+ userId: "user-1",
+ }),
+ ).rejects.toMatchObject({ status: 400 });
+ expect(mockInsert).not.toHaveBeenCalled();
+ });
});
diff --git a/tests/api/external-link/pull-request-number.test.ts b/tests/api/external-link/pull-request-number.test.ts
new file mode 100644
index 000000000..2252c04b7
--- /dev/null
+++ b/tests/api/external-link/pull-request-number.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vite-plus/test";
+import { pullRequestNumber } from "../../../apps/api/src/external-link/pull-request-number";
+
+describe("pullRequestNumber", () => {
+ it.each([
+ ["https://github.com/acme/app/pull/42", "42"],
+ ["https://github.com/acme/app/pull/42/files", "42"],
+ ["https://gitlab.com/acme/app/-/merge_requests/7", "7"],
+ ["https://bitbucket.org/acme/app/pull-requests/9?tab=diff", "9"],
+ ])("reads the number from %s", (url, number) => {
+ expect(pullRequestNumber(url)).toBe(number);
+ });
+
+ it("returns null when the URL has no pull request number", () => {
+ expect(
+ pullRequestNumber("https://github.com/acme/app/issues/42"),
+ ).toBeNull();
+ expect(pullRequestNumber("https://example.com/pull/abc")).toBeNull();
+ });
+});
diff --git a/tests/api/external-link/schema.test.ts b/tests/api/external-link/schema.test.ts
index b34990582..b0690e649 100644
--- a/tests/api/external-link/schema.test.ts
+++ b/tests/api/external-link/schema.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vite-plus/test";
-import { createExternalLinkBody } from "../../../apps/api/src/external-link/schema";
+import {
+ createExternalLinkBody,
+ updateExternalLinkBody,
+} from "../../../apps/api/src/external-link/schema";
describe("manual resource URL validation", () => {
it.each([
@@ -20,3 +23,41 @@ describe("manual resource URL validation", () => {
expect(createExternalLinkBody.safeParse({ url }).success).toBe(false);
});
});
+
+describe("pull request links", () => {
+ it("defaults to a resource link", () => {
+ expect(
+ createExternalLinkBody.parse({ url: "https://example.com" }).resourceType,
+ ).toBe("url");
+ });
+
+ it("accepts a pull request with its status", () => {
+ const parsed = createExternalLinkBody.parse({
+ url: "https://github.com/acme/app/pull/42",
+ resourceType: "pull_request",
+ metadata: { state: "open", draft: true },
+ });
+ expect(parsed.metadata).toEqual({
+ state: "open",
+ merged: false,
+ draft: true,
+ });
+ });
+
+ it.each([
+ { resourceType: "issue" },
+ { resourceType: "pull_request", metadata: { state: "merged" } },
+ ])("rejects %j", (extra) => {
+ expect(
+ createExternalLinkBody.safeParse({ url: "https://example.com", ...extra })
+ .success,
+ ).toBe(false);
+ });
+
+ it("requires something to update", () => {
+ expect(updateExternalLinkBody.safeParse({}).success).toBe(false);
+ expect(updateExternalLinkBody.safeParse({ title: "PR" }).success).toBe(
+ true,
+ );
+ });
+});