diff --git a/eslint.config.js b/eslint.config.js
index 04fcf2c..a331612 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -17,5 +17,10 @@ export default [
eqeqeq: ['error', 'always'],
},
},
+ {
+ // The dashboard front-end runs in the browser, not in Node (M16-T11).
+ files: ['src/web/public/**/*.js'],
+ languageOptions: { globals: globals.browser },
+ },
prettier,
];
diff --git a/package.json b/package.json
index 5c5eaa1..2219944 100644
--- a/package.json
+++ b/package.json
@@ -11,6 +11,7 @@
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
+ "setup": "node scripts/setup-server.js",
"deploy:commands": "node scripts/deploy-commands.js",
"db:init": "node scripts/init-database.js",
"changelog": "node scripts/generate-changelog.js",
diff --git a/scripts/setup-server.js b/scripts/setup-server.js
new file mode 100644
index 0000000..d3efa57
--- /dev/null
+++ b/scripts/setup-server.js
@@ -0,0 +1,47 @@
+#!/usr/bin/env node
+import { env } from '../src/config/env.js';
+import { logger } from '../src/core/logger.js';
+import { initDatabase } from '../src/database/index.js';
+import { startWebServer } from '../src/web/server.js';
+import { generateRuntimeSetupToken, hasSetupToken } from '../src/web/setup-state.js';
+
+/**
+ * Starts the configuration wizard alone, without connecting to Discord (M16-T09).
+ *
+ * This is the entry point for a fresh clone: the bot itself refuses to start
+ * without `DISCORD_TOKEN`, so the `.env` has to be writable from somewhere else.
+ *
+ * Usage: npm run setup
+ */
+
+// The wizard stores its session in SQLite, so the database must exist.
+initDatabase();
+
+const token = env.web.setupToken || generateRuntimeSetupToken();
+const url =
+ env.web.publicUrl || `http://${env.web.host === '0.0.0.0' ? 'localhost' : env.web.host}:${env.web.port}`;
+
+const server = startWebServer({ client: null, setupOnly: true });
+
+logger.info('Configuration wizard started');
+console.log(`
+┌──────────────────────────────────────────────────────────────────────┐
+│ Assistant de configuration FWS-Bot │
+└──────────────────────────────────────────────────────────────────────┘
+
+ Ouvre ${url}/#/setup
+ Jeton ${token}
+ ${env.web.setupToken ? 'Ce jeton vient de WEB_SETUP_TOKEN.' : 'Ce jeton est temporaire : il change à chaque lancement.'}
+
+ Une fois le .env enregistré : Ctrl+C, puis npm run db:init,
+ npm run deploy:commands et npm run dev.
+`);
+
+if (!hasSetupToken()) logger.warn('No setup token available, the wizard cannot be opened');
+
+const shutdown = () => {
+ server.close();
+ process.exit(0);
+};
+process.once('SIGINT', shutdown);
+process.once('SIGTERM', shutdown);
diff --git a/src/index.js b/src/index.js
index 548fbf2..0a2f1f8 100644
--- a/src/index.js
+++ b/src/index.js
@@ -4,9 +4,15 @@ import { loadCommands } from './core/command-loader.js';
import { registerEvents } from './core/event-loader.js';
import { logger } from './core/logger.js';
import { closeDatabase, initDatabase } from './database/index.js';
+import { startWebServer, webhookSharesWebPort } from './web/server.js';
import { startWebhookServer } from './webhooks/server.js';
-assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
+try {
+ assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
+} catch (error) {
+ logger.error(`${error.message}. Lance \`npm run setup\` pour remplir le .env pas à pas.`);
+ throw error;
+}
initDatabase();
@@ -17,7 +23,9 @@ for (const command of await loadCommands()) {
}
await registerEvents(client);
-const webhookServer = env.webhook.enabled ? startWebhookServer(client) : null;
+// When both listen on the same port, the dashboard serves the webhook route too.
+const webServer = env.web.enabled ? startWebServer({ client }) : null;
+const webhookServer = env.webhook.enabled && !webhookSharesWebPort() ? startWebhookServer(client) : null;
process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason));
process.on('uncaughtException', (error) => logger.error('Uncaught exception', error));
@@ -25,6 +33,7 @@ process.on('uncaughtException', (error) => logger.error('Uncaught exception', er
async function shutdown(signal) {
logger.info(`Received ${signal}, shutting down`);
webhookServer?.close();
+ webServer?.close();
await client.destroy();
closeDatabase();
process.exit(0);
diff --git a/src/web/public/app.js b/src/web/public/app.js
new file mode 100644
index 0000000..41b81bc
--- /dev/null
+++ b/src/web/public/app.js
@@ -0,0 +1,301 @@
+import { api } from './core/api.js';
+import { h, mount, qs } from './core/dom.js';
+import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js';
+
+/** Shell, navigation and hash routing of the dashboard (M16-T11). */
+
+const LEVELS = { USER: 0, STAFF: 1, DEV: 2, OWNER: 3 };
+
+/**
+ * `module` is imported on demand, so a view is only downloaded when visited.
+ * `level` hides a page the visitor could not use anyway; the server enforces it too.
+ */
+const ROUTES = [
+ {
+ path: '',
+ icon: '◎',
+ label: 'Vue d’ensemble',
+ group: 'Pilotage',
+ module: './views/overview.js',
+ level: LEVELS.STAFF,
+ },
+ {
+ path: 'org',
+ icon: '⬡',
+ label: 'Organisation',
+ group: 'Pilotage',
+ module: './views/organization.js',
+ level: LEVELS.STAFF,
+ },
+ {
+ path: 'repos',
+ icon: '◫',
+ label: 'Dépôts',
+ group: 'Code',
+ module: './views/repositories.js',
+ level: LEVELS.STAFF,
+ },
+ {
+ path: 'releases',
+ icon: '⬀',
+ label: 'Releases',
+ group: 'Code',
+ module: './views/releases.js',
+ level: LEVELS.STAFF,
+ },
+ {
+ path: 'deploy',
+ icon: '⚙',
+ label: 'Déploiements',
+ group: 'Code',
+ module: './views/deployments.js',
+ level: LEVELS.STAFF,
+ },
+ {
+ path: 'discord',
+ icon: '☰',
+ label: 'Serveur Discord',
+ group: 'Communauté',
+ module: './views/discord.js',
+ level: LEVELS.STAFF,
+ },
+ {
+ path: 'community',
+ icon: '✦',
+ label: 'Tickets & vocaux',
+ group: 'Communauté',
+ module: './views/community.js',
+ level: LEVELS.STAFF,
+ },
+ {
+ path: 'logs',
+ icon: '≡',
+ label: 'Journaux',
+ group: 'Système',
+ module: './views/logs.js',
+ level: LEVELS.STAFF,
+ advanced: true,
+ },
+ {
+ path: 'settings',
+ icon: '⚒',
+ label: 'Paramètres',
+ group: 'Système',
+ module: './views/settings.js',
+ level: LEVELS.STAFF,
+ },
+ {
+ path: 'setup',
+ icon: '✎',
+ label: 'Configuration .env',
+ group: 'Système',
+ module: './views/setup.js',
+ level: LEVELS.OWNER,
+ },
+];
+
+export const state = {
+ me: null,
+ config: null,
+ mode: localStorage.getItem('fws.mode') ?? 'simple',
+ theme: localStorage.getItem('fws.theme') ?? 'dark',
+ /** Repository selected in the Releases and Deployments pages. */
+ repository: localStorage.getItem('fws.repository') ?? '',
+};
+
+export function setMode(mode) {
+ state.mode = mode;
+ localStorage.setItem('fws.mode', mode);
+ document.body.dataset.mode = mode;
+ render();
+}
+
+export function setTheme(theme) {
+ state.theme = theme;
+ localStorage.setItem('fws.theme', theme);
+ document.documentElement.dataset.theme = theme;
+}
+
+export function setRepository(fullName) {
+ state.repository = fullName;
+ localStorage.setItem('fws.repository', fullName);
+}
+
+export const navigate = (path) => {
+ window.location.hash = `#/${path}`;
+};
+
+const currentRoute = () => {
+ const raw = window.location.hash.replace(/^#\/?/, '');
+ const [path] = raw.split('?');
+ const segments = path.split('/').filter(Boolean);
+ return { segments, path };
+};
+
+function sidebar() {
+ const { segments } = currentRoute();
+ const active = segments[0] ?? '';
+ const visible = ROUTES.filter(
+ (route) => state.me.accessLevel >= route.level && (!route.advanced || state.mode === 'advanced'),
+ );
+
+ const groups = [];
+ for (const route of visible) {
+ let group = groups.find((entry) => entry.name === route.group);
+ if (!group) groups.push((group = { name: route.group, routes: [] }));
+ group.routes.push(route);
+ }
+
+ return h(
+ 'aside',
+ { class: 'sidebar' },
+ h(
+ 'a',
+ { class: 'brand', href: '#/' },
+ h('img', { src: 'favicon.svg', alt: '' }),
+ h('div', {}, h('strong', { text: 'FWS-Bot' }), h('span', { text: 'Tableau de bord' })),
+ ),
+ h(
+ 'nav',
+ { class: 'nav' },
+ groups.map((group) => [
+ h('div', { class: 'nav-group', text: group.name }),
+ group.routes.map((route) =>
+ h(
+ 'a',
+ { href: `#/${route.path}`, class: route.path === active ? 'active' : '' },
+ h('span', { class: 'nav-icon', text: route.icon }),
+ h('span', { text: route.label }),
+ ),
+ ),
+ ]),
+ ),
+ h(
+ 'div',
+ { class: 'sidebar-foot' },
+ h(
+ 'div',
+ { class: 'mode-switch', role: 'group', 'aria-label': 'Mode d’affichage' },
+ button('Simple', () => setMode('simple'), {}),
+ button('Avancé', () => setMode('advanced'), {}),
+ ),
+ h(
+ 'div',
+ { class: 'viewer' },
+ state.me.avatar && h('img', { src: state.me.avatar, alt: '' }),
+ h(
+ 'div',
+ {},
+ h('strong', { text: state.me.displayName ?? state.me.username ?? 'Invité' }),
+ h('span', { class: 'muted', text: ACCESS_LABELS[state.me.accessLevel] ?? '—' }),
+ ),
+ ),
+ h(
+ 'div',
+ { class: 'row' },
+ button(
+ state.theme === 'dark' ? '☀ Clair' : '☾ Sombre',
+ () => {
+ setTheme(state.theme === 'dark' ? 'light' : 'dark');
+ render();
+ },
+ { tone: 'ghost' },
+ ),
+ button(
+ 'Déconnexion',
+ async () => {
+ await api.post('/api/auth/logout');
+ window.location.reload();
+ },
+ { tone: 'ghost' },
+ ),
+ ),
+ ),
+ );
+}
+
+function applyModeButtons(node) {
+ for (const control of node.querySelectorAll('.mode-switch button')) {
+ control.classList.toggle(
+ 'active',
+ control.textContent === (state.mode === 'simple' ? 'Simple' : 'Avancé'),
+ );
+ }
+}
+
+async function renderView(host) {
+ const { segments } = currentRoute();
+ const route = ROUTES.find((entry) => entry.path === (segments[0] ?? ''));
+
+ if (!route) {
+ mount(host, h('div', { class: 'notice notice-warning' }, h('p', { text: 'Page inconnue.' })));
+ return;
+ }
+ if (state.me.accessLevel < route.level) {
+ mount(
+ host,
+ h(
+ 'div',
+ { class: 'notice notice-error' },
+ h('p', { text: 'Cette page demande un niveau d’accès supérieur.' }),
+ ),
+ );
+ return;
+ }
+
+ mount(host, spinner());
+ try {
+ const module = await import(route.module);
+ await module.render(host, { params: segments.slice(1), state });
+ } catch (error) {
+ mount(host, h('div', { class: 'notice notice-error' }, h('p', { text: error.message })));
+ }
+}
+
+export function render() {
+ const app = qs('#app');
+
+ if (!state.me?.authenticated) {
+ import('./views/login.js').then((module) => module.render(app, { state }));
+ return;
+ }
+
+ // The bootstrap session may only reach the wizard, so it never gets a shell.
+ if (state.me.source === 'setup') {
+ import('./views/setup.js').then((module) => module.render(app, { state, standalone: true }));
+ return;
+ }
+
+ const main = h('main', { class: 'main' });
+ const shell = h('div', { class: 'shell' }, sidebar(), main);
+ mount(app, shell);
+ applyModeButtons(shell);
+ renderView(main);
+}
+
+async function boot() {
+ document.body.dataset.mode = state.mode;
+ document.documentElement.dataset.theme = state.theme;
+
+ const [me, config] = await Promise.all([
+ api.get('/api/me').catch(() => ({ authenticated: false })),
+ api.get('/api/auth/config').catch(() => ({})),
+ ]);
+ state.me = me;
+ state.config = config;
+
+ window.addEventListener('hashchange', () => {
+ if (state.me?.authenticated && state.me.source !== 'setup') renderView(qs('.main'));
+ else render();
+ });
+ window.addEventListener('unhandledrejection', (event) => {
+ if (event.reason?.status === 401) {
+ state.me = { authenticated: false };
+ render();
+ } else if (event.reason instanceof Error) toast(event.reason.message, 'error');
+ });
+
+ render();
+}
+
+boot();
diff --git a/src/web/public/core/api.js b/src/web/public/core/api.js
new file mode 100644
index 0000000..481bce0
--- /dev/null
+++ b/src/web/public/core/api.js
@@ -0,0 +1,51 @@
+/** Typed-ish client for the dashboard API (M16-T11). */
+
+export class ApiError extends Error {
+ constructor(status, message, details) {
+ super(message);
+ this.name = 'ApiError';
+ this.status = status;
+ this.details = details;
+ }
+}
+
+async function request(method, path, body) {
+ const response = await fetch(path, {
+ method,
+ headers: {
+ Accept: 'application/json',
+ ...(body !== undefined && { 'Content-Type': 'application/json' }),
+ // Required by the server for every write: a cross-site form cannot set it.
+ 'X-Requested-With': 'fws-dashboard',
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ credentials: 'same-origin',
+ });
+
+ const payload = await response.json().catch(() => null);
+ if (!response.ok) {
+ throw new ApiError(response.status, payload?.error ?? `Erreur ${response.status}`, payload?.details);
+ }
+ return payload;
+}
+
+const withQuery = (path, params) => {
+ const search = new URLSearchParams(
+ Object.entries(params ?? {}).filter(([, value]) => value !== undefined && value !== null && value !== ''),
+ ).toString();
+ return search ? `${path}?${search}` : path;
+};
+
+export const api = {
+ get: (path, params) => request('GET', withQuery(path, params)),
+ post: (path, body = {}) => request('POST', path, body),
+ put: (path, body = {}) => request('PUT', path, body),
+ patch: (path, body = {}) => request('PATCH', path, body),
+ delete: (path, body = {}) => request('DELETE', path, body),
+};
+
+export const encodeRepo = (fullName) =>
+ String(fullName)
+ .split('/')
+ .map((part) => encodeURIComponent(part))
+ .join('/');
diff --git a/src/web/public/core/dom.js b/src/web/public/core/dom.js
new file mode 100644
index 0000000..6da3287
--- /dev/null
+++ b/src/web/public/core/dom.js
@@ -0,0 +1,122 @@
+/**
+ * Minimal DOM helpers. No framework, no build step: the dashboard ships the
+ * files it serves (M16-T11).
+ */
+
+/**
+ * `h('div', { class: 'card' }, h('h2', { text: 'Titre' }))`
+ * Text always goes through `textContent`, so API values can never inject markup.
+ */
+export function h(tag, props = {}, ...children) {
+ const node = document.createElement(tag);
+
+ for (const [key, value] of Object.entries(props ?? {})) {
+ if (value === null || value === undefined || value === false) continue;
+
+ if (key === 'text') node.textContent = String(value);
+ else if (key === 'class') node.className = value;
+ else if (key === 'dataset') Object.assign(node.dataset, value);
+ else if (key === 'style') Object.assign(node.style, value);
+ else if (key.startsWith('on') && typeof value === 'function') {
+ node.addEventListener(key.slice(2).toLowerCase(), value);
+ } else if (key === 'value' || key === 'checked' || key === 'disabled' || key === 'selected') {
+ node[key] = value;
+ } else node.setAttribute(key, value === true ? '' : String(value));
+ }
+
+ for (const child of children.flat(Infinity)) {
+ if (child === null || child === undefined || child === false) continue;
+ node.append(child instanceof Node ? child : document.createTextNode(String(child)));
+ }
+ return node;
+}
+
+export const clear = (node) => {
+ while (node.firstChild) node.firstChild.remove();
+ return node;
+};
+
+export const mount = (node, ...children) => {
+ clear(node);
+ node.append(...children.flat(Infinity).filter(Boolean));
+ return node;
+};
+
+export const qs = (selector, scope = document) => scope.querySelector(selector);
+
+/** Escapes then applies the small subset of Markdown used by Gitea bodies. */
+export function markdown(text) {
+ const escaped = String(text ?? '')
+ .replaceAll('&', '&')
+ .replaceAll('<', '<')
+ .replaceAll('>', '>');
+
+ return escaped
+ .replace(/```([\s\S]*?)```/g, (_, code) => `
${code.trim()}
`)
+ .replace(/`([^`\n]+)`/g, '$1')
+ .replace(/^### (.+)$/gm, '$1
')
+ .replace(/^## (.+)$/gm, '$1
')
+ .replace(/^# (.+)$/gm, '$1
')
+ .replace(/\*\*([^*\n]+)\*\*/g, '$1')
+ .replace(/^[-*] (.+)$/gm, '$1')
+ .replace(/([\s\S]*?<\/li>)/g, '')
+ .replace(/\n{2,}/g, '
');
+}
+
+/** Renders trusted Markdown built above; never call it with raw HTML. */
+export function richText(text, className = 'rich') {
+ const node = h('div', { class: className });
+ node.innerHTML = markdown(text);
+ return node;
+}
+
+export const formatDate = (value) => {
+ if (!value) return '—';
+ const date = new Date(String(value).includes('T') ? value : `${value}Z`);
+ if (Number.isNaN(date.getTime())) return String(value);
+ return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' });
+};
+
+export function formatRelative(value) {
+ if (!value) return '—';
+ const date = new Date(String(value).includes('T') ? value : `${value}Z`);
+ if (Number.isNaN(date.getTime())) return String(value);
+
+ const seconds = Math.round((date.getTime() - Date.now()) / 1000);
+ const units = [
+ ['year', 31_536_000],
+ ['month', 2_592_000],
+ ['day', 86_400],
+ ['hour', 3600],
+ ['minute', 60],
+ ];
+ const formatter = new Intl.RelativeTimeFormat('fr', { numeric: 'auto' });
+
+ for (const [unit, size] of units) {
+ if (Math.abs(seconds) >= size) return formatter.format(Math.round(seconds / size), unit);
+ }
+ return formatter.format(seconds, 'second');
+}
+
+export const formatBytes = (bytes) => {
+ const value = Number(bytes) || 0;
+ const units = ['o', 'Ko', 'Mo', 'Go'];
+ let index = 0;
+ let result = value;
+ while (result >= 1024 && index < units.length - 1) {
+ result /= 1024;
+ index += 1;
+ }
+ return `${result.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
+};
+
+export const formatDuration = (ms) => {
+ const seconds = Math.floor(Number(ms) / 1000);
+ const days = Math.floor(seconds / 86_400);
+ const hours = Math.floor((seconds % 86_400) / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+ if (days > 0) return `${days} j ${hours} h`;
+ if (hours > 0) return `${hours} h ${minutes} min`;
+ if (minutes > 0) return `${minutes} min`;
+ return `${seconds} s`;
+};
diff --git a/src/web/public/core/ui.js b/src/web/public/core/ui.js
new file mode 100644
index 0000000..b3fec71
--- /dev/null
+++ b/src/web/public/core/ui.js
@@ -0,0 +1,227 @@
+import { clear, h, mount } from './dom.js';
+
+/** Shared widgets: cards, tables, badges, toasts, modals (M16-T11). */
+
+export const ACCESS_LABELS = { 0: 'Membre', 1: 'Staff', 2: 'Dev', 3: 'Owner' };
+
+export function card(title, { subtitle, actions, advanced = false } = {}, ...children) {
+ return h(
+ 'section',
+ { class: advanced ? 'card advanced-only' : 'card' },
+ (title || actions) &&
+ h(
+ 'header',
+ { class: 'card-head' },
+ h(
+ 'div',
+ {},
+ title && h('h2', { text: title }),
+ subtitle && h('p', { class: 'muted', text: subtitle }),
+ ),
+ actions && h('div', { class: 'card-actions' }, actions),
+ ),
+ h('div', { class: 'card-body' }, ...children),
+ );
+}
+
+export const stat = (label, value, { hint, tone = 'neutral' } = {}) =>
+ h(
+ 'div',
+ { class: `stat stat-${tone}` },
+ h('span', { class: 'stat-label', text: label }),
+ h('strong', { class: 'stat-value', text: value ?? '—' }),
+ hint && h('span', { class: 'stat-hint', text: hint }),
+ );
+
+export const badge = (text, tone = 'neutral') => h('span', { class: `badge badge-${tone}`, text });
+
+export const button = (label, onClick, { tone = 'ghost', disabled = false, title, type = 'button' } = {}) =>
+ h('button', { class: `btn btn-${tone}`, onClick, disabled, title, type, text: label });
+
+export function field(label, control, { help, error } = {}) {
+ return h(
+ 'label',
+ { class: error ? 'field field-error' : 'field' },
+ h('span', { class: 'field-label', text: label }),
+ control,
+ help && h('span', { class: 'field-help', text: help }),
+ error && h('span', { class: 'field-error-text', text: error }),
+ );
+}
+
+export const input = (props = {}) => h('input', { class: 'input', ...props });
+export const textarea = (props = {}) => h('textarea', { class: 'input textarea', ...props });
+
+export function select(options, props = {}) {
+ return h(
+ 'select',
+ { class: 'input', ...props },
+ options.map((option) =>
+ h('option', {
+ value: option.value,
+ text: option.label,
+ selected: option.value === props.value,
+ }),
+ ),
+ );
+}
+
+export function toggle(checked, onChange, label) {
+ return h(
+ 'label',
+ { class: 'toggle' },
+ h('input', { type: 'checkbox', checked, onChange: (event) => onChange(event.target.checked) }),
+ h('span', { class: 'toggle-track' }),
+ label && h('span', { text: label }),
+ );
+}
+
+/**
+ * Renders a table. Each column is `{ key, label, render?, className? }`;
+ * `render` returns a Node or a string.
+ */
+export function table(columns, rows, { empty = 'Rien à afficher pour le moment.' } = {}) {
+ if (!rows || rows.length === 0) return h('p', { class: 'empty', text: empty });
+
+ return h(
+ 'div',
+ { class: 'table-wrap' },
+ h(
+ 'table',
+ { class: 'table' },
+ h(
+ 'thead',
+ {},
+ h(
+ 'tr',
+ {},
+ columns.map((column) => h('th', { class: column.className ?? '', text: column.label })),
+ ),
+ ),
+ h(
+ 'tbody',
+ {},
+ rows.map((row) =>
+ h(
+ 'tr',
+ {},
+ columns.map((column) => {
+ const cell = h('td', { class: column.className ?? '' });
+ const value = column.render ? column.render(row) : row[column.key];
+ if (value instanceof Node) cell.append(value);
+ else cell.textContent = value === null || value === undefined ? '—' : String(value);
+ return cell;
+ }),
+ ),
+ ),
+ ),
+ ),
+ );
+}
+
+export const spinner = (label = 'Chargement…') =>
+ h('div', { class: 'loading' }, h('span', { class: 'spinner' }), h('span', { text: label }));
+
+export const errorBox = (message, { retry } = {}) =>
+ h(
+ 'div',
+ { class: 'notice notice-error' },
+ h('p', { text: message }),
+ retry && button('Réessayer', retry, { tone: 'ghost' }),
+ );
+
+export const notice = (message, tone = 'info') =>
+ h('div', { class: `notice notice-${tone}` }, h('p', { text: message }));
+
+let toastHost;
+
+export function toast(message, tone = 'success') {
+ toastHost ??= document.body.appendChild(h('div', { class: 'toast-host' }));
+ const node = h('div', { class: `toast toast-${tone}`, text: message });
+ toastHost.append(node);
+ setTimeout(() => node.classList.add('toast-out'), 3600);
+ setTimeout(() => node.remove(), 4200);
+}
+
+/** Promise-based modal. Resolves with the value passed to `close`. */
+export function modal(title, buildBody, { confirmLabel = 'Confirmer', tone = 'primary' } = {}) {
+ return new Promise((resolve) => {
+ const overlay = h('div', { class: 'overlay' });
+ const close = (value) => {
+ overlay.remove();
+ document.removeEventListener('keydown', onKey);
+ resolve(value);
+ };
+ const onKey = (event) => {
+ if (event.key === 'Escape') close(null);
+ };
+
+ const body = buildBody(close);
+ const footer = h(
+ 'footer',
+ { class: 'modal-foot' },
+ button('Annuler', () => close(null), { tone: 'ghost' }),
+ button(confirmLabel, () => close(body.submit ? body.submit() : true), { tone }),
+ );
+
+ overlay.append(
+ h(
+ 'div',
+ { class: 'modal' },
+ h('header', { class: 'modal-head' }, h('h2', { text: title })),
+ h('div', { class: 'modal-body' }, body.node ?? body),
+ footer,
+ ),
+ );
+ overlay.addEventListener('click', (event) => {
+ if (event.target === overlay) close(null);
+ });
+ document.addEventListener('keydown', onKey);
+ document.body.append(overlay);
+
+ const firstInput = overlay.querySelector('input, textarea, select');
+ firstInput?.focus();
+ });
+}
+
+/** Confirmation that requires typing an exact phrase, for irreversible actions. */
+export function confirmDangerous(title, message, phrase) {
+ return modal(
+ title,
+ () => {
+ const control = input({ placeholder: phrase, autocomplete: 'off' });
+ const node = h(
+ 'div',
+ {},
+ h('p', { text: message }),
+ h('p', { class: 'muted', text: `Tape « ${phrase} » pour confirmer.` }),
+ control,
+ );
+ return { node, submit: () => control.value.trim() === phrase };
+ },
+ { confirmLabel: 'Supprimer', tone: 'danger' },
+ );
+}
+
+export const confirmAction = (title, message) =>
+ modal(title, () => ({ node: h('p', { text: message }), submit: () => true }));
+
+/**
+ * Renders an async view into a host node, showing a loader then the result.
+ * Any thrown error becomes a retry box instead of a blank page.
+ */
+export async function renderAsync(host, load, build) {
+ mount(host, spinner());
+ try {
+ const data = await load();
+ mount(host, await build(data));
+ } catch (error) {
+ mount(host, errorBox(error.message, { retry: () => renderAsync(host, load, build) }));
+ }
+ return host;
+}
+
+export const section = (...children) => h('div', { class: 'stack' }, ...children);
+export const row = (...children) => h('div', { class: 'row' }, ...children);
+export const grid = (...children) => h('div', { class: 'grid' }, ...children);
+export { clear, mount };
diff --git a/src/web/public/favicon.svg b/src/web/public/favicon.svg
new file mode 100644
index 0000000..928aab8
--- /dev/null
+++ b/src/web/public/favicon.svg
@@ -0,0 +1,5 @@
+
diff --git a/src/web/public/index.html b/src/web/public/index.html
new file mode 100644
index 0000000..e98b2dc
--- /dev/null
+++ b/src/web/public/index.html
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+ FWS-Bot — Tableau de bord
+
+
+
+
+
+
+
+
+
+
diff --git a/src/web/public/styles.css b/src/web/public/styles.css
new file mode 100644
index 0000000..f75ba4b
--- /dev/null
+++ b/src/web/public/styles.css
@@ -0,0 +1,934 @@
+/* FWS-Bot dashboard — Arch blue on a calm dark surface (M16-T11). */
+
+:root {
+ --blue: #1793d1;
+ --blue-soft: #8fd3ff;
+ --green: #2ecc71;
+ --amber: #f1c40f;
+ --red: #e74c3c;
+ --violet: #9b59b6;
+ --gitea: #609926;
+
+ --bg: #0b1016;
+ --bg-elevated: #121a24;
+ --bg-sunken: #080d12;
+ --surface: #16202c;
+ --border: #23303f;
+ --text: #e6edf3;
+ --text-muted: #8da2b6;
+ --shadow: 0 10px 30px rgb(0 0 0 / 35%);
+
+ --radius: 12px;
+ --radius-sm: 8px;
+ --sidebar: 250px;
+ --font: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
+ --mono: ui-monospace, 'JetBrains Mono', 'Fira Code', Menlo, Consolas, monospace;
+}
+
+[data-theme='light'] {
+ --bg: #f4f7fa;
+ --bg-elevated: #ffffff;
+ --bg-sunken: #e8eef5;
+ --surface: #ffffff;
+ --border: #d5e0ea;
+ --text: #14212e;
+ --text-muted: #5b6e80;
+ --shadow: 0 8px 24px rgb(20 33 46 / 10%);
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body {
+ margin: 0;
+ height: 100%;
+}
+
+body {
+ background: var(--bg);
+ color: var(--text);
+ font-family: var(--font);
+ font-size: 15px;
+ line-height: 1.55;
+ -webkit-font-smoothing: antialiased;
+}
+
+a {
+ color: var(--blue-soft);
+ text-decoration: none;
+}
+a:hover {
+ text-decoration: underline;
+}
+
+h1,
+h2,
+h3,
+h4 {
+ margin: 0;
+ line-height: 1.25;
+ font-weight: 650;
+}
+h1 {
+ font-size: 1.5rem;
+}
+h2 {
+ font-size: 1.05rem;
+}
+h3 {
+ font-size: 0.95rem;
+}
+
+p {
+ margin: 0 0 0.6rem;
+}
+p:last-child {
+ margin-bottom: 0;
+}
+
+code,
+pre {
+ font-family: var(--mono);
+ font-size: 0.85em;
+}
+code {
+ background: var(--bg-sunken);
+ border-radius: 4px;
+ padding: 0.1em 0.35em;
+}
+pre {
+ background: var(--bg-sunken);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ padding: 0.8rem;
+ overflow: auto;
+ max-height: 400px;
+}
+pre code {
+ background: none;
+ padding: 0;
+}
+
+.muted {
+ color: var(--text-muted);
+ font-size: 0.88rem;
+}
+
+/* --- Layout ------------------------------------------------------------- */
+
+.app {
+ min-height: 100%;
+}
+
+.shell {
+ display: grid;
+ grid-template-columns: var(--sidebar) 1fr;
+ min-height: 100vh;
+}
+
+.sidebar {
+ background: var(--bg-elevated);
+ border-right: 1px solid var(--border);
+ padding: 1.1rem 0.9rem;
+ display: flex;
+ flex-direction: column;
+ gap: 1.2rem;
+ position: sticky;
+ top: 0;
+ height: 100vh;
+ overflow-y: auto;
+}
+
+.brand {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ padding: 0 0.4rem;
+}
+.brand img {
+ width: 34px;
+ height: 34px;
+ border-radius: 9px;
+}
+.brand strong {
+ display: block;
+ font-size: 0.98rem;
+}
+.brand span {
+ display: block;
+ color: var(--text-muted);
+ font-size: 0.75rem;
+}
+
+.nav {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+}
+.nav-group {
+ margin-top: 0.7rem;
+ padding: 0 0.6rem 0.25rem;
+ font-size: 0.68rem;
+ letter-spacing: 0.09em;
+ text-transform: uppercase;
+ color: var(--text-muted);
+}
+.nav a {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ padding: 0.5rem 0.65rem;
+ border-radius: var(--radius-sm);
+ color: var(--text);
+ font-size: 0.9rem;
+}
+.nav a:hover {
+ background: var(--surface);
+ text-decoration: none;
+}
+.nav a.active {
+ background: color-mix(in srgb, var(--blue) 18%, transparent);
+ color: var(--blue-soft);
+ font-weight: 600;
+}
+.nav-icon {
+ width: 1.15rem;
+ text-align: center;
+ opacity: 0.85;
+}
+
+.sidebar-foot {
+ margin-top: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 0.6rem;
+ font-size: 0.8rem;
+}
+
+.viewer {
+ display: flex;
+ align-items: center;
+ gap: 0.55rem;
+ padding: 0.5rem;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+}
+.viewer img {
+ width: 30px;
+ height: 30px;
+ border-radius: 50%;
+}
+.viewer div {
+ min-width: 0;
+}
+.viewer strong {
+ display: block;
+ font-size: 0.85rem;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.main {
+ padding: 1.4rem 1.8rem 3rem;
+ min-width: 0;
+}
+
+.page-head {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 1rem;
+ margin-bottom: 1.2rem;
+}
+
+.stack {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+.row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.6rem;
+ align-items: center;
+}
+.grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
+ gap: 0.9rem;
+}
+
+/* --- Components ---------------------------------------------------------- */
+
+.card {
+ background: var(--bg-elevated);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ overflow: hidden;
+}
+.card-head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 1rem;
+ padding: 0.85rem 1.1rem;
+ border-bottom: 1px solid var(--border);
+}
+.card-actions {
+ display: flex;
+ gap: 0.45rem;
+ flex-wrap: wrap;
+}
+.card-body {
+ padding: 1.1rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.9rem;
+}
+
+.stat {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ padding: 0.75rem 0.9rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.1rem;
+}
+.stat-label {
+ font-size: 0.75rem;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--text-muted);
+}
+.stat-value {
+ font-size: 1.45rem;
+ line-height: 1.2;
+}
+.stat-hint {
+ font-size: 0.78rem;
+ color: var(--text-muted);
+}
+.stat-success .stat-value {
+ color: var(--green);
+}
+.stat-warning .stat-value {
+ color: var(--amber);
+}
+.stat-danger .stat-value {
+ color: var(--red);
+}
+.stat-primary .stat-value {
+ color: var(--blue-soft);
+}
+
+.badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3rem;
+ padding: 0.12rem 0.5rem;
+ border-radius: 999px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ border: 1px solid transparent;
+ white-space: nowrap;
+}
+.badge-neutral {
+ background: var(--surface);
+ color: var(--text-muted);
+ border-color: var(--border);
+}
+.badge-success {
+ background: color-mix(in srgb, var(--green) 18%, transparent);
+ color: var(--green);
+}
+.badge-warning {
+ background: color-mix(in srgb, var(--amber) 18%, transparent);
+ color: var(--amber);
+}
+.badge-danger {
+ background: color-mix(in srgb, var(--red) 18%, transparent);
+ color: var(--red);
+}
+.badge-info {
+ background: color-mix(in srgb, var(--blue) 20%, transparent);
+ color: var(--blue-soft);
+}
+.badge-gitea {
+ background: color-mix(in srgb, var(--gitea) 22%, transparent);
+ color: #a8d96a;
+}
+
+.btn {
+ font: inherit;
+ font-size: 0.86rem;
+ font-weight: 600;
+ padding: 0.42rem 0.8rem;
+ border-radius: var(--radius-sm);
+ border: 1px solid var(--border);
+ background: var(--surface);
+ color: var(--text);
+ cursor: pointer;
+ transition:
+ background 0.12s ease,
+ border-color 0.12s ease;
+}
+.btn:hover:not(:disabled) {
+ border-color: var(--blue);
+}
+.btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+.btn-primary {
+ background: var(--blue);
+ border-color: var(--blue);
+ color: #04121c;
+}
+.btn-primary:hover:not(:disabled) {
+ filter: brightness(1.1);
+}
+.btn-danger {
+ background: color-mix(in srgb, var(--red) 16%, transparent);
+ border-color: var(--red);
+ color: var(--red);
+}
+.btn-success {
+ background: color-mix(in srgb, var(--green) 16%, transparent);
+ border-color: var(--green);
+ color: var(--green);
+}
+.btn-ghost {
+ background: transparent;
+}
+.btn-sm {
+ padding: 0.25rem 0.55rem;
+ font-size: 0.78rem;
+}
+
+.field {
+ display: flex;
+ flex-direction: column;
+ gap: 0.28rem;
+}
+.field-label {
+ font-size: 0.82rem;
+ font-weight: 600;
+}
+.field-help {
+ font-size: 0.79rem;
+ color: var(--text-muted);
+}
+.field-error-text {
+ font-size: 0.79rem;
+ color: var(--red);
+}
+.field-error .input {
+ border-color: var(--red);
+}
+
+.input {
+ font: inherit;
+ font-size: 0.88rem;
+ width: 100%;
+ padding: 0.45rem 0.6rem;
+ border-radius: var(--radius-sm);
+ border: 1px solid var(--border);
+ background: var(--bg-sunken);
+ color: var(--text);
+}
+.input:focus {
+ outline: 2px solid color-mix(in srgb, var(--blue) 55%, transparent);
+ outline-offset: 1px;
+ border-color: var(--blue);
+}
+.textarea {
+ min-height: 7rem;
+ resize: vertical;
+ font-family: var(--mono);
+ font-size: 0.82rem;
+}
+
+.toggle {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ cursor: pointer;
+ font-size: 0.86rem;
+}
+.toggle input {
+ position: absolute;
+ opacity: 0;
+ width: 0;
+ height: 0;
+}
+.toggle-track {
+ width: 36px;
+ height: 20px;
+ border-radius: 999px;
+ background: var(--border);
+ position: relative;
+ transition: background 0.15s ease;
+ flex: none;
+}
+.toggle-track::after {
+ content: '';
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: var(--text);
+ transition: transform 0.15s ease;
+}
+.toggle input:checked + .toggle-track {
+ background: var(--blue);
+}
+.toggle input:checked + .toggle-track::after {
+ transform: translateX(16px);
+ background: #04121c;
+}
+.toggle input:focus-visible + .toggle-track {
+ outline: 2px solid var(--blue-soft);
+ outline-offset: 2px;
+}
+
+.table-wrap {
+ overflow-x: auto;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+}
+.table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 0.86rem;
+}
+.table th,
+.table td {
+ text-align: left;
+ padding: 0.5rem 0.7rem;
+ border-bottom: 1px solid var(--border);
+ vertical-align: middle;
+}
+.table th {
+ background: var(--surface);
+ font-size: 0.76rem;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+.table tbody tr:last-child td {
+ border-bottom: none;
+}
+.table tbody tr:hover {
+ background: color-mix(in srgb, var(--blue) 6%, transparent);
+}
+.num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+.nowrap {
+ white-space: nowrap;
+}
+
+.empty {
+ color: var(--text-muted);
+ font-size: 0.88rem;
+ padding: 1rem;
+ text-align: center;
+ border: 1px dashed var(--border);
+ border-radius: var(--radius-sm);
+}
+
+.notice {
+ border-radius: var(--radius-sm);
+ padding: 0.7rem 0.9rem;
+ border: 1px solid var(--border);
+ background: var(--surface);
+ font-size: 0.88rem;
+ display: flex;
+ gap: 0.8rem;
+ align-items: center;
+ justify-content: space-between;
+}
+.notice-error {
+ border-color: var(--red);
+ background: color-mix(in srgb, var(--red) 10%, transparent);
+}
+.notice-warning {
+ border-color: var(--amber);
+ background: color-mix(in srgb, var(--amber) 10%, transparent);
+}
+.notice-success {
+ border-color: var(--green);
+ background: color-mix(in srgb, var(--green) 10%, transparent);
+}
+.notice-info {
+ border-color: var(--blue);
+ background: color-mix(in srgb, var(--blue) 10%, transparent);
+}
+
+.loading {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ color: var(--text-muted);
+ padding: 1.6rem;
+ justify-content: center;
+}
+.spinner {
+ width: 16px;
+ height: 16px;
+ border: 2px solid var(--border);
+ border-top-color: var(--blue);
+ border-radius: 50%;
+ animation: spin 0.7s linear infinite;
+}
+@keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+.toast-host {
+ position: fixed;
+ right: 1rem;
+ bottom: 1rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ z-index: 60;
+}
+.toast {
+ padding: 0.6rem 0.9rem;
+ border-radius: var(--radius-sm);
+ background: var(--bg-elevated);
+ border: 1px solid var(--border);
+ box-shadow: var(--shadow);
+ font-size: 0.87rem;
+ max-width: 24rem;
+ animation: toast-in 0.18s ease;
+}
+.toast-success {
+ border-color: var(--green);
+}
+.toast-error {
+ border-color: var(--red);
+}
+.toast-info {
+ border-color: var(--blue);
+}
+.toast-out {
+ opacity: 0;
+ transition: opacity 0.5s ease;
+}
+@keyframes toast-in {
+ from {
+ transform: translateY(8px);
+ opacity: 0;
+ }
+}
+
+.overlay {
+ position: fixed;
+ inset: 0;
+ background: rgb(4 8 12 / 62%);
+ display: grid;
+ place-items: center;
+ padding: 1rem;
+ z-index: 70;
+}
+.modal {
+ background: var(--bg-elevated);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ box-shadow: var(--shadow);
+ width: min(620px, 100%);
+ max-height: 88vh;
+ display: flex;
+ flex-direction: column;
+}
+.modal-head {
+ padding: 0.9rem 1.1rem;
+ border-bottom: 1px solid var(--border);
+}
+.modal-body {
+ padding: 1.1rem;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 0.8rem;
+}
+.modal-foot {
+ padding: 0.8rem 1.1rem;
+ border-top: 1px solid var(--border);
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.5rem;
+}
+
+.rich {
+ font-size: 0.88rem;
+}
+.rich h3,
+.rich h4 {
+ margin: 0.7rem 0 0.3rem;
+}
+.rich ul {
+ margin: 0.3rem 0;
+ padding-left: 1.2rem;
+}
+
+/* --- Simple / advanced mode ---------------------------------------------- */
+
+body[data-mode='simple'] .advanced-only {
+ display: none !important;
+}
+
+.mode-switch {
+ display: flex;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ overflow: hidden;
+ font-size: 0.78rem;
+}
+.mode-switch button {
+ font: inherit;
+ font-weight: 600;
+ border: none;
+ background: transparent;
+ color: var(--text-muted);
+ padding: 0.28rem 0.75rem;
+ cursor: pointer;
+}
+.mode-switch button.active {
+ background: var(--blue);
+ color: #04121c;
+}
+
+/* --- Login and setup ------------------------------------------------------ */
+
+.centered {
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 1.5rem;
+}
+.panel {
+ width: min(520px, 100%);
+ background: var(--bg-elevated);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ box-shadow: var(--shadow);
+ padding: 1.8rem;
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ text-align: center;
+}
+.panel .field {
+ text-align: left;
+}
+
+.wizard {
+ display: grid;
+ grid-template-columns: 240px 1fr;
+ gap: 1.2rem;
+ align-items: start;
+}
+.wizard-steps {
+ display: flex;
+ flex-direction: column;
+ gap: 0.2rem;
+ position: sticky;
+ top: 1rem;
+}
+.wizard-step {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ padding: 0.5rem 0.6rem;
+ border-radius: var(--radius-sm);
+ border: 1px solid transparent;
+ background: none;
+ color: var(--text);
+ font: inherit;
+ font-size: 0.86rem;
+ text-align: left;
+ cursor: pointer;
+ width: 100%;
+}
+.wizard-step:hover {
+ background: var(--surface);
+}
+.wizard-step.active {
+ background: color-mix(in srgb, var(--blue) 16%, transparent);
+ border-color: var(--blue);
+}
+.wizard-step .dot {
+ width: 22px;
+ height: 22px;
+ flex: none;
+ border-radius: 50%;
+ display: grid;
+ place-items: center;
+ font-size: 0.72rem;
+ font-weight: 700;
+ border: 1px solid var(--border);
+ background: var(--bg-sunken);
+}
+.wizard-step.done .dot {
+ background: var(--green);
+ border-color: var(--green);
+ color: #04121c;
+}
+.wizard-step.invalid .dot {
+ background: var(--red);
+ border-color: var(--red);
+ color: #fff;
+}
+
+.steps-list {
+ margin: 0;
+ padding-left: 1.2rem;
+ font-size: 0.87rem;
+ color: var(--text-muted);
+}
+.steps-list li {
+ margin-bottom: 0.3rem;
+}
+.steps-list strong {
+ color: var(--text);
+}
+
+.secret-row {
+ display: flex;
+ gap: 0.4rem;
+ align-items: center;
+}
+.secret-row .input {
+ flex: 1;
+}
+
+.diff {
+ font-family: var(--mono);
+ font-size: 0.8rem;
+}
+.diff del {
+ color: var(--red);
+ text-decoration: line-through;
+}
+.diff ins {
+ color: var(--green);
+ text-decoration: none;
+}
+
+.log-line {
+ font-family: var(--mono);
+ font-size: 0.78rem;
+ padding: 0.18rem 0.4rem;
+ border-left: 3px solid var(--border);
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+.log-error {
+ border-left-color: var(--red);
+}
+.log-warn {
+ border-left-color: var(--amber);
+}
+.log-info {
+ border-left-color: var(--blue);
+}
+.log-debug {
+ border-left-color: var(--border);
+ opacity: 0.75;
+}
+
+.bar {
+ height: 6px;
+ border-radius: 999px;
+ background: var(--bg-sunken);
+ overflow: hidden;
+}
+.bar > span {
+ display: block;
+ height: 100%;
+ background: var(--blue);
+}
+
+.repo-list {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: 0.8rem;
+}
+.repo-card {
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ padding: 0.85rem;
+ background: var(--surface);
+ display: flex;
+ flex-direction: column;
+ gap: 0.45rem;
+}
+.repo-card h3 a {
+ color: var(--text);
+}
+.repo-meta {
+ display: flex;
+ gap: 0.8rem;
+ flex-wrap: wrap;
+ font-size: 0.78rem;
+ color: var(--text-muted);
+}
+
+.tabs {
+ display: flex;
+ gap: 0.3rem;
+ border-bottom: 1px solid var(--border);
+ overflow-x: auto;
+}
+.tabs button {
+ font: inherit;
+ font-size: 0.86rem;
+ font-weight: 600;
+ background: none;
+ border: none;
+ border-bottom: 2px solid transparent;
+ color: var(--text-muted);
+ padding: 0.5rem 0.75rem;
+ cursor: pointer;
+ white-space: nowrap;
+}
+.tabs button.active {
+ color: var(--blue-soft);
+ border-bottom-color: var(--blue);
+}
+
+@media (max-width: 900px) {
+ .shell {
+ grid-template-columns: 1fr;
+ }
+ .sidebar {
+ position: static;
+ height: auto;
+ flex-direction: column;
+ }
+ .main {
+ padding: 1rem;
+ }
+ .wizard {
+ grid-template-columns: 1fr;
+ }
+ .wizard-steps {
+ position: static;
+ flex-direction: row;
+ overflow-x: auto;
+ }
+}
diff --git a/src/web/public/views/community.js b/src/web/public/views/community.js
new file mode 100644
index 0000000..79cc128
--- /dev/null
+++ b/src/web/public/views/community.js
@@ -0,0 +1,382 @@
+import { api } from '../core/api.js';
+import { formatRelative, h } from '../core/dom.js';
+import {
+ badge,
+ button,
+ card,
+ confirmAction,
+ field,
+ input,
+ modal,
+ notice,
+ renderAsync,
+ select,
+ table,
+ toast,
+} from '../core/ui.js';
+
+/** Tickets, polls, temporary voice channels and the bot presence rotation. */
+
+const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
+
+const STATUS_TYPES = [
+ { value: 'playing', label: 'joue à' },
+ { value: 'watching', label: 'regarde' },
+ { value: 'listening', label: 'écoute' },
+ { value: 'competing', label: 'participe à' },
+ { value: 'streaming', label: 'en direct sur' },
+];
+
+function ticketsCard(data, level, reload) {
+ const labels = Object.fromEntries(data.categories.map((category) => [category.id, category.label]));
+
+ return card(
+ 'Tickets',
+ { subtitle: `${data.tickets.filter((ticket) => ticket.status === 'open').length} ticket(s) ouvert(s)` },
+ table(
+ [
+ { label: '#', className: 'num', key: 'id' },
+ { label: 'Catégorie', render: (ticket) => labels[ticket.category_id] ?? ticket.category_id },
+ { label: 'Auteur', render: (ticket) => ticket.author_id },
+ {
+ label: 'État',
+ render: (ticket) =>
+ ticket.status === 'open' ? badge('Ouvert', 'success') : badge('Clôturé', 'neutral'),
+ },
+ {
+ label: 'Prise en charge',
+ className: 'advanced-only',
+ render: (ticket) => ticket.claimed_by ?? '—',
+ },
+ { label: 'Ouvert', className: 'nowrap', render: (ticket) => formatRelative(ticket.created_at) },
+ {
+ label: '',
+ render: (ticket) =>
+ level >= LEVELS.STAFF &&
+ ticket.status === 'open' &&
+ button(
+ 'Clôturer',
+ async () => {
+ const reason = input({ placeholder: 'Motif de clôture' });
+ const confirmed = await modal(
+ `Clôturer le ticket #${ticket.id}`,
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ h('p', { text: 'Le salon privé associé sera supprimé.' }),
+ field('Motif', reason),
+ ),
+ submit: () => true,
+ }),
+ { confirmLabel: 'Clôturer', tone: 'danger' },
+ );
+ if (!confirmed) return;
+ await api.post(`/api/community/tickets/${ticket.id}/close`, { reason: reason.value });
+ toast('Ticket clôturé.');
+ reload();
+ },
+ { tone: 'ghost' },
+ ),
+ },
+ ],
+ data.tickets,
+ { empty: 'Aucun ticket.' },
+ ),
+ );
+}
+
+function pollsCard(polls, level, reload) {
+ return card(
+ 'Sondages',
+ { subtitle: `${polls.filter((poll) => poll.status === 'open').length} sondage(s) en cours` },
+ table(
+ [
+ { label: '#', className: 'num', key: 'id' },
+ { label: 'Question', key: 'question' },
+ {
+ label: 'Résultats',
+ render: (poll) => {
+ const counts = Object.fromEntries(poll.counts.map((row) => [row.choice_index, row.count]));
+ const total = poll.counts.reduce((sum, row) => sum + row.count, 0) || 1;
+ return h(
+ 'div',
+ { class: 'stack', style: { gap: '0.2rem' } },
+ poll.choices.map((choice, index) =>
+ h(
+ 'div',
+ {},
+ h(
+ 'div',
+ { class: 'row', style: { justifyContent: 'space-between', fontSize: '0.8rem' } },
+ h('span', { text: choice }),
+ h('span', { class: 'muted', text: `${counts[index] ?? 0}` }),
+ ),
+ h(
+ 'div',
+ { class: 'bar' },
+ h('span', { style: { width: `${((counts[index] ?? 0) / total) * 100}%` } }),
+ ),
+ ),
+ ),
+ );
+ },
+ },
+ {
+ label: 'État',
+ render: (poll) => (poll.status === 'open' ? badge('Ouvert', 'success') : badge('Clos', 'neutral')),
+ },
+ { label: 'Fin', className: 'nowrap advanced-only', render: (poll) => formatRelative(poll.ends_at) },
+ {
+ label: '',
+ render: (poll) =>
+ level >= LEVELS.STAFF &&
+ poll.status === 'open' &&
+ button(
+ 'Clore',
+ async () => {
+ if (!(await confirmAction('Clore le sondage', poll.question))) return;
+ await api.post(`/api/community/polls/${poll.id}/close`);
+ toast('Sondage clos.');
+ reload();
+ },
+ { tone: 'ghost' },
+ ),
+ },
+ ],
+ polls,
+ { empty: 'Aucun sondage.' },
+ ),
+ );
+}
+
+function voiceCard(voice, level, reload) {
+ return card(
+ 'Salons vocaux temporaires',
+ { subtitle: `${voice.channels.filter((channel) => channel.alive).length} salon(s) actif(s)` },
+ h('h3', { text: 'Déclencheurs' }),
+ table(
+ [
+ { label: 'Salon déclencheur', render: (trigger) => trigger.label || trigger.triggerId },
+ { label: 'Modèle de nom', render: (trigger) => trigger.template ?? '—' },
+ { label: 'Limite', className: 'num', render: (trigger) => trigger.userLimit || '∞' },
+ {
+ label: 'Actif',
+ render: (trigger) => (trigger.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')),
+ },
+ { label: 'Salons vivants', className: 'num', key: 'activeChannels' },
+ {
+ label: '',
+ render: (trigger) =>
+ level >= LEVELS.DEV &&
+ button(
+ trigger.enabled ? 'Mettre en pause' : 'Réactiver',
+ async () => {
+ await api.post(`/api/community/voice/triggers/${trigger.triggerId}/toggle`, {
+ enabled: !trigger.enabled,
+ });
+ toast('Déclencheur mis à jour.');
+ reload();
+ },
+ { tone: 'ghost' },
+ ),
+ },
+ ],
+ voice.triggers,
+ {
+ empty:
+ 'Aucun déclencheur configuré. Utilise `/voice setup` sur Discord ou renseigne CHANNEL_VOICE_TRIGGER_ID.',
+ },
+ ),
+
+ h('h3', { text: 'Salons générés' }),
+ table(
+ [
+ { label: 'Salon', key: 'name' },
+ { label: 'Propriétaire', render: (channel) => channel.owner_id },
+ { label: 'Occupants', className: 'num', key: 'members' },
+ {
+ label: 'État',
+ render: (channel) =>
+ h(
+ 'div',
+ { class: 'row' },
+ channel.alive ? badge('Vivant', 'success') : badge('Fantôme', 'warning'),
+ channel.locked && badge('Verrouillé', 'info'),
+ ),
+ },
+ { label: 'Créé', className: 'nowrap', render: (channel) => formatRelative(channel.created_at) },
+ {
+ label: '',
+ render: (channel) =>
+ level >= LEVELS.STAFF &&
+ button(
+ 'Supprimer',
+ async () => {
+ if (!(await confirmAction('Supprimer le salon', channel.name))) return;
+ await api.delete(`/api/community/voice/channels/${channel.channel_id}`);
+ toast('Salon supprimé.');
+ reload();
+ },
+ { tone: 'danger' },
+ ),
+ },
+ ],
+ voice.channels,
+ { empty: 'Aucun salon temporaire pour l’instant.' },
+ ),
+ );
+}
+
+function statusesCard(statuses, intervalSeconds, level, reload) {
+ const interval = input({ type: 'number', value: intervalSeconds, min: 5, style: { maxWidth: '8rem' } });
+
+ return card(
+ 'Présence du bot',
+ {
+ subtitle: 'Les statuts défilent dans l’ordre d’ajout.',
+ actions:
+ level >= LEVELS.DEV &&
+ h(
+ 'div',
+ { class: 'row' },
+ button(
+ 'Ajouter un statut',
+ async () => {
+ const text = input({ placeholder: 'les issues de FWS Arch' });
+ const type = select(STATUS_TYPES, { value: 'watching' });
+ const url = input({ placeholder: 'https://twitch.tv/… (type « en direct » uniquement)' });
+
+ const confirmed = await modal(
+ 'Nouveau statut',
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ field('Type', type),
+ field('Texte', text),
+ field('Lien', url),
+ ),
+ submit: () => text.value.trim() !== '',
+ }),
+ { confirmLabel: 'Ajouter', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ await api.post('/api/community/statuses', {
+ text: text.value,
+ type: type.value,
+ url: url.value || undefined,
+ });
+ toast('Statut ajouté.');
+ reload();
+ },
+ { tone: 'primary' },
+ ),
+ ),
+ },
+
+ level >= LEVELS.DEV &&
+ h(
+ 'div',
+ { class: 'row' },
+ field('Rythme de rotation (secondes)', interval),
+ button(
+ 'Enregistrer',
+ async () => {
+ const result = await api.put('/api/community/statuses/interval', {
+ seconds: Number(interval.value),
+ });
+ toast(`Rotation réglée sur ${result.intervalSeconds} s. Effective au prochain redémarrage.`);
+ },
+ { tone: 'ghost' },
+ ),
+ ),
+
+ table(
+ [
+ { label: '#', className: 'num', key: 'id' },
+ {
+ label: 'Statut',
+ render: (status) => {
+ const type = STATUS_TYPES.find((item) => item.value === status.type);
+ return `${type?.label ?? status.type} ${status.text}`;
+ },
+ },
+ {
+ label: 'Actif',
+ render: (status) => (status.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')),
+ },
+ {
+ label: '',
+ render: (status) =>
+ level >= LEVELS.DEV &&
+ h(
+ 'div',
+ { class: 'row' },
+ button(
+ status.enabled ? 'Pause' : 'Activer',
+ async () => {
+ await api.patch(`/api/community/statuses/${status.id}`, { enabled: !status.enabled });
+ toast('Statut mis à jour.');
+ reload();
+ },
+ { tone: 'ghost' },
+ ),
+ button(
+ 'Supprimer',
+ async () => {
+ if (!(await confirmAction('Supprimer le statut', status.text))) return;
+ await api.delete(`/api/community/statuses/${status.id}`);
+ toast('Statut supprimé.');
+ reload();
+ },
+ { tone: 'danger' },
+ ),
+ ),
+ },
+ ],
+ statuses,
+ { empty: 'Aucun statut : le bot affiche sa ligne par défaut.' },
+ ),
+ );
+}
+
+export function render(host, { state }) {
+ const level = state.me.accessLevel;
+ const reload = () => render(host, { state });
+
+ return renderAsync(
+ host,
+ async () => {
+ const [tickets, polls, voice, statuses] = await Promise.all([
+ api.get('/api/community/tickets', { limit: 100 }),
+ api.get('/api/community/polls', { limit: 30 }),
+ api.get('/api/community/voice'),
+ api.get('/api/community/statuses'),
+ ]);
+ return { tickets, polls: polls.polls, voice, statuses };
+ },
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: 'Tickets & vocaux' }),
+ h('p', { class: 'muted', text: 'Le quotidien de la communauté, géré depuis le site.' }),
+ ),
+ ),
+ data.voice.triggers.length === 0 &&
+ notice('Aucun salon « rejoindre pour créer » : la fonctionnalité vocale reste inactive.', 'info'),
+ ticketsCard(data.tickets, level, reload),
+ pollsCard(data.polls, level, reload),
+ voiceCard(data.voice, level, reload),
+ statusesCard(data.statuses.statuses, data.statuses.intervalSeconds, level, reload),
+ ),
+ );
+}
diff --git a/src/web/public/views/deployments.js b/src/web/public/views/deployments.js
new file mode 100644
index 0000000..ca7421b
--- /dev/null
+++ b/src/web/public/views/deployments.js
@@ -0,0 +1,348 @@
+import { api } from '../core/api.js';
+import { formatRelative, h, mount } from '../core/dom.js';
+import {
+ badge,
+ button,
+ card,
+ confirmAction,
+ field,
+ input,
+ modal,
+ notice,
+ renderAsync,
+ select,
+ table,
+ toast,
+ toggle,
+} from '../core/ui.js';
+
+/** Deploy targets and deployment history — the operations side of the SaaS (M16-T06). */
+
+const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
+
+const STATUS_TONE = {
+ success: 'success',
+ failed: 'danger',
+ running: 'warning',
+ pending: 'neutral',
+ cancelled: 'neutral',
+};
+
+const KINDS = [
+ { value: 'webhook', label: 'Webhook signé (recommandé)' },
+ { value: 'gitea-action', label: 'Workflow Gitea Actions' },
+ { value: 'command', label: 'Commande shell sur l’hôte du bot' },
+];
+
+const KIND_HELP = {
+ webhook:
+ 'Le bot envoie une requête POST signée en HMAC-SHA256 à ton serveur. C’est la méthode la plus sûre : rien ne s’exécute sur la machine du bot.',
+ 'gitea-action':
+ 'Le bot déclenche un workflow Gitea Actions. Le workflow doit accepter `workflow_dispatch`.',
+ command:
+ 'Le bot exécute une commande shell sur sa propre machine. À réserver à des personnes de confiance : c’est une exécution de code arbitraire.',
+};
+
+async function editTarget(existing, repositories, commandsAllowed, level, reload) {
+ const name = input({ value: existing?.name ?? '', placeholder: 'production-web' });
+ const repository = select(
+ repositories.map((item) => ({ value: item.fullName, label: item.fullName })),
+ { value: existing?.repository ?? repositories[0]?.fullName },
+ );
+ const environment = input({ value: existing?.environment ?? 'production' });
+ const kindOptions = KINDS.filter(
+ (kind) => kind.value !== 'command' || (commandsAllowed && level >= LEVELS.OWNER),
+ );
+ const kind = select(kindOptions, { value: existing?.kind ?? 'webhook' });
+
+ const url = input({ value: existing?.config?.url ?? '', placeholder: 'https://deploy.exemple.org/hook' });
+ const secret = input({
+ type: 'password',
+ placeholder: existing?.config?.hasSecret ? 'Inchangé' : 'Secret HMAC',
+ });
+ const command = input({
+ value: existing?.config?.command ?? '',
+ placeholder: 'systemctl restart fws-arch',
+ });
+ const cwd = input({
+ value: existing?.config?.cwd ?? '',
+ placeholder: 'Répertoire de travail (facultatif)',
+ });
+ const workflow = input({ value: existing?.config?.workflow ?? '', placeholder: 'deploy.yml' });
+ const ref = input({ value: existing?.config?.ref ?? '', placeholder: 'main' });
+
+ let autoDeploy = existing?.autoDeploy ?? false;
+ let enabled = existing?.enabled ?? true;
+
+ const specific = h('div', { class: 'stack' });
+ const help = h('p', { class: 'muted' });
+
+ const drawSpecific = () => {
+ help.textContent = KIND_HELP[kind.value];
+ const fields = {
+ webhook: [
+ field('URL', url),
+ field('Secret partagé', secret, {
+ help: 'Envoyé en en-tête `X-FWS-Signature` (HMAC-SHA256 du corps JSON).',
+ }),
+ ],
+ command: [field('Commande', command), field('Répertoire de travail', cwd)],
+ 'gitea-action': [
+ field('Fichier de workflow', workflow, { help: 'Nom du fichier dans `.gitea/workflows/`.' }),
+ field('Référence', ref, { help: 'Branche ou tag sur lequel déclencher le workflow.' }),
+ ],
+ };
+ mount(specific, fields[kind.value] ?? []);
+ };
+ kind.addEventListener('change', drawSpecific);
+ drawSpecific();
+
+ const confirmed = await modal(
+ existing ? `Modifier « ${existing.name} »` : 'Nouvelle cible de déploiement',
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ field('Nom', name),
+ field('Dépôt', repository),
+ field('Environnement', environment, { help: 'production, staging, preview…' }),
+ field('Type', kind),
+ help,
+ specific,
+ toggle(
+ autoDeploy,
+ (checked) => (autoDeploy = checked),
+ 'Déployer automatiquement à chaque release publiée',
+ ),
+ toggle(enabled, (checked) => (enabled = checked), 'Cible active'),
+ ),
+ submit: () => name.value.trim() !== '',
+ }),
+ { confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ const config = {};
+ if (kind.value === 'webhook') {
+ config.url = url.value.trim();
+ if (secret.value) config.secret = secret.value;
+ } else if (kind.value === 'command') {
+ config.command = command.value.trim();
+ config.cwd = cwd.value.trim();
+ } else {
+ config.workflow = workflow.value.trim();
+ config.ref = ref.value.trim();
+ }
+
+ const payload = {
+ name: name.value.trim(),
+ repository: repository.value,
+ environment: environment.value.trim(),
+ kind: kind.value,
+ config,
+ autoDeploy,
+ enabled,
+ };
+
+ if (existing) await api.patch(`/api/deploy/targets/${existing.id}`, payload);
+ else await api.post('/api/deploy/targets', payload);
+
+ toast(existing ? 'Cible mise à jour.' : 'Cible créée.');
+ reload();
+}
+
+async function runTarget(target, requireConfirmation, reload) {
+ const releaseTag = input({ placeholder: 'v1.2.3 (facultatif)' });
+ const ref = input({ placeholder: 'main (facultatif)' });
+
+ const confirmed = await modal(
+ `Déployer « ${target.name} »`,
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ h('p', {}, 'Environnement : ', h('strong', { text: target.environment })),
+ h('p', { class: 'muted', text: target.summary }),
+ field('Version à déployer', releaseTag),
+ field('Référence git', ref),
+ requireConfirmation && h('p', { class: 'muted', text: 'Le déploiement démarre dès la validation.' }),
+ ),
+ submit: () => true,
+ }),
+ { confirmLabel: 'Déployer', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ toast('Déploiement lancé…', 'info');
+ const result = await api.post(`/api/deploy/targets/${target.id}/run`, {
+ releaseTag: releaseTag.value.trim() || undefined,
+ ref: ref.value.trim() || undefined,
+ });
+
+ toast(
+ result.status === 'success'
+ ? 'Déploiement réussi.'
+ : `Déploiement en échec : ${result.error ?? 'raison inconnue'}`,
+ result.status === 'success' ? 'success' : 'error',
+ );
+ reload();
+}
+
+const showLog = (deployment) =>
+ modal(`Déploiement #${deployment.id}`, () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ h('p', {}, h('strong', { text: deployment.target_name }), ` · ${deployment.environment}`),
+ h('p', {
+ class: 'muted',
+ text: `${deployment.repository} · ${deployment.release_tag ?? deployment.ref ?? '—'}`,
+ }),
+ deployment.error && h('p', { class: 'field-error-text', text: deployment.error }),
+ h('pre', {}, h('code', { text: deployment.log || 'Aucune sortie.' })),
+ ),
+ submit: () => true,
+ }));
+
+export function render(host, { state }) {
+ const level = state.me.accessLevel;
+ const reload = () => render(host, { state });
+
+ return renderAsync(
+ host,
+ async () => {
+ const [targets, deployments, repositories] = await Promise.all([
+ api.get('/api/deploy/targets'),
+ api.get('/api/deployments', { limit: 40 }),
+ api.get('/api/repositories'),
+ ]);
+ return {
+ ...targets,
+ deployments: deployments.deployments,
+ repositories: repositories.repositories ?? [],
+ };
+ },
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: 'Déploiements' }),
+ h('p', {
+ class: 'muted',
+ text: 'Déclare où livrer chaque dépôt, puis déploie à la demande ou automatiquement à chaque release.',
+ }),
+ ),
+ level >= LEVELS.DEV &&
+ data.repositories.length > 0 &&
+ button(
+ 'Nouvelle cible',
+ () => editTarget(null, data.repositories, data.commandDeploysAllowed, level, reload),
+ { tone: 'primary' },
+ ),
+ ),
+
+ !data.commandDeploysAllowed &&
+ notice(
+ 'Les déploiements par commande shell sont désactivés (`WEB_ALLOW_COMMAND_DEPLOYS=false`). Les cibles webhook et Gitea Actions restent disponibles.',
+ 'info',
+ ),
+
+ card(
+ 'Cibles',
+ { subtitle: `${data.targets.length} cible(s) configurée(s)` },
+ table(
+ [
+ {
+ label: 'Cible',
+ render: (target) =>
+ h(
+ 'div',
+ {},
+ h('strong', { text: target.name }),
+ h('div', { class: 'muted', text: target.summary }),
+ ),
+ },
+ { label: 'Dépôt', key: 'repository' },
+ { label: 'Environnement', render: (target) => badge(target.environment, 'info') },
+ {
+ label: 'Type',
+ className: 'advanced-only',
+ render: (target) => badge(target.kind, target.kind === 'command' ? 'warning' : 'neutral'),
+ },
+ {
+ label: 'Auto',
+ render: (target) =>
+ target.autoDeploy ? badge('Auto', 'success') : badge('Manuel', 'neutral'),
+ },
+ {
+ label: 'Actif',
+ render: (target) => (target.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')),
+ },
+ {
+ label: '',
+ render: (target) =>
+ h(
+ 'div',
+ { class: 'row' },
+ level >= LEVELS.DEV &&
+ button('Déployer', () => runTarget(target, true, reload), {
+ tone: 'primary',
+ disabled: !target.enabled,
+ }),
+ level >= LEVELS.DEV &&
+ button(
+ 'Modifier',
+ () =>
+ editTarget(target, data.repositories, data.commandDeploysAllowed, level, reload),
+ { tone: 'ghost' },
+ ),
+ level >= LEVELS.OWNER &&
+ button(
+ 'Supprimer',
+ async () => {
+ if (!(await confirmAction('Supprimer la cible', `Supprimer « ${target.name} » ?`)))
+ return;
+ await api.delete(`/api/deploy/targets/${target.id}`);
+ toast('Cible supprimée.');
+ reload();
+ },
+ { tone: 'danger' },
+ ),
+ ),
+ },
+ ],
+ data.targets,
+ { empty: 'Aucune cible pour l’instant. Crée-en une pour déployer depuis ce site.' },
+ ),
+ ),
+
+ card(
+ 'Historique',
+ { subtitle: 'Les 40 derniers déploiements, réussis comme échoués.' },
+ table(
+ [
+ { label: '#', className: 'num', key: 'id' },
+ { label: 'Cible', key: 'target_name' },
+ { label: 'Environnement', key: 'environment' },
+ { label: 'Version', render: (row) => row.release_tag ?? row.ref ?? '—' },
+ {
+ label: 'État',
+ render: (row) => badge(row.status, STATUS_TONE[row.status] ?? 'neutral'),
+ },
+ { label: 'Source', className: 'advanced-only', key: 'source' },
+ { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.created_at) },
+ { label: '', render: (row) => button('Journal', () => showLog(row), { tone: 'ghost' }) },
+ ],
+ data.deployments,
+ { empty: 'Aucun déploiement enregistré.' },
+ ),
+ ),
+ ),
+ );
+}
diff --git a/src/web/public/views/discord.js b/src/web/public/views/discord.js
new file mode 100644
index 0000000..97356b1
--- /dev/null
+++ b/src/web/public/views/discord.js
@@ -0,0 +1,428 @@
+import { api } from '../core/api.js';
+import { formatDate, formatRelative, h, mount } from '../core/dom.js';
+import {
+ badge,
+ button,
+ card,
+ field,
+ grid,
+ input,
+ modal,
+ notice,
+ renderAsync,
+ select,
+ spinner,
+ stat,
+ table,
+ textarea,
+ toast,
+ toggle,
+} from '../core/ui.js';
+
+/** Discord server console: members, roles, moderation, announcements, routing. */
+
+const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
+const ACCESS_LABELS = { 0: 'Membre', 1: 'Staff', 2: 'Dev', 3: 'Owner' };
+const ACCESS_TONE = { 0: 'neutral', 1: 'info', 2: 'success', 3: 'danger' };
+
+const DURATIONS = [
+ { value: String(5 * 60_000), label: '5 minutes' },
+ { value: String(60 * 60_000), label: '1 heure' },
+ { value: String(24 * 60 * 60_000), label: '1 jour' },
+ { value: String(7 * 24 * 60 * 60_000), label: '7 jours' },
+];
+
+const MODERATION_ACTIONS = [
+ { value: 'warn', label: 'Avertissement' },
+ { value: 'mute', label: 'Exclusion temporaire' },
+ { value: 'kick', label: 'Expulsion' },
+ { value: 'ban', label: 'Bannissement' },
+];
+
+async function moderate(member, reload) {
+ const action = select(MODERATION_ACTIONS, { value: 'warn' });
+ const reason = input({ placeholder: 'Motif communiqué au membre' });
+ const duration = select(DURATIONS, { value: DURATIONS[1].value });
+ const durationField = field('Durée', duration);
+ durationField.style.display = 'none';
+
+ action.addEventListener('change', () => {
+ durationField.style.display = action.value === 'mute' ? '' : 'none';
+ });
+
+ const confirmed = await modal(
+ `Modérer ${member.displayName}`,
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ notice(
+ 'Le barème de rôles s’applique : tu ne peux pas agir sur quelqu’un au moins aussi haut placé.',
+ 'info',
+ ),
+ field('Action', action),
+ field('Motif', reason),
+ durationField,
+ ),
+ submit: () => true,
+ }),
+ { confirmLabel: 'Appliquer', tone: 'danger' },
+ );
+ if (!confirmed) return;
+
+ const result = await api.post('/api/discord/moderation', {
+ action: action.value,
+ userId: member.id,
+ reason: reason.value,
+ durationMs: action.value === 'mute' ? Number(duration.value) : undefined,
+ });
+ toast(`${result.label} appliqué.`);
+ reload();
+}
+
+async function manageRoles(member, roles, reload) {
+ const picker = select(
+ roles.filter((role) => !role.managed).map((role) => ({ value: role.id, label: role.name })),
+ {},
+ );
+ const current = h(
+ 'div',
+ { class: 'row' },
+ member.roles.map((roleId) => {
+ const role = roles.find((item) => item.id === roleId);
+ return badge(role?.name ?? roleId, 'info');
+ }),
+ );
+ let mode = 'add';
+
+ const confirmed = await modal(
+ `Rôles de ${member.displayName}`,
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ h('h3', { text: 'Rôles actuels' }),
+ member.roles.length > 0 ? current : h('p', { class: 'muted', text: 'Aucun rôle.' }),
+ field(
+ 'Action',
+ select(
+ [
+ { value: 'add', label: 'Ajouter' },
+ { value: 'remove', label: 'Retirer' },
+ ],
+ { value: 'add', onChange: (event) => (mode = event.target.value) },
+ ),
+ ),
+ field('Rôle', picker),
+ ),
+ submit: () => true,
+ }),
+ { confirmLabel: 'Appliquer' },
+ );
+ if (!confirmed) return;
+
+ await api.post(`/api/discord/members/${member.id}/roles`, { roleId: picker.value, action: mode });
+ toast('Rôles mis à jour.');
+ reload();
+}
+
+async function announce(channels) {
+ const channel = select(
+ channels
+ .filter((item) => item.kind === 'text' || item.kind === 'announcement')
+ .map((item) => ({ value: item.id, label: `#${item.name}` })),
+ {},
+ );
+ const title = input({ placeholder: 'Titre (facultatif)' });
+ const content = textarea({ placeholder: 'Ton message…' });
+ let asEmbed = true;
+
+ const confirmed = await modal(
+ 'Publier une annonce',
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ field('Salon', channel),
+ field('Titre', title),
+ field('Message', content),
+ toggle(true, (checked) => (asEmbed = checked), 'Publier sous forme d’embed'),
+ ),
+ submit: () => content.value.trim() !== '' || title.value.trim() !== '',
+ }),
+ { confirmLabel: 'Publier', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ const result = await api.post('/api/discord/announce', {
+ channelId: channel.value,
+ title: title.value,
+ content: content.value,
+ asEmbed,
+ });
+ toast(`Annonce publiée (${result.messageId}).`);
+}
+
+function membersCard(guild, level) {
+ const host = h('div', { class: 'stack' });
+ const search = input({ type: 'search', placeholder: 'Nom, pseudo ou identifiant…' });
+
+ const load = () =>
+ renderAsync(
+ host,
+ () => api.get('/api/discord/members', { q: search.value.trim(), limit: 100 }),
+ (data) =>
+ table(
+ [
+ {
+ label: 'Membre',
+ render: (member) =>
+ h(
+ 'div',
+ { class: 'row' },
+ h('img', {
+ src: member.avatar,
+ alt: '',
+ width: 26,
+ height: 26,
+ style: { borderRadius: '50%' },
+ }),
+ h(
+ 'div',
+ {},
+ h('strong', { text: member.displayName }),
+ h('div', { class: 'muted', text: `@${member.username}` }),
+ ),
+ ),
+ },
+ {
+ label: 'Niveau',
+ render: (member) => badge(ACCESS_LABELS[member.accessLevel], ACCESS_TONE[member.accessLevel]),
+ },
+ {
+ label: 'Arrivé',
+ className: 'nowrap advanced-only',
+ render: (member) => formatRelative(member.joinedAt),
+ },
+ {
+ label: 'État',
+ render: (member) =>
+ member.timeoutUntil && new Date(member.timeoutUntil) > new Date()
+ ? badge('Exclu', 'warning')
+ : member.bot
+ ? badge('Bot', 'neutral')
+ : '—',
+ },
+ {
+ label: '',
+ render: (member) =>
+ h(
+ 'div',
+ { class: 'row' },
+ level >= LEVELS.STAFF && button('Modérer', () => moderate(member, load), { tone: 'ghost' }),
+ level >= LEVELS.DEV &&
+ button('Rôles', () => manageRoles(member, guild.roles, load), { tone: 'ghost' }),
+ ),
+ },
+ ],
+ data.members,
+ { empty: 'Aucun membre ne correspond.' },
+ ),
+ );
+
+ let timer = null;
+ search.addEventListener('input', () => {
+ clearTimeout(timer);
+ timer = setTimeout(load, 300);
+ });
+ load();
+
+ return card('Membres', { subtitle: `${guild.memberCount} membre(s)`, actions: search }, host);
+}
+
+function notificationsCard(guild, level) {
+ const host = h('div', { class: 'stack' });
+
+ const load = () =>
+ renderAsync(
+ host,
+ () => api.get('/api/discord/notifications'),
+ (data) => {
+ const overrides = Object.fromEntries(data.overrides.map((row) => [row.type, row.channel_id]));
+ const channels = guild.channels.filter(
+ (item) => item.kind === 'text' || item.kind === 'announcement',
+ );
+
+ return table(
+ [
+ { label: 'Type', key: 'type' },
+ {
+ label: 'Salon par défaut (.env)',
+ className: 'advanced-only',
+ render: (row) => {
+ const channel = guild.channels.find((item) => item.id === row.fallback);
+ return channel ? `#${channel.name}` : '—';
+ },
+ },
+ {
+ label: 'Salon utilisé',
+ render: (row) => {
+ if (level < LEVELS.STAFF) return row.current ? `#${row.current}` : '—';
+ const picker = select(
+ [
+ { value: '', label: 'Valeur par défaut du .env' },
+ ...channels.map((item) => ({ value: item.id, label: `#${item.name}` })),
+ ],
+ {
+ value: overrides[row.type] ?? '',
+ onChange: async (event) => {
+ await api.put(`/api/discord/notifications/${row.type}`, {
+ channelId: event.target.value,
+ });
+ toast('Routage mis à jour.');
+ },
+ },
+ );
+ return picker;
+ },
+ },
+ ],
+ Object.keys(data.defaults).map((type) => ({
+ type,
+ fallback: data.defaults[type],
+ current: overrides[type] ?? data.defaults[type],
+ })),
+ );
+ },
+ );
+
+ load();
+ return card(
+ 'Notifications',
+ { subtitle: 'Où le bot publie les événements Gitea et ses propres messages.' },
+ host,
+ );
+}
+
+export async function render(host, { state }) {
+ const level = state.me.accessLevel;
+ mount(host, spinner());
+
+ let guild;
+ try {
+ guild = await api.get('/api/discord/guild');
+ } catch (error) {
+ mount(host, notice(error.message, 'error'));
+ return;
+ }
+
+ const byKind = (kind) => guild.channels.filter((channel) => channel.kind === kind).length;
+
+ mount(
+ host,
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ { class: 'row' },
+ guild.icon &&
+ h('img', { src: guild.icon, alt: '', width: 48, height: 48, style: { borderRadius: '12px' } }),
+ h(
+ 'div',
+ {},
+ h('h1', { text: guild.name }),
+ h('p', { class: 'muted', text: `Créé le ${formatDate(guild.createdAt)}` }),
+ ),
+ ),
+ level >= LEVELS.STAFF &&
+ button('Publier une annonce', () => announce(guild.channels), { tone: 'primary' }),
+ ),
+
+ card(
+ 'Serveur',
+ {},
+ grid(
+ stat('Membres', guild.memberCount, { tone: 'primary' }),
+ stat('Salons texte', byKind('text')),
+ stat('Salons vocaux', byKind('voice')),
+ stat('Rôles', guild.roles.length),
+ stat('Boosts', guild.boostCount ?? 0),
+ stat('Niveau de boost', guild.boostTier),
+ ),
+ ),
+
+ membersCard(guild, level),
+
+ card(
+ 'Rôles',
+ { advanced: true, subtitle: 'Ordre hiérarchique, du plus élevé au plus bas.' },
+ table(
+ [
+ {
+ label: 'Rôle',
+ render: (role) =>
+ h(
+ 'div',
+ { class: 'row' },
+ h('span', {
+ style: {
+ width: '12px',
+ height: '12px',
+ borderRadius: '50%',
+ background: role.color === '#000000' ? 'var(--border)' : role.color,
+ display: 'inline-block',
+ },
+ }),
+ h('span', { text: role.name }),
+ ),
+ },
+ { label: 'Membres', className: 'num', key: 'memberCount' },
+ { label: 'Position', className: 'num', key: 'position' },
+ {
+ label: 'Rôle FWS',
+ render: (role) => {
+ const mapping = Object.entries(guild.mapping.roles).find(([, id]) => id === role.id);
+ return mapping ? badge(mapping[0], 'success') : '—';
+ },
+ },
+ ],
+ guild.roles,
+ ),
+ ),
+
+ notificationsCard(guild, level),
+
+ card(
+ 'Commandes',
+ { advanced: true, subtitle: 'Commandes slash chargées et niveau requis.' },
+ await renderCommands(),
+ ),
+ ),
+ );
+}
+
+async function renderCommands() {
+ const host = h('div', {});
+ renderAsync(
+ host,
+ () => api.get('/api/discord/commands'),
+ (data) =>
+ table(
+ [
+ { label: 'Commande', render: (command) => `/${command.name}` },
+ { label: 'Description', key: 'description' },
+ { label: 'Niveau', render: (command) => badge(command.accessLabel, ACCESS_TONE[command.access]) },
+ {
+ label: 'Sous-commandes',
+ render: (command) => (command.options ?? []).map((option) => option.name).join(', ') || '—',
+ },
+ ],
+ data.commands,
+ ),
+ );
+ return host;
+}
diff --git a/src/web/public/views/login.js b/src/web/public/views/login.js
new file mode 100644
index 0000000..cdaa4e3
--- /dev/null
+++ b/src/web/public/views/login.js
@@ -0,0 +1,74 @@
+import { api } from '../core/api.js';
+import { h, mount } from '../core/dom.js';
+import { button, field, input, notice, toast } from '../core/ui.js';
+
+/** Sign-in page: Discord OAuth2, or the bootstrap token when nothing is configured yet. */
+
+const ERRORS = {
+ 'oauth-not-configured':
+ 'La connexion Discord n’est pas configurée. Renseigne `DISCORD_CLIENT_SECRET` et `WEB_PUBLIC_URL`, puis redémarre le bot.',
+ 'state-mismatch': 'La session de connexion a expiré. Réessaie.',
+ 'exchange-failed':
+ 'Discord a refusé l’échange du code. Vérifie l’URL de redirection déclarée dans le portail.',
+ 'not-a-member': 'Ton compte Discord n’est pas membre du serveur FWS.',
+ 'insufficient-level': 'Ton compte n’a pas le rôle Staff, Dev ou Owner sur le serveur.',
+ 'missing-code': 'Discord n’a pas renvoyé de code d’autorisation.',
+ access_denied: 'Connexion annulée.',
+};
+
+export function render(host, { state }) {
+ const params = new URLSearchParams(window.location.hash.split('?')[1] ?? '');
+ const failure = params.get('error');
+ const config = state.config ?? {};
+
+ const tokenInput = input({ type: 'password', placeholder: 'Jeton d’amorçage', autocomplete: 'off' });
+
+ const submitSetupToken = async () => {
+ try {
+ await api.post('/api/auth/setup', { token: tokenInput.value.trim() });
+ window.location.hash = '#/setup';
+ window.location.reload();
+ } catch (error) {
+ toast(error.message, 'error');
+ }
+ };
+
+ mount(
+ host,
+ h(
+ 'div',
+ { class: 'centered' },
+ h(
+ 'div',
+ { class: 'panel' },
+ h('img', { src: 'favicon.svg', alt: '', width: 56, height: 56, style: { margin: '0 auto' } }),
+ h('h1', { text: 'FWS-Bot' }),
+ h('p', { class: 'muted', text: 'Administration du bot, de l’organisation et des déploiements.' }),
+
+ failure && notice(ERRORS[failure] ?? `Connexion refusée (${failure}).`, 'error'),
+
+ config.oauthConfigured
+ ? h('a', { class: 'btn btn-primary', href: '/auth/login', text: 'Se connecter avec Discord' })
+ : notice(
+ 'La connexion Discord n’est pas encore disponible. Utilise le jeton d’amorçage pour ouvrir l’assistant de configuration.',
+ 'warning',
+ ),
+
+ config.setupAvailable &&
+ h(
+ 'div',
+ { class: 'stack' },
+ h('hr', { style: { border: 'none', borderTop: '1px solid var(--border)', width: '100%' } }),
+ field('Jeton d’amorçage', tokenInput, {
+ help: 'Affiché par `npm run setup`, ou défini dans `WEB_SETUP_TOKEN`. Il ne donne accès qu’à la configuration.',
+ }),
+ button('Ouvrir l’assistant de configuration', submitSetupToken, { tone: 'ghost' }),
+ ),
+ ),
+ ),
+ );
+
+ tokenInput.addEventListener('keydown', (event) => {
+ if (event.key === 'Enter') submitSetupToken();
+ });
+}
diff --git a/src/web/public/views/logs.js b/src/web/public/views/logs.js
new file mode 100644
index 0000000..901a4a5
--- /dev/null
+++ b/src/web/public/views/logs.js
@@ -0,0 +1,155 @@
+import { api } from '../core/api.js';
+import { formatBytes, formatDate, formatRelative, h, mount } from '../core/dom.js';
+import { badge, button, card, renderAsync, select, table, toast } from '../core/ui.js';
+
+/** Functional event log and daily technical log files. */
+
+const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
+
+function eventsCard() {
+ const host = h('div', { class: 'stack' });
+ let typeFilter = '';
+
+ const load = () =>
+ renderAsync(
+ host,
+ () => api.get('/api/logs/events', { type: typeFilter, limit: 150 }),
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ select(
+ [
+ { value: '', label: 'Tous les événements' },
+ ...data.types.map((row) => ({ value: row.type, label: `${row.type} (${row.count})` })),
+ ],
+ {
+ value: typeFilter,
+ onChange: (event) => {
+ typeFilter = event.target.value;
+ load();
+ },
+ },
+ ),
+ table(
+ [
+ { label: 'Type', render: (event) => badge(event.type, 'info') },
+ { label: 'Auteur', render: (event) => event.actor_id ?? '—' },
+ {
+ label: 'Détail',
+ render: (event) => (event.payload ? JSON.stringify(event.payload) : '—'),
+ },
+ { label: 'Quand', className: 'nowrap', render: (event) => formatRelative(event.created_at) },
+ ],
+ data.events,
+ { empty: 'Aucun événement enregistré.' },
+ ),
+ ),
+ );
+
+ load();
+ return card('Événements fonctionnels', { subtitle: 'Ce que le bot a fait, et pour qui.' }, host);
+}
+
+function filesCard() {
+ const host = h('div', { class: 'stack' });
+ const viewer = h('div', { class: 'stack' });
+ let levelFilter = '';
+
+ const openFile = (name) =>
+ renderAsync(
+ viewer,
+ () => api.get(`/api/logs/files/${name}`, { lines: 400, level: levelFilter }),
+ (data) =>
+ card(
+ data.name,
+ {
+ actions: select(
+ [
+ { value: '', label: 'Tous les niveaux' },
+ { value: 'debug', label: 'debug' },
+ { value: 'info', label: 'info' },
+ { value: 'warn', label: 'warn' },
+ { value: 'error', label: 'error' },
+ ],
+ {
+ value: levelFilter,
+ onChange: (event) => {
+ levelFilter = event.target.value;
+ openFile(name);
+ },
+ },
+ ),
+ },
+ h(
+ 'div',
+ { class: 'stack', style: { gap: '0.1rem', maxHeight: '28rem', overflowY: 'auto' } },
+ data.entries.length === 0
+ ? h('p', { class: 'empty', text: 'Aucune ligne pour ce filtre.' })
+ : data.entries.map((entry) =>
+ h('div', {
+ class: `log-line log-${entry.level ?? 'info'}`,
+ text: `${entry.time ? formatDate(entry.time) : ''} [${entry.scope ?? '—'}] ${entry.message ?? ''}${
+ entry.meta ? ` ${JSON.stringify(entry.meta)}` : ''
+ }`,
+ }),
+ ),
+ ),
+ ),
+ );
+
+ renderAsync(
+ host,
+ () => api.get('/api/logs/files'),
+ (data) =>
+ table(
+ [
+ { label: 'Fichier', key: 'name' },
+ { label: 'Taille', className: 'num', render: (file) => formatBytes(file.sizeBytes) },
+ { label: 'Modifié', className: 'nowrap', render: (file) => formatRelative(file.modifiedAt) },
+ { label: '', render: (file) => button('Ouvrir', () => openFile(file.name), { tone: 'ghost' }) },
+ ],
+ data.files,
+ { empty: 'Aucun fichier de log.' },
+ ),
+ );
+
+ return h(
+ 'div',
+ { class: 'stack' },
+ card('Journaux techniques', { subtitle: 'Un fichier JSON par jour, secrets masqués.' }, host),
+ viewer,
+ );
+}
+
+export function render(host, { state }) {
+ mount(
+ host,
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: 'Journaux' }),
+ h('p', { class: 'muted', text: 'Ce que le bot a fait et ce qu’il a rencontré.' }),
+ ),
+ state.me.accessLevel >= LEVELS.OWNER &&
+ button(
+ 'Purger les anciens événements',
+ async () => {
+ const result = await api.post('/api/settings/purge', {});
+ toast(`${result.events} événement(s) et ${result.sessions} session(s) supprimés.`);
+ render(host, { state });
+ },
+ { tone: 'ghost' },
+ ),
+ ),
+ eventsCard(),
+ state.me.accessLevel >= LEVELS.DEV ? filesCard() : null,
+ ),
+ );
+}
diff --git a/src/web/public/views/organization.js b/src/web/public/views/organization.js
new file mode 100644
index 0000000..3ca94d0
--- /dev/null
+++ b/src/web/public/views/organization.js
@@ -0,0 +1,285 @@
+import { api } from '../core/api.js';
+import { formatBytes, formatRelative, h } from '../core/dom.js';
+import {
+ badge,
+ button,
+ card,
+ field,
+ grid,
+ input,
+ modal,
+ renderAsync,
+ select,
+ stat,
+ table,
+ textarea,
+ toast,
+ toggle,
+} from '../core/ui.js';
+
+/** Organization page: identity, members, teams and repository inventory. */
+
+const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
+
+async function editOrganization(data, refresh) {
+ const fullName = input({ value: data.fullName ?? '' });
+ const description = textarea({ value: data.description ?? '' });
+ const website = input({ value: data.website ?? '', placeholder: 'https://…' });
+ const location = input({ value: data.location ?? '' });
+ const visibility = select(
+ [
+ { value: 'public', label: 'Publique' },
+ { value: 'limited', label: 'Limitée aux comptes connectés' },
+ { value: 'private', label: 'Privée' },
+ ],
+ { value: data.visibility ?? 'public' },
+ );
+
+ const confirmed = await modal(
+ 'Modifier l’organisation',
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ field('Nom affiché', fullName),
+ field('Description', description),
+ field('Site web', website),
+ field('Localisation', location),
+ field('Visibilité', visibility),
+ ),
+ submit: () => true,
+ }),
+ { confirmLabel: 'Enregistrer' },
+ );
+ if (!confirmed) return;
+
+ await api.patch('/api/organization', {
+ full_name: fullName.value,
+ description: description.value,
+ website: website.value,
+ location: location.value,
+ visibility: visibility.value,
+ });
+ toast('Organisation mise à jour.');
+ refresh();
+}
+
+async function createRepository(refresh) {
+ const name = input({ placeholder: 'mon-nouveau-depot' });
+ const description = input({ placeholder: 'À quoi sert ce dépôt ?' });
+ const defaultBranch = input({ value: 'main' });
+ let isPrivate = false;
+ let autoInit = true;
+
+ const confirmed = await modal(
+ 'Créer un dépôt',
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ field('Nom', name, { help: 'Lettres, chiffres, points, tirets et soulignés.' }),
+ field('Description', description),
+ field('Branche par défaut', defaultBranch),
+ toggle(false, (checked) => (isPrivate = checked), 'Dépôt privé'),
+ toggle(true, (checked) => (autoInit = checked), 'Initialiser avec un README'),
+ ),
+ submit: () => name.value.trim() !== '',
+ }),
+ { confirmLabel: 'Créer', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ const created = await api.post('/api/organization/repositories', {
+ name: name.value.trim(),
+ description: description.value,
+ defaultBranch: defaultBranch.value,
+ private: isPrivate,
+ autoInit,
+ });
+ toast(`Dépôt ${created.fullName} créé.`);
+ refresh();
+}
+
+export function render(host, { state }) {
+ const level = state.me.accessLevel;
+ const refresh = () => render(host, { state });
+
+ return renderAsync(
+ host,
+ () => api.get('/api/organization'),
+ (data) => {
+ const totals = data.repositories.reduce(
+ (accumulator, repository) => ({
+ issues: accumulator.issues + (repository.openIssues ?? 0),
+ pulls: accumulator.pulls + (repository.openPulls ?? 0),
+ size: accumulator.size + (repository.sizeKb ?? 0) * 1024,
+ }),
+ { issues: 0, pulls: 0, size: 0 },
+ );
+
+ return h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: data.fullName || data.name }),
+ h('p', { class: 'muted', text: data.description || 'Organisation Gitea de FWS.' }),
+ ),
+ h(
+ 'div',
+ { class: 'row' },
+ h('a', {
+ class: 'btn btn-ghost',
+ href: data.url,
+ target: '_blank',
+ rel: 'noreferrer',
+ text: '↗ Voir sur Gitea',
+ }),
+ level >= LEVELS.DEV &&
+ button('Nouveau dépôt', () => createRepository(refresh), { tone: 'primary' }),
+ level >= LEVELS.OWNER &&
+ button('Modifier', () => editOrganization(data, refresh), { tone: 'ghost' }),
+ ),
+ ),
+
+ card(
+ 'Chiffres clés',
+ {},
+ grid(
+ stat('Dépôts', data.repositories.length, { tone: 'primary' }),
+ stat('Membres', data.members.length),
+ stat('Équipes', data.teams.length),
+ stat('Issues ouvertes', totals.issues, { tone: totals.issues > 0 ? 'warning' : 'neutral' }),
+ stat('PR ouvertes', totals.pulls),
+ stat('Taille totale', formatBytes(totals.size)),
+ ),
+ ),
+
+ card(
+ 'Dépôts',
+ { subtitle: 'Clique sur un dépôt pour le gérer en détail.' },
+ table(
+ [
+ {
+ label: 'Dépôt',
+ render: (repository) =>
+ h(
+ 'div',
+ {},
+ h('a', { href: `#/repos/${repository.fullName}`, text: repository.name }),
+ repository.description && h('div', { class: 'muted', text: repository.description }),
+ ),
+ },
+ {
+ label: 'État',
+ render: (repository) =>
+ h(
+ 'div',
+ { class: 'row' },
+ repository.private ? badge('Privé', 'warning') : badge('Public', 'success'),
+ repository.archived && badge('Archivé', 'neutral'),
+ repository.fork && badge('Fork', 'info'),
+ ),
+ },
+ {
+ label: 'Langage',
+ render: (repository) => repository.language || '—',
+ className: 'advanced-only',
+ },
+ { label: 'Issues', className: 'num', render: (repository) => repository.openIssues ?? 0 },
+ { label: 'PR', className: 'num', render: (repository) => repository.openPulls ?? 0 },
+ {
+ label: 'Releases',
+ className: 'num advanced-only',
+ render: (repository) => repository.releases ?? 0,
+ },
+ {
+ label: 'Mise à jour',
+ className: 'nowrap',
+ render: (repository) => formatRelative(repository.updatedAt),
+ },
+ ],
+ data.repositories,
+ { empty: 'Aucun dépôt dans cette organisation.' },
+ ),
+ ),
+
+ card(
+ 'Membres',
+ { subtitle: `${data.members.length} compte(s) Gitea` },
+ table(
+ [
+ {
+ label: 'Compte',
+ render: (member) =>
+ h(
+ 'div',
+ { class: 'row' },
+ member.avatar &&
+ h('img', {
+ src: member.avatar,
+ alt: '',
+ width: 24,
+ height: 24,
+ style: { borderRadius: '50%' },
+ }),
+ h('span', { text: member.login }),
+ ),
+ },
+ { label: 'Nom', render: (member) => member.fullName || '—' },
+ { label: 'Admin', render: (member) => (member.isAdmin ? badge('Admin', 'danger') : '—') },
+ {
+ label: 'Dernière connexion',
+ className: 'nowrap advanced-only',
+ render: (member) => formatRelative(member.lastLogin),
+ },
+ ],
+ data.members,
+ ),
+ ),
+
+ card(
+ 'Équipes',
+ { advanced: true },
+ table(
+ [
+ { label: 'Équipe', key: 'name' },
+ { label: 'Description', render: (team) => team.description || '—' },
+ { label: 'Permission', render: (team) => badge(team.permission ?? '—', 'info') },
+ {
+ label: 'Tous les dépôts',
+ render: (team) => (team.includesAllRepositories ? 'Oui' : 'Non'),
+ },
+ {
+ label: '',
+ render: (team) =>
+ button(
+ 'Membres',
+ async () => {
+ const { members } = await api.get(`/api/organization/teams/${team.id}/members`);
+ await modal(`Membres de ${team.name}`, () => ({
+ node: table(
+ [
+ { label: 'Compte', key: 'login' },
+ { label: 'Nom', render: (m) => m.fullName || '—' },
+ ],
+ members,
+ ),
+ submit: () => true,
+ }));
+ },
+ { tone: 'ghost' },
+ ),
+ },
+ ],
+ data.teams,
+ ),
+ ),
+ );
+ },
+ );
+}
diff --git a/src/web/public/views/overview.js b/src/web/public/views/overview.js
new file mode 100644
index 0000000..6ed05f7
--- /dev/null
+++ b/src/web/public/views/overview.js
@@ -0,0 +1,205 @@
+import { api } from '../core/api.js';
+import { formatBytes, formatDuration, formatRelative, h } from '../core/dom.js';
+import { badge, card, grid, renderAsync, stat, table } from '../core/ui.js';
+
+/** Landing page: state of the bot, the organization and the last deployments. */
+
+const TONE = {
+ success: 'success',
+ failed: 'danger',
+ running: 'warning',
+ pending: 'neutral',
+ cancelled: 'neutral',
+};
+
+const EVENT_LABELS = {
+ 'web.login': 'Connexion au tableau de bord',
+ 'web.release.create': 'Release publiée',
+ 'deploy.success': 'Déploiement réussi',
+ 'deploy.failed': 'Déploiement en échec',
+ 'web.repository.create': 'Dépôt créé',
+ 'web.repository.delete': 'Dépôt supprimé',
+ 'web.announce': 'Annonce publiée',
+ 'ticket.close': 'Ticket clôturé',
+};
+
+const describeEvent = (type) => EVENT_LABELS[type] ?? type;
+
+function botCard(bot) {
+ return card(
+ 'Bot',
+ { subtitle: bot.online ? `Connecté en tant que ${bot.username}` : 'Hors ligne' },
+ grid(
+ stat('État', bot.online ? 'En ligne' : 'Hors ligne', { tone: bot.online ? 'success' : 'danger' }),
+ stat('Latence', bot.ping === null ? '—' : `${bot.ping} ms`),
+ stat('Actif depuis', formatDuration(bot.uptimeMs)),
+ stat('Commandes', bot.commands),
+ ),
+ h(
+ 'div',
+ { class: 'row advanced-only' },
+ badge(`Node ${bot.nodeVersion}`),
+ badge(`discord.js ${bot.discordJsVersion}`),
+ badge(`${bot.memoryMb} Mo de mémoire`),
+ ),
+ );
+}
+
+function guildCard(guild) {
+ if (!guild) return card('Serveur Discord', {}, h('p', { class: 'empty', text: 'Serveur introuvable.' }));
+
+ return card(
+ 'Serveur Discord',
+ { subtitle: guild.name },
+ grid(
+ stat('Membres', guild.memberCount, { tone: 'primary' }),
+ stat('Salons', guild.channelCount),
+ stat('Rôles', guild.roleCount),
+ stat('Boosts', `Niveau ${guild.boostTier}`),
+ ),
+ );
+}
+
+function giteaCard(gitea) {
+ if (!gitea.configured) {
+ return card(
+ 'Organisation',
+ {},
+ h('p', { class: 'empty', text: 'Gitea n’est pas configuré. Renseigne GITEA_URL et GITEA_TOKEN.' }),
+ );
+ }
+
+ return card(
+ 'Organisation',
+ { subtitle: gitea.organization?.fullName || gitea.organization?.name || '—' },
+ grid(
+ stat('Dépôts', gitea.repositoryCount, { tone: 'primary' }),
+ stat('Issues ouvertes', gitea.openIssues, { tone: gitea.openIssues > 0 ? 'warning' : 'neutral' }),
+ stat('PR ouvertes', gitea.openPulls),
+ stat('Étoiles', gitea.stars),
+ ),
+ h('h3', { text: 'Dépôts récemment actifs' }),
+ table(
+ [
+ {
+ label: 'Dépôt',
+ render: (repository) =>
+ h('a', { href: `#/repos/${repository.fullName}`, text: repository.fullName }),
+ },
+ { label: 'Issues', className: 'num', render: (repository) => repository.openIssues ?? 0 },
+ { label: 'PR', className: 'num', render: (repository) => repository.openPulls ?? 0 },
+ {
+ label: 'Mise à jour',
+ className: 'nowrap',
+ render: (repository) => formatRelative(repository.updatedAt),
+ },
+ ],
+ gitea.repositories,
+ ),
+ );
+}
+
+function activityCard(activity) {
+ const deployTotals = Object.fromEntries(activity.deployments.map((row) => [row.status, row.count]));
+
+ return card(
+ 'Activité',
+ {},
+ grid(
+ stat('Tickets ouverts', activity.openTickets, {
+ tone: activity.openTickets > 0 ? 'warning' : 'neutral',
+ }),
+ stat('Sondages', activity.polls),
+ stat('Salons vocaux', activity.voiceChannels),
+ stat('Déploiements réussis', deployTotals.success ?? 0, { tone: 'success' }),
+ stat('Déploiements en échec', deployTotals.failed ?? 0, {
+ tone: deployTotals.failed ? 'danger' : 'neutral',
+ }),
+ ),
+ activity.environments.length > 0 &&
+ h(
+ 'div',
+ { class: 'stack' },
+ h('h3', { text: 'Dernier déploiement par environnement' }),
+ table(
+ [
+ { label: 'Environnement', key: 'environment' },
+ { label: 'Dépôt', key: 'repository' },
+ { label: 'Version', render: (row) => row.release_tag ?? '—' },
+ { label: 'État', render: (row) => badge(row.status, TONE[row.status] ?? 'neutral') },
+ { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.finished_at) },
+ ],
+ activity.environments,
+ ),
+ ),
+ );
+}
+
+function systemCard(database, features) {
+ return card(
+ 'Système',
+ { advanced: true, subtitle: database.path },
+ grid(
+ stat('Taille de la base', formatBytes(database.sizeBytes)),
+ stat('Migrations', database.migrations.length),
+ stat('Webhooks', features.webhooks ? 'Activés' : 'Désactivés', {
+ tone: features.webhooks ? 'success' : 'neutral',
+ }),
+ stat('Gitea', features.gitea ? 'Connecté' : 'Non configuré', {
+ tone: features.gitea ? 'success' : 'warning',
+ }),
+ ),
+ table(
+ [
+ { label: 'Table', key: 'name' },
+ { label: 'Lignes', className: 'num', key: 'count' },
+ ],
+ Object.entries(database.tables)
+ .map(([name, count]) => ({ name, count }))
+ .sort((a, b) => b.count - a.count),
+ ),
+ );
+}
+
+export function render(host, { state }) {
+ return renderAsync(
+ host,
+ () => api.get('/api/overview'),
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: 'Vue d’ensemble' }),
+ h('p', {
+ class: 'muted',
+ text: `Bonjour ${state.me.displayName ?? ''} — voici l’état de FWS en un coup d’œil.`,
+ }),
+ ),
+ ),
+ botCard(data.bot),
+ guildCard(data.bot.guild),
+ giteaCard(data.gitea),
+ activityCard(data.activity),
+ systemCard(data.database, data.features),
+ card(
+ 'Derniers événements',
+ { advanced: true },
+ table(
+ [
+ { label: 'Événement', render: (event) => describeEvent(event.type) },
+ { label: 'Type', className: 'advanced-only', key: 'type' },
+ { label: 'Auteur', render: (event) => (event.actor_id ? `<@${event.actor_id}>` : '—') },
+ { label: 'Quand', className: 'nowrap', render: (event) => formatRelative(event.created_at) },
+ ],
+ data.events,
+ ),
+ ),
+ ),
+ );
+}
diff --git a/src/web/public/views/releases.js b/src/web/public/views/releases.js
new file mode 100644
index 0000000..0a56946
--- /dev/null
+++ b/src/web/public/views/releases.js
@@ -0,0 +1,276 @@
+import { api, encodeRepo } from '../core/api.js';
+import { formatRelative, h, mount, richText } from '../core/dom.js';
+import {
+ badge,
+ button,
+ card,
+ confirmAction,
+ field,
+ input,
+ modal,
+ notice,
+ renderAsync,
+ select,
+ spinner,
+ table,
+ textarea,
+ toast,
+ toggle,
+} from '../core/ui.js';
+
+/** Publishing releases and watching the deployments they trigger (M16-T08). */
+
+const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
+
+/** Suggests the next patch version from the last tag, so the field is never empty. */
+function nextTag(lastTag) {
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(lastTag ?? '');
+ if (!match) return 'v0.1.0';
+ const [, major, minor, patch] = match;
+ const prefix = lastTag.startsWith('v') ? 'v' : '';
+ return `${prefix}${major}.${minor}.${Number(patch) + 1}`;
+}
+
+async function publishRelease(base, repository, releases, branches, reload) {
+ const tag = input({ value: nextTag(releases[0]?.tag) });
+ const name = input({ placeholder: 'Nom de la version (facultatif)' });
+ const targetBranch = select(
+ branches.map((branch) => ({ value: branch.name, label: branch.name })),
+ { value: repository.defaultBranch },
+ );
+ const body = textarea({ placeholder: 'Notes de version…' });
+ let draft = false;
+ let prerelease = false;
+ let deploy = true;
+
+ const generate = button(
+ 'Générer les notes depuis les commits',
+ async () => {
+ const result = await api.post(`${base}/releases/notes`, { target: targetBranch.value });
+ body.value = result.notes;
+ toast(`${result.commitCount} commit(s) analysé(s) depuis ${result.previousTag ?? 'le début'}.`, 'info');
+ },
+ { tone: 'ghost' },
+ );
+
+ const confirmed = await modal(
+ 'Publier une release',
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ field('Tag', tag, { help: 'SemVer, comme le CHANGELOG généré depuis les commits.' }),
+ field('Nom', name),
+ field('Branche cible', targetBranch),
+ generate,
+ field('Notes de version', body),
+ toggle(false, (checked) => (draft = checked), 'Brouillon (non publié, aucune notification)'),
+ toggle(false, (checked) => (prerelease = checked), 'Préversion'),
+ toggle(true, (checked) => (deploy = checked), 'Lancer les déploiements automatiques configurés'),
+ ),
+ submit: () => tag.value.trim() !== '',
+ }),
+ { confirmLabel: 'Publier', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ const result = await api.post(`${base}/releases`, {
+ tag: tag.value.trim(),
+ name: name.value.trim() || undefined,
+ target: targetBranch.value,
+ body: body.value,
+ draft,
+ prerelease,
+ deploy,
+ });
+
+ const deployed = result.deployments ?? [];
+ toast(
+ deployed.length > 0
+ ? `Release ${result.release.tag} publiée, ${deployed.length} déploiement(s) déclenché(s).`
+ : `Release ${result.release.tag} publiée.`,
+ 'success',
+ );
+ reload();
+}
+
+function releaseRow(base, level, reload) {
+ return [
+ {
+ label: 'Version',
+ render: (release) =>
+ h(
+ 'div',
+ {},
+ h('a', { href: release.htmlUrl, target: '_blank', rel: 'noreferrer', text: release.tag }),
+ release.name && release.name !== release.tag && h('div', { class: 'muted', text: release.name }),
+ ),
+ },
+ {
+ label: 'État',
+ render: (release) =>
+ h(
+ 'div',
+ { class: 'row' },
+ release.draft ? badge('Brouillon', 'neutral') : badge('Publiée', 'success'),
+ release.prerelease && badge('Préversion', 'warning'),
+ ),
+ },
+ { label: 'Auteur', className: 'advanced-only', render: (release) => release.author ?? '—' },
+ {
+ label: 'Publiée',
+ className: 'nowrap',
+ render: (release) => formatRelative(release.publishedAt ?? release.createdAt),
+ },
+ {
+ label: '',
+ render: (release) =>
+ h(
+ 'div',
+ { class: 'row' },
+ button('Notes', () => showNotes(release), { tone: 'ghost' }),
+ level >= LEVELS.DEV &&
+ release.draft &&
+ button(
+ 'Publier',
+ async () => {
+ await api.patch(`${base}/releases/${release.id}`, { draft: false });
+ toast('Release publiée.');
+ reload();
+ },
+ { tone: 'success' },
+ ),
+ level >= LEVELS.OWNER &&
+ button(
+ 'Supprimer',
+ async () => {
+ if (!(await confirmAction('Supprimer la release', `Supprimer ${release.tag} ?`))) return;
+ await api.delete(`${base}/releases/${release.id}`);
+ toast('Release supprimée.');
+ reload();
+ },
+ { tone: 'danger' },
+ ),
+ ),
+ },
+ ];
+}
+
+const showNotes = (release) =>
+ modal(release.name || release.tag, () => ({
+ node: richText(release.body || '_Aucune note._'),
+ submit: () => true,
+ }));
+
+export async function render(host, { state }) {
+ const level = state.me.accessLevel;
+ mount(host, spinner());
+
+ const params = new URLSearchParams(window.location.hash.split('?')[1] ?? '');
+ const { repositories, configured } = await api.get('/api/repositories');
+
+ if (!configured || repositories.length === 0) {
+ mount(host, notice('Aucun dépôt Gitea accessible. Vérifie la configuration Gitea.', 'warning'));
+ return;
+ }
+
+ const preferred = params.get('repo') || state.repository;
+ let current = repositories.find((item) => item.fullName === preferred) ?? repositories[0];
+
+ const picker = select(
+ repositories.map((item) => ({ value: item.fullName, label: item.fullName })),
+ {
+ value: current.fullName,
+ onChange: (event) => {
+ current = repositories.find((item) => item.fullName === event.target.value);
+ state.repository = current.fullName;
+ localStorage.setItem('fws.repository', current.fullName);
+ draw();
+ },
+ },
+ );
+
+ const body = h('div', { class: 'stack' });
+
+ const draw = () => {
+ const base = `/api/repositories/${encodeRepo(current.fullName)}`;
+ renderAsync(
+ body,
+ async () => {
+ const [detail, releases, deployments] = await Promise.all([
+ api.get(base),
+ api.get(`${base}/releases`, { limit: 30 }),
+ api.get('/api/deployments', { repository: current.fullName, limit: 15 }),
+ ]);
+ return { detail, releases: releases.releases, deployments: deployments.deployments };
+ },
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ card(
+ 'Releases',
+ {
+ subtitle: `${data.releases.length} version(s) sur ${current.fullName}`,
+ actions:
+ level >= LEVELS.DEV &&
+ button(
+ 'Publier une release',
+ () => publishRelease(base, data.detail, data.releases, data.detail.branches, draw),
+ { tone: 'primary' },
+ ),
+ },
+ table(releaseRow(base, level, draw), data.releases, { empty: 'Aucune release publiée.' }),
+ ),
+
+ card(
+ 'Déploiements liés',
+ { subtitle: 'Déclenchés par la publication d’une version ou lancés à la main.' },
+ table(
+ [
+ { label: 'Cible', key: 'target_name' },
+ { label: 'Environnement', key: 'environment' },
+ { label: 'Version', render: (row) => row.release_tag ?? row.ref ?? '—' },
+ {
+ label: 'État',
+ render: (row) =>
+ badge(
+ row.status,
+ row.status === 'success' ? 'success' : row.status === 'failed' ? 'danger' : 'warning',
+ ),
+ },
+ { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.created_at) },
+ ],
+ data.deployments,
+ { empty: 'Aucun déploiement pour ce dépôt.' },
+ ),
+ ),
+ ),
+ );
+ };
+
+ mount(
+ host,
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: 'Releases' }),
+ h('p', {
+ class: 'muted',
+ text: 'Publie une version, génère ses notes depuis les commits et laisse les déploiements suivre.',
+ }),
+ ),
+ h('div', { style: { minWidth: '260px' } }, picker),
+ ),
+ body,
+ ),
+ );
+
+ draw();
+}
diff --git a/src/web/public/views/repositories.js b/src/web/public/views/repositories.js
new file mode 100644
index 0000000..59a7510
--- /dev/null
+++ b/src/web/public/views/repositories.js
@@ -0,0 +1,969 @@
+import { api, encodeRepo } from '../core/api.js';
+import { formatBytes, formatRelative, h, mount } from '../core/dom.js';
+import {
+ badge,
+ button,
+ card,
+ confirmAction,
+ confirmDangerous,
+ field,
+ grid,
+ input,
+ modal,
+ notice,
+ renderAsync,
+ select,
+ spinner,
+ stat,
+ table,
+ textarea,
+ toast,
+ toggle,
+} from '../core/ui.js';
+
+/** Repository list and the full management console of a single repository. */
+
+const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
+
+// --- List -------------------------------------------------------------------
+
+function repositoryCard(repository) {
+ return h(
+ 'article',
+ { class: 'repo-card' },
+ h('h3', {}, h('a', { href: `#/repos/${repository.fullName}`, text: repository.name })),
+ h('p', { class: 'muted', text: repository.description || 'Sans description.' }),
+ h(
+ 'div',
+ { class: 'row' },
+ repository.private ? badge('Privé', 'warning') : badge('Public', 'success'),
+ repository.archived && badge('Archivé', 'neutral'),
+ repository.language && badge(repository.language, 'info'),
+ ),
+ h(
+ 'div',
+ { class: 'repo-meta' },
+ h('span', { text: `${repository.openIssues ?? 0} issues` }),
+ h('span', { text: `${repository.openPulls ?? 0} PR` }),
+ h('span', { text: `${repository.releases ?? 0} releases` }),
+ h('span', { text: formatRelative(repository.updatedAt) }),
+ ),
+ );
+}
+
+function renderList(host) {
+ return renderAsync(
+ host,
+ () => api.get('/api/repositories'),
+ (data) => {
+ if (!data.configured) {
+ return notice(
+ 'Gitea n’est pas configuré : renseigne `GITEA_URL` et `GITEA_TOKEN` dans les paramètres.',
+ 'warning',
+ );
+ }
+
+ const search = input({ placeholder: 'Filtrer par nom…', type: 'search' });
+ const list = h('div', { class: 'repo-list' });
+
+ const draw = () => {
+ const needle = search.value.trim().toLowerCase();
+ const filtered = data.repositories.filter(
+ (repository) =>
+ needle === '' ||
+ repository.name.toLowerCase().includes(needle) ||
+ (repository.description ?? '').toLowerCase().includes(needle),
+ );
+ mount(
+ list,
+ filtered.length > 0
+ ? filtered.map(repositoryCard)
+ : h('p', { class: 'empty', text: 'Aucun dépôt ne correspond.' }),
+ );
+ };
+ search.addEventListener('input', draw);
+ draw();
+
+ return h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: 'Dépôts' }),
+ h('p', { class: 'muted', text: `${data.repositories.length} dépôt(s) dans l’organisation.` }),
+ ),
+ h('div', { style: { minWidth: '240px' } }, search),
+ ),
+ list,
+ );
+ },
+ );
+}
+
+// --- Detail -----------------------------------------------------------------
+
+const TABS = [
+ { id: 'overview', label: 'Aperçu', level: LEVELS.STAFF },
+ { id: 'issues', label: 'Issues', level: LEVELS.STAFF },
+ { id: 'pulls', label: 'Pull requests', level: LEVELS.STAFF },
+ { id: 'commits', label: 'Commits', level: LEVELS.STAFF },
+ { id: 'branches', label: 'Branches', level: LEVELS.STAFF, advanced: true },
+ { id: 'people', label: 'Collaborateurs', level: LEVELS.STAFF, advanced: true },
+ { id: 'hooks', label: 'Webhooks', level: LEVELS.DEV, advanced: true },
+ { id: 'actions', label: 'Actions', level: LEVELS.STAFF, advanced: true },
+ { id: 'settings', label: 'Réglages', level: LEVELS.DEV },
+];
+
+const issueBadge = (issue) =>
+ issue.state === 'open' ? badge('Ouverte', 'success') : badge('Fermée', 'neutral');
+
+function issuesTab(base, level) {
+ const host = h('div', { class: 'stack' });
+ let stateFilter = 'open';
+
+ const load = () =>
+ renderAsync(
+ host,
+ () => api.get(`${base}/issues`, { state: stateFilter, limit: 50 }),
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'row' },
+ select(
+ [
+ { value: 'open', label: 'Ouvertes' },
+ { value: 'closed', label: 'Fermées' },
+ { value: 'all', label: 'Toutes' },
+ ],
+ {
+ value: stateFilter,
+ onChange: (event) => {
+ stateFilter = event.target.value;
+ load();
+ },
+ },
+ ),
+ button('Nouvelle issue', () => createIssue(base, load), { tone: 'primary' }),
+ ),
+ table(
+ [
+ { label: '#', className: 'num', key: 'number' },
+ {
+ label: 'Titre',
+ render: (issue) =>
+ h(
+ 'div',
+ {},
+ h('a', { href: issue.htmlUrl, target: '_blank', rel: 'noreferrer', text: issue.title }),
+ issue.labels.length > 0 &&
+ h(
+ 'div',
+ { class: 'row' },
+ issue.labels.map((label) => badge(label.name, 'info')),
+ ),
+ ),
+ },
+ { label: 'État', render: issueBadge },
+ { label: 'Auteur', render: (issue) => issue.author ?? '—' },
+ { label: 'Maj', className: 'nowrap', render: (issue) => formatRelative(issue.updatedAt) },
+ {
+ label: '',
+ render: (issue) =>
+ level >= LEVELS.DEV &&
+ h(
+ 'div',
+ { class: 'row' },
+ button(
+ issue.state === 'open' ? 'Fermer' : 'Rouvrir',
+ async () => {
+ await api.patch(`${base}/issues/${issue.number}`, {
+ state: issue.state === 'open' ? 'closed' : 'open',
+ });
+ toast('Issue mise à jour.');
+ load();
+ },
+ { tone: 'ghost' },
+ ),
+ button('Commenter', () => commentIssue(base, issue, load), { tone: 'ghost' }),
+ ),
+ },
+ ],
+ data.issues,
+ { empty: 'Aucune issue.' },
+ ),
+ ),
+ );
+
+ load();
+ return host;
+}
+
+async function createIssue(base, reload) {
+ const title = input({ placeholder: 'Titre clair et actionnable' });
+ const body = textarea({ placeholder: 'Contexte, étapes de reproduction, comportement attendu…' });
+
+ const confirmed = await modal(
+ 'Nouvelle issue',
+ () => ({
+ node: h('div', { class: 'stack' }, field('Titre', title), field('Description', body)),
+ submit: () => title.value.trim().length >= 3,
+ }),
+ { confirmLabel: 'Créer', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ const issue = await api.post(`${base}/issues`, { title: title.value.trim(), body: body.value });
+ toast(`Issue #${issue.number} créée.`);
+ reload();
+}
+
+async function commentIssue(base, issue, reload) {
+ const body = textarea({ placeholder: 'Ton commentaire…' });
+ const confirmed = await modal(
+ `Commenter #${issue.number}`,
+ () => ({ node: field('Commentaire', body), submit: () => body.value.trim() !== '' }),
+ { confirmLabel: 'Publier', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ await api.post(`${base}/issues/${issue.number}/comments`, { body: body.value });
+ toast('Commentaire publié.');
+ reload();
+}
+
+function pullsTab(base, level) {
+ const host = h('div', { class: 'stack' });
+ let stateFilter = 'open';
+
+ const load = () =>
+ renderAsync(
+ host,
+ () => api.get(`${base}/pulls`, { state: stateFilter, limit: 50 }),
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'row' },
+ select(
+ [
+ { value: 'open', label: 'Ouvertes' },
+ { value: 'closed', label: 'Fermées' },
+ { value: 'all', label: 'Toutes' },
+ ],
+ {
+ value: stateFilter,
+ onChange: (event) => {
+ stateFilter = event.target.value;
+ load();
+ },
+ },
+ ),
+ level >= LEVELS.DEV && button('Nouvelle PR', () => createPull(base, load), { tone: 'primary' }),
+ ),
+ table(
+ [
+ { label: '#', className: 'num', key: 'number' },
+ {
+ label: 'Titre',
+ render: (pull) =>
+ h('a', { href: pull.htmlUrl, target: '_blank', rel: 'noreferrer', text: pull.title }),
+ },
+ {
+ label: 'Branches',
+ className: 'nowrap advanced-only',
+ render: (pull) => `${pull.head} → ${pull.base}`,
+ },
+ {
+ label: 'État',
+ render: (pull) =>
+ pull.merged
+ ? badge('Mergée', 'info')
+ : pull.draft
+ ? badge('Brouillon', 'neutral')
+ : issueBadge(pull),
+ },
+ { label: 'Auteur', render: (pull) => pull.author ?? '—' },
+ { label: 'Maj', className: 'nowrap', render: (pull) => formatRelative(pull.updatedAt) },
+ {
+ label: '',
+ render: (pull) =>
+ level >= LEVELS.DEV &&
+ !pull.merged &&
+ pull.state === 'open' &&
+ button('Merger', () => mergePull(base, pull, load), { tone: 'success' }),
+ },
+ ],
+ data.pulls,
+ { empty: 'Aucune pull request.' },
+ ),
+ ),
+ );
+
+ load();
+ return host;
+}
+
+async function createPull(base, reload) {
+ const title = input({ placeholder: 'feat(scope): description' });
+ const head = input({ placeholder: 'feat/ma-branche' });
+ const baseBranch = input({ value: 'main' });
+ const body = textarea({ placeholder: 'Ce que fait la PR et pourquoi.' });
+
+ const confirmed = await modal(
+ 'Nouvelle pull request',
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ field('Titre', title, { help: 'Format Conventional Commits, comme les commits FWS.' }),
+ field('Branche source', head),
+ field('Branche cible', baseBranch),
+ field('Description', body),
+ ),
+ submit: () => title.value.trim() !== '' && head.value.trim() !== '',
+ }),
+ { confirmLabel: 'Créer', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ const pull = await api.post(`${base}/pulls`, {
+ title: title.value.trim(),
+ head: head.value.trim(),
+ base: baseBranch.value.trim(),
+ body: body.value,
+ });
+ toast(`PR #${pull.number} créée.`);
+ reload();
+}
+
+async function mergePull(base, pull, reload) {
+ const style = select(
+ [
+ { value: 'squash', label: 'Squash (convention FWS)' },
+ { value: 'merge', label: 'Merge commit' },
+ { value: 'rebase', label: 'Rebase' },
+ ],
+ { value: 'squash' },
+ );
+ let deleteBranch = true;
+
+ const confirmed = await modal(
+ `Merger #${pull.number}`,
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ h('p', { text: `${pull.head} → ${pull.base}` }),
+ field('Méthode', style),
+ toggle(true, (checked) => (deleteBranch = checked), 'Supprimer la branche après le merge'),
+ ),
+ submit: () => true,
+ }),
+ { confirmLabel: 'Merger', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ await api.post(`${base}/pulls/${pull.number}/merge`, { style: style.value, deleteBranch });
+ toast('Pull request mergée.');
+ reload();
+}
+
+function commitsTab(base, branches) {
+ const host = h('div', { class: 'stack' });
+ let branch = '';
+
+ const load = () =>
+ renderAsync(
+ host,
+ () => api.get(`${base}/commits`, { branch, limit: 40 }),
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ select(
+ [
+ { value: '', label: 'Branche par défaut' },
+ ...branches.map((item) => ({ value: item.name, label: item.name })),
+ ],
+ {
+ value: branch,
+ onChange: (event) => {
+ branch = event.target.value;
+ load();
+ },
+ },
+ ),
+ table(
+ [
+ {
+ label: 'Commit',
+ render: (commit) =>
+ h('a', {
+ href: commit.htmlUrl,
+ target: '_blank',
+ rel: 'noreferrer',
+ text: commit.shortSha,
+ }),
+ },
+ { label: 'Message', key: 'message' },
+ { label: 'Auteur', render: (commit) => commit.authorLogin || commit.author || '—' },
+ { label: 'Date', className: 'nowrap', render: (commit) => formatRelative(commit.date) },
+ ],
+ data.commits,
+ { empty: 'Aucun commit.' },
+ ),
+ ),
+ );
+
+ load();
+ return host;
+}
+
+function branchesTab(base, repository, level, refresh) {
+ return h(
+ 'div',
+ { class: 'stack' },
+ level >= LEVELS.DEV &&
+ h(
+ 'div',
+ { class: 'row' },
+ button(
+ 'Nouvelle branche',
+ async () => {
+ const name = input({ placeholder: 'feat/ma-branche' });
+ const from = input({ value: repository.defaultBranch ?? 'main' });
+ const confirmed = await modal(
+ 'Créer une branche',
+ () => ({
+ node: h('div', { class: 'stack' }, field('Nom', name), field('Depuis', from)),
+ submit: () => name.value.trim() !== '',
+ }),
+ { confirmLabel: 'Créer', tone: 'primary' },
+ );
+ if (!confirmed) return;
+ await api.post(`${base}/branches`, { name: name.value.trim(), from: from.value.trim() });
+ toast('Branche créée.');
+ refresh();
+ },
+ { tone: 'primary' },
+ ),
+ ),
+ table(
+ [
+ {
+ label: 'Branche',
+ render: (branch) =>
+ h(
+ 'div',
+ { class: 'row' },
+ h('strong', { text: branch.name }),
+ branch.name === repository.defaultBranch && badge('Par défaut', 'info'),
+ branch.protected && badge('Protégée', 'warning'),
+ ),
+ },
+ { label: 'Dernier commit', render: (branch) => branch.commitMessage || '—' },
+ { label: 'SHA', className: 'nowrap', render: (branch) => branch.commit ?? '—' },
+ { label: 'Date', className: 'nowrap', render: (branch) => formatRelative(branch.commitAt) },
+ {
+ label: '',
+ render: (branch) =>
+ level >= LEVELS.DEV &&
+ branch.name !== repository.defaultBranch &&
+ !branch.protected &&
+ button(
+ 'Supprimer',
+ async () => {
+ if (!(await confirmAction('Supprimer la branche', `Supprimer « ${branch.name} » ?`))) return;
+ await api.delete(`${base}/branches`, { name: branch.name });
+ toast('Branche supprimée.');
+ refresh();
+ },
+ { tone: 'danger' },
+ ),
+ },
+ ],
+ repository.branches,
+ ),
+ );
+}
+
+function peopleTab(base, repository, level, refresh) {
+ return h(
+ 'div',
+ { class: 'stack' },
+ level >= LEVELS.OWNER &&
+ button(
+ 'Ajouter un collaborateur',
+ async () => {
+ const login = input({ placeholder: 'identifiant Gitea' });
+ const permission = select(
+ [
+ { value: 'read', label: 'Lecture' },
+ { value: 'write', label: 'Écriture' },
+ { value: 'admin', label: 'Administration' },
+ ],
+ { value: 'write' },
+ );
+ const confirmed = await modal(
+ 'Ajouter un collaborateur',
+ () => ({
+ node: h('div', { class: 'stack' }, field('Compte', login), field('Permission', permission)),
+ submit: () => login.value.trim() !== '',
+ }),
+ { confirmLabel: 'Ajouter', tone: 'primary' },
+ );
+ if (!confirmed) return;
+ await api.put(`${base}/collaborators/${encodeURIComponent(login.value.trim())}`, {
+ permission: permission.value,
+ });
+ toast('Collaborateur ajouté.');
+ refresh();
+ },
+ { tone: 'primary' },
+ ),
+ table(
+ [
+ {
+ label: 'Compte',
+ render: (user) =>
+ h(
+ 'div',
+ { class: 'row' },
+ user.avatar &&
+ h('img', {
+ src: user.avatar,
+ alt: '',
+ width: 24,
+ height: 24,
+ style: { borderRadius: '50%' },
+ }),
+ h('span', { text: user.login }),
+ ),
+ },
+ { label: 'Nom', render: (user) => user.fullName || '—' },
+ {
+ label: 'Droits',
+ render: (user) =>
+ h(
+ 'div',
+ { class: 'row' },
+ user.permissions?.admin && badge('Admin', 'danger'),
+ user.permissions?.push && badge('Écriture', 'info'),
+ user.permissions?.pull && badge('Lecture', 'neutral'),
+ ),
+ },
+ {
+ label: '',
+ render: (user) =>
+ level >= LEVELS.OWNER &&
+ button(
+ 'Retirer',
+ async () => {
+ if (!(await confirmAction('Retirer le collaborateur', `Retirer ${user.login} du dépôt ?`)))
+ return;
+ await api.delete(`${base}/collaborators/${encodeURIComponent(user.login)}`);
+ toast('Collaborateur retiré.');
+ refresh();
+ },
+ { tone: 'danger' },
+ ),
+ },
+ ],
+ repository.collaborators,
+ ),
+ );
+}
+
+function hooksTab(base, level) {
+ const host = h('div', { class: 'stack' });
+
+ const load = () =>
+ renderAsync(
+ host,
+ () => api.get(`${base}/hooks`),
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ notice(
+ 'Un webhook permet à Gitea de prévenir le bot en temps réel (issues, PR, commits, releases).',
+ 'info',
+ ),
+ level >= LEVELS.OWNER &&
+ button(
+ 'Brancher ce dépôt sur le bot',
+ async () => {
+ if (
+ !(await confirmAction(
+ 'Créer le webhook',
+ 'Gitea sera configuré pour envoyer les événements à ce bot, avec le secret déjà en place.',
+ ))
+ ) {
+ return;
+ }
+ const hook = await api.post(`${base}/hooks`, {});
+ toast(`Webhook créé vers ${hook.url}.`);
+ load();
+ },
+ { tone: 'primary' },
+ ),
+ table(
+ [
+ { label: 'URL', key: 'url' },
+ { label: 'Événements', render: (hook) => (hook.events ?? []).join(', ') },
+ {
+ label: 'Actif',
+ render: (hook) => (hook.active ? badge('Oui', 'success') : badge('Non', 'neutral')),
+ },
+ {
+ label: '',
+ render: (hook) =>
+ level >= LEVELS.OWNER &&
+ button(
+ 'Supprimer',
+ async () => {
+ if (!(await confirmAction('Supprimer le webhook', hook.url))) return;
+ await api.delete(`${base}/hooks/${hook.id}`);
+ toast('Webhook supprimé.');
+ load();
+ },
+ { tone: 'danger' },
+ ),
+ },
+ ],
+ data.hooks,
+ { empty: 'Aucun webhook sur ce dépôt.' },
+ ),
+ ),
+ );
+
+ load();
+ return host;
+}
+
+function actionsTab(base) {
+ const host = h('div', {});
+ renderAsync(
+ host,
+ () => api.get(`${base}/actions`),
+ (data) =>
+ data.available
+ ? table(
+ [
+ { label: 'Workflow', key: 'name' },
+ { label: 'Branche', key: 'headBranch' },
+ { label: 'Commit', key: 'headSha' },
+ {
+ label: 'État',
+ render: (task) =>
+ badge(
+ task.conclusion ?? task.status ?? '—',
+ task.conclusion === 'success'
+ ? 'success'
+ : task.conclusion === 'failure'
+ ? 'danger'
+ : 'warning',
+ ),
+ },
+ { label: 'Quand', className: 'nowrap', render: (task) => formatRelative(task.createdAt) },
+ ],
+ data.tasks,
+ { empty: 'Aucune exécution.' },
+ )
+ : notice('Gitea Actions n’est pas disponible sur ce dépôt ou cette version de Gitea.', 'info'),
+ );
+ return host;
+}
+
+function settingsTab(base, repository, level, refresh) {
+ if (level < LEVELS.DEV) return notice('Réservé aux niveaux Dev et Owner.', 'warning');
+
+ const description = input({ value: repository.description ?? '' });
+ const website = input({ value: repository.website ?? '' });
+ const defaultBranch = select(
+ repository.branches.map((branch) => ({ value: branch.name, label: branch.name })),
+ { value: repository.defaultBranch },
+ );
+
+ const switches = [
+ ['has_issues', 'Issues activées', repository.hasIssues],
+ ['has_pull_requests', 'Pull requests activées', repository.hasPullRequests],
+ ['has_releases', 'Releases activées', repository.hasReleases],
+ ['has_wiki', 'Wiki activé', repository.hasWiki],
+ ['has_actions', 'Gitea Actions activées', repository.hasActions],
+ ['allow_squash_merge', 'Autoriser le squash merge', repository.allowSquash],
+ ['allow_merge_commits', 'Autoriser le merge commit', repository.allowMergeCommits],
+ ['allow_rebase', 'Autoriser le rebase', repository.allowRebase],
+ ['private', 'Dépôt privé', repository.private],
+ ['archived', 'Dépôt archivé (lecture seule)', repository.archived],
+ ];
+ const values = Object.fromEntries(switches.map(([key, , value]) => [key, value]));
+
+ return h(
+ 'div',
+ { class: 'stack' },
+ card(
+ 'Identité',
+ {
+ actions: button(
+ 'Enregistrer',
+ async () => {
+ await api.patch(base, {
+ description: description.value,
+ website: website.value,
+ default_branch: defaultBranch.value,
+ });
+ toast('Dépôt mis à jour.');
+ refresh();
+ },
+ { tone: 'primary' },
+ ),
+ },
+ field('Description', description),
+ field('Site web', website),
+ field('Branche par défaut', defaultBranch),
+ ),
+
+ card(
+ 'Fonctionnalités',
+ {
+ actions: button(
+ 'Appliquer',
+ async () => {
+ await api.patch(base, values);
+ toast('Réglages appliqués.');
+ refresh();
+ },
+ { tone: 'primary' },
+ ),
+ },
+ ...switches.map(([key, label, value]) =>
+ toggle(Boolean(value), (checked) => (values[key] = checked), label),
+ ),
+ ),
+
+ level >= LEVELS.OWNER &&
+ card(
+ 'Zone de danger',
+ { subtitle: 'Ces actions sont irréversibles.' },
+ notice(
+ 'La suppression efface le dépôt, ses issues, ses PR et ses releases sur Gitea. Il n’y a pas de corbeille.',
+ 'error',
+ ),
+ button(
+ 'Supprimer ce dépôt',
+ async () => {
+ const ok = await confirmDangerous(
+ 'Supprimer le dépôt',
+ `Le dépôt ${repository.fullName} et tout son contenu seront définitivement supprimés.`,
+ repository.fullName,
+ );
+ if (!ok) return;
+ await api.delete(base, { confirm: repository.fullName });
+ toast('Dépôt supprimé.');
+ window.location.hash = '#/repos';
+ },
+ { tone: 'danger' },
+ ),
+ ),
+ );
+}
+
+function overviewTab(repository) {
+ const languages = Object.entries(repository.languages ?? {});
+ const total = languages.reduce((sum, [, bytes]) => sum + bytes, 0) || 1;
+
+ return h(
+ 'div',
+ { class: 'stack' },
+ card(
+ 'Chiffres',
+ {},
+ grid(
+ stat('Issues ouvertes', repository.openIssues, {
+ tone: repository.openIssues > 0 ? 'warning' : 'neutral',
+ }),
+ stat('PR ouvertes', repository.openPulls),
+ stat('Releases', repository.releases),
+ stat('Branches', repository.branches.length),
+ stat('Étoiles', repository.stars),
+ stat('Taille', formatBytes((repository.sizeKb ?? 0) * 1024)),
+ ),
+ ),
+
+ repository.latestRelease &&
+ card(
+ 'Dernière release',
+ {
+ actions: h('a', {
+ class: 'btn btn-ghost',
+ href: repository.latestRelease.htmlUrl,
+ target: '_blank',
+ rel: 'noreferrer',
+ text: '↗ Voir',
+ }),
+ },
+ h(
+ 'p',
+ {},
+ h('strong', { text: repository.latestRelease.tag }),
+ ' — ',
+ repository.latestRelease.name ?? '',
+ ),
+ h('p', { class: 'muted', text: `Publiée ${formatRelative(repository.latestRelease.publishedAt)}` }),
+ ),
+
+ languages.length > 0 &&
+ card(
+ 'Langages',
+ { advanced: true },
+ ...languages
+ .sort((a, b) => b[1] - a[1])
+ .map(([name, bytes]) =>
+ h(
+ 'div',
+ {},
+ h(
+ 'div',
+ { class: 'row', style: { justifyContent: 'space-between' } },
+ h('span', { text: name }),
+ h('span', { class: 'muted', text: `${((bytes / total) * 100).toFixed(1)} %` }),
+ ),
+ h('div', { class: 'bar' }, h('span', { style: { width: `${(bytes / total) * 100}%` } })),
+ ),
+ ),
+ ),
+
+ repository.topics.length > 0 &&
+ card(
+ 'Sujets',
+ { advanced: true },
+ h(
+ 'div',
+ { class: 'row' },
+ repository.topics.map((topic) => badge(topic, 'info')),
+ ),
+ ),
+
+ card(
+ 'Cloner',
+ { advanced: true },
+ h('pre', {}, h('code', { text: `git clone ${repository.cloneUrl}` })),
+ repository.sshUrl && h('pre', {}, h('code', { text: `git clone ${repository.sshUrl}` })),
+ ),
+ );
+}
+
+async function renderDetail(host, state, owner, name) {
+ const base = `/api/repositories/${encodeRepo(`${owner}/${name}`)}`;
+ const level = state.me.accessLevel;
+ mount(host, spinner());
+
+ let repository;
+ try {
+ repository = await api.get(base);
+ } catch (error) {
+ mount(host, notice(error.message, 'error'));
+ return;
+ }
+
+ const refresh = () => renderDetail(host, state, owner, name);
+ const body = h('div', { class: 'stack' });
+ const tabs = TABS.filter((tab) => level >= tab.level && (!tab.advanced || state.mode === 'advanced'));
+ let active = tabs[0].id;
+
+ const drawTab = () => {
+ const content = {
+ overview: () => overviewTab(repository),
+ issues: () => issuesTab(base, level),
+ pulls: () => pullsTab(base, level),
+ commits: () => commitsTab(base, repository.branches),
+ branches: () => branchesTab(base, repository, level, refresh),
+ people: () => peopleTab(base, repository, level, refresh),
+ hooks: () => hooksTab(base, level),
+ actions: () => actionsTab(base),
+ settings: () => settingsTab(base, repository, level, refresh),
+ };
+ mount(body, content[active]());
+ for (const control of tabBar.querySelectorAll('button')) {
+ control.classList.toggle('active', control.dataset.tab === active);
+ }
+ };
+
+ const tabBar = h(
+ 'div',
+ { class: 'tabs' },
+ tabs.map((tab) =>
+ h('button', {
+ type: 'button',
+ text: tab.label,
+ dataset: { tab: tab.id },
+ onClick: () => {
+ active = tab.id;
+ drawTab();
+ },
+ }),
+ ),
+ );
+
+ mount(
+ host,
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('p', { class: 'muted' }, h('a', { href: '#/repos', text: '← Tous les dépôts' })),
+ h('h1', { text: repository.fullName }),
+ h('p', { class: 'muted', text: repository.description || 'Sans description.' }),
+ h(
+ 'div',
+ { class: 'row' },
+ repository.private ? badge('Privé', 'warning') : badge('Public', 'success'),
+ repository.archived && badge('Archivé', 'neutral'),
+ badge(`Branche ${repository.defaultBranch}`, 'info'),
+ ),
+ ),
+ h(
+ 'div',
+ { class: 'row' },
+ h('a', {
+ class: 'btn btn-ghost',
+ href: repository.htmlUrl,
+ target: '_blank',
+ rel: 'noreferrer',
+ text: '↗ Gitea',
+ }),
+ h('a', {
+ class: 'btn btn-ghost',
+ href: `#/releases?repo=${repository.fullName}`,
+ text: 'Releases',
+ }),
+ ),
+ ),
+ repository.archived && notice('Ce dépôt est archivé : Gitea refusera toute écriture.', 'warning'),
+ tabBar,
+ body,
+ ),
+ );
+
+ drawTab();
+}
+
+export function render(host, { params, state }) {
+ if (params.length >= 2) return renderDetail(host, state, params[0], params[1]);
+ return renderList(host);
+}
diff --git a/src/web/public/views/settings.js b/src/web/public/views/settings.js
new file mode 100644
index 0000000..f565808
--- /dev/null
+++ b/src/web/public/views/settings.js
@@ -0,0 +1,476 @@
+import { api } from '../core/api.js';
+import { formatDate, formatRelative, h } from '../core/dom.js';
+import {
+ badge,
+ button,
+ card,
+ confirmAction,
+ confirmDangerous,
+ field,
+ grid,
+ input,
+ modal,
+ notice,
+ renderAsync,
+ select,
+ stat,
+ table,
+ toast,
+ toggle,
+} from '../core/ui.js';
+
+/** Settings tab: every knob the dashboard exposes, grouped by concern (M16-T10). */
+
+const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
+
+const keyValue = (rows) =>
+ table(
+ [
+ { label: 'Réglage', key: 'label' },
+ { label: 'Valeur', render: (row) => row.value ?? '—' },
+ ],
+ rows,
+ );
+
+function behaviourCard(data, level, reload) {
+ if (level < LEVELS.DEV) {
+ return card(
+ 'Comportement du bot',
+ { subtitle: 'Lecture seule : le niveau Dev est requis pour modifier ces réglages.' },
+ keyValue(
+ data.schema.map((setting) => ({
+ label: setting.label,
+ value: String(data.values[setting.key]),
+ })),
+ ),
+ );
+ }
+
+ return card(
+ 'Comportement du bot',
+ { subtitle: 'Appliqué immédiatement, sans redémarrage.' },
+ ...data.schema.map((setting) => {
+ const apply = async (value) => {
+ await api.put(`/api/settings/values/${setting.key}`, { value });
+ toast(`« ${setting.label} » enregistré.`);
+ };
+
+ if (setting.type === 'bool') {
+ return h(
+ 'div',
+ {},
+ toggle(Boolean(data.values[setting.key]), apply, setting.label),
+ h('div', { class: 'field-help', text: setting.help }),
+ );
+ }
+ return field(
+ setting.label,
+ select(
+ setting.options.map((option) => ({ value: option, label: option })),
+ { value: data.values[setting.key], onChange: (event) => apply(event.target.value) },
+ ),
+ { help: setting.help },
+ );
+ }),
+ button('Recharger', reload, { tone: 'ghost' }),
+ );
+}
+
+const testButton = (service, label) =>
+ button(
+ label,
+ async () => {
+ const result = await api.post(`/api/settings/test/${service}`, {});
+ toast(result.detail, result.ok ? 'success' : 'error');
+ },
+ { tone: 'ghost' },
+ );
+
+function connectionsCard(data) {
+ return h(
+ 'div',
+ { class: 'stack' },
+ card(
+ 'Discord',
+ { actions: testButton('discord', 'Tester la connexion') },
+ grid(
+ stat('Token', data.discord.tokenConfigured ? 'Configuré' : 'Manquant', {
+ tone: data.discord.tokenConfigured ? 'success' : 'danger',
+ }),
+ stat('Application ID', data.discord.clientId || '—'),
+ stat('Serveur', data.discord.guildId || '—'),
+ ),
+ h('h3', { class: 'advanced-only', text: 'Rôles FWS' }),
+ h(
+ 'div',
+ { class: 'advanced-only' },
+ keyValue(Object.entries(data.discord.roles).map(([label, value]) => ({ label, value }))),
+ ),
+ h('h3', { class: 'advanced-only', text: 'Salons' }),
+ h(
+ 'div',
+ { class: 'advanced-only' },
+ keyValue(Object.entries(data.discord.channels).map(([label, value]) => ({ label, value }))),
+ ),
+ ),
+
+ card(
+ 'Gitea',
+ { actions: testButton('gitea', 'Tester le jeton') },
+ grid(
+ stat('Instance', data.gitea.url || '—'),
+ stat('Organisation', data.gitea.owner || '—'),
+ stat('Dépôt principal', data.gitea.repo || '—'),
+ stat('Jeton', data.gitea.tokenConfigured ? 'Configuré' : 'Manquant', {
+ tone: data.gitea.tokenConfigured ? 'success' : 'warning',
+ }),
+ ),
+ h(
+ 'div',
+ { class: 'row advanced-only' },
+ badge(`Délai ${data.gitea.timeoutMs} ms`),
+ badge(`${data.gitea.maxRetries} tentative(s) de secours`),
+ ),
+ ),
+
+ card(
+ 'Webhooks Gitea',
+ {},
+ grid(
+ stat('État', data.webhook.enabled ? 'Activés' : 'Désactivés', {
+ tone: data.webhook.enabled ? 'success' : 'neutral',
+ }),
+ stat('Secret', data.webhook.secretConfigured ? 'Configuré' : 'Manquant', {
+ tone: data.webhook.secretConfigured ? 'success' : 'warning',
+ }),
+ stat('Port', data.webhook.port),
+ ),
+ data.webhook.publicUrl &&
+ h(
+ 'div',
+ {},
+ h('p', { class: 'muted', text: 'URL à renseigner dans Gitea → Paramètres → Webhooks :' }),
+ h('pre', {}, h('code', { text: data.webhook.publicUrl })),
+ ),
+ data.webhook.enabled &&
+ !data.webhook.secretConfigured &&
+ notice('Les webhooks sont activés sans secret : tous les événements seront rejetés.', 'error'),
+ ),
+
+ card(
+ 'Tableau de bord',
+ { advanced: true },
+ grid(
+ stat('Écoute', `${data.web.host}:${data.web.port}`),
+ stat('URL publique', data.web.publicUrl || '—'),
+ stat('Connexion Discord', data.web.oauthConfigured ? 'Prête' : 'Non configurée', {
+ tone: data.web.oauthConfigured ? 'success' : 'warning',
+ }),
+ stat('Durée de session', `${data.web.sessionTtlHours} h`),
+ ),
+ h(
+ 'div',
+ {},
+ h('p', { class: 'muted', text: 'URL de redirection à déclarer dans le Developer Portal :' }),
+ h('pre', {}, h('code', { text: data.web.redirectUri })),
+ ),
+ h(
+ 'div',
+ { class: 'row' },
+ badge(
+ data.web.allowCommandDeploys ? 'Déploiements shell autorisés' : 'Déploiements shell bloqués',
+ data.web.allowCommandDeploys ? 'warning' : 'neutral',
+ ),
+ badge(data.web.allowRestart ? 'Redémarrage autorisé' : 'Redémarrage bloqué', 'neutral'),
+ badge(`${data.web.rateLimitPerMinute} req/min`, 'neutral'),
+ ),
+ ),
+ );
+}
+
+function sessionsCard(reload) {
+ const host = h('div', {});
+ renderAsync(
+ host,
+ () => api.get('/api/settings/sessions'),
+ (data) =>
+ table(
+ [
+ {
+ label: 'Personne',
+ render: (session) =>
+ h(
+ 'div',
+ { class: 'row' },
+ session.avatar &&
+ h('img', {
+ src: session.avatar,
+ alt: '',
+ width: 24,
+ height: 24,
+ style: { borderRadius: '50%' },
+ }),
+ h('span', { text: session.display_name ?? session.username ?? '—' }),
+ session.current && badge('Cette session', 'info'),
+ ),
+ },
+ { label: 'Niveau', render: (session) => badge(session.accessLabel, 'neutral') },
+ { label: 'Origine', key: 'source' },
+ { label: 'IP', className: 'advanced-only', key: 'ip' },
+ {
+ label: 'Dernière activité',
+ className: 'nowrap',
+ render: (session) => formatRelative(session.last_seen_at),
+ },
+ {
+ label: 'Expire',
+ className: 'nowrap advanced-only',
+ render: (session) => formatDate(session.expires_at),
+ },
+ {
+ label: '',
+ render: (session) =>
+ !session.current &&
+ button(
+ 'Révoquer',
+ async () => {
+ if (!(await confirmAction('Révoquer la session', 'Cette personne devra se reconnecter.')))
+ return;
+ await api.delete(`/api/settings/sessions/${session.id}`);
+ toast('Session révoquée.');
+ reload();
+ },
+ { tone: 'danger' },
+ ),
+ },
+ ],
+ data.sessions,
+ { empty: 'Aucune session active.' },
+ ),
+ );
+ return card('Sessions ouvertes', { subtitle: 'Qui est connecté au tableau de bord en ce moment.' }, host);
+}
+
+function tokensCard(reload) {
+ const host = h('div', {});
+
+ const load = () =>
+ renderAsync(
+ host,
+ () => api.get('/api/settings/tokens'),
+ (data) =>
+ table(
+ [
+ { label: 'Nom', key: 'name' },
+ { label: 'Préfixe', className: 'nowrap', key: 'prefix' },
+ { label: 'Niveau', render: (token) => badge(token.accessLabel, 'neutral') },
+ { label: 'Créé', className: 'nowrap', render: (token) => formatRelative(token.created_at) },
+ {
+ label: 'Dernier usage',
+ className: 'nowrap',
+ render: (token) => (token.last_used_at ? formatRelative(token.last_used_at) : 'jamais'),
+ },
+ {
+ label: 'État',
+ render: (token) => (token.active ? badge('Actif', 'success') : badge('Révoqué', 'neutral')),
+ },
+ {
+ label: '',
+ render: (token) =>
+ token.active &&
+ button(
+ 'Révoquer',
+ async () => {
+ if (!(await confirmAction('Révoquer le jeton', token.name))) return;
+ await api.delete(`/api/settings/tokens/${token.id}`);
+ toast('Jeton révoqué.');
+ load();
+ },
+ { tone: 'danger' },
+ ),
+ },
+ ],
+ data.tokens,
+ { empty: 'Aucun jeton d’API.' },
+ ),
+ );
+
+ load();
+
+ return card(
+ 'Jetons d’API',
+ {
+ subtitle: 'Pour appeler cette API depuis un script ou une CI, sans compte Discord.',
+ actions: button(
+ 'Créer un jeton',
+ async () => {
+ const name = input({ placeholder: 'ci-deploiement' });
+ const level = select(
+ [
+ { value: '1', label: 'Staff — lecture' },
+ { value: '2', label: 'Dev — écriture' },
+ { value: '3', label: 'Owner — tout' },
+ ],
+ { value: '1' },
+ );
+ const confirmed = await modal(
+ 'Nouveau jeton d’API',
+ () => ({
+ node: h('div', { class: 'stack' }, field('Nom', name), field('Niveau d’accès', level)),
+ submit: () => name.value.trim().length >= 3,
+ }),
+ { confirmLabel: 'Créer', tone: 'primary' },
+ );
+ if (!confirmed) return;
+
+ const result = await api.post('/api/settings/tokens', {
+ name: name.value.trim(),
+ accessLevel: Number(level.value),
+ });
+ await modal(
+ 'Jeton créé',
+ () => ({
+ node: h(
+ 'div',
+ { class: 'stack' },
+ notice('Copie ce jeton maintenant : il ne sera plus jamais affiché.', 'warning'),
+ h('pre', {}, h('code', { text: result.token })),
+ h('p', { class: 'muted', text: 'À envoyer en en-tête `Authorization: Bearer `.' }),
+ ),
+ submit: () => true,
+ }),
+ { confirmLabel: 'J’ai copié' },
+ );
+ load();
+ reload();
+ },
+ { tone: 'primary' },
+ ),
+ },
+ host,
+ );
+}
+
+function maintenanceCard(data) {
+ return card(
+ 'Maintenance',
+ { subtitle: `Base : ${data.runtime.databasePath}` },
+ grid(
+ stat('Environnement', data.runtime.nodeEnv),
+ stat('Niveau de log', data.runtime.logLevel),
+ stat('Rétention', `${data.runtime.logRetentionDays} jours`),
+ stat('PID', data.runtime.pid),
+ ),
+ h(
+ 'div',
+ { class: 'row' },
+ button(
+ 'Sauvegarder la base',
+ async () => {
+ const result = await api.post('/api/settings/backup', {});
+ toast(`Sauvegarde écrite : ${result.file}`);
+ },
+ { tone: 'primary' },
+ ),
+ button(
+ 'Purger les anciens événements',
+ async () => {
+ const result = await api.post('/api/settings/purge', {});
+ toast(`${result.events} événement(s) et ${result.sessions} session(s) supprimés.`);
+ },
+ { tone: 'ghost' },
+ ),
+ data.web.allowRestart &&
+ button(
+ 'Redémarrer le bot',
+ async () => {
+ const ok = await confirmDangerous(
+ 'Redémarrer le bot',
+ 'Le processus va s’arrêter. Sans superviseur (systemd, pm2, Docker), il ne redémarrera pas tout seul.',
+ 'redemarrer',
+ );
+ if (!ok) return;
+ await api.post('/api/settings/restart', {});
+ toast('Redémarrage demandé.', 'info');
+ },
+ { tone: 'danger' },
+ ),
+ ),
+ !data.web.allowRestart &&
+ h('p', { class: 'muted', text: 'Le redémarrage depuis le site est désactivé (`WEB_ALLOW_RESTART`).' }),
+ );
+}
+
+function referenceCard(data) {
+ return card(
+ 'Référence',
+ { advanced: true, subtitle: 'Ce que le bot connaît, pour se repérer.' },
+ h('h3', { text: 'Niveaux d’accès' }),
+ table(
+ [
+ { label: 'Nom', key: 'name' },
+ { label: 'Valeur', className: 'num', key: 'value' },
+ { label: 'Libellé Discord', key: 'label' },
+ ],
+ data.reference.accessLevels,
+ ),
+ h('h3', { text: 'Catégories de tickets' }),
+ table(
+ [
+ { label: 'Identifiant', key: 'id' },
+ { label: 'Libellé', key: 'label' },
+ { label: 'Visible par', render: (category) => category.scope.join(', ') },
+ ],
+ data.reference.ticketCategories,
+ ),
+ h('h3', { text: 'Types de notification' }),
+ h(
+ 'div',
+ { class: 'row' },
+ data.reference.notificationTypes.map((type) => badge(type, 'info')),
+ ),
+ );
+}
+
+export function render(host, { state }) {
+ const level = state.me.accessLevel;
+ const reload = () => render(host, { state });
+
+ return renderAsync(
+ host,
+ () => api.get('/api/settings'),
+ (data) =>
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: 'Paramètres' }),
+ h('p', {
+ class: 'muted',
+ text: 'Les réglages du bot, ses connexions et la sécurité du tableau de bord.',
+ }),
+ ),
+ level >= LEVELS.OWNER &&
+ h('a', { class: 'btn btn-primary', href: '#/setup', text: 'Assistant de configuration .env' }),
+ ),
+
+ level >= LEVELS.OWNER &&
+ notice(
+ 'Les valeurs du fichier .env ne sont lues qu’au démarrage. L’assistant les modifie, un redémarrage les applique.',
+ 'info',
+ ),
+
+ behaviourCard(data, level, reload),
+ connectionsCard(data),
+ level >= LEVELS.OWNER ? sessionsCard(reload) : null,
+ level >= LEVELS.OWNER ? tokensCard(reload) : null,
+ level >= LEVELS.OWNER ? maintenanceCard(data) : null,
+ referenceCard(data),
+ ),
+ );
+}
diff --git a/src/web/public/views/setup.js b/src/web/public/views/setup.js
new file mode 100644
index 0000000..3014c9f
--- /dev/null
+++ b/src/web/public/views/setup.js
@@ -0,0 +1,394 @@
+import { api } from '../core/api.js';
+import { h, mount, richText } from '../core/dom.js';
+import { button, card, field, input, notice, select, spinner, toast, toggle } from '../core/ui.js';
+
+/**
+ * Step by step `.env` wizard (M16-T09).
+ *
+ * Walks through one section at a time: what the section is for, how to obtain
+ * each value, then the fields themselves with live validation. Nothing is
+ * written until « Enregistrer » is pressed, and the previous file is backed up.
+ */
+
+const stateOf = (data) => ({
+ data,
+ /** Only the fields the user actually touched. */
+ edits: {},
+ step: 0,
+ showAdvanced: false,
+ errors: { ...data.errors },
+ warnings: [...data.warnings],
+ missing: [...data.missingRequired],
+ diff: [],
+ lastSave: null,
+});
+
+const valueOf = (view, key) => view.edits[key] ?? view.data.values[key] ?? '';
+
+/** Step texts reference other fields, so they always show the values being typed. */
+const fillPlaceholders = (view, text) =>
+ text
+ .replaceAll('{WEB_PUBLIC_URL}', valueOf(view, 'WEB_PUBLIC_URL') || 'https://ton-domaine')
+ .replaceAll('{WEBHOOK_PATH}', valueOf(view, 'WEBHOOK_PATH') || '/webhooks/gitea');
+
+/** A section is complete when none of its variables is in error or missing. */
+function sectionStatus(view, sectionId) {
+ const variables = view.data.variables.filter((variable) => variable.section === sectionId);
+ const invalid = variables.some((variable) => view.errors[variable.key]);
+ const missing = variables.some((variable) => view.missing.includes(variable.key));
+ const filled = variables.some((variable) => {
+ const value = valueOf(view, variable.key);
+ return value !== '' || view.data.secrets[variable.key];
+ });
+ return { invalid, missing, filled };
+}
+
+export async function render(host, { standalone = false } = {}) {
+ mount(host, spinner('Lecture de la configuration…'));
+
+ const data = await api.get('/api/configuration');
+ const view = stateOf(data);
+ const container = standalone
+ ? h('div', { class: 'main', style: { maxWidth: '1100px', margin: '0 auto' } })
+ : h('div', {});
+ mount(host, container);
+
+ let validateTimer = null;
+ const scheduleValidation = () => {
+ clearTimeout(validateTimer);
+ validateTimer = setTimeout(async () => {
+ const result = await api.post('/api/configuration/validate', { values: view.edits }).catch(() => null);
+ if (!result) return;
+ view.errors = result.errors;
+ view.warnings = result.warnings;
+ view.missing = result.missingRequired;
+ view.diff = result.diff;
+ draw();
+ }, 350);
+ };
+
+ const setValue = (key, value) => {
+ view.edits[key] = value;
+ scheduleValidation();
+ };
+
+ function controlFor(variable) {
+ const key = variable.key;
+ const current = valueOf(view, key);
+
+ if (variable.type === 'bool') {
+ return toggle(current === 'true', (checked) => {
+ setValue(key, checked ? 'true' : 'false');
+ draw();
+ });
+ }
+
+ if (variable.type === 'enum') {
+ return select(
+ variable.options.map((option) => ({ value: option, label: option })),
+ { value: current, onChange: (event) => setValue(key, event.target.value) },
+ );
+ }
+
+ const control = input({
+ type: variable.type === 'secret' ? 'password' : 'text',
+ value: current,
+ placeholder: variable.placeholder ?? variable.default ?? '',
+ autocomplete: 'off',
+ spellcheck: 'false',
+ onInput: (event) => setValue(key, event.target.value),
+ });
+
+ if (variable.type !== 'secret' && !variable.generator && !variable.testable) return control;
+
+ const extras = [control];
+ if (variable.generator) {
+ extras.push(
+ button(
+ 'Générer',
+ async () => {
+ const { value } = await api.post('/api/configuration/generate', { kind: variable.generator });
+ control.value = value;
+ setValue(key, value);
+ toast('Secret généré. Il ne sera visible qu’ici.', 'info');
+ },
+ { tone: 'ghost' },
+ ),
+ );
+ }
+ if (variable.testable) {
+ extras.push(
+ button(
+ 'Tester',
+ async () => {
+ const result = await api.post(`/api/configuration/test/${variable.testable}`, {
+ values: view.edits,
+ });
+ toast(result.detail, result.ok ? (result.warning ? 'info' : 'success') : 'error');
+ },
+ { tone: 'ghost' },
+ ),
+ );
+ }
+ return h('div', { class: 'secret-row' }, ...extras);
+ }
+
+ function fieldFor(variable) {
+ const key = variable.key;
+ const isSecretSet = variable.type === 'secret' && view.data.secrets[key] && !(key in view.edits);
+ const help = [
+ variable.help,
+ isSecretSet ? 'Une valeur est déjà enregistrée : laisse vide pour la conserver.' : null,
+ variable.restartRequired ? 'Prise en compte au prochain démarrage du bot.' : null,
+ ]
+ .filter(Boolean)
+ .join(' ');
+
+ const wrapper = field(`${variable.label}${variable.required ? ' *' : ''}`, controlFor(variable), {
+ help,
+ error: view.errors[key],
+ });
+ wrapper.append(
+ h('span', { class: 'field-help', text: key, style: { fontFamily: 'var(--mono)', opacity: '0.6' } }),
+ );
+ return variable.advanced ? h('div', { class: 'advanced-wrapper' }, wrapper) : wrapper;
+ }
+
+ async function showPreview() {
+ const { content } = await api.post('/api/configuration/preview', { values: view.edits });
+ mount(
+ previewHost,
+ card(
+ 'Aperçu du fichier .env',
+ { subtitle: 'Les secrets sont masqués dans cet aperçu.' },
+ h('pre', {}, h('code', { text: content })),
+ ),
+ );
+ }
+
+ async function save({ force = false } = {}) {
+ try {
+ const result = await api.post('/api/configuration/save', { values: view.edits, force });
+ view.lastSave = result;
+ view.edits = {};
+ view.data = await api.get('/api/configuration');
+ view.errors = view.data.errors;
+ view.warnings = view.data.warnings;
+ view.missing = view.data.missingRequired;
+ view.diff = [];
+ toast(result.written ? 'Configuration enregistrée.' : 'Aucun changement à enregistrer.', 'success');
+ draw();
+ } catch (error) {
+ toast(error.message, 'error');
+ if (error.details) {
+ view.errors = error.details;
+ draw();
+ }
+ }
+ }
+
+ const previewHost = h('div', {});
+
+ function stepList() {
+ return h(
+ 'div',
+ { class: 'wizard-steps' },
+ view.data.sections.map((section, index) => {
+ const status = sectionStatus(view, section.id);
+ const classes = ['wizard-step'];
+ if (index === view.step) classes.push('active');
+ if (status.invalid || status.missing) classes.push('invalid');
+ else if (status.filled) classes.push('done');
+
+ return h(
+ 'button',
+ {
+ class: classes.join(' '),
+ type: 'button',
+ onClick: () => {
+ view.step = index;
+ draw();
+ },
+ },
+ h('span', { class: 'dot', text: status.invalid || status.missing ? '!' : String(index + 1) }),
+ h(
+ 'span',
+ {},
+ h('strong', { text: section.title }),
+ h('span', { class: 'muted', text: section.summary }),
+ ),
+ );
+ }),
+ );
+ }
+
+ function stepBody() {
+ const section = view.data.sections[view.step];
+ const variables = view.data.variables.filter(
+ (variable) => variable.section === section.id && (view.showAdvanced || !variable.advanced),
+ );
+ const hiddenCount = view.data.variables.filter(
+ (variable) => variable.section === section.id && variable.advanced,
+ ).length;
+
+ return card(
+ section.title,
+ {
+ subtitle: section.summary,
+ actions: [
+ button(
+ view.step === 0 ? '' : '← Précédent',
+ () => {
+ view.step = Math.max(0, view.step - 1);
+ draw();
+ },
+ { tone: 'ghost', disabled: view.step === 0 },
+ ),
+ button(
+ 'Suivant →',
+ () => {
+ view.step = Math.min(view.data.sections.length - 1, view.step + 1);
+ draw();
+ },
+ { tone: 'ghost', disabled: view.step === view.data.sections.length - 1 },
+ ),
+ ],
+ },
+ section.intro && h('p', { text: section.intro }),
+
+ section.steps?.length > 0 &&
+ h(
+ 'ol',
+ { class: 'steps-list' },
+ section.steps.map((step) => h('li', {}, richText(fillPlaceholders(view, step), 'rich-inline'))),
+ ),
+
+ section.links?.length > 0 &&
+ h(
+ 'div',
+ { class: 'row' },
+ section.links.map((link) =>
+ h('a', {
+ class: 'btn btn-ghost',
+ href: link.url,
+ target: '_blank',
+ rel: 'noreferrer',
+ text: `↗ ${link.label}`,
+ }),
+ ),
+ ),
+
+ hiddenCount > 0 &&
+ toggle(
+ view.showAdvanced,
+ (checked) => {
+ view.showAdvanced = checked;
+ draw();
+ },
+ `Afficher les ${hiddenCount} options avancées`,
+ ),
+
+ ...variables.map(fieldFor),
+ );
+ }
+
+ function summary() {
+ const blocking = view.missing.length > 0 || Object.keys(view.errors).length > 0;
+
+ return card(
+ 'Enregistrement',
+ {
+ subtitle: view.data.exists
+ ? 'Le fichier .env actuel sera sauvegardé avant d’être remplacé.'
+ : 'Aucun .env pour l’instant : il sera créé avec les permissions 600.',
+ actions: [
+ button('Aperçu', showPreview, { tone: 'ghost' }),
+ button('Enregistrer le .env', () => save(), { tone: 'primary', disabled: blocking }),
+ ],
+ },
+
+ view.missing.length > 0 &&
+ notice(`Valeurs obligatoires manquantes : ${view.missing.join(', ')}.`, 'error'),
+
+ Object.keys(view.errors).length > 0 &&
+ notice(
+ `${Object.keys(view.errors).length} champ(s) invalide(s) : ${Object.keys(view.errors).join(', ')}.`,
+ 'error',
+ ),
+
+ ...view.warnings.map((warning) => notice(warning, 'warning')),
+
+ view.diff.length > 0 &&
+ h(
+ 'div',
+ { class: 'stack' },
+ h('h3', { text: `${view.diff.length} changement(s) en attente` }),
+ h(
+ 'div',
+ { class: 'diff stack' },
+ view.diff.map((entry) =>
+ h(
+ 'div',
+ {},
+ h('strong', { text: `${entry.key} ` }),
+ h('del', { text: entry.before || '(vide)' }),
+ ' → ',
+ h('ins', { text: entry.after || '(vide)' }),
+ entry.restartRequired && h('span', { class: 'muted', text: ' · redémarrage requis' }),
+ ),
+ ),
+ ),
+ ),
+
+ view.lastSave?.written &&
+ notice(
+ `Fichier écrit.${view.lastSave.backup ? ` Sauvegarde : ${view.lastSave.backup}.` : ''}${
+ view.lastSave.restartRequired ? ' Redémarre le bot pour appliquer les changements.' : ''
+ }`,
+ 'success',
+ ),
+
+ view.data.unknownKeys.length > 0 &&
+ notice(
+ `Variables inconnues conservées telles quelles : ${view.data.unknownKeys.join(', ')}.`,
+ 'info',
+ ),
+ );
+ }
+
+ function draw() {
+ mount(
+ container,
+ h(
+ 'div',
+ { class: 'stack' },
+ h(
+ 'div',
+ { class: 'page-head' },
+ h(
+ 'div',
+ {},
+ h('h1', { text: 'Configuration du bot' }),
+ h('p', {
+ class: 'muted',
+ text: 'Chaque valeur est expliquée, vérifiée puis écrite dans le fichier .env. Rien n’est enregistré avant ta validation.',
+ }),
+ ),
+ ),
+ standalone &&
+ notice(
+ 'Session d’amorçage : seule cette page est accessible. Une fois le .env enregistré, redémarre le bot et connecte-toi avec Discord.',
+ 'info',
+ ),
+ h(
+ 'div',
+ { class: 'wizard' },
+ stepList(),
+ h('div', { class: 'stack' }, stepBody(), summary(), previewHost),
+ ),
+ ),
+ );
+ }
+
+ draw();
+}
diff --git a/src/web/server.js b/src/web/server.js
new file mode 100644
index 0000000..e58550f
--- /dev/null
+++ b/src/web/server.js
@@ -0,0 +1,136 @@
+import { createServer } from 'node:http';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { env } from '../config/env.js';
+import { ExternalApiError, PermissionDeniedError, UserFacingError } from '../core/errors.js';
+import { createLogger } from '../core/logger.js';
+import { handleGiteaWebhook } from '../webhooks/gitea-webhook.js';
+import { registerApiRoutes } from './api/index.js';
+import { authenticate, assertSameOrigin } from './auth/session.js';
+import { authorize } from './auth/guard.js';
+import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js';
+import { createRouter } from './router.js';
+
+/** HTTP server of the dashboard (M16-T01). */
+
+const log = createLogger('web');
+const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
+
+/** Sliding window per client address, reset every minute. */
+function createRateLimiter(limit) {
+ const hits = new Map();
+ let windowStart = Date.now();
+
+ return (key) => {
+ const now = Date.now();
+ if (now - windowStart >= 60_000) {
+ hits.clear();
+ windowStart = now;
+ }
+ const count = (hits.get(key) ?? 0) + 1;
+ hits.set(key, count);
+ return count <= limit;
+ };
+}
+
+function statusOf(error) {
+ if (error instanceof HttpError) return error.status;
+ if (error instanceof PermissionDeniedError) return 403;
+ if (error instanceof UserFacingError) return 400;
+ if (error instanceof ExternalApiError) return 502;
+ return 500;
+}
+
+/**
+ * Builds the request handler. Exported on its own so the tests can drive it
+ * without opening a socket.
+ */
+export function createHandler({ client = null, setupOnly = false, startedAt = Date.now() } = {}) {
+ const router = registerApiRoutes(createRouter(), { setupOnly });
+ const context = { client, setupOnly, startedAt };
+ const allowWithinRate = createRateLimiter(env.web.rateLimitPerMinute);
+
+ // The webhook shares the port when both servers are configured on it.
+ const sharesWebhookPort = env.webhook.enabled && env.webhook.port === env.web.port;
+
+ return async function handle(request, response) {
+ const url = new URL(request.url, `http://${request.headers.host ?? 'localhost'}`);
+ const pathname = url.pathname;
+
+ if (sharesWebhookPort && request.method === 'POST' && pathname === env.webhook.path) {
+ try {
+ const rawBody = await readRawBody(request);
+ response.writeHead(await handleGiteaWebhook(client, request.headers, rawBody)).end();
+ } catch (error) {
+ log.error('Webhook handling failed', error);
+ response.writeHead(500).end();
+ }
+ return;
+ }
+
+ const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/');
+ if (!isApi) {
+ // Anything else is the single page application; unknown paths fall back to
+ // its shell so client-side routing works on a hard refresh.
+ const served = await sendStatic(response, publicDir, pathname, { fallback: 'index.html' });
+ if (!served) sendEmpty(response, 404);
+ return;
+ }
+
+ if (!allowWithinRate(request.socket.remoteAddress ?? 'unknown')) {
+ sendJson(response, 429, { error: 'Trop de requêtes, réessaie dans une minute.' });
+ return;
+ }
+
+ try {
+ const route = router.resolve(request.method, pathname);
+ const actor = authenticate(request);
+ assertSameOrigin(request, actor);
+ authorize(actor, route.options);
+
+ const body = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(request.method)
+ ? await readJsonBody(request)
+ : {};
+
+ const result = await route.handler({
+ request,
+ response,
+ params: route.params,
+ query: url.searchParams,
+ body,
+ actor,
+ context,
+ });
+
+ // A handler that wrote the response itself (a redirect) returns nothing.
+ if (!response.headersSent) sendJson(response, 200, result ?? { ok: true });
+ } catch (error) {
+ const status = statusOf(error);
+ if (status >= 500) log.error(`${request.method} ${pathname} failed`, error);
+ else log.debug(`${request.method} ${pathname} rejected with ${status}`, { message: error.message });
+
+ if (!response.headersSent) {
+ sendJson(response, status, {
+ error: status >= 500 ? 'Une erreur interne est survenue.' : error.message,
+ ...(error.details && { details: error.details }),
+ });
+ }
+ }
+ };
+}
+
+export function startWebServer({ client = null, setupOnly = false } = {}) {
+ const server = createServer(createHandler({ client, setupOnly, startedAt: Date.now() }));
+
+ server.listen(env.web.port, env.web.host, () => {
+ const url = env.web.publicUrl || `http://${env.web.host}:${env.web.port}`;
+ log.info(`Dashboard listening on ${env.web.host}:${env.web.port}`, { url, setupOnly });
+ });
+ server.on('error', (error) => log.error('Dashboard server error', error));
+ return server;
+}
+
+/** True when the webhook server does not need its own port. */
+export function webhookSharesWebPort() {
+ return env.web.enabled && env.webhook.enabled && env.webhook.port === env.web.port;
+}