Files
FWS-DiscordBot/src/database/repositories/project-repository.js
T
nocodeandClaude Opus 5 901ca56959 feat(projects): add a Kanban board per repository and one for the organization
Boards live in SQLite rather than in Gitea, whose project API is not stable
across versions: a board that stops working whenever the forge hiccups is
worse than no board, and this one has hiccupped already.

A card can still point at an issue — `owner/repo#12` — and its real state is
resolved when the forge answers, one request per repository rather than per
card. Open issues can also be imported in bulk, skipping those already on
the board.

Columns follow the ones the README describes, and carry an optional card
limit which warns rather than refuses: stopping someone mid-gesture to
enforce a convention is not what a limit is for.

Moving a card rebuilds the order explicitly — take the column without it,
insert at the wanted rank, renumber — because fractional positions get the
same-column case wrong, as the tests showed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00

286 lines
9.2 KiB
JavaScript

import { getDatabase } from '../index.js';
/** Kanban boards, their columns and their cards (M18). */
/** Same wording as the board described in the FWS README. */
export const DEFAULT_COLUMNS = Object.freeze([
{ name: 'À faire', wipLimit: 0, isDone: false },
{ name: 'En cours', wipLimit: 3, isDone: false },
{ name: 'En revue', wipLimit: 0, isDone: false },
{ name: 'Terminé', wipLimit: 0, isDone: true },
]);
const parseBoard = (row) => (row ? { ...row, archived: Boolean(row.archived) } : null);
const parseColumn = (row) => (row ? { ...row, is_done: Boolean(row.is_done) } : null);
const parseCard = (row) => (row ? { ...row, labels: JSON.parse(row.labels || '[]') } : null);
// --- Boards ------------------------------------------------------------------
export function createBoard({
guildId,
scope,
repository = null,
name,
description = null,
createdBy = null,
}) {
const database = getDatabase();
const { lastInsertRowid } = database
.prepare(
`INSERT INTO project_boards (guild_id, scope, repository, name, description, created_by)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(guildId, scope, repository, name, description, createdBy);
const id = Number(lastInsertRowid);
// A board with no column cannot receive a card, so it is never created empty.
for (const [index, column] of DEFAULT_COLUMNS.entries()) {
addColumn({
boardId: id,
name: column.name,
position: index,
wipLimit: column.wipLimit,
isDone: column.isDone,
});
}
return getBoard(id);
}
export function getBoard(id) {
return parseBoard(getDatabase().prepare('SELECT * FROM project_boards WHERE id = ?').get(id) ?? null);
}
export function getBoardByRepository(guildId, repository) {
return parseBoard(
getDatabase()
.prepare('SELECT * FROM project_boards WHERE guild_id = ? AND repository = ?')
.get(guildId, repository) ?? null,
);
}
export function getOrgBoard(guildId) {
return parseBoard(
getDatabase().prepare("SELECT * FROM project_boards WHERE guild_id = ? AND scope = 'org'").get(guildId) ??
null,
);
}
export function listBoards(guildId) {
return getDatabase()
.prepare('SELECT * FROM project_boards WHERE guild_id = ? ORDER BY scope DESC, name')
.all(guildId)
.map(parseBoard);
}
export function updateBoard(id, { name, description, archived }) {
const fields = [];
const values = [];
if (name !== undefined) (fields.push('name = ?'), values.push(name));
if (description !== undefined) (fields.push('description = ?'), values.push(description));
if (archived !== undefined) (fields.push('archived = ?'), values.push(archived ? 1 : 0));
if (fields.length === 0) return getBoard(id);
getDatabase()
.prepare(`UPDATE project_boards SET ${fields.join(', ')}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getBoard(id);
}
export function removeBoard(id) {
return getDatabase().prepare('DELETE FROM project_boards WHERE id = ?').run(id).changes;
}
// --- Columns -----------------------------------------------------------------
export function addColumn({ boardId, name, position = null, wipLimit = 0, isDone = false }) {
const database = getDatabase();
const nextPosition =
position ??
database
.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS next FROM project_columns WHERE board_id = ?')
.get(boardId).next ??
0;
const { lastInsertRowid } = database
.prepare(
'INSERT INTO project_columns (board_id, name, position, wip_limit, is_done) VALUES (?, ?, ?, ?, ?)',
)
.run(boardId, name, nextPosition, wipLimit, isDone ? 1 : 0);
return getColumn(Number(lastInsertRowid));
}
export function getColumn(id) {
return parseColumn(getDatabase().prepare('SELECT * FROM project_columns WHERE id = ?').get(id) ?? null);
}
export function listColumns(boardId) {
return getDatabase()
.prepare('SELECT * FROM project_columns WHERE board_id = ? ORDER BY position, id')
.all(boardId)
.map(parseColumn);
}
export function updateColumn(id, { name, wipLimit, isDone, position }) {
const fields = [];
const values = [];
if (name !== undefined) (fields.push('name = ?'), values.push(name));
if (wipLimit !== undefined) (fields.push('wip_limit = ?'), values.push(Number(wipLimit) || 0));
if (isDone !== undefined) (fields.push('is_done = ?'), values.push(isDone ? 1 : 0));
if (position !== undefined) (fields.push('position = ?'), values.push(Number(position) || 0));
if (fields.length === 0) return getColumn(id);
getDatabase()
.prepare(`UPDATE project_columns SET ${fields.join(', ')} WHERE id = ?`)
.run(...values, id);
return getColumn(id);
}
export function removeColumn(id) {
return getDatabase().prepare('DELETE FROM project_columns WHERE id = ?').run(id).changes;
}
export function countColumns(boardId) {
return getDatabase()
.prepare('SELECT COUNT(*) AS count FROM project_columns WHERE board_id = ?')
.get(boardId).count;
}
// --- Cards -------------------------------------------------------------------
export function addCard({
boardId,
columnId,
title,
body = null,
assigneeId = null,
issueRef = null,
labels = [],
dueAt = null,
createdBy = null,
}) {
const database = getDatabase();
const next =
database
.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS next FROM project_cards WHERE column_id = ?')
.get(columnId).next ?? 0;
const { lastInsertRowid } = database
.prepare(
`INSERT INTO project_cards
(board_id, column_id, title, body, position, assignee_id, issue_ref, labels, due_at, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
boardId,
columnId,
title,
body,
next,
assigneeId,
issueRef,
JSON.stringify(labels),
dueAt,
createdBy,
);
return getCard(Number(lastInsertRowid));
}
export function getCard(id) {
return parseCard(getDatabase().prepare('SELECT * FROM project_cards WHERE id = ?').get(id) ?? null);
}
export function listCards(boardId) {
return getDatabase()
.prepare('SELECT * FROM project_cards WHERE board_id = ? ORDER BY column_id, position, id')
.all(boardId)
.map(parseCard);
}
export function countCardsInColumn(columnId) {
return getDatabase()
.prepare('SELECT COUNT(*) AS count FROM project_cards WHERE column_id = ?')
.get(columnId).count;
}
export function updateCard(id, { title, body, assigneeId, issueRef, labels, dueAt }) {
const fields = [];
const values = [];
if (title !== undefined) (fields.push('title = ?'), values.push(title));
if (body !== undefined) (fields.push('body = ?'), values.push(body));
if (assigneeId !== undefined) (fields.push('assignee_id = ?'), values.push(assigneeId || null));
if (issueRef !== undefined) (fields.push('issue_ref = ?'), values.push(issueRef || null));
if (labels !== undefined) (fields.push('labels = ?'), values.push(JSON.stringify(labels)));
if (dueAt !== undefined) (fields.push('due_at = ?'), values.push(dueAt || null));
if (fields.length === 0) return getCard(id);
getDatabase()
.prepare(`UPDATE project_cards SET ${fields.join(', ')}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getCard(id);
}
/**
* Moves a card to a rank in a column.
*
* The order is rebuilt explicitly — take the column without the card, insert it
* at the wanted index, renumber — rather than nudged with fractional positions.
* Within one column the card has to be removed before being counted back in, a
* subtlety fractional ranks get wrong every time.
*/
export function moveCard(id, { columnId, position = 0 }) {
const database = getDatabase();
const card = getCard(id);
if (!card) return null;
const order = (target) =>
database
.prepare('SELECT id FROM project_cards WHERE column_id = ? ORDER BY position, id')
.all(target)
.map((row) => row.id)
.filter((cardId) => cardId !== id);
const write = (ids, target) => {
for (const [index, cardId] of ids.entries()) {
database
.prepare(
"UPDATE project_cards SET column_id = ?, position = ?, updated_at = datetime('now') WHERE id = ?",
)
.run(target, index, cardId);
}
};
const destination = order(columnId);
const rank = Math.max(0, Math.min(Number(position) || 0, destination.length));
destination.splice(rank, 0, id);
database.exec('BEGIN');
try {
// The column it leaves closes its gap, the one it joins makes room.
if (card.column_id !== columnId) write(order(card.column_id), card.column_id);
write(destination, columnId);
database.exec('COMMIT');
} catch (error) {
database.exec('ROLLBACK');
throw error;
}
return getCard(id);
}
export function removeCard(id) {
return getDatabase().prepare('DELETE FROM project_cards WHERE id = ?').run(id).changes;
}
/** Cards carried by one member, across every board of the guild. */
export function listCardsForAssignee(guildId, assigneeId) {
return getDatabase()
.prepare(
`SELECT c.*, b.name AS board_name, b.repository
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
WHERE b.guild_id = ? AND c.assignee_id = ?
ORDER BY c.due_at IS NULL, c.due_at, c.id`,
)
.all(guildId, assigneeId)
.map(parseCard);
}