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): add pagination, bulk ops, comments, members, and project archival

Ivan Bobchenkovaf22fd257fd5
diff --git a/apps/api/drizzle/0015_add_comment_table.sql b/apps/api/drizzle/0015_add_comment_table.sql
new file mode 100644
index 000000000..671bc35d2
--- /dev/null
+++ b/apps/api/drizzle/0015_add_comment_table.sql
@@ -0,0 +1,13 @@
+CREATE TABLE "comment" (
+ "id" text PRIMARY KEY NOT NULL,
+ "task_id" text NOT NULL,
+ "user_id" text NOT NULL,
+ "content" text NOT NULL,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ "updated_at" timestamp DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+ALTER TABLE "comment" ADD CONSTRAINT "comment_task_id_task_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."task"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint
+ALTER TABLE "comment" ADD CONSTRAINT "comment_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint
+CREATE INDEX "comment_task_idx" ON "comment" USING btree ("task_id");--> statement-breakpoint
+CREATE INDEX "comment_user_idx" ON "comment" USING btree ("user_id");
diff --git a/apps/api/drizzle/0016_project_archival.sql b/apps/api/drizzle/0016_project_archival.sql
new file mode 100644
index 000000000..5222d77b3
--- /dev/null
+++ b/apps/api/drizzle/0016_project_archival.sql
@@ -0,0 +1,30 @@
+CREATE TABLE "asset" (
+ "id" text PRIMARY KEY NOT NULL,
+ "workspace_id" text NOT NULL,
+ "project_id" text NOT NULL,
+ "task_id" text,
+ "activity_id" text,
+ "object_key" text NOT NULL,
+ "filename" text NOT NULL,
+ "mime_type" text NOT NULL,
+ "size" integer NOT NULL,
+ "kind" text DEFAULT 'image' NOT NULL,
+ "surface" text DEFAULT 'description' NOT NULL,
+ "created_by" text,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ CONSTRAINT "asset_object_key_unique" UNIQUE("object_key")
+);
+--> statement-breakpoint
+ALTER TABLE "apikey" ALTER COLUMN "reference_id" SET NOT NULL;--> statement-breakpoint
+ALTER TABLE "apikey" ALTER COLUMN "user_id" DROP NOT NULL;--> statement-breakpoint
+ALTER TABLE "project" ADD COLUMN "archived_at" timestamp;--> statement-breakpoint
+ALTER TABLE "asset" ADD CONSTRAINT "asset_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint
+ALTER TABLE "asset" ADD CONSTRAINT "asset_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint
+ALTER TABLE "asset" ADD CONSTRAINT "asset_task_id_task_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."task"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint
+ALTER TABLE "asset" ADD CONSTRAINT "asset_activity_id_activity_id_fk" FOREIGN KEY ("activity_id") REFERENCES "public"."activity"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint
+ALTER TABLE "asset" ADD CONSTRAINT "asset_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE cascade;--> statement-breakpoint
+CREATE INDEX "asset_workspaceId_idx" ON "asset" USING btree ("workspace_id");--> statement-breakpoint
+CREATE INDEX "asset_projectId_idx" ON "asset" USING btree ("project_id");--> statement-breakpoint
+CREATE INDEX "asset_taskId_idx" ON "asset" USING btree ("task_id");--> statement-breakpoint
+CREATE INDEX "asset_activityId_idx" ON "asset" USING btree ("activity_id");--> statement-breakpoint
+ALTER TABLE "apikey" ADD CONSTRAINT "apikey_reference_id_user_id_fk" FOREIGN KEY ("reference_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;
\ No newline at end of file
diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.json
index c8b014564..c474c4ba1 100644
--- a/apps/api/drizzle/meta/_journal.json
+++ b/apps/api/drizzle/meta/_journal.json
@@ -106,6 +106,20 @@
"when": 1773259300000,
"tag": "0014_private_assets",
"breakpoints": true
+ },
+ {
+ "idx": 15,
+ "version": "7",
+ "when": 1773947411304,
+ "tag": "0015_add_comment_table",
+ "breakpoints": true
+ },
+ {
+ "idx": 16,
+ "version": "7",
+ "when": 1773948000000,
+ "tag": "0016_project_archival",
+ "breakpoints": true
}
]
}
diff --git a/apps/api/src/comment/controllers/create-comment.ts b/apps/api/src/comment/controllers/create-comment.ts
new file mode 100644
index 000000000..23e5ad4d1
--- /dev/null
+++ b/apps/api/src/comment/controllers/create-comment.ts
@@ -0,0 +1,22 @@
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { commentTable } from "../../database/schema";
+
+async function createComment(taskId: string, userId: string, content: string) {
+ const [comment] = await db
+ .insert(commentTable)
+ .values({
+ taskId,
+ userId,
+ content,
+ })
+ .returning();
+
+ if (!comment) {
+ throw new HTTPException(500, { message: "Failed to create comment" });
+ }
+
+ return comment;
+}
+
+export default createComment;
diff --git a/apps/api/src/comment/controllers/delete-comment.ts b/apps/api/src/comment/controllers/delete-comment.ts
new file mode 100644
index 000000000..c2687b6c5
--- /dev/null
+++ b/apps/api/src/comment/controllers/delete-comment.ts
@@ -0,0 +1,35 @@
+import { eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { commentTable } from "../../database/schema";
+
+async function deleteComment(userId: string, id: string) {
+ const [existing] = await db
+ .select({ userId: commentTable.userId })
+ .from(commentTable)
+ .where(eq(commentTable.id, id))
+ .limit(1);
+
+ if (!existing) {
+ throw new HTTPException(404, { message: "Comment not found" });
+ }
+
+ if (existing.userId !== userId) {
+ throw new HTTPException(403, {
+ message: "Only the author can delete this comment",
+ });
+ }
+
+ const [deleted] = await db
+ .delete(commentTable)
+ .where(eq(commentTable.id, id))
+ .returning();
+
+ if (!deleted) {
+ throw new HTTPException(500, { message: "Failed to delete comment" });
+ }
+
+ return deleted;
+}
+
+export default deleteComment;
diff --git a/apps/api/src/comment/controllers/get-comments.ts b/apps/api/src/comment/controllers/get-comments.ts
new file mode 100644
index 000000000..3b5afe79b
--- /dev/null
+++ b/apps/api/src/comment/controllers/get-comments.ts
@@ -0,0 +1,36 @@
+import { asc, eq } from "drizzle-orm";
+import db from "../../database";
+import { commentTable, userTable } from "../../database/schema";
+
+async function getComments(taskId: string) {
+ const comments = await db
+ .select({
+ id: commentTable.id,
+ taskId: commentTable.taskId,
+ userId: commentTable.userId,
+ content: commentTable.content,
+ createdAt: commentTable.createdAt,
+ updatedAt: commentTable.updatedAt,
+ userName: userTable.name,
+ userImage: userTable.image,
+ })
+ .from(commentTable)
+ .leftJoin(userTable, eq(commentTable.userId, userTable.id))
+ .where(eq(commentTable.taskId, taskId))
+ .orderBy(asc(commentTable.createdAt));
+
+ return comments.map((c) => ({
+ id: c.id,
+ taskId: c.taskId,
+ userId: c.userId,
+ content: c.content,
+ createdAt: c.createdAt,
+ updatedAt: c.updatedAt,
+ user: {
+ name: c.userName ?? "",
+ image: c.userImage,
+ },
+ }));
+}
+
+export default getComments;
diff --git a/apps/api/src/comment/controllers/update-comment.ts b/apps/api/src/comment/controllers/update-comment.ts
new file mode 100644
index 000000000..2b38c5e0b
--- /dev/null
+++ b/apps/api/src/comment/controllers/update-comment.ts
@@ -0,0 +1,36 @@
+import { eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { commentTable } from "../../database/schema";
+
+async function updateComment(userId: string, id: string, content: string) {
+ const [existing] = await db
+ .select({ userId: commentTable.userId })
+ .from(commentTable)
+ .where(eq(commentTable.id, id))
+ .limit(1);
+
+ if (!existing) {
+ throw new HTTPException(404, { message: "Comment not found" });
+ }
+
+ if (existing.userId !== userId) {
+ throw new HTTPException(403, {
+ message: "Only the author can edit this comment",
+ });
+ }
+
+ const [updated] = await db
+ .update(commentTable)
+ .set({ content })
+ .where(eq(commentTable.id, id))
+ .returning();
+
+ if (!updated) {
+ throw new HTTPException(500, { message: "Failed to update comment" });
+ }
+
+ return updated;
+}
+
+export default updateComment;
diff --git a/apps/api/src/comment/index.ts b/apps/api/src/comment/index.ts
new file mode 100644
index 000000000..92cd1ba3e
--- /dev/null
+++ b/apps/api/src/comment/index.ts
@@ -0,0 +1,124 @@
+import { Hono } from "hono";
+import { describeRoute, resolver, validator } from "hono-openapi";
+import * as v from "valibot";
+import { commentSchema } from "../schemas";
+import { workspaceAccess } from "../utils/workspace-access-middleware";
+import createComment from "./controllers/create-comment";
+import deleteComment from "./controllers/delete-comment";
+import getComments from "./controllers/get-comments";
+import updateComment from "./controllers/update-comment";
+
+const comment = new Hono<{
+ Variables: {
+ userId: string;
+ };
+}>()
+ .get(
+ "/:taskId",
+ describeRoute({
+ operationId: "getTaskComments",
+ tags: ["Comments"],
+ description: "Get all comments for a specific task",
+ responses: {
+ 200: {
+ description: "List of comments for the task",
+ content: {
+ "application/json": {
+ schema: resolver(v.array(commentSchema)),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ taskId: v.string() })),
+ workspaceAccess.fromTaskId(),
+ async (c) => {
+ const { taskId } = c.req.valid("param");
+ const comments = await getComments(taskId);
+ return c.json(comments);
+ },
+ )
+ .post(
+ "/:taskId",
+ describeRoute({
+ operationId: "createTaskComment",
+ tags: ["Comments"],
+ description: "Create a new comment on a task",
+ responses: {
+ 200: {
+ description: "Comment created successfully",
+ content: {
+ "application/json": { schema: resolver(commentSchema) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ taskId: v.string() })),
+ validator(
+ "json",
+ v.object({ content: v.pipe(v.string(), v.minLength(1)) }),
+ ),
+ workspaceAccess.fromTaskId(),
+ async (c) => {
+ const { taskId } = c.req.valid("param");
+ const { content } = c.req.valid("json");
+ const userId = c.get("userId");
+ const newComment = await createComment(taskId, userId, content);
+ return c.json(newComment);
+ },
+ )
+ .put(
+ "/:id",
+ describeRoute({
+ operationId: "updateTaskComment",
+ tags: ["Comments"],
+ description: "Update an existing comment (author only)",
+ responses: {
+ 200: {
+ description: "Comment updated successfully",
+ content: {
+ "application/json": { schema: resolver(commentSchema) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ id: v.string() })),
+ validator(
+ "json",
+ v.object({ content: v.pipe(v.string(), v.minLength(1)) }),
+ ),
+ workspaceAccess.fromComment(),
+ async (c) => {
+ const { id } = c.req.valid("param");
+ const { content } = c.req.valid("json");
+ const userId = c.get("userId");
+ const updated = await updateComment(userId, id, content);
+ return c.json(updated);
+ },
+ )
+ .delete(
+ "/:id",
+ describeRoute({
+ operationId: "deleteTaskComment",
+ tags: ["Comments"],
+ description: "Delete a comment (author only)",
+ responses: {
+ 200: {
+ description: "Comment deleted successfully",
+ content: {
+ "application/json": { schema: resolver(commentSchema) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ id: v.string() })),
+ workspaceAccess.fromComment(),
+ async (c) => {
+ const { id } = c.req.valid("param");
+ const userId = c.get("userId");
+ const deleted = await deleteComment(userId, id);
+ return c.json(deleted);
+ },
+ );
+
+export default comment;
diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.ts
index 0aab6c127..1f09684e5 100644
--- a/apps/api/src/database/index.ts
+++ b/apps/api/src/database/index.ts
@@ -7,6 +7,7 @@ import {
apikeyTableRelations,
assetTableRelations,
columnTableRelations,
+ commentTableRelations,
externalLinkTableRelations,
githubIntegrationTableRelations,
integrationTableRelations,
@@ -31,6 +32,7 @@ import {
apikeyTable,
assetTable,
columnTable,
+ commentTable,
externalLinkTable,
githubIntegrationTable,
integrationTable,
@@ -64,6 +66,7 @@ export const schema = {
activityTable,
apikeyTable,
columnTable,
+ commentTable,
externalLinkTable,
githubIntegrationTable,
integrationTable,
@@ -86,6 +89,7 @@ export const schema = {
activityTableRelations,
apikeyTableRelations,
columnTableRelations,
+ commentTableRelations,
externalLinkTableRelations,
githubIntegrationTableRelations,
integrationTableRelations,
diff --git a/apps/api/src/database/relations.ts b/apps/api/src/database/relations.ts
index ff17e709e..7e95849ca 100644
--- a/apps/api/src/database/relations.ts
+++ b/apps/api/src/database/relations.ts
@@ -5,6 +5,7 @@ import {
apikeyTable,
assetTable,
columnTable,
+ commentTable,
externalLinkTable,
githubIntegrationTable,
integrationTable,
@@ -33,6 +34,7 @@ export const userTableRelations = relations(userTable, ({ many }) => ({
assignedTasks: many(taskTable),
timeEntries: many(timeEntryTable),
activities: many(activityTable),
+ comments: many(commentTable),
assets: many(assetTable),
notifications: many(notificationTable),
sentInvitations: many(invitationTable),
@@ -137,6 +139,7 @@ export const taskTableRelations = relations(taskTable, ({ one, many }) => ({
}),
timeEntries: many(timeEntryTable),
activities: many(activityTable),
+ comments: many(commentTable),
assets: many(assetTable),
labels: many(labelTable),
externalLinks: many(externalLinkTable),
@@ -281,3 +284,14 @@ export const externalLinkTableRelations = relations(
}),
}),
);
+
+export const commentTableRelations = relations(commentTable, ({ one }) => ({
+ task: one(taskTable, {
+ fields: [commentTable.taskId],
+ references: [taskTable.id],
+ }),
+ user: one(userTable, {
+ fields: [commentTable.userId],
+ references: [userTable.id],
+ }),
+}));
diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.ts
index 803d8d217..1866bf558 100644
--- a/apps/api/src/database/schema.ts
+++ b/apps/api/src/database/schema.ts
@@ -208,6 +208,7 @@ export const projectTable = pgTable("project", {
description: text("description"),
createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),
isPublic: boolean("is_public").default(false),
+ archivedAt: timestamp("archived_at", { mode: "date" }),
});
export const columnTable = pgTable(
@@ -505,6 +506,37 @@ export const externalLinkTable = pgTable(
],
);
+export const commentTable = pgTable(
+ "comment",
+ {
+ id: text("id")
+ .$defaultFn(() => createId())
+ .primaryKey(),
+ taskId: text("task_id")
+ .notNull()
+ .references(() => taskTable.id, {
+ onDelete: "cascade",
+ onUpdate: "cascade",
+ }),
+ userId: text("user_id")
+ .notNull()
+ .references(() => userTable.id, {
+ onDelete: "cascade",
+ onUpdate: "cascade",
+ }),
+ content: text("content").notNull(),
+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),
+ updatedAt: timestamp("updated_at", { mode: "date" })
+ .defaultNow()
+ .$onUpdate(() => new Date())
+ .notNull(),
+ },
+ (table) => [
+ index("comment_task_idx").on(table.taskId),
+ index("comment_user_idx").on(table.userId),
+ ],
+);
+
export const apikeyTable = pgTable(
"apikey",
{
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 69844d300..79f95cf01 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -15,6 +15,7 @@ import * as v from "valibot";
import activity from "./activity";
import { auth } from "./auth";
import column from "./column";
+import comment from "./comment";
import config from "./config";
import db, { schema } from "./database";
import externalLink from "./external-link";
@@ -49,6 +50,7 @@ import {
import { validateWorkspaceAccess } from "./utils/validate-workspace-access";
import { verifyApiKey } from "./utils/verify-api-key";
import workflowRule from "./workflow-rule";
+import workspace from "./workspace";
type ApiKey = {
id: string;
@@ -380,6 +382,7 @@ const projectApi = api.route("/project", project);
const taskApi = api.route("/task", task);
const columnApi = api.route("/column", column);
const activityApi = api.route("/activity", activity);
+const commentApi = api.route("/comment", comment);
const timeEntryApi = api.route("/time-entry", timeEntry);
const labelApi = api.route("/label", label);
const notificationApi = api.route("/notification", notification);
@@ -391,6 +394,7 @@ const githubIntegrationApi = api.route(
const externalLinkApi = api.route("/external-link", externalLink);
const workflowRuleApi = api.route("/workflow-rule", workflowRule);
const invitationApi = api.route("/invitation", invitation);
+const workspaceApi = api.route("/workspace", workspace);
app.route("/api", api);
@@ -434,6 +438,7 @@ export type AppType =
| typeof taskApi
| typeof columnApi
| typeof activityApi
+ | typeof commentApi
| typeof timeEntryApi
| typeof labelApi
| typeof notificationApi
@@ -442,6 +447,7 @@ export type AppType =
| typeof externalLinkApi
| typeof workflowRuleApi
| typeof invitationApi
+ | typeof workspaceApi
| typeof publicProjectApi
| typeof invitationPublicApi;
diff --git a/apps/api/src/project/controllers/archive-project.ts b/apps/api/src/project/controllers/archive-project.ts
new file mode 100644
index 000000000..2d2c83da6
--- /dev/null
+++ b/apps/api/src/project/controllers/archive-project.ts
@@ -0,0 +1,36 @@
+import { and, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { projectTable } from "../../database/schema";
+
+async function archiveProject(id: string, workspaceId: string) {
+ const [existingProject] = await db
+ .select()
+ .from(projectTable)
+ .where(
+ and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
+ );
+
+ if (!existingProject) {
+ throw new HTTPException(404, {
+ message:
+ "Project doesn't exist or doesn't belong to the specified workspace",
+ });
+ }
+
+ const [archivedProject] = await db
+ .update(projectTable)
+ .set({ archivedAt: new Date() })
+ .where(eq(projectTable.id, id))
+ .returning();
+
+ if (!archivedProject) {
+ throw new HTTPException(500, {
+ message: "Failed to archive project",
+ });
+ }
+
+ return archivedProject;
+}
+
+export default archiveProject;
diff --git a/apps/api/src/project/controllers/get-projects.ts b/apps/api/src/project/controllers/get-projects.ts
index d6a4f71cc..bcee8eb18 100644
--- a/apps/api/src/project/controllers/get-projects.ts
+++ b/apps/api/src/project/controllers/get-projects.ts
@@ -1,10 +1,15 @@
-import { eq } from "drizzle-orm";
+import { and, eq, isNull } from "drizzle-orm";
import db from "../../database";
import { projectTable } from "../../database/schema";
-async function getProjects(workspaceId: string) {
+async function getProjects(workspaceId: string, includeArchived = false) {
const projects = await db.query.projectTable.findMany({
- where: eq(projectTable.workspaceId, workspaceId),
+ where: includeArchived
+ ? eq(projectTable.workspaceId, workspaceId)
+ : and(
+ eq(projectTable.workspaceId, workspaceId),
+ isNull(projectTable.archivedAt),
+ ),
with: {
tasks: true,
},
diff --git a/apps/api/src/project/controllers/unarchive-project.ts b/apps/api/src/project/controllers/unarchive-project.ts
new file mode 100644
index 000000000..ec8eabbeb
--- /dev/null
+++ b/apps/api/src/project/controllers/unarchive-project.ts
@@ -0,0 +1,36 @@
+import { and, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { projectTable } from "../../database/schema";
+
+async function unarchiveProject(id: string, workspaceId: string) {
+ const [existingProject] = await db
+ .select()
+ .from(projectTable)
+ .where(
+ and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
+ );
+
+ if (!existingProject) {
+ throw new HTTPException(404, {
+ message:
+ "Project doesn't exist or doesn't belong to the specified workspace",
+ });
+ }
+
+ const [unarchivedProject] = await db
+ .update(projectTable)
+ .set({ archivedAt: null })
+ .where(eq(projectTable.id, id))
+ .returning();
+
+ if (!unarchivedProject) {
+ throw new HTTPException(500, {
+ message: "Failed to unarchive project",
+ });
+ }
+
+ return unarchivedProject;
+}
+
+export default unarchiveProject;
diff --git a/apps/api/src/project/index.ts b/apps/api/src/project/index.ts
index 72df229d3..c902dd804 100644
--- a/apps/api/src/project/index.ts
+++ b/apps/api/src/project/index.ts
@@ -3,10 +3,12 @@ import { describeRoute, resolver, validator } from "hono-openapi";
import * as v from "valibot";
import { projectSchema } from "../schemas";
import { workspaceAccess } from "../utils/workspace-access-middleware";
+import archiveProjectCtrl from "./controllers/archive-project";
import createProjectCtrl from "./controllers/create-project";
import deleteProjectCtrl from "./controllers/delete-project";
import getProjectCtrl from "./controllers/get-project";
import getProjectsCtrl from "./controllers/get-projects";
+import unarchiveProjectCtrl from "./controllers/unarchive-project";
import updateProjectCtrl from "./controllers/update-project";
const project = new Hono<{
@@ -30,11 +32,21 @@ const project = new Hono<{
},
},
}),
- validator("query", v.object({ workspaceId: v.string() })),
+ validator(
+ "query",
+ v.object({
+ workspaceId: v.string(),
+ includeArchived: v.optional(v.string()),
+ }),
+ ),
workspaceAccess.fromQuery(),
async (c) => {
const workspaceId = c.get("workspaceId");
- const projects = await getProjectsCtrl(workspaceId);
+ const { includeArchived } = c.req.valid("query");
+ const projects = await getProjectsCtrl(
+ workspaceId,
+ includeArchived === "true",
+ );
return c.json(projects);
},
)
@@ -160,6 +172,54 @@ const project = new Hono<{
const deletedProject = await deleteProjectCtrl(id, workspaceId);
return c.json(deletedProject);
},
+ )
+ .put(
+ "/:id/archive",
+ describeRoute({
+ operationId: "archiveProject",
+ tags: ["Projects"],
+ description: "Archive a project by ID",
+ responses: {
+ 200: {
+ description: "Project archived successfully",
+ content: {
+ "application/json": { schema: resolver(projectSchema) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ id: v.string() })),
+ workspaceAccess.fromProject(),
+ async (c) => {
+ const { id } = c.req.valid("param");
+ const workspaceId = c.get("workspaceId");
+ const archivedProject = await archiveProjectCtrl(id, workspaceId);
+ return c.json(archivedProject);
+ },
+ )
+ .put(
+ "/:id/unarchive",
+ describeRoute({
+ operationId: "unarchiveProject",
+ tags: ["Projects"],
+ description: "Unarchive a project by ID",
+ responses: {
+ 200: {
+ description: "Project unarchived successfully",
+ content: {
+ "application/json": { schema: resolver(projectSchema) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ id: v.string() })),
+ workspaceAccess.fromProject(),
+ async (c) => {
+ const { id } = c.req.valid("param");
+ const workspaceId = c.get("workspaceId");
+ const unarchivedProject = await unarchiveProjectCtrl(id, workspaceId);
+ return c.json(unarchivedProject);
+ },
);
export default project;
diff --git a/apps/api/src/schemas.ts b/apps/api/src/schemas.ts
index fa0c737b1..c6d2dc584 100644
--- a/apps/api/src/schemas.ts
+++ b/apps/api/src/schemas.ts
@@ -18,6 +18,7 @@ export const projectSchema = v.object({
description: v.nullable(v.string()),
createdAt: v.date(),
isPublic: v.nullable(v.boolean()),
+ archivedAt: v.nullable(v.date()),
});
export const taskSchema = v.object({
@@ -105,6 +106,21 @@ export const githubIntegrationSchema = v.object({
updatedAt: v.date(),
});
+export const commentSchema = v.object({
+ id: v.string(),
+ taskId: v.string(),
+ userId: v.string(),
+ content: v.string(),
+ createdAt: v.date(),
+ updatedAt: v.date(),
+ user: v.optional(
+ v.object({
+ name: v.string(),
+ image: v.nullable(v.string()),
+ }),
+ ),
+});
+
export const configSchema = v.object({
disableRegistration: v.nullable(v.boolean()),
isDemoMode: v.boolean(),
diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.ts
new file mode 100644
index 000000000..1dd60f05f
--- /dev/null
+++ b/apps/api/src/task/controllers/bulk-update-tasks.ts
@@ -0,0 +1,198 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import {
+ columnTable,
+ labelTable,
+ projectTable,
+ taskTable,
+ workspaceUserTable,
+} from "../../database/schema";
+
+type BulkOperation =
+ | "updateStatus"
+ | "updatePriority"
+ | "updateAssignee"
+ | "delete"
+ | "addLabel"
+ | "removeLabel";
+
+async function bulkUpdateTasks({
+ taskIds,
+ operation,
+ value,
+ userId,
+}: {
+ taskIds: string[];
+ operation: BulkOperation;
+ value?: string | null;
+ userId: string;
+}) {
+ const tasks = await db
+ .select({
+ id: taskTable.id,
+ projectId: taskTable.projectId,
+ workspaceId: projectTable.workspaceId,
+ })
+ .from(taskTable)
+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))
+ .where(inArray(taskTable.id, taskIds));
+
+ if (tasks.length === 0) {
+ throw new HTTPException(404, {
+ message: "No tasks found",
+ });
+ }
+
+ const workspaceIds = [...new Set(tasks.map((t) => t.workspaceId))];
+
+ if (workspaceIds.length > 1) {
+ throw new HTTPException(400, {
+ message: "All tasks must belong to the same workspace",
+ });
+ }
+
+ const workspaceId = workspaceIds[0];
+
+ if (!workspaceId) {
+ throw new HTTPException(400, {
+ message: "Could not determine workspace",
+ });
+ }
+
+ const [membership] = await db
+ .select({ id: workspaceUserTable.id })
+ .from(workspaceUserTable)
+ .where(
+ and(
+ eq(workspaceUserTable.userId, userId),
+ eq(workspaceUserTable.workspaceId, workspaceId),
+ ),
+ )
+ .limit(1);
+
+ if (!membership) {
+ throw new HTTPException(403, {
+ message: "You don't have access to this workspace",
+ });
+ }
+
+ const foundIds = tasks.map((t) => t.id);
+ let updatedCount = 0;
+
+ switch (operation) {
+ case "updateStatus": {
+ if (!value) {
+ throw new HTTPException(400, { message: "Status value is required" });
+ }
+ const projectIds = [...new Set(tasks.map((t) => t.projectId))];
+
+ for (const projectId of projectIds) {
+ const column = await db.query.columnTable.findFirst({
+ where: and(
+ eq(columnTable.projectId, projectId),
+ eq(columnTable.slug, value),
+ ),
+ });
+
+ const projectTaskIds = tasks
+ .filter((t) => t.projectId === projectId)
+ .map((t) => t.id);
+
+ const result = await db
+ .update(taskTable)
+ .set({ status: value, columnId: column?.id ?? null })
+ .where(inArray(taskTable.id, projectTaskIds));
+
+ updatedCount += result.rowCount ?? projectTaskIds.length;
+ }
+ break;
+ }
+
+ case "updatePriority": {
+ if (!value) {
+ throw new HTTPException(400, { message: "Priority value is required" });
+ }
+ const result = await db
+ .update(taskTable)
+ .set({ priority: value })
+ .where(inArray(taskTable.id, foundIds));
+
+ updatedCount = result.rowCount ?? foundIds.length;
+ break;
+ }
+
+ case "updateAssignee": {
+ const result = await db
+ .update(taskTable)
+ .set({ userId: value || null })
+ .where(inArray(taskTable.id, foundIds));
+
+ updatedCount = result.rowCount ?? foundIds.length;
+ break;
+ }
+
+ case "delete": {
+ const result = await db
+ .delete(taskTable)
+ .where(inArray(taskTable.id, foundIds));
+
+ updatedCount = result.rowCount ?? foundIds.length;
+ break;
+ }
+
+ case "addLabel": {
+ if (!value) {
+ throw new HTTPException(400, { message: "Label ID is required" });
+ }
+
+ const label = await db.query.labelTable.findFirst({
+ where: eq(labelTable.id, value),
+ });
+
+ if (!label) {
+ throw new HTTPException(404, { message: "Label not found" });
+ }
+
+ for (const task of tasks) {
+ const existingAssignment = await db.query.labelTable.findFirst({
+ where: and(
+ eq(labelTable.name, label.name),
+ eq(labelTable.color, label.color),
+ eq(labelTable.taskId, task.id),
+ ),
+ });
+
+ if (!existingAssignment) {
+ await db.insert(labelTable).values({
+ name: label.name,
+ color: label.color,
+ workspaceId: workspaceId,
+ taskId: task.id,
+ });
+ updatedCount++;
+ }
+ }
+ break;
+ }
+
+ case "removeLabel": {
+ if (!value) {
+ throw new HTTPException(400, { message: "Label ID is required" });
+ }
+ const result = await db
+ .update(labelTable)
+ .set({ taskId: null })
+ .where(
+ and(eq(labelTable.id, value), inArray(labelTable.taskId, foundIds)),
+ );
+
+ updatedCount = result.rowCount ?? foundIds.length;
+ break;
+ }
+ }
+
+ return { success: true, updatedCount };
+}
+
+export default bulkUpdateTasks;
diff --git a/apps/api/src/task/controllers/get-tasks.ts b/apps/api/src/task/controllers/get-tasks.ts
index 44218ae76..a75a8d6dd 100644
--- a/apps/api/src/task/controllers/get-tasks.ts
+++ b/apps/api/src/task/controllers/get-tasks.ts
@@ -1,4 +1,14 @@
-import { and, asc, eq, inArray, sql } from "drizzle-orm";
+import {
+ and,
+ asc,
+ desc,
+ eq,
+ gte,
+ inArray,
+ lte,
+ type SQL,
+ sql,
+} from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
@@ -12,12 +22,52 @@ import {
type GetTasksOptions = {
assigneeId?: string;
+ dueAfter?: string;
+ dueBefore?: string;
limit?: number;
page?: number;
priority?: string;
+ sortBy?:
+ | "createdAt"
+ | "priority"
+ | "dueDate"
+ | "position"
+ | "title"
+ | "number";
+ sortOrder?: "asc" | "desc";
status?: string;
};
+const priorityCaseExpr = sql<number>`CASE
+ WHEN ${taskTable.priority} = 'urgent' THEN 4
+ WHEN ${taskTable.priority} = 'high' THEN 3
+ WHEN ${taskTable.priority} = 'medium' THEN 2
+ WHEN ${taskTable.priority} = 'low' THEN 1
+ ELSE 0
+END`;
+
+function buildOrderBy(
+ sortBy: GetTasksOptions["sortBy"],
+ sortOrder: GetTasksOptions["sortOrder"],
+): SQL {
+ const direction = sortOrder === "desc" ? desc : asc;
+
+ switch (sortBy) {
+ case "createdAt":
+ return direction(taskTable.createdAt);
+ case "priority":
+ return direction(priorityCaseExpr);
+ case "dueDate":
+ return direction(taskTable.dueDate);
+ case "title":
+ return direction(taskTable.title);
+ case "number":
+ return direction(taskTable.number);
+ default:
+ return direction(taskTable.position);
+ }
+}
+
async function getTasks(projectId: string, options: GetTasksOptions = {}) {
const project = await db.query.projectTable.findFirst({
where: eq(projectTable.id, projectId),
@@ -43,17 +93,32 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {
conditions.push(eq(taskTable.userId, options.assigneeId));
}
+ if (options.dueBefore) {
+ conditions.push(lte(taskTable.dueDate, new Date(options.dueBefore)));
+ }
+
+ if (options.dueAfter) {
+ conditions.push(gte(taskTable.dueDate, new Date(options.dueAfter)));
+ }
+
const whereClause = and(...conditions);
const page = options.page && options.page > 0 ? options.page : 1;
- const limit =
- options.limit && options.limit > 0 ? Math.min(options.limit, 100) : null;
- const offset = limit ? (page - 1) * limit : 0;
+ const pageSize =
+ options.limit && options.limit > 0 ? Math.min(options.limit, 100) : 50;
+ const offset = (page - 1) * pageSize;
+
+ const orderByClause = buildOrderBy(
+ options.sortBy ?? "position",
+ options.sortOrder ?? "asc",
+ );
const [taskCount] = await db
.select({ count: sql<number>`count(*)` })
.from(taskTable)
.where(whereClause);
+ const total = Number(taskCount?.count ?? 0);
+
const taskSelection = {
id: taskTable.id,
title: taskTable.title,
@@ -71,23 +136,15 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {
projectId: taskTable.projectId,
};
- const paginatedTasks = limit
- ? await db
- .select(taskSelection)
- .from(taskTable)
- .leftJoin(userTable, eq(taskTable.userId, userTable.id))
- .leftJoin(projectTable, eq(taskTable.projectId, projectTable.id))
- .where(whereClause)
- .orderBy(taskTable.position)
- .limit(limit)
- .offset(offset)
- : await db
- .select(taskSelection)
- .from(taskTable)
- .leftJoin(userTable, eq(taskTable.userId, userTable.id))
- .leftJoin(projectTable, eq(taskTable.projectId, projectTable.id))
- .where(whereClause)
- .orderBy(taskTable.position);
+ const paginatedTasks = await db
+ .select(taskSelection)
+ .from(taskTable)
+ .leftJoin(userTable, eq(taskTable.userId, userTable.id))
+ .leftJoin(projectTable, eq(taskTable.projectId, projectTable.id))
+ .where(whereClause)
+ .orderBy(orderByClause)
+ .limit(pageSize)
+ .offset(offset);
const taskIds = paginatedTasks.map((task) => task.id);
@@ -190,26 +247,24 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {
}));
return {
- id: project.id,
- name: project.name,
- slug: project.slug,
- icon: project.icon,
- description: project.description,
- isPublic: project.isPublic,
- workspaceId: project.workspaceId,
- columns,
- archivedTasks,
- plannedTasks,
- pagination: limit
- ? {
- page,
- limit,
- total: taskCount?.count ?? 0,
- totalPages: Math.max(1, Math.ceil((taskCount?.count ?? 0) / limit)),
- hasNextPage: offset + paginatedTasks.length < (taskCount?.count ?? 0),
- hasPreviousPage: page > 1,
- }
- : undefined,
+ data: {
+ id: project.id,
+ name: project.name,
+ slug: project.slug,
+ icon: project.icon,
+ description: project.description,
+ isPublic: project.isPublic,
+ workspaceId: project.workspaceId,
+ columns,
+ archivedTasks,
+ plannedTasks,
+ },
+ pagination: {
+ total,
+ page,
+ pageSize,
+ totalPages: Math.max(1, Math.ceil(total / pageSize)),
+ },
};
}
diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.ts
index f1c8ad246..4e7b0fc6a 100644
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@ -21,6 +21,7 @@ import {
validateTaskAssetUploadInput,
} from "../storage/s3";
import { workspaceAccess } from "../utils/workspace-access-middleware";
+import bulkUpdateTasks from "./controllers/bulk-update-tasks";
import createTask from "./controllers/create-task";
import deleteTask from "./controllers/delete-task";
import exportTasks from "./controllers/export-tasks";
@@ -65,6 +66,19 @@ const task = new Hono<{
assigneeId: v.optional(v.string()),
page: v.optional(v.pipe(v.string(), v.transform(Number))),
limit: v.optional(v.pipe(v.string(), v.transform(Number))),
+ sortBy: v.optional(
+ v.picklist([
+ "createdAt",
+ "priority",
+ "dueDate",
+ "position",
+ "title",
+ "number",
+ ]),
+ ),
+ sortOrder: v.optional(v.picklist(["asc", "desc"])),
+ dueBefore: v.optional(v.string()),
+ dueAfter: v.optional(v.string()),
}),
),
),
@@ -78,6 +92,67 @@ const task = new Hono<{
return c.json(tasks);
},
)
+ .patch(
+ "/bulk",
+ describeRoute({
+ operationId: "bulkUpdateTasks",
+ tags: ["Tasks"],
+ description: "Perform bulk operations on multiple tasks",
+ responses: {
+ 200: {
+ description: "Bulk operation completed successfully",
+ content: {
+ "application/json": {
+ schema: resolver(
+ v.object({
+ success: v.boolean(),
+ updatedCount: v.number(),
+ }),
+ ),
+ },
+ },
+ },
+ },
+ }),
+ validator(
+ "json",
+ v.object({
+ taskIds: v.pipe(v.array(v.string()), v.minLength(1)),
+ operation: v.picklist([
+ "updateStatus",
+ "updatePriority",
+ "updateAssignee",
+ "delete",
+ "addLabel",
+ "removeLabel",
+ ] as const),
+ value: v.optional(v.nullable(v.string())),
+ }),
+ ),
+ async (c) => {
+ const { taskIds, operation, value } = c.req.valid("json");
+ const userId = c.get("userId");
+
+ if (!userId) {
+ throw new HTTPException(401, { message: "Unauthorized" });
+ }
+
+ if (operation !== "delete" && value === undefined) {
+ throw new HTTPException(400, {
+ message: "Value is required for this operation",
+ });
+ }
+
+ const result = await bulkUpdateTasks({
+ taskIds,
+ operation,
+ value,
+ userId,
+ });
+
+ return c.json(result);
+ },
+ )
.post(
"/:projectId",
describeRoute({
diff --git a/apps/api/src/utils/workspace-access-middleware.ts b/apps/api/src/utils/workspace-access-middleware.ts
index 85716c958..802de9bce 100644
--- a/apps/api/src/utils/workspace-access-middleware.ts
+++ b/apps/api/src/utils/workspace-access-middleware.ts
@@ -16,6 +16,7 @@ type WorkspaceIdSource =
| "label"
| "timeEntry"
| "activity"
+ | "comment"
| "column"
| "workflowRule";
idKey: string;
@@ -85,6 +86,7 @@ async function lookupWorkspaceId(
| "label"
| "timeEntry"
| "activity"
+ | "comment"
| "column"
| "workflowRule",
id: string,
@@ -162,6 +164,25 @@ async function lookupWorkspaceId(
return activity?.workspaceId || null;
}
+ case "comment": {
+ const [comment] = await db
+ .select({
+ workspaceId: schema.projectTable.workspaceId,
+ })
+ .from(schema.commentTable)
+ .innerJoin(
+ schema.taskTable,
+ eq(schema.commentTable.taskId, schema.taskTable.id),
+ )
+ .innerJoin(
+ schema.projectTable,
+ eq(schema.taskTable.projectId, schema.projectTable.id),
+ )
+ .where(eq(schema.commentTable.id, id))
+ .limit(1);
+ return comment?.workspaceId || null;
+ }
+
case "column": {
const [column] = await db
.select({
@@ -259,6 +280,14 @@ export const workspaceAccess = {
],
}),
+ fromComment: (idKey = "id") =>
+ workspaceAccessMiddleware({
+ sources: [
+ { type: "lookup", resource: "comment", idKey },
+ { type: "query", key: "workspaceId" },
+ ],
+ }),
+
fromColumn: (idKey = "id") =>
workspaceAccessMiddleware({
sources: [
diff --git a/apps/api/src/workspace/controllers/get-workspace-members.ts b/apps/api/src/workspace/controllers/get-workspace-members.ts
new file mode 100644
index 000000000..59b71bc78
--- /dev/null
+++ b/apps/api/src/workspace/controllers/get-workspace-members.ts
@@ -0,0 +1,21 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { userTable, workspaceUserTable } from "../../database/schema";
+
+async function getWorkspaceMembers(workspaceId: string) {
+ const members = await db
+ .select({
+ id: userTable.id,
+ name: userTable.name,
+ email: userTable.email,
+ image: userTable.image,
+ role: workspaceUserTable.role,
+ })
+ .from(workspaceUserTable)
+ .innerJoin(userTable, eq(workspaceUserTable.userId, userTable.id))
+ .where(eq(workspaceUserTable.workspaceId, workspaceId));
+
+ return members;
+}
+
+export default getWorkspaceMembers;
diff --git a/apps/api/src/workspace/index.ts b/apps/api/src/workspace/index.ts
new file mode 100644
index 000000000..de7554b8e
--- /dev/null
+++ b/apps/api/src/workspace/index.ts
@@ -0,0 +1,48 @@
+import { Hono } from "hono";
+import { describeRoute, resolver, validator } from "hono-openapi";
+import * as v from "valibot";
+import { workspaceAccess } from "../utils/workspace-access-middleware";
+import getWorkspaceMembersCtrl from "./controllers/get-workspace-members";
+
+const workspace = new Hono<{
+ Variables: {
+ userId: string;
+ workspaceId: string;
+ };
+}>().get(
+ "/:workspaceId/members",
+ describeRoute({
+ operationId: "getWorkspaceMembers",
+ tags: ["Workspaces"],
+ description: "Get all members of a workspace",
+ responses: {
+ 200: {
+ description: "List of workspace members",
+ content: {
+ "application/json": {
+ schema: resolver(
+ v.array(
+ v.object({
+ id: v.string(),
+ name: v.string(),
+ email: v.string(),
+ image: v.nullable(v.string()),
+ role: v.string(),
+ }),
+ ),
+ ),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ workspaceId: v.string() })),
+ workspaceAccess.fromParam("workspaceId"),
+ async (c) => {
+ const workspaceId = c.get("workspaceId");
+ const members = await getWorkspaceMembersCtrl(workspaceId);
+ return c.json(members);
+ },
+);
+
+export default workspace;
diff --git a/apps/web/src/fetchers/task/get-tasks.ts b/apps/web/src/fetchers/task/get-tasks.ts
index 17678d340..c87f8ea76 100644
--- a/apps/web/src/fetchers/task/get-tasks.ts
+++ b/apps/web/src/fetchers/task/get-tasks.ts
@@ -10,9 +10,9 @@ async function getTasks(projectId: string) {
throw new Error(error);
}
- const data = await response.json();
+ const json = await response.json();
- return data;
+ return json.data;
}
export default getTasks;
diff --git a/apps/web/src/types/project/index.ts b/apps/web/src/types/project/index.ts
index 1086bee09..70c553bcd 100644
--- a/apps/web/src/types/project/index.ts
+++ b/apps/web/src/types/project/index.ts
@@ -7,14 +7,13 @@ export type Project = Extract<
{ id: string }
>;
-type ProjectWithTasksRaw = Extract<
- InferResponseType<
- (typeof client)["task"]["tasks"][":projectId"]["$get"],
- 200
- >,
- { id: string }
+type TasksApiResponse = InferResponseType<
+ (typeof client)["task"]["tasks"][":projectId"]["$get"],
+ 200
>;
+type ProjectWithTasksRaw = TasksApiResponse["data"];
+
export type ProjectWithTasks = Omit<
ProjectWithTasksRaw,
"archivedTasks" | "columns" | "plannedTasks"