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.

12.4 KB
Raw Blame
import { and, eq } from "drizzle-orm";
import db from "../../database";
import {
  columnTable,
  integrationTable,
  projectTable,
  taskTable,
  userTable,
  workspaceTable,
} from "../../database/schema";
import { safeOutboundError } from "../../utils/outbound-request";
import type {
  PluginContext,
  TaskAssigneeChangedEvent,
  TaskCommentCreatedEvent,
  TaskCreatedEvent,
  TaskDeletedEvent,
  TaskDescriptionChangedEvent,
  TaskDueDateChangedEvent,
  TaskMovedEvent,
  TaskPriorityChangedEvent,
  TaskStatusChangedEvent,
  TaskTitleChangedEvent,
  TaskUnassignedEvent,
} from "../types";
import { postToGenericWebhook } from "./client";
import type { GenericWebhookConfig, GenericWebhookEventKey } from "./config";
import { normalizeGenericWebhookConfig } from "./config";

type GenericWebhookTaskData = {
  id: string;
  title: string;
  number: number | null;
  status: string | null;
  statusName: string | null;
  priority: string | null;
  projectId: string;
  projectName: string;
  workspaceId: string;
  taskUrl: string;
};

function isEnabled(
  config: GenericWebhookConfig,
  key: GenericWebhookEventKey,
): boolean {
  return config.events?.[key] ?? false;
}

async function getTaskData(
  taskId: string,
  projectId: string,
): Promise<GenericWebhookTaskData | null> {
  const [taskRow] = await db
    .select({
      id: taskTable.id,
      title: taskTable.title,
      number: taskTable.number,
      status: taskTable.status,
      priority: taskTable.priority,
      columnName: columnTable.name,
      projectId: projectTable.id,
      projectName: projectTable.name,
      workspaceId: workspaceTable.id,
    })
    .from(taskTable)
    .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))
    .innerJoin(workspaceTable, eq(projectTable.workspaceId, workspaceTable.id))
    .leftJoin(
      columnTable,
      and(
        eq(taskTable.columnId, columnTable.id),
        eq(columnTable.projectId, projectTable.id),
      ),
    )
    .where(and(eq(taskTable.id, taskId), eq(projectTable.id, projectId)))
    .limit(1);

  if (!taskRow) {
    return null;
  }

  const clientUrl = process.env.KANEO_CLIENT_URL || "http://localhost:5173";

  return {
    ...taskRow,
    status: taskRow.status,
    statusName: taskRow.columnName ?? taskRow.status,
    taskUrl: `${clientUrl}/dashboard/workspace/${taskRow.workspaceId}/project/${taskRow.projectId}/task/${taskId}`,
  };
}

async function getActor(userId: string | null): Promise<{
  id: string | null;
  name: string | null;
}> {
  if (!userId) {
    return {
      id: null,
      name: null,
    };
  }

  const [user] = await db
    .select({ id: userTable.id, name: userTable.name })
    .from(userTable)
    .where(eq(userTable.id, userId))
    .limit(1);

  return {
    id: user?.id ?? userId,
    name: user?.name ?? null,
  };
}

async function persistWebhookHealth(
  projectId: string,
  update: (config: GenericWebhookConfig) => GenericWebhookConfig,
): Promise<void> {
  try {
    const integration = await db.query.integrationTable.findFirst({
      where: and(
        eq(integrationTable.projectId, projectId),
        eq(integrationTable.type, "generic-webhook"),
      ),
    });

    if (!integration) {
      return;
    }

    const currentConfig = normalizeGenericWebhookConfig(
      JSON.parse(integration.config) as GenericWebhookConfig,
    );

    await db
      .update(integrationTable)
      .set({
        config: JSON.stringify(update(currentConfig)),
        updatedAt: new Date(),
      })
      .where(eq(integrationTable.id, integration.id));
  } catch {
    console.error("persistWebhookHealth failed", {
      error: "Webhook health update failed",
      projectId,
    });
  }
}

async function deliverWebhookEvent(
  config: GenericWebhookConfig,
  eventName: string,
  taskId: string,
  projectId: string,
  payload: Record<string, unknown>,
): Promise<boolean> {
  const attempt = {
    eventName,
    taskId,
    projectId,
    webhookUrl: "configured destination",
  };

  try {
    await postToGenericWebhook(config.webhookUrl, payload, config.secret);

    void persistWebhookHealth(projectId, (currentConfig) => ({
      ...currentConfig,
      health: {
        ...currentConfig.health,
        lastSuccessAt: new Date().toISOString(),
        lastFailureMessage: undefined,
        lastAttempt: attempt,
      },
    }));
    return true;
  } catch (error) {
    const message = safeOutboundError(error);

    void persistWebhookHealth(projectId, (currentConfig) => ({
      ...currentConfig,
      health: {
        ...currentConfig.health,
        lastFailureAt: new Date().toISOString(),
        lastFailureMessage: message,
        failureCount: (currentConfig.health?.failureCount ?? 0) + 1,
        lastAttempt: attempt,
      },
    }));

    console.error("postToGenericWebhook failed", {
      error: message,
      eventName,
      taskId,
      projectId,
      webhookUrl: "configured destination",
    });
    return false;
  }
}

async function sendEvent(
  config: GenericWebhookConfig,
  eventName: string,
  taskId: string,
  projectId: string,
  userId: string | null,
  data: Record<string, unknown>,
): Promise<boolean> {
  const task = await getTaskData(taskId, projectId);
  if (!task) return false;

  const actor = await getActor(userId);

  return deliverWebhookEvent(config, eventName, taskId, projectId, {
    event: eventName,
    timestamp: new Date().toISOString(),
    integration: {
      type: "generic-webhook",
    },
    project: {
      id: task.projectId,
      name: task.projectName,
      workspaceId: task.workspaceId,
    },
    task: {
      id: task.id,
      number: task.number,
      title: task.title,
      status: task.status,
      statusName: task.statusName,
      priority: task.priority,
      url: task.taskUrl,
    },
    actor,
    data,
  });
}

