Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1b9a5cc77
|
||
|
|
901ca56959
|
||
|
|
b793298cbf
|
||
|
|
3f4a5709cf
|
||
|
|
c031b4d9e2
|
||
|
|
92c27aed9f
|
||
|
|
75d1e53205
|
||
|
|
95b51ab428
|
||
|
|
539b1506f4
|
||
|
|
3bd290cba6
|
||
|
|
afcd0e55bc
|
||
|
|
40032ec091
|
||
|
|
5660235f3d
|
||
|
|
e5b7303a01
|
||
|
|
c76c0b96eb
|
||
|
|
621f3e404b
|
||
|
|
e397abcfcd
|
||
|
|
262274473a
|
||
|
|
b42fb1065a
|
||
|
|
406b5af3ea
|
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);
|
||||
}
|
||||
+22
-4
@@ -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';
|
||||
@@ -32,7 +33,20 @@ const VERSION = (() => {
|
||||
* Deployments that ship an archive make it easy to look at a stale copy and
|
||||
* wonder why a fix is missing; this gives the page something to state.
|
||||
*/
|
||||
const BUILD_AT = (() => {
|
||||
/**
|
||||
* Newest file of the served interface.
|
||||
*
|
||||
* Read from disk rather than frozen at startup: the front-end is served from
|
||||
* disk on every request, so a marker captured at boot would keep announcing an
|
||||
* old build after an upload — the exact confusion it exists to prevent. Cached
|
||||
* briefly so a health check does not walk the tree each time.
|
||||
*/
|
||||
const BUILD_TTL_MS = 10_000;
|
||||
let buildCache = { at: null, readAt: 0 };
|
||||
|
||||
function buildAt() {
|
||||
if (buildCache.readAt && Date.now() - buildCache.readAt < BUILD_TTL_MS) return buildCache.at;
|
||||
|
||||
const root = path.join(here, '../public');
|
||||
let newest = 0;
|
||||
|
||||
@@ -47,10 +61,13 @@ const BUILD_AT = (() => {
|
||||
try {
|
||||
walk(root);
|
||||
} catch {
|
||||
buildCache = { at: null, readAt: Date.now() };
|
||||
return null;
|
||||
}
|
||||
return newest > 0 ? new Date(newest).toISOString() : null;
|
||||
})();
|
||||
|
||||
buildCache = { at: newest > 0 ? new Date(newest).toISOString() : null, readAt: Date.now() };
|
||||
return buildCache.at;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route registration order matters only for readability: the router matches on
|
||||
@@ -66,7 +83,7 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
|
||||
setupOnly: context.setupOnly,
|
||||
uptimeMs: Date.now() - context.startedAt,
|
||||
version: VERSION,
|
||||
buildAt: BUILD_AT,
|
||||
buildAt: buildAt(),
|
||||
}),
|
||||
{ public: true },
|
||||
);
|
||||
@@ -91,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':
|
||||
|
||||
+8
-2
@@ -164,8 +164,14 @@ export async function sendStatic(response, root, requestPath, { fallback = null,
|
||||
...SECURITY_HEADERS,
|
||||
'Content-Type': MIME_TYPES[extension] ?? 'application/octet-stream',
|
||||
'Content-Length': info.size,
|
||||
// The SPA shell must never be cached, its modules are revalidated on each load.
|
||||
'Cache-Control': extension === '.html' ? 'no-store' : 'no-cache',
|
||||
// Every module is fetched fresh rather than revalidated.
|
||||
//
|
||||
// A dashboard is a handful of small files loaded by one person at a time,
|
||||
// so the bandwidth saved by caching is worth less than the failure it
|
||||
// causes: modules cache independently, so a partial revalidation leaves a
|
||||
// page running one version of itself and another of its helpers, which
|
||||
// surfaces as an error inside a feature rather than as a stale cache.
|
||||
'Cache-Control': 'no-store',
|
||||
ETag: etag,
|
||||
'Last-Modified': new Date(info.mtimeMs).toUTCString(),
|
||||
});
|
||||
|
||||
+13
-13
@@ -1,6 +1,7 @@
|
||||
import { api } from './core/api.js';
|
||||
import { h, mount, qs } from './core/dom.js';
|
||||
import { onStatus, resetSubscriptions, startLive } from './core/live.js';
|
||||
import { activePath, highlight } from './core/nav.js';
|
||||
import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js';
|
||||
|
||||
/** Shell, navigation and hash routing of the dashboard (M16-T11). */
|
||||
@@ -28,6 +29,14 @@ const ROUTES = [
|
||||
module: './views/organization.js',
|
||||
level: LEVELS.STAFF,
|
||||
},
|
||||
{
|
||||
path: 'projects',
|
||||
icon: '▦',
|
||||
label: 'Projets',
|
||||
group: 'Pilotage',
|
||||
module: './views/projects.js',
|
||||
level: LEVELS.STAFF,
|
||||
},
|
||||
{
|
||||
path: 'repos',
|
||||
icon: '◫',
|
||||
@@ -138,7 +147,7 @@ const currentRoute = () => {
|
||||
const raw = window.location.hash.replace(/^#\/?/, '');
|
||||
const [path] = raw.split('?');
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
return { segments, path };
|
||||
return { segments, path, active: activePath(window.location.hash) };
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -148,18 +157,8 @@ const currentRoute = () => {
|
||||
* its own — otherwise it keeps pointing at the page you arrived on.
|
||||
*/
|
||||
function highlightNav(scope = document) {
|
||||
const { segments } = currentRoute();
|
||||
const active = segments[0] ?? '';
|
||||
const active = highlight(scope, window.location.hash);
|
||||
const route = ROUTES.find((entry) => entry.path === active);
|
||||
|
||||
for (const link of scope.querySelectorAll('.nav a')) {
|
||||
// Compare the route the link carries, not its href: a trailing slash or a
|
||||
// query string in the hash must not make an entry look inactive.
|
||||
const current = link.dataset.route === active;
|
||||
link.classList.toggle('active', current);
|
||||
if (current) link.setAttribute('aria-current', 'page');
|
||||
else link.removeAttribute('aria-current');
|
||||
}
|
||||
document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot';
|
||||
}
|
||||
|
||||
@@ -310,8 +309,9 @@ async function renderView(host) {
|
||||
const module = await import(route.module);
|
||||
await module.render(host, { params: segments.slice(1), state });
|
||||
} catch (error) {
|
||||
console.error('[fws] échec de la vue', error);
|
||||
const { errorBox } = await import('./core/ui.js');
|
||||
mount(host, errorBox(error.message, { retry: () => renderView(host) }));
|
||||
mount(host, errorBox(error.message, { retry: () => renderView(host), error }));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ function connect() {
|
||||
'gitea',
|
||||
'discord',
|
||||
'community',
|
||||
'projects',
|
||||
'settings',
|
||||
]) {
|
||||
source.addEventListener(topic, (event) => {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Which navigation entry is the current one (M16-T11).
|
||||
*
|
||||
* Kept apart from the shell so it can be tested: getting this wrong leaves the
|
||||
* sidebar pointing at a page you are not on, which is the kind of bug that
|
||||
* looks like nothing and gets reported three times.
|
||||
*/
|
||||
|
||||
/**
|
||||
* First segment of a hash route, which is what a sidebar entry stands for.
|
||||
* `#/repos/FWS/Arch` and `#/repos` are the same entry; `#/releases?repo=x` too.
|
||||
*/
|
||||
export function activePath(hash = '') {
|
||||
const raw = String(hash).replace(/^#\/?/, '');
|
||||
const [path] = raw.split('?');
|
||||
const [first = ''] = path.split('/').filter(Boolean);
|
||||
return first;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the matching link inside `scope` and clears the others.
|
||||
* Returns the active path, so a caller can retitle the page from it.
|
||||
*/
|
||||
export function highlight(scope, hash = '') {
|
||||
const active = activePath(hash);
|
||||
|
||||
for (const link of scope.querySelectorAll('.nav a')) {
|
||||
// Compare the route a link carries, not its href: a trailing slash or a
|
||||
// query string must not make an entry look inactive.
|
||||
const current = (link.dataset.route ?? '') === active;
|
||||
link.classList.toggle('active', current);
|
||||
if (current) link.setAttribute('aria-current', 'page');
|
||||
else link.removeAttribute('aria-current');
|
||||
}
|
||||
return active;
|
||||
}
|
||||
@@ -154,7 +154,12 @@ export const spinner = (label = 'Chargement…') =>
|
||||
const looksLikeVersionMismatch = (message) =>
|
||||
/Cannot read propert|undefined is not|is not a function|of undefined/i.test(String(message));
|
||||
|
||||
export const errorBox = (message, { retry } = {}) =>
|
||||
/**
|
||||
* `error` carries the stack; `message` alone leaves nobody able to say where it
|
||||
* came from. Showing it on the page matters for a self-hosted panel, where
|
||||
* opening the developer console is not always an option.
|
||||
*/
|
||||
export const errorBox = (message, { retry, error = null } = {}) =>
|
||||
h(
|
||||
'div',
|
||||
{ class: 'notice notice-error' },
|
||||
@@ -167,6 +172,13 @@ export const errorBox = (message, { retry } = {}) =>
|
||||
class: 'muted',
|
||||
text: 'Cette erreur vient en général d’une interface plus ancienne que l’API : recharge avec Ctrl+Shift+R, et si elle persiste, re-téléverse le dossier src/web/public.',
|
||||
}),
|
||||
error?.stack &&
|
||||
h(
|
||||
'details',
|
||||
{},
|
||||
h('summary', { text: 'Détails techniques' }),
|
||||
h('pre', {}, h('code', { text: error.stack })),
|
||||
),
|
||||
),
|
||||
retry && button('Réessayer', retry, { tone: 'ghost' }),
|
||||
);
|
||||
@@ -257,7 +269,9 @@ export async function renderAsync(host, load, build) {
|
||||
const data = await load();
|
||||
mount(host, await build(data));
|
||||
} catch (error) {
|
||||
mount(host, errorBox(error.message, { retry: () => renderAsync(host, load, build) }));
|
||||
// Swallowing the stack leaves a failure impossible to place.
|
||||
console.error('[fws] échec du rendu', error);
|
||||
mount(host, errorBox(error.message, { retry: () => renderAsync(host, load, build), error }));
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
@@ -771,6 +771,73 @@ details > *:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* --- Kanban --------------------------------------------------------------- */
|
||||
|
||||
.kboard {
|
||||
display: flex;
|
||||
gap: 0.8rem;
|
||||
align-items: flex-start;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.6rem;
|
||||
}
|
||||
|
||||
.kcolumn {
|
||||
flex: 0 0 280px;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 0.7rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
min-height: 8rem;
|
||||
}
|
||||
.kcolumn > header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
/* Only the border moves: a background change under a dragged card flickers. */
|
||||
.kcolumn-target {
|
||||
border-color: var(--blue);
|
||||
box-shadow: inset 0 0 0 1px var(--blue);
|
||||
}
|
||||
.kcolumn-over > header .muted {
|
||||
color: var(--amber);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.kcolumn-cards {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
min-height: 2.5rem;
|
||||
}
|
||||
|
||||
.kcard {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 0.6rem 0.7rem;
|
||||
cursor: grab;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
.kcard:hover {
|
||||
border-color: var(--blue);
|
||||
}
|
||||
.kcard h4 {
|
||||
font-size: 0.88rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.kcard.dragging {
|
||||
opacity: 0.4;
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
/* --- Simple / advanced mode ---------------------------------------------- */
|
||||
|
||||
body[data-mode='simple'] .advanced-only {
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
import { api } from '../core/api.js';
|
||||
import { formatRelative, h, mount } from '../core/dom.js';
|
||||
import { autoRefresh } from '../core/live.js';
|
||||
import {
|
||||
badge,
|
||||
button,
|
||||
card,
|
||||
confirmDangerous,
|
||||
field,
|
||||
input,
|
||||
modal,
|
||||
notice,
|
||||
renderAsync,
|
||||
select,
|
||||
spinner,
|
||||
table,
|
||||
textarea,
|
||||
toast,
|
||||
toggle,
|
||||
} from '../core/ui.js';
|
||||
|
||||
/** Kanban boards: one per repository, one for the organization (M18). */
|
||||
|
||||
const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
|
||||
|
||||
const overdue = (dueAt) => dueAt && new Date(`${dueAt}Z`) < new Date();
|
||||
|
||||
// --- Board list --------------------------------------------------------------
|
||||
|
||||
function renderList(host, state) {
|
||||
const reload = () => renderList(host, state);
|
||||
|
||||
return renderAsync(
|
||||
host,
|
||||
async () => {
|
||||
const [projects, repositories] = await Promise.all([
|
||||
api.get('/api/projects'),
|
||||
api.get('/api/repositories').catch(() => ({ repositories: [] })),
|
||||
]);
|
||||
return { ...projects, repositories: repositories.repositories ?? [] };
|
||||
},
|
||||
(data) => {
|
||||
const taken = new Set(data.boards.map((entry) => entry.repository).filter(Boolean));
|
||||
const available = data.repositories.filter((entry) => !taken.has(entry.fullName));
|
||||
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'page-head' },
|
||||
h(
|
||||
'div',
|
||||
{},
|
||||
h('h1', { text: 'Projets' }),
|
||||
h('p', {
|
||||
class: 'muted',
|
||||
text: 'Un tableau par dépôt, plus un pour l’organisation. Les cartes peuvent pointer vers une issue Gitea.',
|
||||
}),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
!data.orgBoard &&
|
||||
button('Tableau de l’organisation', () => createBoard({ scope: 'org' }, reload), {
|
||||
tone: 'primary',
|
||||
}),
|
||||
available.length > 0 &&
|
||||
button('Tableau de dépôt', () => createBoard({ scope: 'repo', available }, reload), {
|
||||
tone: available.length > 0 && data.orgBoard ? 'primary' : 'ghost',
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
data.boards.length === 0 &&
|
||||
notice(
|
||||
'Aucun tableau pour l’instant. Commence par celui de l’organisation, puis ajoute ceux des dépôts.',
|
||||
'info',
|
||||
),
|
||||
|
||||
card(
|
||||
'Tableaux',
|
||||
{ subtitle: `${data.boards.length} tableau(x)` },
|
||||
table(
|
||||
[
|
||||
{
|
||||
label: 'Tableau',
|
||||
render: (entry) =>
|
||||
h(
|
||||
'div',
|
||||
{},
|
||||
h('strong', { text: entry.name }),
|
||||
h('div', {
|
||||
class: 'muted',
|
||||
text: entry.scope === 'org' ? 'Organisation' : entry.repository,
|
||||
}),
|
||||
),
|
||||
},
|
||||
{
|
||||
label: 'Portée',
|
||||
render: (entry) =>
|
||||
entry.scope === 'org' ? badge('Organisation', 'info') : badge('Dépôt', 'neutral'),
|
||||
},
|
||||
{ label: 'Colonnes', className: 'num', key: 'columns' },
|
||||
{ label: 'Cartes', className: 'num', key: 'cards' },
|
||||
{
|
||||
label: 'Modifié',
|
||||
className: 'nowrap',
|
||||
render: (entry) => formatRelative(entry.updatedAt),
|
||||
},
|
||||
],
|
||||
data.boards,
|
||||
{
|
||||
empty: 'Aucun tableau.',
|
||||
rowHref: (entry) => `#/projects/${entry.id}`,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function createBoard({ scope, available = [] }, reload) {
|
||||
const name = input({ placeholder: scope === 'org' ? 'Organisation FWS' : 'Nom du tableau' });
|
||||
const repository =
|
||||
scope === 'repo'
|
||||
? select(
|
||||
available.map((entry) => ({ value: entry.fullName, label: entry.fullName })),
|
||||
{},
|
||||
)
|
||||
: null;
|
||||
const description = input({ placeholder: 'À quoi sert ce tableau ?' });
|
||||
|
||||
const confirmed = await modal(
|
||||
scope === 'org' ? 'Tableau de l’organisation' : 'Nouveau tableau de dépôt',
|
||||
() => ({
|
||||
node: h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
repository && field('Dépôt', repository),
|
||||
field('Nom', name, { help: 'Laisse vide pour reprendre le nom du dépôt.' }),
|
||||
field('Description', description),
|
||||
h('p', {
|
||||
class: 'muted',
|
||||
text: 'Les colonnes À faire, En cours, En revue et Terminé sont créées automatiquement.',
|
||||
}),
|
||||
),
|
||||
submit: () => scope === 'org' || Boolean(repository?.value),
|
||||
}),
|
||||
{ confirmLabel: 'Créer', tone: 'primary' },
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
await api.post('/api/projects', {
|
||||
scope,
|
||||
repository: repository?.value,
|
||||
name: name.value.trim(),
|
||||
description: description.value.trim(),
|
||||
});
|
||||
toast('Tableau créé.');
|
||||
reload();
|
||||
}
|
||||
|
||||
// --- Board -------------------------------------------------------------------
|
||||
|
||||
function cardNode(entry, issues, board, reload) {
|
||||
const issue = entry.issueRef ? issues[entry.issueRef] : null;
|
||||
|
||||
const node = h(
|
||||
'article',
|
||||
{ class: 'kcard', draggable: 'true', dataset: { card: String(entry.id) } },
|
||||
h('h4', { text: entry.title }),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
entry.labels.map((label) => badge(label, 'neutral')),
|
||||
issue &&
|
||||
badge(
|
||||
`${entry.issueRef} · ${issue.state === 'open' ? 'ouverte' : 'fermée'}`,
|
||||
issue.state === 'open' ? 'success' : 'neutral',
|
||||
),
|
||||
!issue && entry.issueRef && badge(entry.issueRef, 'neutral'),
|
||||
entry.dueAt && badge(formatRelative(entry.dueAt), overdue(entry.dueAt) ? 'danger' : 'warning'),
|
||||
),
|
||||
entry.assigneeId && h('div', { class: 'muted', text: `Assignée à ${entry.assigneeId}` }),
|
||||
);
|
||||
|
||||
node.addEventListener('dragstart', (event) => {
|
||||
event.dataTransfer.setData('text/plain', String(entry.id));
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
node.classList.add('dragging');
|
||||
});
|
||||
node.addEventListener('dragend', () => node.classList.remove('dragging'));
|
||||
node.addEventListener('click', () => editCard(board, entry, reload));
|
||||
return node;
|
||||
}
|
||||
|
||||
function columnNode(column, issues, board, reload) {
|
||||
const count = column.cards.length;
|
||||
const over = column.wipLimit > 0 && count > column.wipLimit;
|
||||
|
||||
const list = h(
|
||||
'div',
|
||||
{ class: 'kcolumn-cards' },
|
||||
column.cards.map((entry) => cardNode(entry, issues, board, reload)),
|
||||
);
|
||||
|
||||
const node = h(
|
||||
'section',
|
||||
{ class: over ? 'kcolumn kcolumn-over' : 'kcolumn', dataset: { column: String(column.id) } },
|
||||
h(
|
||||
'header',
|
||||
{},
|
||||
h('strong', { text: column.name }),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'muted' },
|
||||
h('span', { text: column.wipLimit > 0 ? `${count} / ${column.wipLimit}` : String(count) }),
|
||||
),
|
||||
),
|
||||
list,
|
||||
button('+ Carte', () => editCard(board, { columnId: column.id }, reload), { tone: 'ghost' }),
|
||||
);
|
||||
|
||||
// Dropping anywhere on the column appends; the API renumbers the rest.
|
||||
node.addEventListener('dragover', (event) => {
|
||||
event.preventDefault();
|
||||
node.classList.add('kcolumn-target');
|
||||
});
|
||||
node.addEventListener('dragleave', () => node.classList.remove('kcolumn-target'));
|
||||
node.addEventListener('drop', async (event) => {
|
||||
event.preventDefault();
|
||||
node.classList.remove('kcolumn-target');
|
||||
|
||||
const cardId = event.dataTransfer.getData('text/plain');
|
||||
if (!cardId) return;
|
||||
|
||||
const result = await api.post(`/api/projects/${board.id}/cards/${cardId}/move`, {
|
||||
columnId: column.id,
|
||||
position: column.cards.length,
|
||||
});
|
||||
if (result.overloaded) toast(`« ${column.name} » dépasse sa limite de ${column.wipLimit}.`, 'info');
|
||||
reload();
|
||||
});
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
async function editCard(board, entry, reload) {
|
||||
const existing = Boolean(entry.id);
|
||||
const title = input({ value: entry.title ?? '', placeholder: 'Ce qu’il y a à faire' });
|
||||
const body = textarea({ value: entry.body ?? '', placeholder: 'Contexte, critères d’acceptation…' });
|
||||
const assignee = input({ value: entry.assigneeId ?? '', placeholder: 'Identifiant Discord (facultatif)' });
|
||||
const issueRef = input({ value: entry.issueRef ?? '', placeholder: 'FWS/FWS-Arch#12 (facultatif)' });
|
||||
const labels = input({ value: (entry.labels ?? []).join(', '), placeholder: 'bug, urgent' });
|
||||
const dueAt = input({ type: 'date', value: (entry.dueAt ?? '').slice(0, 10) });
|
||||
|
||||
const confirmed = await modal(
|
||||
existing ? 'Modifier la carte' : 'Nouvelle carte',
|
||||
() => ({
|
||||
node: h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
field('Titre', title),
|
||||
field('Description', body),
|
||||
field('Assignée à', assignee, { help: 'Identifiant Discord du membre qui la porte.' }),
|
||||
field('Issue liée', issueRef, {
|
||||
help: 'Format `organisation/depot#12`. Son état s’affiche sur la carte.',
|
||||
}),
|
||||
field('Étiquettes', labels, { help: 'Séparées par des virgules.' }),
|
||||
field('Échéance', dueAt),
|
||||
),
|
||||
submit: () => title.value.trim().length >= 2,
|
||||
}),
|
||||
{ confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' },
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
const payload = {
|
||||
title: title.value.trim(),
|
||||
body: body.value,
|
||||
assigneeId: assignee.value.trim(),
|
||||
issueRef: issueRef.value.trim(),
|
||||
labels: labels.value
|
||||
.split(',')
|
||||
.map((label) => label.trim())
|
||||
.filter(Boolean),
|
||||
dueAt: dueAt.value || '',
|
||||
};
|
||||
|
||||
try {
|
||||
if (existing) await api.patch(`/api/projects/${board.id}/cards/${entry.id}`, payload);
|
||||
else await api.post(`/api/projects/${board.id}/cards`, { ...payload, columnId: entry.columnId });
|
||||
toast(existing ? 'Carte enregistrée.' : 'Carte créée.');
|
||||
reload();
|
||||
} catch (error) {
|
||||
toast(error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function renderBoard(host, state, id) {
|
||||
const level = state.me.accessLevel;
|
||||
const reload = () => renderBoard(host, state, id);
|
||||
autoRefresh(reload, { topics: ['mutation'], minIntervalMs: 3000 });
|
||||
|
||||
mount(host, spinner());
|
||||
let board;
|
||||
try {
|
||||
board = await api.get(`/api/projects/${id}`);
|
||||
} catch (error) {
|
||||
mount(host, notice(error.message, 'error'));
|
||||
return;
|
||||
}
|
||||
|
||||
const total = board.columns.reduce((sum, column) => sum + column.cards.length, 0);
|
||||
const done = board.columns
|
||||
.filter((column) => column.isDone)
|
||||
.reduce((sum, column) => sum + column.cards.length, 0);
|
||||
|
||||
mount(
|
||||
host,
|
||||
h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'page-head' },
|
||||
h(
|
||||
'div',
|
||||
{},
|
||||
h('p', { class: 'muted' }, h('a', { href: '#/projects', text: '← Tous les tableaux' })),
|
||||
h('h1', { text: board.name }),
|
||||
h('p', {
|
||||
class: 'muted',
|
||||
text: board.description || (board.repository ?? 'Tableau de l’organisation'),
|
||||
}),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
badge(`${total} carte(s)`, 'neutral'),
|
||||
badge(`${done} terminée(s)`, done > 0 ? 'success' : 'neutral'),
|
||||
),
|
||||
),
|
||||
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('Colonne', () => addColumn(board, reload), { tone: 'ghost' }),
|
||||
level >= LEVELS.OWNER &&
|
||||
button(
|
||||
'Supprimer',
|
||||
async () => {
|
||||
if (
|
||||
!(await confirmDangerous(
|
||||
'Supprimer le tableau',
|
||||
`« ${board.name} » et toutes ses cartes seront perdus.`,
|
||||
board.name,
|
||||
))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await api.delete(`/api/projects/${board.id}`, { confirm: board.name });
|
||||
toast('Tableau supprimé.');
|
||||
window.location.hash = '#/projects';
|
||||
},
|
||||
{ tone: 'danger' },
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
h(
|
||||
'div',
|
||||
{ class: 'kboard' },
|
||||
board.columns.map((column) => columnNode(column, board.issues ?? {}, board, reload)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function addColumn(board, reload) {
|
||||
const name = input({ placeholder: 'Nom de la colonne' });
|
||||
const wipLimit = input({ type: 'number', value: 0, min: 0 });
|
||||
let isDone = false;
|
||||
|
||||
const confirmed = await modal(
|
||||
'Nouvelle colonne',
|
||||
() => ({
|
||||
node: h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
field('Nom', name),
|
||||
field('Limite de cartes', wipLimit, { help: '0 = pas de limite. Au-delà, la colonne est signalée.' }),
|
||||
toggle(false, (checked) => (isDone = checked), 'Les cartes déposées ici sont terminées'),
|
||||
),
|
||||
submit: () => name.value.trim() !== '',
|
||||
}),
|
||||
{ confirmLabel: 'Ajouter', tone: 'primary' },
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
await api.post(`/api/projects/${board.id}/columns`, {
|
||||
name: name.value.trim(),
|
||||
wipLimit: Number(wipLimit.value) || 0,
|
||||
isDone,
|
||||
});
|
||||
toast('Colonne ajoutée.');
|
||||
reload();
|
||||
}
|
||||
|
||||
export function render(host, { params, state }) {
|
||||
if (params.length >= 1) return renderBoard(host, state, params[0]);
|
||||
return renderList(host, state);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import { activePath, highlight } from '../src/web/public/core/nav.js';
|
||||
|
||||
/**
|
||||
* Sidebar highlighting (M16-T11).
|
||||
*
|
||||
* Tested against a tiny stand-in for the DOM, because getting it wrong leaves
|
||||
* the sidebar pointing at a page you are not on — a bug that looks like
|
||||
* nothing and has been reported more than once.
|
||||
*/
|
||||
|
||||
/** Just enough element to satisfy `highlight`: classes, dataset, attributes. */
|
||||
function link(route) {
|
||||
const classes = new Set();
|
||||
const attributes = {};
|
||||
return {
|
||||
dataset: { route },
|
||||
attributes,
|
||||
classList: {
|
||||
toggle: (name, on) => (on ? classes.add(name) : classes.delete(name)),
|
||||
contains: (name) => classes.has(name),
|
||||
},
|
||||
setAttribute: (name, value) => (attributes[name] = value),
|
||||
removeAttribute: (name) => delete attributes[name],
|
||||
get active() {
|
||||
return classes.has('active');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const sidebar = (...routes) => {
|
||||
const links = routes.map(link);
|
||||
return { links, querySelectorAll: () => links };
|
||||
};
|
||||
|
||||
const activeNames = (bar) => bar.links.filter((entry) => entry.active).map((entry) => entry.dataset.route);
|
||||
|
||||
describe('active route', () => {
|
||||
it('reads the first segment of a hash route', () => {
|
||||
assert.equal(activePath('#/repos'), 'repos');
|
||||
assert.equal(activePath('#/settings'), 'settings');
|
||||
});
|
||||
|
||||
it('treats a detail page as its section', () => {
|
||||
assert.equal(activePath('#/repos/FWS/FWS-Arch'), 'repos');
|
||||
});
|
||||
|
||||
it('ignores a query string', () => {
|
||||
assert.equal(activePath('#/releases?repo=FWS/Arch'), 'releases');
|
||||
});
|
||||
|
||||
it('maps every spelling of the home page to the same entry', () => {
|
||||
for (const hash of ['', '#', '#/', '#//']) {
|
||||
assert.equal(activePath(hash), '', `« ${hash} » should be the home page`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('sidebar highlighting', () => {
|
||||
it('marks the current entry and only it', () => {
|
||||
const bar = sidebar('', 'repos', 'settings');
|
||||
highlight(bar, '#/repos');
|
||||
assert.deepEqual(activeNames(bar), ['repos']);
|
||||
});
|
||||
|
||||
it('marks the home entry on the home page', () => {
|
||||
const bar = sidebar('', 'repos');
|
||||
highlight(bar, '#/');
|
||||
assert.deepEqual(activeNames(bar), ['']);
|
||||
});
|
||||
|
||||
/** The regression that started all this: home stayed lit on every page. */
|
||||
it('clears the home entry once elsewhere', () => {
|
||||
const bar = sidebar('', 'repos');
|
||||
highlight(bar, '#/');
|
||||
highlight(bar, '#/repos');
|
||||
assert.deepEqual(activeNames(bar), ['repos']);
|
||||
});
|
||||
|
||||
it('keeps the section lit on a detail page', () => {
|
||||
const bar = sidebar('', 'repos', 'releases');
|
||||
highlight(bar, '#/repos/FWS/FWS-Arch');
|
||||
assert.deepEqual(activeNames(bar), ['repos']);
|
||||
});
|
||||
|
||||
it('keeps the section lit despite a query string', () => {
|
||||
const bar = sidebar('', 'releases', 'deploy');
|
||||
highlight(bar, '#/releases?repo=FWS/Arch');
|
||||
assert.deepEqual(activeNames(bar), ['releases']);
|
||||
});
|
||||
|
||||
it('lights nothing on an unknown route', () => {
|
||||
const bar = sidebar('', 'repos');
|
||||
highlight(bar, '#/inexistant');
|
||||
assert.deepEqual(activeNames(bar), []);
|
||||
});
|
||||
|
||||
it('announces the current entry to screen readers', () => {
|
||||
const bar = sidebar('', 'repos');
|
||||
highlight(bar, '#/repos');
|
||||
|
||||
const [home, repos] = bar.links;
|
||||
assert.equal(repos.attributes['aria-current'], 'page');
|
||||
assert.equal(home.attributes['aria-current'], undefined);
|
||||
});
|
||||
|
||||
it('survives a link that carries no route', () => {
|
||||
const bar = { links: [], querySelectorAll: () => [{ ...link(undefined) }] };
|
||||
assert.doesNotThrow(() => highlight(bar, '#/repos'));
|
||||
});
|
||||
});
|
||||
@@ -95,6 +95,13 @@ describe('dashboard server', () => {
|
||||
assert.match(response.headers.get('content-type'), /javascript/);
|
||||
});
|
||||
|
||||
it('never lets a module be cached, so versions cannot drift apart', async () => {
|
||||
for (const path of ['/app.js', '/core/ui.js', '/views/settings.js', '/styles.css']) {
|
||||
const response = await app.fetch(path);
|
||||
assert.equal(response.headers.get('cache-control'), 'no-store', `${path} peut être mis en cache`);
|
||||
}
|
||||
});
|
||||
|
||||
it('gives its assets a validator so a cache can revalidate', async () => {
|
||||
const response = await app.fetch('/core/dom.js');
|
||||
assert.ok(response.headers.get('etag'), 'no ETag on a static asset');
|
||||
|
||||
Reference in new issue
Block a user