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>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 23:20:08 +02:00
1 parent b793298cbf
commit 901ca56959
6 files changed
+1133

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
-- Kanban boards: one per repository, plus one for the organization (M18)
CREATE TABLE IF NOT EXISTS project_boards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
-- 'org' has no repository; 'repo' carries `owner/name`.
scope TEXT NOT NULL CHECK (scope IN ('org', 'repo')),
repository TEXT,
name TEXT NOT NULL,
description TEXT,
archived INTEGER NOT NULL DEFAULT 0,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- One board per repository, and a single organization board per guild.
CREATE UNIQUE INDEX IF NOT EXISTS idx_boards_repository
ON project_boards (guild_id, repository) WHERE repository IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_boards_org
ON project_boards (guild_id) WHERE scope = 'org';
CREATE TABLE IF NOT EXISTS project_columns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
board_id INTEGER NOT NULL REFERENCES project_boards (id) ON DELETE CASCADE,
name TEXT NOT NULL,
position INTEGER NOT NULL DEFAULT 0,
-- 0 means no limit; above it the column is flagged as overloaded.
wip_limit INTEGER NOT NULL DEFAULT 0,
-- Cards dropped here are considered finished, which drives the board counters.
is_done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_columns_board ON project_columns (board_id, position);
CREATE TABLE IF NOT EXISTS project_cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
board_id INTEGER NOT NULL REFERENCES project_boards (id) ON DELETE CASCADE,
column_id INTEGER NOT NULL REFERENCES project_columns (id) ON DELETE CASCADE,
title TEXT NOT NULL,
body TEXT,
position INTEGER NOT NULL DEFAULT 0,
-- Discord id of whoever carries the card.
assignee_id TEXT,
-- `owner/repo#12`, resolved against Gitea when the forge answers.
issue_ref TEXT,
labels TEXT NOT NULL DEFAULT '[]',
due_at TEXT,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_cards_column ON project_cards (column_id, position);
CREATE INDEX IF NOT EXISTS idx_cards_board ON project_cards (board_id);
CREATE INDEX IF NOT EXISTS idx_cards_assignee ON project_cards (board_id, assignee_id);
@@ -0,0 +1,285 @@
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);
}
+2
View File
@@ -11,6 +11,7 @@ import { registerDiscordRoutes } from './discord.js';
import { registerLogRoutes } from './logs.js';
import { registerOrganizationRoutes } from './organization.js';
import { registerOverviewRoutes } from './overview.js';
import { registerProjectRoutes } from './projects.js';
import { registerReleaseRoutes } from './releases.js';
import { registerRepositoryRoutes } from './repositories.js';
import { registerSettingsRoutes } from './settings.js';
@@ -107,6 +108,7 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
registerOverviewRoutes(router);
registerOrganizationRoutes(router);
registerProjectRoutes(router);
registerRepositoryRoutes(router);
registerReleaseRoutes(router);
registerDeploymentRoutes(router);
+453
View File
@@ -0,0 +1,453 @@
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
addCard,
addColumn,
countCardsInColumn,
countColumns,
createBoard,
getBoard,
getBoardByRepository,
getCard,
getColumn,
getOrgBoard,
listBoards,
listCards,
listColumns,
moveCard,
removeBoard,
removeCard,
removeColumn,
updateBoard,
updateCard,
updateColumn,
} from '../../database/repositories/project-repository.js';
import { repos, splitRepository } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { notify } from '../../services/notifications/notification-service.js';
import { badRequest, notFound } from '../http.js';
/**
* Kanban boards: one per repository, one for the organization (M18).
*
* Cards live here rather than in Gitea, whose project API is not stable across
* versions — a board that breaks whenever the forge hiccups is worse than none.
* A card may still point at an issue, and its real state is fetched when the
* forge answers.
*/
const log = createLogger('web:projects');
const guildId = () => env.discord.guildId;
/** `owner/repo#12`, the only shape a card may reference. */
const ISSUE_REF = /^[\w.-]+\/[\w.-]+#\d+$/;
const publicBoard = (board) => ({
id: board.id,
scope: board.scope,
repository: board.repository,
name: board.name,
description: board.description,
archived: board.archived,
createdAt: board.created_at,
updatedAt: board.updated_at,
});
const publicCard = (card) => ({
id: card.id,
columnId: card.column_id,
title: card.title,
body: card.body,
position: card.position,
assigneeId: card.assignee_id,
issueRef: card.issue_ref,
labels: card.labels,
dueAt: card.due_at,
createdBy: card.created_by,
updatedAt: card.updated_at,
});
const publicColumn = (column) => ({
id: column.id,
name: column.name,
position: column.position,
wipLimit: column.wip_limit,
isDone: column.is_done,
});
function board(id) {
const found = getBoard(Number.parseInt(id, 10));
if (!found || found.guild_id !== guildId()) throw notFound('Tableau introuvable.');
return found;
}
const audit = (actor, type, payload) =>
logEvent({ guildId: guildId(), type, actorId: actor.userId, payload });
/**
* Resolves the referenced issues, one request per repository rather than per
* card. A forge that does not answer costs the cards their live state and
* nothing else.
*/
async function resolveIssues(cards) {
if (!isGiteaConfigured()) return {};
const byRepository = new Map();
for (const ref of new Set(cards.map((card) => card.issue_ref).filter(Boolean))) {
const [full, number] = ref.split('#');
if (!splitRepository(full)) continue;
if (!byRepository.has(full)) byRepository.set(full, new Set());
byRepository.get(full).add(number);
}
if (byRepository.size === 0) return {};
const resolved = {};
await Promise.all(
[...byRepository].map(async ([full, numbers]) => {
const { owner, repo } = splitRepository(full);
const issues = await repos.listIssues(owner, repo, { state: 'all', limit: 100 }).catch(() => []);
for (const issue of issues) {
if (!numbers.has(String(issue.number))) continue;
resolved[`${full}#${issue.number}`] = {
state: issue.state,
title: issue.title,
htmlUrl: issue.html_url,
};
}
}),
);
return resolved;
}
/** Announces a card movement in the community channel, when one is configured. */
async function announce(client, { board: owner, card, action, actor, column }) {
if (!client) return;
const titles = {
created: '🆕 Nouvelle carte',
moved: '➡️ Carte déplacée',
done: '✅ Carte terminée',
};
const embed = {
title: `${titles[action]} — ${owner.name}`,
description: card.title,
color: action === 'done' ? COLORS.success : COLORS.primary,
fields: [
{ name: 'Colonne', value: column?.name ?? '—', inline: true },
...(card.assignee_id ? [{ name: 'Assignée à', value: `<@${card.assignee_id}>`, inline: true }] : []),
...(card.issue_ref ? [{ name: 'Issue', value: card.issue_ref, inline: true }] : []),
],
footer: { text: `Par ${actor.displayName ?? actor.username ?? 'le tableau de bord'}` },
timestamp: new Date().toISOString(),
};
await notify(client, 'community', { embeds: [embed] }).catch((error) =>
log.debug('Could not announce the card movement', error),
);
}
export function registerProjectRoutes(router) {
// --- Boards ----------------------------------------------------------------
router.get(
'/api/projects',
() => ({
boards: listBoards(guildId()).map((entry) => ({
...publicBoard(entry),
columns: countColumns(entry.id),
cards: listCards(entry.id).length,
})),
orgBoard: getOrgBoard(guildId()) ? publicBoard(getOrgBoard(guildId())) : null,
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/projects',
({ body, actor }) => {
const scope = body.scope === 'org' ? 'org' : 'repo';
const repository = scope === 'repo' ? String(body.repository ?? '').trim() : null;
if (scope === 'repo' && !splitRepository(repository)) {
throw badRequest('Dépôt attendu au format `organisation/depot`.');
}
if (scope === 'org' && getOrgBoard(guildId())) {
throw badRequest('L’organisation a déjà son tableau.');
}
if (repository && getBoardByRepository(guildId(), repository)) {
throw badRequest(`Le dépôt ${repository} a déjà son tableau.`);
}
const name = String(body.name ?? '').trim() || (repository ?? 'Organisation');
const created = createBoard({
guildId: guildId(),
scope,
repository,
name,
description: body.description ? String(body.description) : null,
createdBy: actor.userId,
});
audit(actor, 'web.project.create', { board: created.id, scope, repository });
return publicBoard(created);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/projects/:id',
async ({ params }) => {
const found = board(params.id);
const cards = listCards(found.id);
return {
...publicBoard(found),
columns: listColumns(found.id).map((column) => ({
...publicColumn(column),
cards: cards.filter((card) => card.column_id === column.id).map(publicCard),
})),
issues: await resolveIssues(cards),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/projects/:id',
({ params, body, actor }) => {
const found = board(params.id);
const updated = updateBoard(found.id, {
name: body.name === undefined ? undefined : String(body.name).trim(),
description: body.description === undefined ? undefined : String(body.description),
archived: body.archived,
});
audit(actor, 'web.project.update', { board: found.id });
return publicBoard(updated);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.delete(
'/api/projects/:id',
({ params, body, actor }) => {
const found = board(params.id);
if (body.confirm !== found.name) {
throw badRequest(`Pour confirmer, renvoie exactement « ${found.name} ».`);
}
removeBoard(found.id);
audit(actor, 'web.project.delete', { board: found.id, name: found.name });
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
// --- Columns ---------------------------------------------------------------
router.post(
'/api/projects/:id/columns',
({ params, body, actor }) => {
const found = board(params.id);
const name = String(body.name ?? '').trim();
if (name === '') throw badRequest('Nom de colonne manquant.');
const column = addColumn({
boardId: found.id,
name,
wipLimit: Number.parseInt(body.wipLimit ?? 0, 10) || 0,
isDone: Boolean(body.isDone),
});
audit(actor, 'web.project.column.create', { board: found.id, column: column.id });
return publicColumn(column);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/projects/:id/columns/:columnId',
({ params, body }) => {
board(params.id);
const column = getColumn(Number.parseInt(params.columnId, 10));
if (!column) throw notFound('Colonne introuvable.');
return publicColumn(
updateColumn(column.id, {
name: body.name === undefined ? undefined : String(body.name).trim(),
wipLimit: body.wipLimit,
isDone: body.isDone,
position: body.position,
}),
);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.delete(
'/api/projects/:id/columns/:columnId',
({ params, actor }) => {
const found = board(params.id);
if (countColumns(found.id) <= 1) throw badRequest('Un tableau garde au moins une colonne.');
removeColumn(Number.parseInt(params.columnId, 10));
audit(actor, 'web.project.column.delete', { board: found.id, column: params.columnId });
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
// --- Cards -----------------------------------------------------------------
router.post(
'/api/projects/:id/cards',
async ({ params, body, actor, context }) => {
const found = board(params.id);
const title = String(body.title ?? '').trim();
if (title.length < 2) throw badRequest('Le titre doit faire au moins 2 caractères.');
const columnId = Number.parseInt(body.columnId ?? 0, 10);
const column = getColumn(columnId);
if (!column || column.board_id !== found.id) throw badRequest('Colonne inconnue sur ce tableau.');
const issueRef = String(body.issueRef ?? '').trim();
if (issueRef && !ISSUE_REF.test(issueRef)) {
throw badRequest('Référence attendue au format `organisation/depot#12`.');
}
const card = addCard({
boardId: found.id,
columnId,
title,
body: body.body ? String(body.body) : null,
assigneeId: body.assigneeId ? String(body.assigneeId) : null,
issueRef: issueRef || null,
labels: Array.isArray(body.labels) ? body.labels.map(String) : [],
dueAt: body.dueAt ? String(body.dueAt) : null,
createdBy: actor.userId,
});
audit(actor, 'web.project.card.create', { board: found.id, card: card.id });
await announce(context.client, { board: found, card, action: 'created', actor, column });
return publicCard(card);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/projects/:id/cards/:cardId',
({ params, body, actor }) => {
const found = board(params.id);
const card = getCard(Number.parseInt(params.cardId, 10));
if (!card || card.board_id !== found.id) throw notFound('Carte introuvable.');
if (body.issueRef !== undefined && body.issueRef && !ISSUE_REF.test(String(body.issueRef))) {
throw badRequest('Référence attendue au format `organisation/depot#12`.');
}
const updated = updateCard(card.id, {
title: body.title === undefined ? undefined : String(body.title).trim(),
body: body.body === undefined ? undefined : String(body.body),
assigneeId: body.assigneeId,
issueRef: body.issueRef,
labels: body.labels === undefined ? undefined : body.labels.map(String),
dueAt: body.dueAt,
});
audit(actor, 'web.project.card.update', { board: found.id, card: card.id });
return publicCard(updated);
},
{ access: ACCESS_LEVELS.STAFF },
);
/** Drag and drop: the card lands in a column, at a rank. */
router.post(
'/api/projects/:id/cards/:cardId/move',
async ({ params, body, actor, context }) => {
const found = board(params.id);
const card = getCard(Number.parseInt(params.cardId, 10));
if (!card || card.board_id !== found.id) throw notFound('Carte introuvable.');
const columnId = Number.parseInt(body.columnId ?? 0, 10);
const column = getColumn(columnId);
if (!column || column.board_id !== found.id) throw badRequest('Colonne inconnue sur ce tableau.');
// The limit is a warning, not a wall: it says the column is overloaded
// without stopping someone mid-gesture.
const overloaded =
column.wip_limit > 0 &&
card.column_id !== columnId &&
countCardsInColumn(columnId) >= column.wip_limit;
const moved = moveCard(card.id, { columnId, position: Number.parseInt(body.position ?? 0, 10) });
audit(actor, 'web.project.card.move', { board: found.id, card: card.id, column: columnId });
if (card.column_id !== columnId) {
await announce(context.client, {
board: found,
card: moved,
action: column.is_done ? 'done' : 'moved',
actor,
column,
});
}
return { card: publicCard(moved), overloaded };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.delete(
'/api/projects/:id/cards/:cardId',
({ params, actor }) => {
const found = board(params.id);
const card = getCard(Number.parseInt(params.cardId, 10));
if (!card || card.board_id !== found.id) throw notFound('Carte introuvable.');
removeCard(card.id);
audit(actor, 'web.project.card.delete', { board: found.id, card: card.id });
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
/** Turns the open issues of a repository into cards, skipping the ones already there. */
router.post(
'/api/projects/:id/import',
async ({ params, body, actor }) => {
const found = board(params.id);
const repository = String(body.repository ?? found.repository ?? '');
const parts = splitRepository(repository);
if (!parts) throw badRequest('Dépôt attendu au format `organisation/depot`.');
if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré.');
const columns = listColumns(found.id);
const target = columns.find((column) => !column.is_done) ?? columns[0];
if (!target) throw badRequest('Ce tableau n’a aucune colonne.');
const existing = new Set(
listCards(found.id)
.map((card) => card.issue_ref)
.filter(Boolean),
);
const issues = await repos.listIssues(parts.owner, parts.repo, { state: 'open', limit: 50 });
let imported = 0;
for (const issue of issues) {
const ref = `${repository}#${issue.number}`;
if (existing.has(ref)) continue;
addCard({
boardId: found.id,
columnId: target.id,
title: issue.title,
body: issue.body ? String(issue.body).slice(0, 2000) : null,
issueRef: ref,
labels: (issue.labels ?? []).map((label) => label.name),
createdBy: actor.userId,
});
imported += 1;
}
audit(actor, 'web.project.import', { board: found.id, repository, imported });
return { imported, skipped: issues.length - imported, column: target.name };
},
{ access: ACCESS_LEVELS.STAFF },
);
}
+2
View File
@@ -122,6 +122,8 @@ export function topicForPath(pathname) {
case 'repositories':
case 'organization':
return 'gitea';
case 'projects':
return 'projects';
case 'discord':
return 'discord';
case 'community':
+334
View File
@@ -0,0 +1,334 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
DEFAULT_COLUMNS,
addCard,
addColumn,
countCardsInColumn,
createBoard,
getBoardByRepository,
getCard,
getOrgBoard,
listBoards,
listCards,
listCardsForAssignee,
listColumns,
moveCard,
removeBoard,
removeColumn,
} from '../src/database/repositories/project-repository.js';
import { createApiToken } from '../src/database/repositories/web-session-repository.js';
import { hashToken } from '../src/web/auth/session.js';
import { createHandler } from '../src/web/server.js';
/** Kanban boards (M18). */
const GUILD = '';
const board = (overrides = {}) =>
createBoard({ guildId: GUILD, scope: 'repo', repository: 'FWS/FWS-Arch', name: 'FWS Arch', ...overrides });
const columnsOf = (id) => listColumns(id);
describe('project boards', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM project_boards;'));
it('creates a board with the FWS columns', () => {
const created = board();
assert.deepEqual(
columnsOf(created.id).map((column) => column.name),
DEFAULT_COLUMNS.map((column) => column.name),
);
});
it('marks the last column as the finished one', () => {
const columns = columnsOf(board().id);
assert.equal(columns.at(-1).is_done, true);
assert.equal(columns[0].is_done, false);
});
it('carries the default limit on « En cours »', () => {
const inProgress = columnsOf(board().id).find((column) => column.name === 'En cours');
assert.equal(inProgress.wip_limit, 3);
});
it('allows one board per repository', () => {
board();
assert.throws(() => board(), /UNIQUE/);
});
it('allows a single organization board', () => {
createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
assert.throws(() => createBoard({ guildId: GUILD, scope: 'org', name: 'Autre' }), /UNIQUE/);
});
it('finds a board by its repository and by its scope', () => {
const repo = board();
const org = createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
assert.equal(getBoardByRepository(GUILD, 'FWS/FWS-Arch').id, repo.id);
assert.equal(getOrgBoard(GUILD).id, org.id);
assert.equal(listBoards(GUILD).length, 2);
});
it('takes its columns and cards with it when deleted', () => {
const created = board();
addCard({ boardId: created.id, columnId: columnsOf(created.id)[0].id, title: 'Une tâche' });
removeBoard(created.id);
assert.equal(listColumns(created.id).length, 0);
assert.equal(listCards(created.id).length, 0);
});
});
describe('cards', () => {
let created;
let columns;
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM project_boards;');
created = board();
columns = columnsOf(created.id);
});
const add = (title, columnId = columns[0].id) => addCard({ boardId: created.id, columnId, title });
const titles = (columnId) =>
listCards(created.id)
.filter((card) => card.column_id === columnId)
.sort((a, b) => a.position - b.position)
.map((card) => card.title);
it('appends a card at the end of its column', () => {
add('un');
add('deux');
assert.deepEqual(titles(columns[0].id), ['un', 'deux']);
});
it('keeps labels as a list', () => {
const card = addCard({
boardId: created.id,
columnId: columns[0].id,
title: 'Étiquetée',
labels: ['bug', 'urgent'],
});
assert.deepEqual(getCard(card.id).labels, ['bug', 'urgent']);
});
it('moves a card to another column', () => {
const card = add('un');
add('deux');
moveCard(card.id, { columnId: columns[1].id, position: 0 });
assert.deepEqual(titles(columns[0].id), ['deux']);
assert.deepEqual(titles(columns[1].id), ['un']);
});
it('inserts at the requested rank', () => {
add('un');
add('deux');
const third = add('trois');
moveCard(third.id, { columnId: columns[0].id, position: 1 });
assert.deepEqual(titles(columns[0].id), ['un', 'trois', 'deux']);
});
/** Positions must stay contiguous, or the next drop lands somewhere odd. */
it('renumbers both columns after a move', () => {
add('un');
const second = add('deux');
add('trois');
moveCard(second.id, { columnId: columns[1].id, position: 0 });
const left = listCards(created.id).filter((card) => card.column_id === columns[0].id);
assert.deepEqual(left.map((card) => card.position).sort(), [0, 1], 'la colonne quittée garde un trou');
assert.equal(getCard(second.id).position, 0);
});
it('survives a move onto itself', () => {
const card = add('un');
add('deux');
moveCard(card.id, { columnId: columns[0].id, position: 1 });
assert.deepEqual(titles(columns[0].id), ['deux', 'un']);
});
it('counts the cards of a column', () => {
add('un');
add('deux');
assert.equal(countCardsInColumn(columns[0].id), 2);
assert.equal(countCardsInColumn(columns[1].id), 0);
});
it('lists what one member carries, soonest deadline first', () => {
addCard({
boardId: created.id,
columnId: columns[0].id,
title: 'plus tard',
assigneeId: 'u1',
dueAt: '2026-12-01',
});
addCard({
boardId: created.id,
columnId: columns[0].id,
title: 'bientôt',
assigneeId: 'u1',
dueAt: '2026-10-01',
});
addCard({ boardId: created.id, columnId: columns[0].id, title: 'sans date', assigneeId: 'u1' });
addCard({ boardId: created.id, columnId: columns[0].id, title: 'quelqu’un d’autre', assigneeId: 'u2' });
assert.deepEqual(
listCardsForAssignee(GUILD, 'u1').map((card) => card.title),
['bientôt', 'plus tard', 'sans date'],
);
});
it('drops the cards of a removed column', () => {
add('un');
const extra = addColumn({ boardId: created.id, name: 'Bloqué' });
const card = add('deux', extra.id);
removeColumn(extra.id);
assert.equal(getCard(card.id), null);
assert.deepEqual(titles(columns[0].id), ['un']);
});
});
describe('projects over HTTP', () => {
const TOKEN = 'fws_projects-test';
let app;
before(async () => {
initDatabase(':memory:');
createApiToken({
name: 'projects',
tokenHash: hashToken(TOKEN),
prefix: TOKEN.slice(0, 12),
accessLevel: ACCESS_LEVELS.OWNER,
});
app = createServer(createHandler({ client: null, setupOnly: false }));
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
});
after(async () => {
await new Promise((resolve) => app.close(resolve));
closeDatabase();
});
beforeEach(() => getDatabase().exec('DELETE FROM project_boards;'));
const call = (method, path, body) =>
fetch(`http://127.0.0.1:${app.address().port}${path}`, {
method,
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
it('refuses a board without a session', async () => {
const response = await fetch(`http://127.0.0.1:${app.address().port}/api/projects`);
assert.equal(response.status, 401);
});
it('creates the organization board once', async () => {
assert.equal((await call('POST', '/api/projects', { scope: 'org', name: 'Organisation' })).status, 200);
const again = await call('POST', '/api/projects', { scope: 'org', name: 'Encore' });
assert.equal(again.status, 400);
assert.match((await again.json()).error, /déjà son tableau/);
});
it('refuses a repository that is not owner/name', async () => {
const response = await call('POST', '/api/projects', { scope: 'repo', repository: 'pas-un-depot' });
assert.equal(response.status, 400);
});
it('returns a board with its columns and cards', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
const columns = columnsOf(created.id);
await call('POST', `/api/projects/${created.id}/cards`, {
columnId: columns[0].id,
title: 'Première carte',
});
const full = await (await call('GET', `/api/projects/${created.id}`)).json();
assert.equal(full.columns.length, DEFAULT_COLUMNS.length);
assert.equal(full.columns[0].cards[0].title, 'Première carte');
});
it('refuses an issue reference that is not owner/repo#n', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
const response = await call('POST', `/api/projects/${created.id}/cards`, {
columnId: columnsOf(created.id)[0].id,
title: 'Liée',
issueRef: 'pas-une-reference',
});
assert.equal(response.status, 400);
assert.match((await response.json()).error, /organisation\/depot#12/);
});
it('reports an overloaded column without refusing the move', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
const columns = columnsOf(created.id);
const inProgress = columns.find((column) => column.name === 'En cours');
// Fill it to its limit of three, then push a fourth in. Each step is
// asserted, so a failure cannot cascade into a misleading one later.
const cards = [];
for (const title of ['une', 'deux', 'trois', 'quatre']) {
const response = await call('POST', `/api/projects/${created.id}/cards`, {
columnId: columns[0].id,
title,
});
assert.equal(response.status, 200, `la carte « ${title} » n'a pas été créée`);
cards.push(await response.json());
}
for (const card of cards.slice(0, 3)) {
const response = await call('POST', `/api/projects/${created.id}/cards/${card.id}/move`, {
columnId: inProgress.id,
});
assert.equal(response.status, 200, `le déplacement de « ${card.title} » a échoué`);
assert.equal(
(await response.json()).overloaded,
false,
'la limite ne doit pas être atteinte avant la 4e',
);
}
const response = await call('POST', `/api/projects/${created.id}/cards/${cards[3].id}/move`, {
columnId: inProgress.id,
});
const body = await response.json();
assert.equal(response.status, 200, 'le déplacement doit aboutir malgré la limite');
assert.equal(body.overloaded, true);
assert.equal(countCardsInColumn(inProgress.id), 4);
});
it('keeps a board from losing its last column', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
for (const column of columnsOf(created.id).slice(0, 3)) {
await call('DELETE', `/api/projects/${created.id}/columns/${column.id}`);
}
const last = columnsOf(created.id);
assert.equal(last.length, 1);
const response = await call('DELETE', `/api/projects/${created.id}/columns/${last[0].id}`);
assert.equal(response.status, 400);
});
it('asks for the name before deleting a board', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
assert.equal((await call('DELETE', `/api/projects/${created.id}`, { confirm: 'faux' })).status, 400);
assert.equal((await call('DELETE', `/api/projects/${created.id}`, { confirm: 'Org' })).status, 200);
});
});