diff --git a/.env.example b/.env.example index 6216568..5c9f6b3 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,8 @@ CHANNEL_NOTIF_RELEASES_ID= CHANNEL_NOTIF_ERRORS_ID= # Category under which private ticket channels are created (M6) CATEGORY_TICKETS_ID= +# Où le bot publie les candidatures Gitea (repli : CHANNEL_LOGS_ID) +CHANNEL_GITEA_APPLICATIONS_ID= # --- Salons vocaux temporaires (M14) ---------------------------------------- # Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire @@ -59,6 +61,10 @@ GITEA_URL=https://gitea.nocode-var.tech GITEA_TOKEN= GITEA_OWNER=FWS GITEA_REPO=FWS-Arch +# Organisation qui accueille les personnes recrutées (défaut : GITEA_OWNER) +GITEA_ORG=FWS +# Équipe de l'organisation où elles sont ajoutées à l'acceptation +GITEA_DEV_TEAM=Dev GITEA_TIMEOUT_MS=10000 GITEA_MAX_RETRIES=2 diff --git a/README.en.md b/README.en.md index 7f7f268..a0c39d6 100644 --- a/README.en.md +++ b/README.en.md @@ -142,14 +142,16 @@ Full template: [`.env.example`](.env.example). Default values in brackets. ### Gitea -| Variable | Default | Description | -| ------------------- | ------- | ---------------------------------------------------------------------- | -| `GITEA_URL` | — | Instance URL (without a trailing `/`) | -| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged | -| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) | -| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) | -| `GITEA_TIMEOUT_MS` | `10000` | Request timeout | -| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) | +| Variable | Default | Description | +| ------------------- | ------------- | ---------------------------------------------------------------------- | +| `GITEA_URL` | — | Instance URL (without a trailing `/`) | +| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged | +| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) | +| `GITEA_ORG` | `GITEA_OWNER` | Organization that hosts recruited people | +| `GITEA_DEV_TEAM` | `Dev` | Gitea team they join on acceptance | +| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) | +| `GITEA_TIMEOUT_MS` | `10000` | Request timeout | +| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) | ### Gitea webhooks diff --git a/README.md b/README.md index f5cf218..eae73cd 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare | `CHANNEL_NOTIF_RELEASES_ID` | Notifications releases | | `CHANNEL_NOTIF_ERRORS_ID` | Erreurs et incidents | | `CATEGORY_TICKETS_ID` | Catégorie où sont créés les salons de tickets privés | +| `CHANNEL_GITEA_APPLICATIONS_ID` | Candidatures Gitea : repli sur `CHANNEL_LOGS_ID` | | `CHANNEL_VOICE_TRIGGER_ID` | Salon vocal déclencheur (repli : `/voice setup` gère une liste de déclencheurs) | | `CATEGORY_VOICE_ID` | Catégorie d'accueil des salons vocaux créés (facultatif) | @@ -148,6 +149,8 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare | `GITEA_URL` | — | URL de l'instance (sans `/` final) | | `GITEA_TOKEN` | — | Token à moindre privilège (`read:repository`, `write:issue`). Jamais loggé | | `GITEA_OWNER` | — | Propriétaire du dépôt (ex. `FWS`) | +| `GITEA_ORG` | `GITEA_OWNER` | Organisation qui accueille les personnes recrutées | +| `GITEA_DEV_TEAM` | `Dev` | Équipe Gitea où elles sont ajoutées à l'acceptation | | `GITEA_REPO` | — | Dépôt ciblé (ex. `FWS-Arch`) | | `GITEA_TIMEOUT_MS` | `10000` | Timeout des requêtes | | `GITEA_MAX_RETRIES` | `2` | Tentatives sur erreurs transitoires (429, 5xx, timeout) | @@ -230,6 +233,7 @@ Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) : | `/pr list` | — | User | ✅ | PR ouvertes (15 dernières) | | `/gitea activity` | — | User | ✅ | Derniers commits + issues et PR ouvertes | | `/gitea release` | — | User | ✅ | Releases de FWS Arch (5 dernières) | +| `/gitea panel` | — (modale) | **Staff** | ✅ | Publie ou modifie le panneau de recrutement Gitea | > Le client Gitea (`src/services/gitea/gitea-client.js`) : REST avec token, timeout, retry exponentiel sur erreurs transitoires. Les formulaires (`/issue create`, `/pr create`) passent par une **modale** ; les options de branches y sont conservées en mémoire quelques minutes (`pending-actions.js`). Toute panne (token absent, 404, 5xx) devient un message éphémère explicite, jamais une erreur brute. diff --git a/src/commands/gitea/gitea.js b/src/commands/gitea/gitea.js index 54c65ab..131971c 100644 --- a/src/commands/gitea/gitea.js +++ b/src/commands/gitea/gitea.js @@ -2,15 +2,21 @@ import { SlashCommandBuilder } from 'discord.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js'; +import { openPanelEditor } from '../../services/gitea/team-recruitment.js'; import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; export const access = ACCESS_LEVELS.USER; +export const subcommandAccess = { panel: ACCESS_LEVELS.STAFF }; + export const data = new SlashCommandBuilder() .setName('gitea') .setDescription('Activité Gitea de FWS Arch') .addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents')) - .addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles')); + .addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles')) + .addSubcommand((sub) => + sub.setName('panel').setDescription('Publier ou modifier le panneau de recrutement Gitea'), + ); const commitLines = (commits) => bullets( @@ -22,8 +28,13 @@ const commitLines = (commits) => }), ); -/** Read-only summaries of the repository (M5-T06 / M5-T07). */ +/** Read-only summaries of the repository (M5-T06 / M5-T07), plus the panel editor. */ export async function execute(interaction) { + if (interaction.options.getSubcommand() === 'panel') { + await openPanelEditor(interaction); + return; + } + assertGiteaConfigured(); await interaction.deferReply(); diff --git a/src/config/env.js b/src/config/env.js index a0d812a..70f3f08 100644 --- a/src/config/env.js +++ b/src/config/env.js @@ -49,6 +49,7 @@ export const env = Object.freeze({ notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'), notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'), ticketCategory: read('CATEGORY_TICKETS_ID'), + giteaApplications: read('CHANNEL_GITEA_APPLICATIONS_ID'), voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'), voiceCategory: read('CATEGORY_VOICE_ID'), }, @@ -66,6 +67,8 @@ export const env = Object.freeze({ token: read('GITEA_TOKEN'), owner: read('GITEA_OWNER'), repo: read('GITEA_REPO'), + org: read('GITEA_ORG') || read('GITEA_OWNER'), + devTeam: read('GITEA_DEV_TEAM', 'Dev'), timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000), maxRetries: readInt('GITEA_MAX_RETRIES', 2), }, diff --git a/src/config/guild-settings.js b/src/config/guild-settings.js index d25ce02..ac602c2 100644 --- a/src/config/guild-settings.js +++ b/src/config/guild-settings.js @@ -23,6 +23,11 @@ export const SETTING_SECTIONS = Object.freeze([ summary: 'Message affiché et épinglé dans le salon des règles.', }, { id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' }, + { + id: 'recruitment', + title: 'Recrutement Gitea', + summary: 'Le message du salon « rejoindre l’équipe » et les candidatures.', + }, { id: 'voice', title: 'Salons vocaux', @@ -136,6 +141,19 @@ export const GUILD_SETTINGS = Object.freeze([ default: true, }, + // --- Recrutement Gitea ----------------------------------------------------- + { + key: 'gitea.recruitmentText', + section: 'recruitment', + label: 'Texte du panneau de recrutement', + help: 'Description de l’embed publié dans le salon « rejoindre l’équipe ». `/gitea panel` la modifie et republie le panneau.', + type: 'markdown', + default: + 'Tu veux contribuer sur Gitea ? Postule pour rejoindre l’équipe : on cherche des personnes motivées, quel que soit le niveau.\n\n' + + 'Remplis le formulaire avec le bouton ci-dessous. On lit chaque candidature et on te répond en message privé.', + maxLength: 4000, + }, + // --- Salons vocaux --------------------------------------------------------- { key: 'voice.adoptOrphans', diff --git a/src/database/migrations/013-gitea-recruitment.sql b/src/database/migrations/013-gitea-recruitment.sql new file mode 100644 index 0000000..ea56f84 --- /dev/null +++ b/src/database/migrations/013-gitea-recruitment.sql @@ -0,0 +1,40 @@ +-- Gitea team recruitment (M20) +-- +-- Applications are stored before the team reviews them: the panel is pressed by +-- members, not staff, so losing an application on restart would mean asking +-- someone to fill the whole form again. The panel message is remembered too, so +-- re-running the installation edits it instead of stacking a second copy. + +CREATE TABLE IF NOT EXISTS gitea_applications ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + user_id TEXT NOT NULL, + languages TEXT NOT NULL, + level TEXT NOT NULL, + experience TEXT, + gitea_username TEXT NOT NULL, + email TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'rejected')), + channel_id TEXT, + message_id TEXT, + reviewed_by TEXT, + reviewed_at TEXT, + gitea_user_id INTEGER, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +-- One open application per member: a second one would give the team two +-- buttons for the same person and could create their Gitea account twice. +CREATE UNIQUE INDEX IF NOT EXISTS idx_gitea_applications_pending_member + ON gitea_applications (guild_id, user_id) WHERE status = 'pending'; + +CREATE INDEX IF NOT EXISTS idx_gitea_applications_status + ON gitea_applications (guild_id, status); + +CREATE TABLE IF NOT EXISTS gitea_recruitment_panels ( + guild_id TEXT PRIMARY KEY, + category_id TEXT, + channel_id TEXT NOT NULL, + message_id TEXT, + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); diff --git a/src/database/repositories/gitea-recruitment-repository.js b/src/database/repositories/gitea-recruitment-repository.js new file mode 100644 index 0000000..1428344 --- /dev/null +++ b/src/database/repositories/gitea-recruitment-repository.js @@ -0,0 +1,129 @@ +import { getDatabase } from '../index.js'; + +// --- Applications ----------------------------------------------------------- + +export function createApplication({ + guildId, + userId, + languages, + level, + experience = null, + giteaUsername, + email, +}) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO gitea_applications + (guild_id, user_id, languages, level, experience, gitea_username, email) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ) + .run(guildId, userId, languages, level, experience, giteaUsername, email); + return Number(lastInsertRowid); +} + +export function getApplication(id) { + return getDatabase().prepare('SELECT * FROM gitea_applications WHERE id = ?').get(id) ?? null; +} + +export function getPendingApplicationByMember({ guildId, userId }) { + return ( + getDatabase() + .prepare( + `SELECT * FROM gitea_applications + WHERE guild_id = ? AND user_id = ? AND status = 'pending'`, + ) + .get(guildId, userId) ?? null + ); +} + +/** Gitea compares usernames without case, so the pending check must too. */ +export function getPendingApplicationByUsername({ guildId, username }) { + return ( + getDatabase() + .prepare( + `SELECT * FROM gitea_applications + WHERE guild_id = ? AND status = 'pending' AND lower(gitea_username) = lower(?)`, + ) + .get(guildId, username) ?? null + ); +} + +export function listPendingApplications({ guildId, limit = 25 }) { + return getDatabase() + .prepare( + `SELECT * FROM gitea_applications + WHERE guild_id = ? AND status = 'pending' + ORDER BY id ASC LIMIT ?`, + ) + .all(guildId, limit); +} + +/** + * Reserves an application before the Gitea call: the conditional update makes + * the second click on « Accepter » lose the race instead of creating a second + * account. + */ +export function claimApplication(id, reviewerId) { + return getDatabase() + .prepare( + `UPDATE gitea_applications + SET status = 'accepted', reviewed_by = ?, reviewed_at = datetime('now') + WHERE id = ? AND status = 'pending'`, + ) + .run(reviewerId, id).changes; +} + +/** Puts a claimed application back in the queue after a failed Gitea call. */ +export function releaseApplication(id) { + return getDatabase() + .prepare( + `UPDATE gitea_applications + SET status = 'pending', reviewed_by = NULL, reviewed_at = NULL, gitea_user_id = NULL + WHERE id = ? AND status = 'accepted'`, + ) + .run(id).changes; +} + +export function rejectApplication(id, reviewerId) { + return getDatabase() + .prepare( + `UPDATE gitea_applications + SET status = 'rejected', reviewed_by = ?, reviewed_at = datetime('now') + WHERE id = ? AND status = 'pending'`, + ) + .run(reviewerId, id).changes; +} + +export function setApplicationGiteaUser(id, giteaUserId) { + return getDatabase() + .prepare('UPDATE gitea_applications SET gitea_user_id = ? WHERE id = ?') + .run(giteaUserId ?? null, id).changes; +} + +export function setApplicationMessage(id, { channelId, messageId }) { + return getDatabase() + .prepare('UPDATE gitea_applications SET channel_id = ?, message_id = ? WHERE id = ?') + .run(channelId, messageId, id).changes; +} + +// --- Recruitment panel ------------------------------------------------------ + +export function getRecruitmentPanel(guildId) { + return ( + getDatabase().prepare('SELECT * FROM gitea_recruitment_panels WHERE guild_id = ?').get(guildId) ?? null + ); +} + +export function setRecruitmentPanel({ guildId, categoryId, channelId, messageId }) { + getDatabase() + .prepare( + `INSERT INTO gitea_recruitment_panels (guild_id, category_id, channel_id, message_id) + VALUES (?, ?, ?, ?) + ON CONFLICT (guild_id) DO UPDATE SET + category_id = excluded.category_id, + channel_id = excluded.channel_id, + message_id = excluded.message_id, + updated_at = datetime('now')`, + ) + .run(guildId, categoryId ?? null, channelId, messageId ?? null); +} diff --git a/src/events/client-ready.js b/src/events/client-ready.js index 1bb0d4b..73a3536 100644 --- a/src/events/client-ready.js +++ b/src/events/client-ready.js @@ -1,5 +1,6 @@ import { Events } from 'discord.js'; import { createLogger } from '../core/logger.js'; +import { installRecruitmentPanel } from '../services/gitea/team-recruitment.js'; import { startPollScheduler } from '../services/polls/poll-service.js'; import { startBotStatusRotation } from '../services/status/bot-status-service.js'; import { @@ -23,6 +24,11 @@ export async function execute(client) { await sweepVoiceChannels(client); startVoiceJanitor(client); startBotStatusRotation(client); + // The Gitea recruitment salon is created on the first start and repaired on + // every later one; a permission problem must not keep the bot offline. + await installRecruitmentPanel(client).catch((error) => + log.warn('Could not install the Gitea recruitment panel', error), + ); log.info(`Connected as ${client.user.tag}`, { guilds: client.guilds.cache.size, commands: client.commands.size, diff --git a/src/events/interaction-create.js b/src/events/interaction-create.js index f5e9d88..5407223 100644 --- a/src/events/interaction-create.js +++ b/src/events/interaction-create.js @@ -4,6 +4,7 @@ import { PermissionDeniedError, UserFacingError } from '../core/errors.js'; import { createLogger } from '../core/logger.js'; import { hasAccess } from '../core/permissions.js'; import { handleGiteaModal } from '../services/gitea/gitea-modals.js'; +import { handleTeamComponent, handleTeamModal } from '../services/gitea/team-recruitment.js'; import { handlePollComponent } from '../services/polls/poll-service.js'; import { handleTicketComponent } from '../services/tickets/ticket-service.js'; import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js'; @@ -20,6 +21,7 @@ const routes = [ { prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal }, { prefix: 'issue:', modal: handleGiteaModal }, { prefix: 'pr:', modal: handleGiteaModal }, + { prefix: 'gitea-team:', component: handleTeamComponent, modal: handleTeamModal }, ]; async function replyError(interaction, message) { diff --git a/src/services/gitea/gitea-client.js b/src/services/gitea/gitea-client.js index 845d9fd..25e640e 100644 --- a/src/services/gitea/gitea-client.js +++ b/src/services/gitea/gitea-client.js @@ -66,4 +66,36 @@ export const gitea = { getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`), getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`), listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`), + getUser: (username) => giteaRequest(`/users/${encodeURIComponent(username)}`), + createUser: ({ username, email, password, mustChangePassword = true }) => + giteaRequest('/admin/users', { + method: 'POST', + body: { + username, + email, + password, + must_change_password: mustChangePassword, + visibility: 'public', + // Recruited accounts must not browse the whole forge: with `restricted` + // Gitea only shows them the repositories their teams give access to. + restricted: true, + }, + }), + deleteUser: (username) => + giteaRequest(`/admin/users/${encodeURIComponent(username)}?purge=true`, { method: 'DELETE' }), + updateUser: (username, body) => + giteaRequest(`/admin/users/${encodeURIComponent(username)}`, { method: 'PATCH', body }), + listTeams: (org) => giteaRequest(`/orgs/${encodeURIComponent(org)}/teams`), + addTeamMember: (teamId, username) => + giteaRequest(`/teams/${teamId}/members/${encodeURIComponent(username)}`, { method: 'PUT' }), }; + +/** Returns the Gitea user, or null when the name is still free. */ +export async function findGiteaUser(username) { + try { + return await gitea.getUser(username); + } catch (error) { + if (error.status === 404) return null; + throw error; + } +} diff --git a/src/services/gitea/team-recruitment.js b/src/services/gitea/team-recruitment.js new file mode 100644 index 0000000..4c3b421 --- /dev/null +++ b/src/services/gitea/team-recruitment.js @@ -0,0 +1,728 @@ +import { randomInt } from 'node:crypto'; +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + ChannelType, + MessageFlags, + ModalBuilder, + TextInputBuilder, + TextInputStyle, +} from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { readSetting, writeSetting } from '../../config/guild-settings.js'; +import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; +import { hasAccess } from '../../core/permissions.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { + claimApplication, + createApplication, + getApplication, + getPendingApplicationByMember, + getPendingApplicationByUsername, + getRecruitmentPanel, + releaseApplication, + rejectApplication, + setApplicationGiteaUser, + setApplicationMessage, + setRecruitmentPanel, +} from '../../database/repositories/gitea-recruitment-repository.js'; +import { baseEmbed, bullets, errorEmbed, successEmbed, warningEmbed } from '../../ui/embeds.js'; +import { asList, findGiteaUser, gitea, isGiteaConfigured } from './gitea-client.js'; +import { replyGiteaFailure } from './gitea-modals.js'; + +/** + * Gitea team recruitment (M20). + * + * The panel lives in a category of its own. The button opens one modal with the + * five questions, in two blocks: the member, then the Gitea account. Discord + * forbids answering a modal with another modal, so a single form is the only + * way to keep the whole application in one gesture. + */ + +const log = createLogger('gitea-recruitment'); + +export const CATEGORY_NAME = '════ GITEA ════'; +// Discord strips apostrophes from channel names, so the dash keeps the words apart. +export const CHANNEL_NAME = 'rejoindre-l-équipe'; +export const RECRUITMENT_SETTING = 'gitea.recruitmentText'; + +const USERNAME_MAX = 39; + +const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; +const USERNAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9-_.]{0,38}$/; + +/** Ambiguous characters are left out: the password is read from a DM and typed. */ +const PASSWORD_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%*-_'; + +export function generatePassword(length = 20) { + let password = ''; + for (let index = 0; index < length; index += 1) { + password += PASSWORD_ALPHABET[randomInt(PASSWORD_ALPHABET.length)]; + } + return password; +} + +/** Returns null when the name is usable, a French explanation otherwise. */ +export function validateGiteaUsername(value) { + const username = String(value ?? '').trim(); + if (username === '') return 'Indique le nom d’utilisateur Gitea que tu veux.'; + if (username.length > USERNAME_MAX) return `${USERNAME_MAX} caractères maximum pour un nom Gitea.`; + if (!USERNAME_PATTERN.test(username)) { + return 'Un nom Gitea commence par une lettre ou un chiffre, puis des lettres, chiffres, points, tirets ou underscores.'; + } + return null; +} + +export function validateEmail(value) { + const email = String(value ?? '').trim(); + if (email === '') return 'Indique une adresse e-mail : elle sert à créer ton compte Gitea.'; + if (email.length > 254) return 'Cette adresse e-mail est trop longue.'; + if (!EMAIL_PATTERN.test(email)) return 'Cette adresse e-mail ne ressemble pas à une adresse valide.'; + return null; +} + +// --- Panel ------------------------------------------------------------------ + +const panelEmbed = (text) => + baseEmbed(COLORS.gitea) + .setTitle('🤝 Rejoindre l’équipe Gitea') + .setDescription(text) + .addFields({ + name: 'Comment ça se passe', + value: bullets([ + 'tu réponds à quelques questions, puis tu choisis ton compte Gitea', + 'l’équipe lit la candidature et accepte ou refuse', + 'si c’est accepté, ton mot de passe provisoire arrive en message privé', + ]), + }); + +function panelComponents() { + return [ + new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId('gitea-team:apply') + .setLabel('Rejoindre l’équipe') + .setEmoji('🤝') + .setStyle(ButtonStyle.Primary), + ), + ]; +} + +async function resolveCategory(guild, storedId) { + if (storedId) { + const stored = await guild.channels.fetch(storedId).catch(() => null); + if (stored?.type === ChannelType.GuildCategory) return stored; + } + + const existing = guild.channels.cache.find( + (channel) => channel.type === ChannelType.GuildCategory && channel.name === CATEGORY_NAME, + ); + if (existing) return existing; + + return guild.channels.create({ + name: CATEGORY_NAME, + type: ChannelType.GuildCategory, + reason: 'Espace Gitea créé par FWS-Bot', + }); +} + +async function resolveChannel(guild, category, storedId) { + if (storedId) { + const stored = await guild.channels.fetch(storedId).catch(() => null); + if (stored?.type === ChannelType.GuildText) { + // An older name or a moved salon is repaired here rather than duplicated. + if (stored.name !== CHANNEL_NAME) { + await stored + .setName(CHANNEL_NAME) + .catch((error) => log.debug('Could not rename the recruitment salon', error)); + } + if (stored.parentId !== category.id) { + await stored + .setParent(category.id) + .catch((error) => log.debug('Could not move the recruitment salon', error)); + } + return stored; + } + } + + const existing = + category.children?.cache?.find( + (channel) => channel.type === ChannelType.GuildText && channel.name === CHANNEL_NAME, + ) ?? + guild.channels.cache.find( + (channel) => channel.type === ChannelType.GuildText && channel.name === CHANNEL_NAME, + ); + if (existing && existing.parentId === category.id) return existing; + + return guild.channels.create({ + name: CHANNEL_NAME, + type: ChannelType.GuildText, + parent: category.id, + topic: 'Candidatures pour rejoindre l’équipe Gitea', + reason: 'Salon de recrutement Gitea créé par FWS-Bot', + }); +} + +/** + * Creates the category, the salon and the panel when they are missing, and + * edits the existing message otherwise. Safe to call on every start. + */ +export async function ensureRecruitmentPanel(client, { guildId = env.discord.guildId, text } = {}) { + if (!guildId) throw new UserFacingError('Aucun serveur Discord n’est configuré (`DISCORD_GUILD_ID`).'); + + const guild = await client.guilds.fetch(guildId).catch(() => null); + if (!guild) { + throw new UserFacingError( + 'Je ne trouve pas ce serveur Discord : vérifie que le bot y est invité et que `DISCORD_GUILD_ID` est correct.', + ); + } + + const stored = getRecruitmentPanel(guildId); + const category = await resolveCategory(guild, stored?.category_id); + const channel = await resolveChannel(guild, category, stored?.channel_id); + const content = String(text ?? readSetting(RECRUITMENT_SETTING, guildId)).trim(); + const embed = panelEmbed(content); + + let message = null; + let edited = false; + if (stored?.message_id && stored.channel_id === channel.id) { + const previous = await channel.messages?.fetch(stored.message_id).catch(() => null); + if (previous) { + message = await previous + .edit({ embeds: [embed], components: panelComponents() }) + .then((result) => result ?? previous) + .catch((error) => { + log.warn('Could not edit the recruitment panel', error); + return null; + }); + edited = Boolean(message); + } + } + + if (!message) { + message = await channel.send({ embeds: [embed], components: panelComponents() }); + // A bot without “Gérer les messages” still installs the panel. + await message.pin().catch((error) => log.debug('Could not pin the recruitment panel', error)); + } + + setRecruitmentPanel({ + guildId, + categoryId: category.id, + channelId: channel.id, + messageId: message.id, + }); + + return { guildId, categoryId: category.id, channelId: channel.id, messageId: message.id, edited }; +} + +/** Called at startup: a failure here must never keep the bot offline. */ +export async function installRecruitmentPanel(client) { + const panel = await ensureRecruitmentPanel(client); + log.info('Gitea recruitment panel ready', panel); + return panel; +} + +/** `/gitea panel`: edits the embed text and republishes it in the salon. */ +export async function openPanelEditor(interaction) { + const text = readSetting(RECRUITMENT_SETTING, interaction.guildId ?? env.discord.guildId); + await interaction.showModal( + new ModalBuilder() + .setCustomId('gitea-team:panel') + .setTitle('Panneau de recrutement Gitea') + .addComponents( + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId('text') + .setLabel('Texte de présentation') + .setStyle(TextInputStyle.Paragraph) + .setMaxLength(4000) + .setRequired(true) + .setValue(text), + ), + ), + ); +} + +async function submitPanelEditor(interaction) { + const guildId = interaction.guildId ?? env.discord.guildId; + const text = interaction.fields.getTextInputValue('text').trim(); + if (text === '') throw new UserFacingError('Le panneau ne peut pas être vide.'); + + writeSetting(RECRUITMENT_SETTING, text, { guildId, updatedBy: interaction.user.id }); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + + const panel = await ensureRecruitmentPanel(interaction.client, { guildId, text }); + logEvent({ + guildId, + type: 'gitea.recruitment.panel', + actorId: interaction.user.id, + payload: panel, + }); + + await interaction.editReply({ + embeds: [ + successEmbed(`Panneau publié dans <#${panel.channelId}>. Les membres peuvent postuler avec le bouton.`), + ], + }); +} + +// --- Application ------------------------------------------------------------- + +function modal(customId, title, fields) { + return new ModalBuilder() + .setCustomId(customId) + .setTitle(title) + .addComponents( + fields.map((field) => + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId(field.id) + .setLabel(field.label) + .setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short) + .setMaxLength(field.maxLength) + .setRequired(field.required ?? true) + .setPlaceholder(field.placeholder ?? ''), + ), + ), + ); +} + +function applicationEmbed(application, { reviewedBy = null } = {}) { + const statusLabel = { + pending: 'En attente', + accepted: 'Acceptée', + rejected: 'Refusée', + }[application.status]; + + const embed = baseEmbed(application.status === 'rejected' ? COLORS.error : COLORS.gitea) + .setTitle(`📨 Candidature Gitea #${application.id}`) + .addFields( + { name: 'Membre', value: `<@${application.user_id}>` }, + { name: 'Langages', value: String(application.languages).slice(0, 1000) }, + { name: 'Niveau', value: String(application.level).slice(0, 1000) }, + { name: 'Motivation', value: String(application.experience || 'Non précisée').slice(0, 1000) }, + { name: 'Compte Gitea', value: `\`${application.gitea_username}\``, inline: true }, + { name: 'E-mail', value: `\`${application.email}\``, inline: true }, + { name: 'Statut', value: statusLabel, inline: true }, + ); + + if (reviewedBy) embed.addFields({ name: 'Traitée par', value: `<@${reviewedBy}>` }); + return embed; +} + +function applicationComponents(application) { + if (application.status !== 'pending') return []; + return [ + new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(`gitea-team:accept:${application.id}`) + .setLabel('Accepter') + .setEmoji('✅') + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`gitea-team:reject:${application.id}`) + .setLabel('Refuser') + .setEmoji('✖️') + .setStyle(ButtonStyle.Danger), + ), + ]; +} + +/** Where verdicts are posted: its own salon, or the technical logs. */ +async function resolveReviewChannel(client) { + const channelId = env.channels.giteaApplications || env.channels.logs; + if (!channelId) { + throw new UserFacingError( + 'Les candidatures n’ont pas de salon : renseigne `CHANNEL_GITEA_APPLICATIONS_ID` (ou `CHANNEL_LOGS_ID`) dans le `.env`.', + ); + } + + const channel = await client.channels.fetch(channelId).catch(() => null); + if (!channel?.isSendable()) { + throw new UserFacingError( + 'Le salon des candidatures est introuvable, ou je n’ai pas le droit d’y écrire. L’équipe doit vérifier `CHANNEL_GITEA_APPLICATIONS_ID`.', + ); + } + return channel; +} + +export async function openApplicationModal(interaction) { + await interaction.showModal( + modal('gitea-team:form', 'Candidature — toi et ton compte Gitea', [ + { + id: 'languages', + label: 'Langages de programmation', + maxLength: 200, + placeholder: 'Python, JavaScript, Rust…', + }, + { + id: 'level', + label: 'Ton niveau', + maxLength: 100, + placeholder: 'Débutant, intermédiaire, avancé…', + }, + { + id: 'experience', + label: 'Ce que tu veux apporter', + paragraph: true, + maxLength: 500, + required: false, + placeholder: 'Projets, disponibilité, expérience…', + }, + { + id: 'username', + label: 'Pseudo Gitea souhaité', + maxLength: USERNAME_MAX, + placeholder: 'ton-pseudo', + }, + { id: 'email', label: 'Adresse e-mail', maxLength: 254, placeholder: 'toi@exemple.org' }, + ]), + ); +} + +async function submitApplication(interaction) { + const context = { + languages: interaction.fields.getTextInputValue('languages').trim(), + level: interaction.fields.getTextInputValue('level').trim(), + experience: interaction.fields.getTextInputValue('experience').trim() || null, + }; + const username = interaction.fields.getTextInputValue('username').trim(); + const email = interaction.fields.getTextInputValue('email').trim(); + const usernameError = validateGiteaUsername(username); + if (usernameError) throw new UserFacingError(usernameError); + const emailError = validateEmail(email); + if (emailError) throw new UserFacingError(emailError); + + if (!isGiteaConfigured()) { + throw new UserFacingError( + 'Le recrutement Gitea n’est pas encore configuré : l’équipe doit renseigner `GITEA_URL` et `GITEA_TOKEN`. Réessaie plus tard.', + ); + } + + const guildId = interaction.guildId ?? env.discord.guildId; + const channel = await resolveReviewChannel(interaction.client); + + if (getPendingApplicationByMember({ guildId, userId: interaction.user.id })) { + throw new UserFacingError( + 'Tu as déjà une candidature en attente : l’équipe la lit en ce moment. Tu recevras la réponse en message privé.', + ); + } + if (getPendingApplicationByUsername({ guildId, username })) { + throw new UserFacingError( + 'Ce nom d’utilisateur Gitea est déjà demandé par une autre candidature en attente. Choisis-en un autre.', + ); + } + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + + let existing; + try { + existing = await findGiteaUser(username); + } catch (error) { + await replyGiteaFailure(interaction, error); + return; + } + if (existing) { + throw new UserFacingError( + `Le nom **${username}** est déjà pris sur Gitea. Reclique sur **Rejoindre l’équipe** et choisis-en un autre.`, + ); + } + + const id = createApplication({ + guildId, + userId: interaction.user.id, + languages: context.languages, + level: context.level, + experience: context.experience, + giteaUsername: username, + email, + }); + const application = getApplication(id); + + const message = await channel.send({ + embeds: [applicationEmbed(application)], + components: applicationComponents(application), + }); + setApplicationMessage(id, { channelId: channel.id, messageId: message.id }); + + logEvent({ + guildId, + type: 'gitea.recruitment.applied', + actorId: interaction.user.id, + payload: { id, username }, + }); + + await interaction.editReply({ + embeds: [ + successEmbed( + `Ta candidature est partie : <#${channel.id}>. L’équipe la lit et te répond en message privé — garde tes MP ouverts.`, + ), + ], + }); +} + +// --- Review ------------------------------------------------------------------ + +/** + * Puts the new account in the organization's developer team. Recruited people + * have no other organization, so this team is the only place they can work. + */ +/** + * Removes what a recruited account could do outside the organization: no + * personal repositories, no organization of its own. The team still allows + * creating repositories inside FWS. + */ +export async function lockGiteaAccount(username) { + try { + await gitea.updateUser(username, { + restricted: true, + max_repo_creation: 0, + allow_create_organization: false, + }); + return { locked: true }; + } catch (error) { + log.error('Could not lock the new Gitea account', error); + return { locked: false, reason: 'Gitea a refusé les restrictions' }; + } +} + +export async function addToDeveloperTeam(username) { + const org = env.gitea.org; + const teamName = env.gitea.devTeam; + if (!org || !teamName) return { added: false, reason: 'organisation ou équipe non configurée' }; + + const teams = asList(await gitea.listTeams(org)); + const team = teams.find((entry) => String(entry.name).toLowerCase() === teamName.toLowerCase()); + if (!team) return { added: false, reason: `équipe « ${teamName} » introuvable dans ${org}` }; + + await gitea.addTeamMember(team.id, username); + return { added: true, team: team.name }; +} + +/** Gives the accepted member the Discord Dev role, when one is configured. */ +async function grantDeveloperRole(interaction, userId) { + if (!env.roles.dev) return { added: false, reason: 'ROLE_DEV_ID non configuré' }; + + const member = await interaction.guild?.members?.fetch(userId).catch(() => null); + if (!member) return { added: false, reason: 'membre introuvable sur le serveur' }; + + return member.roles + .add(env.roles.dev) + .then(() => ({ added: true })) + .catch((error) => { + log.warn('Could not grant the Dev role', error); + return { added: false, reason: 'permission refusée par Discord' }; + }); +} + +function credentialsEmbed(username, password) { + return baseEmbed(COLORS.gitea) + .setTitle('✅ Ton accès Gitea est prêt') + .setDescription( + `Ta candidature a été acceptée. Voici ton compte :\n\n` + + `**Identifiant** : \`${username}\`\n` + + `**Mot de passe provisoire** : \`${password}\``, + ) + .addFields({ + name: 'Première connexion', + value: bullets([ + `connecte-toi sur ${env.gitea.url}`, + 'change ton mot de passe dès la première connexion', + 'garde-le pour toi : il ne sera plus affiché ensuite', + ]), + }); +} + +async function acceptApplication(interaction, application) { + if (!isGiteaConfigured()) { + throw new UserFacingError( + 'Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`) : impossible de créer le compte pour l’instant.', + ); + } + + if (claimApplication(application.id, interaction.user.id) === 0) { + throw new UserFacingError('Cette candidature vient d’être traitée par quelqu’un d’autre.'); + } + + await interaction.deferUpdate(); + const password = generatePassword(); + + let created; + try { + created = await gitea.createUser({ + username: application.gitea_username, + email: application.email, + password, + mustChangePassword: true, + }); + } catch (error) { + releaseApplication(application.id); + log.error('Gitea refused a team account creation', error); + const reason = + error.status === 422 + ? 'Gitea a refusé : ce nom ou cette adresse e-mail est déjà utilisé. Demande au membre d’en choisir un autre.' + : 'Gitea n’a pas répondu. La candidature reste en attente : réessaie plus tard.'; + await interaction.followUp({ + embeds: [errorEmbed(reason)], + flags: MessageFlags.Ephemeral, + }); + return; + } + + setApplicationGiteaUser(application.id, created?.id); + const reviewed = { ...application, status: 'accepted', reviewed_by: interaction.user.id }; + + const [team, role, lock] = await Promise.all([ + addToDeveloperTeam(application.gitea_username).catch((error) => { + log.error('Could not add the new account to the developer team', error); + return { added: false, reason: 'erreur Gitea' }; + }), + grantDeveloperRole(interaction, application.user_id), + lockGiteaAccount(application.gitea_username), + ]); + + const applicant = await interaction.client.users.fetch(application.user_id).catch(() => null); + const delivered = await applicant + ?.send({ embeds: [credentialsEmbed(application.gitea_username, password)] }) + .then(() => true) + .catch(() => false); + + logEvent({ + guildId: application.guild_id, + type: 'gitea.recruitment.accepted', + actorId: interaction.user.id, + payload: { + id: application.id, + username: application.gitea_username, + giteaUserId: created?.id ?? null, + delivered, + team: team.added ? team.team : null, + discordRole: role.added, + giteaLocked: lock.locked, + }, + }); + + await interaction.editReply({ + embeds: [applicationEmbed(reviewed, { reviewedBy: interaction.user.id })], + components: [], + }); + + if (!delivered) { + // The account exists: the password must reach the member somehow, and the + // ephemeral reply is the only place that does not expose it to the salon. + await interaction.followUp({ + embeds: [ + errorEmbed( + `Je n’ai pas pu écrire à <@${application.user_id}> (messages privés fermés). ` + + `Transmets-lui ces identifiants toi-même : identifiant \`${application.gitea_username}\`, mot de passe \`${password}\`.`, + ), + ], + flags: MessageFlags.Ephemeral, + }); + } + + const warnings = []; + if (!team.added) + warnings.push(`l’ajout à l’équipe Gitea « ${env.gitea.devTeam} » a échoué (${team.reason})`); + if (!role.added) warnings.push(`le rôle Discord Dev n’a pas été attribué (${role.reason})`); + if (!lock.locked) warnings.push(`le compte Gitea n’a pas pu être verrouillé (${lock.reason})`); + if (warnings.length > 0) { + await interaction.followUp({ + embeds: [ + warningEmbed( + `${bullets(warnings)}\n\nLe compte Gitea existe déjà : corrige ces deux points à la main, ne recrée pas la candidature.`, + ), + ], + flags: MessageFlags.Ephemeral, + }); + } +} + +async function rejectApplicationFlow(interaction, application) { + if (rejectApplication(application.id, interaction.user.id) === 0) { + throw new UserFacingError('Cette candidature vient d’être traitée par quelqu’un d’autre.'); + } + + await interaction.deferUpdate(); + + const applicant = await interaction.client.users.fetch(application.user_id).catch(() => null); + const notified = await applicant + ?.send({ + embeds: [ + baseEmbed(COLORS.info) + .setTitle('Ta candidature Gitea') + .setDescription( + 'Merci d’avoir postulé ! L’équipe n’a pas retenu ta candidature cette fois. ' + + 'Tu peux continuer à contribuer sur le serveur et retenter plus tard.', + ), + ], + }) + .then(() => true) + .catch(() => false); + + logEvent({ + guildId: application.guild_id, + type: 'gitea.recruitment.rejected', + actorId: interaction.user.id, + payload: { id: application.id, notified }, + }); + + await interaction.editReply({ + embeds: [applicationEmbed({ ...application, status: 'rejected' }, { reviewedBy: interaction.user.id })], + components: [], + }); +} + +export async function reviewApplication(interaction, decision, idText) { + if (!hasAccess(interaction.member, ACCESS_LEVELS.STAFF)) { + throw new PermissionDeniedError( + 'Seule l’équipe peut accepter ou refuser une candidature. Si tu as postulé, attends la réponse en message privé.', + ); + } + + const application = getApplication(Number.parseInt(idText, 10)); + if (!application) throw new UserFacingError('Cette candidature n’existe plus.'); + if (application.status !== 'pending') { + throw new UserFacingError( + `Cette candidature est déjà ${application.status === 'accepted' ? 'acceptée' : 'refusée'}.`, + ); + } + + if (decision === 'reject') { + await rejectApplicationFlow(interaction, application); + return; + } + await acceptApplication(interaction, application); +} + +// --- Routing ----------------------------------------------------------------- + +export async function handleTeamComponent(interaction) { + if (interaction.customId === 'gitea-team:apply') { + await openApplicationModal(interaction); + return; + } + + const match = /^gitea-team:(accept|reject):(\d+)$/.exec(interaction.customId); + if (!match) { + log.debug(`Ignored unknown recruitment component ${interaction.customId}`); + return; + } + await reviewApplication(interaction, match[1], match[2]); +} + +export async function handleTeamModal(interaction) { + switch (interaction.customId) { + case 'gitea-team:form': + await submitApplication(interaction); + return; + case 'gitea-team:panel': + await submitPanelEditor(interaction); + return; + default: + log.debug(`Ignored unknown recruitment modal ${interaction.customId}`); + } +} diff --git a/src/web/services/env-schema.js b/src/web/services/env-schema.js index 9b6962c..acb1712 100644 --- a/src/web/services/env-schema.js +++ b/src/web/services/env-schema.js @@ -275,6 +275,13 @@ export const VARIABLES = Object.freeze([ help: 'Catégorie sous laquelle les salons privés de tickets sont créés.', type: 'snowflake', }, + { + key: 'CHANNEL_GITEA_APPLICATIONS_ID', + section: 'channels', + label: 'Candidatures Gitea', + help: 'Salon où le bot publie les candidatures à rejoindre l’équipe Gitea, avec les boutons Accepter et Refuser. Vide : repli sur `CHANNEL_LOGS_ID`.', + type: 'snowflake', + }, // --- Voice ----------------------------------------------------------------- { @@ -345,6 +352,23 @@ export const VARIABLES = Object.freeze([ type: 'text', placeholder: 'FWS-Arch', }, + { + key: 'GITEA_ORG', + section: 'gitea', + label: 'Organisation de recrutement', + help: 'Organisation Gitea où les personnes recrutées sont ajoutées. Vide : `GITEA_OWNER` est utilisée.', + type: 'text', + placeholder: 'FWS', + }, + { + key: 'GITEA_DEV_TEAM', + section: 'gitea', + label: 'Équipe des développeurs', + help: 'Équipe de cette organisation où chaque candidature acceptée est ajoutée. Elle doit exister côté Gitea.', + type: 'text', + default: 'Dev', + placeholder: 'Dev', + }, { key: 'GITEA_TIMEOUT_MS', section: 'gitea', diff --git a/tests/team-recruitment.test.js b/tests/team-recruitment.test.js new file mode 100644 index 0000000..23f2fdc --- /dev/null +++ b/tests/team-recruitment.test.js @@ -0,0 +1,254 @@ +import assert from 'node:assert/strict'; +import { Collection } from 'discord.js'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + claimApplication, + createApplication, + getApplication, + getPendingApplicationByMember, + getPendingApplicationByUsername, + getRecruitmentPanel, + rejectApplication, + releaseApplication, +} from '../src/database/repositories/gitea-recruitment-repository.js'; +import { + CATEGORY_NAME, + CHANNEL_NAME, + ensureRecruitmentPanel, + generatePassword, + openApplicationModal, + validateEmail, + validateGiteaUsername, +} from '../src/services/gitea/team-recruitment.js'; + +/** Gitea team recruitment (M20): panel installation and stored applications. */ + +const GUILD_ID = 'guild-1'; + +describe('application answers', () => { + it('generates a long password from an unambiguous alphabet', () => { + const password = generatePassword(24); + + assert.equal(password.length, 24); + assert.match(password, /^[A-Za-z0-9!@#$%*-_]+$/); + assert.notEqual(generatePassword(24), generatePassword(24)); + }); + + it('accepts the names Gitea allows', () => { + assert.equal(validateGiteaUsername('damien'), null); + assert.equal(validateGiteaUsername('fws-bot_2.0'), null); + }); + + it('refuses a name Gitea would reject', () => { + assert.match(validateGiteaUsername(''), /Indique/); + assert.match(validateGiteaUsername('-leading'), /commence/); + assert.match(validateGiteaUsername('has space'), /commence/); + assert.match(validateGiteaUsername('a'.repeat(40)), /39 caractères/); + }); + + it('checks the e-mail before calling Gitea', () => { + assert.equal(validateEmail('moi@exemple.org'), null); + assert.match(validateEmail('pas-un-email'), /valide/); + assert.match(validateEmail(''), /Indique/); + }); + + /** Discord rejects more than five inputs, and a modal cannot answer another modal. */ + it('asks everything in a single modal of five fields', async () => { + let shown; + await openApplicationModal({ + showModal: async (modal) => { + shown = modal.toJSON(); + }, + }); + + assert.equal(shown.custom_id, 'gitea-team:form'); + assert.equal(shown.components.length, 5); + assert.deepEqual( + shown.components.map((row) => row.components[0].custom_id), + ['languages', 'level', 'experience', 'username', 'email'], + ); + }); +}); + +describe('recruitment repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => + getDatabase().exec('DELETE FROM gitea_applications; DELETE FROM gitea_recruitment_panels;'), + ); + + const apply = (overrides = {}) => + createApplication({ + guildId: GUILD_ID, + userId: 'member-1', + languages: 'JavaScript, Rust', + level: 'Intermédiaire', + experience: 'Je veux aider sur la doc.', + giteaUsername: 'membre-1', + email: 'membre@exemple.org', + ...overrides, + }); + + it('stores a pending application and finds it by member and username', () => { + const id = apply(); + + assert.equal(getApplication(id).status, 'pending'); + assert.equal(getPendingApplicationByMember({ guildId: GUILD_ID, userId: 'member-1' }).id, id); + assert.equal( + getPendingApplicationByUsername({ guildId: GUILD_ID, username: 'MEMBRE-1' }).id, + id, + 'Gitea compares usernames without case', + ); + }); + + it('refuses a second pending application from the same member', () => { + apply(); + assert.throws(() => apply({ giteaUsername: 'autre' }), /UNIQUE/); + }); + + it('claims only once, so two clicks cannot create two accounts', () => { + const id = apply(); + + assert.equal(claimApplication(id, 'staff'), 1); + assert.equal(claimApplication(id, 'other-staff'), 0); + assert.equal(getApplication(id).status, 'accepted'); + assert.equal(getApplication(id).reviewed_by, 'staff'); + }); + + it('puts a claimed application back in the queue when Gitea fails', () => { + const id = apply(); + claimApplication(id, 'staff'); + + assert.equal(releaseApplication(id), 1); + assert.equal(getApplication(id).status, 'pending'); + assert.equal(getApplication(id).reviewed_by, null); + assert.equal(releaseApplication(id), 0); + }); + + it('rejects only a pending application', () => { + const id = apply(); + + assert.equal(rejectApplication(id, 'staff'), 1); + assert.equal(getApplication(id).status, 'rejected'); + assert.equal(rejectApplication(id, 'staff'), 0); + }); + + it('keeps one panel row per guild and updates it', () => { + assert.equal(getRecruitmentPanel(GUILD_ID), null); + }); +}); + +/** A guild reduced to what installing the panel touches. */ +function fakeGuild() { + const state = { + messages: new Map(), + sent: 0, + edits: 0, + nextId: 0, + }; + const cache = new Collection(); + + const channel = ({ id, name, type, parent = null }) => { + const parentId = parent?.id ?? null; + const created = { + id, + name, + type, + parentId, + children: { cache: new Collection() }, + isSendable: () => true, + messages: { + fetch: async (messageId) => state.messages.get(messageId) ?? null, + }, + send: async (payload) => { + state.sent += 1; + const messageId = `message-${(state.nextId += 1)}`; + const message = { + id: messageId, + payload, + pin: async () => {}, + edit: async (next) => { + state.edits += 1; + message.payload = next; + return message; + }, + }; + state.messages.set(messageId, message); + return message; + }, + }; + if (parent) parent.children.cache.set(id, created); + cache.set(id, created); + return created; + }; + + const guild = { + id: GUILD_ID, + channels: { + cache, + fetch: async (channelId) => cache.get(channelId) ?? null, + create: async (options) => { + if (options.type === 4) { + return channel({ id: `category-${(state.nextId += 1)}`, name: options.name, type: options.type }); + } + return channel({ + id: `channel-${(state.nextId += 1)}`, + name: options.name, + type: options.type, + parent: cache.get(options.parent), + }); + }, + }, + }; + + return { guild, state, client: { guilds: { fetch: async () => guild } } }; +} + +describe('recruitment panel', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => + getDatabase().exec('DELETE FROM gitea_applications; DELETE FROM gitea_recruitment_panels;'), + ); + + it('creates the category, the salon and the panel on the first start', async () => { + const { guild, state, client } = fakeGuild(); + + const panel = await ensureRecruitmentPanel(client, { guildId: GUILD_ID, text: 'Viens aider !' }); + + assert.equal(panel.edited, false); + assert.equal(state.sent, 1); + assert.equal(guild.channels.cache.get(panel.categoryId).name, CATEGORY_NAME); + assert.equal(guild.channels.cache.get(panel.channelId).name, CHANNEL_NAME); + assert.equal(guild.channels.cache.get(panel.channelId).parentId, panel.categoryId); + assert.equal(getRecruitmentPanel(GUILD_ID).message_id, panel.messageId); + }); + + it('edits the existing panel instead of posting a second one', async () => { + const { state, client } = fakeGuild(); + + const first = await ensureRecruitmentPanel(client, { guildId: GUILD_ID, text: 'Version 1' }); + const second = await ensureRecruitmentPanel(client, { guildId: GUILD_ID, text: 'Version 2' }); + + assert.equal(state.sent, 1, 'a second panel message was sent'); + assert.equal(state.edits, 1); + assert.equal(second.messageId, first.messageId); + }); + + it('reuses a category and a salon that already exist by name', async () => { + const { guild, state, client } = fakeGuild(); + const category = await guild.channels.create({ name: CATEGORY_NAME, type: 4 }); + const salon = await guild.channels.create({ + name: CHANNEL_NAME, + type: 0, + parent: category.id, + }); + + const panel = await ensureRecruitmentPanel(client, { guildId: GUILD_ID, text: 'Salut' }); + + assert.equal(panel.categoryId, category.id); + assert.equal(panel.channelId, salon.id); + assert.equal(state.sent, 1); + }); +});