diff --git a/src/web/api/projects.js b/src/web/api/projects.js index 801140e..fdb5ba2 100644 --- a/src/web/api/projects.js +++ b/src/web/api/projects.js @@ -407,26 +407,40 @@ export function registerProjectRoutes(router) { { access: ACCESS_LEVELS.STAFF }, ); - /** Turns the open issues of a repository into cards, skipping the ones already there. */ + /** + * Pulls issues from Gitea onto the board. + * + * An issue already on the board is skipped rather than duplicated, so the + * button can be pressed again after a sprint without cleaning up after it. + */ 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 repository = String(body.repository ?? found.repository ?? '').trim(); + const parts = splitRepository(repository); + if (!parts) throw badRequest('Dépôt attendu au format `organisation/depot`.'); + + const state = body.state === 'all' ? 'all' : 'open'; 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.'); + if (columns.length === 0) throw badRequest('Ce tableau n’a aucune colonne.'); + + // Falls back to the first column that is not the finished one: importing + // straight into « Terminé » is never what anyone means. + const requested = body.columnId ? getColumn(Number.parseInt(body.columnId, 10)) : null; + const target = + requested && requested.board_id === found.id + ? requested + : (columns.find((column) => !column.is_done) ?? columns[0]); 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 }); + const issues = await repos.listIssues(parts.owner, parts.repo, { state, limit: 100 }); let imported = 0; for (const issue of issues) { @@ -440,13 +454,20 @@ export function registerProjectRoutes(router) { body: issue.body ? String(issue.body).slice(0, 2000) : null, issueRef: ref, labels: (issue.labels ?? []).map((label) => label.name), + dueAt: issue.due_date ? String(issue.due_date).slice(0, 10) : null, createdBy: actor.userId, }); imported += 1; } - audit(actor, 'web.project.import', { board: found.id, repository, imported }); - return { imported, skipped: issues.length - imported, column: target.name }; + audit(actor, 'web.project.import', { board: found.id, repository, state, imported }); + return { + imported, + skipped: issues.length - imported, + found: issues.length, + column: target.name, + repository, + }; }, { access: ACCESS_LEVELS.STAFF }, ); diff --git a/src/web/public/views/projects.js b/src/web/public/views/projects.js index dfda19b..3db23a7 100644 --- a/src/web/public/views/projects.js +++ b/src/web/public/views/projects.js @@ -345,18 +345,7 @@ async function renderBoard(host, state, id) { h( 'div', { class: 'row' }, - board.repository && - button( - 'Importer les issues', - async () => { - const result = await api.post(`/api/projects/${board.id}/import`, {}); - toast( - `${result.imported} carte(s) créée(s) dans « ${result.column} », ${result.skipped} déjà présente(s).`, - ); - reload(); - }, - { tone: 'ghost' }, - ), + button('Importer depuis Gitea', () => importIssues(board, reload), { tone: 'ghost' }), button('Colonne', () => addColumn(board, reload), { tone: 'ghost' }), level >= LEVELS.OWNER && button( @@ -389,6 +378,73 @@ async function renderBoard(host, state, id) { ); } +/** + * Pulls Gitea issues onto the board. + * + * Offered on every board, not only on a repository one: the organization board + * is exactly where issues from several repositories belong together. + */ +async function importIssues(board, reload) { + const { repositories } = await api.get('/api/repositories').catch(() => ({ repositories: [] })); + + const repository = + repositories.length > 0 + ? select( + repositories.map((entry) => ({ value: entry.fullName, label: entry.fullName })), + { value: board.repository ?? repositories[0]?.fullName }, + ) + : input({ value: board.repository ?? '', placeholder: 'FWS/FWS-Arch' }); + + const column = select( + board.columns.map((entry) => ({ value: String(entry.id), label: entry.name })), + { value: String((board.columns.find((entry) => !entry.isDone) ?? board.columns[0])?.id) }, + ); + let closedToo = false; + + const confirmed = await modal( + 'Importer depuis Gitea', + () => ({ + node: h( + 'div', + { class: 'stack' }, + repositories.length === 0 && + notice( + 'La liste des dépôts est indisponible — saisis le dépôt à la main, au format `organisation/depot`.', + 'warning', + ), + field('Dépôt', repository), + field('Colonne d’arrivée', column), + toggle(false, (checked) => (closedToo = checked), 'Inclure aussi les issues fermées'), + h('p', { + class: 'muted', + text: 'Une issue déjà présente sur le tableau est ignorée : tu peux relancer l’import sans créer de doublon.', + }), + ), + submit: () => repository.value.trim() !== '', + }), + { confirmLabel: 'Importer', tone: 'primary' }, + ); + if (!confirmed) return; + + try { + const result = await api.post(`/api/projects/${board.id}/import`, { + repository: repository.value.trim(), + columnId: Number(column.value), + state: closedToo ? 'all' : 'open', + }); + + toast( + result.imported === 0 + ? `Rien à importer : les ${result.found} issue(s) de ${result.repository} sont déjà sur le tableau.` + : `${result.imported} carte(s) créée(s) dans « ${result.column} », ${result.skipped} déjà présente(s).`, + result.imported === 0 ? 'info' : 'success', + ); + reload(); + } catch (error) { + toast(error.message, 'error'); + } +} + async function addColumn(board, reload) { const name = input({ placeholder: 'Nom de la colonne' }); const wipLimit = input({ type: 'number', value: 0, min: 0 }); diff --git a/tests/projects-import.test.js b/tests/projects-import.test.js new file mode 100644 index 0000000..9b442e3 --- /dev/null +++ b/tests/projects-import.test.js @@ -0,0 +1,145 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { after, before, beforeEach, describe, it } from 'node:test'; + +/** + * Importing Gitea issues onto a board (M18). + * + * A stand-in forge answers on a real socket, and the environment is set before + * the modules that read it are loaded — hence the dynamic imports. + */ + +let issues = []; + +const forge = createServer((request, response) => { + if (!request.url.includes('/issues')) { + response.writeHead(404).end(); + return; + } + const state = new URL(request.url, 'http://x').searchParams.get('state'); + const body = state === 'all' ? issues : issues.filter((issue) => issue.state === 'open'); + + response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(body)); +}); +await new Promise((resolve) => forge.listen(0, '127.0.0.1', resolve)); + +process.env.GITEA_URL = `http://127.0.0.1:${forge.address().port}`; +process.env.GITEA_TOKEN = 'jeton-de-test'; +process.env.GITEA_OWNER = 'FWS'; + +const { closeDatabase, getDatabase, initDatabase } = await import('../src/database/index.js'); +const { createBoard, listCards, listColumns } = await import( + '../src/database/repositories/project-repository.js' +); +const { createApiToken } = await import('../src/database/repositories/web-session-repository.js'); +const { hashToken } = await import('../src/web/auth/session.js'); +const { createHandler } = await import('../src/web/server.js'); + +const TOKEN = 'fws_import-test'; + +describe('importing issues from Gitea', () => { + let app; + let board; + let columns; + + before(async () => { + initDatabase(':memory:'); + createApiToken({ name: 'import', tokenHash: hashToken(TOKEN), prefix: 'fws_impo', accessLevel: 3 }); + app = createServer(createHandler({ client: null })); + await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve)); + }); + + after(async () => { + await new Promise((resolve) => app.close(resolve)); + await new Promise((resolve) => forge.close(resolve)); + closeDatabase(); + }); + + beforeEach(() => { + getDatabase().exec('DELETE FROM project_boards;'); + board = createBoard({ guildId: '', scope: 'org', name: 'Organisation' }); + columns = listColumns(board.id); + + issues = [ + { number: 1, title: 'Corriger le démarrage', state: 'open', body: 'Détails', labels: [{ name: 'bug' }] }, + { number: 2, title: 'Documenter le wiki', state: 'open', body: null, labels: [] }, + { number: 3, title: 'Ancienne demande', state: 'closed', body: null, labels: [] }, + ]; + }); + + const call = (path, body) => + fetch(`http://127.0.0.1:${app.address().port}${path}`, { + method: 'POST', + headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + + const importInto = (body = {}) => + call(`/api/projects/${board.id}/import`, { repository: 'FWS/FWS-Arch', ...body }).then((response) => + response.json(), + ); + + it('creates one card per open issue', async () => { + const result = await importInto(); + + assert.equal(result.imported, 2); + assert.equal(result.column, 'À faire'); + assert.deepEqual( + listCards(board.id) + .map((card) => card.title) + .sort(), + ['Corriger le démarrage', 'Documenter le wiki'], + ); + }); + + it('records the issue each card came from', async () => { + await importInto(); + const card = listCards(board.id).find((entry) => entry.title === 'Corriger le démarrage'); + + assert.equal(card.issue_ref, 'FWS/FWS-Arch#1'); + assert.deepEqual(card.labels, ['bug']); + assert.match(card.body, /Détails/); + }); + + /** The button has to survive being pressed twice. */ + it('skips what is already on the board', async () => { + await importInto(); + const second = await importInto(); + + assert.equal(second.imported, 0); + assert.equal(second.skipped, 2); + assert.equal(listCards(board.id).length, 2); + }); + + it('brings the closed issues in when asked', async () => { + const result = await importInto({ state: 'all' }); + assert.equal(result.imported, 3); + }); + + it('imports into the chosen column', async () => { + const review = columns.find((column) => column.name === 'En revue'); + const result = await importInto({ columnId: review.id }); + + assert.equal(result.column, 'En revue'); + assert.ok(listCards(board.id).every((card) => card.column_id === review.id)); + }); + + /** Importing straight into « Terminé » is never what anyone means. */ + it('never imports into a column of another board', async () => { + const other = createBoard({ guildId: '', scope: 'repo', repository: 'FWS/site', name: 'Site' }); + const foreign = listColumns(other.id)[0]; + + const result = await importInto({ columnId: foreign.id }); + assert.equal(result.column, 'À faire'); + assert.equal(listCards(other.id).length, 0); + }); + + it('reports what it found even when nothing is new', async () => { + issues = []; + const result = await importInto(); + + assert.equal(result.found, 0); + assert.equal(result.imported, 0); + assert.equal(result.repository, 'FWS/FWS-Arch'); + }); +}); diff --git a/tests/projects.test.js b/tests/projects.test.js index 7fbf755..7511a50 100644 --- a/tests/projects.test.js +++ b/tests/projects.test.js @@ -325,6 +325,23 @@ describe('projects over HTTP', () => { assert.equal(response.status, 400); }); + it('refuses to import when Gitea is not configured', async () => { + const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json(); + const response = await call('POST', `/api/projects/${created.id}/import`, { + repository: 'FWS/FWS-Arch', + }); + + // `GITEA_TOKEN` is unset in the tests, so the import cannot run. + assert.equal(response.status, 400); + assert.match((await response.json()).error, /Gitea/); + }); + + it('refuses a repository that is not owner/name', async () => { + const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json(); + const response = await call('POST', `/api/projects/${created.id}/import`, { repository: 'nope' }); + 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();