CI / quality (push) Failing after 45s
Recruitment needs `write:admin` and `write:organization`, which the everyday token must not carry. A second token keeps the repository and issue scopes least privileged, falls back to `GITEA_TOKEN` so existing installs keep working, and a 403 now names the missing scope instead of pretending Gitea did not answer.
801 lines
27 KiB
JavaScript
801 lines
27 KiB
JavaScript
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, giteaRecruitment, isGiteaRecruitmentConfigured } 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 (application.rejection_reason) {
|
||
embed.addFields({ name: 'Raison du refus', value: String(application.rejection_reason).slice(0, 1000) });
|
||
}
|
||
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 (!isGiteaRecruitmentConfigured()) {
|
||
throw new UserFacingError(
|
||
'Le recrutement Gitea n’est pas encore configuré : l’équipe doit renseigner `GITEA_URL` et `GITEA_RECRUITMENT_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 ------------------------------------------------------------------
|
||
|
||
/**
|
||
* 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 giteaRecruitment.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' };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 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.
|
||
*/
|
||
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 giteaRecruitment.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 giteaRecruitment.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 (!isGiteaRecruitmentConfigured()) {
|
||
throw new UserFacingError(
|
||
'Gitea n’est pas configuré (`GITEA_URL` et `GITEA_RECRUITMENT_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 giteaRecruitment.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);
|
||
let reason = 'Gitea n’a pas répondu. La candidature reste en attente : réessaie plus tard.';
|
||
if (error.status === 422) {
|
||
reason =
|
||
'Gitea a refusé : ce nom ou cette adresse e-mail est déjà utilisé. Demande au membre d’en choisir un autre.';
|
||
}
|
||
if (error.status === 403) {
|
||
reason =
|
||
'Gitea a refusé l’appel : le jeton de recrutement n’a pas les droits d’administration. ' +
|
||
'Il lui faut la portée `write:admin` (`GITEA_RECRUITMENT_TOKEN`).';
|
||
}
|
||
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,
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* A refusal is written, not clicked away: the modal makes the reason mandatory,
|
||
* and it is the only thing the member gets to read.
|
||
*/
|
||
export async function openRejectionModal(interaction, application) {
|
||
await interaction.showModal(
|
||
modal(`gitea-team:reject:${application.id}`, `Refus de la candidature #${application.id}`, [
|
||
{
|
||
id: 'reason',
|
||
label: 'Pourquoi cette candidature est refusée',
|
||
paragraph: true,
|
||
maxLength: 500,
|
||
placeholder: 'Le membre reçoit ce texte : sois précis et courtois.',
|
||
},
|
||
]),
|
||
);
|
||
}
|
||
|
||
function rejectionEmbed(reason) {
|
||
return baseEmbed(COLORS.info)
|
||
.setTitle('Ta candidature Gitea')
|
||
.setDescription('Merci d’avoir postulé ! L’équipe n’a pas retenu ta candidature cette fois.')
|
||
.addFields(
|
||
{ name: 'La raison', value: String(reason).slice(0, 1000) },
|
||
{
|
||
name: 'Et ensuite',
|
||
value: 'Tu peux continuer à contribuer sur le serveur et retenter plus tard.',
|
||
},
|
||
);
|
||
}
|
||
|
||
async function submitRejection(interaction, idText) {
|
||
if (!hasAccess(interaction.member, ACCESS_LEVELS.STAFF)) {
|
||
throw new PermissionDeniedError('Seule l’équipe peut refuser une candidature.');
|
||
}
|
||
|
||
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'}.`,
|
||
);
|
||
}
|
||
|
||
const reason = interaction.fields.getTextInputValue('reason').trim();
|
||
if (reason === '') {
|
||
throw new UserFacingError('Indique la raison du refus : elle est envoyée au membre.');
|
||
}
|
||
|
||
if (rejectApplication(application.id, interaction.user.id, reason) === 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: [rejectionEmbed(reason)] })
|
||
.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', rejection_reason: reason },
|
||
{ reviewedBy: interaction.user.id },
|
||
),
|
||
],
|
||
components: [],
|
||
});
|
||
|
||
if (!notified) {
|
||
// The refusal is still recorded: the team can pass the reason along itself.
|
||
await interaction.followUp({
|
||
embeds: [
|
||
errorEmbed(
|
||
`Je n’ai pas pu écrire à <@${application.user_id}> (messages privés fermés). ` +
|
||
`Transmets-lui la raison toi-même : « ${reason} »`,
|
||
),
|
||
],
|
||
flags: MessageFlags.Ephemeral,
|
||
});
|
||
}
|
||
}
|
||
|
||
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 openRejectionModal(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: {
|
||
const rejection = /^gitea-team:reject:(\d+)$/.exec(interaction.customId);
|
||
if (rejection) {
|
||
await submitRejection(interaction, rejection[1]);
|
||
return;
|
||
}
|
||
log.debug(`Ignored unknown recruitment modal ${interaction.customId}`);
|
||
}
|
||
}
|
||
}
|