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:
6 files changed
+1133
No files matched your search
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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 },
|
||||
);
|
||||
}
|
||||
@@ -122,6 +122,8 @@ export function topicForPath(pathname) {
|
||||
case 'repositories':
|
||||
case 'organization':
|
||||
return 'gitea';
|
||||
case 'projects':
|
||||
return 'projects';
|
||||
case 'discord':
|
||||
return 'discord';
|
||||
case 'community':
|
||||
|
||||
Reference in new issue
Block a user