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 }, ); }