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: implement GitHub issue handling for task status and priority changes

Andrej Acevski6d7fe200f3ae
diff --git a/apps/api/src/github-integration/index.ts b/apps/api/src/github-integration/index.ts
index 8feec1774..3954ef12c 100644
--- a/apps/api/src/github-integration/index.ts
+++ b/apps/api/src/github-integration/index.ts
@@ -9,13 +9,17 @@ import { importIssues } from "./controllers/import-issues";
import listUserRepositories from "./controllers/list-user-repositories";
import verifyGithubInstallation from "./controllers/verify-github-installation";
import createGithubApp from "./utils/create-github-app";
+import { handleIssueClosed } from "./utils/issue-closed";
import { handleIssueOpened } from "./utils/issue-opened";
import { handleTaskCreated } from "./utils/task-created";
+import { handleTaskPriorityChanged } from "./utils/task-priority-changed";
+import { handleTaskStatusChanged } from "./utils/task-status-changed";
const githubApp = createGithubApp();
if (githubApp) {
githubApp.webhooks.on("issues.opened", handleIssueOpened);
+ githubApp.webhooks.on("issues.closed", handleIssueClosed);
}
subscribeToEvent<{
@@ -29,6 +33,22 @@ subscribeToEvent<{
projectId: string;
}>("task.created", handleTaskCreated);
+subscribeToEvent<{
+ taskId: string;
+ userEmail: string | null;
+ oldStatus: string;
+ newStatus: string;
+ title: string;
+}>("task.status_changed", handleTaskStatusChanged);
+
+subscribeToEvent<{
+ taskId: string;
+ userEmail: string | null;
+ oldPriority: string;
+ newPriority: string;
+ title: string;
+}>("task.priority_changed", handleTaskPriorityChanged);
+
const githubIntegration = new Hono()
.get("/app-info", async (c) => {
return c.json({
diff --git a/apps/api/src/github-integration/utils/create-github-labels.ts b/apps/api/src/github-integration/utils/create-github-labels.ts
new file mode 100644
index 000000000..9b983db5f
--- /dev/null
+++ b/apps/api/src/github-integration/utils/create-github-labels.ts
@@ -0,0 +1,55 @@
+import type { Octokit } from "octokit";
+import { getLabelColor } from "./github-label-colors";
+
+export async function createGitHubLabels(
+ octokit: Octokit,
+ owner: string,
+ repo: string,
+ labels: string[],
+) {
+ for (const labelName of labels) {
+ try {
+ try {
+ await octokit.rest.issues.getLabel({
+ owner,
+ repo,
+ name: labelName,
+ });
+ console.log(`Label "${labelName}" already exists`);
+ } catch (error) {
+ const color = getLabelColor(labelName);
+ await octokit.rest.issues.createLabel({
+ owner,
+ repo,
+ name: labelName,
+ color,
+ description: `Kaneo ${labelName.replace(":", " ")} label`,
+ });
+ console.log(`Created label "${labelName}" with color ${color}`);
+ }
+ } catch (error) {
+ console.error(`Failed to create label "${labelName}":`, error);
+ }
+ }
+}
+
+export async function addLabelsToIssue(
+ octokit: Octokit,
+ owner: string,
+ repo: string,
+ issueNumber: number,
+ labels: string[],
+) {
+ try {
+ await createGitHubLabels(octokit, owner, repo, labels);
+
+ await octokit.rest.issues.addLabels({
+ owner,
+ repo,
+ issue_number: issueNumber,
+ labels,
+ });
+ } catch (error) {
+ console.error("Failed to add labels to issue:", error);
+ }
+}
diff --git a/apps/api/src/github-integration/utils/extract-issue-priority.ts b/apps/api/src/github-integration/utils/extract-issue-priority.ts
index f2c555592..e237bfde6 100644
--- a/apps/api/src/github-integration/utils/extract-issue-priority.ts
+++ b/apps/api/src/github-integration/utils/extract-issue-priority.ts
@@ -15,3 +15,17 @@ export function extractIssuePriority(
const validPriorities = ["low", "medium", "high", "urgent"];
return validPriorities.includes(priority) ? priority : "medium";
}
+
+export function extractIssueStatus(labels: GitHubLabel[] | undefined): string {
+ if (!labels) return "to-do";
+
+ const statusLabels = labels
+ .map((label) => (typeof label === "string" ? label : label?.name))
+ .filter((name) => name?.startsWith("status:"));
+
+ const firstStatusLabel = statusLabels[0];
+ const status = firstStatusLabel?.replace("status:", "") || "to-do";
+
+ const validStatuses = ["to-do", "in-progress", "done", "planned", "archived"];
+ return validStatuses.includes(status) ? status : "to-do";
+}
diff --git a/apps/api/src/github-integration/utils/github-label-colors.ts b/apps/api/src/github-integration/utils/github-label-colors.ts
new file mode 100644
index 000000000..97e5f3e5f
--- /dev/null
+++ b/apps/api/src/github-integration/utils/github-label-colors.ts
@@ -0,0 +1,20 @@
+export const githubLabelColors = {
+ "priority:low": "0EA5E9", // Blue
+ "priority:medium": "EAB308", // Yellow
+ "priority:high": "F97316", // Orange
+ "priority:urgent": "EF4444", // Red
+
+ "status:to-do": "6B7280", // Gray
+ "status:in-progress": "3B82F6", // Blue
+ "status:done": "10B981", // Green
+ "status:planned": "8B5CF6", // Purple
+ "status:archived": "6B7280", // Gray
+
+ kaneo: "6366F1", // Indigo
+};
+
+export function getLabelColor(labelName: string): string {
+ return (
+ githubLabelColors[labelName as keyof typeof githubLabelColors] || "6B7280"
+ );
+}
diff --git a/apps/api/src/github-integration/utils/issue-closed.ts b/apps/api/src/github-integration/utils/issue-closed.ts
new file mode 100644
index 000000000..f22e62cc6
--- /dev/null
+++ b/apps/api/src/github-integration/utils/issue-closed.ts
@@ -0,0 +1,72 @@
+import type {
+ EmitterWebhookEvent,
+ EmitterWebhookEventName,
+} from "@octokit/webhooks";
+import { eq } from "drizzle-orm";
+import type { Octokit } from "octokit";
+import db from "../../database";
+import { taskTable } from "../../database/schema";
+import getGithubIntegrationByRepositoryId from "../controllers/get-github-integration-by-repository-id";
+
+export type HandlerFunction<
+ TName extends EmitterWebhookEventName,
+ TTransformed = unknown,
+> = (event: EmitterWebhookEvent<TName> & TTransformed) => void;
+
+export const handleIssueClosed: HandlerFunction<
+ "issues.closed",
+ { octokit: Octokit }
+> = async ({ payload }): Promise<void> => {
+ try {
+ if (payload.issue.title.startsWith("[Kaneo]")) {
+ console.log("Skipping Kaneo-created issue to avoid loop");
+ return;
+ }
+
+ const integration = await getGithubIntegrationByRepositoryId(
+ payload.repository.owner.login,
+ payload.repository.name,
+ );
+
+ if (!integration || !integration.isActive) {
+ console.log(
+ "No active Kaneo integration found for repository:",
+ payload.repository.full_name,
+ );
+ return;
+ }
+
+ const tasks = await db.query.taskTable.findMany({
+ where: eq(taskTable.projectId, integration.projectId),
+ });
+
+ const kaneoTask = tasks.find((task) =>
+ task.description?.includes(
+ `Created from GitHub issue: ${payload.issue.html_url}`,
+ ),
+ );
+
+ if (!kaneoTask) {
+ console.log(
+ "Kaneo task not found for GitHub issue:",
+ payload.issue.html_url,
+ );
+ return;
+ }
+
+ try {
+ await db
+ .update(taskTable)
+ .set({
+ status: "done",
+ })
+ .where(eq(taskTable.id, kaneoTask.id));
+
+ console.log(`Updated Kaneo task ${kaneoTask.id} status to "done"`);
+ } catch (error) {
+ console.error("Failed to update Kaneo task status:", error);
+ }
+ } catch (error) {
+ console.error("Failed to handle GitHub issue closed:", error);
+ }
+};
diff --git a/apps/api/src/github-integration/utils/issue-opened.ts b/apps/api/src/github-integration/utils/issue-opened.ts
index 28f44b0f7..751e782cc 100644
--- a/apps/api/src/github-integration/utils/issue-opened.ts
+++ b/apps/api/src/github-integration/utils/issue-opened.ts
@@ -5,7 +5,11 @@ import type {
import type { Octokit } from "octokit";
import createTask from "../../task/controllers/create-task";
import getGithubIntegrationByRepositoryId from "../controllers/get-github-integration-by-repository-id";
-import { extractIssuePriority } from "./extract-issue-priority";
+import { addLabelsToIssue } from "./create-github-labels";
+import {
+ extractIssuePriority,
+ extractIssueStatus,
+} from "./extract-issue-priority";
import { formatGitHubComment } from "./format-github-comment";
import { formatTaskDescription } from "./format-task-description";
@@ -38,6 +42,7 @@ export const handleIssueOpened: HandlerFunction<
}
const taskPriority = extractIssuePriority(payload.issue.labels);
+ const taskStatus = extractIssueStatus(payload.issue.labels);
const task = await createTask({
projectId: integration.projectId,
@@ -49,13 +54,34 @@ export const handleIssueOpened: HandlerFunction<
user: payload.issue.user,
repository: payload.repository,
}),
- status: "to-do",
+ status: taskStatus,
priority: taskPriority,
dueDate: new Date(),
userEmail: undefined,
});
+ const existingLabels =
+ payload.issue.labels
+ ?.map((label) => (typeof label === "string" ? label : label.name))
+ .filter(Boolean) || [];
+
+ const labelsToAdd = [
+ "kaneo",
+ `priority:${taskPriority}`,
+ `status:${taskStatus}`,
+ ].filter((label) => !existingLabels.includes(label));
+
try {
+ if (labelsToAdd.length > 0) {
+ await addLabelsToIssue(
+ octokit,
+ payload.repository.owner.login,
+ payload.repository.name,
+ payload.issue.number,
+ labelsToAdd,
+ );
+ }
+
await octokit.rest.issues.createComment({
owner: payload.repository.owner.login,
repo: payload.repository.name,
@@ -68,7 +94,10 @@ export const handleIssueOpened: HandlerFunction<
}),
});
} catch (commentError) {
- console.error("Failed to add comment to GitHub issue:", commentError);
+ console.error(
+ "Failed to add comment or labels to GitHub issue:",
+ commentError,
+ );
}
} catch (error) {
console.error("Failed to create Kaneo task from GitHub issue:", error);
diff --git a/apps/api/src/github-integration/utils/task-created.ts b/apps/api/src/github-integration/utils/task-created.ts
index 97921253e..d0325f781 100644
--- a/apps/api/src/github-integration/utils/task-created.ts
+++ b/apps/api/src/github-integration/utils/task-created.ts
@@ -1,5 +1,9 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { taskTable } from "../../database/schema";
import getGithubIntegration from "../controllers/get-github-integration";
import createGithubApp from "./create-github-app";
+import { addLabelsToIssue } from "./create-github-labels";
const githubApp = createGithubApp();
@@ -55,7 +59,7 @@ export async function handleTaskCreated(data: {
const octokit = await githubApp.getInstallationOctokit(installationId);
- await octokit.rest.issues.create({
+ const createdIssue = await octokit.rest.issues.create({
owner: repositoryOwner,
repo: repositoryName,
title: `[Kaneo] ${title}`,
@@ -71,8 +75,38 @@ export async function handleTaskCreated(data: {
---
*This issue was automatically created from Kaneo task management system.*`,
- labels: ["kaneo", `priority:${priority || "low"}`, `status:${status}`],
});
+
+ const labelsToAdd = [
+ "kaneo",
+ `priority:${priority || "low"}`,
+ `status:${status}`,
+ ];
+ await addLabelsToIssue(
+ octokit,
+ repositoryOwner,
+ repositoryName,
+ createdIssue.data.number,
+ labelsToAdd,
+ );
+
+ try {
+ await db
+ .update(taskTable)
+ .set({
+ description: `${description || ""}
+
+---
+
+*Linked to GitHub issue: ${createdIssue.data.html_url}*`,
+ })
+ .where(eq(taskTable.id, taskId));
+ } catch (error) {
+ console.error(
+ "Failed to update task description with GitHub issue link:",
+ error,
+ );
+ }
} catch (error) {
console.error("Failed to create GitHub issue:", error);
}
diff --git a/apps/api/src/github-integration/utils/task-priority-changed.ts b/apps/api/src/github-integration/utils/task-priority-changed.ts
new file mode 100644
index 000000000..dcae52de9
--- /dev/null
+++ b/apps/api/src/github-integration/utils/task-priority-changed.ts
@@ -0,0 +1,131 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { taskTable } from "../../database/schema";
+import getGithubIntegration from "../controllers/get-github-integration";
+import createGithubApp from "./create-github-app";
+import { addLabelsToIssue } from "./create-github-labels";
+
+const githubApp = createGithubApp();
+
+export async function handleTaskPriorityChanged(data: {
+ taskId: string;
+ userEmail: string | null;
+ oldPriority: string;
+ newPriority: string;
+}) {
+ if (!githubApp) {
+ return;
+ }
+
+ const { taskId, oldPriority, newPriority } = data;
+
+ try {
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, taskId),
+ });
+
+ if (!task) {
+ console.log("Task not found for priority change:", taskId);
+ return;
+ }
+
+ const integration = await getGithubIntegration(task.projectId);
+
+ if (!integration || !integration.isActive) {
+ console.log(
+ "No active GitHub integration found for project:",
+ task.projectId,
+ );
+ return;
+ }
+
+ const hasKaneoLink = task.description?.includes("Linked to GitHub issue:");
+ const hasGitHubLink = task.description?.includes(
+ "Created from GitHub issue:",
+ );
+
+ if (!hasKaneoLink && !hasGitHubLink) {
+ console.log(
+ "Skipping GitHub issue update - task has no GitHub issue link:",
+ taskId,
+ );
+ return;
+ }
+
+ const { repositoryOwner, repositoryName } = integration;
+ console.log(
+ "Updating GitHub issue priority for repository:",
+ `${repositoryOwner}/${repositoryName}`,
+ );
+
+ let installationId = integration.installationId;
+
+ if (!installationId) {
+ const { data: installation } =
+ await githubApp.octokit.rest.apps.getRepoInstallation({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ });
+ installationId = installation.id;
+ }
+
+ const octokit = await githubApp.getInstallationOctokit(installationId);
+
+ let githubIssueUrlMatch = task.description?.match(
+ /Linked to GitHub issue: (https:\/\/github\.com\/[^\/]+\/[^\/]+\/issues\/\d+)/,
+ );
+
+ if (!githubIssueUrlMatch) {
+ githubIssueUrlMatch = task.description?.match(
+ /Created from GitHub issue: (https:\/\/github\.com\/[^\/]+\/[^\/]+\/issues\/\d+)/,
+ );
+ }
+
+ if (!githubIssueUrlMatch) {
+ console.log("GitHub issue URL not found in task description:", taskId);
+ return;
+ }
+
+ const githubIssueUrl = githubIssueUrlMatch[1];
+ const issueNumber = Number.parseInt(
+ githubIssueUrl?.split("/").pop() || "0",
+ 10,
+ );
+
+ if (!issueNumber) {
+ console.log("Could not extract issue number from URL:", githubIssueUrl);
+ return;
+ }
+
+ const labelsToAdd = [`priority:${newPriority}`];
+
+ try {
+ await octokit.rest.issues.removeLabel({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ name: `priority:${oldPriority}`,
+ });
+ } catch (error) {
+ console.log("Could not remove old priority label:", error);
+ }
+
+ try {
+ await addLabelsToIssue(
+ octokit,
+ repositoryOwner,
+ repositoryName,
+ issueNumber,
+ labelsToAdd,
+ );
+ } catch (error) {
+ console.error("Failed to add new priority label:", error);
+ }
+
+ console.log(
+ `Updated GitHub issue ${issueNumber} priority from ${oldPriority} to ${newPriority}`,
+ );
+ } catch (error) {
+ console.error("Failed to update GitHub issue priority:", error);
+ }
+}
diff --git a/apps/api/src/github-integration/utils/task-status-changed.ts b/apps/api/src/github-integration/utils/task-status-changed.ts
new file mode 100644
index 000000000..9f2d6a218
--- /dev/null
+++ b/apps/api/src/github-integration/utils/task-status-changed.ts
@@ -0,0 +1,157 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { taskTable } from "../../database/schema";
+import getGithubIntegration from "../controllers/get-github-integration";
+import createGithubApp from "./create-github-app";
+import { addLabelsToIssue } from "./create-github-labels";
+
+const githubApp = createGithubApp();
+
+export async function handleTaskStatusChanged(data: {
+ taskId: string;
+ userEmail: string | null;
+ oldStatus: string;
+ newStatus: string;
+}) {
+ if (!githubApp) {
+ return;
+ }
+
+ const { taskId, oldStatus, newStatus } = data;
+
+ try {
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, taskId),
+ });
+
+ if (!task) {
+ console.log("Task not found for status change:", taskId);
+ return;
+ }
+
+ const integration = await getGithubIntegration(task.projectId);
+
+ if (!integration || !integration.isActive) {
+ console.log(
+ "No active GitHub integration found for project:",
+ task.projectId,
+ );
+ return;
+ }
+
+ const hasKaneoLink = task.description?.includes("Linked to GitHub issue:");
+ const hasGitHubLink = task.description?.includes(
+ "Created from GitHub issue:",
+ );
+
+ if (!hasKaneoLink && !hasGitHubLink) {
+ console.log(
+ "Skipping GitHub issue update - task has no GitHub issue link:",
+ taskId,
+ );
+ return;
+ }
+
+ const { repositoryOwner, repositoryName } = integration;
+ console.log(
+ "Updating GitHub issue status for repository:",
+ `${repositoryOwner}/${repositoryName}`,
+ );
+
+ let installationId = integration.installationId;
+
+ if (!installationId) {
+ const { data: installation } =
+ await githubApp.octokit.rest.apps.getRepoInstallation({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ });
+ installationId = installation.id;
+ }
+
+ const octokit = await githubApp.getInstallationOctokit(installationId);
+
+ let githubIssueUrlMatch = task.description?.match(
+ /Linked to GitHub issue: (https:\/\/github\.com\/[^\/]+\/[^\/]+\/issues\/\d+)/,
+ );
+
+ if (!githubIssueUrlMatch) {
+ githubIssueUrlMatch = task.description?.match(
+ /Created from GitHub issue: (https:\/\/github\.com\/[^\/]+\/[^\/]+\/issues\/\d+)/,
+ );
+ }
+
+ if (!githubIssueUrlMatch) {
+ console.log("GitHub issue URL not found in task description:", taskId);
+ return;
+ }
+
+ const githubIssueUrl = githubIssueUrlMatch[1];
+ const issueNumber = Number.parseInt(
+ githubIssueUrl?.split("/").pop() || "0",
+ 10,
+ );
+
+ if (!issueNumber) {
+ console.log("Could not extract issue number from URL:", githubIssueUrl);
+ return;
+ }
+
+ const labelsToAdd = [`status:${newStatus}`];
+
+ try {
+ await octokit.rest.issues.removeLabel({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ name: `status:${oldStatus}`,
+ });
+ } catch (error) {
+ console.log("Could not remove old status label:", error);
+ }
+
+ try {
+ await addLabelsToIssue(
+ octokit,
+ repositoryOwner,
+ repositoryName,
+ issueNumber,
+ labelsToAdd,
+ );
+ } catch (error) {
+ console.error("Failed to add new status label:", error);
+ }
+
+ if (newStatus === "done") {
+ try {
+ await octokit.rest.issues.update({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ state: "closed",
+ });
+ console.log(`Closed GitHub issue ${issueNumber}`);
+ } catch (error) {
+ console.error("Failed to close GitHub issue:", error);
+ }
+ } else if (oldStatus === "done" && newStatus !== "done") {
+ try {
+ await octokit.rest.issues.update({
+ owner: repositoryOwner,
+ repo: repositoryName,
+ issue_number: issueNumber,
+ state: "open",
+ });
+ console.log(`Reopened GitHub issue ${issueNumber}`);
+ } catch (error) {
+ console.error("Failed to reopen GitHub issue:", error);
+ }
+ }
+
+ console.log(
+ `Updated GitHub issue ${issueNumber} status from ${oldStatus} to ${newStatus}`,
+ );
+ } catch (error) {
+ console.error("Failed to update GitHub issue status:", error);
+ }
+}
diff --git a/apps/api/src/task/controllers/update-task.ts b/apps/api/src/task/controllers/update-task.ts
index b92b1bb88..3f2b09574 100644
--- a/apps/api/src/task/controllers/update-task.ts
+++ b/apps/api/src/task/controllers/update-task.ts
@@ -56,6 +56,16 @@ async function updateTask(
});
}
+ if (existingTask.priority !== priority) {
+ await publishEvent("task.priority_changed", {
+ taskId: updatedTask.id,
+ userEmail: updatedTask.userEmail,
+ oldPriority: existingTask.priority,
+ newPriority: priority,
+ title: updatedTask.title,
+ });
+ }
+
if (existingTask.userEmail !== userEmail) {
await publishEvent("task.assignee_changed", {
taskId: updatedTask.id,
diff --git a/apps/web/src/components/project/github-integration-settings.tsx b/apps/web/src/components/project/github-integration-settings.tsx
index 4be0d32be..012b76e2d 100644
--- a/apps/web/src/components/project/github-integration-settings.tsx
+++ b/apps/web/src/components/project/github-integration-settings.tsx
@@ -254,19 +254,6 @@ export function GitHubIntegrationSettings({
return (
<div className="space-y-6">
- <div className="flex items-start gap-4">
- <div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
- <Github className="w-6 h-6" />
- </div>
- <div className="flex-1">
- <h3 className="text-lg font-semibold">GitHub Integration</h3>
- <p className="text-sm text-gray-600 dark:text-gray-400">
- Connect this project to a GitHub repository to sync issues and
- tasks.
- </p>
- </div>
- </div>
-
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">