6 Commits
Author SHA1 Message Date
BlackAngelTV ed14b8260c feat(tickets): open tickets from a panel button in any channel
CI / quality (push) Has been cancelled
Members had to know `/ticket create` and its category list to reach support,
so the entry point is now a panel: `/ticket setup` publishes it in the current
channel, the button opens a menu of the categories the member is allowed to
open, and the choice creates the ticket.

The panel channel and message are stored in `ticket_panels`, so a reinstall
replaces the previous message instead of leaving the server two entry points,
and the panel survives a restart.
2026-10-02 20:29:22 +02:00
BlackAngelTV 1310840215 feat(tickets): guide members in ticket channels and log to the technical salon
CI / quality (push) Has been cancelled
Tickets were opened with three words and members expected an immediate answer,
so the channel now posts a guidance embed: what details to give (context, steps
to reproduce, exact error, OS version) and that a reply can take a while.

The ticket journal moves to CHANNEL_LOGS_ID so the environment keeps one log
salon per purpose: CHANNEL_TICKETS_LOGS_ID held the same entries and nothing
else read it. A wrong CATEGORY_TICKETS_ID now says which case it is, since a
missing category was reported as a mistyped one.
2026-10-02 20:13:31 +02:00
BlackAngelTV a996065861 Merge pull request 'Feat/dashboard rules' (#150) from feat/dashboard-rules into main
CI / quality (push) Has been cancelled
Reviewed-on: #150
2026-09-25 19:16:10 +00:00
BlackAngelTV ffb54a8e37 chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
2026-09-25 21:14:00 +02:00
BlackAngelTV e6ce594b34 fix(rules): show the rules field with a save button and edit the message
The rules lived in a card of their own that never showed up next to the
settings, so the section read as an empty toggle nobody could fill in. The
markdown now renders as a real field with an "Enregistrer" button, and
saving edits the message already pinned instead of deleting it and
posting a new one: same link, same place, pin kept.
2026-09-25 21:14:00 +02:00
BlackAngelTV 4e0f43eace Merge pull request 'Feat/dashboard rules' (#149) from feat/dashboard-rules into main
CI / quality (push) Has been cancelled
Reviewed-on: #149
2026-09-25 18:50:41 +00:00
18 changed files with 829 additions and 213 deletions

No files matched your search

-1
View File
@@ -33,7 +33,6 @@ CHANNEL_RULES_ID=
CHANNEL_ANNOUNCEMENTS_ID= CHANNEL_ANNOUNCEMENTS_ID=
CHANNEL_LOGS_ID= CHANNEL_LOGS_ID=
CHANNEL_MOD_LOGS_ID= CHANNEL_MOD_LOGS_ID=
CHANNEL_TICKETS_LOGS_ID=
CHANNEL_NOTIF_ISSUES_ID= CHANNEL_NOTIF_ISSUES_ID=
CHANNEL_NOTIF_PULL_REQUESTS_ID= CHANNEL_NOTIF_PULL_REQUESTS_ID=
CHANNEL_NOTIF_COMMITS_ID= CHANNEL_NOTIF_COMMITS_ID=
+1
View File
@@ -93,6 +93,7 @@ The project follows [Semantic Versioning](https://semver.org/).
- **config:** _(feat)_ load and expose environment settings ([d1388b6]) - **config:** _(feat)_ load and expose environment settings ([d1388b6])
### Bug Fixes ### Bug Fixes
- **rules:** _(fix)_ show the rules field with a save button and edit the message ([e6ce594])
- **moderation:** _(fix)_ tell a mute apart from a kick in the logs ([99e1fd2]) - **moderation:** _(fix)_ tell a mute apart from a kick in the logs ([99e1fd2])
- **wiki:** _(fix)_ render the public pages on the server ([8869c74]) - **wiki:** _(fix)_ render the public pages on the server ([8869c74])
- **web:** _(fix)_ stop caching the interface modules ([3f4a570]) - **web:** _(fix)_ stop caching the interface modules ([3f4a570])
+8 -4
View File
@@ -126,11 +126,11 @@ Full template: [`.env.example`](.env.example). Default values in brackets.
| Variable | Usage | | Variable | Usage |
| -------------------------------- | --------------------------------------------------------------------------- | | -------------------------------- | --------------------------------------------------------------------------- |
| `CHANNEL_WELCOME_ID` | Welcome messages | | `CHANNEL_WELCOME_ID` | Welcome messages |
| `CHANNEL_RULES_ID` | Rules: link sent to newcomers, and where the dashboard pins the message | | `CHANNEL_RULES_ID` | Rules: link sent to newcomers, and where the dashboard pins the message. |
| | Later saves edit that same message |
| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements | | `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements |
| `CHANNEL_LOGS_ID` | Functional logs | | `CHANNEL_LOGS_ID` | Functional and technical logs, ticket journal |
| `CHANNEL_MOD_LOGS_ID` | Moderation logs | | `CHANNEL_MOD_LOGS_ID` | Moderation logs |
| `CHANNEL_TICKETS_LOGS_ID` | Ticket opening/closing journal |
| `CHANNEL_NOTIF_ISSUES_ID` | Issue notifications | | `CHANNEL_NOTIF_ISSUES_ID` | Issue notifications |
| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Pull request notifications | | `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Pull request notifications |
| `CHANNEL_NOTIF_COMMITS_ID` | Commit notifications | | `CHANNEL_NOTIF_COMMITS_ID` | Commit notifications |
@@ -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). 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 | | Command | Options | Access | State | Description |
| ---------------- | ------------------------------ | -------------------------------- | ----- | ------------------------------------------------------------------------------------ | | ---------------- | ------------------------------ | -------------------------------- | ----- | ------------------------------------------------------------------------------------ |
| `/ticket create` | `category` (required) | User (depending on the category) | ✅ | Creates a private channel under `CATEGORY_TICKETS_ID` | | `/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 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 claim` | — | **Staff** | ✅ | Takes the ticket over (**Claim** button) |
| `/ticket add` | `user` | **Staff** | ✅ | Adds a participant to the private channel | | `/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: 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. - 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`). - 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. - 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. - 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`). - The database holds real data: it is **excluded from git** (`.gitignore`) and must be backed up (`BACKUP_DIR`).
+7 -4
View File
@@ -128,11 +128,10 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
| Variable | Usage | | Variable | Usage |
| --- | --- | | --- | --- |
| `CHANNEL_WELCOME_ID` | Messages de bienvenue | | `CHANNEL_WELCOME_ID` | Messages de bienvenue |
| `CHANNEL_RULES_ID` | Règlement : lien envoyé aux nouveaux, et salon où le tableau de bord publie le message épinglé | | `CHANNEL_RULES_ID` | Règlement : lien envoyé aux nouveaux, et salon où le tableau de bord publie le message épinglé (les enregistrements suivants le modifient) |
| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS | | `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS |
| `CHANNEL_LOGS_ID` | Logs fonctionnels | | `CHANNEL_LOGS_ID` | Logs fonctionnels et techniques, journal des tickets |
| `CHANNEL_MOD_LOGS_ID` | Logs de modération | | `CHANNEL_MOD_LOGS_ID` | Logs de modération |
| `CHANNEL_TICKETS_LOGS_ID` | Journal d'ouverture/fermeture des tickets |
| `CHANNEL_NOTIF_ISSUES_ID` | Notifications issues | | `CHANNEL_NOTIF_ISSUES_ID` | Notifications issues |
| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Notifications pull requests | | `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Notifications pull requests |
| `CHANNEL_NOTIF_COMMITS_ID` | Notifications commits | | `CHANNEL_NOTIF_COMMITS_ID` | Notifications commits |
@@ -238,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). 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 | | 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 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 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 claim` | — | **Staff** | ✅ | Prend le ticket en charge (bouton **Prendre en charge**) |
| `/ticket add` | `user` | **Staff** | ✅ | Ajoute un participant au salon privé | | `/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 : Catégories disponibles et qui y a accès :
@@ -431,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. - 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`). - 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. - 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. - 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`). - La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`).
+2 -2
View File
@@ -62,7 +62,7 @@ Le commutateur en bas de la barre latérale masque ou révèle les panneaux tech
| **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes | | **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes |
| **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot | | **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot |
| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués | | **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués |
| **Paramètres** | Comportement du bot, règlement du serveur, connexions, sessions, jetons d'API, maintenance | | **Paramètres** | Comportement du bot, règlement, connexions, sessions, jetons d'API, maintenance |
| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré | | **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré |
## 4. Assistant de configuration ## 4. Assistant de configuration
@@ -212,7 +212,7 @@ Les changements prennent effet immédiatement, sans redémarrage, contrairement
### Rédiger et publier le règlement ### Rédiger et publier le règlement
La carte **Règlement du serveur** écrit les règles en markdown (celui de Discord : `**gras**`, `*italique*`, `code`, listes, titres) et les publie dans `CHANNEL_RULES_ID` sous forme d'un embed épinglé. Publier supprime le message précédent avant d'envoyer le nouveau : le salon ne garde qu'une seule version, épinglée, et l'identifiant du message est retenu en base (`rules_messages`) pour pouvoir le remplacer la fois suivante. Un message supprimé à la main, un salon devenu inaccessible ou une épinglage refusé n'empêchent pas la publication ; l'échec de l'épinglage est simplement signalé. Le texte est enregistré même si la publication échoue, pour ne pas perdre ce qui a été écrit. Niveau **Dev** requis. La section **Règlement** de la page Paramètres écrit les règles en markdown (celui de Discord : `**gras**`, `*italique*`, `code`, listes, titres) et **Enregistrer** les publie dans `CHANNEL_RULES_ID` sous forme d'un embed épinglé. L'identifiant du message est retenu en base (`rules_messages`) : les enregistrements suivants **modifient ce message**, même lien, même place dans le salon et épingle conservée, au lieu d'empiler les versions. Un message supprimé à la main, un salon devenu inaccessible ou un bot qui ne peut plus éditer font repartir sur un nouveau message ; un épinglage refusé est signalé sans bloquer la publication. Le texte est enregistré même si la publication échoue, pour ne pas perdre ce qui a été écrit. Niveau **Dev** requis.
## 10. Publier les commandes slash ## 10. Publier les commandes slash
+18 -1
View File
@@ -5,12 +5,19 @@ import {
claimTicket, claimTicket,
closeTicket, closeTicket,
createTicket, createTicket,
removePanel,
setupPanel,
} from '../../services/tickets/ticket-service.js'; } from '../../services/tickets/ticket-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
// `close` is also allowed for the ticket author: checked in the ticket service. // `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() export const data = new SlashCommandBuilder()
.setName('ticket') .setName('ticket')
@@ -33,6 +40,10 @@ export const data = new SlashCommandBuilder()
.setDescription('Fermer le ticket') .setDescription('Fermer le ticket')
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)), .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.setName('claim').setDescription('Prendre le ticket en charge'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
@@ -60,6 +71,12 @@ export async function execute(interaction) {
case 'close': case 'close':
await closeTicket(interaction, interaction.options.getString('reason')); await closeTicket(interaction, interaction.options.getString('reason'));
return; return;
case 'setup':
await setupPanel(interaction);
return;
case 'setup-remove':
await removePanel(interaction);
return;
case 'claim': case 'claim':
await claimTicket(interaction); await claimTicket(interaction);
return; return;
+30 -5
View File
@@ -52,11 +52,36 @@ export const MODERATION_ACTIONS = Object.freeze({
/** Ticket categories and who can see them (M0-T05 / M6-T01). */ /** Ticket categories and who can see them (M0-T05 / M6-T01). */
export const TICKET_CATEGORIES = Object.freeze([ export const TICKET_CATEGORIES = Object.freeze([
{ id: 'support', label: 'Aide et support', scope: ['staff', 'owner'] }, {
{ id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] }, id: 'support',
{ id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] }, label: 'Aide et support',
{ id: 'report', label: 'Signalement', scope: ['staff', 'owner'] }, description: 'Une question, besoin d’un coup de main',
{ id: 'internal', label: 'Demande interne', scope: ['owner'] }, 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). */ /** Gitea webhook event -> notification type (M9-T03). */
-1
View File
@@ -43,7 +43,6 @@ export const env = Object.freeze({
announcements: read('CHANNEL_ANNOUNCEMENTS_ID'), announcements: read('CHANNEL_ANNOUNCEMENTS_ID'),
logs: read('CHANNEL_LOGS_ID'), logs: read('CHANNEL_LOGS_ID'),
modLogs: read('CHANNEL_MOD_LOGS_ID'), modLogs: read('CHANNEL_MOD_LOGS_ID'),
ticketLogs: read('CHANNEL_TICKETS_LOGS_ID'),
notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'), notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'),
notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'), notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'),
notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'), notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'),
+3 -3
View File
@@ -20,7 +20,7 @@ export const SETTING_SECTIONS = Object.freeze([
{ {
id: 'rules', id: 'rules',
title: 'Règlement', title: 'Règlement',
summary: 'Message publié et épinglé dans le salon des règles.', summary: 'Message affiché et épinglé dans le salon des règles.',
}, },
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' }, { id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
{ {
@@ -120,8 +120,8 @@ export const GUILD_SETTINGS = Object.freeze([
key: 'rules.markdown', key: 'rules.markdown',
section: 'rules', section: 'rules',
label: 'Règlement (markdown)', label: 'Règlement (markdown)',
help: 'Publié et épinglé dans le salon des règles (`CHANNEL_RULES_ID`). Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Publier remplace le message précédent.', help: 'Enregistré et épinglé dans le salon des règles (`CHANNEL_RULES_ID`). Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Enregistrer modifie le message déjà publié.',
type: 'text', type: 'markdown',
default: '', default: '',
maxLength: 4000, maxLength: 4000,
}, },
@@ -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)
);
@@ -69,3 +69,38 @@ export function countOpenTickets(guildId) {
.get(guildId); .get(guildId);
return row.count; 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;
}
+64 -43
View File
@@ -6,12 +6,13 @@ import { getRulesMessage, setRulesMessage } from '../../database/repositories/ru
import { baseEmbed } from '../../ui/embeds.js'; import { baseEmbed } from '../../ui/embeds.js';
/** /**
* Rules of the server, written from the dashboard and published as a single * Rules of the server, written from the dashboard and kept in a single pinned
* pinned message in `CHANNEL_RULES_ID` (M19). * message in `CHANNEL_RULES_ID` (M19).
* *
* Publishing deletes the message the bot posted last time before sending the * Saving edits the message already published, so the channel keeps one set of
* new one: the channel keeps a single set of rules, and members following the * rules — same link, same position, and the pin survives. A new message is
* channel see the update rather than a second copy. * only sent when the bot has none yet, or when the previous one was deleted by
* hand.
*/ */
const log = createLogger('rules'); const log = createLogger('rules');
@@ -21,11 +22,18 @@ export const RULES_MAX_LENGTH = 4000;
const TITLE = '📜 Règlement'; const TITLE = '📜 Règlement';
const rulesEmbed = (content) =>
baseEmbed(COLORS.primary)
.setTitle(TITLE)
.setDescription(content)
.setFooter({ text: 'Mis à jour depuis le tableau de bord FWS-Bot' })
.setTimestamp(new Date());
/** /**
* Replaces the published rules with `markdown`. * Publishes the rules, editing the message already there when there is one.
* @param {import('discord.js').Client} client * @param {import('discord.js').Client} client
* @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options * @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options
* @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean }>} * @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean, edited: boolean }>}
*/ */
export async function publishRules( export async function publishRules(
client, client,
@@ -46,57 +54,70 @@ export async function publishRules(
throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.'); throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.');
} }
await deletePublishedRules(client, guildId); const edited = await editPublishedRules(client, guildId, content);
const message = edited ?? (await channel.send({ embeds: [rulesEmbed(content)] }));
const embed = baseEmbed(COLORS.primary) // Only a brand new message has to be pinned: an edited one keeps its pin.
.setTitle(TITLE) const pinned = edited
.setDescription(content) ? true
.setFooter({ text: 'Mis à jour depuis le tableau de bord FWS-Bot' }) : await message
.setTimestamp(new Date()); .pin()
.then(() => true)
.catch((error) => {
// A bot without “Gérer les messages” still publishes the rules.
log.warn('Could not pin the rules message', error);
return false;
});
const message = await channel.send({ embeds: [embed] }); setRulesMessage({
guildId,
// Pinning is a convenience, not a requirement: a bot without “Gérer les channelId,
// messages” still publishes the rules. messageId: message.id,
const pinned = await message updatedBy: actorId,
.pin() });
.then(() => true)
.catch((error) => {
log.warn('Could not pin the rules message', error);
return false;
});
setRulesMessage({ guildId, channelId, messageId: message.id, updatedBy: actorId });
logEvent({ logEvent({
guildId, guildId,
type: 'web.rules.published', type: 'web.rules.published',
actorId, actorId,
payload: { channelId, messageId: message.id, pinned }, payload: { channelId, messageId: message.id, pinned, edited: Boolean(edited) },
});
log.info('Rules saved from the dashboard', {
channelId,
messageId: message.id,
edited: Boolean(edited),
actor: actorId,
}); });
log.info('Rules published from the dashboard', { channelId, messageId: message.id, actor: actorId });
return { messageId: message.id, url: message.url ?? null, channelId, pinned }; return {
messageId: message.id,
url: message.url ?? null,
channelId,
pinned,
edited: Boolean(edited),
};
} }
/** Removes the message the bot published last time, if it is still there. */ /**
export async function deletePublishedRules(client, guildId) { * Rewrites the message the bot published last time.
* @returns the edited message, or null when there is none to edit
*/
async function editPublishedRules(client, guildId, content) {
const stored = getRulesMessage(guildId); const stored = getRulesMessage(guildId);
if (!stored) return false; if (!stored) return null;
const channel = await client.channels.fetch(stored.channel_id).catch(() => null); const channel = await client.channels.fetch(stored.channel_id).catch(() => null);
const message = await channel?.messages?.fetch(stored.message_id).catch(() => null); const message = await channel?.messages?.fetch(stored.message_id).catch(() => null);
const deleted = await message if (!message?.editable) return null;
?.delete()
.then(() => true)
.catch((error) => {
// A message deleted by hand, or a channel the bot no longer sees, must
// not stop the republication.
log.warn('Could not delete the previous rules message', error);
return false;
});
if (deleted !== false) return Boolean(deleted); return message
return false; .edit({ embeds: [rulesEmbed(content)] })
.then((edited) => edited ?? message)
.catch((error) => {
// A message deleted by hand, or one the bot may no longer edit, must not
// stop the publication: a fresh one takes its place.
log.warn('Could not edit the previous rules message', error);
return null;
});
} }
/** What the dashboard needs to show the current state of the rules. */ /** What the dashboard needs to show the current state of the rules. */
+225 -22
View File
@@ -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 { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js';
import { readSetting } from '../../config/guild-settings.js'; import { readSetting } from '../../config/guild-settings.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
@@ -10,10 +10,13 @@ import {
claimTicket as claimTicketRow, claimTicket as claimTicketRow,
closeTicket as closeTicketRow, closeTicket as closeTicketRow,
createTicket as createTicketRow, createTicket as createTicketRow,
deleteTicketPanel,
getTicketByChannel, getTicketByChannel,
getTicketPanel,
setTicketPanel,
} from '../../database/repositories/ticket-repository.js'; } from '../../database/repositories/ticket-repository.js';
import { ticketButtons } from '../../ui/buttons.js'; import { ticketButtons, ticketCategorySelect, ticketPanelButton } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js'; import { TONE, baseEmbed, bullets, errorEmbed, successEmbed } from '../../ui/embeds.js';
const log = createLogger('tickets'); const log = createLogger('tickets');
@@ -39,10 +42,7 @@ function ticketEmbed(ticket, category) {
const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne'; const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne';
return baseEmbed(COLORS.ticket) return baseEmbed(COLORS.ticket)
.setTitle(`🎫 Ticket ${category.label} #${ticket.id}`) .setTitle(`🎫 Ticket ${category.label} #${ticket.id}`)
.setDescription( .setDescription(`<@${ticket.author_id}> décris ta demande ici, l’équipe lit ce salon.`)
`<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` +
'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.',
)
.addFields( .addFields(
{ name: 'Catégorie', value: category.label, inline: true }, { name: 'Catégorie', value: category.label, inline: true },
{ name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true }, { name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
@@ -50,6 +50,37 @@ function ticketEmbed(ticket, category) {
); );
} }
/**
* Guidance posted under the ticket header: what to write, and that an answer can
* take a while. Members often open a ticket with three words and wait.
*/
function ticketHelpEmbed() {
return baseEmbed(COLORS.info)
.setTitle(TONE.advice)
.setDescription(
'Détaille au maximum : tout ce que tu écris ici nous évite de te poser des questions pour rien.',
)
.addFields(
{
name: 'Ce qui nous aide',
value: bullets([
'ce que tu voulais faire, et ce qui s’est passé à la place',
'les étapes pour reproduire le problème, une par une',
'le message d’erreur exact, en photo ou recopié tel quel',
'ta version de l’OS, et ce que tu viens d’installer',
]),
},
{
name: 'Ça peut prendre un peu de temps',
value: bullets([
'ce salon est privé : toi, l’équipe et les personnes que vous ajoutez y voient ces messages',
'l’équipe répond ici, donc ne cherche pas ailleurs pour suivre ton ticket',
'une fois ta demande réglée, ferme le ticket avec le bouton **Fermer**',
]),
},
);
}
function channelName(categoryId, username) { function channelName(categoryId, username) {
const slug = username const slug = username
.toLowerCase() .toLowerCase()
@@ -83,9 +114,10 @@ function buildOverwrites(guild, client, category, authorId) {
return overwrites; return overwrites;
} }
/** The ticket journal lives in the technical logs salon (`CHANNEL_LOGS_ID`). */
async function fetchTicketLogChannel(client) { async function fetchTicketLogChannel(client) {
if (!env.channels.ticketLogs) return null; if (!env.channels.logs) return null;
const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null); const channel = await client.channels.fetch(env.channels.logs).catch(() => null);
return channel?.isSendable() ? channel : null; return channel?.isSendable() ? channel : null;
} }
@@ -94,6 +126,33 @@ async function logTicket(client, embed) {
await channel?.send({ embeds: [embed] }); await channel?.send({ embeds: [embed] });
} }
/**
* 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 parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null);
if (!parent) {
log.warn('Ticket category is unreachable', { categoryId: env.channels.ticketCategory });
throw new UserFacingError(
'`CATEGORY_TICKETS_ID` ne pointe vers aucun salon accessible : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.',
);
}
if (parent.type !== ChannelType.GuildCategory) {
log.warn('Ticket category is not a category', { categoryId: parent.id, type: parent.type });
throw new UserFacingError(
'`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). */ /** Opens a private channel for the ticket (M6-T03). */
export async function createTicket(interaction, categoryId) { export async function createTicket(interaction, categoryId) {
const category = findCategory(categoryId); const category = findCategory(categoryId);
@@ -107,19 +166,8 @@ export async function createTicket(interaction, categoryId) {
`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.`, `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.`,
); );
} }
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 guild = interaction.guild;
const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null); const parent = await resolveTicketCategory(guild);
if (parent?.type !== ChannelType.GuildCategory) {
throw new UserFacingError(
'`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`.',
);
}
const channel = await guild.channels.create({ const channel = await guild.channels.create({
name: channelName(category.id, interaction.user.username), name: channelName(category.id, interaction.user.username),
@@ -157,7 +205,7 @@ export async function createTicket(interaction, categoryId) {
await channel.send({ await channel.send({
content: `<@${ticket.author_id}>`, content: `<@${ticket.author_id}>`,
embeds: [ticketEmbed(ticket, category)], embeds: [ticketEmbed(ticket, category), ticketHelpEmbed()],
components: ticketButtons(), components: ticketButtons(),
}); });
@@ -292,9 +340,164 @@ export async function addParticipant(interaction, userId) {
await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] }); 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. */ /** Routes the buttons posted in ticket channels. */
export async function handleTicketComponent(interaction) { export async function handleTicketComponent(interaction) {
switch (interaction.customId) { switch (interaction.customId) {
case 'ticket:panel:open':
await openPanelPicker(interaction);
return;
case 'ticket:panel:pick':
await pickPanelCategory(interaction);
return;
case 'ticket:claim': case 'ticket:claim':
await claimTicket(interaction); await claimTicket(interaction);
return; return;
+37 -1
View File
@@ -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. */ /** Discord label and custom id limits. */
const LABEL_MAX = 80; const LABEL_MAX = 80;
@@ -97,3 +103,33 @@ export function pollButtons(pollId, choices) {
} }
return rows; 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,
})),
),
),
];
}
+39 -88
View File
@@ -56,6 +56,30 @@ function settingControl(setting, value, apply) {
); );
} }
// Markdown is a long text: a single-line input would hide what is written.
if (setting.type === 'markdown') {
const editor = textarea({
value: value ?? '',
rows: 12,
maxlength: setting.maxLength,
placeholder: '## Règlement\n\n1. …\n2. …',
});
return field(
setting.label,
h(
'div',
{ class: 'stack' },
editor,
h(
'div',
{ class: 'row' },
button('Enregistrer', () => apply(editor.value), { tone: 'primary' }),
),
),
{ help: setting.help },
);
}
const control = input({ const control = input({
value: value ?? '', value: value ?? '',
type: setting.type === 'int' ? 'number' : 'text', type: setting.type === 'int' ? 'number' : 'text',
@@ -77,11 +101,7 @@ function settingControl(setting, value, apply) {
function behaviourCard(data, level, reload) { function behaviourCard(data, level, reload) {
const editable = level >= LEVELS.DEV; const editable = level >= LEVELS.DEV;
// The rules get their own card: a plain text field would not carry the const schema = Array.isArray(data.schema) ? data.schema : [];
// markdown editor nor the publishing button.
const schema = (Array.isArray(data.schema) ? data.schema : []).filter(
(setting) => setting.key !== 'rules.markdown',
);
const values = data.values ?? {}; const values = data.values ?? {};
// Falling back to one section keeps the page useful against an API that does // Falling back to one section keeps the page useful against an API that does
@@ -115,6 +135,20 @@ function behaviourCard(data, level, reload) {
const apply = async (next) => { const apply = async (next) => {
try { try {
// The rules are a message on Discord, not a stored value: saving
// them has to publish them.
if (setting.key === 'rules.markdown') {
const published = await api.post('/api/discord/rules', { markdown: next });
values[setting.key] = next;
toast(
published.edited
? 'Règlement mis à jour dans le salon des règles.'
: 'Règlement publié et épinglé dans le salon des règles.',
published.pinned ? 'success' : 'info',
);
return;
}
const saved = await api.put(`/api/settings/values/${setting.key}`, { value: next }); const saved = await api.put(`/api/settings/values/${setting.key}`, { value: next });
toast(`« ${setting.label} » enregistré.`); toast(`« ${setting.label} » enregistré.`);
values[setting.key] = saved.value; values[setting.key] = saved.value;
@@ -497,88 +531,6 @@ function referenceCard(data) {
); );
} }
/**
* Writes the rules in markdown and republishes them: the previous message is
* deleted, the new one is sent and pinned in `CHANNEL_RULES_ID`.
*/
function rulesCard(level, reload) {
const host = h('div', { class: 'stack' });
const editable = level >= LEVELS.DEV;
renderAsync(
host,
() => api.get('/api/discord/rules'),
(data) => {
const editor = textarea({
value: data.markdown ?? '',
placeholder: '## Règlement\n\n1. …\n2. …',
rows: 12,
maxlength: 4000,
disabled: !editable,
});
const counter = h('span', { class: 'field-help' });
const refresh = () => {
counter.textContent = `${editor.value.length} / 4000 caractères`;
};
editor.addEventListener('input', refresh);
refresh();
return h(
'div',
{ class: 'stack' },
!data.configured &&
notice(
'Aucun salon des règles dans le .env : renseigne `CHANNEL_RULES_ID` puis redémarre le bot.',
'error',
),
field('Règlement (markdown)', editor, {
help: 'Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Publié et épinglé dans le salon des règles.',
}),
counter,
h(
'div',
{ class: 'row' },
editable &&
button(
'Publier le règlement',
async (event) => {
// The button stays disabled until the answer arrives: a second
// click would publish the rules twice.
event.currentTarget.disabled = true;
try {
const result = await api.post('/api/discord/rules', { markdown: editor.value });
toast(
result.pinned
? 'Règlement publié et épinglé.'
: 'Règlement publié, mais l’épinglage a échoué.',
result.pinned ? 'success' : 'info',
);
reload();
} catch (error) {
toast(error.message, 'error');
event.currentTarget.disabled = false;
}
},
{ tone: 'primary', disabled: !data.configured },
),
data.publishedAt
? h('span', {
class: 'muted',
text: `Dernier règlement publié ${formatRelative(data.publishedAt)}.`,
})
: h('span', { class: 'muted', text: 'Aucun règlement publié pour l’instant.' }),
),
);
},
);
return card(
'Règlement du serveur',
{ subtitle: 'Un seul message, épinglé dans le salon des règles, remis à jour à chaque publication.' },
host,
);
}
export function render(host, { state }) { export function render(host, { state }) {
const level = state.me.accessLevel; const level = state.me.accessLevel;
const reload = () => render(host, { state }); const reload = () => render(host, { state });
@@ -619,7 +571,6 @@ export function render(host, { state }) {
), ),
behaviourCard(data, level, reload), behaviourCard(data, level, reload),
rulesCard(level, reload),
connectionsCard(data), connectionsCard(data),
level >= LEVELS.OWNER ? sessionsCard(reload) : null, level >= LEVELS.OWNER ? sessionsCard(reload) : null,
level >= LEVELS.OWNER ? tokensCard(reload) : null, level >= LEVELS.OWNER ? tokensCard(reload) : null,
+1 -8
View File
@@ -223,7 +223,7 @@ export const VARIABLES = Object.freeze([
key: 'CHANNEL_LOGS_ID', key: 'CHANNEL_LOGS_ID',
section: 'channels', section: 'channels',
label: 'Salon des logs techniques', label: 'Salon des logs techniques',
help: 'Erreurs et événements techniques du bot.', help: 'Erreurs, événements techniques du bot et journal des tickets.',
type: 'snowflake', type: 'snowflake',
}, },
{ {
@@ -233,13 +233,6 @@ export const VARIABLES = Object.freeze([
help: 'Avertissements, mises en sourdine, bannissements.', help: 'Avertissements, mises en sourdine, bannissements.',
type: 'snowflake', type: 'snowflake',
}, },
{
key: 'CHANNEL_TICKETS_LOGS_ID',
section: 'channels',
label: 'Salon des logs de tickets',
help: 'Ouverture, prise en charge et clôture des tickets.',
type: 'snowflake',
},
{ {
key: 'CHANNEL_NOTIF_ISSUES_ID', key: 'CHANNEL_NOTIF_ISSUES_ID',
section: 'channels', section: 'channels',
+45 -30
View File
@@ -7,44 +7,46 @@ import { publishRules, rulesStatus } from '../src/services/rules/rules-service.j
// channel is passed explicitly here rather than read from the environment. // channel is passed explicitly here rather than read from the environment.
const RULES_CHANNEL = '1234567890123456789'; const RULES_CHANNEL = '1234567890123456789';
/** A Discord client reduced to what publishing the rules touches. */ /** A Discord client reduced to what saving the rules touches. */
function harness({ pinFails = false } = {}) { function harness({ pinFails = false, notEditable = false } = {}) {
const state = { sent: [], deleted: [], pinned: [], messages: new Map() }; const state = { sent: [], edited: [], pinned: [], messages: new Map() };
// Discord edits a message in place: the id, the link and the pin stay.
const withEdit = (message) => ({
...message,
edit: async ({ embeds }) => {
state.edited.push({ id: message.id, description: embeds[0].toJSON().description });
return message;
},
});
const channel = { const channel = {
isSendable: () => true, isSendable: () => true,
async send(payload) { async send(payload) {
const id = `message-${state.sent.length + 1}`; const id = `message-${state.sent.length + 1}`;
state.sent.push({ id, payload }); state.sent.push({ id, payload });
state.messages.set(id, { state.messages.set(id, { id, editable: !notEditable });
id,
delete: async () => {
state.deleted.push(id);
state.messages.delete(id);
},
});
return { return {
id, ...withEdit({ id, url: `https://discord.test/${id}` }),
url: `https://discord.test/${id}`,
pin: async () => { pin: async () => {
if (pinFails) throw new Error('Missing Permissions'); if (pinFails) throw new Error('Missing Permissions');
state.pinned.push(id); state.pinned.push(id);
}, },
}; };
}, },
messages: { fetch: async (id) => state.messages.get(id) ?? null }, messages: {
fetch: async (id) => {
const message = state.messages.get(id);
return message ? withEdit(message) : null;
},
},
}; };
return { state, client: { channels: { fetch: async () => channel } } }; return { state, client: { channels: { fetch: async () => channel } } };
} }
const publish = (client, markdown = '## Règlement\n\n1. Reste.bg') => const publish = (client, markdown = '## Règlement\n\n1. Reste.bg') =>
publishRules(client, { publishRules(client, { guildId: 'g', markdown, actorId: 'mod', channelId: RULES_CHANNEL });
guildId: 'g',
markdown,
actorId: 'mod',
channelId: RULES_CHANNEL,
});
const description = (entry) => entry.payload.embeds[0].toJSON().description; const description = (entry) => entry.payload.embeds[0].toJSON().description;
@@ -53,7 +55,7 @@ describe('rules service', () => {
after(() => closeDatabase()); after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM rules_messages;')); beforeEach(() => getDatabase().exec('DELETE FROM rules_messages;'));
it('publishes the rules and remembers the message', async () => { it('sends and pins the rules the first time', async () => {
const { state, client } = harness(); const { state, client } = harness();
const result = await publish(client, '**Pas de contenu illégal.**'); const result = await publish(client, '**Pas de contenu illégal.**');
@@ -61,32 +63,45 @@ describe('rules service', () => {
assert.equal(state.sent.length, 1); assert.equal(state.sent.length, 1);
assert.equal(description(state.sent[0]), '**Pas de contenu illégal.**'); assert.equal(description(state.sent[0]), '**Pas de contenu illégal.**');
assert.deepEqual(state.pinned, ['message-1']); assert.deepEqual(state.pinned, ['message-1']);
assert.equal(result.pinned, true); assert.deepEqual({ pinned: result.pinned, edited: result.edited }, { pinned: true, edited: false });
assert.equal(rulesStatus('g').messageId, 'message-1'); assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
}); });
it('deletes the previous message instead of piling copies up', async () => { it('edits the published message instead of sending a second one', async () => {
const { state, client } = harness(); const { state, client } = harness();
await publish(client, 'Version 1'); await publish(client, 'Version 1');
await publish(client, 'Version 2'); const result = await publish(client, 'Version 2');
assert.deepEqual(state.deleted, ['message-1']); assert.equal(state.sent.length, 1, 'a second message was sent');
assert.deepEqual(state.sent.map(description), ['Version 1', 'Version 2']); assert.deepEqual(state.edited, [{ id: 'message-1', description: 'Version 2' }]);
assert.equal(rulesStatus('g').messageId, 'message-2'); assert.equal(result.messageId, 'message-1', 'the message id must not change');
assert.equal(result.edited, true);
}); });
it('publishes even when the previous message was deleted by hand', async () => { it('sends a new one when the previous message is gone', async () => {
const { state, client } = harness(); const { state, client } = harness();
await publish(client, 'Version 1'); await publish(client, 'Version 1');
state.messages.delete('message-1'); state.messages.clear();
const result = await publish(client, 'Version 2'); const result = await publish(client, 'Version 2');
assert.equal(state.sent.length, 2);
assert.equal(result.edited, false);
assert.equal(result.messageId, 'message-2'); assert.equal(result.messageId, 'message-2');
}); });
it('sends a new one when the bot may no longer edit it', async () => {
const { state, client } = harness({ notEditable: true });
await publish(client, 'Version 1');
const result = await publish(client, 'Version 2');
assert.equal(state.sent.length, 2);
assert.equal(result.edited, false);
});
it('publishes even when the bot cannot pin', async () => { it('publishes even when the bot cannot pin', async () => {
const { state, client } = harness({ pinFails: true }); const { state, client } = harness({ pinFails: true });
@@ -94,7 +109,7 @@ describe('rules service', () => {
assert.deepEqual(state.pinned, []); assert.deepEqual(state.pinned, []);
assert.equal(result.pinned, false); assert.equal(result.pinned, false);
assert.equal(rulesStatus('g').messageId, 'message-1'); assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
}); });
it('refuses an empty or oversized regulation', async () => { it('refuses an empty or oversized regulation', async () => {
+301
View File
@@ -0,0 +1,301 @@
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import { ChannelType, Collection } from 'discord.js';
/**
* Ticket channel creation (M6).
*
* The channels are declared before the modules that read them are loaded, hence the
* dynamic imports: `createTicket` refuses to work without a ticket category, and the
* journal goes to the technical logs salon.
*/
process.env.CATEGORY_TICKETS_ID = '1463259435970461925';
process.env.CHANNEL_LOGS_ID = '1237076782453358745';
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 { 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;
const TICKET_CATEGORY = { id: CATEGORY_ID, type: ChannelType.GuildCategory };
const member = (roleIds = []) => ({
id: 'author-1',
guild: { ownerId: 'owner-1' },
roles: { cache: new Collection(roleIds.map((id) => [id, { id }])) },
});
/** Discord reduced to what opening a ticket touches: the category and the new channel. */
function harness({ parent = TICKET_CATEGORY } = {}) {
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),
delete: async () => {},
};
const guild = {
id: 'guild-1',
roles: { everyone: { id: 'everyone' } },
channels: {
fetch: async (id) => {
state.fetched.push(id);
if (id === CATEGORY_ID) return parent;
if (id === LOGS_CHANNEL) return journalChannel;
return null;
},
create: async (options) => {
state.created.push(options);
return channel;
},
},
};
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, panelChannel };
}
const open = (harness) => createTicket(harness.interaction, 'bug');
const embedsOf = (payload) => payload.embeds.map((embed) => embed.toJSON());
describe('ticket creation', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM tickets'));
it('creates the channel inside the category declared in the environment', async () => {
const test = harness();
await open(test);
assert.equal(test.state.fetched.includes(CATEGORY_ID), true);
assert.equal(test.state.created.length, 1);
assert.equal(test.state.created[0].parent, CATEGORY_ID);
assert.equal(test.state.created[0].type, ChannelType.GuildText);
});
it('posts the ticket header and a guidance embed', async () => {
const test = harness();
await open(test);
assert.equal(test.state.channelMessages.length, 1);
const [header, guidance] = embedsOf(test.state.channelMessages[0]);
assert.match(header.title, /^🎫 Ticket Bug #/);
assert.match(guidance.description, /Détaille au maximum/);
assert.match(guidance.fields[0].value, /étapes pour reproduire/);
assert.match(guidance.fields[1].name, /un peu de temps/);
});
it('writes the journal in the technical logs salon', async () => {
const test = harness();
await open(test);
assert.equal(test.state.journal.length, 1);
assert.equal(test.state.journal[0].embeds[0].toJSON().title, '🎫 Ticket ouvert');
});
it('explains how to fix the environment when the category is missing', async () => {
const test = harness({ parent: null });
await assert.rejects(
() => open(test),
(error) => {
assert.ok(error instanceof UserFacingError);
assert.match(error.message, /CATEGORY_TICKETS_ID/);
return true;
},
);
assert.equal(test.state.created.length, 0);
});
it('refuses a category id that points at a plain channel', async () => {
const test = harness({ parent: { id: CATEGORY_ID, type: ChannelType.GuildText } });
await assert.rejects(
() => open(test),
(error) => {
assert.ok(error instanceof UserFacingError);
assert.match(error.message, /catégorie Discord/);
return true;
},
);
});
});
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/);
});
});