Compare commits
27
Commits
e1b9a5cc77
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed14b8260c
|
||
|
|
1310840215
|
||
|
|
a996065861 | ||
|
|
ffb54a8e37
|
||
|
|
e6ce594b34
|
||
|
|
4e0f43eace | ||
|
|
22e9723700
|
||
|
|
31c0fc861a
|
||
|
|
20ffbbacad | ||
|
|
c61a13176e
|
||
|
|
44e990d04b
|
||
|
|
99e1fd2723
|
||
|
|
859b229181 | ||
|
|
d720c0a17e
|
||
|
|
9f8ac0d29e
|
||
|
|
b8be549fda
|
||
|
|
b9bc3b934b | ||
|
|
566af4db70 | ||
|
|
a1e1de7734 | ||
|
|
9acb523510 | ||
|
|
fcc82d82d6 | ||
|
|
d2256e2211 | ||
|
|
e3ce266225 | ||
|
|
1643fcb591 | ||
|
|
1c21f6ff53 | ||
|
|
8869c74b7b | ||
|
|
3d0e21d7cb |
No files matched your search
+3
-1
@@ -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=
|
||||||
@@ -92,6 +91,9 @@ DISCORD_CLIENT_SECRET=
|
|||||||
# Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord.
|
# Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord.
|
||||||
# À vider une fois le .env rempli.
|
# À vider une fois le .env rempli.
|
||||||
WEB_SETUP_TOKEN=
|
WEB_SETUP_TOKEN=
|
||||||
|
# Publie /status : bot en ligne, derniers déploiements, dernières releases.
|
||||||
|
# Les dépôts privés n'y apparaissent jamais par leur nom.
|
||||||
|
WEB_PUBLIC_STATUS=true
|
||||||
# Autorise les cibles de déploiement de type « commande shell » (Owner uniquement).
|
# Autorise les cibles de déploiement de type « commande shell » (Owner uniquement).
|
||||||
WEB_ALLOW_COMMAND_DEPLOYS=false
|
WEB_ALLOW_COMMAND_DEPLOYS=false
|
||||||
# Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2).
|
# Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2).
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
# Lint and tests on every push and every pull request. `format:check` is
|
||||||
|
# deliberately absent: the repository still holds CRLF files that predate the
|
||||||
|
# Prettier configuration, so the step would fail on untouched code. Normalise
|
||||||
|
# the line endings in a commit of their own, then add it here.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
quality:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
cache: npm
|
||||||
|
|
||||||
|
- name: Installer les dépendances
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: npm run lint
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
run: npm test
|
||||||
|
|
||||||
|
# The changelog is generated from the commit history, so a stale one is
|
||||||
|
# a real defect rather than a formatting detail.
|
||||||
|
- name: Changelog à jour
|
||||||
|
run: npm run changelog:check
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
# AGENTS.md — Instructions pour les agents IA
|
# AGENTS.md — Instructions pour les agents IA
|
||||||
|
|
||||||
> Fichier de référence pour les agents IA (Codebuff, Cursor, Claude Code, GitHub Copilot…) qui travaillent sur un repo de l'organisation **FWS**. Un agent doit lire ce fichier en premier : il contient les instructions à respecter. Le `README.md` apporte le contexte complet.
|
> Fichier de référence pour les agents IA (Codebuff, Cursor, Claude Code, GitHub Copilot…) qui travaillent sur un dépôt de l'organisation **FWS**. Un agent doit lire ce fichier en premier : il contient les instructions à respecter. Le `README.md` présente l'organisation et le `CONTRIBUTING.md` détaille les conventions de collaboration.
|
||||||
|
|
||||||
## Contexte
|
## Contexte
|
||||||
|
|
||||||
- **FWS** est une organisation open source multi-projets : chaque projet choisit librement sa stack (pas de restriction de langage).
|
- **FWS** est une organisation open source multi-projets : chaque projet choisit librement sa stack technique (sans restriction de langage).
|
||||||
- Projet principal : **FWS Arch** — un fork d'Arch Linux avec une surcouche conviviale pour simplifier l'installation et l'usage au quotidien.
|
- Projet principal : **FWS ISO** — une distribution Linux basée sur Arch Linux, pensée pour simplifier l'installation et l'usage au quotidien.
|
||||||
- Conventions détaillées : `README.md` (FR) / `README.en.md` (EN).
|
- Conventions détaillées : `CONTRIBUTING.md` (FR) / `CONTRIBUTING.en.md` (EN).
|
||||||
|
|
||||||
## Règles à respecter
|
## Règles à respecter
|
||||||
|
|
||||||
@@ -24,29 +24,36 @@
|
|||||||
|
|
||||||
### Code & commentaires
|
### Code & commentaires
|
||||||
|
|
||||||
- Commentaires en **anglais**, style « pourquoi » : pas de commentaire si le code est explicite, documenter le non-évident (choix d'implémentation, trade-offs, cas limites).
|
- Commentaires en **anglais**, style « pourquoi » : pas de commentaire si le code est explicite ; documenter le non-évident (choix d'implémentation, compromis, cas limites).
|
||||||
- Respecter la stack et les conventions existantes du repo avant d'ajouter de nouvelles dépendances.
|
- Respecter la stack technique et les conventions existantes du dépôt avant d'ajouter de nouvelles dépendances.
|
||||||
|
|
||||||
### Fichiers sensibles (`.gitignore`)
|
### Fichiers sensibles (`.gitignore`)
|
||||||
|
|
||||||
- Ne **jamais** committer : fichiers d'environnement (`.env*`), données d'assistants de développement (`.freebuff/`), artefacts compilés (`dist/`, `build/`, `target/`, `__pycache__/`…), dépendances (`node_modules/`), secrets.
|
- Ne **jamais** versionner : fichiers d'environnement (`.env*`), données d'assistants de développement (`.freebuff/`), artefacts compilés (`dist/`, `build/`, `target/`, `__pycache__/`…), dépendances (`node_modules/`), secrets.
|
||||||
- Un `.gitignore` doit exister à la racine de chaque repo.
|
- Un `.gitignore` doit exister à la racine de chaque dépôt.
|
||||||
|
|
||||||
### Tests
|
### Tests
|
||||||
|
|
||||||
- Fichiers de test : `*.test.*`, noms `describe` / `it` en anglais.
|
- Fichiers de test : `*.test.*` ; noms de tests `describe` / `it` en anglais.
|
||||||
- Vérifier que les tests (et le typecheck / lint quand ils existent) passent avant de considérer une tâche terminée.
|
- Vérifier que les tests (et le typecheck / lint quand ils existent) passent avant de considérer une tâche terminée.
|
||||||
|
|
||||||
### Issues & signalement de bugs
|
### Issues & signalement de bugs
|
||||||
|
|
||||||
- Les bugs et demandes sont suivis via les **issues**, liées au tableau Kanban.
|
- Les bugs et demandes sont suivis via les **issues** et, lorsqu'il existe, le tableau Kanban du projet.
|
||||||
- Une PR qui corrige un bug référence l'issue dans son titre ou sa description (`Fixes #123`).
|
- Une pull request qui corrige un bug référence l'issue dans son titre ou sa description (`Fixes #123`).
|
||||||
- Ne pas fermer ni modifier une issue sans demande explicite de l'utilisateur.
|
- Ne pas fermer ni modifier une issue sans demande explicite de l'utilisateur.
|
||||||
|
|
||||||
|
### Commits demandés par l'utilisateur
|
||||||
|
|
||||||
|
- Lorsque l'utilisateur demande explicitement de créer un commit, l'IA doit le faire après avoir vérifié les changements et les contrôles disponibles, sans attendre une confirmation supplémentaire.
|
||||||
|
- Le titre et le corps du commit ne doivent jamais mentionner l'IA, l'assistant, Codebuff ou l'outil utilisé.
|
||||||
|
- Ne pas ajouter l'IA comme auteur ou co-auteur dans le message du commit.
|
||||||
|
|
||||||
## Bonnes pratiques pour un agent
|
## Bonnes pratiques pour un agent
|
||||||
|
|
||||||
- Lire `AGENTS.md` puis `README.md` avant d'éditer du code.
|
- Lire `AGENTS.md`, le `README.md` et le `CONTRIBUTING.md` avant d'éditer du code.
|
||||||
|
- Les commits doivent être signés.
|
||||||
- Faire les changements les plus petits possibles qui répondent à la demande.
|
- Faire les changements les plus petits possibles qui répondent à la demande.
|
||||||
- Ne pas pousser, merger ni publier sans demande explicite de l'utilisateur.
|
- Ne pas pousser, fusionner ni publier sans demande explicite de l'utilisateur.
|
||||||
- Suivre les cartes du tableau Kanban du projet pour l'organisation du travail.
|
- Suivre les cartes du tableau Kanban lorsqu'il existe pour organiser le travail.
|
||||||
- En cas de doute, demander plutôt que deviner.
|
- En cas de doute, demander plutôt que de deviner.
|
||||||
@@ -7,6 +7,32 @@ The project follows [Semantic Versioning](https://semver.org/).
|
|||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
- **rules:** _(feat)_ write the rules from the dashboard and republish them ([31c0fc8])
|
||||||
|
- **moderation:** _(feat)_ add the unmute and unban commands ([9f8ac0d])
|
||||||
|
- **web:** _(feat)_ publish a public status page at /status ([a1e1de7])
|
||||||
|
- **web:** _(feat)_ search the whole panel from one place ([9acb523])
|
||||||
|
- **projects:** _(feat)_ gather the cards one member carries ([fcc82d8])
|
||||||
|
- **projects:** _(feat)_ pull Gitea issues onto any board ([1c21f6f])
|
||||||
|
- **wiki:** _(feat)_ serve the legal pages at /terms-of-service and /privacy-policy ([3d0e21d])
|
||||||
|
- **projects:** _(feat)_ add the board interface ([e1b9a5c])
|
||||||
|
- **projects:** _(feat)_ add a Kanban board per repository and one for the organization ([901ca56])
|
||||||
|
- **web:** _(feat)_ open a repository from anywhere on its row ([95b51ab])
|
||||||
|
- **wiki:** _(feat)_ add the reading site and its editor ([e5b7303])
|
||||||
|
- **wiki:** _(feat)_ serve a public documentation written from the panel ([c76c0b9])
|
||||||
|
- **web:** _(feat)_ publish the slash commands from the panel ([2622744])
|
||||||
|
- **voice:** _(feat)_ take back the generated channels the database forgot ([b42fb10])
|
||||||
|
- **settings:** _(feat)_ make the server settings real, and widen them ([406b5af])
|
||||||
|
- **web:** _(feat)_ make deploying reachable from where it is looked for ([d439b1b])
|
||||||
|
- **web:** _(feat)_ refresh the pages as the events arrive ([5481e79])
|
||||||
|
- **web:** _(feat)_ push live updates to the dashboard ([df89cc5])
|
||||||
|
- **web:** _(feat)_ serve the dashboard and its interface ([06a9be0])
|
||||||
|
- **web:** _(feat)_ expose the dashboard API ([bf92bad])
|
||||||
|
- **web:** _(feat)_ run and record release deployments ([611129b])
|
||||||
|
- **web:** _(feat)_ read, validate and write the .env configuration ([efaaca3])
|
||||||
|
- **web:** _(feat)_ add the HTTP layer and Discord-backed sessions ([e03b184])
|
||||||
|
- **database:** _(feat)_ store dashboard sessions, deploy targets and deployments ([5abe713])
|
||||||
|
- **gitea:** _(feat)_ add an organization and repository administration client ([4b0737a])
|
||||||
|
- **config:** _(feat)_ declare the web dashboard environment variables ([e4534d4])
|
||||||
- **status:** _(feat)_ rotate an editable list of bot statuses ([c785e9a])
|
- **status:** _(feat)_ rotate an editable list of bot statuses ([c785e9a])
|
||||||
- **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269])
|
- **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269])
|
||||||
- **voice:** _(feat)_ support several trigger channels with their own category ([836abea])
|
- **voice:** _(feat)_ support several trigger channels with their own category ([836abea])
|
||||||
@@ -66,7 +92,39 @@ The project follows [Semantic Versioning](https://semver.org/).
|
|||||||
- **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe])
|
- **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe])
|
||||||
- **config:** _(feat)_ load and expose environment settings ([d1388b6])
|
- **config:** _(feat)_ load and expose environment settings ([d1388b6])
|
||||||
|
|
||||||
|
### 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])
|
||||||
|
- **wiki:** _(fix)_ render the public pages on the server ([8869c74])
|
||||||
|
- **web:** _(fix)_ stop caching the interface modules ([3f4a570])
|
||||||
|
- **web:** _(fix)_ keep the stack when a view fails ([c031b4d])
|
||||||
|
- **web:** _(fix)_ read the interface build date instead of freezing it at startup ([92c27ae])
|
||||||
|
- **web:** _(fix)_ stop the settings page breaking on an unexpected payload ([75d1e53])
|
||||||
|
- **web:** _(fix)_ give static assets a validator caches can check ([539b150])
|
||||||
|
- **web:** _(fix)_ say when the dashboard is disabled ([3bd290c])
|
||||||
|
- **web:** _(fix)_ say out loud when the dashboard cannot listen ([afcd0e5])
|
||||||
|
- **config:** _(fix)_ warn when a public address is announced but only loopback is bound ([40032ec])
|
||||||
|
- **web:** _(fix)_ make the whole repository card open the repository ([e397abc])
|
||||||
|
- **web:** _(fix)_ pin the sidebar highlight to the route, and name the build ([a44ff0c])
|
||||||
|
- **web:** _(fix)_ always offer the bootstrap token on the sign-in page ([9c6297e])
|
||||||
|
- **web:** _(fix)_ let a deploy target be created without a reachable Gitea ([ff15dfe])
|
||||||
|
- **web:** _(fix)_ keep the sidebar in step with the page being shown ([a0428e0])
|
||||||
|
- **web:** _(fix)_ derive the OAuth2 redirect from the address actually used ([20ff701])
|
||||||
|
- **notifications:** _(fix)_ apply the channel overrides set from Discord ([92405ac])
|
||||||
|
|
||||||
### Other changes
|
### Other changes
|
||||||
|
- **agents:** _(docs)_ update the repository conventions and commit rules ([44e990d])
|
||||||
|
- **web:** _(docs)_ document my tasks, the search and the status page ([566af4d])
|
||||||
|
- **web:** _(refactor)_ extract the build marker into its own module ([d2256e2])
|
||||||
|
- **ops:** _(docs)_ correct the deployment path for a panel without a shell ([e3ce266])
|
||||||
|
- **ops:** _(docs)_ document deployment, CI, monitoring and backups ([1643fcb])
|
||||||
|
- **web:** _(test)_ lock the sidebar highlighting behind tests ([b793298])
|
||||||
|
- **web:** _(docs)_ document the wiki, the settings and the command publishing ([5660235])
|
||||||
|
- **web:** _(style)_ adopt the official FWS mark and its palette ([621f3e4])
|
||||||
|
- **web:** _(docs)_ document the live updates ([2083133])
|
||||||
|
- **web:** _(docs)_ document the dashboard and the configuration wizard ([e63d6aa])
|
||||||
|
- **web:** _(test)_ cover the router, configuration, auth, deployments and server ([bd7fdea])
|
||||||
|
- **all:** _(refactor)_ uniformisation ([50665c8])
|
||||||
- **readme:** _(docs)_ translate the documentation and document the contribution workflow ([9bbe9cb])
|
- **readme:** _(docs)_ translate the documentation and document the contribution workflow ([9bbe9cb])
|
||||||
- **changelog:** _(build)_ generate the changelog from the commit history ([478ae41])
|
- **changelog:** _(build)_ generate the changelog from the commit history ([478ae41])
|
||||||
- **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2])
|
- **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2])
|
||||||
|
|||||||
+12
-5
@@ -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) |
|
| `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:
|
||||||
|
|
||||||
@@ -289,6 +293,8 @@ Every command checks the FWS level **and** the matching Discord permission. The
|
|||||||
| ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ |
|
| ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ |
|
||||||
| `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action |
|
| `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action |
|
||||||
| `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification |
|
| `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification |
|
||||||
|
| `/unmute` | `user`, `reason` | Moderate Members | ✅ | Lifts the timeout early (clear message when nobody is muted) |
|
||||||
|
| `/unban` | `user`, `reason` | Ban Members | ✅ | Lifts the ban, even if the member already left, and DMs them |
|
||||||
| `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action |
|
| `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action |
|
||||||
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge |
|
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge |
|
||||||
| `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) |
|
| `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) |
|
||||||
@@ -324,7 +330,7 @@ No added dependency: `node:http` for the server, `node:sqlite` for the sessions,
|
|||||||
|
|
||||||
The bot also serves **public documentation** at `/wiki`, readable without an account and written from the panel. It ships with **terms of use** and a **privacy policy** aligned with the Swiss LPD, describing exactly what this code processes — the bracketed details still have to be filled in and reviewed.
|
The bot also serves **public documentation** at `/wiki`, readable without an account and written from the panel. It ships with **terms of use** and a **privacy policy** aligned with the Swiss LPD, describing exactly what this code processes — the bracketed details still have to be filled in and reviewed.
|
||||||
|
|
||||||
The panel also **publishes the slash commands** to Discord without shell access, and gathers under **Settings** everything that can be changed without touching the `.env`: welcome, moderation, tickets, voice, notifications.
|
The panel also **publishes the slash commands** to Discord without shell access, and gathers under **Settings** everything that can be changed without touching the `.env`: welcome, moderation, rules, tickets, voice, notifications.
|
||||||
|
|
||||||
### 6.1 Getting started
|
### 6.1 Getting started
|
||||||
|
|
||||||
@@ -427,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`).
|
||||||
@@ -533,6 +539,7 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h
|
|||||||
- FWS documentation: `[link to add]`
|
- FWS documentation: `[link to add]`
|
||||||
- Technical documentation: [`docs/architecture.md`](docs/architecture.md)
|
- Technical documentation: [`docs/architecture.md`](docs/architecture.md)
|
||||||
- Web dashboard: [`docs/web-dashboard.md`](docs/web-dashboard.md)
|
- Web dashboard: [`docs/web-dashboard.md`](docs/web-dashboard.md)
|
||||||
|
- Operations (deployment, continuous integration, monitoring, backups): [`docs/exploitation.md`](docs/exploitation.md)
|
||||||
- Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md)
|
- Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md)
|
||||||
- Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_
|
- Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_
|
||||||
- Instructions for AI agents: [`AGENTS.md`](AGENTS.md)
|
- Instructions for AI agents: [`AGENTS.md`](AGENTS.md)
|
||||||
|
|||||||
@@ -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) |
|
| `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 :
|
||||||
|
|
||||||
@@ -291,6 +294,8 @@ Chaque commande vérifie le niveau FWS **et** la permission Discord correspondan
|
|||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| `/warn` | `user`, `reason` (obligatoires) | Modérer les membres | ✅ | Avertit, prévient le membre en MP et enregistre l'action |
|
| `/warn` | `user`, `reason` (obligatoires) | Modérer les membres | ✅ | Avertit, prévient le membre en MP et enregistre l'action |
|
||||||
| `/mute` | `user`, `minutes` (1–40320), `reason` | Modérer les membres | ✅ | Timeout temporaire (28 j max) + notification en MP |
|
| `/mute` | `user`, `minutes` (1–40320), `reason` | Modérer les membres | ✅ | Timeout temporaire (28 j max) + notification en MP |
|
||||||
|
| `/unmute` | `user`, `reason` | Modérer les membres | ✅ | Lève le timeout avant l’échéance (message clair si la personne n’est pas en exclusion) |
|
||||||
|
| `/unban` | `user`, `reason` | Bannir | ✅ | Lève le bannissement, même si la personne a déjà quitté, et la prévient en MP |
|
||||||
| `/kick` | `user`, `reason` | Expulser | ✅ | Expulse du serveur et journalise l'action |
|
| `/kick` | `user`, `reason` | Expulser | ✅ | Expulse du serveur et journalise l'action |
|
||||||
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Bannir | ✅ | Bannit (même si le membre a déjà quitté), purge optionnelle des messages |
|
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Bannir | ✅ | Bannit (même si le membre a déjà quitté), purge optionnelle des messages |
|
||||||
| `/clear` | `amount` (1–100) | Gérer les messages | ✅ | Supprime les N derniers messages (ceux de plus de 14 j sont ignorés) |
|
| `/clear` | `amount` (1–100) | Gérer les messages | ✅ | Supprime les N derniers messages (ceux de plus de 14 j sont ignorés) |
|
||||||
@@ -326,7 +331,7 @@ Aucune dépendance ajoutée : `node:http` pour le serveur, `node:sqlite` pour le
|
|||||||
|
|
||||||
Le bot sert aussi une **documentation publique** sur `/wiki`, lisible sans compte et rédigée depuis le panel. Elle est livrée avec des **conditions d'utilisation** et une **politique de confidentialité** conformes à la LPD suisse, décrivant précisément les données que ce code traite — les mentions entre crochets restent à compléter et à faire relire.
|
Le bot sert aussi une **documentation publique** sur `/wiki`, lisible sans compte et rédigée depuis le panel. Elle est livrée avec des **conditions d'utilisation** et une **politique de confidentialité** conformes à la LPD suisse, décrivant précisément les données que ce code traite — les mentions entre crochets restent à compléter et à faire relire.
|
||||||
|
|
||||||
Le panel permet aussi de **publier les commandes slash** sur Discord sans accès shell, et regroupe dans **Paramètres** tout ce qui se règle sans toucher au `.env` : accueil, modération, tickets, vocaux, notifications.
|
Le panel permet aussi de **publier les commandes slash** sur Discord sans accès shell, et regroupe dans **Paramètres** tout ce qui se règle sans toucher au `.env` : accueil, modération, règlement, tickets, vocaux, notifications.
|
||||||
|
|
||||||
### 6.1 Démarrer
|
### 6.1 Démarrer
|
||||||
|
|
||||||
@@ -429,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`).
|
||||||
@@ -538,6 +543,7 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de
|
|||||||
- Documentation FWS : `[lien à ajouter]`
|
- Documentation FWS : `[lien à ajouter]`
|
||||||
- Documentation technique : [`docs/architecture.md`](docs/architecture.md)
|
- Documentation technique : [`docs/architecture.md`](docs/architecture.md)
|
||||||
- Tableau de bord web : [`docs/web-dashboard.md`](docs/web-dashboard.md)
|
- Tableau de bord web : [`docs/web-dashboard.md`](docs/web-dashboard.md)
|
||||||
|
- Exploitation (déploiement, intégration continue, surveillance, sauvegardes) : [`docs/exploitation.md`](docs/exploitation.md)
|
||||||
- Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md)
|
- Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md)
|
||||||
- Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)*
|
- Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)*
|
||||||
- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md)
|
- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md)
|
||||||
|
|||||||
@@ -0,0 +1,305 @@
|
|||||||
|
# Exploitation
|
||||||
|
|
||||||
|
Comment déployer, vérifier, surveiller et sauvegarder FWS-Bot en production. Écrit pour un hébergement de type panel (Pterodactyl), qui est le cas actuel.
|
||||||
|
|
||||||
|
Les quatre chapitres sont indépendants et classés par valeur décroissante.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Déployer sans archive
|
||||||
|
|
||||||
|
**Le problème qu'on résout.** Téléverser un zip laisse régulièrement une copie partielle : le front plus ancien que l'API, un module oublié, une page qui plante sans raison apparente. Trois symptômes pour une seule cause, et aucun moyen simple de savoir laquelle.
|
||||||
|
|
||||||
|
Un déploiement reproductible supprime toute la famille.
|
||||||
|
|
||||||
|
> **L'onglet « Console » de Pterodactyl n'est pas un terminal** : c'est l'entrée/sortie du processus en cours. On n'y lance pas de commande shell, même avec tous les droits du panel. Si tu disposes d'un vrai shell ailleurs, suis le point 1.0 ; sinon, tout se fait depuis le tableau de bord, à partir du point 1.1.
|
||||||
|
|
||||||
|
### 1.0 Si tu as un accès shell
|
||||||
|
|
||||||
|
Assure-toi d'abord d'être **sur le bon système de fichiers** — celui que le bot lit. Un `git pull` au mauvais endroit ne produit aucune erreur et ne change rien, ce qui est le plus trompeur des résultats :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/container
|
||||||
|
ls package.json src/index.js .env && echo "bon endroit"
|
||||||
|
```
|
||||||
|
|
||||||
|
Si cette commande échoue, ton shell ne voit pas le conteneur du bot : passe au point 1.1.
|
||||||
|
|
||||||
|
Sinon, l'amorçage se fait directement :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env .env.sauvegarde && tar czf data-sauvegarde.tgz data/
|
||||||
|
|
||||||
|
git init
|
||||||
|
git remote add origin https://gitea.nocode-var.tech/FWS/fws-discordbot.git
|
||||||
|
git fetch origin main
|
||||||
|
git reset --hard origin/main
|
||||||
|
npm ci --omit=dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Puis saute au point 1.3 pour déclarer la cible de production, qui te permettra de déployer d'un clic depuis le tableau de bord plutôt que de revenir ici à chaque fois.
|
||||||
|
|
||||||
|
> ⚠️ Ne lance **jamais** `git clean -fd` dans ce dossier : il effacerait `.env` et la base.
|
||||||
|
|
||||||
|
### 1.1 Autoriser l'exécution de commandes
|
||||||
|
|
||||||
|
**Tableau de bord → Configuration .env → Tableau de bord web** (niveau Owner) :
|
||||||
|
|
||||||
|
| Variable | Valeur |
|
||||||
|
| --------------------------- | ------ |
|
||||||
|
| `WEB_ALLOW_COMMAND_DEPLOYS` | `true` |
|
||||||
|
| `WEB_ALLOW_RESTART` | `true` |
|
||||||
|
|
||||||
|
Enregistre, puis redémarre le bot depuis le panel. Ces deux valeurs ne sont lues qu'au démarrage.
|
||||||
|
|
||||||
|
> Elles permettent d'exécuter une commande sur la machine du bot depuis un navigateur — une exécution de code arbitraire. Réservées au niveau Owner, désactivées par défaut. N'ouvre l'accès Owner qu'à des personnes de confiance.
|
||||||
|
|
||||||
|
### 1.2 Amorcer le clone sans shell
|
||||||
|
|
||||||
|
Si le point 1.0 ne s'applique pas : le dossier du conteneur contient aujourd'hui une archive décompressée, pas un dépôt. On le convertit avec une cible jetable, exécutée par le bot lui-même.
|
||||||
|
|
||||||
|
**Déploiements → Nouvelle cible**
|
||||||
|
|
||||||
|
| Champ | Valeur |
|
||||||
|
| --------------------- | -------------------------------- |
|
||||||
|
| Nom | `amorçage` |
|
||||||
|
| Dépôt | `FWS/fws-discordbot` |
|
||||||
|
| Type | Commande shell sur l'hôte du bot |
|
||||||
|
| Répertoire de travail | `/home/container` |
|
||||||
|
| Commande | voir ci-dessous |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git init && git remote add origin https://gitea.nocode-var.tech/FWS/fws-discordbot.git && git fetch origin main && git reset --hard origin/main
|
||||||
|
```
|
||||||
|
|
||||||
|
Clique **Déployer**, puis lis le journal dans l'historique. Deux cas d'échec :
|
||||||
|
|
||||||
|
- **`git: not found`** — l'image du conteneur n'a pas git. Utilise la variante sans git du point 1.5.
|
||||||
|
- **authentification refusée** — le dépôt est privé. Remplace l'URL par `https://<utilisateur>:<jeton>@gitea.nocode-var.tech/FWS/fws-discordbot.git`. Le jeton est alors stocké dans la configuration de la cible, en base : utilise un jeton dédié, en lecture seule.
|
||||||
|
|
||||||
|
`git reset --hard` écrase les fichiers **suivis**. Ton `.env` et ton dossier `data/` sont ignorés par git, donc intacts.
|
||||||
|
|
||||||
|
> ⚠️ N'ajoute **jamais** `git clean -fd` à cette commande : elle effacerait `.env` et la base.
|
||||||
|
|
||||||
|
Supprime ensuite la cible `amorçage` : elle ne sert qu'une fois.
|
||||||
|
|
||||||
|
### 1.3 Déclarer la cible de production
|
||||||
|
|
||||||
|
**Déploiements → Nouvelle cible**
|
||||||
|
|
||||||
|
| Champ | Valeur |
|
||||||
|
| ----------------------- | ---------------------------------------------------------------------------- |
|
||||||
|
| Nom | `production` |
|
||||||
|
| Dépôt | `FWS/fws-discordbot` |
|
||||||
|
| Environnement | `production` |
|
||||||
|
| Type | Commande shell sur l'hôte du bot |
|
||||||
|
| Répertoire de travail | `/home/container` |
|
||||||
|
| Commande | `git fetch origin main && git reset --hard origin/main && npm ci --omit=dev` |
|
||||||
|
| Déploiement automatique | à activer si tu veux qu'une release publiée déploie seule |
|
||||||
|
|
||||||
|
### 1.4 Le cycle courant
|
||||||
|
|
||||||
|
1. **Déploiements → Déployer** sur `production`. Le journal complet est conservé, réussite comme échec.
|
||||||
|
2. **Paramètres → Redémarrer le bot** — le code n'est relu qu'au démarrage.
|
||||||
|
|
||||||
|
Contrôle, depuis n'importe où :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://node01.zi-host.ch:25571/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
`buildAt` doit refléter ton dernier commit. C'est le seul indicateur fiable de ce qui tourne réellement.
|
||||||
|
|
||||||
|
### 1.5 Si le conteneur n'a pas git
|
||||||
|
|
||||||
|
Gitea sert une archive de n'importe quelle branche. La commande devient :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -sL -H "Authorization: token TON_JETON" https://gitea.nocode-var.tech/api/v1/repos/FWS/fws-discordbot/archive/main.tar.gz | tar xz --strip-components=1 && npm ci --omit=dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Moins bien que git — pas d'historique, pas de moyen de savoir ce qui a changé — mais reproductible, et suffisant pour supprimer le téléversement à la main.
|
||||||
|
|
||||||
|
### Ce qu'il faut savoir
|
||||||
|
|
||||||
|
- `npm ci --omit=dev` n'installe ni ESLint, ni Prettier, ni de quoi lancer les tests. C'est voulu : ils tournent en intégration continue (chapitre 2), pas en production.
|
||||||
|
- Si ton egg Pterodactyl réinstalle les fichiers au démarrage, il écrasera le clone. Vérifie l'option _Auto-update / Reinstall on boot_ et désactive-la.
|
||||||
|
- Les migrations de base s'appliquent toutes seules au démarrage : rien à lancer.
|
||||||
|
- Tout ce chapitre reste faisable en **SFTP** si tu préfères : le panel en donne les identifiants, et un client comme FileZilla remplace le téléversement par zip. Mais tu restes exposé à la copie partielle, que le déploiement par commande supprime.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Faire tourner les tests avant de déployer
|
||||||
|
|
||||||
|
**Le problème qu'on résout.** 301 tests et un lint existent, et ne tournent jamais avant une mise en production. Un déplacement de cartes cassé est passé inaperçu jusqu'à ce qu'un test l'attrape — après coup.
|
||||||
|
|
||||||
|
Le fichier de workflow est déjà dans le dépôt : [`.gitea/workflows/ci.yml`](../.gitea/workflows/ci.yml). Il reste à donner un exécuteur à Gitea.
|
||||||
|
|
||||||
|
### 2.1 Activer Actions sur l'instance
|
||||||
|
|
||||||
|
Côté administration Gitea, dans `app.ini` :
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[actions]
|
||||||
|
ENABLED = true
|
||||||
|
```
|
||||||
|
|
||||||
|
Puis redémarrer Gitea. Si l'instance ne t'appartient pas, c'est à demander à son administration.
|
||||||
|
|
||||||
|
### 2.2 Enregistrer un exécuteur
|
||||||
|
|
||||||
|
**Dépôt → Settings → Actions → Runners → Create new runner** te donne un jeton d'enregistrement.
|
||||||
|
|
||||||
|
Sur une machine qui a Docker et qui joint ton Gitea — ton poste, un VPS, ou le nœud lui-même :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -sL -o act_runner \
|
||||||
|
https://gitea.com/gitea/act_runner/releases/download/v0.2.11/act_runner-0.2.11-linux-amd64
|
||||||
|
chmod +x act_runner
|
||||||
|
|
||||||
|
./act_runner register --no-interactive \
|
||||||
|
--instance https://gitea.nocode-var.tech \
|
||||||
|
--token <JETON_DENREGISTREMENT> \
|
||||||
|
--name fws-runner \
|
||||||
|
--labels ubuntu-latest:docker://node:22-bookworm
|
||||||
|
|
||||||
|
./act_runner daemon
|
||||||
|
```
|
||||||
|
|
||||||
|
Sans Docker, remplace l'étiquette par `ubuntu-latest:host` — les tâches s'exécutent alors directement sur la machine, qui doit avoir Node 22.
|
||||||
|
|
||||||
|
Pour qu'il survive à un redémarrage, place-le en service systemd ou en conteneur `--restart=always`.
|
||||||
|
|
||||||
|
### 2.3 Vérifier
|
||||||
|
|
||||||
|
Pousse une branche : l'onglet **Actions** du dépôt montre le résultat, et la pull request affiche son état.
|
||||||
|
|
||||||
|
### Pourquoi `format:check` n'est pas dans le workflow
|
||||||
|
|
||||||
|
Le dépôt contient encore des fichiers en CRLF antérieurs à la configuration Prettier. L'étape échouerait sur du code que personne n'a touché.
|
||||||
|
|
||||||
|
Pour l'ajouter : normalise les fins de ligne dans un commit dédié (`refactor(all): normalise les fins de ligne`), puis ajoute l'étape. Tant que ce n'est pas fait, l'absence est volontaire.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Savoir que le bot est tombé
|
||||||
|
|
||||||
|
**Le problème qu'on résout.** Une soirée passée à chercher pourquoi le site ne répondait plus, alors qu'une sonde aurait répondu en trente secondes.
|
||||||
|
|
||||||
|
Le bot expose déjà tout ce qu'il faut :
|
||||||
|
|
||||||
|
```json
|
||||||
|
GET /api/health
|
||||||
|
{ "status": "ok", "version": "0.1.0", "buildAt": "…", "uptimeMs": 106470 }
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.1 Surveiller depuis l'extérieur
|
||||||
|
|
||||||
|
Un bot ne peut pas signaler sa propre mort : il faut une sonde **externe**. [Uptime Kuma](https://github.com/louislam/uptime-kuma) est léger et sait écrire sur Discord.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d --restart=always -p 3001:3001 \
|
||||||
|
-v uptime-kuma:/app/data --name uptime-kuma louislam/uptime-kuma:1
|
||||||
|
```
|
||||||
|
|
||||||
|
Puis, dans son interface :
|
||||||
|
|
||||||
|
| Réglage | Valeur |
|
||||||
|
| ------------ | ------------------------------------------- |
|
||||||
|
| Type | HTTP(s) - Keyword |
|
||||||
|
| URL | `http://node01.zi-host.ch:25571/api/health` |
|
||||||
|
| Mot-clé | `"status":"ok"` |
|
||||||
|
| Intervalle | 60 s |
|
||||||
|
| Notification | Webhook Discord vers ton salon de logs |
|
||||||
|
|
||||||
|
> **Surveille l'origine, pas le domaine public.** Cloudflare renvoie un challenge à toute requête non-navigateur : une sonde sur `https://fws-bot.laxacube.ch` signalerait une panne permanente qui n'existe pas.
|
||||||
|
|
||||||
|
Le mot-clé compte : une page qui répond `200` mais sans `"status":"ok"` n'est pas un bot en bonne santé.
|
||||||
|
|
||||||
|
### 3.2 Une page que les autres peuvent lire
|
||||||
|
|
||||||
|
`/status` répond sans compte : état du bot, latence Discord, dernier déploiement par environnement, dernières releases. Elle est rendue côté serveur, sans JavaScript, et se rafraîchit toute seule.
|
||||||
|
|
||||||
|
C’est l’adresse à donner à la communauté quand quelqu’un demande « c’est en panne ou c’est moi ? ».
|
||||||
|
|
||||||
|
`/api/status` en donne la version JSON. Elle vaut mieux que `/api/health` pour une sonde qui affiche un tableau de bord :
|
||||||
|
|
||||||
|
```json
|
||||||
|
GET /api/status
|
||||||
|
{ "bot": { "online": true, "pingMs": 42, "version": "0.1.0" },
|
||||||
|
"environments": [ { "environment": "production", "status": "success", "tone": "ok" } ],
|
||||||
|
"releases": [ … ] }
|
||||||
|
```
|
||||||
|
|
||||||
|
`WEB_PUBLIC_STATUS=false` désactive les deux. Un dépôt privé n’apparaît jamais par son nom sur la page publique.
|
||||||
|
|
||||||
|
### 3.3 Ce que le bot surveille déjà lui-même
|
||||||
|
|
||||||
|
- Chaque déploiement, réussi ou non, est annoncé sur Discord et consigné avec son journal.
|
||||||
|
- Les erreurs d'appel Gitea partent dans le salon `errors`.
|
||||||
|
- **Paramètres → Tester la connexion** vérifie Discord et Gitea à la demande.
|
||||||
|
|
||||||
|
Ça couvre les pannes partielles. Ça ne couvre pas un processus mort — d'où le point 3.1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Sauvegarder hors du conteneur
|
||||||
|
|
||||||
|
**Le problème qu'on résout.** Le bouton _Sauvegarder la base_ écrit dans `data/backups`, **à l'intérieur du conteneur**. Une reconstruction efface les deux. C'est déjà arrivé : les salons vocaux orphelins venaient d'une base repartie de zéro.
|
||||||
|
|
||||||
|
### 4.1 Sauvegardes du panel (le plus simple)
|
||||||
|
|
||||||
|
Pterodactyl sait archiver le serveur entier, hors conteneur.
|
||||||
|
|
||||||
|
**Panel → Schedules → Create schedule**
|
||||||
|
|
||||||
|
| Réglage | Valeur |
|
||||||
|
| ------- | ----------------------- |
|
||||||
|
| Nom | Sauvegarde hebdomadaire |
|
||||||
|
| Cron | `0 4 * * 1` (lundi 4 h) |
|
||||||
|
| Tâche | _Create backup_ |
|
||||||
|
|
||||||
|
Les archives apparaissent dans l'onglet **Backups**, avec téléchargement. Vérifie la limite d'archives de ton offre.
|
||||||
|
|
||||||
|
### 4.2 Instantané cohérent de la base
|
||||||
|
|
||||||
|
Une archive de fichiers peut attraper la base en cours d'écriture. Le bot, lui, produit une copie cohérente (`VACUUM INTO`), même journal WAL actif.
|
||||||
|
|
||||||
|
Crée un jeton dans **Paramètres → Jetons d'API** (niveau Owner), puis, depuis une machine qui tourne en permanence :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Chaque nuit à 3 h
|
||||||
|
0 3 * * * curl -sS -X POST -H "Authorization: Bearer fws_…" \
|
||||||
|
http://node01.zi-host.ch:25571/api/settings/backup
|
||||||
|
```
|
||||||
|
|
||||||
|
Le fichier atterrit dans `BACKUP_DIR`, que la sauvegarde du panel emporte ensuite.
|
||||||
|
|
||||||
|
### 4.3 Vraiment hors site
|
||||||
|
|
||||||
|
Une sauvegarde chez le même hébergeur ne protège pas d'un incident chez lui. Depuis une machine qui a l'accès SFTP du panel :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rclone sync sftp-panel:/home/container/data backblaze:fws-bot-backups \
|
||||||
|
--backup-dir backblaze:fws-bot-backups/anciens/$(date +%F)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.4 Tester la restauration
|
||||||
|
|
||||||
|
Une sauvegarde jamais restaurée n'est pas une sauvegarde. Une fois :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp fws-bot-2026-09-24.sqlite /tmp/test.sqlite
|
||||||
|
DATABASE_PATH=/tmp/test.sqlite npm run db:init
|
||||||
|
```
|
||||||
|
|
||||||
|
La commande doit se terminer sans erreur et appliquer les migrations.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dans quel ordre
|
||||||
|
|
||||||
|
1. **Chapitre 1** — supprime une famille entière de pannes, ne demande que de la configuration.
|
||||||
|
2. **Chapitre 2** — évite de découvrir un bug en production.
|
||||||
|
3. **Chapitre 4** — protège ce qui n'est pas remplaçable.
|
||||||
|
4. **Chapitre 3** — utile, mais vient après ce qui empêche les pannes plutôt que ce qui les signale.
|
||||||
+63
-11
@@ -54,6 +54,7 @@ Le commutateur en bas de la barre latérale masque ou révèle les panneaux tech
|
|||||||
| Page | Contenu |
|
| Page | Contenu |
|
||||||
| ---------------------- | ----------------------------------------------------------------------------------------------- |
|
| ---------------------- | ----------------------------------------------------------------------------------------------- |
|
||||||
| **Vue d'ensemble** | État du bot, du serveur Discord, de l'organisation, activité, derniers événements |
|
| **Vue d'ensemble** | État du bot, du serveur Discord, de l'organisation, activité, derniers événements |
|
||||||
|
| **Mes tâches** | Les cartes qui te sont assignées, tous tableaux confondus, la plus urgente en premier |
|
||||||
| **Organisation** | Identité Gitea, membres, équipes, inventaire des dépôts, création de dépôt |
|
| **Organisation** | Identité Gitea, membres, équipes, inventaire des dépôts, création de dépôt |
|
||||||
| **Dépôts** | Un dépôt en détail : issues, PR, commits, branches, collaborateurs, webhooks, Actions, réglages |
|
| **Dépôts** | Un dépôt en détail : issues, PR, commits, branches, collaborateurs, webhooks, Actions, réglages |
|
||||||
| **Releases** | Publier une version, générer ses notes depuis les commits, suivre les déploiements déclenchés |
|
| **Releases** | Publier une version, générer ses notes depuis les commits, suivre les déploiements déclenchés |
|
||||||
@@ -61,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, 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
|
||||||
@@ -142,7 +143,49 @@ Si le flux ne s'établit pas — proxy qui met en tampon, réseau instable — u
|
|||||||
|
|
||||||
Pour un reverse proxy, pense à désactiver la mise en tampon sur ce chemin. Le serveur envoie déjà `X-Accel-Buffering: no` et `Cache-Control: no-transform`, ce que nginx respecte.
|
Pour un reverse proxy, pense à désactiver la mise en tampon sur ce chemin. Le serveur envoie déjà `X-Accel-Buffering: no` et `Cache-Control: no-transform`, ce que nginx respecte.
|
||||||
|
|
||||||
## 7. Wiki public
|
## 7. Trouver et suivre son travail
|
||||||
|
|
||||||
|
### Mes tâches
|
||||||
|
|
||||||
|
**Tableau de bord → Mes tâches** rassemble les cartes qui te sont assignées sur **tous** les tableaux, groupées par échéance : en retard, pour aujourd’hui, cette semaine, plus tard, sans date. Les cartes terminées sont repliées en bas.
|
||||||
|
|
||||||
|
- Le bouton rond à gauche d’une carte la déplace dans la colonne « terminé » de son tableau, sans quitter la page.
|
||||||
|
- Le compteur de la barre latérale indique le nombre de cartes ouvertes, en rouge dès qu’une est en retard.
|
||||||
|
- Le sélecteur en haut à droite permet de regarder la charge d’un autre membre, quand plusieurs personnes portent des cartes.
|
||||||
|
|
||||||
|
Une carte n’apparaît ici que si elle a un **assigné**. C’est le seul champ qui compte pour cette page.
|
||||||
|
|
||||||
|
### Recherche globale
|
||||||
|
|
||||||
|
**⌘K** (ou **Ctrl+K**, ou la barre « Rechercher ») ouvre une recherche unique sur :
|
||||||
|
|
||||||
|
| Source | Où elle mène | D’où elle vient |
|
||||||
|
| ----------- | -------------------------------------- | ------------------------- |
|
||||||
|
| Pages | L’onglet correspondant | Le navigateur, sans appel |
|
||||||
|
| Cartes | Le tableau qui la porte | La base locale |
|
||||||
|
| Dépôts | La fiche du dépôt | Gitea, en cache 60 s |
|
||||||
|
| Issues / PR | Gitea, dans un onglet | Gitea |
|
||||||
|
| Wiki | La page publique | La base locale |
|
||||||
|
| Membres | L’onglet Discord, recherche préremplie | Le cache du bot |
|
||||||
|
|
||||||
|
Les pages sont filtrées dans le navigateur : la palette répond avant même d’avoir interrogé le serveur, et reste utile si Gitea ne répond pas. Une source qui échoue est simplement absente des résultats.
|
||||||
|
|
||||||
|
Les flèches naviguent, **Entrée** ouvre, **Échap** ferme. Une page à laquelle tu n’as pas accès n’apparaît jamais dans les résultats.
|
||||||
|
|
||||||
|
### Page de statut publique
|
||||||
|
|
||||||
|
**`/status`** est lisible sans compte : état du bot, latence Discord, dernier déploiement par environnement, dernières releases. Elle est rendue **côté serveur, sans une seule ligne de JavaScript**, et s’actualise par une balise `meta refresh` — une page de statut qui a besoin d’un navigateur moderne pour dire qu’il y a une panne est une page inutile au moment où elle sert.
|
||||||
|
|
||||||
|
Deux garde-fous, parce que la page est publique :
|
||||||
|
|
||||||
|
- Un dépôt que Gitea ne liste pas comme public apparaît **sans son nom** : l’environnement reste visible, le dépôt non.
|
||||||
|
- La bannière annonce toujours le pire état vrai. Un déploiement en échec empêche l’en-tête vert, même si le bot répond.
|
||||||
|
|
||||||
|
`WEB_PUBLIC_STATUS=false` la désactive entièrement ; `/status` renvoie alors 404, comme `/api/status`.
|
||||||
|
|
||||||
|
`/api/status` donne la même chose en JSON, sans session : c’est ce qu’une sonde de supervision doit interroger, plutôt que `/api/health` qui ne dit que « le processus vit ».
|
||||||
|
|
||||||
|
## 8. Wiki public
|
||||||
|
|
||||||
Le bot sert une documentation publique sur **`/wiki`**, lisible sans compte, écrite depuis **Tableau de bord → Wiki**.
|
Le bot sert une documentation publique sur **`/wiki`**, lisible sans compte, écrite depuis **Tableau de bord → Wiki**.
|
||||||
|
|
||||||
@@ -161,17 +204,21 @@ La politique de confidentialité est rédigée selon la **LPD suisse révisée**
|
|||||||
|
|
||||||
Une page supprimée par erreur est recréée au démarrage suivant ; une page réécrite ne l'est jamais.
|
Une page supprimée par erreur est recréée au démarrage suivant ; une page réécrite ne l'est jamais.
|
||||||
|
|
||||||
## 8. Réglages du serveur
|
## 9. Réglages du serveur
|
||||||
|
|
||||||
**Tableau de bord → Paramètres** regroupe ce qui se change sans toucher au `.env` : accueil des membres, modération, tickets, salons vocaux, notifications, interface. Chaque réglage est décrit une seule fois dans `src/config/guild-settings.js`, et un test vérifie que **chaque clé déclarée est réellement lue par le code** — un interrupteur qui ne fait rien est pire que pas d'interrupteur.
|
**Tableau de bord → Paramètres** regroupe ce qui se change sans toucher au `.env` : accueil des membres, modération, règlement, tickets, salons vocaux, notifications, interface. Chaque réglage est décrit une seule fois dans `src/config/guild-settings.js`, et un test vérifie que **chaque clé déclarée est réellement lue par le code** — un interrupteur qui ne fait rien est pire que pas d'interrupteur.
|
||||||
|
|
||||||
Les changements prennent effet immédiatement, sans redémarrage, contrairement aux valeurs du `.env`.
|
Les changements prennent effet immédiatement, sans redémarrage, contrairement aux valeurs du `.env`.
|
||||||
|
|
||||||
## 9. Publier les commandes slash
|
### Rédiger et publier le règlement
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
**Tableau de bord → Serveur Discord → Commandes slash → Publier sur Discord** fait ce que fait `npm run deploy:commands`, sans accès shell. Les commandes par serveur sont actives immédiatement. À relancer après chaque ajout ou modification de commande.
|
**Tableau de bord → Serveur Discord → Commandes slash → Publier sur Discord** fait ce que fait `npm run deploy:commands`, sans accès shell. Les commandes par serveur sont actives immédiatement. À relancer après chaque ajout ou modification de commande.
|
||||||
|
|
||||||
## 10. Jetons d'API
|
## 11. Jetons d'API
|
||||||
|
|
||||||
Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée.
|
Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée.
|
||||||
|
|
||||||
@@ -181,7 +228,7 @@ curl -H "Authorization: Bearer fws_…" https://bot.exemple.org/api/overview
|
|||||||
|
|
||||||
Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment.
|
Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment.
|
||||||
|
|
||||||
## 11. Sécurité
|
## 12. Sécurité
|
||||||
|
|
||||||
- **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site.
|
- **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site.
|
||||||
- **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`.
|
- **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`.
|
||||||
@@ -192,7 +239,7 @@ Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personn
|
|||||||
- **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact.
|
- **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact.
|
||||||
- **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur.
|
- **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur.
|
||||||
|
|
||||||
## 12. Fonctionnement interne
|
## 13. Fonctionnement interne
|
||||||
|
|
||||||
```text
|
```text
|
||||||
src/web/
|
src/web/
|
||||||
@@ -209,12 +256,17 @@ src/web/
|
|||||||
├── services/
|
├── services/
|
||||||
│ ├── env-schema.js # Description documentée de chaque variable
|
│ ├── env-schema.js # Description documentée de chaque variable
|
||||||
│ ├── env-file.js # Lecture, rendu, sauvegarde et écriture du .env
|
│ ├── env-file.js # Lecture, rendu, sauvegarde et écriture du .env
|
||||||
│ └── deploy-service.js # Exécution des déploiements et notifications
|
│ ├── deploy-service.js # Exécution des déploiements et notifications
|
||||||
|
│ ├── build-info.js # Version et date de l’interface réellement servie
|
||||||
|
│ ├── wiki-seed.js # Pages créées au premier démarrage, adresses publiques
|
||||||
|
│ ├── wiki-render.js # Wiki rendu côté serveur
|
||||||
|
│ ├── status-service.js # Instantané public : bot, déploiements, releases
|
||||||
|
│ └── status-render.js # Page /status rendue côté serveur, sans script
|
||||||
└── public/ # Front servi tel quel (aucun build)
|
└── public/ # Front servi tel quel (aucun build)
|
||||||
├── index.html
|
├── index.html
|
||||||
├── styles.css
|
├── styles.css
|
||||||
├── app.js # Shell, navigation, routage par fragment
|
├── app.js # Shell, navigation, routage par fragment
|
||||||
├── core/ # dom.js, api.js, ui.js
|
├── core/ # dom.js, api.js, ui.js, live.js, nav.js, palette.js
|
||||||
└── views/ # Une vue par page
|
└── views/ # Une vue par page
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -236,7 +288,7 @@ Le serveur authentifie, vérifie l'origine, applique le niveau requis, lit le co
|
|||||||
|
|
||||||
Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port.
|
Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port.
|
||||||
|
|
||||||
## 13. Dépannage
|
## 14. Dépannage
|
||||||
|
|
||||||
| Symptôme | Cause probable |
|
| Symptôme | Cause probable |
|
||||||
| ---------------------------------------------- | ------------------------------------------------------------------------------- |
|
| ---------------------------------------------- | ------------------------------------------------------------------------------- |
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||||
import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
|
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
|
||||||
import { listActions } from '../../database/repositories/moderation-repository.js';
|
import { listActions } from '../../database/repositories/moderation-repository.js';
|
||||||
import { formatDuration } from '../../services/moderation/moderation-service.js';
|
import { formatDuration, moderationLabel } from '../../services/moderation/moderation-service.js';
|
||||||
import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
|
import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
|
||||||
|
|
||||||
export const access = ACCESS_LEVELS.STAFF;
|
export const access = ACCESS_LEVELS.STAFF;
|
||||||
@@ -20,11 +20,10 @@ export const data = new SlashCommandBuilder()
|
|||||||
);
|
);
|
||||||
|
|
||||||
function formatEntry(row) {
|
function formatEntry(row) {
|
||||||
const meta = MODERATION_ACTIONS[row.action];
|
|
||||||
const target = row.target_id ? `<@${row.target_id}>` : 'salon';
|
const target = row.target_id ? `<@${row.target_id}>` : 'salon';
|
||||||
const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : '';
|
const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : '';
|
||||||
return (
|
return (
|
||||||
`\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` +
|
`\`${row.created_at}\` **${moderationLabel(row.action)}** — ${target}${duration}\n` +
|
||||||
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
|
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ export async function execute(interaction) {
|
|||||||
assertModerationTarget(interaction, target);
|
assertModerationTarget(interaction, target);
|
||||||
|
|
||||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||||
await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`);
|
await target.timeout(durationMs, reason ?? `Mise en sourdine de ${minutes} minutes`);
|
||||||
|
|
||||||
await logModerationAction(interaction, {
|
await logModerationAction(interaction, {
|
||||||
action: 'mute',
|
action: 'mute',
|
||||||
@@ -55,7 +55,7 @@ export async function execute(interaction) {
|
|||||||
await interaction.editReply({
|
await interaction.editReply({
|
||||||
embeds: [
|
embeds: [
|
||||||
successEmbed(
|
successEmbed(
|
||||||
`C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
|
`C’est fait : **${target.user.tag}** est en sourdine pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||||
|
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||||
|
import { UserFacingError } from '../../core/errors.js';
|
||||||
|
import {
|
||||||
|
assertModerationTarget,
|
||||||
|
logModerationAction,
|
||||||
|
notifyTarget,
|
||||||
|
targetNoticeEmbed,
|
||||||
|
} from '../../services/moderation/moderation-service.js';
|
||||||
|
import { successEmbed } from '../../ui/embeds.js';
|
||||||
|
|
||||||
|
export const access = ACCESS_LEVELS.STAFF;
|
||||||
|
|
||||||
|
export const data = new SlashCommandBuilder()
|
||||||
|
.setName('unban')
|
||||||
|
.setDescription('Lever le bannissement d’un membre')
|
||||||
|
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
|
||||||
|
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
|
||||||
|
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
|
||||||
|
|
||||||
|
/** Counterpart of `/ban`, usable whether or not the member already left. */
|
||||||
|
export async function execute(interaction) {
|
||||||
|
const user = interaction.options.getUser('user', true);
|
||||||
|
const reason = interaction.options.getString('reason');
|
||||||
|
|
||||||
|
// Fetching the ban first turns “not banned” into a clear message instead of
|
||||||
|
// the missing-ban error Discord returns from the removal itself.
|
||||||
|
const ban = await interaction.guild.bans.fetch(user.id).catch(() => null);
|
||||||
|
if (!ban) {
|
||||||
|
throw new UserFacingError(`${user.tag} n’est pas banni de ce serveur : il n’y a rien à lever.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A banned member has usually already left, so the hierarchy is only checked
|
||||||
|
// while they are still on the server (a ban applied too quickly, typically).
|
||||||
|
const member = await interaction.guild.members.fetch(user.id).catch(() => null);
|
||||||
|
if (member) assertModerationTarget(interaction, member);
|
||||||
|
|
||||||
|
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||||
|
await interaction.guild.bans.remove(
|
||||||
|
user.id,
|
||||||
|
reason ?? `Débannissement demandé par ${interaction.user.tag}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
await logModerationAction(interaction, { action: 'unban', targetId: user.id, reason });
|
||||||
|
// A direct message is the only way to tell someone they may come back.
|
||||||
|
const recipient = member ?? (await interaction.client.users.fetch(user.id).catch(() => null));
|
||||||
|
if (recipient) {
|
||||||
|
await notifyTarget(
|
||||||
|
recipient,
|
||||||
|
{ embeds: [targetNoticeEmbed({ action: 'unban', guildName: interaction.guild.name, reason })] },
|
||||||
|
interaction.guildId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await interaction.editReply({
|
||||||
|
embeds: [
|
||||||
|
successEmbed(
|
||||||
|
`C’est fait : **${user.tag}** peut de nouveau rejoindre le serveur. L’historique reste consultable avec \`/mod logs\`.`,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||||
|
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||||
|
import { UserFacingError } from '../../core/errors.js';
|
||||||
|
import {
|
||||||
|
assertModerationTarget,
|
||||||
|
fetchTargetMember,
|
||||||
|
logModerationAction,
|
||||||
|
notifyTarget,
|
||||||
|
targetNoticeEmbed,
|
||||||
|
} from '../../services/moderation/moderation-service.js';
|
||||||
|
import { successEmbed } from '../../ui/embeds.js';
|
||||||
|
|
||||||
|
export const access = ACCESS_LEVELS.STAFF;
|
||||||
|
|
||||||
|
export const data = new SlashCommandBuilder()
|
||||||
|
.setName('unmute')
|
||||||
|
.setDescription('Lever l’exclusion temporaire d’un membre avant la fin')
|
||||||
|
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
|
||||||
|
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
|
||||||
|
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
|
||||||
|
|
||||||
|
/** Counterpart of `/mute`: clears the timeout early and keeps the trail. */
|
||||||
|
export async function execute(interaction) {
|
||||||
|
const user = interaction.options.getUser('user', true);
|
||||||
|
const reason = interaction.options.getString('reason');
|
||||||
|
|
||||||
|
const target = await fetchTargetMember(interaction, user.id);
|
||||||
|
assertModerationTarget(interaction, target);
|
||||||
|
// Discord answers a timeout removal on a member who is not muted with an
|
||||||
|
// opaque error, so the check turns it into an explicit message.
|
||||||
|
if (!target.isCommunicationDisabled()) {
|
||||||
|
throw new UserFacingError(
|
||||||
|
`${target.user.tag} n’est pas en exclusion temporaire : cette personne peut déjà écrire.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||||
|
await target.timeout(null, reason ?? `Levée d’exclusion demandée par ${interaction.user.tag}`);
|
||||||
|
|
||||||
|
await logModerationAction(interaction, { action: 'unmute', targetId: target.id, reason });
|
||||||
|
await notifyTarget(target, {
|
||||||
|
embeds: [targetNoticeEmbed({ action: 'unmute', guildName: interaction.guild.name, reason })],
|
||||||
|
});
|
||||||
|
|
||||||
|
await interaction.editReply({
|
||||||
|
embeds: [
|
||||||
|
successEmbed(
|
||||||
|
`C’est fait : **${target.user.tag}** peut de nouveau écrire sur le serveur. L’historique reste consultable avec \`/mod logs\`.`,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
|||||||
+49
-12
@@ -28,23 +28,60 @@ export const ACCESS_LABELS = Object.freeze({
|
|||||||
[ACCESS_LEVELS.OWNER]: 'Owner',
|
[ACCESS_LEVELS.OWNER]: 'Owner',
|
||||||
});
|
});
|
||||||
|
|
||||||
/** Moderation actions: Discord label, embed color and stored duration (M8). */
|
/**
|
||||||
|
* Moderation actions: Discord label, embed color and stored duration (M8).
|
||||||
|
* The emoji belongs to the entry so every surface (log channel, direct message,
|
||||||
|
* `/mod logs`, dashboard) tells a mute from a kick at a glance: the wording
|
||||||
|
* alone read like a temporary kick.
|
||||||
|
*/
|
||||||
export const MODERATION_ACTIONS = Object.freeze({
|
export const MODERATION_ACTIONS = Object.freeze({
|
||||||
warn: { label: 'Avertissement', color: COLORS.warning, duration: false },
|
warn: { label: 'Avertissement', emoji: '⚠️', color: COLORS.warning, duration: false },
|
||||||
mute: { label: 'Exclusion temporaire', color: COLORS.moderation, duration: true },
|
mute: { label: 'Mise en sourdine', emoji: '🔇', color: COLORS.moderation, duration: true },
|
||||||
kick: { label: 'Expulsion', color: COLORS.moderation, duration: false },
|
unmute: {
|
||||||
ban: { label: 'Bannissement', color: COLORS.error, duration: false },
|
label: 'Levée de la mise en sourdine',
|
||||||
clear: { label: 'Suppression de messages', color: COLORS.warning, duration: false },
|
emoji: '🔊',
|
||||||
role: { label: 'Modification de rôle', color: COLORS.primary, duration: false },
|
color: COLORS.success,
|
||||||
|
duration: false,
|
||||||
|
},
|
||||||
|
kick: { label: 'Expulsion', emoji: '👢', color: COLORS.moderation, duration: false },
|
||||||
|
ban: { label: 'Bannissement', emoji: '🔨', color: COLORS.error, duration: false },
|
||||||
|
unban: { label: 'Débannissement', emoji: '🔓', color: COLORS.success, duration: false },
|
||||||
|
clear: { label: 'Supclusion de messages', emoji: '🧹', color: COLORS.warning, duration: false },
|
||||||
|
role: { label: 'Modification de rôle', emoji: '🏷️', color: COLORS.primary, duration: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
/** 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). */
|
||||||
|
|||||||
+3
-1
@@ -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'),
|
||||||
@@ -92,6 +91,9 @@ export const env = Object.freeze({
|
|||||||
// dashboard, so it stays off until it is explicitly enabled (M16-T06).
|
// dashboard, so it stays off until it is explicitly enabled (M16-T06).
|
||||||
allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'),
|
allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'),
|
||||||
allowRestart: readBool('WEB_ALLOW_RESTART'),
|
allowRestart: readBool('WEB_ALLOW_RESTART'),
|
||||||
|
// The public status page is opt-out rather than opt-in: a bot people rely on
|
||||||
|
// owes them a place to check before asking.
|
||||||
|
publicStatus: readBool('WEB_PUBLIC_STATUS', true),
|
||||||
deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000),
|
deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000),
|
||||||
rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240),
|
rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -17,6 +17,11 @@ export const SETTING_SECTIONS = Object.freeze([
|
|||||||
summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.',
|
summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.',
|
||||||
},
|
},
|
||||||
{ id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' },
|
{ id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' },
|
||||||
|
{
|
||||||
|
id: 'rules',
|
||||||
|
title: 'Règlement',
|
||||||
|
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.' },
|
||||||
{
|
{
|
||||||
id: 'voice',
|
id: 'voice',
|
||||||
@@ -91,7 +96,7 @@ export const GUILD_SETTINGS = Object.freeze([
|
|||||||
{
|
{
|
||||||
key: 'moderation.defaultMuteMinutes',
|
key: 'moderation.defaultMuteMinutes',
|
||||||
section: 'moderation',
|
section: 'moderation',
|
||||||
label: 'Durée d’exclusion par défaut (min)',
|
label: 'Durée de mise en sourdine par défaut (min)',
|
||||||
help: 'Proposée quand `/mute` est lancé sans durée.',
|
help: 'Proposée quand `/mute` est lancé sans durée.',
|
||||||
type: 'int',
|
type: 'int',
|
||||||
default: 60,
|
default: 60,
|
||||||
@@ -110,6 +115,17 @@ export const GUILD_SETTINGS = Object.freeze([
|
|||||||
advanced: true,
|
advanced: true,
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// --- Règlement ---------------------------------------------------------------
|
||||||
|
{
|
||||||
|
key: 'rules.markdown',
|
||||||
|
section: 'rules',
|
||||||
|
label: 'Règlement (markdown)',
|
||||||
|
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: 'markdown',
|
||||||
|
default: '',
|
||||||
|
maxLength: 4000,
|
||||||
|
},
|
||||||
|
|
||||||
// --- Tickets ---------------------------------------------------------------
|
// --- Tickets ---------------------------------------------------------------
|
||||||
{
|
{
|
||||||
key: 'tickets.deleteChannelOnClose',
|
key: 'tickets.deleteChannelOnClose',
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- The legal pages move to the addresses platforms expect (M17)
|
||||||
|
--
|
||||||
|
-- Discord, and most app stores, ask for a terms URL and a privacy URL. Serving
|
||||||
|
-- them under `/wiki/` works but reads badly in a form field, so they move to
|
||||||
|
-- the root. Renaming rather than recreating keeps whatever the organization
|
||||||
|
-- has already written in them.
|
||||||
|
|
||||||
|
UPDATE wiki_pages SET slug = 'terms-of-service' WHERE slug = 'conditions-utilisation';
|
||||||
|
UPDATE wiki_pages SET slug = 'privacy-policy' WHERE slug = 'politique-confidentialite';
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
-- Lifted sanctions join the sanctions in the moderation history
|
||||||
|
--
|
||||||
|
-- `/unmute` and `/unban` are recorded like `/mute` and `/ban`, but SQLite cannot
|
||||||
|
-- alter a CHECK constraint: the table is rebuilt and the rows copied over so the
|
||||||
|
-- history already stored survives the migration.
|
||||||
|
|
||||||
|
CREATE TABLE moderation_actions_lifted (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
guild_id TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'unmute', 'kick', 'ban', 'unban', 'clear', 'role')),
|
||||||
|
target_id TEXT,
|
||||||
|
moderator_id TEXT NOT NULL,
|
||||||
|
reason TEXT,
|
||||||
|
duration_ms INTEGER,
|
||||||
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO moderation_actions_lifted (id, guild_id, action, target_id, moderator_id, reason, duration_ms, created_at)
|
||||||
|
SELECT id, guild_id, action, target_id, moderator_id, reason, duration_ms, created_at FROM moderation_actions;
|
||||||
|
|
||||||
|
DROP TABLE moderation_actions;
|
||||||
|
ALTER TABLE moderation_actions_lifted RENAME TO moderation_actions;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
-- The rules message published from the dashboard (M19)
|
||||||
|
--
|
||||||
|
-- The bot republishes the rules by deleting the previous message and sending
|
||||||
|
-- the new one, so it has to remember which message it owns. Without this the
|
||||||
|
-- channel would slowly fill with outdated copies.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS rules_messages (
|
||||||
|
guild_id TEXT PRIMARY KEY,
|
||||||
|
channel_id TEXT NOT NULL,
|
||||||
|
message_id TEXT NOT NULL,
|
||||||
|
updated_by TEXT,
|
||||||
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
@@ -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)
|
||||||
|
);
|
||||||
@@ -270,16 +270,83 @@ export function removeCard(id) {
|
|||||||
return getDatabase().prepare('DELETE FROM project_cards WHERE id = ?').run(id).changes;
|
return getDatabase().prepare('DELETE FROM project_cards WHERE id = ?').run(id).changes;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cards carried by one member, across every board of the guild. */
|
const parseAssignedCard = (row) => ({
|
||||||
|
...parseCard(row),
|
||||||
|
column_is_done: Boolean(row.column_is_done),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cards carried by one member, across every board of the guild (M19).
|
||||||
|
*
|
||||||
|
* The column travels with the card: « what am I on today » cannot be answered
|
||||||
|
* without knowing whether a card is still open, and asking per card turns the
|
||||||
|
* page into a staircase of queries. `done_column_id` comes along for the same
|
||||||
|
* reason — finishing a card from here is then a single move.
|
||||||
|
*/
|
||||||
export function listCardsForAssignee(guildId, assigneeId) {
|
export function listCardsForAssignee(guildId, assigneeId) {
|
||||||
return getDatabase()
|
return getDatabase()
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT c.*, b.name AS board_name, b.repository
|
`SELECT c.*,
|
||||||
|
b.name AS board_name,
|
||||||
|
b.scope AS board_scope,
|
||||||
|
b.repository,
|
||||||
|
col.name AS column_name,
|
||||||
|
col.is_done AS column_is_done,
|
||||||
|
(SELECT d.id FROM project_columns d
|
||||||
|
WHERE d.board_id = b.id AND d.is_done = 1
|
||||||
|
ORDER BY d.position, d.id LIMIT 1) AS done_column_id
|
||||||
FROM project_cards c
|
FROM project_cards c
|
||||||
JOIN project_boards b ON b.id = c.board_id
|
JOIN project_boards b ON b.id = c.board_id
|
||||||
|
JOIN project_columns col ON col.id = c.column_id
|
||||||
WHERE b.guild_id = ? AND c.assignee_id = ?
|
WHERE b.guild_id = ? AND c.assignee_id = ?
|
||||||
ORDER BY c.due_at IS NULL, c.due_at, c.id`,
|
ORDER BY c.due_at IS NULL, c.due_at, c.id`,
|
||||||
)
|
)
|
||||||
.all(guildId, assigneeId)
|
.all(guildId, assigneeId)
|
||||||
.map(parseCard);
|
.map(parseAssignedCard);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Who carries cards, and how many are still open.
|
||||||
|
*
|
||||||
|
* Lets the page offer a picker without asking Discord for the member list,
|
||||||
|
* which is unavailable whenever the bot is offline — precisely when someone is
|
||||||
|
* most likely to be looking at the dashboard.
|
||||||
|
*/
|
||||||
|
export function listAssignees(guildId) {
|
||||||
|
return getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`SELECT c.assignee_id AS assigneeId,
|
||||||
|
COUNT(*) AS total,
|
||||||
|
SUM(CASE WHEN col.is_done = 1 THEN 0 ELSE 1 END) AS open
|
||||||
|
FROM project_cards c
|
||||||
|
JOIN project_boards b ON b.id = c.board_id
|
||||||
|
JOIN project_columns col ON col.id = c.column_id
|
||||||
|
WHERE b.guild_id = ? AND c.assignee_id IS NOT NULL AND c.assignee_id <> ''
|
||||||
|
GROUP BY c.assignee_id
|
||||||
|
ORDER BY open DESC, total DESC`,
|
||||||
|
)
|
||||||
|
.all(guildId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cards whose title, body, labels or issue matches, for the command palette (M19). */
|
||||||
|
export function searchCards(guildId, term, limit = 8) {
|
||||||
|
const needle = `%${term}%`;
|
||||||
|
return getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`SELECT c.*,
|
||||||
|
b.name AS board_name,
|
||||||
|
b.scope AS board_scope,
|
||||||
|
b.repository,
|
||||||
|
col.name AS column_name,
|
||||||
|
col.is_done AS column_is_done
|
||||||
|
FROM project_cards c
|
||||||
|
JOIN project_boards b ON b.id = c.board_id
|
||||||
|
JOIN project_columns col ON col.id = c.column_id
|
||||||
|
WHERE b.guild_id = ?
|
||||||
|
AND (c.title LIKE ? OR c.body LIKE ? OR c.labels LIKE ? OR c.issue_ref LIKE ?)
|
||||||
|
ORDER BY col.is_done, c.due_at IS NULL, c.due_at, c.id DESC
|
||||||
|
LIMIT ?`,
|
||||||
|
)
|
||||||
|
.all(guildId, needle, needle, needle, needle, limit)
|
||||||
|
.map(parseAssignedCard);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { getDatabase } from '../index.js';
|
||||||
|
|
||||||
|
/** The rules message the bot published, so the next version can replace it. */
|
||||||
|
export function setRulesMessage({ guildId, channelId, messageId, updatedBy = null }) {
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO rules_messages (guild_id, channel_id, message_id, updated_by)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
ON CONFLICT (guild_id) DO UPDATE SET
|
||||||
|
channel_id = excluded.channel_id,
|
||||||
|
message_id = excluded.message_id,
|
||||||
|
updated_by = excluded.updated_by,
|
||||||
|
updated_at = datetime('now')`,
|
||||||
|
)
|
||||||
|
.run(guildId, channelId, messageId, updatedBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRulesMessage(guildId) {
|
||||||
|
return getDatabase().prepare('SELECT * FROM rules_messages WHERE guild_id = ?').get(guildId) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearRulesMessage(guildId) {
|
||||||
|
return getDatabase().prepare('DELETE FROM rules_messages WHERE guild_id = ?').run(guildId).changes;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -40,6 +40,15 @@ export const org = {
|
|||||||
giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList),
|
giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList),
|
||||||
createRepo: (payload, owner = defaultOwner()) =>
|
createRepo: (payload, owner = defaultOwner()) =>
|
||||||
giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos`, { method: 'POST', body: payload }),
|
giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos`, { method: 'POST', body: payload }),
|
||||||
|
/**
|
||||||
|
* Issues and pull requests of the whole organization, in one request.
|
||||||
|
*
|
||||||
|
* The per-repository endpoint would mean one call per repository, which the
|
||||||
|
* command palette cannot afford on every keystroke. Absent before Gitea 1.15,
|
||||||
|
* so callers tolerate a rejection.
|
||||||
|
*/
|
||||||
|
searchIssues: ({ owner = defaultOwner(), q, state = 'open', type, limit = 10 } = {}) =>
|
||||||
|
giteaRequest(`/repos/issues/search${query({ q, owner, state, type, limit })}`).then(asList),
|
||||||
/** Identity behind `GITEA_TOKEN`, used by the settings page to check the credentials. */
|
/** Identity behind `GITEA_TOKEN`, used by the settings page to check the credentials. */
|
||||||
whoami: () => giteaRequest('/user'),
|
whoami: () => giteaRequest('/user'),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,17 @@ import { logEvent } from '../../database/repositories/event-log-repository.js';
|
|||||||
import { recordAction } from '../../database/repositories/moderation-repository.js';
|
import { recordAction } from '../../database/repositories/moderation-repository.js';
|
||||||
import { baseEmbed } from '../../ui/embeds.js';
|
import { baseEmbed } from '../../ui/embeds.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Label shown for an action everywhere it is rendered (log channel, direct
|
||||||
|
* message, `/mod logs`, dashboard). Falls back to the raw action name, so a
|
||||||
|
* row written by another version still reads as something.
|
||||||
|
* @param {string} action
|
||||||
|
*/
|
||||||
|
export function moderationLabel(action) {
|
||||||
|
const meta = MODERATION_ACTIONS[action];
|
||||||
|
return meta ? `${meta.emoji} ${meta.label}` : action;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
|
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
|
||||||
* @param {import('discord.js').ChatInputCommandInteraction} interaction
|
* @param {import('discord.js').ChatInputCommandInteraction} interaction
|
||||||
@@ -82,7 +93,7 @@ export async function sendModerationLog(
|
|||||||
|
|
||||||
const meta = MODERATION_ACTIONS[action];
|
const meta = MODERATION_ACTIONS[action];
|
||||||
const embed = baseEmbed(meta?.color)
|
const embed = baseEmbed(meta?.color)
|
||||||
.setTitle(`🛡️ Modération — ${meta?.label ?? action}`)
|
.setTitle(`🛡️ Modération — ${moderationLabel(action)}`)
|
||||||
.addFields(
|
.addFields(
|
||||||
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
|
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
|
||||||
{ name: 'Par', value: `<@${moderatorId}>`, inline: true },
|
{ name: 'Par', value: `<@${moderatorId}>`, inline: true },
|
||||||
@@ -100,9 +111,11 @@ export async function sendModerationLog(
|
|||||||
* Sends the private notice to the sanctioned member, when the server wants one
|
* Sends the private notice to the sanctioned member, when the server wants one
|
||||||
* (M8-T07). Never throws: plenty of accounts refuse direct messages, and that
|
* (M8-T07). Never throws: plenty of accounts refuse direct messages, and that
|
||||||
* must not turn a successful sanction into an error.
|
* must not turn a successful sanction into an error.
|
||||||
|
* @param guildId Server the sanction belongs to. A lifted ban targets someone
|
||||||
|
* who has left the server, so a plain `User` is accepted with an explicit id.
|
||||||
*/
|
*/
|
||||||
export async function notifyTarget(member, payload) {
|
export async function notifyTarget(member, payload, guildId = member.guild?.id) {
|
||||||
if (!readSetting('moderation.dmTarget', member.guild.id)) return false;
|
if (!readSetting('moderation.dmTarget', guildId)) return false;
|
||||||
return member
|
return member
|
||||||
.send(payload)
|
.send(payload)
|
||||||
.then(() => true)
|
.then(() => true)
|
||||||
@@ -115,7 +128,7 @@ export function targetNoticeEmbed({ action, guildName, reason = null, durationMs
|
|||||||
const embed = baseEmbed(meta?.color)
|
const embed = baseEmbed(meta?.color)
|
||||||
.setTitle(`Sanction sur ${guildName}`)
|
.setTitle(`Sanction sur ${guildName}`)
|
||||||
.setDescription(
|
.setDescription(
|
||||||
`Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
|
`Action : **${moderationLabel(action)}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
|
||||||
)
|
)
|
||||||
.addFields({ name: 'Motif', value: reason || 'Non précisé' });
|
.addFields({ name: 'Motif', value: reason || 'Non précisé' });
|
||||||
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
|
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import { COLORS } from '../../config/constants.js';
|
||||||
|
import { env } from '../../config/env.js';
|
||||||
|
import { createLogger } from '../../core/logger.js';
|
||||||
|
import { logEvent } from '../../database/repositories/event-log-repository.js';
|
||||||
|
import { getRulesMessage, setRulesMessage } from '../../database/repositories/rules-repository.js';
|
||||||
|
import { baseEmbed } from '../../ui/embeds.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rules of the server, written from the dashboard and kept in a single pinned
|
||||||
|
* message in `CHANNEL_RULES_ID` (M19).
|
||||||
|
*
|
||||||
|
* Saving edits the message already published, so the channel keeps one set of
|
||||||
|
* rules — same link, same position, and the pin survives. A new message is
|
||||||
|
* only sent when the bot has none yet, or when the previous one was deleted by
|
||||||
|
* hand.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const log = createLogger('rules');
|
||||||
|
|
||||||
|
/** Discord refuses an embed description longer than that. */
|
||||||
|
export const RULES_MAX_LENGTH = 4000;
|
||||||
|
|
||||||
|
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());
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Publishes the rules, editing the message already there when there is one.
|
||||||
|
* @param {import('discord.js').Client} client
|
||||||
|
* @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options
|
||||||
|
* @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean, edited: boolean }>}
|
||||||
|
*/
|
||||||
|
export async function publishRules(
|
||||||
|
client,
|
||||||
|
{ guildId, markdown, actorId = null, channelId = env.channels.rules },
|
||||||
|
) {
|
||||||
|
if (!channelId) {
|
||||||
|
throw new Error('Aucun salon des règles configuré : renseigne CHANNEL_RULES_ID dans le .env.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = String(markdown ?? '').trim();
|
||||||
|
if (content === '') throw new Error('Le règlement est vide.');
|
||||||
|
if (content.length > RULES_MAX_LENGTH) {
|
||||||
|
throw new Error(`${RULES_MAX_LENGTH} caractères maximum pour un règlement.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const channel = await client.channels.fetch(channelId).catch(() => null);
|
||||||
|
if (!channel?.isSendable()) {
|
||||||
|
throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const edited = await editPublishedRules(client, guildId, content);
|
||||||
|
const message = edited ?? (await channel.send({ embeds: [rulesEmbed(content)] }));
|
||||||
|
|
||||||
|
// Only a brand new message has to be pinned: an edited one keeps its pin.
|
||||||
|
const pinned = edited
|
||||||
|
? true
|
||||||
|
: await message
|
||||||
|
.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;
|
||||||
|
});
|
||||||
|
|
||||||
|
setRulesMessage({
|
||||||
|
guildId,
|
||||||
|
channelId,
|
||||||
|
messageId: message.id,
|
||||||
|
updatedBy: actorId,
|
||||||
|
});
|
||||||
|
logEvent({
|
||||||
|
guildId,
|
||||||
|
type: 'web.rules.published',
|
||||||
|
actorId,
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
messageId: message.id,
|
||||||
|
url: message.url ?? null,
|
||||||
|
channelId,
|
||||||
|
pinned,
|
||||||
|
edited: Boolean(edited),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
if (!stored) return null;
|
||||||
|
|
||||||
|
const channel = await client.channels.fetch(stored.channel_id).catch(() => null);
|
||||||
|
const message = await channel?.messages?.fetch(stored.message_id).catch(() => null);
|
||||||
|
if (!message?.editable) return null;
|
||||||
|
|
||||||
|
return message
|
||||||
|
.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. */
|
||||||
|
export function rulesStatus(guildId, channelId = env.channels.rules) {
|
||||||
|
const stored = getRulesMessage(guildId);
|
||||||
|
return {
|
||||||
|
channelId: channelId || null,
|
||||||
|
configured: Boolean(channelId),
|
||||||
|
messageId: stored?.message_id ?? null,
|
||||||
|
publishedAt: stored?.updated_at ?? null,
|
||||||
|
publishedBy: stored?.updated_by ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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
@@ -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
-4
@@ -1,6 +1,7 @@
|
|||||||
import { ChannelType, REST, Routes } from 'discord.js';
|
import { ChannelType, REST, Routes } from 'discord.js';
|
||||||
import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js';
|
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
|
||||||
import { env } from '../../config/env.js';
|
import { env } from '../../config/env.js';
|
||||||
|
import { readSetting, writeSetting } from '../../config/guild-settings.js';
|
||||||
import { ExternalApiError } from '../../core/errors.js';
|
import { ExternalApiError } from '../../core/errors.js';
|
||||||
import { createLogger } from '../../core/logger.js';
|
import { createLogger } from '../../core/logger.js';
|
||||||
import { canActOn, getAccessLevel } from '../../core/permissions.js';
|
import { canActOn, getAccessLevel } from '../../core/permissions.js';
|
||||||
@@ -15,7 +16,8 @@ import {
|
|||||||
removeNotificationChannel,
|
removeNotificationChannel,
|
||||||
setNotificationChannel,
|
setNotificationChannel,
|
||||||
} from '../../database/repositories/notification-repository.js';
|
} from '../../database/repositories/notification-repository.js';
|
||||||
import { sendModerationLog } from '../../services/moderation/moderation-service.js';
|
import { moderationLabel, sendModerationLog } from '../../services/moderation/moderation-service.js';
|
||||||
|
import { publishRules, rulesStatus } from '../../services/rules/rules-service.js';
|
||||||
import { badRequest, forbidden, notFound } from '../http.js';
|
import { badRequest, forbidden, notFound } from '../http.js';
|
||||||
|
|
||||||
/** Discord server management from the dashboard (M16-T05). */
|
/** Discord server management from the dashboard (M16-T05). */
|
||||||
@@ -201,7 +203,7 @@ export function registerDiscordRoutes(router) {
|
|||||||
const reason = String(body.reason ?? '').trim() || 'Non précisé';
|
const reason = String(body.reason ?? '').trim() || 'Non précisé';
|
||||||
const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null;
|
const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null;
|
||||||
if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) {
|
if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) {
|
||||||
throw badRequest('Une durée en millisecondes est requise pour une exclusion temporaire.');
|
throw badRequest('Une durée en millisecondes est requise pour une mise en sourdine.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`;
|
const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`;
|
||||||
@@ -231,7 +233,7 @@ export function registerDiscordRoutes(router) {
|
|||||||
durationMs,
|
durationMs,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { ok: true, action, label: MODERATION_ACTIONS[action]?.label ?? action };
|
return { ok: true, action, label: moderationLabel(action) };
|
||||||
},
|
},
|
||||||
{ access: ACCESS_LEVELS.STAFF },
|
{ access: ACCESS_LEVELS.STAFF },
|
||||||
);
|
);
|
||||||
@@ -292,6 +294,39 @@ export function registerDiscordRoutes(router) {
|
|||||||
{ access: ACCESS_LEVELS.STAFF },
|
{ access: ACCESS_LEVELS.STAFF },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// --- Server rules ----------------------------------------------------------
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/api/discord/rules',
|
||||||
|
() => ({ markdown: readSetting('rules.markdown', guildId()), ...rulesStatus(guildId()) }),
|
||||||
|
{ access: ACCESS_LEVELS.STAFF },
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Publishes the rules, replacing the message the bot posted last time. */
|
||||||
|
router.post(
|
||||||
|
'/api/discord/rules',
|
||||||
|
async ({ context, body, actor }) => {
|
||||||
|
const markdown = writeSetting('rules.markdown', body.markdown, {
|
||||||
|
guildId: guildId(),
|
||||||
|
updatedBy: actor.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const published = await publishRules(context.client, {
|
||||||
|
guildId: guildId(),
|
||||||
|
markdown,
|
||||||
|
actorId: actor.userId,
|
||||||
|
});
|
||||||
|
return { ok: true, ...published, ...rulesStatus(guildId()) };
|
||||||
|
} catch (error) {
|
||||||
|
// The text is saved either way: a channel that is simply not configured
|
||||||
|
// yet must not throw away what was written.
|
||||||
|
throw badRequest(error.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ access: ACCESS_LEVELS.DEV },
|
||||||
|
);
|
||||||
|
|
||||||
// --- Notification routing --------------------------------------------------
|
// --- Notification routing --------------------------------------------------
|
||||||
router.get(
|
router.get(
|
||||||
'/api/discord/notifications',
|
'/api/discord/notifications',
|
||||||
|
|||||||
+7
-55
@@ -1,9 +1,7 @@
|
|||||||
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
||||||
import path from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||||
import { registerAuthRoutes } from '../auth/routes.js';
|
import { registerAuthRoutes } from '../auth/routes.js';
|
||||||
import { openEventStream } from '../events.js';
|
import { openEventStream } from '../events.js';
|
||||||
|
import { VERSION, buildAt } from '../services/build-info.js';
|
||||||
import { registerCommunityRoutes } from './community.js';
|
import { registerCommunityRoutes } from './community.js';
|
||||||
import { registerConfigurationRoutes } from './configuration.js';
|
import { registerConfigurationRoutes } from './configuration.js';
|
||||||
import { registerDeploymentRoutes } from './deployments.js';
|
import { registerDeploymentRoutes } from './deployments.js';
|
||||||
@@ -14,61 +12,11 @@ import { registerOverviewRoutes } from './overview.js';
|
|||||||
import { registerProjectRoutes } from './projects.js';
|
import { registerProjectRoutes } from './projects.js';
|
||||||
import { registerReleaseRoutes } from './releases.js';
|
import { registerReleaseRoutes } from './releases.js';
|
||||||
import { registerRepositoryRoutes } from './repositories.js';
|
import { registerRepositoryRoutes } from './repositories.js';
|
||||||
|
import { registerSearchRoutes } from './search.js';
|
||||||
import { registerSettingsRoutes } from './settings.js';
|
import { registerSettingsRoutes } from './settings.js';
|
||||||
|
import { registerStatusRoutes } from './status.js';
|
||||||
import { registerWikiRoutes } from './wiki.js';
|
import { registerWikiRoutes } from './wiki.js';
|
||||||
|
|
||||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
|
|
||||||
const VERSION = (() => {
|
|
||||||
try {
|
|
||||||
return JSON.parse(readFileSync(path.join(here, '../../../package.json'), 'utf8')).version;
|
|
||||||
} catch {
|
|
||||||
return 'inconnue';
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Newest file of the served interface.
|
|
||||||
*
|
|
||||||
* Deployments that ship an archive make it easy to look at a stale copy and
|
|
||||||
* wonder why a fix is missing; this gives the page something to state.
|
|
||||||
*/
|
|
||||||
/**
|
|
||||||
* Newest file of the served interface.
|
|
||||||
*
|
|
||||||
* Read from disk rather than frozen at startup: the front-end is served from
|
|
||||||
* disk on every request, so a marker captured at boot would keep announcing an
|
|
||||||
* old build after an upload — the exact confusion it exists to prevent. Cached
|
|
||||||
* briefly so a health check does not walk the tree each time.
|
|
||||||
*/
|
|
||||||
const BUILD_TTL_MS = 10_000;
|
|
||||||
let buildCache = { at: null, readAt: 0 };
|
|
||||||
|
|
||||||
function buildAt() {
|
|
||||||
if (buildCache.readAt && Date.now() - buildCache.readAt < BUILD_TTL_MS) return buildCache.at;
|
|
||||||
|
|
||||||
const root = path.join(here, '../public');
|
|
||||||
let newest = 0;
|
|
||||||
|
|
||||||
const walk = (directory) => {
|
|
||||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
||||||
const target = path.join(directory, entry.name);
|
|
||||||
if (entry.isDirectory()) walk(target);
|
|
||||||
else newest = Math.max(newest, statSync(target).mtimeMs);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
walk(root);
|
|
||||||
} catch {
|
|
||||||
buildCache = { at: null, readAt: Date.now() };
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
buildCache = { at: newest > 0 ? new Date(newest).toISOString() : null, readAt: Date.now() };
|
|
||||||
return buildCache.at;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Route registration order matters only for readability: the router matches on
|
* Route registration order matters only for readability: the router matches on
|
||||||
* the full pattern, not on declaration order.
|
* the full pattern, not on declaration order.
|
||||||
@@ -92,6 +40,9 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
|
|||||||
registerConfigurationRoutes(router);
|
registerConfigurationRoutes(router);
|
||||||
// The public documentation stays reachable even while the bot is being set up.
|
// The public documentation stays reachable even while the bot is being set up.
|
||||||
registerWikiRoutes(router);
|
registerWikiRoutes(router);
|
||||||
|
// So does the status page: a bot still being configured is exactly what an
|
||||||
|
// uptime monitor, or a visitor, would want to be told.
|
||||||
|
registerStatusRoutes(router);
|
||||||
|
|
||||||
// Long-lived stream the pages listen to instead of polling (M16-T12).
|
// Long-lived stream the pages listen to instead of polling (M16-T12).
|
||||||
router.get(
|
router.get(
|
||||||
@@ -114,6 +65,7 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
|
|||||||
registerDeploymentRoutes(router);
|
registerDeploymentRoutes(router);
|
||||||
registerDiscordRoutes(router);
|
registerDiscordRoutes(router);
|
||||||
registerCommunityRoutes(router);
|
registerCommunityRoutes(router);
|
||||||
|
registerSearchRoutes(router);
|
||||||
registerSettingsRoutes(router);
|
registerSettingsRoutes(router);
|
||||||
registerLogRoutes(router);
|
registerLogRoutes(router);
|
||||||
return router;
|
return router;
|
||||||
|
|||||||
+83
-9
@@ -13,8 +13,10 @@ import {
|
|||||||
getCard,
|
getCard,
|
||||||
getColumn,
|
getColumn,
|
||||||
getOrgBoard,
|
getOrgBoard,
|
||||||
|
listAssignees,
|
||||||
listBoards,
|
listBoards,
|
||||||
listCards,
|
listCards,
|
||||||
|
listCardsForAssignee,
|
||||||
listColumns,
|
listColumns,
|
||||||
moveCard,
|
moveCard,
|
||||||
removeBoard,
|
removeBoard,
|
||||||
@@ -77,6 +79,18 @@ const publicColumn = (column) => ({
|
|||||||
isDone: column.is_done,
|
isDone: column.is_done,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** A card seen from outside its board: it has to say where it comes from (M19). */
|
||||||
|
const publicTask = (card) => ({
|
||||||
|
...publicCard(card),
|
||||||
|
boardId: card.board_id,
|
||||||
|
boardName: card.board_name,
|
||||||
|
boardScope: card.board_scope,
|
||||||
|
repository: card.repository,
|
||||||
|
columnName: card.column_name,
|
||||||
|
isDone: card.column_is_done,
|
||||||
|
doneColumnId: card.done_column_id ?? null,
|
||||||
|
});
|
||||||
|
|
||||||
function board(id) {
|
function board(id) {
|
||||||
const found = getBoard(Number.parseInt(id, 10));
|
const found = getBoard(Number.parseInt(id, 10));
|
||||||
if (!found || found.guild_id !== guildId()) throw notFound('Tableau introuvable.');
|
if (!found || found.guild_id !== guildId()) throw notFound('Tableau introuvable.');
|
||||||
@@ -150,6 +164,45 @@ async function announce(client, { board: owner, card, action, actor, column }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function registerProjectRoutes(router) {
|
export function registerProjectRoutes(router) {
|
||||||
|
// --- My tasks --------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* What one member carries, across every board (M19).
|
||||||
|
*
|
||||||
|
* The boards answer « where does the work stand ». This answers « what am I
|
||||||
|
* on », which is the question someone actually opens a dashboard with, and no
|
||||||
|
* board alone can answer it once the work is spread over several.
|
||||||
|
*/
|
||||||
|
router.get(
|
||||||
|
'/api/me/tasks',
|
||||||
|
async ({ query, actor }) => {
|
||||||
|
const assigneeId = String(query.get('assignee') ?? '').trim() || actor.userId;
|
||||||
|
if (!assigneeId) throw badRequest('Aucun membre à qui rattacher des cartes.');
|
||||||
|
|
||||||
|
const cards = listCardsForAssignee(guildId(), assigneeId);
|
||||||
|
const today = new Date().toISOString().slice(0, 10);
|
||||||
|
const open = cards.filter((entry) => !entry.column_is_done);
|
||||||
|
const dated = (entry, test) => entry.due_at && test(String(entry.due_at).slice(0, 10));
|
||||||
|
|
||||||
|
return {
|
||||||
|
assigneeId,
|
||||||
|
self: assigneeId === actor.userId,
|
||||||
|
assignees: listAssignees(guildId()),
|
||||||
|
counts: {
|
||||||
|
total: cards.length,
|
||||||
|
open: open.length,
|
||||||
|
done: cards.length - open.length,
|
||||||
|
overdue: open.filter((entry) => dated(entry, (due) => due < today)).length,
|
||||||
|
dueToday: open.filter((entry) => dated(entry, (due) => due === today)).length,
|
||||||
|
},
|
||||||
|
cards: cards.map(publicTask),
|
||||||
|
// Resolving costs a round trip to the forge, which the sidebar counter
|
||||||
|
// has no use for — it asks for the numbers and skips it.
|
||||||
|
issues: query.get('issues') === '0' ? {} : await resolveIssues(cards),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
{ access: ACCESS_LEVELS.STAFF },
|
||||||
|
);
|
||||||
|
|
||||||
// --- Boards ----------------------------------------------------------------
|
// --- Boards ----------------------------------------------------------------
|
||||||
router.get(
|
router.get(
|
||||||
'/api/projects',
|
'/api/projects',
|
||||||
@@ -407,26 +460,40 @@ export function registerProjectRoutes(router) {
|
|||||||
{ access: ACCESS_LEVELS.STAFF },
|
{ access: ACCESS_LEVELS.STAFF },
|
||||||
);
|
);
|
||||||
|
|
||||||
/** Turns the open issues of a repository into cards, skipping the ones already there. */
|
/**
|
||||||
|
* Pulls issues from Gitea onto the board.
|
||||||
|
*
|
||||||
|
* An issue already on the board is skipped rather than duplicated, so the
|
||||||
|
* button can be pressed again after a sprint without cleaning up after it.
|
||||||
|
*/
|
||||||
router.post(
|
router.post(
|
||||||
'/api/projects/:id/import',
|
'/api/projects/:id/import',
|
||||||
async ({ params, body, actor }) => {
|
async ({ params, body, actor }) => {
|
||||||
const found = board(params.id);
|
const found = board(params.id);
|
||||||
const repository = String(body.repository ?? found.repository ?? '');
|
|
||||||
const parts = splitRepository(repository);
|
|
||||||
if (!parts) throw badRequest('Dépôt attendu au format `organisation/depot`.');
|
|
||||||
if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré.');
|
if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré.');
|
||||||
|
|
||||||
|
const repository = String(body.repository ?? found.repository ?? '').trim();
|
||||||
|
const parts = splitRepository(repository);
|
||||||
|
if (!parts) throw badRequest('Dépôt attendu au format `organisation/depot`.');
|
||||||
|
|
||||||
|
const state = body.state === 'all' ? 'all' : 'open';
|
||||||
const columns = listColumns(found.id);
|
const columns = listColumns(found.id);
|
||||||
const target = columns.find((column) => !column.is_done) ?? columns[0];
|
if (columns.length === 0) throw badRequest('Ce tableau n’a aucune colonne.');
|
||||||
if (!target) throw badRequest('Ce tableau n’a aucune colonne.');
|
|
||||||
|
// Falls back to the first column that is not the finished one: importing
|
||||||
|
// straight into « Terminé » is never what anyone means.
|
||||||
|
const requested = body.columnId ? getColumn(Number.parseInt(body.columnId, 10)) : null;
|
||||||
|
const target =
|
||||||
|
requested && requested.board_id === found.id
|
||||||
|
? requested
|
||||||
|
: (columns.find((column) => !column.is_done) ?? columns[0]);
|
||||||
|
|
||||||
const existing = new Set(
|
const existing = new Set(
|
||||||
listCards(found.id)
|
listCards(found.id)
|
||||||
.map((card) => card.issue_ref)
|
.map((card) => card.issue_ref)
|
||||||
.filter(Boolean),
|
.filter(Boolean),
|
||||||
);
|
);
|
||||||
const issues = await repos.listIssues(parts.owner, parts.repo, { state: 'open', limit: 50 });
|
const issues = await repos.listIssues(parts.owner, parts.repo, { state, limit: 100 });
|
||||||
|
|
||||||
let imported = 0;
|
let imported = 0;
|
||||||
for (const issue of issues) {
|
for (const issue of issues) {
|
||||||
@@ -440,13 +507,20 @@ export function registerProjectRoutes(router) {
|
|||||||
body: issue.body ? String(issue.body).slice(0, 2000) : null,
|
body: issue.body ? String(issue.body).slice(0, 2000) : null,
|
||||||
issueRef: ref,
|
issueRef: ref,
|
||||||
labels: (issue.labels ?? []).map((label) => label.name),
|
labels: (issue.labels ?? []).map((label) => label.name),
|
||||||
|
dueAt: issue.due_date ? String(issue.due_date).slice(0, 10) : null,
|
||||||
createdBy: actor.userId,
|
createdBy: actor.userId,
|
||||||
});
|
});
|
||||||
imported += 1;
|
imported += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
audit(actor, 'web.project.import', { board: found.id, repository, imported });
|
audit(actor, 'web.project.import', { board: found.id, repository, state, imported });
|
||||||
return { imported, skipped: issues.length - imported, column: target.name };
|
return {
|
||||||
|
imported,
|
||||||
|
skipped: issues.length - imported,
|
||||||
|
found: issues.length,
|
||||||
|
column: target.name,
|
||||||
|
repository,
|
||||||
|
};
|
||||||
},
|
},
|
||||||
{ access: ACCESS_LEVELS.STAFF },
|
{ access: ACCESS_LEVELS.STAFF },
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||||
|
import { env } from '../../config/env.js';
|
||||||
|
import { createLogger } from '../../core/logger.js';
|
||||||
|
import { searchCards } from '../../database/repositories/project-repository.js';
|
||||||
|
import { searchPublished } from '../../database/repositories/wiki-repository.js';
|
||||||
|
import { org } from '../../services/gitea/gitea-admin.js';
|
||||||
|
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
|
||||||
|
import { pagePath } from '../services/wiki-seed.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One search across everything the dashboard knows (M19).
|
||||||
|
*
|
||||||
|
* Until now, finding something meant knowing which tab it lived in — which is
|
||||||
|
* fine once you have learned the panel and hopeless before. Each source is
|
||||||
|
* asked independently and a source that fails is simply left out: a forge that
|
||||||
|
* is down must not take the wiki and the boards with it.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const log = createLogger('web:search');
|
||||||
|
const guildId = () => env.discord.guildId;
|
||||||
|
|
||||||
|
/** Below this a search matches half the organization, which helps nobody. */
|
||||||
|
const MIN_TERM = 2;
|
||||||
|
const PER_GROUP = 6;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repository lists change by the hour and are asked for on every keystroke, so
|
||||||
|
* they are kept briefly. The stamp only moves on success, which turns a forge
|
||||||
|
* outage into slightly old results rather than none.
|
||||||
|
*/
|
||||||
|
const REPO_TTL_MS = 60_000;
|
||||||
|
let repoCache = { at: 0, repositories: [] };
|
||||||
|
|
||||||
|
async function repositories() {
|
||||||
|
if (!isGiteaConfigured()) return [];
|
||||||
|
if (Date.now() - repoCache.at < REPO_TTL_MS) return repoCache.repositories;
|
||||||
|
|
||||||
|
const list = await org.listRepos({ limit: 50 }).catch((error) => {
|
||||||
|
log.debug('Falling back to the cached repository list', error);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
if (list) repoCache = { at: Date.now(), repositories: list };
|
||||||
|
return repoCache.repositories;
|
||||||
|
}
|
||||||
|
|
||||||
|
const contains = (haystack, needle) =>
|
||||||
|
String(haystack ?? '')
|
||||||
|
.toLowerCase()
|
||||||
|
.includes(needle);
|
||||||
|
|
||||||
|
async function searchRepositories(needle) {
|
||||||
|
const list = await repositories();
|
||||||
|
return list
|
||||||
|
.filter(
|
||||||
|
(repository) => contains(repository.full_name, needle) || contains(repository.description, needle),
|
||||||
|
)
|
||||||
|
.slice(0, PER_GROUP)
|
||||||
|
.map((repository) => ({
|
||||||
|
kind: 'repository',
|
||||||
|
title: repository.full_name,
|
||||||
|
subtitle: repository.description || 'Dépôt de l’organisation',
|
||||||
|
href: `#/repos/${repository.full_name}`,
|
||||||
|
badge: repository.private ? 'Privé' : null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function searchIssues(needle) {
|
||||||
|
if (!isGiteaConfigured()) return [];
|
||||||
|
|
||||||
|
// `all` rather than `open`: someone searching for an issue by name usually
|
||||||
|
// wants the one they remember, closed or not.
|
||||||
|
const issues = await org.searchIssues({ q: needle, state: 'all', limit: PER_GROUP }).catch((error) => {
|
||||||
|
log.debug('The forge did not answer the issue search', error);
|
||||||
|
return [];
|
||||||
|
});
|
||||||
|
|
||||||
|
return issues.slice(0, PER_GROUP).map((issue) => ({
|
||||||
|
kind: issue.pull_request ? 'pull' : 'issue',
|
||||||
|
title: issue.title,
|
||||||
|
subtitle: `${issue.repository?.full_name ?? 'Gitea'}#${issue.number}`,
|
||||||
|
href: issue.html_url,
|
||||||
|
external: true,
|
||||||
|
badge: issue.state === 'closed' ? 'Fermée' : 'Ouverte',
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function searchBoardCards(needle) {
|
||||||
|
return searchCards(guildId(), needle, PER_GROUP).map((card) => ({
|
||||||
|
kind: 'card',
|
||||||
|
title: card.title,
|
||||||
|
subtitle: `${card.board_name} · ${card.column_name}`,
|
||||||
|
href: `#/projects/${card.board_id}`,
|
||||||
|
badge: card.column_is_done ? 'Terminée' : (card.issue_ref ?? null),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function searchWiki(needle) {
|
||||||
|
return searchPublished(needle)
|
||||||
|
.slice(0, PER_GROUP)
|
||||||
|
.map((page) => ({
|
||||||
|
kind: 'wiki',
|
||||||
|
title: page.title,
|
||||||
|
subtitle: page.summary || page.category,
|
||||||
|
href: pagePath(page.slug),
|
||||||
|
external: true,
|
||||||
|
badge: page.category,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Members come from the cache rather than a fetch: pulling the roster from
|
||||||
|
* Discord on every keystroke would be slow and rate-limited, and whoever is
|
||||||
|
* being looked for is almost always already cached.
|
||||||
|
*/
|
||||||
|
function searchMembers(client, needle) {
|
||||||
|
const guild = client?.guilds?.cache?.get(guildId());
|
||||||
|
if (!guild) return [];
|
||||||
|
|
||||||
|
return [...guild.members.cache.values()]
|
||||||
|
.filter(
|
||||||
|
(member) =>
|
||||||
|
contains(member.user.username, needle) ||
|
||||||
|
contains(member.displayName, needle) ||
|
||||||
|
member.id === needle,
|
||||||
|
)
|
||||||
|
.slice(0, PER_GROUP)
|
||||||
|
.map((member) => ({
|
||||||
|
kind: 'member',
|
||||||
|
title: member.displayName,
|
||||||
|
subtitle: `@${member.user.username}`,
|
||||||
|
href: `#/discord?member=${encodeURIComponent(member.user.username)}`,
|
||||||
|
badge: member.user.bot ? 'Bot' : null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerSearchRoutes(router) {
|
||||||
|
router.get(
|
||||||
|
'/api/search',
|
||||||
|
async ({ query, context }) => {
|
||||||
|
const term = String(query.get('q') ?? '').trim();
|
||||||
|
if (term.length < MIN_TERM) return { term, results: [], truncated: false };
|
||||||
|
|
||||||
|
const needle = term.toLowerCase();
|
||||||
|
const [repos, issues] = await Promise.all([searchRepositories(needle), searchIssues(term)]);
|
||||||
|
|
||||||
|
// Local sources first: they are exact, instant, and what the panel owns.
|
||||||
|
const results = [
|
||||||
|
...searchBoardCards(term),
|
||||||
|
...repos,
|
||||||
|
...issues,
|
||||||
|
...searchWiki(term),
|
||||||
|
...searchMembers(context.client, needle),
|
||||||
|
];
|
||||||
|
|
||||||
|
return { term, results, truncated: results.length >= PER_GROUP * 5 };
|
||||||
|
},
|
||||||
|
{ access: ACCESS_LEVELS.STAFF },
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { env } from '../../config/env.js';
|
||||||
|
import { notFound } from '../http.js';
|
||||||
|
import { statusSnapshot } from '../services/status-service.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Machine-readable twin of the public status page (M19).
|
||||||
|
*
|
||||||
|
* `/api/health` says whether the process is alive, which is what a load
|
||||||
|
* balancer asks. This says what state the service is in, which is what a person
|
||||||
|
* — or an uptime monitor with a dashboard — asks.
|
||||||
|
*/
|
||||||
|
export function registerStatusRoutes(router) {
|
||||||
|
router.get(
|
||||||
|
'/api/status',
|
||||||
|
async ({ context }) => {
|
||||||
|
if (!env.web.publicStatus) throw notFound('La page de statut est désactivée.');
|
||||||
|
return statusSnapshot(context);
|
||||||
|
},
|
||||||
|
{ public: true },
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
updatePage,
|
updatePage,
|
||||||
} from '../../database/repositories/wiki-repository.js';
|
} from '../../database/repositories/wiki-repository.js';
|
||||||
import { badRequest, forbidden, notFound } from '../http.js';
|
import { badRequest, forbidden, notFound } from '../http.js';
|
||||||
|
import { pagePath } from '../services/wiki-seed.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Public wiki, written from the dashboard (M17).
|
* Public wiki, written from the dashboard (M17).
|
||||||
@@ -26,6 +27,7 @@ const SLUG = /^[a-z0-9][a-z0-9-]{0,80}$/;
|
|||||||
/** Shown in a listing: everything but the body, which can be long. */
|
/** Shown in a listing: everything but the body, which can be long. */
|
||||||
const summarize = (page) => ({
|
const summarize = (page) => ({
|
||||||
slug: page.slug,
|
slug: page.slug,
|
||||||
|
path: pagePath(page.slug),
|
||||||
title: page.title,
|
title: page.title,
|
||||||
summary: page.summary,
|
summary: page.summary,
|
||||||
category: page.category,
|
category: page.category,
|
||||||
|
|||||||
@@ -59,6 +59,24 @@ export function sendJson(response, status, payload) {
|
|||||||
response.end(body);
|
response.end(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends a finished HTML document. Public pages carry a relaxed policy: they
|
||||||
|
* embed no script of their own, and must stay readable to whoever fetches them.
|
||||||
|
*/
|
||||||
|
export function sendHtml(response, status, html) {
|
||||||
|
const body = Buffer.from(html, 'utf8');
|
||||||
|
response.writeHead(status, {
|
||||||
|
...SECURITY_HEADERS,
|
||||||
|
'Content-Security-Policy':
|
||||||
|
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'none'; " +
|
||||||
|
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
||||||
|
'Content-Type': 'text/html; charset=utf-8',
|
||||||
|
'Content-Length': body.length,
|
||||||
|
'Cache-Control': 'no-cache',
|
||||||
|
});
|
||||||
|
response.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
export function sendEmpty(response, status, headers = {}) {
|
export function sendEmpty(response, status, headers = {}) {
|
||||||
response.writeHead(status, { ...SECURITY_HEADERS, ...headers }).end();
|
response.writeHead(status, { ...SECURITY_HEADERS, ...headers }).end();
|
||||||
}
|
}
|
||||||
|
|||||||
+69
-3
@@ -2,6 +2,7 @@ import { api } from './core/api.js';
|
|||||||
import { h, mount, qs } from './core/dom.js';
|
import { h, mount, qs } from './core/dom.js';
|
||||||
import { onStatus, resetSubscriptions, startLive } from './core/live.js';
|
import { onStatus, resetSubscriptions, startLive } from './core/live.js';
|
||||||
import { activePath, highlight } from './core/nav.js';
|
import { activePath, highlight } from './core/nav.js';
|
||||||
|
import { bindPalette, openPalette } from './core/palette.js';
|
||||||
import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js';
|
import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js';
|
||||||
|
|
||||||
/** Shell, navigation and hash routing of the dashboard (M16-T11). */
|
/** Shell, navigation and hash routing of the dashboard (M16-T11). */
|
||||||
@@ -21,6 +22,14 @@ const ROUTES = [
|
|||||||
module: './views/overview.js',
|
module: './views/overview.js',
|
||||||
level: LEVELS.STAFF,
|
level: LEVELS.STAFF,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'tasks',
|
||||||
|
icon: '✓',
|
||||||
|
label: 'Mes tâches',
|
||||||
|
group: 'Pilotage',
|
||||||
|
module: './views/tasks.js',
|
||||||
|
level: LEVELS.STAFF,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'org',
|
path: 'org',
|
||||||
icon: '⬡',
|
icon: '⬡',
|
||||||
@@ -190,10 +199,20 @@ function liveIndicator() {
|
|||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
function sidebar() {
|
/**
|
||||||
const visible = ROUTES.filter(
|
* Pages the visitor can actually reach. Shared with the palette so a search
|
||||||
(route) => state.me.accessLevel >= route.level && (!route.advanced || state.mode === 'advanced'),
|
* never offers a page that would answer with « niveau d’accès supérieur ».
|
||||||
|
*/
|
||||||
|
function visibleRoutes() {
|
||||||
|
return ROUTES.filter(
|
||||||
|
(route) => (state.me?.accessLevel ?? 0) >= route.level && (!route.advanced || state.mode === 'advanced'),
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHORTCUT = navigator.userAgent.includes('Mac') ? '⌘K' : 'Ctrl+K';
|
||||||
|
|
||||||
|
function sidebar() {
|
||||||
|
const visible = visibleRoutes();
|
||||||
|
|
||||||
const groups = [];
|
const groups = [];
|
||||||
for (const route of visible) {
|
for (const route of visible) {
|
||||||
@@ -211,6 +230,18 @@ function sidebar() {
|
|||||||
h('img', { src: 'favicon.svg', alt: '' }),
|
h('img', { src: 'favicon.svg', alt: '' }),
|
||||||
h('div', {}, h('strong', { text: 'FWS-Bot' }), h('span', { text: 'Tableau de bord' })),
|
h('div', {}, h('strong', { text: 'FWS-Bot' }), h('span', { text: 'Tableau de bord' })),
|
||||||
),
|
),
|
||||||
|
h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
class: 'nav-search',
|
||||||
|
type: 'button',
|
||||||
|
onClick: () => openPalette(visibleRoutes()),
|
||||||
|
title: `Recherche globale (${SHORTCUT})`,
|
||||||
|
},
|
||||||
|
h('span', { class: 'nav-icon', text: '⌕' }),
|
||||||
|
h('span', { text: 'Rechercher' }),
|
||||||
|
h('kbd', { text: SHORTCUT }),
|
||||||
|
),
|
||||||
h(
|
h(
|
||||||
'nav',
|
'nav',
|
||||||
{ class: 'nav' },
|
{ class: 'nav' },
|
||||||
@@ -222,6 +253,9 @@ function sidebar() {
|
|||||||
{ href: `#/${route.path}`, dataset: { route: route.path } },
|
{ href: `#/${route.path}`, dataset: { route: route.path } },
|
||||||
h('span', { class: 'nav-icon', text: route.icon }),
|
h('span', { class: 'nav-icon', text: route.icon }),
|
||||||
h('span', { text: route.label }),
|
h('span', { text: route.label }),
|
||||||
|
// A page you have to open to know whether it needs you is a page
|
||||||
|
// you stop opening; the count is what makes it a morning habit.
|
||||||
|
route.path === 'tasks' && h('span', { class: 'nav-count', hidden: true }),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
]),
|
]),
|
||||||
@@ -286,6 +320,7 @@ async function renderView(host) {
|
|||||||
const route = ROUTES.find((entry) => entry.path === (segments[0] ?? ''));
|
const route = ROUTES.find((entry) => entry.path === (segments[0] ?? ''));
|
||||||
resetSubscriptions();
|
resetSubscriptions();
|
||||||
highlightNav();
|
highlightNav();
|
||||||
|
refreshTaskCount();
|
||||||
host.scrollIntoView?.({ block: 'start' });
|
host.scrollIntoView?.({ block: 'start' });
|
||||||
|
|
||||||
if (!route) {
|
if (!route) {
|
||||||
@@ -334,9 +369,39 @@ export function render() {
|
|||||||
mount(app, shell);
|
mount(app, shell);
|
||||||
applyModeButtons(shell);
|
applyModeButtons(shell);
|
||||||
highlightNav(shell);
|
highlightNav(shell);
|
||||||
|
refreshTaskCount();
|
||||||
renderView(main);
|
renderView(main);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open cards assigned to the viewer, shown on the sidebar entry.
|
||||||
|
*
|
||||||
|
* Asked for with `issues=0`: the counter needs a number, not a round trip to
|
||||||
|
* the forge to resolve every linked issue. Throttled, because navigating is not
|
||||||
|
* a reason to ask again.
|
||||||
|
*/
|
||||||
|
const TASK_COUNT_TTL_MS = 60_000;
|
||||||
|
let taskCountAt = 0;
|
||||||
|
|
||||||
|
async function refreshTaskCount(force = false) {
|
||||||
|
if (!qs('.nav-count')) return;
|
||||||
|
if (!force && Date.now() - taskCountAt < TASK_COUNT_TTL_MS) return;
|
||||||
|
taskCountAt = Date.now();
|
||||||
|
|
||||||
|
const data = await api.get('/api/me/tasks', { issues: '0' }).catch(() => null);
|
||||||
|
// The shell may have been rebuilt while the request was in flight.
|
||||||
|
const node = qs('.nav-count');
|
||||||
|
if (!node || !data) return;
|
||||||
|
|
||||||
|
const { open, overdue } = data.counts;
|
||||||
|
node.textContent = open > 99 ? '99+' : String(open);
|
||||||
|
node.hidden = open === 0;
|
||||||
|
node.dataset.tone = overdue > 0 ? 'late' : 'normal';
|
||||||
|
node.title = overdue > 0 ? `${overdue} carte(s) en retard` : `${open} carte(s) à faire`;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('fws:tasks-changed', () => refreshTaskCount(true));
|
||||||
|
|
||||||
/** Names the interface actually being served, archive deployments being easy to get wrong. */
|
/** Names the interface actually being served, archive deployments being easy to get wrong. */
|
||||||
async function showBuild() {
|
async function showBuild() {
|
||||||
const health = await api.get('/api/health').catch(() => null);
|
const health = await api.get('/api/health').catch(() => null);
|
||||||
@@ -363,6 +428,7 @@ async function boot() {
|
|||||||
|
|
||||||
startLive();
|
startLive();
|
||||||
showBuild();
|
showBuild();
|
||||||
|
bindPalette(visibleRoutes);
|
||||||
|
|
||||||
window.addEventListener('hashchange', () => {
|
window.addEventListener('hashchange', () => {
|
||||||
const main = qs('.main');
|
const main = qs('.main');
|
||||||
|
|||||||
@@ -0,0 +1,251 @@
|
|||||||
|
import { api } from './api.js';
|
||||||
|
import { h, mount } from './dom.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command palette: one search across everything (M19).
|
||||||
|
*
|
||||||
|
* Before this, finding something meant knowing which tab it lived in. Pages are
|
||||||
|
* matched in the browser so the palette is useful the instant it opens, even
|
||||||
|
* with the forge down; everything else comes from `/api/search`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const DEBOUNCE_MS = 180;
|
||||||
|
const MIN_REMOTE = 2;
|
||||||
|
|
||||||
|
const GROUPS = [
|
||||||
|
{ kind: 'page', label: 'Pages', icon: '◈' },
|
||||||
|
{ kind: 'card', label: 'Cartes', icon: '▦' },
|
||||||
|
{ kind: 'repository', label: 'Dépôts', icon: '◫' },
|
||||||
|
{ kind: 'issue', label: 'Issues', icon: '◇' },
|
||||||
|
{ kind: 'pull', label: 'Pull requests', icon: '⑂' },
|
||||||
|
{ kind: 'wiki', label: 'Wiki', icon: '📖' },
|
||||||
|
{ kind: 'member', label: 'Membres', icon: '☺' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ICONS = Object.fromEntries(GROUPS.map((group) => [group.kind, group.icon]));
|
||||||
|
const RANK = Object.fromEntries(GROUPS.map((group, index) => [group.kind, index]));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sorts the results into their groups, keeping the order inside each one.
|
||||||
|
*
|
||||||
|
* The forge returns issues and pull requests interleaved, which would print a
|
||||||
|
* heading above almost every line.
|
||||||
|
*/
|
||||||
|
export const grouped = (results) =>
|
||||||
|
results
|
||||||
|
.map((result, index) => ({ result, index }))
|
||||||
|
.sort((a, b) => (RANK[a.result.kind] ?? 99) - (RANK[b.result.kind] ?? 99) || a.index - b.index)
|
||||||
|
.map((entry) => entry.result);
|
||||||
|
|
||||||
|
let open = false;
|
||||||
|
|
||||||
|
const matches = (text, needle) =>
|
||||||
|
String(text ?? '')
|
||||||
|
.toLowerCase()
|
||||||
|
.includes(needle);
|
||||||
|
|
||||||
|
/** Pages the visitor may actually reach, matched locally on label and group. */
|
||||||
|
export function localPages(pages, needle) {
|
||||||
|
return pages
|
||||||
|
.filter((page) => needle === '' || matches(page.label, needle) || matches(page.group, needle))
|
||||||
|
.slice(0, 8)
|
||||||
|
.map((page) => ({
|
||||||
|
kind: 'page',
|
||||||
|
title: page.label,
|
||||||
|
subtitle: page.group,
|
||||||
|
href: `#/${page.path}`,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function go(result) {
|
||||||
|
if (result.external) window.open(result.href, '_blank', 'noreferrer');
|
||||||
|
else window.location.hash = result.href.replace(/^#/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens the palette. `pages` is the navigation the visitor can see, so a page
|
||||||
|
* they have no access to never shows up as a result.
|
||||||
|
*/
|
||||||
|
export function openPalette(pages = []) {
|
||||||
|
if (open) return;
|
||||||
|
open = true;
|
||||||
|
|
||||||
|
const restoreFocus = document.activeElement;
|
||||||
|
const overlay = h('div', { class: 'overlay palette-overlay' });
|
||||||
|
const list = h('div', { class: 'palette-list', role: 'listbox', id: 'palette-results' });
|
||||||
|
const hint = h('div', { class: 'palette-hint' });
|
||||||
|
|
||||||
|
const field = h('input', {
|
||||||
|
class: 'palette-input',
|
||||||
|
type: 'search',
|
||||||
|
placeholder: 'Rechercher une page, un dépôt, une carte, une issue…',
|
||||||
|
'aria-label': 'Recherche globale',
|
||||||
|
'aria-controls': 'palette-results',
|
||||||
|
autocomplete: 'off',
|
||||||
|
spellcheck: 'false',
|
||||||
|
});
|
||||||
|
|
||||||
|
let results = [];
|
||||||
|
let cursor = 0;
|
||||||
|
let timer = null;
|
||||||
|
/** Answers can arrive out of order; only the latest query may draw. */
|
||||||
|
let sequence = 0;
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
open = false;
|
||||||
|
clearTimeout(timer);
|
||||||
|
document.removeEventListener('keydown', onKey, true);
|
||||||
|
overlay.remove();
|
||||||
|
restoreFocus?.focus?.();
|
||||||
|
};
|
||||||
|
|
||||||
|
const draw = () => {
|
||||||
|
if (results.length === 0) {
|
||||||
|
mount(list, h('p', { class: 'palette-empty', text: 'Aucun résultat.' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cursor = Math.max(0, Math.min(cursor, results.length - 1));
|
||||||
|
|
||||||
|
const nodes = [];
|
||||||
|
let group = null;
|
||||||
|
|
||||||
|
for (const [index, result] of results.entries()) {
|
||||||
|
if (result.kind !== group) {
|
||||||
|
group = result.kind;
|
||||||
|
const label = GROUPS.find((entry) => entry.kind === group)?.label ?? group;
|
||||||
|
nodes.push(h('div', { class: 'palette-group', text: label }));
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes.push(
|
||||||
|
h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
class: index === cursor ? 'palette-item active' : 'palette-item',
|
||||||
|
type: 'button',
|
||||||
|
role: 'option',
|
||||||
|
'aria-selected': index === cursor ? 'true' : 'false',
|
||||||
|
// `mousedown` rather than `click`: the input keeps focus, so the
|
||||||
|
// palette does not close under the pointer before the choice lands.
|
||||||
|
onMousedown: (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
close();
|
||||||
|
go(result);
|
||||||
|
},
|
||||||
|
// Guarded: a redraw replaces the node under the pointer, which
|
||||||
|
// fires `mouseenter` again — without this the two loop forever.
|
||||||
|
onMouseenter: () => {
|
||||||
|
if (cursor === index) return;
|
||||||
|
cursor = index;
|
||||||
|
draw();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
h('span', { class: 'palette-icon', text: ICONS[result.kind] ?? '·' }),
|
||||||
|
h(
|
||||||
|
'span',
|
||||||
|
{ class: 'palette-text' },
|
||||||
|
h('strong', { text: result.title }),
|
||||||
|
result.subtitle && h('span', { class: 'muted', text: result.subtitle }),
|
||||||
|
),
|
||||||
|
result.badge && h('span', { class: 'palette-badge', text: result.badge }),
|
||||||
|
result.external && h('span', { class: 'palette-external', text: '↗', title: 'Ouvre un onglet' }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
mount(list, nodes);
|
||||||
|
list.querySelector('.palette-item.active')?.scrollIntoView({ block: 'nearest' });
|
||||||
|
};
|
||||||
|
|
||||||
|
const search = async (term) => {
|
||||||
|
const needle = term.trim().toLowerCase();
|
||||||
|
const local = localPages(pages, needle);
|
||||||
|
|
||||||
|
results = grouped(local);
|
||||||
|
cursor = 0;
|
||||||
|
hint.textContent = needle.length < MIN_REMOTE ? 'Tape au moins 2 caractères pour chercher partout.' : '';
|
||||||
|
draw();
|
||||||
|
if (needle.length < MIN_REMOTE) return;
|
||||||
|
|
||||||
|
const mine = ++sequence;
|
||||||
|
const remote = await api.get('/api/search', { q: term.trim() }).catch(() => null);
|
||||||
|
if (mine !== sequence || !open) return;
|
||||||
|
|
||||||
|
if (!remote) {
|
||||||
|
hint.textContent = 'La recherche étendue n’a pas répondu ; seules les pages sont listées.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
hint.textContent = '';
|
||||||
|
// Pages stay first: they are the fastest thing the palette can do.
|
||||||
|
results = grouped([...local, ...remote.results]);
|
||||||
|
draw();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKey = (event) => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.preventDefault();
|
||||||
|
close();
|
||||||
|
} else if (event.key === 'ArrowDown' || (event.key === 'Tab' && !event.shiftKey)) {
|
||||||
|
event.preventDefault();
|
||||||
|
cursor = results.length === 0 ? 0 : (cursor + 1) % results.length;
|
||||||
|
draw();
|
||||||
|
} else if (event.key === 'ArrowUp' || (event.key === 'Tab' && event.shiftKey)) {
|
||||||
|
event.preventDefault();
|
||||||
|
cursor = results.length === 0 ? 0 : (cursor - 1 + results.length) % results.length;
|
||||||
|
draw();
|
||||||
|
} else if (event.key === 'Enter' && results[cursor]) {
|
||||||
|
event.preventDefault();
|
||||||
|
const chosen = results[cursor];
|
||||||
|
close();
|
||||||
|
go(chosen);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
field.addEventListener('input', () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => search(field.value), DEBOUNCE_MS);
|
||||||
|
});
|
||||||
|
overlay.addEventListener('click', (event) => {
|
||||||
|
if (event.target === overlay) close();
|
||||||
|
});
|
||||||
|
document.addEventListener('keydown', onKey, true);
|
||||||
|
|
||||||
|
overlay.append(
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'palette', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Recherche globale' },
|
||||||
|
h('div', { class: 'palette-head' }, h('span', { class: 'palette-prompt', text: '⌕' }), field),
|
||||||
|
list,
|
||||||
|
h(
|
||||||
|
'footer',
|
||||||
|
{ class: 'palette-foot' },
|
||||||
|
hint,
|
||||||
|
h('span', { class: 'muted', text: '↑ ↓ pour naviguer · ↵ pour ouvrir · Échap pour fermer' }),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
document.body.append(overlay);
|
||||||
|
field.focus();
|
||||||
|
search('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Binds ⌘K / Ctrl+K globally.
|
||||||
|
*
|
||||||
|
* `/` opens it too, but only when nothing is being typed into: stealing a
|
||||||
|
* slash from someone writing a release note would be unforgivable.
|
||||||
|
*/
|
||||||
|
export function bindPalette(pages) {
|
||||||
|
const typing = () =>
|
||||||
|
['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName) ||
|
||||||
|
document.activeElement?.isContentEditable;
|
||||||
|
|
||||||
|
document.addEventListener('keydown', (event) => {
|
||||||
|
const combo = (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k';
|
||||||
|
if (!combo && !(event.key === '/' && !typing())) return;
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
openPalette(pages());
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1079,6 +1079,425 @@ body[data-mode='simple'] .advanced-only {
|
|||||||
border-bottom-color: var(--blue);
|
border-bottom-color: var(--blue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- My tasks ------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.task-list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.task {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0.55rem 0.2rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.task:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
.task-done .task-title {
|
||||||
|
text-decoration: line-through;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.task-check {
|
||||||
|
flex: none;
|
||||||
|
width: 1.35rem;
|
||||||
|
height: 1.35rem;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 2px solid var(--border);
|
||||||
|
background: none;
|
||||||
|
color: var(--green);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.task-check:hover:not(:disabled) {
|
||||||
|
border-color: var(--green);
|
||||||
|
}
|
||||||
|
.task-check:disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
.task-body {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.task-title {
|
||||||
|
display: block;
|
||||||
|
color: var(--text);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.94rem;
|
||||||
|
}
|
||||||
|
.task-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
margin-top: 0.15rem;
|
||||||
|
}
|
||||||
|
.task-issue {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
color: var(--gitea);
|
||||||
|
}
|
||||||
|
.task-due {
|
||||||
|
flex: none;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.task-due-late {
|
||||||
|
color: var(--red);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.task-archive {
|
||||||
|
padding: 0.8rem 1.1rem;
|
||||||
|
}
|
||||||
|
.task-archive summary {
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.92rem;
|
||||||
|
}
|
||||||
|
.task-picker {
|
||||||
|
display: inline-flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-count {
|
||||||
|
margin-left: auto;
|
||||||
|
min-width: 1.4rem;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 0.05rem 0.35rem;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.nav-count[data-tone='late'] {
|
||||||
|
background: color-mix(in srgb, var(--red) 24%, transparent);
|
||||||
|
color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Anchored near the top rather than centred: the list grows downwards, and a
|
||||||
|
dialog that re-centres itself on every keystroke is unusable. */
|
||||||
|
/* --- Command palette ------------------------------------------------------ */
|
||||||
|
|
||||||
|
.nav-search {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
width: 100%;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
text-align: left;
|
||||||
|
color: var(--text-muted);
|
||||||
|
background: var(--bg-sunken);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
padding: 0.45rem 0.65rem;
|
||||||
|
margin-bottom: 0.4rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.nav-search:hover {
|
||||||
|
border-color: var(--blue);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.nav-search kbd {
|
||||||
|
margin-left: auto;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.7rem;
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 0.05rem 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette-overlay {
|
||||||
|
align-items: start;
|
||||||
|
padding-top: min(14vh, 8rem);
|
||||||
|
}
|
||||||
|
.palette {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
width: min(640px, 100%);
|
||||||
|
max-height: 70vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.palette-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
padding: 0.7rem 0.9rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.palette-prompt {
|
||||||
|
color: var(--blue);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
.palette-input {
|
||||||
|
flex: 1;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 1rem;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
color: var(--text);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.palette-input::-webkit-search-cancel-button {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.palette-list {
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 0.35rem;
|
||||||
|
}
|
||||||
|
.palette-group {
|
||||||
|
padding: 0.55rem 0.6rem 0.25rem;
|
||||||
|
font-size: 0.68rem;
|
||||||
|
letter-spacing: 0.09em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.palette-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.7rem;
|
||||||
|
width: 100%;
|
||||||
|
font: inherit;
|
||||||
|
text-align: left;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
color: var(--text);
|
||||||
|
padding: 0.45rem 0.6rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.palette-item.active {
|
||||||
|
background: color-mix(in srgb, var(--blue) 16%, transparent);
|
||||||
|
}
|
||||||
|
.palette-icon {
|
||||||
|
width: 1.3rem;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.palette-text {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.palette-text strong {
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.92rem;
|
||||||
|
}
|
||||||
|
.palette-text span,
|
||||||
|
.palette-text strong {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.palette-badge {
|
||||||
|
margin-left: auto;
|
||||||
|
flex: none;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
background: var(--bg-sunken);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 0.05rem 0.45rem;
|
||||||
|
}
|
||||||
|
.palette-external {
|
||||||
|
flex: none;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.palette-empty {
|
||||||
|
padding: 1.2rem 0.6rem;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.palette-foot {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0.5rem 0.9rem;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
font-size: 0.76rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.palette-hint {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- Public status page --------------------------------------------------- */
|
||||||
|
|
||||||
|
.status-body {
|
||||||
|
background: var(--bg);
|
||||||
|
}
|
||||||
|
.status-page {
|
||||||
|
max-width: 820px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem 1rem 3rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
.status-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.status-brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.status-brand:hover {
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.status-brand strong {
|
||||||
|
display: block;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
.status-brand span {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.status-muted {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.84rem;
|
||||||
|
}
|
||||||
|
.status-banner {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-left: 4px solid var(--text-muted);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
padding: 1.2rem 1.4rem;
|
||||||
|
}
|
||||||
|
.status-banner h1 {
|
||||||
|
font-size: 1.35rem;
|
||||||
|
margin-bottom: 0.3rem;
|
||||||
|
}
|
||||||
|
.status-banner p {
|
||||||
|
color: var(--text-muted);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.status-banner-ok {
|
||||||
|
border-left-color: var(--green);
|
||||||
|
}
|
||||||
|
.status-banner-busy {
|
||||||
|
border-left-color: var(--amber);
|
||||||
|
}
|
||||||
|
.status-banner-down {
|
||||||
|
border-left-color: var(--red);
|
||||||
|
}
|
||||||
|
.status-section h2 {
|
||||||
|
margin-bottom: 0.7rem;
|
||||||
|
}
|
||||||
|
.status-tiles {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||||
|
gap: 0.8rem;
|
||||||
|
}
|
||||||
|
.status-tile {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
padding: 0.8rem 0.9rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.1rem;
|
||||||
|
}
|
||||||
|
.status-tile-label {
|
||||||
|
font-size: 0.74rem;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.status-tile-value {
|
||||||
|
font-size: 1.15rem;
|
||||||
|
}
|
||||||
|
.status-tile-hint {
|
||||||
|
font-size: 0.76rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.status-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
.status-table th {
|
||||||
|
text-align: left;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
letter-spacing: 0.07em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--text-muted);
|
||||||
|
padding: 0.4rem 0.6rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.status-table td {
|
||||||
|
padding: 0.55rem 0.6rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.status-pill {
|
||||||
|
display: inline-block;
|
||||||
|
font-size: 0.74rem;
|
||||||
|
font-weight: 600;
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 0.1rem 0.55rem;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.status-pill-ok {
|
||||||
|
background: color-mix(in srgb, var(--green) 20%, transparent);
|
||||||
|
color: var(--green);
|
||||||
|
}
|
||||||
|
.status-pill-busy {
|
||||||
|
background: color-mix(in srgb, var(--amber) 22%, transparent);
|
||||||
|
color: var(--amber);
|
||||||
|
}
|
||||||
|
.status-pill-down {
|
||||||
|
background: color-mix(in srgb, var(--red) 20%, transparent);
|
||||||
|
color: var(--red);
|
||||||
|
}
|
||||||
|
.status-releases {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.status-releases li {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding: 0.5rem 0.6rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.status-releases li:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
.status-empty {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
padding: 0.6rem;
|
||||||
|
}
|
||||||
|
.status-generated {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.status-footer {
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
padding-top: 1rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 900px) {
|
@media (max-width: 900px) {
|
||||||
.shell {
|
.shell {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
@@ -1099,4 +1518,15 @@ body[data-mode='simple'] .advanced-only {
|
|||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.palette-overlay {
|
||||||
|
padding-top: 6vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-page {
|
||||||
|
padding: 1.2rem 1rem 2rem;
|
||||||
|
}
|
||||||
|
.status-table {
|
||||||
|
font-size: 0.82rem;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -33,11 +33,13 @@ const DURATIONS = [
|
|||||||
{ value: String(7 * 24 * 60 * 60_000), label: '7 jours' },
|
{ value: String(7 * 24 * 60 * 60_000), label: '7 jours' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Mirrors MODERATION_ACTIONS in `src/config/constants.js`, emoji included: the
|
||||||
|
// panel must not be the one place where a mute reads like a kick.
|
||||||
const MODERATION_ACTIONS = [
|
const MODERATION_ACTIONS = [
|
||||||
{ value: 'warn', label: 'Avertissement' },
|
{ value: 'warn', label: '⚠️ Avertissement' },
|
||||||
{ value: 'mute', label: 'Exclusion temporaire' },
|
{ value: 'mute', label: '🔇 Mise en sourdine' },
|
||||||
{ value: 'kick', label: 'Expulsion' },
|
{ value: 'kick', label: '👢 Expulsion' },
|
||||||
{ value: 'ban', label: 'Bannissement' },
|
{ value: 'ban', label: '🔨 Bannissement' },
|
||||||
];
|
];
|
||||||
|
|
||||||
async function moderate(member, reload) {
|
async function moderate(member, reload) {
|
||||||
@@ -164,9 +166,15 @@ async function announce(channels) {
|
|||||||
toast(`Annonce publiée (${result.messageId}).`);
|
toast(`Annonce publiée (${result.messageId}).`);
|
||||||
}
|
}
|
||||||
|
|
||||||
function membersCard(guild, level) {
|
function membersCard(guild, level, initialSearch = '') {
|
||||||
const host = h('div', { class: 'stack' });
|
const host = h('div', { class: 'stack' });
|
||||||
const search = input({ type: 'search', placeholder: 'Nom, pseudo ou identifiant…' });
|
// Pre-filled when the command palette sent us here for one member, so the
|
||||||
|
// link lands on that person rather than on the top of the roster.
|
||||||
|
const search = input({
|
||||||
|
type: 'search',
|
||||||
|
placeholder: 'Nom, pseudo ou identifiant…',
|
||||||
|
value: initialSearch,
|
||||||
|
});
|
||||||
|
|
||||||
const load = () =>
|
const load = () =>
|
||||||
renderAsync(
|
renderAsync(
|
||||||
@@ -305,6 +313,9 @@ function notificationsCard(guild, level) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** `#/discord?member=nom` — where the command palette points a member result. */
|
||||||
|
const memberQuery = () => new URLSearchParams(window.location.hash.split('?')[1] ?? '').get('member') ?? '';
|
||||||
|
|
||||||
export async function render(host, { state }) {
|
export async function render(host, { state }) {
|
||||||
const level = state.me.accessLevel;
|
const level = state.me.accessLevel;
|
||||||
mount(host, spinner());
|
mount(host, spinner());
|
||||||
@@ -356,7 +367,7 @@ export async function render(host, { state }) {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
||||||
membersCard(guild, level),
|
membersCard(guild, level, memberQuery()),
|
||||||
|
|
||||||
card(
|
card(
|
||||||
'Rôles',
|
'Rôles',
|
||||||
|
|||||||
@@ -345,18 +345,7 @@ async function renderBoard(host, state, id) {
|
|||||||
h(
|
h(
|
||||||
'div',
|
'div',
|
||||||
{ class: 'row' },
|
{ class: 'row' },
|
||||||
board.repository &&
|
button('Importer depuis Gitea', () => importIssues(board, reload), { tone: 'ghost' }),
|
||||||
button(
|
|
||||||
'Importer les issues',
|
|
||||||
async () => {
|
|
||||||
const result = await api.post(`/api/projects/${board.id}/import`, {});
|
|
||||||
toast(
|
|
||||||
`${result.imported} carte(s) créée(s) dans « ${result.column} », ${result.skipped} déjà présente(s).`,
|
|
||||||
);
|
|
||||||
reload();
|
|
||||||
},
|
|
||||||
{ tone: 'ghost' },
|
|
||||||
),
|
|
||||||
button('Colonne', () => addColumn(board, reload), { tone: 'ghost' }),
|
button('Colonne', () => addColumn(board, reload), { tone: 'ghost' }),
|
||||||
level >= LEVELS.OWNER &&
|
level >= LEVELS.OWNER &&
|
||||||
button(
|
button(
|
||||||
@@ -389,6 +378,73 @@ async function renderBoard(host, state, id) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pulls Gitea issues onto the board.
|
||||||
|
*
|
||||||
|
* Offered on every board, not only on a repository one: the organization board
|
||||||
|
* is exactly where issues from several repositories belong together.
|
||||||
|
*/
|
||||||
|
async function importIssues(board, reload) {
|
||||||
|
const { repositories } = await api.get('/api/repositories').catch(() => ({ repositories: [] }));
|
||||||
|
|
||||||
|
const repository =
|
||||||
|
repositories.length > 0
|
||||||
|
? select(
|
||||||
|
repositories.map((entry) => ({ value: entry.fullName, label: entry.fullName })),
|
||||||
|
{ value: board.repository ?? repositories[0]?.fullName },
|
||||||
|
)
|
||||||
|
: input({ value: board.repository ?? '', placeholder: 'FWS/FWS-Arch' });
|
||||||
|
|
||||||
|
const column = select(
|
||||||
|
board.columns.map((entry) => ({ value: String(entry.id), label: entry.name })),
|
||||||
|
{ value: String((board.columns.find((entry) => !entry.isDone) ?? board.columns[0])?.id) },
|
||||||
|
);
|
||||||
|
let closedToo = false;
|
||||||
|
|
||||||
|
const confirmed = await modal(
|
||||||
|
'Importer depuis Gitea',
|
||||||
|
() => ({
|
||||||
|
node: h(
|
||||||
|
'div',
|
||||||
|
{ class: 'stack' },
|
||||||
|
repositories.length === 0 &&
|
||||||
|
notice(
|
||||||
|
'La liste des dépôts est indisponible — saisis le dépôt à la main, au format `organisation/depot`.',
|
||||||
|
'warning',
|
||||||
|
),
|
||||||
|
field('Dépôt', repository),
|
||||||
|
field('Colonne d’arrivée', column),
|
||||||
|
toggle(false, (checked) => (closedToo = checked), 'Inclure aussi les issues fermées'),
|
||||||
|
h('p', {
|
||||||
|
class: 'muted',
|
||||||
|
text: 'Une issue déjà présente sur le tableau est ignorée : tu peux relancer l’import sans créer de doublon.',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
submit: () => repository.value.trim() !== '',
|
||||||
|
}),
|
||||||
|
{ confirmLabel: 'Importer', tone: 'primary' },
|
||||||
|
);
|
||||||
|
if (!confirmed) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await api.post(`/api/projects/${board.id}/import`, {
|
||||||
|
repository: repository.value.trim(),
|
||||||
|
columnId: Number(column.value),
|
||||||
|
state: closedToo ? 'all' : 'open',
|
||||||
|
});
|
||||||
|
|
||||||
|
toast(
|
||||||
|
result.imported === 0
|
||||||
|
? `Rien à importer : les ${result.found} issue(s) de ${result.repository} sont déjà sur le tableau.`
|
||||||
|
: `${result.imported} carte(s) créée(s) dans « ${result.column} », ${result.skipped} déjà présente(s).`,
|
||||||
|
result.imported === 0 ? 'info' : 'success',
|
||||||
|
);
|
||||||
|
reload();
|
||||||
|
} catch (error) {
|
||||||
|
toast(error.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function addColumn(board, reload) {
|
async function addColumn(board, reload) {
|
||||||
const name = input({ placeholder: 'Nom de la colonne' });
|
const name = input({ placeholder: 'Nom de la colonne' });
|
||||||
const wipLimit = input({ type: 'number', value: 0, min: 0 });
|
const wipLimit = input({ type: 'number', value: 0, min: 0 });
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
stat,
|
stat,
|
||||||
table,
|
table,
|
||||||
toast,
|
toast,
|
||||||
|
textarea,
|
||||||
toggle,
|
toggle,
|
||||||
} from '../core/ui.js';
|
} from '../core/ui.js';
|
||||||
|
|
||||||
@@ -55,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',
|
||||||
@@ -110,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;
|
||||||
|
|||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import { api } from '../core/api.js';
|
||||||
|
import { formatRelative, h, mount } from '../core/dom.js';
|
||||||
|
import { autoRefresh } from '../core/live.js';
|
||||||
|
import { badge, card, notice, renderAsync, select, stat, toast } from '../core/ui.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* « Mes tâches » — every card one member carries, across every board (M19).
|
||||||
|
*
|
||||||
|
* A board answers « where does the work stand ». Nobody opens a dashboard to
|
||||||
|
* ask that first: they ask what is on them today, and once the work is spread
|
||||||
|
* over several boards no single board can say.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const today = () => new Date().toISOString().slice(0, 10);
|
||||||
|
const day = (value) => (value ? String(value).slice(0, 10) : null);
|
||||||
|
|
||||||
|
const plus = (days) => {
|
||||||
|
const date = new Date();
|
||||||
|
date.setDate(date.getDate() + days);
|
||||||
|
return date.toISOString().slice(0, 10);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Buckets, in the order someone wants to be told about them: what is late,
|
||||||
|
* what is due, then everything else. A card with no date is not urgent but is
|
||||||
|
* not invisible either — it sits at the bottom rather than nowhere.
|
||||||
|
*/
|
||||||
|
function bucketOf(task) {
|
||||||
|
if (task.isDone) return 'done';
|
||||||
|
|
||||||
|
const due = day(task.dueAt);
|
||||||
|
if (!due) return 'undated';
|
||||||
|
if (due < today()) return 'overdue';
|
||||||
|
if (due === today()) return 'today';
|
||||||
|
return due <= plus(7) ? 'week' : 'later';
|
||||||
|
}
|
||||||
|
|
||||||
|
const BUCKETS = [
|
||||||
|
{ key: 'overdue', title: 'En retard' },
|
||||||
|
{ key: 'today', title: 'Pour aujourd’hui' },
|
||||||
|
{ key: 'week', title: 'Cette semaine' },
|
||||||
|
{ key: 'later', title: 'Plus tard' },
|
||||||
|
{ key: 'undated', title: 'Sans échéance' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Member names, asked once: the picker must not cost a roster fetch per render. */
|
||||||
|
let memberNames = null;
|
||||||
|
|
||||||
|
async function names() {
|
||||||
|
if (memberNames) return memberNames;
|
||||||
|
const data = await api.get('/api/discord/members', { limit: 200 }).catch(() => null);
|
||||||
|
|
||||||
|
memberNames = new Map((data?.members ?? []).map((member) => [member.id, member.displayName]));
|
||||||
|
return memberNames;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function finish(task, reload) {
|
||||||
|
if (!task.doneColumnId) {
|
||||||
|
toast('Ce tableau n’a pas de colonne « terminé ».', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await api.post(`/api/projects/${task.boardId}/cards/${task.id}/move`, {
|
||||||
|
columnId: task.doneColumnId,
|
||||||
|
position: 0,
|
||||||
|
});
|
||||||
|
toast(`« ${task.title} » est terminée.`);
|
||||||
|
// The shell owns the sidebar counter; it has no reason to know this view.
|
||||||
|
document.dispatchEvent(new CustomEvent('fws:tasks-changed'));
|
||||||
|
reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
function taskRow(task, issues, reload) {
|
||||||
|
const issue = task.issueRef ? issues[task.issueRef] : null;
|
||||||
|
const due = day(task.dueAt);
|
||||||
|
const late = !task.isDone && due && due < today();
|
||||||
|
|
||||||
|
return h(
|
||||||
|
'li',
|
||||||
|
{ class: task.isDone ? 'task task-done' : 'task', dataset: { bucket: bucketOf(task) } },
|
||||||
|
h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
class: 'task-check',
|
||||||
|
type: 'button',
|
||||||
|
title: task.isDone ? 'Déjà terminée' : 'Marquer comme terminée',
|
||||||
|
disabled: task.isDone || !task.doneColumnId,
|
||||||
|
onClick: () => finish(task, reload),
|
||||||
|
},
|
||||||
|
h('span', { text: task.isDone ? '✓' : '' }),
|
||||||
|
),
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'task-body' },
|
||||||
|
h(
|
||||||
|
'a',
|
||||||
|
{ class: 'task-title', href: `#/projects/${task.boardId}`, title: 'Ouvrir le tableau' },
|
||||||
|
task.title,
|
||||||
|
),
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'task-meta' },
|
||||||
|
h('span', { class: 'muted', text: task.boardName }),
|
||||||
|
badge(task.columnName, task.isDone ? 'success' : 'neutral'),
|
||||||
|
task.labels.map((label) => badge(label, 'info')),
|
||||||
|
issue &&
|
||||||
|
h(
|
||||||
|
'a',
|
||||||
|
{ href: issue.htmlUrl, target: '_blank', rel: 'noreferrer', class: 'task-issue' },
|
||||||
|
`${task.issueRef} · ${issue.state === 'closed' ? 'fermée' : 'ouverte'}`,
|
||||||
|
),
|
||||||
|
!issue && task.issueRef && h('span', { class: 'muted', text: task.issueRef }),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
due &&
|
||||||
|
h(
|
||||||
|
'span',
|
||||||
|
{ class: late ? 'task-due task-due-late' : 'task-due', title: due },
|
||||||
|
formatRelative(`${due}T12:00:00Z`),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns its node right away and fills it once the names arrive: waiting on
|
||||||
|
* Discord would hold up the tasks, which are the point of the page.
|
||||||
|
*/
|
||||||
|
function picker(data, reload) {
|
||||||
|
if (data.assignees.length < 2) return null;
|
||||||
|
|
||||||
|
const host = h('span', { class: 'task-picker' });
|
||||||
|
const build = (resolved) =>
|
||||||
|
mount(
|
||||||
|
host,
|
||||||
|
select(
|
||||||
|
[
|
||||||
|
{ value: '', label: 'Moi' },
|
||||||
|
...data.assignees.map((entry) => ({
|
||||||
|
value: entry.assigneeId,
|
||||||
|
label: `${resolved.get(entry.assigneeId) ?? entry.assigneeId} (${entry.open})`,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
{
|
||||||
|
value: data.self ? '' : data.assigneeId,
|
||||||
|
'aria-label': 'Voir les tâches de',
|
||||||
|
onChange: (event) => reload(event.target.value),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (memberNames) build(memberNames);
|
||||||
|
else names().then(build);
|
||||||
|
return host;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function render(host) {
|
||||||
|
let assignee = '';
|
||||||
|
|
||||||
|
const load = () => api.get('/api/me/tasks', { assignee });
|
||||||
|
|
||||||
|
const reload = (next) => {
|
||||||
|
if (next !== undefined) assignee = next;
|
||||||
|
return draw();
|
||||||
|
};
|
||||||
|
|
||||||
|
const draw = () =>
|
||||||
|
renderAsync(host, load, (data) => {
|
||||||
|
const grouped = new Map(BUCKETS.map((bucket) => [bucket.key, []]));
|
||||||
|
const done = [];
|
||||||
|
|
||||||
|
for (const task of data.cards) {
|
||||||
|
const bucket = bucketOf(task);
|
||||||
|
if (bucket === 'done') done.push(task);
|
||||||
|
else grouped.get(bucket).push(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
const owner = data.self ? 'toi' : (memberNames?.get(data.assigneeId) ?? `le membre ${data.assigneeId}`);
|
||||||
|
|
||||||
|
return h(
|
||||||
|
'div',
|
||||||
|
{ class: 'stack' },
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'page-head' },
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{},
|
||||||
|
h('h1', { text: data.self ? 'Mes tâches' : 'Tâches assignées' }),
|
||||||
|
h('p', {
|
||||||
|
class: 'muted',
|
||||||
|
text: `Toutes les cartes assignées à ${owner}, tous tableaux confondus, la plus urgente en premier.`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
h('div', { class: 'row' }, picker(data, reload)),
|
||||||
|
),
|
||||||
|
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'grid' },
|
||||||
|
stat('À faire', data.counts.open, { tone: data.counts.open > 0 ? 'primary' : 'neutral' }),
|
||||||
|
stat('En retard', data.counts.overdue, {
|
||||||
|
tone: data.counts.overdue > 0 ? 'danger' : 'neutral',
|
||||||
|
}),
|
||||||
|
stat('Pour aujourd’hui', data.counts.dueToday, {
|
||||||
|
tone: data.counts.dueToday > 0 ? 'warning' : 'neutral',
|
||||||
|
}),
|
||||||
|
stat('Terminées', data.counts.done),
|
||||||
|
),
|
||||||
|
|
||||||
|
data.cards.length === 0 &&
|
||||||
|
notice(
|
||||||
|
data.self
|
||||||
|
? 'Rien ne t’est assigné. Ouvre un tableau et mets ton nom sur une carte pour la voir apparaître ici.'
|
||||||
|
: 'Aucune carte n’est assignée à ce membre.',
|
||||||
|
'info',
|
||||||
|
),
|
||||||
|
|
||||||
|
BUCKETS.map((bucket) => {
|
||||||
|
const tasks = grouped.get(bucket.key);
|
||||||
|
if (tasks.length === 0) return null;
|
||||||
|
|
||||||
|
return card(
|
||||||
|
bucket.title,
|
||||||
|
{ subtitle: `${tasks.length} carte(s)` },
|
||||||
|
h(
|
||||||
|
'ul',
|
||||||
|
{ class: 'task-list' },
|
||||||
|
tasks.map((task) => taskRow(task, data.issues, () => reload())),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
|
||||||
|
done.length > 0 &&
|
||||||
|
h(
|
||||||
|
'details',
|
||||||
|
{ class: 'card task-archive' },
|
||||||
|
h('summary', { text: `Terminées (${done.length})` }),
|
||||||
|
h(
|
||||||
|
'ul',
|
||||||
|
{ class: 'task-list' },
|
||||||
|
done.map((task) => taskRow(task, data.issues, () => reload())),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
autoRefresh(() => draw(), { topics: ['projects', 'tick'] });
|
||||||
|
return draw();
|
||||||
|
}
|
||||||
@@ -167,7 +167,8 @@ export function render(host, { state }) {
|
|||||||
'div',
|
'div',
|
||||||
{},
|
{},
|
||||||
h('strong', { text: page.title }),
|
h('strong', { text: page.title }),
|
||||||
h('div', { class: 'muted', text: page.summary || `/wiki/${page.slug}` }),
|
h('div', { class: 'muted', text: page.summary || page.path }),
|
||||||
|
h('div', { class: 'muted', style: { fontFamily: 'var(--mono)' }, text: page.path }),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{ label: 'Catégorie', render: (page) => badge(page.category, 'info') },
|
{ label: 'Catégorie', render: (page) => badge(page.category, 'info') },
|
||||||
@@ -196,7 +197,7 @@ export function render(host, { state }) {
|
|||||||
page.published &&
|
page.published &&
|
||||||
h('a', {
|
h('a', {
|
||||||
class: 'btn btn-ghost btn-sm',
|
class: 'btn btn-ghost btn-sm',
|
||||||
href: `/wiki/${page.slug}`,
|
href: page.path,
|
||||||
target: '_blank',
|
target: '_blank',
|
||||||
rel: 'noreferrer',
|
rel: 'noreferrer',
|
||||||
text: 'Voir',
|
text: 'Voir',
|
||||||
|
|||||||
@@ -144,6 +144,37 @@
|
|||||||
margin-bottom: 1.2rem;
|
margin-bottom: 1.2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.wiki-search {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wiki-index {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0 0 1.4rem;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.wiki-index li {
|
||||||
|
padding: 0.35rem 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.wiki-index li:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wiki-footer {
|
||||||
|
margin-top: 3rem;
|
||||||
|
padding-top: 1rem;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.wiki-footer a {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.wiki-footer a:hover {
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
.wiki-toc {
|
.wiki-toc {
|
||||||
position: sticky;
|
position: sticky;
|
||||||
top: 2rem;
|
top: 2rem;
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="fr" data-theme="dark">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<meta name="color-scheme" content="dark light" />
|
|
||||||
<meta name="description" content="Documentation publique de l'organisation open source FWS." />
|
|
||||||
<title>Documentation FWS</title>
|
|
||||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
|
||||||
<link rel="stylesheet" href="/styles.css" />
|
|
||||||
<link rel="stylesheet" href="/wiki.css" />
|
|
||||||
</head>
|
|
||||||
<body class="wiki-body">
|
|
||||||
<div id="wiki">
|
|
||||||
<noscript>Cette documentation nécessite JavaScript.</noscript>
|
|
||||||
</div>
|
|
||||||
<script type="module" src="/wiki.js"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,183 +0,0 @@
|
|||||||
import { h, mount, qs } from './core/dom.js';
|
|
||||||
import { render as renderMarkdown } from './core/markdown.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Public documentation site (M17).
|
|
||||||
*
|
|
||||||
* Standalone on purpose: no session, no dashboard shell, and its own small
|
|
||||||
* bundle — a visitor reading the privacy notice should never meet a login page.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const state = { tree: null, slug: null, theme: localStorage.getItem('fws.theme') ?? 'dark' };
|
|
||||||
|
|
||||||
const api = async (path) => {
|
|
||||||
const response = await fetch(path, { headers: { Accept: 'application/json' } });
|
|
||||||
if (!response.ok) throw new Error((await response.json().catch(() => null))?.error ?? 'Page introuvable.');
|
|
||||||
return response.json();
|
|
||||||
};
|
|
||||||
|
|
||||||
const currentSlug = () => {
|
|
||||||
const path = window.location.pathname.replace(/^\/wiki\/?/, '').replace(/\/$/, '');
|
|
||||||
return decodeURIComponent(path) || null;
|
|
||||||
};
|
|
||||||
|
|
||||||
function navigate(slug, { replace = false } = {}) {
|
|
||||||
const url = slug ? `/wiki/${encodeURIComponent(slug)}` : '/wiki';
|
|
||||||
if (replace) window.history.replaceState({}, '', url);
|
|
||||||
else window.history.pushState({}, '', url);
|
|
||||||
draw();
|
|
||||||
}
|
|
||||||
|
|
||||||
function sidebar() {
|
|
||||||
const search = h('input', {
|
|
||||||
class: 'input',
|
|
||||||
type: 'search',
|
|
||||||
placeholder: 'Rechercher…',
|
|
||||||
'aria-label': 'Rechercher dans la documentation',
|
|
||||||
});
|
|
||||||
const results = h('div', { class: 'wiki-results' });
|
|
||||||
|
|
||||||
let timer = null;
|
|
||||||
search.addEventListener('input', () => {
|
|
||||||
clearTimeout(timer);
|
|
||||||
const term = search.value.trim();
|
|
||||||
if (term.length < 2) {
|
|
||||||
mount(results);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
timer = setTimeout(async () => {
|
|
||||||
const { results: found } = await api(`/api/wiki/search?q=${encodeURIComponent(term)}`).catch(() => ({
|
|
||||||
results: [],
|
|
||||||
}));
|
|
||||||
mount(
|
|
||||||
results,
|
|
||||||
found.length === 0
|
|
||||||
? h('p', { class: 'muted', text: 'Aucun résultat.' })
|
|
||||||
: found.map((page) =>
|
|
||||||
h('a', {
|
|
||||||
href: `/wiki/${page.slug}`,
|
|
||||||
text: page.title,
|
|
||||||
onClick: (event) => {
|
|
||||||
event.preventDefault();
|
|
||||||
search.value = '';
|
|
||||||
mount(results);
|
|
||||||
navigate(page.slug);
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}, 250);
|
|
||||||
});
|
|
||||||
|
|
||||||
return h(
|
|
||||||
'aside',
|
|
||||||
{ class: 'wiki-side' },
|
|
||||||
h(
|
|
||||||
'a',
|
|
||||||
{ class: 'wiki-brand', href: '/wiki' },
|
|
||||||
h('img', { src: '/favicon.svg', alt: '', width: 36, height: 36 }),
|
|
||||||
h('div', {}, h('strong', { text: 'FWS' }), h('span', { text: 'Documentation' })),
|
|
||||||
),
|
|
||||||
search,
|
|
||||||
results,
|
|
||||||
h(
|
|
||||||
'nav',
|
|
||||||
{ class: 'wiki-nav' },
|
|
||||||
(state.tree?.categories ?? []).map((category) =>
|
|
||||||
h(
|
|
||||||
'div',
|
|
||||||
{},
|
|
||||||
h('div', { class: 'nav-group', text: category.name }),
|
|
||||||
category.pages.map((page) =>
|
|
||||||
h('a', {
|
|
||||||
href: `/wiki/${page.slug}`,
|
|
||||||
text: page.title,
|
|
||||||
class: page.slug === state.slug ? 'active' : '',
|
|
||||||
onClick: (event) => {
|
|
||||||
event.preventDefault();
|
|
||||||
navigate(page.slug);
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function tableOfContents(headings) {
|
|
||||||
if (headings.length < 2) return null;
|
|
||||||
return h(
|
|
||||||
'nav',
|
|
||||||
{ class: 'wiki-toc' },
|
|
||||||
h('div', { class: 'nav-group', text: 'Sur cette page' }),
|
|
||||||
headings.map((heading) =>
|
|
||||||
h('a', { href: `#${heading.id}`, text: heading.text, dataset: { level: String(heading.level) } }),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function article(host) {
|
|
||||||
const slug = state.slug ?? state.tree?.categories?.[0]?.pages?.[0]?.slug ?? null;
|
|
||||||
if (!slug) {
|
|
||||||
mount(host, h('p', { class: 'empty', text: 'Aucune page publiée pour l’instant.' }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let page;
|
|
||||||
try {
|
|
||||||
page = await api(`/api/wiki/pages/${encodeURIComponent(slug)}`);
|
|
||||||
} catch (error) {
|
|
||||||
mount(host, h('div', { class: 'notice notice-error' }, h('p', { text: error.message })));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
document.title = `${page.title} · Documentation FWS`;
|
|
||||||
const { html, headings } = renderMarkdown(page.content);
|
|
||||||
|
|
||||||
const body = h('div', { class: 'wiki-content' });
|
|
||||||
body.innerHTML = html;
|
|
||||||
|
|
||||||
mount(
|
|
||||||
host,
|
|
||||||
h(
|
|
||||||
'div',
|
|
||||||
{ class: 'wiki-article' },
|
|
||||||
h(
|
|
||||||
'article',
|
|
||||||
{},
|
|
||||||
h('p', { class: 'muted', text: page.category }),
|
|
||||||
h('h1', { text: page.title }),
|
|
||||||
page.summary && h('p', { class: 'wiki-summary', text: page.summary }),
|
|
||||||
body,
|
|
||||||
h('footer', {
|
|
||||||
class: 'muted wiki-updated',
|
|
||||||
text: `Dernière modification : ${new Date(`${page.updatedAt}Z`).toLocaleDateString('fr-FR', {
|
|
||||||
dateStyle: 'long',
|
|
||||||
})}`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
tableOfContents(headings),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function draw() {
|
|
||||||
state.slug = currentSlug();
|
|
||||||
const root = qs('#wiki');
|
|
||||||
|
|
||||||
if (!state.tree) {
|
|
||||||
state.tree = await api('/api/wiki').catch(() => ({ categories: [], site: {} }));
|
|
||||||
}
|
|
||||||
|
|
||||||
const main = h('main', { class: 'wiki-main' });
|
|
||||||
mount(root, h('div', { class: 'wiki-shell' }, sidebar(), main));
|
|
||||||
await article(main);
|
|
||||||
|
|
||||||
// In-page anchors only work once the article is on screen.
|
|
||||||
if (window.location.hash) qs(window.location.hash)?.scrollIntoView({ block: 'start' });
|
|
||||||
}
|
|
||||||
|
|
||||||
document.documentElement.dataset.theme = state.theme;
|
|
||||||
window.addEventListener('popstate', draw);
|
|
||||||
draw();
|
|
||||||
+95
-6
@@ -9,13 +9,73 @@ import { registerApiRoutes } from './api/index.js';
|
|||||||
import { authenticate, assertSameOrigin } from './auth/session.js';
|
import { authenticate, assertSameOrigin } from './auth/session.js';
|
||||||
import { authorize } from './auth/guard.js';
|
import { authorize } from './auth/guard.js';
|
||||||
import { broadcast, closeEventStreams, topicForPath } from './events.js';
|
import { broadcast, closeEventStreams, topicForPath } from './events.js';
|
||||||
import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js';
|
import { HttpError, readJsonBody, readRawBody, sendEmpty, sendHtml, sendJson, sendStatic } from './http.js';
|
||||||
import { createRouter } from './router.js';
|
import { createRouter } from './router.js';
|
||||||
import { seedWiki } from './services/wiki-seed.js';
|
import { listPublished } from '../database/repositories/wiki-repository.js';
|
||||||
|
import { renderStatus } from './services/status-render.js';
|
||||||
|
import { statusSnapshot } from './services/status-service.js';
|
||||||
|
import { pagePath } from './services/wiki-seed.js';
|
||||||
|
import { renderIndex, renderNotFound, renderPage } from './services/wiki-render.js';
|
||||||
|
import { ROOT_PAGES, seedWiki } from './services/wiki-seed.js';
|
||||||
|
|
||||||
/** HTTP server of the dashboard (M16-T01). */
|
/** HTTP server of the dashboard (M16-T01). */
|
||||||
|
|
||||||
const log = createLogger('web');
|
const log = createLogger('web');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The wiki address a path stands for: `''` for the index, a slug for a page,
|
||||||
|
* `null` when the path is not the wiki's business.
|
||||||
|
*/
|
||||||
|
function wikiSlug(pathname) {
|
||||||
|
const clean = pathname.replace(/\/+$/, '');
|
||||||
|
if (clean === '/wiki' || clean === '') return clean === '/wiki' ? '' : null;
|
||||||
|
if (clean.startsWith('/wiki/')) return decodeURIComponent(clean.slice('/wiki/'.length));
|
||||||
|
|
||||||
|
const root = clean.replace(/^\//, '');
|
||||||
|
return ROOT_PAGES.includes(root) ? root : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Answers with the finished HTML of a wiki page, or its index. */
|
||||||
|
function sendWiki(response, slug, term) {
|
||||||
|
let pages = [];
|
||||||
|
try {
|
||||||
|
pages = listPublished();
|
||||||
|
} catch (error) {
|
||||||
|
log.warn('Could not read the wiki pages', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const categories = [];
|
||||||
|
for (const page of pages) {
|
||||||
|
const entry = { ...page, path: pagePath(page.slug) };
|
||||||
|
let category = categories.find((item) => item.name === page.category);
|
||||||
|
if (!category) categories.push((category = { name: page.category, pages: [] }));
|
||||||
|
category.pages.push(entry);
|
||||||
|
}
|
||||||
|
const all = categories.flatMap((category) => category.pages);
|
||||||
|
|
||||||
|
if (slug === '') {
|
||||||
|
const needle = term.trim().toLowerCase();
|
||||||
|
const results =
|
||||||
|
needle.length >= 2
|
||||||
|
? all.filter((page) =>
|
||||||
|
[page.title, page.summary, page.content].some((field) =>
|
||||||
|
String(field ?? '')
|
||||||
|
.toLowerCase()
|
||||||
|
.includes(needle),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
sendHtml(response, 200, renderIndex(categories, { term, results }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const page = all.find((entry) => entry.slug === slug);
|
||||||
|
if (!page) {
|
||||||
|
sendHtml(response, 404, renderNotFound(categories));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sendHtml(response, 200, renderPage(page, categories));
|
||||||
|
}
|
||||||
const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
|
const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
|
||||||
|
|
||||||
/** Sliding window per client address, reset every minute. */
|
/** Sliding window per client address, reset every minute. */
|
||||||
@@ -72,10 +132,39 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da
|
|||||||
|
|
||||||
const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/');
|
const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/');
|
||||||
if (!isApi) {
|
if (!isApi) {
|
||||||
// The wiki is a separate public page: it must never fall back to the
|
// The wiki is rendered here rather than in the browser: a terms page
|
||||||
// dashboard shell, which would send a visitor to a login screen.
|
// that needs scripts to show its text reads as blank to anything that
|
||||||
const fallback = pathname === '/wiki' || pathname.startsWith('/wiki/') ? 'wiki.html' : 'index.html';
|
// does not run them, which includes whoever checks the link before
|
||||||
const served = await sendStatic(response, publicDir, pathname, { fallback, request });
|
// approving an application.
|
||||||
|
const slug = wikiSlug(pathname);
|
||||||
|
if (slug !== null) {
|
||||||
|
sendWiki(response, slug, url.searchParams.get('q') ?? '');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same reasoning for the status page, with one addition: it is read when
|
||||||
|
// something is wrong, which is the worst moment to need a working browser.
|
||||||
|
// Turned off, it answers 404 rather than falling through to the dashboard
|
||||||
|
// shell — « this address does not exist here » is the honest answer, and
|
||||||
|
// a shell served at /status only looks like a broken status page.
|
||||||
|
if (pathname.replace(/\/+$/, '') === '/status') {
|
||||||
|
if (!env.web.publicStatus) {
|
||||||
|
sendEmpty(response, 404);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
sendHtml(response, 200, renderStatus(await statusSnapshot(context)));
|
||||||
|
} catch (error) {
|
||||||
|
log.error('Could not render the status page', error);
|
||||||
|
sendHtml(response, 503, '<!doctype html><title>État indisponible</title><p>État indisponible.');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const served = await sendStatic(response, publicDir, pathname, {
|
||||||
|
fallback: 'index.html',
|
||||||
|
request,
|
||||||
|
});
|
||||||
if (!served) sendEmpty(response, 404);
|
if (!served) sendEmpty(response, 404);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What is actually being served (M16-T01, extracted in M19).
|
||||||
|
*
|
||||||
|
* Kept apart from the routes because the health probe, the status page and the
|
||||||
|
* sidebar all need the same answer, and a second copy would eventually give a
|
||||||
|
* different one.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
export const VERSION = (() => {
|
||||||
|
try {
|
||||||
|
return JSON.parse(readFileSync(path.join(here, '../../../package.json'), 'utf8')).version;
|
||||||
|
} catch {
|
||||||
|
return 'inconnue';
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Newest file of the served interface.
|
||||||
|
*
|
||||||
|
* Read from disk rather than frozen at startup: the front-end is served from
|
||||||
|
* disk on every request, so a marker captured at boot would keep announcing an
|
||||||
|
* old build after an upload — the exact confusion it exists to prevent. Cached
|
||||||
|
* briefly so a health check does not walk the tree each time.
|
||||||
|
*/
|
||||||
|
const BUILD_TTL_MS = 10_000;
|
||||||
|
let cache = { at: null, readAt: 0 };
|
||||||
|
|
||||||
|
export function buildAt() {
|
||||||
|
if (cache.readAt && Date.now() - cache.readAt < BUILD_TTL_MS) return cache.at;
|
||||||
|
|
||||||
|
const root = path.join(here, '../public');
|
||||||
|
let newest = 0;
|
||||||
|
|
||||||
|
const walk = (directory) => {
|
||||||
|
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||||
|
const target = path.join(directory, entry.name);
|
||||||
|
if (entry.isDirectory()) walk(target);
|
||||||
|
else newest = Math.max(newest, statSync(target).mtimeMs);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
walk(root);
|
||||||
|
} catch {
|
||||||
|
cache = { at: null, readAt: Date.now() };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
cache = { at: newest > 0 ? new Date(newest).toISOString() : null, readAt: Date.now() };
|
||||||
|
return cache.at;
|
||||||
|
}
|
||||||
@@ -223,21 +223,14 @@ 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',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'CHANNEL_MOD_LOGS_ID',
|
key: 'CHANNEL_MOD_LOGS_ID',
|
||||||
section: 'channels',
|
section: 'channels',
|
||||||
label: 'Salon des logs de modération',
|
label: 'Salon des logs de modération',
|
||||||
help: 'Avertissements, exclusions, bannissements.',
|
help: 'Avertissements, mises en sourdine, bannissements.',
|
||||||
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',
|
type: 'snowflake',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -499,6 +492,15 @@ export const VARIABLES = Object.freeze([
|
|||||||
generator: 'hex16',
|
generator: 'hex16',
|
||||||
advanced: true,
|
advanced: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'WEB_PUBLIC_STATUS',
|
||||||
|
section: 'web',
|
||||||
|
label: 'Page de statut publique',
|
||||||
|
help: 'Publie `/status` : bot en ligne, dernier déploiement par environnement, dernières releases. Les dépôts privés n’y apparaissent jamais par leur nom.',
|
||||||
|
type: 'bool',
|
||||||
|
default: 'true',
|
||||||
|
restartRequired: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: 'WEB_ALLOW_COMMAND_DEPLOYS',
|
key: 'WEB_ALLOW_COMMAND_DEPLOYS',
|
||||||
section: 'web',
|
section: 'web',
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
/**
|
||||||
|
* Public status page, rendered on the server (M19).
|
||||||
|
*
|
||||||
|
* Same reasoning as the wiki: a page that needs JavaScript to say whether the
|
||||||
|
* service is up is a page that reads as blank to a monitor, a crawler, or
|
||||||
|
* anyone on a connection bad enough to be checking the status in the first
|
||||||
|
* place. There is no script tag here, and the refresh is a meta tag.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const escape = (text) =>
|
||||||
|
String(text ?? '')
|
||||||
|
.replaceAll('&', '&')
|
||||||
|
.replaceAll('<', '<')
|
||||||
|
.replaceAll('>', '>')
|
||||||
|
.replaceAll('"', '"');
|
||||||
|
|
||||||
|
const REFRESH_SECONDS = 60;
|
||||||
|
|
||||||
|
const STATE_LABELS = {
|
||||||
|
ok: 'Opérationnel',
|
||||||
|
down: 'Hors ligne',
|
||||||
|
busy: 'En cours',
|
||||||
|
unknown: 'Inconnu',
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEPLOY_LABELS = {
|
||||||
|
success: 'Déployé',
|
||||||
|
failed: 'Échec',
|
||||||
|
running: 'En cours',
|
||||||
|
pending: 'En attente',
|
||||||
|
};
|
||||||
|
|
||||||
|
function duration(ms) {
|
||||||
|
const seconds = Math.floor(Number(ms) / 1000);
|
||||||
|
if (!Number.isFinite(seconds) || seconds < 0) return '—';
|
||||||
|
|
||||||
|
const days = Math.floor(seconds / 86_400);
|
||||||
|
const hours = Math.floor((seconds % 86_400) / 3600);
|
||||||
|
const minutes = Math.floor((seconds % 3600) / 60);
|
||||||
|
if (days > 0) return `${days} j ${hours} h`;
|
||||||
|
if (hours > 0) return `${hours} h ${minutes} min`;
|
||||||
|
if (minutes > 0) return `${minutes} min`;
|
||||||
|
return `${seconds} s`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function moment(value) {
|
||||||
|
if (!value) return '—';
|
||||||
|
const date = new Date(String(value).includes('T') ? value : `${value}Z`);
|
||||||
|
if (Number.isNaN(date.getTime())) return '—';
|
||||||
|
return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const pill = (tone, label) => `<span class="status-pill status-pill-${escape(tone)}">${escape(label)}</span>`;
|
||||||
|
|
||||||
|
const tile = (label, value, hint) => `
|
||||||
|
<div class="status-tile">
|
||||||
|
<span class="status-tile-label">${escape(label)}</span>
|
||||||
|
<strong class="status-tile-value">${escape(value)}</strong>
|
||||||
|
${hint ? `<span class="status-tile-hint">${escape(hint)}</span>` : ''}
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
function environmentRows(environments) {
|
||||||
|
if (environments.length === 0) {
|
||||||
|
return '<p class="status-empty">Aucun déploiement enregistré pour l’instant.</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
return `<table class="status-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th>Environnement</th><th>Dépôt</th><th>Version</th><th>État</th><th>Le</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
${environments
|
||||||
|
.map(
|
||||||
|
(entry) => `<tr>
|
||||||
|
<td><strong>${escape(entry.environment)}</strong></td>
|
||||||
|
<td>${entry.repository ? escape(entry.repository) : '<span class="status-muted">privé</span>'}</td>
|
||||||
|
<td>${entry.releaseTag ? `<code>${escape(entry.releaseTag)}</code>` : '—'}</td>
|
||||||
|
<td>${pill(entry.tone, DEPLOY_LABELS[entry.status] ?? entry.status)}</td>
|
||||||
|
<td class="status-muted">${escape(moment(entry.finishedAt))}</td>
|
||||||
|
</tr>`,
|
||||||
|
)
|
||||||
|
.join('\n ')}
|
||||||
|
</tbody>
|
||||||
|
</table>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function releaseList(releases) {
|
||||||
|
if (releases.length === 0) {
|
||||||
|
return '<p class="status-empty">Aucune release publiée pour l’instant.</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
return `<ul class="status-releases">
|
||||||
|
${releases
|
||||||
|
.map((release) => {
|
||||||
|
const label = `${release.repository} · ${release.name}`;
|
||||||
|
const title = release.htmlUrl
|
||||||
|
? `<a href="${escape(release.htmlUrl)}">${escape(label)}</a>`
|
||||||
|
: escape(label);
|
||||||
|
return `<li>
|
||||||
|
<div>${title}${release.prerelease ? ` ${pill('busy', 'préversion')}` : ''}</div>
|
||||||
|
<span class="status-muted">${escape(moment(release.publishedAt))}</span>
|
||||||
|
</li>`;
|
||||||
|
})
|
||||||
|
.join('\n ')}
|
||||||
|
</ul>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function footer(links) {
|
||||||
|
const entries = [
|
||||||
|
['/wiki', 'Documentation'],
|
||||||
|
['/terms-of-service', 'Conditions d’utilisation'],
|
||||||
|
['/privacy-policy', 'Politique de confidentialité'],
|
||||||
|
links.website && [links.website, 'Site'],
|
||||||
|
links.forge && [links.forge, 'Forge'],
|
||||||
|
links.discordInvite && [links.discordInvite, 'Discord'],
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
return `<footer class="status-footer">${entries
|
||||||
|
.map(([href, label]) => `<a href="${escape(href)}">${escape(label)}</a>`)
|
||||||
|
.join(' · ')}</footer>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Turns a snapshot from `status-service.js` into the finished page. */
|
||||||
|
export function renderStatus(snapshot) {
|
||||||
|
const { bot } = snapshot;
|
||||||
|
const failing = snapshot.environments.filter((entry) => entry.status === 'failed');
|
||||||
|
|
||||||
|
// The banner states the worst true thing: a green headline above a failed
|
||||||
|
// deployment is how a status page loses the only thing it has.
|
||||||
|
const headline = !bot.online
|
||||||
|
? { tone: 'down', title: 'Le bot est hors ligne', detail: 'Le service ne répond pas à Discord.' }
|
||||||
|
: failing.length > 0
|
||||||
|
? {
|
||||||
|
tone: 'busy',
|
||||||
|
title: 'Service opérationnel, déploiement en échec',
|
||||||
|
detail: `Le bot répond, mais ${failing.length} environnement(s) n’ont pas reçu leur dernière mise à jour.`,
|
||||||
|
}
|
||||||
|
: { tone: 'ok', title: 'Tous les services fonctionnent', detail: 'Le bot répond à Discord.' };
|
||||||
|
|
||||||
|
return `<!doctype html>
|
||||||
|
<html lang="fr" data-theme="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="color-scheme" content="dark light" />
|
||||||
|
<meta name="description" content="État en direct des services FWS : bot Discord, déploiements et releases." />
|
||||||
|
<meta name="robots" content="index, follow" />
|
||||||
|
<meta http-equiv="refresh" content="${REFRESH_SECONDS}" />
|
||||||
|
<title>État des services · FWS</title>
|
||||||
|
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||||
|
<link rel="stylesheet" href="/styles.css" />
|
||||||
|
</head>
|
||||||
|
<body class="status-body">
|
||||||
|
<main class="status-page">
|
||||||
|
<header class="status-head">
|
||||||
|
<a class="status-brand" href="/wiki">
|
||||||
|
<img src="/favicon.svg" alt="" width="40" height="40" />
|
||||||
|
<div><strong>FWS</strong><span>État des services</span></div>
|
||||||
|
</a>
|
||||||
|
<span class="status-muted">Actualisé automatiquement toutes les ${REFRESH_SECONDS} secondes</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="status-banner status-banner-${escape(headline.tone)}">
|
||||||
|
<h1>${escape(headline.title)}</h1>
|
||||||
|
<p>${escape(headline.detail)}</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="status-section">
|
||||||
|
<h2>Bot Discord</h2>
|
||||||
|
<div class="status-tiles">
|
||||||
|
${tile('État', STATE_LABELS[bot.state] ?? bot.state)}
|
||||||
|
${tile('En ligne depuis', duration(bot.uptimeMs), `Démarré le ${moment(bot.startedAt)}`)}
|
||||||
|
${tile('Latence Discord', bot.pingMs === null ? '—' : `${bot.pingMs} ms`)}
|
||||||
|
${tile('Version', bot.version)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="status-section">
|
||||||
|
<h2>Déploiements</h2>
|
||||||
|
${environmentRows(snapshot.environments)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="status-section">
|
||||||
|
<h2>Dernières releases</h2>
|
||||||
|
${releaseList(snapshot.releases)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<p class="status-muted status-generated">
|
||||||
|
Relevé du <time datetime="${escape(snapshot.generatedAt)}">${escape(moment(snapshot.generatedAt))}</time>.
|
||||||
|
Version lisible par une machine : <a href="/api/status">/api/status</a>.
|
||||||
|
</p>
|
||||||
|
${footer(snapshot.links)}
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import { env } from '../../config/env.js';
|
||||||
|
import { createLogger } from '../../core/logger.js';
|
||||||
|
import { lastDeploymentPerEnvironment } from '../../database/repositories/deploy-repository.js';
|
||||||
|
import { org, repos, splitRepository } from '../../services/gitea/gitea-admin.js';
|
||||||
|
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
|
||||||
|
import { VERSION } from './build-info.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the public status page and `/api/status` both answer with (M19).
|
||||||
|
*
|
||||||
|
* Two rules shape this file. The page is **public**, so nothing here may name
|
||||||
|
* something the organization has not made public — a private repository leaking
|
||||||
|
* through a deployment row would be a real disclosure. And it is **unauthenticated**,
|
||||||
|
* so it may not turn a page load into a forge request: everything from Gitea is
|
||||||
|
* cached, and a failed refresh serves the previous answer rather than none.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const log = createLogger('web:status');
|
||||||
|
|
||||||
|
const CACHE_TTL_MS = 60_000;
|
||||||
|
let cache = { at: 0, publicRepositories: null, releases: [] };
|
||||||
|
|
||||||
|
/** `success` is the only state worth claiming; everything else is spelled out. */
|
||||||
|
const DEPLOY_TONES = {
|
||||||
|
success: 'ok',
|
||||||
|
failed: 'down',
|
||||||
|
running: 'busy',
|
||||||
|
pending: 'busy',
|
||||||
|
};
|
||||||
|
|
||||||
|
async function refreshForge() {
|
||||||
|
if (!isGiteaConfigured()) return;
|
||||||
|
if (Date.now() - cache.at < CACHE_TTL_MS) return;
|
||||||
|
|
||||||
|
const repositories = await org.listRepos({ limit: 50 }).catch((error) => {
|
||||||
|
log.debug('Could not refresh the public repository list', error);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
if (!repositories) return;
|
||||||
|
|
||||||
|
const open = repositories.filter((repository) => !repository.private && !repository.archived);
|
||||||
|
|
||||||
|
// One release request per repository would grow with the organization; the
|
||||||
|
// three most recently touched are what a status page is read for anyway.
|
||||||
|
const recent = open
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
|
||||||
|
.slice(0, 3);
|
||||||
|
|
||||||
|
const releases = (
|
||||||
|
await Promise.all(
|
||||||
|
recent.map(async (repository) => {
|
||||||
|
const parts = splitRepository(repository.full_name);
|
||||||
|
if (!parts) return null;
|
||||||
|
|
||||||
|
const release = await repos.latestRelease(parts.owner, parts.repo).catch(() => null);
|
||||||
|
if (!release || release.draft) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
repository: repository.full_name,
|
||||||
|
tag: release.tag_name,
|
||||||
|
name: release.name || release.tag_name,
|
||||||
|
prerelease: Boolean(release.prerelease),
|
||||||
|
publishedAt: release.published_at ?? release.created_at ?? null,
|
||||||
|
htmlUrl: release.html_url ?? null,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
).filter(Boolean);
|
||||||
|
|
||||||
|
cache = {
|
||||||
|
at: Date.now(),
|
||||||
|
publicRepositories: new Set(open.map((repository) => repository.full_name)),
|
||||||
|
releases,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deployment rows, stripped of anything the public has no business seeing.
|
||||||
|
*
|
||||||
|
* A repository the forge does not list as public is kept as a row — the
|
||||||
|
* environment is still meaningful — but loses its name.
|
||||||
|
*/
|
||||||
|
function environments() {
|
||||||
|
const guildId = env.discord.guildId;
|
||||||
|
if (!guildId) return [];
|
||||||
|
|
||||||
|
const rows = lastDeploymentPerEnvironment(guildId);
|
||||||
|
const known = cache.publicRepositories;
|
||||||
|
|
||||||
|
return rows.map((row) => ({
|
||||||
|
environment: row.environment,
|
||||||
|
repository: !known || known.has(row.repository) ? row.repository : null,
|
||||||
|
status: row.status,
|
||||||
|
tone: DEPLOY_TONES[row.status] ?? 'unknown',
|
||||||
|
releaseTag: row.release_tag ?? null,
|
||||||
|
finishedAt: row.finished_at ?? null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The snapshot behind `/status` and `/api/status`. Never throws. */
|
||||||
|
export async function statusSnapshot({ client = null, startedAt = Date.now() } = {}) {
|
||||||
|
await refreshForge().catch((error) => log.debug('Status refresh failed', error));
|
||||||
|
|
||||||
|
const online = Boolean(client?.isReady?.());
|
||||||
|
return {
|
||||||
|
bot: {
|
||||||
|
online,
|
||||||
|
state: online ? 'ok' : 'down',
|
||||||
|
uptimeMs: Date.now() - startedAt,
|
||||||
|
startedAt: new Date(startedAt).toISOString(),
|
||||||
|
version: VERSION,
|
||||||
|
// Round-trip to Discord: the one number that says the link is healthy
|
||||||
|
// rather than merely established.
|
||||||
|
pingMs: typeof client?.ws?.ping === 'number' && client.ws.ping >= 0 ? client.ws.ping : null,
|
||||||
|
},
|
||||||
|
environments: environments(),
|
||||||
|
releases: cache.releases,
|
||||||
|
links: {
|
||||||
|
website: env.links.website || null,
|
||||||
|
docs: env.links.docs || null,
|
||||||
|
discordInvite: env.links.discordInvite || null,
|
||||||
|
archRepo: env.links.archRepo || null,
|
||||||
|
forge: isGiteaConfigured() ? env.gitea.url : null,
|
||||||
|
},
|
||||||
|
generatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lets the tests start from a known state. */
|
||||||
|
export function resetStatusCache() {
|
||||||
|
cache = { at: 0, publicRepositories: null, releases: [] };
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import { env } from '../../config/env.js';
|
||||||
|
import { render as renderMarkdown } from '../public/core/markdown.js';
|
||||||
|
import { pagePath } from './wiki-seed.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Server-rendered wiki (M17).
|
||||||
|
*
|
||||||
|
* The public documentation is delivered as finished HTML rather than assembled
|
||||||
|
* in the browser. A terms page that needs JavaScript to show its text is a page
|
||||||
|
* that reads as blank to anything that does not run scripts — a platform
|
||||||
|
* checking the link before approving an application, a crawler, a reader with
|
||||||
|
* scripts disabled — and those are exactly the readers it exists for.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const escape = (text) =>
|
||||||
|
String(text ?? '')
|
||||||
|
.replaceAll('&', '&')
|
||||||
|
.replaceAll('<', '<')
|
||||||
|
.replaceAll('>', '>')
|
||||||
|
.replaceAll('"', '"');
|
||||||
|
|
||||||
|
const document = ({ title, description, body, noindex = false }) => `<!doctype html>
|
||||||
|
<html lang="fr" data-theme="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="color-scheme" content="dark light" />
|
||||||
|
<meta name="description" content="${escape(description)}" />
|
||||||
|
<meta name="robots" content="${noindex ? 'noindex, nofollow' : 'index, follow'}" />
|
||||||
|
<title>${escape(title)}</title>
|
||||||
|
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||||
|
<link rel="stylesheet" href="/styles.css" />
|
||||||
|
<link rel="stylesheet" href="/wiki.css" />
|
||||||
|
</head>
|
||||||
|
<body class="wiki-body">
|
||||||
|
${body}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
|
|
||||||
|
/** Sidebar: the page tree and a search box that works without scripts. */
|
||||||
|
function sidebar(categories, currentSlug, term = '') {
|
||||||
|
const groups = categories
|
||||||
|
.map(
|
||||||
|
(category) => `
|
||||||
|
<div class="nav-group">${escape(category.name)}</div>
|
||||||
|
${category.pages
|
||||||
|
.map(
|
||||||
|
(page) =>
|
||||||
|
`<a href="${escape(page.path ?? pagePath(page.slug))}"${
|
||||||
|
page.slug === currentSlug ? ' class="active" aria-current="page"' : ''
|
||||||
|
}>${escape(page.title)}</a>`,
|
||||||
|
)
|
||||||
|
.join('\n ')}`,
|
||||||
|
)
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
return ` <aside class="wiki-side">
|
||||||
|
<a class="wiki-brand" href="/wiki">
|
||||||
|
<img src="/favicon.svg" alt="" width="36" height="36" />
|
||||||
|
<div><strong>FWS</strong><span>Documentation</span></div>
|
||||||
|
</a>
|
||||||
|
<form class="wiki-search" method="get" action="/wiki">
|
||||||
|
<input class="input" type="search" name="q" value="${escape(term)}" placeholder="Rechercher…" aria-label="Rechercher dans la documentation" />
|
||||||
|
</form>
|
||||||
|
<nav class="wiki-nav">
|
||||||
|
${groups}
|
||||||
|
</nav>
|
||||||
|
</aside>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Table of contents, built from the headings the renderer collected. */
|
||||||
|
const contents = (headings) =>
|
||||||
|
headings.length < 2
|
||||||
|
? ''
|
||||||
|
: ` <nav class="wiki-toc">
|
||||||
|
<div class="nav-group">Sur cette page</div>
|
||||||
|
${headings
|
||||||
|
.map(
|
||||||
|
(heading) =>
|
||||||
|
`<a href="#${escape(heading.id)}" data-level="${heading.level}">${escape(heading.text)}</a>`,
|
||||||
|
)
|
||||||
|
.join('\n ')}
|
||||||
|
</nav>`;
|
||||||
|
|
||||||
|
const footerLinks = () => {
|
||||||
|
const links = [
|
||||||
|
env.links.website && `<a href="${escape(env.links.website)}">Site</a>`,
|
||||||
|
env.links.docs && `<a href="${escape(env.links.docs)}">Documentation</a>`,
|
||||||
|
`<a href="/terms-of-service">Conditions d'utilisation</a>`,
|
||||||
|
`<a href="/privacy-policy">Politique de confidentialité</a>`,
|
||||||
|
].filter(Boolean);
|
||||||
|
return `<footer class="wiki-footer">${links.join(' · ')}</footer>`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const shell = (categories, currentSlug, main, term) => ` <div class="wiki-shell">
|
||||||
|
${sidebar(categories, currentSlug, term)}
|
||||||
|
<main class="wiki-main">
|
||||||
|
${main}
|
||||||
|
${footerLinks()}
|
||||||
|
</main>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
/** A page, with its body already turned into HTML. */
|
||||||
|
export function renderPage(page, categories) {
|
||||||
|
const { html, headings } = renderMarkdown(page.content);
|
||||||
|
const updated = new Date(`${page.updated_at}Z`);
|
||||||
|
|
||||||
|
const main = ` <div class="wiki-article">
|
||||||
|
<article>
|
||||||
|
<p class="muted">${escape(page.category)}</p>
|
||||||
|
<h1>${escape(page.title)}</h1>
|
||||||
|
${page.summary ? `<p class="wiki-summary">${escape(page.summary)}</p>` : ''}
|
||||||
|
<div class="wiki-content">
|
||||||
|
${html}
|
||||||
|
</div>
|
||||||
|
<footer class="muted wiki-updated">
|
||||||
|
Dernière modification :
|
||||||
|
<time datetime="${escape(updated.toISOString())}">${updated.toLocaleDateString('fr-FR', {
|
||||||
|
dateStyle: 'long',
|
||||||
|
})}</time>
|
||||||
|
</footer>
|
||||||
|
</article>
|
||||||
|
${contents(headings)}
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
return document({
|
||||||
|
title: `${page.title} · Documentation FWS`,
|
||||||
|
description: page.summary || `${page.title} — documentation de l'organisation FWS.`,
|
||||||
|
body: shell(categories, page.slug, main),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Landing page, and the search results when a term is given. */
|
||||||
|
export function renderIndex(categories, { term = '', results = null } = {}) {
|
||||||
|
const list = (pages) =>
|
||||||
|
pages.length === 0
|
||||||
|
? '<p class="empty">Aucun résultat.</p>'
|
||||||
|
: `<ul class="wiki-index">${pages
|
||||||
|
.map(
|
||||||
|
(page) =>
|
||||||
|
`<li><a href="${escape(page.path ?? pagePath(page.slug))}">${escape(page.title)}</a>${
|
||||||
|
page.summary ? ` — <span class="muted">${escape(page.summary)}</span>` : ''
|
||||||
|
}</li>`,
|
||||||
|
)
|
||||||
|
.join('')}</ul>`;
|
||||||
|
|
||||||
|
const main = results
|
||||||
|
? ` <article>
|
||||||
|
<h1>Recherche</h1>
|
||||||
|
<p class="muted">${results.length} résultat(s) pour « ${escape(term)} ».</p>
|
||||||
|
${list(results)}
|
||||||
|
</article>`
|
||||||
|
: ` <article>
|
||||||
|
<h1>Documentation FWS</h1>
|
||||||
|
<p class="wiki-summary">Tout ce qu'il faut savoir sur le bot et l'organisation.</p>
|
||||||
|
${categories
|
||||||
|
.map((category) => `<h2>${escape(category.name)}</h2>${list(category.pages)}`)
|
||||||
|
.join('\n ')}
|
||||||
|
</article>`;
|
||||||
|
|
||||||
|
return document({
|
||||||
|
title: 'Documentation FWS',
|
||||||
|
description: "Documentation publique de l'organisation open source FWS.",
|
||||||
|
body: shell(categories, null, main, term),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderNotFound(categories) {
|
||||||
|
const main = ` <article>
|
||||||
|
<h1>Page introuvable</h1>
|
||||||
|
<p class="muted">Cette page n'existe pas, ou n'est pas encore publiée.</p>
|
||||||
|
<p><a href="/wiki">Revenir à la documentation</a></p>
|
||||||
|
</article>`;
|
||||||
|
|
||||||
|
return document({
|
||||||
|
title: 'Page introuvable · Documentation FWS',
|
||||||
|
description: 'Page introuvable.',
|
||||||
|
body: shell(categories, null, main),
|
||||||
|
noindex: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -15,6 +15,17 @@ import { countPages, createPage, getPageBySlug } from '../../database/repositori
|
|||||||
|
|
||||||
const log = createLogger('wiki');
|
const log = createLogger('wiki');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pages served at the root rather than under `/wiki/`.
|
||||||
|
*
|
||||||
|
* Discord, and most platforms, ask for a terms URL and a privacy URL; pasting
|
||||||
|
* `/wiki/...` in those fields reads like an afterthought.
|
||||||
|
*/
|
||||||
|
export const ROOT_PAGES = Object.freeze(['terms-of-service', 'privacy-policy']);
|
||||||
|
|
||||||
|
/** Public address of a page, root pages included. */
|
||||||
|
export const pagePath = (slug) => (ROOT_PAGES.includes(slug) ? `/${slug}` : `/wiki/${slug}`);
|
||||||
|
|
||||||
const TERMS = `## 1. Objet
|
const TERMS = `## 1. Objet
|
||||||
|
|
||||||
Ces conditions régissent l'utilisation du bot Discord **FWS-Bot** et de son tableau de bord, exploités par **[NOM DE L'ENTITÉ RESPONSABLE]** (ci-après « nous »).
|
Ces conditions régissent l'utilisation du bot Discord **FWS-Bot** et de son tableau de bord, exploités par **[NOM DE L'ENTITÉ RESPONSABLE]** (ci-après « nous »).
|
||||||
@@ -185,8 +196,8 @@ Ces pages sont rédigées et publiées depuis le tableau de bord du bot : elles
|
|||||||
|
|
||||||
## Pour commencer
|
## Pour commencer
|
||||||
|
|
||||||
- **Conditions d'utilisation** — ce à quoi tu t'engages en utilisant le bot.
|
- [**Conditions d'utilisation**](/terms-of-service) — ce à quoi tu t'engages en utilisant le bot.
|
||||||
- **Politique de confidentialité** — quelles données sont traitées, pourquoi, et tes droits.
|
- [**Politique de confidentialité**](/privacy-policy) — quelles données sont traitées, pourquoi, et tes droits.
|
||||||
|
|
||||||
## Contribuer
|
## Contribuer
|
||||||
|
|
||||||
@@ -206,7 +217,7 @@ const DEFAULT_PAGES = [
|
|||||||
isProtected: false,
|
isProtected: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
slug: 'conditions-utilisation',
|
slug: 'terms-of-service',
|
||||||
title: 'Conditions d’utilisation',
|
title: 'Conditions d’utilisation',
|
||||||
summary: 'Ce à quoi tu t’engages en utilisant le bot FWS.',
|
summary: 'Ce à quoi tu t’engages en utilisant le bot FWS.',
|
||||||
category: 'Légal',
|
category: 'Légal',
|
||||||
@@ -216,7 +227,7 @@ const DEFAULT_PAGES = [
|
|||||||
isProtected: true,
|
isProtected: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
slug: 'politique-confidentialite',
|
slug: 'privacy-policy',
|
||||||
title: 'Politique de confidentialité',
|
title: 'Politique de confidentialité',
|
||||||
summary: 'Données traitées, durées de conservation et droits, selon la LPD suisse.',
|
summary: 'Données traitées, durées de conservation et droits, selon la LPD suisse.',
|
||||||
category: 'Légal',
|
category: 'Légal',
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { after, before, describe, it } from 'node:test';
|
import { after, before, describe, it } from 'node:test';
|
||||||
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
||||||
|
import { listActions, recordAction } from '../src/database/repositories/moderation-repository.js';
|
||||||
import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js';
|
import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js';
|
||||||
|
|
||||||
describe('database', () => {
|
describe('database', () => {
|
||||||
@@ -22,6 +23,20 @@ describe('database', () => {
|
|||||||
assert.equal(getSetting('guild-b', 'welcome'), null);
|
assert.equal(getSetting('guild-b', 'welcome'), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('records a lifted sanction next to the sanction it lifts', () => {
|
||||||
|
// `/unmute` and `/unban` go through the same CHECK constraint as `/mute`
|
||||||
|
// and `/ban`, so a migration that forgets them breaks the history.
|
||||||
|
for (const action of ['unban', 'unmute']) {
|
||||||
|
recordAction({ guildId: 'g', action, moderatorId: 'mod', targetId: 'u', reason: 'Erreur' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = listActions({ guildId: 'g', targetId: 'u' });
|
||||||
|
assert.deepEqual(
|
||||||
|
rows.map((row) => row.action).sort(),
|
||||||
|
['unban', 'unmute'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('prevents two open tickets for the same author and category', () => {
|
it('prevents two open tickets for the same author and category', () => {
|
||||||
const insert = getDatabase().prepare(
|
const insert = getDatabase().prepare(
|
||||||
"INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')",
|
"INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')",
|
||||||
|
|||||||
@@ -94,6 +94,30 @@ describe('webhook entry points', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('moderation labels', () => {
|
||||||
|
it('tells every action apart by wording and emoji', async () => {
|
||||||
|
const { MODERATION_ACTIONS } = await import('../src/config/constants.js');
|
||||||
|
const { moderationLabel } = await import('../src/services/moderation/moderation-service.js');
|
||||||
|
|
||||||
|
const emojis = Object.values(MODERATION_ACTIONS).map((meta) => meta.emoji);
|
||||||
|
assert.ok(emojis.every(Boolean), 'an action has no emoji');
|
||||||
|
assert.equal(new Set(emojis).size, emojis.length, 'two actions share an emoji');
|
||||||
|
|
||||||
|
const labels = Object.keys(MODERATION_ACTIONS).map(moderationLabel);
|
||||||
|
assert.equal(new Set(labels).size, labels.length, 'two actions read the same');
|
||||||
|
assert.equal(moderationLabel('inconnu'), 'inconnu', 'an unknown action must stay readable');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never reads a mute like a kick', async () => {
|
||||||
|
// Reported from the moderation log channel: a timeout was filed as a
|
||||||
|
// temporary kick because both labels sat next to each other.
|
||||||
|
const { moderationLabel } = await import('../src/services/moderation/moderation-service.js');
|
||||||
|
|
||||||
|
assert.equal(moderationLabel('mute'), '🔇 Mise en sourdine');
|
||||||
|
assert.equal(moderationLabel('kick'), '👢 Expulsion');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('event modules', () => {
|
describe('event modules', () => {
|
||||||
it('exports a name and a handler', async () => {
|
it('exports a name and a handler', async () => {
|
||||||
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
|
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { after, before, beforeEach, describe, it } from 'node:test';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Importing Gitea issues onto a board (M18).
|
||||||
|
*
|
||||||
|
* A stand-in forge answers on a real socket, and the environment is set before
|
||||||
|
* the modules that read it are loaded — hence the dynamic imports.
|
||||||
|
*/
|
||||||
|
|
||||||
|
let issues = [];
|
||||||
|
|
||||||
|
const forge = createServer((request, response) => {
|
||||||
|
if (!request.url.includes('/issues')) {
|
||||||
|
response.writeHead(404).end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const state = new URL(request.url, 'http://x').searchParams.get('state');
|
||||||
|
const body = state === 'all' ? issues : issues.filter((issue) => issue.state === 'open');
|
||||||
|
|
||||||
|
response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(body));
|
||||||
|
});
|
||||||
|
await new Promise((resolve) => forge.listen(0, '127.0.0.1', resolve));
|
||||||
|
|
||||||
|
process.env.GITEA_URL = `http://127.0.0.1:${forge.address().port}`;
|
||||||
|
process.env.GITEA_TOKEN = 'jeton-de-test';
|
||||||
|
process.env.GITEA_OWNER = 'FWS';
|
||||||
|
|
||||||
|
const { closeDatabase, getDatabase, initDatabase } = await import('../src/database/index.js');
|
||||||
|
const { createBoard, listCards, listColumns } = await import(
|
||||||
|
'../src/database/repositories/project-repository.js'
|
||||||
|
);
|
||||||
|
const { createApiToken } = await import('../src/database/repositories/web-session-repository.js');
|
||||||
|
const { hashToken } = await import('../src/web/auth/session.js');
|
||||||
|
const { createHandler } = await import('../src/web/server.js');
|
||||||
|
|
||||||
|
const TOKEN = 'fws_import-test';
|
||||||
|
|
||||||
|
describe('importing issues from Gitea', () => {
|
||||||
|
let app;
|
||||||
|
let board;
|
||||||
|
let columns;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
initDatabase(':memory:');
|
||||||
|
createApiToken({ name: 'import', tokenHash: hashToken(TOKEN), prefix: 'fws_impo', accessLevel: 3 });
|
||||||
|
app = createServer(createHandler({ client: null }));
|
||||||
|
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
|
||||||
|
});
|
||||||
|
|
||||||
|
after(async () => {
|
||||||
|
await new Promise((resolve) => app.close(resolve));
|
||||||
|
await new Promise((resolve) => forge.close(resolve));
|
||||||
|
closeDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
getDatabase().exec('DELETE FROM project_boards;');
|
||||||
|
board = createBoard({ guildId: '', scope: 'org', name: 'Organisation' });
|
||||||
|
columns = listColumns(board.id);
|
||||||
|
|
||||||
|
issues = [
|
||||||
|
{ number: 1, title: 'Corriger le démarrage', state: 'open', body: 'Détails', labels: [{ name: 'bug' }] },
|
||||||
|
{ number: 2, title: 'Documenter le wiki', state: 'open', body: null, labels: [] },
|
||||||
|
{ number: 3, title: 'Ancienne demande', state: 'closed', body: null, labels: [] },
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
const call = (path, body) =>
|
||||||
|
fetch(`http://127.0.0.1:${app.address().port}${path}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
const importInto = (body = {}) =>
|
||||||
|
call(`/api/projects/${board.id}/import`, { repository: 'FWS/FWS-Arch', ...body }).then((response) =>
|
||||||
|
response.json(),
|
||||||
|
);
|
||||||
|
|
||||||
|
it('creates one card per open issue', async () => {
|
||||||
|
const result = await importInto();
|
||||||
|
|
||||||
|
assert.equal(result.imported, 2);
|
||||||
|
assert.equal(result.column, 'À faire');
|
||||||
|
assert.deepEqual(
|
||||||
|
listCards(board.id)
|
||||||
|
.map((card) => card.title)
|
||||||
|
.sort(),
|
||||||
|
['Corriger le démarrage', 'Documenter le wiki'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records the issue each card came from', async () => {
|
||||||
|
await importInto();
|
||||||
|
const card = listCards(board.id).find((entry) => entry.title === 'Corriger le démarrage');
|
||||||
|
|
||||||
|
assert.equal(card.issue_ref, 'FWS/FWS-Arch#1');
|
||||||
|
assert.deepEqual(card.labels, ['bug']);
|
||||||
|
assert.match(card.body, /Détails/);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** The button has to survive being pressed twice. */
|
||||||
|
it('skips what is already on the board', async () => {
|
||||||
|
await importInto();
|
||||||
|
const second = await importInto();
|
||||||
|
|
||||||
|
assert.equal(second.imported, 0);
|
||||||
|
assert.equal(second.skipped, 2);
|
||||||
|
assert.equal(listCards(board.id).length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('brings the closed issues in when asked', async () => {
|
||||||
|
const result = await importInto({ state: 'all' });
|
||||||
|
assert.equal(result.imported, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('imports into the chosen column', async () => {
|
||||||
|
const review = columns.find((column) => column.name === 'En revue');
|
||||||
|
const result = await importInto({ columnId: review.id });
|
||||||
|
|
||||||
|
assert.equal(result.column, 'En revue');
|
||||||
|
assert.ok(listCards(board.id).every((card) => card.column_id === review.id));
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Importing straight into « Terminé » is never what anyone means. */
|
||||||
|
it('never imports into a column of another board', async () => {
|
||||||
|
const other = createBoard({ guildId: '', scope: 'repo', repository: 'FWS/site', name: 'Site' });
|
||||||
|
const foreign = listColumns(other.id)[0];
|
||||||
|
|
||||||
|
const result = await importInto({ columnId: foreign.id });
|
||||||
|
assert.equal(result.column, 'À faire');
|
||||||
|
assert.equal(listCards(other.id).length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports what it found even when nothing is new', async () => {
|
||||||
|
issues = [];
|
||||||
|
const result = await importInto();
|
||||||
|
|
||||||
|
assert.equal(result.found, 0);
|
||||||
|
assert.equal(result.imported, 0);
|
||||||
|
assert.equal(result.repository, 'FWS/FWS-Arch');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -325,6 +325,23 @@ describe('projects over HTTP', () => {
|
|||||||
assert.equal(response.status, 400);
|
assert.equal(response.status, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('refuses to import when Gitea is not configured', async () => {
|
||||||
|
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
|
||||||
|
const response = await call('POST', `/api/projects/${created.id}/import`, {
|
||||||
|
repository: 'FWS/FWS-Arch',
|
||||||
|
});
|
||||||
|
|
||||||
|
// `GITEA_TOKEN` is unset in the tests, so the import cannot run.
|
||||||
|
assert.equal(response.status, 400);
|
||||||
|
assert.match((await response.json()).error, /Gitea/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a repository that is not owner/name', async () => {
|
||||||
|
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
|
||||||
|
const response = await call('POST', `/api/projects/${created.id}/import`, { repository: 'nope' });
|
||||||
|
assert.equal(response.status, 400);
|
||||||
|
});
|
||||||
|
|
||||||
it('asks for the name before deleting a board', async () => {
|
it('asks for the name before deleting a board', async () => {
|
||||||
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
|
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,11 @@ import {
|
|||||||
removeNotificationChannel,
|
removeNotificationChannel,
|
||||||
setNotificationChannel,
|
setNotificationChannel,
|
||||||
} from '../src/database/repositories/notification-repository.js';
|
} from '../src/database/repositories/notification-repository.js';
|
||||||
|
import {
|
||||||
|
clearRulesMessage,
|
||||||
|
getRulesMessage,
|
||||||
|
setRulesMessage,
|
||||||
|
} from '../src/database/repositories/rules-repository.js';
|
||||||
import {
|
import {
|
||||||
castVote,
|
castVote,
|
||||||
closePoll,
|
closePoll,
|
||||||
@@ -29,7 +34,7 @@ import {
|
|||||||
|
|
||||||
const reset = () =>
|
const reset = () =>
|
||||||
getDatabase().exec(
|
getDatabase().exec(
|
||||||
'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;',
|
'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels; DELETE FROM rules_messages;',
|
||||||
);
|
);
|
||||||
|
|
||||||
describe('ticket repository', () => {
|
describe('ticket repository', () => {
|
||||||
@@ -187,3 +192,25 @@ describe('notification repository', () => {
|
|||||||
assert.equal(removeNotificationChannel('g', 'release'), 0);
|
assert.equal(removeNotificationChannel('g', 'release'), 0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('rules repository', () => {
|
||||||
|
before(() => initDatabase(':memory:'));
|
||||||
|
after(() => closeDatabase());
|
||||||
|
beforeEach(reset);
|
||||||
|
|
||||||
|
it('keeps one rules message per guild and replaces it', () => {
|
||||||
|
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm1', updatedBy: 'mod' });
|
||||||
|
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm2', updatedBy: 'mod' });
|
||||||
|
|
||||||
|
const stored = getRulesMessage('g');
|
||||||
|
assert.equal(stored.message_id, 'm2');
|
||||||
|
assert.equal(stored.updated_by, 'mod');
|
||||||
|
assert.equal(getRulesMessage('other'), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forgets the message when it is cleared', () => {
|
||||||
|
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm1' });
|
||||||
|
assert.equal(clearRulesMessage('g'), 1);
|
||||||
|
assert.equal(getRulesMessage('g'), null);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { after, before, beforeEach, describe, it } from 'node:test';
|
||||||
|
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
||||||
|
import { publishRules, rulesStatus } from '../src/services/rules/rules-service.js';
|
||||||
|
|
||||||
|
// The dashboard relies on `CHANNEL_RULES_ID`, which no CI run declares, so the
|
||||||
|
// channel is passed explicitly here rather than read from the environment.
|
||||||
|
const RULES_CHANNEL = '1234567890123456789';
|
||||||
|
|
||||||
|
/** A Discord client reduced to what saving the rules touches. */
|
||||||
|
function harness({ pinFails = false, notEditable = false } = {}) {
|
||||||
|
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 = {
|
||||||
|
isSendable: () => true,
|
||||||
|
async send(payload) {
|
||||||
|
const id = `message-${state.sent.length + 1}`;
|
||||||
|
state.sent.push({ id, payload });
|
||||||
|
state.messages.set(id, { id, editable: !notEditable });
|
||||||
|
return {
|
||||||
|
...withEdit({ id, url: `https://discord.test/${id}` }),
|
||||||
|
pin: async () => {
|
||||||
|
if (pinFails) throw new Error('Missing Permissions');
|
||||||
|
state.pinned.push(id);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
messages: {
|
||||||
|
fetch: async (id) => {
|
||||||
|
const message = state.messages.get(id);
|
||||||
|
return message ? withEdit(message) : null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return { state, client: { channels: { fetch: async () => channel } } };
|
||||||
|
}
|
||||||
|
|
||||||
|
const publish = (client, markdown = '## Règlement\n\n1. Reste.bg') =>
|
||||||
|
publishRules(client, { guildId: 'g', markdown, actorId: 'mod', channelId: RULES_CHANNEL });
|
||||||
|
|
||||||
|
const description = (entry) => entry.payload.embeds[0].toJSON().description;
|
||||||
|
|
||||||
|
describe('rules service', () => {
|
||||||
|
before(() => initDatabase(':memory:'));
|
||||||
|
after(() => closeDatabase());
|
||||||
|
beforeEach(() => getDatabase().exec('DELETE FROM rules_messages;'));
|
||||||
|
|
||||||
|
it('sends and pins the rules the first time', async () => {
|
||||||
|
const { state, client } = harness();
|
||||||
|
|
||||||
|
const result = await publish(client, '**Pas de contenu illégal.**');
|
||||||
|
|
||||||
|
assert.equal(state.sent.length, 1);
|
||||||
|
assert.equal(description(state.sent[0]), '**Pas de contenu illégal.**');
|
||||||
|
assert.deepEqual(state.pinned, ['message-1']);
|
||||||
|
assert.deepEqual({ pinned: result.pinned, edited: result.edited }, { pinned: true, edited: false });
|
||||||
|
assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('edits the published message instead of sending a second one', async () => {
|
||||||
|
const { state, client } = harness();
|
||||||
|
|
||||||
|
await publish(client, 'Version 1');
|
||||||
|
const result = await publish(client, 'Version 2');
|
||||||
|
|
||||||
|
assert.equal(state.sent.length, 1, 'a second message was sent');
|
||||||
|
assert.deepEqual(state.edited, [{ id: 'message-1', description: 'Version 2' }]);
|
||||||
|
assert.equal(result.messageId, 'message-1', 'the message id must not change');
|
||||||
|
assert.equal(result.edited, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends a new one when the previous message is gone', async () => {
|
||||||
|
const { state, client } = harness();
|
||||||
|
|
||||||
|
await publish(client, 'Version 1');
|
||||||
|
state.messages.clear();
|
||||||
|
|
||||||
|
const result = await publish(client, 'Version 2');
|
||||||
|
|
||||||
|
assert.equal(state.sent.length, 2);
|
||||||
|
assert.equal(result.edited, false);
|
||||||
|
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 () => {
|
||||||
|
const { state, client } = harness({ pinFails: true });
|
||||||
|
|
||||||
|
const result = await publish(client);
|
||||||
|
|
||||||
|
assert.deepEqual(state.pinned, []);
|
||||||
|
assert.equal(result.pinned, false);
|
||||||
|
assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses an empty or oversized regulation', async () => {
|
||||||
|
const { client } = harness();
|
||||||
|
|
||||||
|
await assert.rejects(() => publish(client, ' '), /vide/);
|
||||||
|
await assert.rejects(() => publish(client, 'a'.repeat(4001)), /4000 caractères/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses to publish without a rules channel', async () => {
|
||||||
|
const { client } = harness();
|
||||||
|
|
||||||
|
await assert.rejects(
|
||||||
|
() => publishRules(client, { guildId: 'g', markdown: 'Règlement', channelId: '' }),
|
||||||
|
/CHANNEL_RULES_ID/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports the configured channel to the dashboard', () => {
|
||||||
|
assert.deepEqual(rulesStatus('g', RULES_CHANNEL), {
|
||||||
|
channelId: RULES_CHANNEL,
|
||||||
|
configured: true,
|
||||||
|
messageId: null,
|
||||||
|
publishedAt: null,
|
||||||
|
publishedBy: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { after, before, beforeEach, describe, it } from 'node:test';
|
||||||
|
import { ACCESS_LEVELS } from '../src/config/constants.js';
|
||||||
|
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
||||||
|
import {
|
||||||
|
addCard,
|
||||||
|
createBoard,
|
||||||
|
listAssignees,
|
||||||
|
listCardsForAssignee,
|
||||||
|
listColumns,
|
||||||
|
} from '../src/database/repositories/project-repository.js';
|
||||||
|
import { createApiToken } from '../src/database/repositories/web-session-repository.js';
|
||||||
|
import { hashToken } from '../src/web/auth/session.js';
|
||||||
|
import { createHandler } from '../src/web/server.js';
|
||||||
|
|
||||||
|
/** « Mes tâches » — cards gathered across every board (M19). */
|
||||||
|
|
||||||
|
const GUILD = '';
|
||||||
|
const ME = '111';
|
||||||
|
const OTHER = '222';
|
||||||
|
|
||||||
|
/** Whole days from today, in the `YYYY-MM-DD` shape the cards store. */
|
||||||
|
const dayOffset = (days) => {
|
||||||
|
const date = new Date();
|
||||||
|
date.setDate(date.getDate() + days);
|
||||||
|
return date.toISOString().slice(0, 10);
|
||||||
|
};
|
||||||
|
|
||||||
|
let board;
|
||||||
|
let columns;
|
||||||
|
|
||||||
|
function seed() {
|
||||||
|
getDatabase().exec('DELETE FROM project_boards;');
|
||||||
|
board = createBoard({ guildId: GUILD, scope: 'repo', repository: 'FWS/FWS-Arch', name: 'FWS Arch' });
|
||||||
|
columns = listColumns(board.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const put = (title, overrides = {}) =>
|
||||||
|
addCard({ boardId: board.id, columnId: columns[0].id, title, ...overrides });
|
||||||
|
|
||||||
|
describe('cards gathered by assignee', () => {
|
||||||
|
before(() => initDatabase(':memory:'));
|
||||||
|
after(() => closeDatabase());
|
||||||
|
beforeEach(seed);
|
||||||
|
|
||||||
|
it('carries the column each card sits in', () => {
|
||||||
|
put('Une tâche', { assigneeId: ME });
|
||||||
|
const [task] = listCardsForAssignee(GUILD, ME);
|
||||||
|
|
||||||
|
assert.equal(task.column_name, 'À faire');
|
||||||
|
assert.equal(task.column_is_done, false);
|
||||||
|
assert.equal(task.board_name, 'FWS Arch');
|
||||||
|
assert.equal(task.repository, 'FWS/FWS-Arch');
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Finishing a card from the list is one move, so the target travels with it. */
|
||||||
|
it('names the column that would finish the card', () => {
|
||||||
|
put('Une tâche', { assigneeId: ME });
|
||||||
|
const done = columns.at(-1);
|
||||||
|
|
||||||
|
assert.equal(listCardsForAssignee(GUILD, ME)[0].done_column_id, done.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks a card already in the finished column', () => {
|
||||||
|
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'Livrée', assigneeId: ME });
|
||||||
|
assert.equal(listCardsForAssignee(GUILD, ME)[0].column_is_done, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('orders by deadline, undated last', () => {
|
||||||
|
put('plus tard', { assigneeId: ME, dueAt: dayOffset(9) });
|
||||||
|
put('sans date', { assigneeId: ME });
|
||||||
|
put('demain', { assigneeId: ME, dueAt: dayOffset(1) });
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
listCardsForAssignee(GUILD, ME).map((task) => task.title),
|
||||||
|
['demain', 'plus tard', 'sans date'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores what belongs to someone else', () => {
|
||||||
|
put('à moi', { assigneeId: ME });
|
||||||
|
put('à l’autre', { assigneeId: OTHER });
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
listCardsForAssignee(GUILD, ME).map((task) => task.title),
|
||||||
|
['à moi'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists who carries cards, finished ones excluded from the open count', () => {
|
||||||
|
put('ouverte', { assigneeId: ME });
|
||||||
|
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'close', assigneeId: ME });
|
||||||
|
put('autre', { assigneeId: OTHER });
|
||||||
|
|
||||||
|
const [mine] = listAssignees(GUILD).filter((entry) => entry.assigneeId === ME);
|
||||||
|
assert.equal(mine.total, 2);
|
||||||
|
assert.equal(mine.open, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves unassigned cards out of the roster', () => {
|
||||||
|
put('orpheline');
|
||||||
|
assert.deepEqual(listAssignees(GUILD), []);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('my tasks over HTTP', () => {
|
||||||
|
const TOKEN = 'fws_tasks-test';
|
||||||
|
const ANONYMOUS = 'fws_tasks-anon';
|
||||||
|
let app;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
initDatabase(':memory:');
|
||||||
|
createApiToken({
|
||||||
|
name: 'tasks',
|
||||||
|
tokenHash: hashToken(TOKEN),
|
||||||
|
prefix: TOKEN.slice(0, 12),
|
||||||
|
accessLevel: ACCESS_LEVELS.STAFF,
|
||||||
|
createdBy: ME,
|
||||||
|
});
|
||||||
|
// A token with nobody behind it: there is no « me » to answer for.
|
||||||
|
createApiToken({
|
||||||
|
name: 'anonyme',
|
||||||
|
tokenHash: hashToken(ANONYMOUS),
|
||||||
|
prefix: ANONYMOUS.slice(0, 12),
|
||||||
|
accessLevel: ACCESS_LEVELS.STAFF,
|
||||||
|
});
|
||||||
|
|
||||||
|
app = createServer(createHandler({ client: null, setupOnly: false }));
|
||||||
|
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
await new Promise((resolve) => app.close(resolve));
|
||||||
|
closeDatabase();
|
||||||
|
});
|
||||||
|
beforeEach(seed);
|
||||||
|
|
||||||
|
const call = (path, token = TOKEN) =>
|
||||||
|
fetch(`http://127.0.0.1:${app.address().port}${path}`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
|
||||||
|
const tasks = (query = '') => call(`/api/me/tasks${query}`).then((response) => response.json());
|
||||||
|
|
||||||
|
it('refuses a visitor without a session', async () => {
|
||||||
|
const response = await fetch(`http://127.0.0.1:${app.address().port}/api/me/tasks`);
|
||||||
|
assert.equal(response.status, 401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers with the caller’s own cards', async () => {
|
||||||
|
put('à moi', { assigneeId: ME });
|
||||||
|
put('à l’autre', { assigneeId: OTHER });
|
||||||
|
|
||||||
|
const body = await tasks();
|
||||||
|
assert.equal(body.self, true);
|
||||||
|
assert.equal(body.assigneeId, ME);
|
||||||
|
assert.deepEqual(
|
||||||
|
body.cards.map((task) => task.title),
|
||||||
|
['à moi'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts what is late, due today and finished', async () => {
|
||||||
|
put('en retard', { assigneeId: ME, dueAt: dayOffset(-2) });
|
||||||
|
put('aujourd’hui', { assigneeId: ME, dueAt: dayOffset(0) });
|
||||||
|
put('plus tard', { assigneeId: ME, dueAt: dayOffset(30) });
|
||||||
|
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'faite', assigneeId: ME });
|
||||||
|
|
||||||
|
const { counts } = await tasks();
|
||||||
|
assert.deepEqual(counts, { total: 4, open: 3, done: 1, overdue: 1, dueToday: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
/** A finished card must not be counted as late, however old its deadline. */
|
||||||
|
it('never calls a finished card late', async () => {
|
||||||
|
addCard({
|
||||||
|
boardId: board.id,
|
||||||
|
columnId: columns.at(-1).id,
|
||||||
|
title: 'livrée en retard',
|
||||||
|
assigneeId: ME,
|
||||||
|
dueAt: dayOffset(-40),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { counts } = await tasks();
|
||||||
|
assert.equal(counts.overdue, 0);
|
||||||
|
assert.equal(counts.done, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tells the page where each card lives and how to finish it', async () => {
|
||||||
|
put('une carte', { assigneeId: ME });
|
||||||
|
const [task] = (await tasks()).cards;
|
||||||
|
|
||||||
|
assert.equal(task.boardId, board.id);
|
||||||
|
assert.equal(task.boardName, 'FWS Arch');
|
||||||
|
assert.equal(task.columnName, 'À faire');
|
||||||
|
assert.equal(task.isDone, false);
|
||||||
|
assert.equal(task.doneColumnId, columns.at(-1).id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('looks at another member when asked', async () => {
|
||||||
|
put('à l’autre', { assigneeId: OTHER });
|
||||||
|
|
||||||
|
const body = await tasks(`?assignee=${OTHER}`);
|
||||||
|
assert.equal(body.self, false);
|
||||||
|
assert.equal(body.assigneeId, OTHER);
|
||||||
|
assert.equal(body.cards.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('offers the members who carry cards', async () => {
|
||||||
|
put('à moi', { assigneeId: ME });
|
||||||
|
put('à l’autre', { assigneeId: OTHER });
|
||||||
|
|
||||||
|
const ids = (await tasks()).assignees.map((entry) => entry.assigneeId).sort();
|
||||||
|
assert.deepEqual(ids, [ME, OTHER]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('explains itself when the caller has no identity', async () => {
|
||||||
|
const response = await call('/api/me/tasks', ANONYMOUS);
|
||||||
|
assert.equal(response.status, 400);
|
||||||
|
assert.match((await response.json()).error, /membre/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips the forge when only the counters are wanted', async () => {
|
||||||
|
put('liée', { assigneeId: ME, issueRef: 'FWS/FWS-Arch#1' });
|
||||||
|
|
||||||
|
assert.deepEqual((await tasks('?issues=0')).issues, {});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import { grouped, localPages } from '../src/web/public/core/palette.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command palette, the parts that hold no DOM (M19).
|
||||||
|
*
|
||||||
|
* Both are small and both are the kind of thing that degrades quietly: a
|
||||||
|
* heading above every line, or a page offered to someone who cannot open it.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const result = (kind, title) => ({ kind, title });
|
||||||
|
|
||||||
|
describe('grouping the results', () => {
|
||||||
|
/** The forge returns issues and pull requests interleaved. */
|
||||||
|
it('gathers each kind, however they arrive', () => {
|
||||||
|
const order = grouped([
|
||||||
|
result('issue', 'i1'),
|
||||||
|
result('pull', 'p1'),
|
||||||
|
result('issue', 'i2'),
|
||||||
|
result('pull', 'p2'),
|
||||||
|
]).map((entry) => entry.kind);
|
||||||
|
|
||||||
|
assert.deepEqual(order, ['issue', 'issue', 'pull', 'pull']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the order the server chose inside a group', () => {
|
||||||
|
const titles = grouped([
|
||||||
|
result('card', 'première'),
|
||||||
|
result('page', 'une page'),
|
||||||
|
result('card', 'seconde'),
|
||||||
|
])
|
||||||
|
.filter((entry) => entry.kind === 'card')
|
||||||
|
.map((entry) => entry.title);
|
||||||
|
|
||||||
|
assert.deepEqual(titles, ['première', 'seconde']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('puts the pages first and the members last', () => {
|
||||||
|
const order = grouped([
|
||||||
|
result('member', 'quelqu’un'),
|
||||||
|
result('repository', 'FWS/x'),
|
||||||
|
result('page', 'Dépôts'),
|
||||||
|
]).map((entry) => entry.kind);
|
||||||
|
|
||||||
|
assert.deepEqual(order, ['page', 'repository', 'member']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends an unknown kind to the end rather than dropping it', () => {
|
||||||
|
const order = grouped([result('inconnu', '?'), result('page', 'Dépôts')]).map((entry) => entry.kind);
|
||||||
|
assert.deepEqual(order, ['page', 'inconnu']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('survives an empty answer', () => {
|
||||||
|
assert.deepEqual(grouped([]), []);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('matching the pages locally', () => {
|
||||||
|
const pages = [
|
||||||
|
{ path: '', label: 'Vue d’ensemble', group: 'Pilotage' },
|
||||||
|
{ path: 'tasks', label: 'Mes tâches', group: 'Pilotage' },
|
||||||
|
{ path: 'repos', label: 'Dépôts', group: 'Code' },
|
||||||
|
{ path: 'settings', label: 'Paramètres', group: 'Système' },
|
||||||
|
];
|
||||||
|
|
||||||
|
it('lists everything when nothing is typed', () => {
|
||||||
|
assert.equal(localPages(pages, '').length, pages.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('matches on the label', () => {
|
||||||
|
assert.deepEqual(
|
||||||
|
localPages(pages, 'tâche').map((entry) => entry.title),
|
||||||
|
['Mes tâches'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Typing the section is how people who know the panel navigate it. */
|
||||||
|
it('matches on the group', () => {
|
||||||
|
assert.deepEqual(
|
||||||
|
localPages(pages, 'pilotage').map((entry) => entry.title),
|
||||||
|
['Vue d’ensemble', 'Mes tâches'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('points at the hash route of each page', () => {
|
||||||
|
const [overview] = localPages(pages, 'ensemble');
|
||||||
|
assert.equal(overview.href, '#/');
|
||||||
|
assert.equal(localPages(pages, 'dépôt')[0].href, '#/repos');
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The caller passes only the pages the visitor can see, so a page missing
|
||||||
|
* from that list must never surface — the palette does no filtering of its own.
|
||||||
|
*/
|
||||||
|
it('offers nothing beyond the list it was given', () => {
|
||||||
|
const visible = pages.filter((page) => page.path !== 'settings');
|
||||||
|
assert.deepEqual(localPages(visible, 'paramètres'), []);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { after, before, beforeEach, describe, it } from 'node:test';
|
||||||
|
import { ACCESS_LEVELS } from '../src/config/constants.js';
|
||||||
|
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
||||||
|
import {
|
||||||
|
addCard,
|
||||||
|
createBoard,
|
||||||
|
listColumns,
|
||||||
|
searchCards,
|
||||||
|
} from '../src/database/repositories/project-repository.js';
|
||||||
|
import { createApiToken } from '../src/database/repositories/web-session-repository.js';
|
||||||
|
import { createPage } from '../src/database/repositories/wiki-repository.js';
|
||||||
|
import { hashToken } from '../src/web/auth/session.js';
|
||||||
|
import { createHandler } from '../src/web/server.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Global search behind the command palette (M19).
|
||||||
|
*
|
||||||
|
* Gitea is deliberately left unconfigured here: the point is that the local
|
||||||
|
* sources answer on their own, so a forge that is down costs the palette its
|
||||||
|
* repositories and nothing else.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const GUILD = '';
|
||||||
|
const TOKEN = 'fws_search-test';
|
||||||
|
|
||||||
|
describe('global search', () => {
|
||||||
|
let app;
|
||||||
|
let board;
|
||||||
|
let columns;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
initDatabase(':memory:');
|
||||||
|
createApiToken({
|
||||||
|
name: 'recherche',
|
||||||
|
tokenHash: hashToken(TOKEN),
|
||||||
|
prefix: TOKEN.slice(0, 12),
|
||||||
|
accessLevel: ACCESS_LEVELS.STAFF,
|
||||||
|
});
|
||||||
|
app = createServer(createHandler({ client: null, setupOnly: false }));
|
||||||
|
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
await new Promise((resolve) => app.close(resolve));
|
||||||
|
closeDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
getDatabase().exec('DELETE FROM project_boards; DELETE FROM wiki_pages;');
|
||||||
|
board = createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
|
||||||
|
columns = listColumns(board.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
const search = (term) =>
|
||||||
|
fetch(`http://127.0.0.1:${app.address().port}/api/search?q=${encodeURIComponent(term)}`, {
|
||||||
|
headers: { Authorization: `Bearer ${TOKEN}` },
|
||||||
|
});
|
||||||
|
|
||||||
|
const results = (term) => search(term).then((response) => response.json());
|
||||||
|
|
||||||
|
const card = (title, overrides = {}) =>
|
||||||
|
addCard({ boardId: board.id, columnId: columns[0].id, title, ...overrides });
|
||||||
|
|
||||||
|
const page = (title, overrides = {}) =>
|
||||||
|
createPage({
|
||||||
|
slug: title.toLowerCase().replaceAll(' ', '-'),
|
||||||
|
title,
|
||||||
|
published: true,
|
||||||
|
category: 'Guides',
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a visitor without a session', async () => {
|
||||||
|
const response = await fetch(`http://127.0.0.1:${app.address().port}/api/search?q=test`);
|
||||||
|
assert.equal(response.status, 401);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** One or two letters match half the organization, which helps nobody. */
|
||||||
|
it('stays silent on a term too short to mean anything', async () => {
|
||||||
|
card('Pterodactyl');
|
||||||
|
assert.deepEqual((await results('p')).results, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('finds a card and says which board it is on', async () => {
|
||||||
|
card('Corriger le démarrage');
|
||||||
|
|
||||||
|
const [found] = (await results('démarrage')).results;
|
||||||
|
assert.equal(found.kind, 'card');
|
||||||
|
assert.equal(found.title, 'Corriger le démarrage');
|
||||||
|
assert.equal(found.subtitle, 'Organisation · À faire');
|
||||||
|
assert.equal(found.href, `#/projects/${board.id}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('finds a published wiki page at its public address', async () => {
|
||||||
|
page('Installer FWS Arch', { summary: 'Le guide pas à pas.' });
|
||||||
|
|
||||||
|
const [found] = (await results('Installer')).results;
|
||||||
|
assert.equal(found.kind, 'wiki');
|
||||||
|
assert.equal(found.href, '/wiki/installer-fws-arch');
|
||||||
|
assert.equal(found.external, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves an unpublished page out of the results', async () => {
|
||||||
|
page('Brouillon interne', { published: false });
|
||||||
|
assert.deepEqual((await results('Brouillon')).results, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** The legal pages live at the root, not under /wiki. */
|
||||||
|
it('sends a root page to its own address', async () => {
|
||||||
|
page('Conditions', { slug: 'terms-of-service' });
|
||||||
|
|
||||||
|
const [found] = (await results('Conditions')).results;
|
||||||
|
assert.equal(found.href, '/terms-of-service');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gathers several kinds under one answer', async () => {
|
||||||
|
card('Sauvegarde automatique');
|
||||||
|
page('Sauvegarde et restauration');
|
||||||
|
|
||||||
|
const kinds = (await results('Sauvegarde')).results.map((entry) => entry.kind);
|
||||||
|
assert.deepEqual(kinds.slice().sort(), ['card', 'wiki']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('puts the local results first', async () => {
|
||||||
|
card('Wiki à relire');
|
||||||
|
page('Wiki public');
|
||||||
|
|
||||||
|
assert.equal((await results('Wiki')).results[0].kind, 'card');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers with nothing rather than failing when nothing matches', async () => {
|
||||||
|
const body = await results('introuvable-xyz');
|
||||||
|
assert.deepEqual(body.results, []);
|
||||||
|
assert.equal(body.term, 'introuvable-xyz');
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Gitea is not configured here; the palette must still answer. */
|
||||||
|
it('answers although the forge is absent', async () => {
|
||||||
|
card('Déploiement');
|
||||||
|
const response = await search('Déploiement');
|
||||||
|
|
||||||
|
assert.equal(response.status, 200);
|
||||||
|
assert.equal((await response.json()).results.length, 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/** The query behind the palette's card results, exercised without HTTP. */
|
||||||
|
describe('searching the cards directly', () => {
|
||||||
|
let board;
|
||||||
|
let columns;
|
||||||
|
|
||||||
|
before(() => initDatabase(':memory:'));
|
||||||
|
after(() => closeDatabase());
|
||||||
|
beforeEach(() => {
|
||||||
|
getDatabase().exec('DELETE FROM project_boards;');
|
||||||
|
board = createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
|
||||||
|
columns = listColumns(board.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
const put = (title, overrides = {}) =>
|
||||||
|
addCard({ boardId: board.id, columnId: columns[0].id, title, ...overrides });
|
||||||
|
|
||||||
|
it('matches the title', () => {
|
||||||
|
put('Corriger le démarrage');
|
||||||
|
put('Documenter le wiki');
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
searchCards(GUILD, 'démarrage').map((entry) => entry.title),
|
||||||
|
['Corriger le démarrage'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('matches the body, the labels and the issue', () => {
|
||||||
|
put('Sans rapport', { body: 'contient pterodactyl' });
|
||||||
|
put('Étiquetée', { labels: ['urgent'] });
|
||||||
|
put('Liée', { issueRef: 'FWS/FWS-Arch#42' });
|
||||||
|
|
||||||
|
assert.equal(searchCards(GUILD, 'pterodactyl').length, 1);
|
||||||
|
assert.equal(searchCards(GUILD, 'urgent').length, 1);
|
||||||
|
assert.equal(searchCards(GUILD, '#42').length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** A finished card is still a result, just never the first one. */
|
||||||
|
it('puts the finished cards last', () => {
|
||||||
|
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'sujet fini' });
|
||||||
|
put('sujet en cours');
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
searchCards(GUILD, 'sujet').map((entry) => entry.title),
|
||||||
|
['sujet en cours', 'sujet fini'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('honours the limit', () => {
|
||||||
|
for (let index = 0; index < 5; index += 1) put(`sujet ${index}`);
|
||||||
|
assert.equal(searchCards(GUILD, 'sujet', 2).length, 2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { after, before, describe, it } from 'node:test';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `WEB_PUBLIC_STATUS=false` (M19).
|
||||||
|
*
|
||||||
|
* The switch decides what an anonymous visitor may learn about the
|
||||||
|
* infrastructure, so it gets a file of its own: the flag is read when the
|
||||||
|
* configuration module loads, and a suite cannot hold both answers at once.
|
||||||
|
*/
|
||||||
|
|
||||||
|
process.env.WEB_PUBLIC_STATUS = 'false';
|
||||||
|
|
||||||
|
const { closeDatabase, initDatabase } = await import('../src/database/index.js');
|
||||||
|
const { createHandler } = await import('../src/web/server.js');
|
||||||
|
|
||||||
|
describe('status page turned off', () => {
|
||||||
|
let app;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
initDatabase(':memory:');
|
||||||
|
app = createServer(createHandler({ client: null, setupOnly: false }));
|
||||||
|
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
await new Promise((resolve) => app.close(resolve));
|
||||||
|
closeDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
const call = (path) => fetch(`http://127.0.0.1:${app.address().port}${path}`);
|
||||||
|
|
||||||
|
it('does not serve the page', async () => {
|
||||||
|
const response = await call('/status');
|
||||||
|
assert.equal(response.status, 404);
|
||||||
|
assert.doesNotMatch(await response.text(), /État des services/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not answer in JSON either', async () => {
|
||||||
|
assert.equal((await call('/api/status')).status, 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves the health probe alone', async () => {
|
||||||
|
assert.equal((await call('/api/health')).status, 200);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { after, before, beforeEach, describe, it } from 'node:test';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public status page (M19).
|
||||||
|
*
|
||||||
|
* The guild id is set before the modules that read it are loaded — hence the
|
||||||
|
* dynamic imports, the same arrangement the Gitea import test uses.
|
||||||
|
*/
|
||||||
|
|
||||||
|
process.env.DISCORD_GUILD_ID = '900000000000000000';
|
||||||
|
|
||||||
|
const GUILD = process.env.DISCORD_GUILD_ID;
|
||||||
|
|
||||||
|
const { closeDatabase, getDatabase, initDatabase } = await import('../src/database/index.js');
|
||||||
|
const { createDeployment, finishDeployment } =
|
||||||
|
await import('../src/database/repositories/deploy-repository.js');
|
||||||
|
const { renderStatus } = await import('../src/web/services/status-render.js');
|
||||||
|
const { resetStatusCache, statusSnapshot } = await import('../src/web/services/status-service.js');
|
||||||
|
const { createHandler } = await import('../src/web/server.js');
|
||||||
|
|
||||||
|
const snapshot = (overrides = {}) => ({
|
||||||
|
bot: {
|
||||||
|
online: true,
|
||||||
|
state: 'ok',
|
||||||
|
uptimeMs: 3_600_000,
|
||||||
|
startedAt: new Date().toISOString(),
|
||||||
|
version: '1.2.3',
|
||||||
|
pingMs: 42,
|
||||||
|
},
|
||||||
|
environments: [],
|
||||||
|
releases: [],
|
||||||
|
links: {},
|
||||||
|
generatedAt: new Date().toISOString(),
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const deploy = ({ environment, repository, status, releaseTag = null }) => {
|
||||||
|
const created = createDeployment({
|
||||||
|
guildId: GUILD,
|
||||||
|
targetName: environment,
|
||||||
|
repository,
|
||||||
|
environment,
|
||||||
|
releaseTag,
|
||||||
|
});
|
||||||
|
finishDeployment(created.id, { status });
|
||||||
|
return created;
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('status page rendering', () => {
|
||||||
|
it('says everything works when the bot answers', () => {
|
||||||
|
const html = renderStatus(snapshot());
|
||||||
|
assert.match(html, /Tous les services fonctionnent/);
|
||||||
|
assert.match(html, /status-banner-ok/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leads with the outage when the bot is down', () => {
|
||||||
|
const html = renderStatus(snapshot({ bot: { ...snapshot().bot, online: false, state: 'down' } }));
|
||||||
|
assert.match(html, /Le bot est hors ligne/);
|
||||||
|
assert.match(html, /status-banner-down/);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** A green headline above a failed deployment is how a status page loses its point. */
|
||||||
|
it('refuses to look healthy while a deployment has failed', () => {
|
||||||
|
const html = renderStatus(
|
||||||
|
snapshot({
|
||||||
|
environments: [
|
||||||
|
{
|
||||||
|
environment: 'production',
|
||||||
|
repository: 'FWS/x',
|
||||||
|
status: 'failed',
|
||||||
|
tone: 'down',
|
||||||
|
releaseTag: null,
|
||||||
|
finishedAt: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.match(html, /déploiement en échec/);
|
||||||
|
assert.match(html, /status-banner-busy/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('carries no script at all', () => {
|
||||||
|
assert.doesNotMatch(renderStatus(snapshot()), /<script/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refreshes itself without one', () => {
|
||||||
|
assert.match(renderStatus(snapshot()), /http-equiv="refresh"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('escapes what it is given', () => {
|
||||||
|
const html = renderStatus(
|
||||||
|
snapshot({
|
||||||
|
environments: [
|
||||||
|
{
|
||||||
|
environment: '<img src=x onerror=alert(1)>',
|
||||||
|
repository: null,
|
||||||
|
status: 'success',
|
||||||
|
tone: 'ok',
|
||||||
|
releaseTag: null,
|
||||||
|
finishedAt: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.doesNotMatch(html, /<img src=x/);
|
||||||
|
assert.match(html, /<img src=x/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a private repository nameless rather than hiding the environment', () => {
|
||||||
|
const html = renderStatus(
|
||||||
|
snapshot({
|
||||||
|
environments: [
|
||||||
|
{
|
||||||
|
environment: 'staging',
|
||||||
|
repository: null,
|
||||||
|
status: 'success',
|
||||||
|
tone: 'ok',
|
||||||
|
releaseTag: 'v1',
|
||||||
|
finishedAt: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.match(html, /staging/);
|
||||||
|
assert.match(html, /privé/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('points at the machine-readable version', () => {
|
||||||
|
assert.match(renderStatus(snapshot()), /\/api\/status/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('status snapshot', () => {
|
||||||
|
before(() => initDatabase(':memory:'));
|
||||||
|
after(() => closeDatabase());
|
||||||
|
beforeEach(() => {
|
||||||
|
getDatabase().exec('DELETE FROM deployments;');
|
||||||
|
resetStatusCache();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports the bot as down when there is no client', async () => {
|
||||||
|
const data = await statusSnapshot({ client: null, startedAt: Date.now() });
|
||||||
|
assert.equal(data.bot.online, false);
|
||||||
|
assert.equal(data.bot.state, 'down');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the last deployment of each environment', async () => {
|
||||||
|
deploy({ environment: 'production', repository: 'FWS/bot', status: 'success', releaseTag: 'v1.0.0' });
|
||||||
|
deploy({ environment: 'staging', repository: 'FWS/bot', status: 'failed' });
|
||||||
|
|
||||||
|
const { environments } = await statusSnapshot({ client: null });
|
||||||
|
const names = environments.map((entry) => entry.environment).sort();
|
||||||
|
|
||||||
|
assert.deepEqual(names, ['production', 'staging']);
|
||||||
|
assert.equal(environments.find((entry) => entry.environment === 'staging').tone, 'down');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('names a tone for every deployment state', async () => {
|
||||||
|
deploy({ environment: 'production', repository: 'FWS/bot', status: 'running' });
|
||||||
|
const [entry] = (await statusSnapshot({ client: null })).environments;
|
||||||
|
|
||||||
|
assert.equal(entry.tone, 'busy');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('status over HTTP', () => {
|
||||||
|
let app;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
initDatabase(':memory:');
|
||||||
|
resetStatusCache();
|
||||||
|
app = createServer(createHandler({ client: null, setupOnly: false }));
|
||||||
|
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
await new Promise((resolve) => app.close(resolve));
|
||||||
|
closeDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
const call = (path) => fetch(`http://127.0.0.1:${app.address().port}${path}`);
|
||||||
|
|
||||||
|
it('serves the page to a visitor with no session', async () => {
|
||||||
|
const response = await call('/status');
|
||||||
|
const html = await response.text();
|
||||||
|
|
||||||
|
assert.equal(response.status, 200);
|
||||||
|
assert.match(response.headers.get('content-type'), /text\/html/);
|
||||||
|
assert.match(html, /État des services/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forbids scripts in its own headers', async () => {
|
||||||
|
const policy = (await call('/status')).headers.get('content-security-policy');
|
||||||
|
assert.match(policy, /script-src 'none'/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers the same in JSON, without a session', async () => {
|
||||||
|
const response = await call('/api/status');
|
||||||
|
const body = await response.json();
|
||||||
|
|
||||||
|
assert.equal(response.status, 200);
|
||||||
|
assert.equal(typeof body.bot.online, 'boolean');
|
||||||
|
assert.ok(Array.isArray(body.environments));
|
||||||
|
assert.ok(Array.isArray(body.releases));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tolerates a trailing slash', async () => {
|
||||||
|
assert.equal((await call('/status/')).status, 200);
|
||||||
|
});
|
||||||
|
});
|
||||||
+75
-12
@@ -127,19 +127,19 @@ describe('wiki seeding', () => {
|
|||||||
|
|
||||||
it('creates the welcome page and both legal pages', () => {
|
it('creates the welcome page and both legal pages', () => {
|
||||||
assert.equal(seedWiki(), 3);
|
assert.equal(seedWiki(), 3);
|
||||||
assert.ok(getPageBySlug('conditions-utilisation').published);
|
assert.ok(getPageBySlug('terms-of-service').published);
|
||||||
assert.ok(getPageBySlug('politique-confidentialite').published);
|
assert.ok(getPageBySlug('privacy-policy').published);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('marks the legal pages as protected', () => {
|
it('marks the legal pages as protected', () => {
|
||||||
seedWiki();
|
seedWiki();
|
||||||
assert.equal(getPageBySlug('politique-confidentialite').protected, true);
|
assert.equal(getPageBySlug('privacy-policy').protected, true);
|
||||||
assert.equal(getPageBySlug('accueil').protected, false);
|
assert.equal(getPageBySlug('accueil').protected, false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('names the Swiss law it is written against', () => {
|
it('names the Swiss law it is written against', () => {
|
||||||
seedWiki();
|
seedWiki();
|
||||||
const privacy = getPageBySlug('politique-confidentialite').content;
|
const privacy = getPageBySlug('privacy-policy').content;
|
||||||
assert.match(privacy, /LPD/);
|
assert.match(privacy, /LPD/);
|
||||||
assert.match(privacy, /PFPDT/);
|
assert.match(privacy, /PFPDT/);
|
||||||
assert.match(privacy, /art\. 25 LPD/);
|
assert.match(privacy, /art\. 25 LPD/);
|
||||||
@@ -147,18 +147,18 @@ describe('wiki seeding', () => {
|
|||||||
|
|
||||||
it('never overwrites what the organisation has written', () => {
|
it('never overwrites what the organisation has written', () => {
|
||||||
seedWiki();
|
seedWiki();
|
||||||
updatePage(getPageBySlug('conditions-utilisation').id, { content: 'Notre propre texte.' });
|
updatePage(getPageBySlug('terms-of-service').id, { content: 'Notre propre texte.' });
|
||||||
|
|
||||||
assert.equal(seedWiki(), 0);
|
assert.equal(seedWiki(), 0);
|
||||||
assert.equal(getPageBySlug('conditions-utilisation').content, 'Notre propre texte.');
|
assert.equal(getPageBySlug('terms-of-service').content, 'Notre propre texte.');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('brings a deleted legal page back, but not the welcome one', () => {
|
it('brings a deleted legal page back, but not the welcome one', () => {
|
||||||
seedWiki();
|
seedWiki();
|
||||||
getDatabase().exec("DELETE FROM wiki_pages WHERE slug IN ('politique-confidentialite', 'accueil')");
|
getDatabase().exec("DELETE FROM wiki_pages WHERE slug IN ('privacy-policy', 'accueil')");
|
||||||
|
|
||||||
assert.equal(seedWiki(), 1);
|
assert.equal(seedWiki(), 1);
|
||||||
assert.ok(getPageBySlug('politique-confidentialite'));
|
assert.ok(getPageBySlug('privacy-policy'));
|
||||||
assert.equal(getPageBySlug('accueil'), null);
|
assert.equal(getPageBySlug('accueil'), null);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -188,7 +188,7 @@ describe('wiki over HTTP', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('serves a published page without a session', async () => {
|
it('serves a published page without a session', async () => {
|
||||||
const response = await get('/api/wiki/pages/conditions-utilisation');
|
const response = await get('/api/wiki/pages/terms-of-service');
|
||||||
assert.equal(response.status, 200);
|
assert.equal(response.status, 200);
|
||||||
assert.match((await response.json()).content, /droit suisse/);
|
assert.match((await response.json()).content, /droit suisse/);
|
||||||
});
|
});
|
||||||
@@ -203,13 +203,76 @@ describe('wiki over HTTP', () => {
|
|||||||
assert.ok(Array.isArray(body.results));
|
assert.ok(Array.isArray(body.results));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('serves the legal pages at the root, where platforms expect them', async () => {
|
||||||
|
for (const path of ['/terms-of-service', '/privacy-policy']) {
|
||||||
|
const response = await get(path);
|
||||||
|
assert.equal(response.status, 200, `${path} ne répond pas`);
|
||||||
|
assert.match(response.headers.get('content-type'), /text\/html/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The point of the whole exercise: whoever checks these links before
|
||||||
|
* approving an application does not run scripts.
|
||||||
|
*/
|
||||||
|
it('delivers the legal text without any script', async () => {
|
||||||
|
const terms = await get('/terms-of-service').then((response) => response.text());
|
||||||
|
const privacy = await get('/privacy-policy').then((response) => response.text());
|
||||||
|
|
||||||
|
assert.match(terms, /droit suisse/, 'les conditions ne sont pas dans le HTML');
|
||||||
|
assert.match(privacy, /LPD/, 'la politique n’est pas dans le HTML');
|
||||||
|
assert.match(privacy, /PFPDT/);
|
||||||
|
assert.doesNotMatch(terms, /<script/i, 'la page embarque un script');
|
||||||
|
assert.doesNotMatch(privacy, /<script/i, 'la page embarque un script');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets itself be indexed, unlike the dashboard', async () => {
|
||||||
|
const terms = await get('/terms-of-service').then((response) => response.text());
|
||||||
|
assert.match(terms, /name="robots" content="index, follow"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('links both legal pages from every page of the wiki', async () => {
|
||||||
|
const index = await get('/wiki').then((response) => response.text());
|
||||||
|
assert.match(index, /href="\/terms-of-service"/);
|
||||||
|
assert.match(index, /href="\/privacy-policy"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('searches without scripts, through a plain query string', async () => {
|
||||||
|
const results = await get('/wiki?q=confidentialit').then((response) => response.text());
|
||||||
|
assert.match(results, /résultat\(s\)/);
|
||||||
|
assert.match(results, /privacy-policy/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers 404 on an unknown page rather than a blank shell', async () => {
|
||||||
|
const response = await get('/wiki/inexistante');
|
||||||
|
assert.equal(response.status, 404);
|
||||||
|
assert.match(await response.text(), /introuvable/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tells each page where it lives', async () => {
|
||||||
|
const body = await get('/api/wiki').then((response) => response.json());
|
||||||
|
const pages = body.categories.flatMap((category) => category.pages);
|
||||||
|
|
||||||
|
assert.equal(pages.find((page) => page.slug === 'terms-of-service').path, '/terms-of-service');
|
||||||
|
assert.equal(pages.find((page) => page.slug === 'privacy-policy').path, '/privacy-policy');
|
||||||
|
assert.equal(pages.find((page) => page.slug === 'accueil').path, '/wiki/accueil');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps an ordinary page under /wiki', async () => {
|
||||||
|
createPage({ slug: 'guide', title: 'Guide', content: 'x', published: true });
|
||||||
|
|
||||||
|
// Not a legal page: `/guide` belongs to the dashboard, not to the wiki.
|
||||||
|
assert.doesNotMatch(await get('/guide').then((r) => r.text()), /wiki-shell/);
|
||||||
|
assert.match(await get('/wiki/guide').then((r) => r.text()), /wiki-shell/);
|
||||||
|
});
|
||||||
|
|
||||||
it('keeps the administration behind the login', async () => {
|
it('keeps the administration behind the login', async () => {
|
||||||
assert.equal((await get('/api/wiki/admin')).status, 401);
|
assert.equal((await get('/api/wiki/admin')).status, 401);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('serves its own page rather than the dashboard shell', async () => {
|
it('serves the documentation rather than the dashboard shell', async () => {
|
||||||
const body = await get('/wiki/conditions-utilisation').then((response) => response.text());
|
const body = await get('/wiki/terms-of-service').then((response) => response.text());
|
||||||
assert.match(body, /wiki\.js/);
|
assert.match(body, /wiki-shell/);
|
||||||
assert.doesNotMatch(body, /id="app"/);
|
assert.doesNotMatch(body, /id="app"/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user