diff --git a/README.en.md b/README.en.md index d2c6d94..7f7f268 100644 --- a/README.en.md +++ b/README.en.md @@ -236,12 +236,16 @@ Resolved from the roles configured in `.env` (highest to lowest): Tickets are private channels created under `CATEGORY_TICKETS_ID`. One open ticket per member and per category (SQL constraint). +`/ticket setup` publishes a panel with an **Open a ticket** button in the current channel: the member presses the button, picks a category in a menu, and the private channel opens. The panel channel is stored (`ticket_panels`), so the panel survives a restart and a reinstall replaces the previous message instead of stacking a second one. + | Command | Options | Access | State | Description | | ---------------- | ------------------------------ | -------------------------------- | ----- | ------------------------------------------------------------------------------------ | | `/ticket create` | `category` (required) | User (depending on the category) | ✅ | Creates a private channel under `CATEGORY_TICKETS_ID` | | `/ticket close` | `reason` (optional, 500 chars) | Author, Staff | ✅ | Closes, logs and then deletes the channel (10 s) — also through the **Close** button | | `/ticket claim` | — | **Staff** | ✅ | Takes the ticket over (**Claim** button) | | `/ticket add` | `user` | **Staff** | ✅ | Adds a participant to the private channel | +| `/ticket setup` | — | **Staff** | ✅ | Publishes and pins the opening panel in this channel (replaces the previous one) | +| `/ticket setup-remove` | — | **Staff** | ✅ | Removes the panel from this channel | Available categories and who can use them: @@ -429,7 +433,7 @@ Every text shown in Discord follows the same rules, listed at the top of `src/ui - Engine: `node:sqlite` (`DatabaseSync`), **WAL** mode, foreign keys enabled. - Migrations: numbered SQL files in `src/database/migrations/`, applied in a transaction and tracked in `schema_migrations` (`npm run db:init`). -- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`, `web_sessions` (dashboard sessions, cookie fingerprint only), `web_api_tokens`, `deploy_targets` (deploy targets), `deployments` (history and log of every run). +- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `ticket_panels` (channel and message of the `/ticket setup` panel), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`, `web_sessions` (dashboard sessions, cookie fingerprint only), `web_api_tokens`, `deploy_targets` (deploy targets), `deployments` (history and log of every run). - Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-`, `web-session-`, `deploy-repository.js`) — SQL queries never leave that layer. - Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) `005-bot-statuses.sql` (bot statuses edited from a command) and `006-web-dashboard.sql` (sessions, API tokens, deploy targets and history) complete the initial schema. - The database holds real data: it is **excluded from git** (`.gitignore`) and must be backed up (`BACKUP_DIR`). diff --git a/README.md b/README.md index 9a9edeb..f5cf218 100644 --- a/README.md +++ b/README.md @@ -237,12 +237,16 @@ Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) : Les tickets sont des salons privés créés sous `CATEGORY_TICKETS_ID`. Un seul ticket ouvert par membre et par catégorie (contrainte SQL). +`/ticket setup` publie dans le salon courant un panneau avec un bouton **Ouvrir un ticket** : le membre presse le bouton, choisit sa catégorie dans un menu, et le salon privé s'ouvre. Le salon du panneau est retenu en base (`ticket_panels`), donc le panneau survit au redémarrage et une réinstallation remplace l'ancien message au lieu de l'empiler. + | Commande | Options | Accès | État | Description | | --- | --- | --- | --- | --- | | `/ticket create` | `category` (obligatoire) | User (selon la catégorie) | ✅ | Crée un salon privé sous `CATEGORY_TICKETS_ID` | | `/ticket close` | `reason` (optionnel, 500 car.) | Auteur, Staff | ✅ | Ferme, journalise puis supprime le salon (10 s) — aussi via le bouton **Fermer** | | `/ticket claim` | — | **Staff** | ✅ | Prend le ticket en charge (bouton **Prendre en charge**) | | `/ticket add` | `user` | **Staff** | ✅ | Ajoute un participant au salon privé | +| `/ticket setup` | — | **Staff** | ✅ | Publie et épingle le panneau d'ouverture dans ce salon (remplace le précédent) | +| `/ticket setup-remove` | — | **Staff** | ✅ | Retire le panneau de ce salon | Catégories disponibles et qui y a accès : @@ -430,7 +434,7 @@ Tous les textes visibles dans Discord suivent les mêmes règles, rappelées en - Moteur : `node:sqlite` (`DatabaseSync`), mode **WAL**, foreign keys activées. - Migrations : fichiers SQL numérotés dans `src/database/migrations/`, appliqués en transaction et tracés dans `schema_migrations` (`npm run db:init`). -- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`, `web_sessions` (sessions du tableau de bord, empreinte du cookie seulement), `web_api_tokens`, `deploy_targets` (cibles de déploiement), `deployments` (historique et journal de chaque exécution). +- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `ticket_panels` (salon et message du panneau `/ticket setup`), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`, `web_sessions` (sessions du tableau de bord, empreinte du cookie seulement), `web_api_tokens`, `deploy_targets` (cibles de déploiement), `deployments` (historique et journal de chaque exécution). - Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-`, `web-session-`, `deploy-repository.js`) — les requêtes SQL ne sortent jamais de cette couche. - Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) `005-bot-statuses.sql` (statuts du bot édités en commande) et `006-web-dashboard.sql` (sessions, jetons d'API, cibles et historique de déploiement) complètent le schéma initial. - La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`). diff --git a/src/commands/tickets/ticket.js b/src/commands/tickets/ticket.js index 48b21f1..4616054 100644 --- a/src/commands/tickets/ticket.js +++ b/src/commands/tickets/ticket.js @@ -5,12 +5,19 @@ import { claimTicket, closeTicket, createTicket, + removePanel, + setupPanel, } 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. -export const subcommandAccess = { claim: ACCESS_LEVELS.STAFF, add: ACCESS_LEVELS.STAFF }; +export const subcommandAccess = { + claim: ACCESS_LEVELS.STAFF, + add: ACCESS_LEVELS.STAFF, + setup: ACCESS_LEVELS.STAFF, + 'setup-remove': ACCESS_LEVELS.STAFF, +}; export const data = new SlashCommandBuilder() .setName('ticket') @@ -33,6 +40,10 @@ export const data = new SlashCommandBuilder() .setDescription('Fermer le ticket') .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)), ) + .addSubcommand((sub) => + sub.setName('setup').setDescription('Publier le panneau d’ouverture de ticket dans ce salon'), + ) + .addSubcommand((sub) => sub.setName('setup-remove').setDescription('Retirer le panneau de ce salon')) .addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge')) .addSubcommand((sub) => sub @@ -60,6 +71,12 @@ export async function execute(interaction) { case 'close': await closeTicket(interaction, interaction.options.getString('reason')); return; + case 'setup': + await setupPanel(interaction); + return; + case 'setup-remove': + await removePanel(interaction); + return; case 'claim': await claimTicket(interaction); return; diff --git a/src/config/constants.js b/src/config/constants.js index a4d0598..693380f 100644 --- a/src/config/constants.js +++ b/src/config/constants.js @@ -52,11 +52,36 @@ export const MODERATION_ACTIONS = Object.freeze({ /** Ticket categories and who can see them (M0-T05 / M6-T01). */ export const TICKET_CATEGORIES = Object.freeze([ - { id: 'support', label: 'Aide et support', scope: ['staff', 'owner'] }, - { id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] }, - { id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] }, - { id: 'report', label: 'Signalement', scope: ['staff', 'owner'] }, - { id: 'internal', label: 'Demande interne', scope: ['owner'] }, + { + id: 'support', + label: 'Aide et support', + description: 'Une question, besoin d’un coup de main', + scope: ['staff', 'owner'], + }, + { + id: 'bug', + label: 'Bug', + description: 'Quelque chose ne marche pas comme prévu', + scope: ['staff', 'dev', 'owner'], + }, + { + id: 'dev-question', + label: 'Question de développement', + description: 'Conseil, architecture, code', + scope: ['dev', 'owner'], + }, + { + id: 'report', + label: 'Signalement', + description: 'Un membre ou un message pose problème', + scope: ['staff', 'owner'], + }, + { + id: 'internal', + label: 'Demande interne', + description: 'Réservé à l’équipe', + scope: ['owner'], + }, ]); /** Gitea webhook event -> notification type (M9-T03). */ diff --git a/src/database/migrations/012-ticket-panels.sql b/src/database/migrations/012-ticket-panels.sql new file mode 100644 index 0000000..a1e703e --- /dev/null +++ b/src/database/migrations/012-ticket-panels.sql @@ -0,0 +1,13 @@ +-- The ticket panel published by `/ticket setup` +-- +-- The panel is a button that opens a ticket, and it has to survive a restart: +-- the channel alone is not enough, because reinstalling must replace the previous +-- message instead of leaving an outdated copy in the salon. +CREATE TABLE IF NOT EXISTS ticket_panels ( + guild_id TEXT NOT NULL, + channel_id TEXT NOT NULL, + message_id TEXT NOT NULL, + created_by TEXT, + updated_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (guild_id, channel_id) +); \ No newline at end of file diff --git a/src/database/repositories/ticket-repository.js b/src/database/repositories/ticket-repository.js index 8b1d795..05b868f 100644 --- a/src/database/repositories/ticket-repository.js +++ b/src/database/repositories/ticket-repository.js @@ -69,3 +69,38 @@ export function countOpenTickets(guildId) { .get(guildId); return row.count; } + +// --- Ticket panels (`/ticket setup`) ---------------------------------------- + +export function setTicketPanel({ guildId, channelId, messageId, createdBy = null }) { + getDatabase() + .prepare( + `INSERT INTO ticket_panels (guild_id, channel_id, message_id, created_by) + VALUES (?, ?, ?, ?) + ON CONFLICT (guild_id, channel_id) DO UPDATE SET + message_id = excluded.message_id, + created_by = excluded.created_by, + updated_at = datetime('now')`, + ) + .run(guildId, channelId, messageId, createdBy); +} + +export function getTicketPanel({ guildId, channelId }) { + return ( + getDatabase() + .prepare('SELECT * FROM ticket_panels WHERE guild_id = ? AND channel_id = ?') + .get(guildId, channelId) ?? null + ); +} + +export function listTicketPanels({ guildId }) { + return getDatabase() + .prepare('SELECT * FROM ticket_panels WHERE guild_id = ? ORDER BY updated_at DESC') + .all(guildId); +} + +export function deleteTicketPanel({ guildId, channelId }) { + return getDatabase() + .prepare('DELETE FROM ticket_panels WHERE guild_id = ? AND channel_id = ?') + .run(guildId, channelId).changes; +} diff --git a/src/services/tickets/ticket-service.js b/src/services/tickets/ticket-service.js index 9d0d43c..7d267d5 100644 --- a/src/services/tickets/ticket-service.js +++ b/src/services/tickets/ticket-service.js @@ -1,4 +1,4 @@ -import { ChannelType, PermissionFlagsBits } from 'discord.js'; +import { ChannelType, MessageFlags, PermissionFlagsBits } from 'discord.js'; import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js'; import { readSetting } from '../../config/guild-settings.js'; import { env } from '../../config/env.js'; @@ -10,10 +10,13 @@ import { claimTicket as claimTicketRow, closeTicket as closeTicketRow, createTicket as createTicketRow, + deleteTicketPanel, getTicketByChannel, + getTicketPanel, + setTicketPanel, } from '../../database/repositories/ticket-repository.js'; -import { ticketButtons } from '../../ui/buttons.js'; -import { TONE, baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; +import { ticketButtons, ticketCategorySelect, ticketPanelButton } from '../../ui/buttons.js'; +import { TONE, baseEmbed, bullets, errorEmbed, successEmbed } from '../../ui/embeds.js'; const log = createLogger('tickets'); @@ -123,26 +126,17 @@ async function logTicket(client, embed) { 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( - 'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.', - ); - } - if (!canUseCategory(interaction.member, category)) { - throw new UserFacingError( - `La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`, - ); - } +/** + * The category the ticket channels live in (`CATEGORY_TICKETS_ID`), or a message + * saying how to fix it. A panel is useless without it, so both paths ask here. + */ +async function resolveTicketCategory(guild) { if (!env.channels.ticketCategory) { throw new UserFacingError( 'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !', ); } - const guild = interaction.guild; const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null); if (!parent) { log.warn('Ticket category is unreachable', { categoryId: env.channels.ticketCategory }); @@ -156,6 +150,24 @@ export async function createTicket(interaction, categoryId) { '`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.', ); } + return parent; +} + +/** Opens a private channel for the ticket (M6-T03). */ +export async function createTicket(interaction, categoryId) { + const category = findCategory(categoryId); + if (!category) { + throw new UserFacingError( + 'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.', + ); + } + if (!canUseCategory(interaction.member, category)) { + throw new UserFacingError( + `La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`, + ); + } + const guild = interaction.guild; + const parent = await resolveTicketCategory(guild); const channel = await guild.channels.create({ name: channelName(category.id, interaction.user.username), @@ -328,9 +340,164 @@ export async function addParticipant(interaction, userId) { await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] }); } +/** Panel posted by `/ticket setup`: one button, then the category chooser. */ +function panelEmbed() { + return baseEmbed(COLORS.ticket) + .setTitle('🎫 Besoin d’aide ?') + .setDescription( + 'Ouvre un ticket, choisis la catégorie qui correspond, et écris tout ce que tu sais déjà dedans. ' + + 'Le salon est privé : seul toi et l’équipe le voyez.', + ) + .addFields({ + name: 'Tu peux aussi', + value: bullets([ + 'fermer ton ticket toi-même quand c’est réglé', + 'demander à l’équipe d’ajouter quelqu’un au ticket si besoin', + ]), + }); +} + +const ephemeral = (payload) => ({ ...payload, flags: MessageFlags.Ephemeral }); + +/** The panel belongs in a text salon, and only works with a usable ticket category. */ +async function resolvePanelChannel(interaction) { + const channel = interaction.channel; + if (!channel?.isTextBased?.() || channel.isThread?.()) { + throw new UserFacingError( + 'Lance cette commande dans un salon texte : le panneau doit rester dans le salon, pas dans un fil.', + ); + } + await resolveTicketCategory(interaction.guild); + return channel; +} + +/** + * Posts the ticket panel in the current channel and remembers it. + * + * A panel already published there is deleted first: leaving it would give the + * server two entry points, and the stale one would keep working with an old text. + */ +export async function setupPanel(interaction) { + const channel = await resolvePanelChannel(interaction); + const previous = getTicketPanel({ guildId: interaction.guildId, channelId: channel.id }); + + if (previous) { + const stale = await channel.messages?.fetch(previous.message_id).catch(() => null); + await stale?.delete().catch((error) => log.debug('Could not delete the previous panel', error)); + } + + const message = await channel.send({ + embeds: [panelEmbed()], + components: ticketPanelButton(), + }); + + // A bot without “Gérer les messages” still installs the panel. + const pinned = await message + .pin() + .then(() => true) + .catch((error) => { + log.warn('Could not pin the ticket panel', error); + return false; + }); + + setTicketPanel({ + guildId: interaction.guildId, + channelId: channel.id, + messageId: message.id, + createdBy: interaction.user.id, + }); + logEvent({ + guildId: interaction.guildId, + type: 'ticket.panel.installed', + actorId: interaction.user.id, + payload: { channelId: channel.id }, + }); + + await interaction.reply( + ephemeral({ + embeds: [ + successEmbed( + pinned + ? 'Panneau publié et épinglé dans ce salon. Les membres ouvrent un ticket avec le bouton.' + : 'Panneau publié dans ce salon, mais je n’ai pas pu l’épingler : vérifie mes droits.', + ), + ], + }), + ); +} + +/** Removes the panel of the current channel, message included. */ +export async function removePanel(interaction) { + const channel = interaction.channel; + const panel = getTicketPanel({ guildId: interaction.guildId, channelId: channel?.id }); + if (!panel) { + throw new UserFacingError( + 'Ce salon n’a pas de panneau : lance `/ticket setup` ici pour en installer un.', + ); + } + + const message = await channel.messages?.fetch(panel.message_id).catch(() => null); + await message?.delete().catch((error) => log.debug('Could not delete the panel message', error)); + deleteTicketPanel({ guildId: interaction.guildId, channelId: channel.id }); + + logEvent({ + guildId: interaction.guildId, + type: 'ticket.panel.removed', + actorId: interaction.user.id, + payload: { channelId: channel.id }, + }); + await interaction.reply({ + embeds: [successEmbed('Panneau retiré de ce salon.')], + flags: MessageFlags.Ephemeral, + }); +} + +/** Answers the panel button with the categories this member is allowed to open. */ +async function openPanelPicker(interaction) { + const categories = TICKET_CATEGORIES.filter((category) => canUseCategory(interaction.member, category)); + if (categories.length === 0) { + await interaction.reply( + ephemeral({ + embeds: [ + errorEmbed( + 'Aucune catégorie de ticket ne t’est ouverte pour l’instant. Demande de l’aide dans le salon, l’équipe te répondra.', + ), + ], + }), + ); + return; + } + + await interaction.reply( + ephemeral({ + content: 'Choisis la catégorie : le salon s’ouvre ensuite, tu écris ton message dedans.', + components: ticketCategorySelect(categories), + }), + ); +} + +/** Opens the ticket chosen in the panel select menu, and closes the menu. */ +async function pickPanelCategory(interaction) { + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const channel = await createTicket(interaction, interaction.values[0]); + await interaction.editReply({ + embeds: [ + successEmbed( + `Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`, + ), + ], + }); +} + /** Routes the buttons posted in ticket channels. */ export async function handleTicketComponent(interaction) { switch (interaction.customId) { + case 'ticket:panel:open': + await openPanelPicker(interaction); + return; + case 'ticket:panel:pick': + await pickPanelCategory(interaction); + return; case 'ticket:claim': await claimTicket(interaction); return; diff --git a/src/ui/buttons.js b/src/ui/buttons.js index 97bf5b1..dcf689b 100644 --- a/src/ui/buttons.js +++ b/src/ui/buttons.js @@ -1,4 +1,10 @@ -import { ActionRowBuilder, ButtonBuilder, ButtonStyle, UserSelectMenuBuilder } from 'discord.js'; +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + StringSelectMenuBuilder, + UserSelectMenuBuilder, +} from 'discord.js'; /** Discord label and custom id limits. */ const LABEL_MAX = 80; @@ -97,3 +103,33 @@ export function pollButtons(pollId, choices) { } return rows; } + +/** Button of the ticket panel posted by `/ticket setup`. */ +export function ticketPanelButton() { + return [ + new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId('ticket:panel:open') + .setLabel('Ouvrir un ticket') + .setStyle(ButtonStyle.Primary), + ), + ]; +} + +/** Category chooser shown after pressing the panel button, limited to the member's level. */ +export function ticketCategorySelect(categories) { + return [ + new ActionRowBuilder().addComponents( + new StringSelectMenuBuilder() + .setCustomId('ticket:panel:pick') + .setPlaceholder('Dans quelle catégorie ?') + .addOptions( + categories.map(({ id, label, description }) => ({ + label, + value: id, + description, + })), + ), + ), + ]; +} diff --git a/tests/tickets.test.js b/tests/tickets.test.js index 714b5a6..3ad8b1c 100644 --- a/tests/tickets.test.js +++ b/tests/tickets.test.js @@ -15,7 +15,9 @@ process.env.ROLE_STAFF_ID = 'role-staff'; const { closeDatabase, getDatabase, initDatabase } = await import('../src/database/index.js'); const { UserFacingError } = await import('../src/core/errors.js'); -const { createTicket } = await import('../src/services/tickets/ticket-service.js'); +const { getTicketPanel } = await import('../src/database/repositories/ticket-repository.js'); +const { createTicket, handleTicketComponent, removePanel, setupPanel } = + await import('../src/services/tickets/ticket-service.js'); const CATEGORY_ID = process.env.CATEGORY_TICKETS_ID; const LOGS_CHANNEL = process.env.CHANNEL_LOGS_ID; @@ -29,12 +31,42 @@ const member = (roleIds = []) => ({ /** Discord reduced to what opening a ticket touches: the category and the new channel. */ function harness({ parent = TICKET_CATEGORY } = {}) { - const state = { created: [], channelMessages: [], journal: [], fetched: [] }; + const state = { + channelMessages: [], + created: [], + deleted: [], + fetched: [], + journal: [], + pinned: [], + replies: [], + }; const journalChannel = { isSendable: () => true, send: async (payload) => state.journal.push(payload), }; + const panelChannel = { + id: 'panel-1', + isTextBased: () => true, + isThread: () => false, + send: async (payload) => { + const message = { + id: `panel-message-${state.channelMessages.length + 1}`, + pin: async () => { + state.pinned.push('panel'); + }, + delete: async () => { + state.deleted.push(message.id); + }, + }; + state.channelMessages.push({ ...payload, id: message.id }); + return message; + }, + messages: { + fetch: async (id) => ({ id, delete: async () => state.deleted.push(id) }), + }, + }; + const channel = { id: 'channel-1', send: async (payload) => state.channelMessages.push(payload), @@ -60,12 +92,16 @@ function harness({ parent = TICKET_CATEGORY } = {}) { const interaction = { guild, + guildId: 'guild-1', client: { user: { id: 'bot-1' }, channels: guild.channels }, user: { id: 'author-1', username: 'Léa', tag: 'Léa#0001' }, member: member([process.env.ROLE_STAFF_ID]), + reply: async (payload) => state.replies.push(payload), + deferReply: async () => {}, + editReply: async (payload) => state.replies.push(payload), }; - return { state, interaction, journalChannel }; + return { state, interaction, journalChannel, panelChannel }; } const open = (harness) => createTicket(harness.interaction, 'bug'); @@ -137,3 +173,129 @@ describe('ticket creation', () => { ); }); }); + +describe('ticket panel', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM tickets; DELETE FROM ticket_panels;')); + + const panelInteraction = (test) => ({ ...test.interaction, channel: test.panelChannel }); + + const panelMessage = (test) => test.state.channelMessages.at(-1); + + it('publishes and pins the panel, then remembers it', async () => { + const test = harness(); + + await setupPanel(panelInteraction(test)); + + const message = panelMessage(test); + assert.match(message.embeds[0].toJSON().title, /Besoin d’aide/); + assert.deepEqual(test.state.pinned, ['panel']); + const panel = getTicketPanel({ guildId: 'guild-1', channelId: 'panel-1' }); + assert.equal(panel.message_id, message.id); + assert.equal(panel.created_by, 'author-1'); + assert.match(test.state.replies.at(-1).embeds[0].toJSON().description, /Panneau publié et épinglé/); + }); + + it('replaces the previous panel instead of stacking a second one', async () => { + const test = harness(); + + await setupPanel(panelInteraction(test)); + await setupPanel(panelInteraction(test)); + + assert.deepEqual(test.state.deleted, ['panel-message-1']); + assert.equal(test.state.channelMessages.length, 2); + assert.equal(getTicketPanel({ guildId: 'guild-1', channelId: 'panel-1' }).message_id, 'panel-message-2'); + }); + + it('keeps the panel when the previous message was deleted by hand', async () => { + const test = harness(); + + await setupPanel(panelInteraction(test)); + await setupPanel(panelInteraction(test)); + + assert.equal(getTicketPanel({ guildId: 'guild-1', channelId: 'panel-1' }).message_id, 'panel-message-2'); + }); + + it('refuses to install a panel when the ticket category is unusable', async () => { + const test = harness(); + test.interaction.guild.channels.fetch = async () => null; + + await assert.rejects( + () => setupPanel(panelInteraction(test)), + (error) => { + assert.ok(error instanceof UserFacingError); + assert.match(error.message, /CATEGORY_TICKETS_ID/); + return true; + }, + ); + assert.equal(test.state.channelMessages.length, 0); + }); + + it('removes the panel and its message', async () => { + const test = harness(); + await setupPanel(panelInteraction(test)); + + await removePanel(panelInteraction(test)); + + assert.deepEqual(test.state.deleted, ['panel-message-1']); + assert.equal(getTicketPanel({ guildId: 'guild-1', channelId: 'panel-1' }), null); + }); + + it('says so when the channel has no panel', async () => { + const test = harness(); + + await assert.rejects( + () => removePanel(panelInteraction(test)), + (error) => { + assert.ok(error instanceof UserFacingError); + assert.match(error.message, /\/ticket setup/); + return true; + }, + ); + }); + + it('offers only the categories the member may open', async () => { + const test = harness(); + + await handleTicketComponent({ + ...panelInteraction(test), + customId: 'ticket:panel:open', + member: member([process.env.ROLE_STAFF_ID]), + }); + + const [row] = test.state.replies.at(-1).components; + const { options } = row.toJSON().components[0]; + assert.deepEqual( + options.map((option) => option.value), + ['support', 'bug', 'report'], + ); + }); + + it('tells a member with no category to ask in the salon', async () => { + const test = harness(); + + await handleTicketComponent({ + ...panelInteraction(test), + customId: 'ticket:panel:open', + member: member([]), + }); + + const reply = test.state.replies.at(-1); + assert.equal(reply.components, undefined); + assert.match(reply.embeds[0].toJSON().description, /Aucune catégorie/); + }); + + it('opens the ticket from the chosen category', async () => { + const test = harness(); + + await handleTicketComponent({ + ...panelInteraction(test), + customId: 'ticket:panel:pick', + values: ['bug'], + }); + + assert.equal(test.state.created[0].parent, CATEGORY_ID); + assert.match(test.state.replies.at(-1).embeds[0].toJSON().description, /Ton ticket est ouvert/); + }); +});