export async function sendDueDateReminder(
  config: GenericWebhookConfig,
  taskId: string,
  projectId: string,
  leadTimeMinutes: number,
  dueDate: Date,
): Promise<boolean> {
  const normalizedConfig = normalizeGenericWebhookConfig(config);
  if (!isEnabled(normalizedConfig, "dueDateReminder")) return false;

  return sendEvent(
    normalizedConfig,
    "task.due_date_reminder",
    taskId,
    projectId,
    null,
    {
      dueDate: dueDate.toISOString(),
      leadTimeMinutes,
    },
  );
}

export async function handleTaskCreated(
  event: TaskCreatedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskCreated")) return;

  await sendEvent(
    config,
    "task.created",
    event.taskId,
    event.projectId,
    event.userId,
    {
      title: event.title,
      description: event.description,
      priority: event.priority,
      status: event.status,
      number: event.number,
    },
  );
}

export async function handleTaskStatusChanged(
  event: TaskStatusChangedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskStatusChanged")) return;

  await sendEvent(
    config,
    "task.status_changed",
    event.taskId,
    event.projectId,
    event.userId,
    {
      title: event.title,
      oldStatus: event.oldStatus,
      newStatus: event.newStatus,
    },
  );
}

export async function handleTaskPriorityChanged(
  event: TaskPriorityChangedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskPriorityChanged")) return;

  await sendEvent(
    config,
    "task.priority_changed",
    event.taskId,
    event.projectId,
    event.userId,
    {
      title: event.title,
      oldPriority: event.oldPriority,
      newPriority: event.newPriority,
    },
  );
}

export async function handleTaskTitleChanged(
  event: TaskTitleChangedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskTitleChanged")) return;

  await sendEvent(
    config,
    "task.title_changed",
    event.taskId,
    event.projectId,
    event.userId,
    {
      oldTitle: event.oldTitle,
      newTitle: event.newTitle,
    },
  );
}

export async function handleTaskDescriptionChanged(
  event: TaskDescriptionChangedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskDescriptionChanged")) return;

  await sendEvent(
    config,
    "task.description_changed",
    event.taskId,
    event.projectId,
    event.userId,
    {
      oldDescription: event.oldDescription,
      newDescription: event.newDescription,
    },
  );
}

export async function handleTaskCommentCreated(
  event: TaskCommentCreatedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskCommentCreated")) return;

  await sendEvent(
    config,
    "task.comment_created",
    event.taskId,
    event.projectId,
    event.userId,
    {
      comment: event.comment,
    },
  );
}

async function sendTaskDeletedEvent(
  config: GenericWebhookConfig,
  event: TaskDeletedEvent,
): Promise<boolean> {
  const [project] = await db
    .select({
      id: projectTable.id,
      name: projectTable.name,
      workspaceId: projectTable.workspaceId,
    })
    .from(projectTable)
    .where(eq(projectTable.id, event.projectId))
    .limit(1);

  if (!project) return false;

  const actor = await getActor(event.userId);

  return deliverWebhookEvent(
    config,
    "task.deleted",
    event.taskId,
    event.projectId,
    {
      event: "task.deleted",
      timestamp: new Date().toISOString(),
      integration: {
        type: "generic-webhook",
      },
      project: {
        id: project.id,
        name: project.name,
        workspaceId: project.workspaceId,
      },
      task: {
        id: event.taskId,
        title: event.title,
      },
      actor,
      data: {},
    },
  );
}

export async function handleTaskDeleted(
  event: TaskDeletedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskDeleted")) return;

  await sendTaskDeletedEvent(config, event);
}

export async function handleTaskMoved(
  event: TaskMovedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskMoved")) return;

  await sendEvent(
    config,
    "task.moved",
    event.taskId,
    event.projectId,
    event.userId,
    {
      fromProjectId: event.fromProjectId,
      fromProjectName: event.fromProjectName,
      toProjectId: event.toProjectId,
      toProjectName: event.toProjectName,
      oldStatus: event.oldStatus,
      newStatus: event.newStatus,
    },
  );
}

export async function handleTaskDueDateChanged(
  event: TaskDueDateChangedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskDueDateChanged")) return;

  await sendEvent(
    config,
    "task.due_date_changed",
    event.taskId,
    event.projectId,
    event.userId,
    {
      title: event.title,
      oldDueDate: event.oldDueDate,
      newDueDate: event.newDueDate,
    },
  );
}

export async function handleTaskAssigneeChanged(
  event: TaskAssigneeChangedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskAssigneeChanged")) return;

  await sendEvent(
    config,
    "task.assignee_changed",
    event.taskId,
    event.projectId,
    event.userId,
    {
      title: event.title,
      oldAssigneeId: event.oldAssignee ?? null,
      newAssigneeId: event.newAssigneeId,
      newAssignee: event.newAssignee ?? null,
    },
  );
}

export async function handleTaskUnassigned(
  event: TaskUnassignedEvent,
  context: PluginContext,
): Promise<void> {
  const config = normalizeGenericWebhookConfig(
    context.config as GenericWebhookConfig,
  );
  if (!isEnabled(config, "taskUnassigned")) return;

  await sendEvent(
    config,
    "task.unassigned",
    event.taskId,
    event.projectId,
    event.userId,
    {
      title: event.title,
    },
  );
}