260 lines · 13.5 KBRaw
| 1 | import { now } from "./auth.ts"; |
| 2 | import type { Actor } from "./contract/actor.ts"; |
| 3 | import type { Page } from "./contract/common.ts"; |
| 4 | import { LABEL_COLORS, MAX_LABEL_NAME_LENGTH, TASK_LIST_LIMIT } from "./contract/limits.ts"; |
| 5 | import type { Label, LabelColor, LabelWithUsage, TaskCounts, TaskDetail, TaskStatus, TaskSummary } from "./contract/views.ts"; |
| 6 | import { recordEvent, taskStream } from "./events.ts"; |
| 7 | import { renderMarkdown } from "./markdown.ts"; |
| 8 | |
| 9 | export { bodyError, requiredBodyError, titleError } from "./text.ts"; |
| 10 | |
| 11 | export interface TaskRecord { |
| 12 | id: number; |
| 13 | repo_id: string; |
| 14 | repo_name: string; |
| 15 | number: number; |
| 16 | title: string; |
| 17 | body: string; |
| 18 | status: TaskStatus; |
| 19 | author_id: string; |
| 20 | author: string; |
| 21 | assignee_id: string | null; |
| 22 | assignee: string | null; |
| 23 | created_at: number; |
| 24 | updated_at: number; |
| 25 | closed_at: number | null; |
| 26 | } |
| 27 | |
| 28 | type ListRow = TaskRecord & { comments: number; labels_json: string }; |
| 29 | |
| 30 | const SELECT_TASK = |
| 31 | "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"; |
| 32 | |
| 33 | const SELECT_LIST = SELECT_TASK.replace( |
| 34 | "SELECT t.*", |
| 35 | "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", |
| 36 | ); |
| 37 | |
| 38 | 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))"; |
| 39 | |
| 40 | function sortLabels(labels: Label[]): Label[] { |
| 41 | return labels.sort((a, b) => a.name.localeCompare(b.name)); |
| 42 | } |
| 43 | |
| 44 | export function toSummary(row: TaskRecord, labels: Label[], comments: number): TaskSummary { |
| 45 | return { |
| 46 | number: row.number, |
| 47 | repo: row.repo_name, |
| 48 | title: row.title, |
| 49 | status: row.status, |
| 50 | author: { id: row.author_id, name: row.author }, |
| 51 | assignee: row.assignee_id ? { id: row.assignee_id, name: row.assignee ?? "Former member" } : null, |
| 52 | labels, |
| 53 | comments, |
| 54 | createdAt: row.created_at, |
| 55 | closedAt: row.closed_at, |
| 56 | }; |
| 57 | } |
| 58 | |
| 59 | export function toDetail(row: TaskRecord, labels: Label[], comments: number): TaskDetail { |
| 60 | return { ...toSummary(row, labels, comments), body: row.body, bodyHtml: row.body ? renderMarkdown(row.body) : null, updatedAt: row.updated_at }; |
| 61 | } |
| 62 | |
| 63 | export interface TaskFilter { |
| 64 | namespaceId: string; |
| 65 | status: TaskStatus; |
| 66 | repoId?: string; |
| 67 | label?: string; |
| 68 | assigneeId?: string; |
| 69 | cursor?: string; |
| 70 | limit?: number; |
| 71 | } |
| 72 | |
| 73 | export async function listTasks(db: D1Database, filter: TaskFilter): Promise<{ page: Page<TaskSummary>; counts: TaskCounts }> { |
| 74 | const conditions: string[] = ["t.repo_id IN (SELECT id FROM repos WHERE namespace_id = ?)"]; |
| 75 | const bindings: (string | number)[] = [filter.namespaceId]; |
| 76 | if (filter.repoId) { |
| 77 | conditions.push("t.repo_id = ?"); |
| 78 | bindings.push(filter.repoId); |
| 79 | } |
| 80 | if (filter.assigneeId) { |
| 81 | conditions.push("t.assignee_id = ?"); |
| 82 | bindings.push(filter.assigneeId); |
| 83 | } |
| 84 | if (filter.label) { |
| 85 | 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 = ?)"); |
| 86 | bindings.push(filter.label); |
| 87 | } |
| 88 | const scope = conditions.map((condition) => ` AND ${condition}`).join(""); |
| 89 | const limit = Math.min(Math.max(filter.limit ?? TASK_LIST_LIMIT, 1), TASK_LIST_LIMIT); |
| 90 | const cursor = Number(filter.cursor); |
| 91 | const after = Number.isInteger(cursor) && cursor > 0 ? ` AND t.id < ${cursor}` : ""; |
| 92 | |
| 93 | const [counts, rows] = await db.batch([ |
| 94 | db.prepare(`SELECT status, count(*) AS total FROM tasks t WHERE 1 = 1${scope} GROUP BY status`).bind(...bindings), |
| 95 | db.prepare(`${SELECT_LIST} WHERE t.status = ?${scope}${after} ORDER BY t.id DESC LIMIT ${limit + 1}`).bind(filter.status, ...bindings), |
| 96 | ]); |
| 97 | const totals = Object.fromEntries((counts.results as { status: TaskStatus; total: number }[]).map((row) => [row.status, row.total])); |
| 98 | const found = rows.results as ListRow[]; |
| 99 | const items = found.slice(0, limit).map(({ labels_json, comments, ...row }) => toSummary(row, sortLabels(JSON.parse(labels_json) as Label[]), comments)); |
| 100 | const next = found.length > limit ? String(found[limit - 1].id) : null; |
| 101 | return { page: { items, next }, counts: { open: totals.open ?? 0, closed: totals.closed ?? 0 } }; |
| 102 | } |
| 103 | |
| 104 | /** Finds a task by repository and number, following the redirect left by a transfer. */ |
| 105 | export async function findTaskRecord(db: D1Database, repoId: string, number: number): Promise<TaskRecord | null> { |
| 106 | if (!Number.isInteger(number) || number < 1) return null; |
| 107 | const direct = await db.prepare(`${SELECT_TASK} WHERE t.repo_id = ? AND t.number = ?`).bind(repoId, number).first<TaskRecord>(); |
| 108 | if (direct) return direct; |
| 109 | return db.prepare(`${SELECT_TASK} WHERE t.id = (SELECT task_id FROM task_redirects WHERE repo_id = ? AND number = ?)`).bind(repoId, number).first<TaskRecord>(); |
| 110 | } |
| 111 | |
| 112 | export async function taskExtras(db: D1Database, taskId: number): Promise<{ labels: Label[]; comments: number }> { |
| 113 | const [labels, comments] = await db.batch([ |
| 114 | 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), |
| 115 | db.prepare("SELECT count(*) AS total FROM events WHERE stream = ? AND kind = 'task.commented'").bind(taskStream(taskId)), |
| 116 | ]); |
| 117 | return { labels: labels.results as Label[], comments: (comments.results[0] as { total: number }).total }; |
| 118 | } |
| 119 | |
| 120 | export async function memberName(db: D1Database, repoId: string, userId: string): Promise<string | null> { |
| 121 | return db |
| 122 | .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 = ?") |
| 123 | .bind(repoId, userId) |
| 124 | .first<string>("name"); |
| 125 | } |
| 126 | |
| 127 | export async function createTaskRecord( |
| 128 | db: D1Database, |
| 129 | actor: Actor, |
| 130 | input: { repoId: string; title: string; body: string; authorId: string; assigneeId: string | null; labelIds: readonly string[] }, |
| 131 | ): Promise<{ id: number; number: number }> { |
| 132 | const at = now(); |
| 133 | const [inserted] = await db.batch<{ id: number; number: number }>([ |
| 134 | db |
| 135 | .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`) |
| 136 | .bind(input.repoId, input.title, input.body, input.authorId, input.assigneeId, at), |
| 137 | recordEvent(db, actor, { newest: "task", repoId: input.repoId }, "task.opened", { title: input.title }, at), |
| 138 | ...input.labelIds.map((labelId) => |
| 139 | db |
| 140 | .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") |
| 141 | .bind(null, labelId, input.repoId), |
| 142 | ), |
| 143 | ]); |
| 144 | return inserted.results[0]; |
| 145 | } |
| 146 | |
| 147 | function touch(db: D1Database, taskId: number, at: number): D1PreparedStatement { |
| 148 | return db.prepare("UPDATE tasks SET updated_at = ? WHERE id = ?").bind(at, taskId); |
| 149 | } |
| 150 | |
| 151 | function statusChange(db: D1Database, actor: Actor, task: TaskRecord, status: TaskStatus, at: number): D1PreparedStatement[] { |
| 152 | return [ |
| 153 | db.prepare("UPDATE tasks SET status = ?, closed_at = ?, updated_at = ? WHERE id = ?").bind(status, status === "closed" ? at : null, at, task.id), |
| 154 | recordEvent(db, actor, taskStream(task.id), status === "closed" ? "task.closed" : "task.reopened", {}, at), |
| 155 | ]; |
| 156 | } |
| 157 | |
| 158 | export async function addComment(db: D1Database, actor: Actor, task: TaskRecord, body: string, then?: TaskStatus): Promise<number> { |
| 159 | const at = now(); |
| 160 | const [inserted] = await db.batch([ |
| 161 | recordEvent(db, actor, taskStream(task.id), "task.commented", { body }, at), |
| 162 | touch(db, task.id, at), |
| 163 | ...(then && then !== task.status ? statusChange(db, actor, task, then, at) : []), |
| 164 | ]); |
| 165 | return inserted.meta.last_row_id; |
| 166 | } |
| 167 | |
| 168 | export async function setStatus(db: D1Database, actor: Actor, task: TaskRecord, status: TaskStatus): Promise<void> { |
| 169 | if (status !== task.status) await db.batch(statusChange(db, actor, task, status, now())); |
| 170 | } |
| 171 | |
| 172 | export async function rename(db: D1Database, actor: Actor, task: TaskRecord, title: string): Promise<void> { |
| 173 | if (title === task.title) return; |
| 174 | const at = now(); |
| 175 | await db.batch([ |
| 176 | db.prepare("UPDATE tasks SET title = ?, updated_at = ? WHERE id = ?").bind(title, at, task.id), |
| 177 | recordEvent(db, actor, taskStream(task.id), "task.renamed", { from: task.title, to: title }, at), |
| 178 | ]); |
| 179 | } |
| 180 | |
| 181 | export async function describe(db: D1Database, task: TaskRecord, body: string): Promise<void> { |
| 182 | await db.prepare("UPDATE tasks SET body = ?, updated_at = ? WHERE id = ?").bind(body, now(), task.id).run(); |
| 183 | } |
| 184 | |
| 185 | export async function assign(db: D1Database, actor: Actor, task: TaskRecord, assignee: { id: string; name: string } | null): Promise<void> { |
| 186 | if ((assignee?.id ?? null) === task.assignee_id) return; |
| 187 | const at = now(); |
| 188 | const previous = { id: task.assignee_id ?? "", name: task.assignee ?? "Former member" }; |
| 189 | await db.batch([ |
| 190 | db.prepare("UPDATE tasks SET assignee_id = ?, updated_at = ? WHERE id = ?").bind(assignee?.id ?? null, at, task.id), |
| 191 | assignee ? recordEvent(db, actor, taskStream(task.id), "task.assigned", { assignee }, at) : recordEvent(db, actor, taskStream(task.id), "task.unassigned", { assignee: previous }, at), |
| 192 | ]); |
| 193 | } |
| 194 | |
| 195 | /** Moves the task to another repository under that repository's next number, leaving a redirect at its old address. */ |
| 196 | export async function transfer(db: D1Database, actor: Actor, task: TaskRecord, target: { id: string; name: string }): Promise<{ repo: string; number: number }> { |
| 197 | const at = now(); |
| 198 | await db.batch([ |
| 199 | db.prepare("INSERT OR REPLACE INTO task_redirects (repo_id, number, task_id) VALUES (?, ?, ?)").bind(task.repo_id, task.number, task.id), |
| 200 | db.prepare(`UPDATE tasks SET repo_id = ?1, number = ${NEXT_NUMBER}, updated_at = ?2 WHERE id = ?3`).bind(target.id, at, task.id), |
| 201 | ]); |
| 202 | const number = (await db.prepare("SELECT number FROM tasks WHERE id = ?").bind(task.id).first<number>("number"))!; |
| 203 | await recordEvent(db, actor, taskStream(task.id), "task.transferred", { from: { repo: task.repo_name, number: task.number }, to: { repo: target.name, number } }, at).run(); |
| 204 | return { repo: target.name, number }; |
| 205 | } |
| 206 | |
| 207 | export async function setLabels(db: D1Database, actor: Actor, task: TaskRecord, labelIds: readonly string[]): Promise<void> { |
| 208 | const { labels: current } = await taskExtras(db, task.id); |
| 209 | const known = new Map(( |
| 210 | await db |
| 211 | .prepare("SELECT l.id, l.name, l.color FROM labels l JOIN repos r ON r.namespace_id = l.namespace_id WHERE r.id = ?") |
| 212 | .bind(task.repo_id) |
| 213 | .all<{ id: string; name: string; color: LabelColor }>() |
| 214 | ).results.map((label) => [label.id, label])); |
| 215 | const wanted = new Set(labelIds.filter((id) => known.has(id))); |
| 216 | const added = [...wanted].filter((id) => !current.some((label) => label.id === id)); |
| 217 | const removed = current.filter((label) => !wanted.has(label.id)); |
| 218 | if (!added.length && !removed.length) return; |
| 219 | |
| 220 | const at = now(); |
| 221 | await db.batch([ |
| 222 | ...added.map((id) => db.prepare("INSERT OR IGNORE INTO task_labels (task_id, label_id) VALUES (?, ?)").bind(task.id, id)), |
| 223 | ...removed.map((label) => db.prepare("DELETE FROM task_labels WHERE task_id = ? AND label_id = ?").bind(task.id, label.id)), |
| 224 | ...added.map((id) => recordEvent(db, actor, taskStream(task.id), "task.labeled", { label: { name: known.get(id)!.name, color: known.get(id)!.color } }, at)), |
| 225 | ...removed.map((label) => recordEvent(db, actor, taskStream(task.id), "task.unlabeled", { label: { name: label.name, color: label.color } }, at)), |
| 226 | touch(db, task.id, at), |
| 227 | ]); |
| 228 | } |
| 229 | |
| 230 | export async function editComment(db: D1Database, task: TaskRecord, commentId: number, authorId: string, body: string): Promise<boolean> { |
| 231 | const result = await db |
| 232 | .prepare("UPDATE events SET data = ?, edited_at = ? WHERE id = ? AND stream = ? AND kind = 'task.commented' AND actor_kind = 'human' AND actor_id = ?") |
| 233 | .bind(JSON.stringify({ body }), now(), commentId, taskStream(task.id), authorId) |
| 234 | .run(); |
| 235 | return result.meta.changes > 0; |
| 236 | } |
| 237 | |
| 238 | export async function deleteComment(db: D1Database, task: TaskRecord, commentId: number, actorId: string, canModerate: boolean): Promise<boolean> { |
| 239 | const result = await db |
| 240 | .prepare("DELETE FROM events WHERE id = ? AND stream = ? AND kind = 'task.commented' AND (coalesce(on_behalf_of, actor_id) = ? OR ? = 1)") |
| 241 | .bind(commentId, taskStream(task.id), actorId, canModerate ? 1 : 0) |
| 242 | .run(); |
| 243 | return result.meta.changes > 0; |
| 244 | } |
| 245 | |
| 246 | export async function listLabels(db: D1Database, namespaceId: string): Promise<LabelWithUsage[]> { |
| 247 | const { results } = await db |
| 248 | .prepare( |
| 249 | "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", |
| 250 | ) |
| 251 | .bind(namespaceId) |
| 252 | .all<LabelWithUsage>(); |
| 253 | return results; |
| 254 | } |
| 255 | |
| 256 | export function labelError(input: { name: string; color: string; description: string }): string | undefined { |
| 257 | if (!input.name || input.name.length > MAX_LABEL_NAME_LENGTH) return `Label names must be 1–${MAX_LABEL_NAME_LENGTH} characters.`; |
| 258 | if (!LABEL_COLORS.includes(input.color as LabelColor)) return "Pick one of the label colors."; |
| 259 | if (input.description.length > 200) return "Label descriptions must be at most 200 characters."; |
| 260 | } |