import { now } from "./auth.ts"; import type { Actor } from "./contract/actor.ts"; import type { Page } from "./contract/common.ts"; import { LABEL_COLORS, MAX_LABEL_NAME_LENGTH, TASK_LIST_LIMIT } from "./contract/limits.ts"; import type { Label, LabelColor, LabelWithUsage, TaskCounts, TaskDetail, TaskStatus, TaskSummary } from "./contract/views.ts"; import { recordEvent, taskStream } from "./events.ts"; import { renderMarkdown } from "./markdown.ts"; export { bodyError, requiredBodyError, titleError } from "./text.ts"; export interface TaskRecord { id: number; repo_id: string; repo_name: string; number: number; title: string; body: string; status: TaskStatus; author_id: string; author: string; assignee_id: string | null; assignee: string | null; created_at: number; updated_at: number; closed_at: number | null; } type ListRow = TaskRecord & { comments: number; labels_json: string }; const SELECT_TASK = "SELECT t.*, (SELECT slug FROM namespaces WHERE id = r.namespace_id) || '/' || r.name AS repo_name, a.name AS author, u.name AS assignee FROM tasks t JOIN repos r ON r.id = t.repo_id JOIN users a ON a.id = t.author_id LEFT JOIN users u ON u.id = t.assignee_id"; const SELECT_LIST = SELECT_TASK.replace( "SELECT t.*", "SELECT t.*, (SELECT count(*) FROM events e WHERE e.stream = 'task:' || t.id AND e.kind = 'task.commented') AS comments, (SELECT json_group_array(json_object('id', l.id, 'name', l.name, 'color', l.color, 'description', l.description)) FROM task_labels tl JOIN labels l ON l.id = tl.label_id WHERE tl.task_id = t.id) AS labels_json", ); const NEXT_NUMBER = "(SELECT coalesce(max(n), 0) + 1 FROM (SELECT number AS n FROM tasks WHERE repo_id = ?1 UNION ALL SELECT number FROM task_redirects WHERE repo_id = ?1))"; function sortLabels(labels: Label[]): Label[] { return labels.sort((a, b) => a.name.localeCompare(b.name)); } export function toSummary(row: TaskRecord, labels: Label[], comments: number): TaskSummary { return { number: row.number, repo: row.repo_name, title: row.title, status: row.status, author: { id: row.author_id, name: row.author }, assignee: row.assignee_id ? { id: row.assignee_id, name: row.assignee ?? "Former member" } : null, labels, comments, createdAt: row.created_at, closedAt: row.closed_at, }; } export function toDetail(row: TaskRecord, labels: Label[], comments: number): TaskDetail { return { ...toSummary(row, labels, comments), body: row.body, bodyHtml: row.body ? renderMarkdown(row.body) : null, updatedAt: row.updated_at }; } export interface TaskFilter { namespaceId: string; status: TaskStatus; repoId?: string; label?: string; assigneeId?: string; cursor?: string; limit?: number; } export async function listTasks(db: D1Database, filter: TaskFilter): Promise<{ page: Page; counts: TaskCounts }> { const conditions: string[] = ["t.repo_id IN (SELECT id FROM repos WHERE namespace_id = ?)"]; const bindings: (string | number)[] = [filter.namespaceId]; if (filter.repoId) { conditions.push("t.repo_id = ?"); bindings.push(filter.repoId); } if (filter.assigneeId) { conditions.push("t.assignee_id = ?"); bindings.push(filter.assigneeId); } if (filter.label) { conditions.push("EXISTS (SELECT 1 FROM task_labels tl JOIN labels l ON l.id = tl.label_id WHERE tl.task_id = t.id AND l.name = ?)"); bindings.push(filter.label); } const scope = conditions.map((condition) => ` AND ${condition}`).join(""); const limit = Math.min(Math.max(filter.limit ?? TASK_LIST_LIMIT, 1), TASK_LIST_LIMIT); const cursor = Number(filter.cursor); const after = Number.isInteger(cursor) && cursor > 0 ? ` AND t.id < ${cursor}` : ""; const [counts, rows] = await db.batch([ db.prepare(`SELECT status, count(*) AS total FROM tasks t WHERE 1 = 1${scope} GROUP BY status`).bind(...bindings), db.prepare(`${SELECT_LIST} WHERE t.status = ?${scope}${after} ORDER BY t.id DESC LIMIT ${limit + 1}`).bind(filter.status, ...bindings), ]); const totals = Object.fromEntries((counts.results as { status: TaskStatus; total: number }[]).map((row) => [row.status, row.total])); const found = rows.results as ListRow[]; const items = found.slice(0, limit).map(({ labels_json, comments, ...row }) => toSummary(row, sortLabels(JSON.parse(labels_json) as Label[]), comments)); const next = found.length > limit ? String(found[limit - 1].id) : null; return { page: { items, next }, counts: { open: totals.open ?? 0, closed: totals.closed ?? 0 } }; } /** Finds a task by repository and number, following the redirect left by a transfer. */ export async function findTaskRecord(db: D1Database, repoId: string, number: number): Promise { if (!Number.isInteger(number) || number < 1) return null; const direct = await db.prepare(`${SELECT_TASK} WHERE t.repo_id = ? AND t.number = ?`).bind(repoId, number).first(); if (direct) return direct; return db.prepare(`${SELECT_TASK} WHERE t.id = (SELECT task_id FROM task_redirects WHERE repo_id = ? AND number = ?)`).bind(repoId, number).first(); } export async function taskExtras(db: D1Database, taskId: number): Promise<{ labels: Label[]; comments: number }> { const [labels, comments] = await db.batch([ db.prepare("SELECT l.id, l.name, l.color, l.description FROM task_labels tl JOIN labels l ON l.id = tl.label_id WHERE tl.task_id = ? ORDER BY l.name COLLATE NOCASE").bind(taskId), db.prepare("SELECT count(*) AS total FROM events WHERE stream = ? AND kind = 'task.commented'").bind(taskStream(taskId)), ]); return { labels: labels.results as Label[], comments: (comments.results[0] as { total: number }).total }; } export async function memberName(db: D1Database, repoId: string, userId: string): Promise { return db .prepare("SELECT u.name FROM users u JOIN memberships m ON m.user_id = u.id JOIN repos r ON r.namespace_id = m.namespace_id WHERE r.id = ? AND u.id = ?") .bind(repoId, userId) .first("name"); } export async function createTaskRecord( db: D1Database, actor: Actor, input: { repoId: string; title: string; body: string; authorId: string; assigneeId: string | null; labelIds: readonly string[] }, ): Promise<{ id: number; number: number }> { const at = now(); const [inserted] = await db.batch<{ id: number; number: number }>([ db .prepare(`INSERT INTO tasks (repo_id, number, title, body, author_id, assignee_id, created_at, updated_at) VALUES (?1, ${NEXT_NUMBER}, ?2, ?3, ?4, ?5, ?6, ?6) RETURNING id, number`) .bind(input.repoId, input.title, input.body, input.authorId, input.assigneeId, at), recordEvent(db, actor, { newest: "task", repoId: input.repoId }, "task.opened", { title: input.title }, at), ...input.labelIds.map((labelId) => db .prepare("INSERT OR IGNORE INTO task_labels (task_id, label_id) SELECT (SELECT max(id) FROM tasks WHERE repo_id = ?3), l.id FROM labels l JOIN repos r ON r.namespace_id = l.namespace_id WHERE l.id = ?2 AND r.id = ?3") .bind(null, labelId, input.repoId), ), ]); return inserted.results[0]; } function touch(db: D1Database, taskId: number, at: number): D1PreparedStatement { return db.prepare("UPDATE tasks SET updated_at = ? WHERE id = ?").bind(at, taskId); } function statusChange(db: D1Database, actor: Actor, task: TaskRecord, status: TaskStatus, at: number): D1PreparedStatement[] { return [ db.prepare("UPDATE tasks SET status = ?, closed_at = ?, updated_at = ? WHERE id = ?").bind(status, status === "closed" ? at : null, at, task.id), recordEvent(db, actor, taskStream(task.id), status === "closed" ? "task.closed" : "task.reopened", {}, at), ]; } export async function addComment(db: D1Database, actor: Actor, task: TaskRecord, body: string, then?: TaskStatus): Promise { const at = now(); const [inserted] = await db.batch([ recordEvent(db, actor, taskStream(task.id), "task.commented", { body }, at), touch(db, task.id, at), ...(then && then !== task.status ? statusChange(db, actor, task, then, at) : []), ]); return inserted.meta.last_row_id; } export async function setStatus(db: D1Database, actor: Actor, task: TaskRecord, status: TaskStatus): Promise { if (status !== task.status) await db.batch(statusChange(db, actor, task, status, now())); } export async function rename(db: D1Database, actor: Actor, task: TaskRecord, title: string): Promise { if (title === task.title) return; const at = now(); await db.batch([ db.prepare("UPDATE tasks SET title = ?, updated_at = ? WHERE id = ?").bind(title, at, task.id), recordEvent(db, actor, taskStream(task.id), "task.renamed", { from: task.title, to: title }, at), ]); } export async function describe(db: D1Database, task: TaskRecord, body: string): Promise { await db.prepare("UPDATE tasks SET body = ?, updated_at = ? WHERE id = ?").bind(body, now(), task.id).run(); } export async function assign(db: D1Database, actor: Actor, task: TaskRecord, assignee: { id: string; name: string } | null): Promise { if ((assignee?.id ?? null) === task.assignee_id) return; const at = now(); const previous = { id: task.assignee_id ?? "", name: task.assignee ?? "Former member" }; await db.batch([ db.prepare("UPDATE tasks SET assignee_id = ?, updated_at = ? WHERE id = ?").bind(assignee?.id ?? null, at, task.id), assignee ? recordEvent(db, actor, taskStream(task.id), "task.assigned", { assignee }, at) : recordEvent(db, actor, taskStream(task.id), "task.unassigned", { assignee: previous }, at), ]); } /** Moves the task to another repository under that repository's next number, leaving a redirect at its old address. */ export async function transfer(db: D1Database, actor: Actor, task: TaskRecord, target: { id: string; name: string }): Promise<{ repo: string; number: number }> { const at = now(); await db.batch([ db.prepare("INSERT OR REPLACE INTO task_redirects (repo_id, number, task_id) VALUES (?, ?, ?)").bind(task.repo_id, task.number, task.id), db.prepare(`UPDATE tasks SET repo_id = ?1, number = ${NEXT_NUMBER}, updated_at = ?2 WHERE id = ?3`).bind(target.id, at, task.id), ]); const number = (await db.prepare("SELECT number FROM tasks WHERE id = ?").bind(task.id).first("number"))!; await recordEvent(db, actor, taskStream(task.id), "task.transferred", { from: { repo: task.repo_name, number: task.number }, to: { repo: target.name, number } }, at).run(); return { repo: target.name, number }; } export async function setLabels(db: D1Database, actor: Actor, task: TaskRecord, labelIds: readonly string[]): Promise { const { labels: current } = await taskExtras(db, task.id); const known = new Map(( await db .prepare("SELECT l.id, l.name, l.color FROM labels l JOIN repos r ON r.namespace_id = l.namespace_id WHERE r.id = ?") .bind(task.repo_id) .all<{ id: string; name: string; color: LabelColor }>() ).results.map((label) => [label.id, label])); const wanted = new Set(labelIds.filter((id) => known.has(id))); const added = [...wanted].filter((id) => !current.some((label) => label.id === id)); const removed = current.filter((label) => !wanted.has(label.id)); if (!added.length && !removed.length) return; const at = now(); await db.batch([ ...added.map((id) => db.prepare("INSERT OR IGNORE INTO task_labels (task_id, label_id) VALUES (?, ?)").bind(task.id, id)), ...removed.map((label) => db.prepare("DELETE FROM task_labels WHERE task_id = ? AND label_id = ?").bind(task.id, label.id)), ...added.map((id) => recordEvent(db, actor, taskStream(task.id), "task.labeled", { label: { name: known.get(id)!.name, color: known.get(id)!.color } }, at)), ...removed.map((label) => recordEvent(db, actor, taskStream(task.id), "task.unlabeled", { label: { name: label.name, color: label.color } }, at)), touch(db, task.id, at), ]); } export async function editComment(db: D1Database, task: TaskRecord, commentId: number, authorId: string, body: string): Promise { const result = await db .prepare("UPDATE events SET data = ?, edited_at = ? WHERE id = ? AND stream = ? AND kind = 'task.commented' AND actor_kind = 'human' AND actor_id = ?") .bind(JSON.stringify({ body }), now(), commentId, taskStream(task.id), authorId) .run(); return result.meta.changes > 0; } export async function deleteComment(db: D1Database, task: TaskRecord, commentId: number, actorId: string, canModerate: boolean): Promise { const result = await db .prepare("DELETE FROM events WHERE id = ? AND stream = ? AND kind = 'task.commented' AND (coalesce(on_behalf_of, actor_id) = ? OR ? = 1)") .bind(commentId, taskStream(task.id), actorId, canModerate ? 1 : 0) .run(); return result.meta.changes > 0; } export async function listLabels(db: D1Database, namespaceId: string): Promise { const { results } = await db .prepare( "SELECT l.id, l.name, l.color, l.description, (SELECT count(*) FROM task_labels tl JOIN tasks t ON t.id = tl.task_id WHERE tl.label_id = l.id AND t.status = 'open') AS openTasks FROM labels l WHERE l.namespace_id = ? ORDER BY l.name COLLATE NOCASE", ) .bind(namespaceId) .all(); return results; } export function labelError(input: { name: string; color: string; description: string }): string | undefined { if (!input.name || input.name.length > MAX_LABEL_NAME_LENGTH) return `Label names must be 1–${MAX_LABEL_NAME_LENGTH} characters.`; if (!LABEL_COLORS.includes(input.color as LabelColor)) return "Pick one of the label colors."; if (input.description.length > 200) return "Label descriptions must be at most 200 characters."; }