Build/project structure #142

Merged
BlackAngelTV merged 80 commits from build/project-structure into main 2026-09-23 14:31:21 +02:00
3 changed files with 353 additions and 18 deletions
Showing only changes of commit e8c95b2ba3 - Show all commits

No files matched your search

+31 -6
View File
@@ -1,6 +1,12 @@
import { SlashCommandBuilder } from 'discord.js';
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
import {
addParticipant,
claimTicket,
closeTicket,
createTicket,
} from '../../services/tickets/ticket-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
// `close` is also allowed for the ticket author: checked in the ticket service.
@@ -35,9 +41,28 @@ export const data = new SlashCommandBuilder()
.addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)),
);
// TODO(M6-T03..T09): implement with a ticket service backed by the tickets table.
/** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */
export async function execute(interaction) {
await interaction.reply({
embeds: [notImplementedEmbed(`/ticket ${interaction.options.getSubcommand()}`)],
});
switch (interaction.options.getSubcommand()) {
case 'create': {
const categoryId = interaction.options.getString('category', true);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const channel = await createTicket(interaction, categoryId);
await interaction.editReply({
embeds: [successEmbed(`Ton ticket est ouvert : <#${channel.id}>`)],
});
return;
}
case 'close':
await closeTicket(interaction, interaction.options.getString('reason'));
return;
case 'claim':
await claimTicket(interaction);
return;
case 'add':
await addParticipant(interaction, interaction.options.getUser('user', true).id);
return;
default:
return;
}
}
+45 -12
View File
@@ -2,12 +2,23 @@ import { Events, MessageFlags } from 'discord.js';
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 { handlePollComponent } from '../services/polls/poll-service.js';
import { handleTicketComponent } from '../services/tickets/ticket-service.js';
import { errorEmbed } from '../ui/embeds.js';
const log = createLogger('interactions');
export const name = Events.InteractionCreate;
/** Custom id prefix -> handlers for the message components and the modals. */
const routes = [
{ prefix: 'ticket:', component: handleTicketComponent },
{ prefix: 'poll:', component: handlePollComponent },
{ prefix: 'issue:', modal: handleGiteaModal },
{ prefix: 'pr:', modal: handleGiteaModal },
];
async function replyError(interaction, message) {
const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
@@ -17,31 +28,53 @@ async function replyError(interaction, message) {
}
}
export async function execute(client, interaction) {
if (!interaction.isChatInputCommand() && !interaction.isAutocomplete()) return;
const command = client.commands.get(interaction.commandName);
async function runChatInputCommand(interaction) {
const command = interaction.client.commands.get(interaction.commandName);
if (!command) return;
if (interaction.isAutocomplete()) {
await command.autocomplete?.(interaction);
const subcommand = interaction.options.getSubcommand(false);
const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access;
if (!hasAccess(interaction.member, requiredLevel)) {
throw new PermissionDeniedError();
}
await command.execute(interaction);
}
async function runRoute(interaction, kind) {
const route = routes.find(
({ prefix, [kind]: handler }) => handler && interaction.customId.startsWith(prefix),
);
if (!route) {
log.debug(`Ignored ${kind} ${interaction.customId}`);
return;
}
await route[kind](interaction);
}
export async function execute(_client, interaction) {
try {
const subcommand = interaction.options.getSubcommand(false);
const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access;
if (!hasAccess(interaction.member, requiredLevel)) {
throw new PermissionDeniedError();
if (interaction.isAutocomplete()) {
await interaction.client.commands.get(interaction.commandName)?.autocomplete?.(interaction);
return;
}
await command.execute(interaction);
if (interaction.isButton() || interaction.isAnySelectMenu()) {
await runRoute(interaction, 'component');
return;
}
if (interaction.isModalSubmit()) {
await runRoute(interaction, 'modal');
return;
}
if (!interaction.isChatInputCommand()) return;
await runChatInputCommand(interaction);
} catch (error) {
if (error instanceof UserFacingError) {
await replyError(interaction, error.message);
return;
}
log.error(`Command failed: /${interaction.commandName}`, error);
log.error(`Interaction failed: ${interaction.commandName ?? interaction.customId ?? 'unknown'}`, error);
await replyError(interaction, 'Une erreur inattendue est survenue. Réessaie plus tard.').catch(() => {});
}
}
+277
View File
@@ -0,0 +1,277 @@
import { ChannelType, PermissionFlagsBits } from 'discord.js';
import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { getAccessLevel } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
claimTicket as claimTicketRow,
closeTicket as closeTicketRow,
createTicket as createTicketRow,
getTicketByChannel,
} from '../../database/repositories/ticket-repository.js';
import { ticketButtons } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
const log = createLogger('tickets');
/** Ticket scope names to the FWS access level they require. */
const SCOPE_LEVELS = {
staff: ACCESS_LEVELS.STAFF,
dev: ACCESS_LEVELS.DEV,
owner: ACCESS_LEVELS.OWNER,
};
export function findCategory(categoryId) {
return TICKET_CATEGORIES.find((category) => category.id === categoryId) ?? null;
}
/** A member may open a ticket only for a category their access level covers (M6-T02). */
export function canUseCategory(member, category) {
const level = getAccessLevel(member);
return category.scope.some((scope) => level >= SCOPE_LEVELS[scope]);
}
/** Static info about a ticket, used by the embeds below. */
function ticketEmbed(ticket, category) {
const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne';
return baseEmbed(COLORS.ticket)
.setTitle(`Ticket ${category.label} #${ticket.id}`)
.setDescription(
`<@${ticket.author_id}> décris ici ta demande avec le plus de détails possible : ` +
'contexte, étapes de reproduction, messages d’erreur.',
)
.addFields(
{ name: 'Catégorie', value: category.label, inline: true },
{ name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
{ name: 'Pris en charge par', value: claimed, inline: true },
);
}
function channelName(categoryId, username) {
const slug = username
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 40);
return `ticket-${categoryId}-${slug || 'membre'}`.slice(0, 100);
}
/** Permission overwrites: the author, the staff roles of the scope and the bot (M6-T04). */
function buildOverwrites(guild, client, category, authorId) {
const allow = [
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.SendMessages,
PermissionFlagsBits.ReadMessageHistory,
PermissionFlagsBits.AttachFiles,
];
const overwrites = [
{ id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] },
{ id: authorId, allow },
{ id: client.user.id, allow: [...allow, PermissionFlagsBits.ManageChannels] },
];
for (const scope of category.scope) {
const roleId = env.roles[scope];
if (roleId) overwrites.push({ id: roleId, allow });
}
return overwrites;
}
async function fetchTicketLogChannel(client) {
if (!env.channels.ticketLogs) return null;
const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null);
return channel?.isSendable() ? channel : null;
}
async function logTicket(client, embed) {
const channel = await fetchTicketLogChannel(client);
await channel?.send({ embeds: [embed] });
}
/** Opens a private channel for the ticket (M6-T03). */
export async function createTicket(interaction, categoryId) {
const category = findCategory(categoryId);
if (!category) throw new UserFacingError('Catégorie de ticket inconnue.');
if (!canUseCategory(interaction.member, category)) {
throw new UserFacingError(`Tu n’as pas accès à la catégorie **${category.label}**.`);
}
if (!env.channels.ticketCategory) {
throw new UserFacingError('Le salon parent des tickets n’est pas configuré (`CATEGORY_TICKETS_ID`).');
}
const guild = interaction.guild;
const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null);
if (parent?.type !== ChannelType.GuildCategory) {
throw new UserFacingError('`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord.');
}
const channel = await guild.channels.create({
name: channelName(category.id, interaction.user.username),
type: ChannelType.GuildText,
parent: parent.id,
topic: `Ticket ${category.label} — ${interaction.user.tag}`,
permissionOverwrites: buildOverwrites(guild, interaction.client, category, interaction.user.id),
reason: `Ticket ${category.label} ouvert par ${interaction.user.tag}`,
});
let ticket;
try {
ticket = {
id: createTicketRow({
guildId: guild.id,
channelId: channel.id,
categoryId: category.id,
authorId: interaction.user.id,
}),
guild_id: guild.id,
channel_id: channel.id,
category_id: category.id,
author_id: interaction.user.id,
claimed_by: null,
status: 'open',
};
} catch (error) {
// The unique index rejects a second open ticket for the same author and category.
await channel.delete('Ticket en doublon').catch(() => {});
log.warn('Duplicate ticket rejected', error);
throw new UserFacingError('Tu as déjà un ticket ouvert dans cette catégorie.');
}
await channel.send({
content: `<@${ticket.author_id}>`,
embeds: [ticketEmbed(ticket, category)],
components: ticketButtons(),
});
logEvent({
guildId: guild.id,
type: 'ticket.created',
actorId: ticket.author_id,
payload: { ticketId: ticket.id, categoryId: category.id },
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket ouvert')
.setDescription(`<#${channel.id}> — ${category.label}`)
.addFields({ name: 'Auteur', value: `<@${ticket.author_id}>`, inline: true }),
);
return channel;
}
/** Resolves the ticket of the current channel, or throws a user facing error. */
export async function getChannelTicket(interaction) {
const ticket = getTicketByChannel(interaction.channelId);
if (!ticket) {
throw new UserFacingError('Cette action doit être lancée depuis un salon de ticket.');
}
if (ticket.status !== 'open') {
throw new UserFacingError('Ce ticket est déjà fermé.');
}
return ticket;
}
export async function claimTicket(interaction) {
const ticket = await getChannelTicket(interaction);
if (ticket.claimed_by === interaction.user.id) {
throw new UserFacingError('Tu as déjà pris ce ticket en charge.');
}
claimTicketRow(ticket.id, interaction.user.id);
logEvent({
guildId: ticket.guild_id,
type: 'ticket.claimed',
actorId: interaction.user.id,
payload: { ticketId: ticket.id },
});
await interaction.reply({
embeds: [successEmbed(`<@${interaction.user.id}> prend ce ticket en charge.`)],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket pris en charge')
.setDescription(`#${ticket.id} — <#${ticket.channel_id}>`)
.addFields({ name: 'Staff', value: `<@${interaction.user.id}>`, inline: true }),
);
}
/** Closes the ticket: the author or any staff member may do it (M6-T06 / M6-T07). */
export async function closeTicket(interaction, reason = null) {
const ticket = await getChannelTicket(interaction);
const isStaff = getAccessLevel(interaction.member) >= ACCESS_LEVELS.STAFF;
if (interaction.user.id !== ticket.author_id && !isStaff) {
throw new PermissionDeniedError('Seul l’auteur du ticket ou le staff peut le fermer.');
}
closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason });
logEvent({
guildId: ticket.guild_id,
type: 'ticket.closed',
actorId: interaction.user.id,
payload: { ticketId: ticket.id, reason },
});
await interaction.reply({
embeds: [
successEmbed(`Ticket fermé par <@${interaction.user.id}>. Le salon sera supprimé dans 10 secondes.`),
],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket fermé')
.setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`)
.addFields(
{ name: 'Auteur', value: `<@${ticket.author_id}>`, inline: true },
{ name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true },
{ name: 'Raison', value: reason || 'Non précisée' },
),
);
const channel = interaction.channel;
setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref();
}
/** Grants a staff member access to the ticket channel (M6-T07). */
export async function addParticipant(interaction, userId) {
const ticket = await getChannelTicket(interaction);
if (userId === ticket.author_id || userId === ticket.claimed_by) {
throw new UserFacingError('Ce membre participe déjà au ticket.');
}
await interaction.channel.permissionOverwrites.edit(userId, {
ViewChannel: true,
SendMessages: true,
ReadMessageHistory: true,
});
logEvent({
guildId: ticket.guild_id,
type: 'ticket.participant.added',
actorId: interaction.user.id,
payload: { ticketId: ticket.id, userId },
});
await interaction.reply({ embeds: [successEmbed(`<@${userId}> a été ajouté au ticket.`)] });
}
/** Routes the buttons posted in ticket channels. */
export async function handleTicketComponent(interaction) {
switch (interaction.customId) {
case 'ticket:claim':
await claimTicket(interaction);
return;
case 'ticket:close':
await closeTicket(interaction);
return;
default:
log.debug(`Ignored unknown ticket component ${interaction.customId}`);
}
}