The 669 // comments sitting right above a function, method or hook become /** */ blocks, unchanged in wording; eslint directives stay right above the line they target. website/AGENTS.md now asks for JSDoc on function comments and // inside function bodies. ExpeditionPlanner.jsx grew past 300 lines and gets its full header, as the header test requires. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
130 lines
7.9 KiB
JavaScript
130 lines
7.9 KiB
JavaScript
/**
|
||
* @file Alertes Discord des Expéditions de Sokko TCG : choix de chaque joueur et file des messages à envoyer
|
||
* (groupe ouvert, expédition de retour).
|
||
*
|
||
* Contexte : méthodes d'ExpeditionService, ajoutées à son prototype par `Object.assign` en fin
|
||
* d'expedition-service.js. Ce fichier ne fait que remplir et vider une file en base : discord-alerts.js
|
||
* envoie les messages, rédigés par alert-messages.js.
|
||
* Points d'entrée : `setAlertPreferences`, `queueGroupOpenedInTx`, `queueReturnAlerts`, `pendingAlerts`,
|
||
* `markAlertSent`, `markAlertFailed`, `purgeAlertOutbox`.
|
||
* Utilisé par : api.js (préférences) ; `dispatchAlerts` de discord-alerts.js, lancé toutes les 30 s par api.js,
|
||
* qui remplit la file des retours puis l'envoie ; `purgeAlertOutbox` par la maintenance de service.js.
|
||
* Attention : rien n'est mis en file sans bot configuré ou quand l'administration a coupé les alertes
|
||
* (`alertsActive`) ; un message est abandonné après `MAX_ALERT_ATTEMPTS` échecs.
|
||
*/
|
||
|
||
import { randomUUID } from "node:crypto";
|
||
import { expeditionReturnedMessage, groupOpenedMessage } from "./alert-messages.js";
|
||
|
||
// Un vrai compte Discord : le compte de développement et les comptes supprimés n'ont pas d'identifiant numérique.
|
||
const DISCORD_ID_PATTERN = /^\d{17,20}$/;
|
||
export const MAX_ALERT_ATTEMPTS = 5;
|
||
const OUTBOX_RETENTION_MS = 30 * 24 * 3_600_000;
|
||
|
||
export const alertMethods = {
|
||
/** Les alertes partent si le bot est configuré sur ce serveur et si l'administration ne les a pas coupées. */
|
||
alertsActive(settings = this.settings) {
|
||
return Boolean(this.alertsAvailable) && settings.alerts.enabled;
|
||
},
|
||
|
||
alertPreferences(playerId) {
|
||
const row = this.db.prepare("SELECT group_opened, expedition_returned FROM player_alerts WHERE player_id = ?").get(playerId);
|
||
return { available: this.alertsActive(), groupOpened: Boolean(row?.group_opened), expeditionReturned: Boolean(row?.expedition_returned) };
|
||
},
|
||
|
||
setAlertPreferences(playerId, { groupOpened, expeditionReturned } = {}) {
|
||
if (typeof groupOpened !== "boolean" || typeof expeditionReturned !== "boolean") {
|
||
throw Object.assign(new Error("Choix d’alertes invalide."), { status: 400, code: "ALERTS_INVALID" });
|
||
}
|
||
this.db.prepare(`INSERT INTO player_alerts(player_id, group_opened, expedition_returned, updated_at) VALUES (?, ?, ?, ?)
|
||
ON CONFLICT(player_id) DO UPDATE SET group_opened = excluded.group_opened, expedition_returned = excluded.expedition_returned, updated_at = excluded.updated_at`)
|
||
.run(playerId, Number(groupOpened), Number(expeditionReturned), this.now());
|
||
return this.cards.getState(playerId);
|
||
},
|
||
|
||
/** `message` : { content, embed?, link? } (alert-messages.js), ou un simple texte. */
|
||
enqueueInTx(playerId, kind, message) {
|
||
const { content, embed = null, link = null } = typeof message === "string" ? { content: message } : message;
|
||
const extra = embed || link ? JSON.stringify({ ...(embed ? { embed } : {}), ...(link ? { link } : {}) }) : null;
|
||
this.db.prepare("INSERT INTO alert_outbox(id, player_id, kind, content, extra_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(randomUUID(), playerId, kind, content, extra, this.now());
|
||
},
|
||
|
||
/** Groupe ouvert : prévient les autres joueurs qui ont activé cette alerte. */
|
||
queueGroupOpenedInTx(creatorId, setup, expeditionId) {
|
||
if (!this.alertsActive()) return;
|
||
const creator = this.db.prepare("SELECT display_name FROM players WHERE id = ?").get(creatorId);
|
||
const message = groupOpenedMessage({ creatorName: creator?.display_name, setup, expeditionId, origin: this.publicOrigin, catalog: this.cards.catalog });
|
||
for (const row of this.db.prepare(`SELECT p.id, p.discord_id FROM player_alerts a JOIN players p ON p.id = a.player_id
|
||
WHERE a.group_opened = 1 AND p.deleted_at IS NULL AND p.id != ?`).all(creatorId)) {
|
||
if (DISCORD_ID_PATTERN.test(row.discord_id)) this.enqueueInTx(row.id, "group_opened", message);
|
||
}
|
||
},
|
||
|
||
/**
|
||
* Expéditions rentrées depuis le dernier passage : une alerte par joueur qui l'a activée, une seule fois par expédition. Les groupes
|
||
* dont l'inscription est échue partent d'abord : sans visite de joueur, leur retour serait sinon invisible au passage périodique.
|
||
*/
|
||
queueReturnAlerts() {
|
||
if (!this.alertsActive()) return 0;
|
||
this.settleForming();
|
||
let queued = 0;
|
||
this.cards.database.transaction(() => {
|
||
const rows = this.db.prepare(`SELECT e.id, e.setup_json, e.result_json, m.reward_json, m.player_id, p.discord_id, a.expedition_returned FROM expedition_members m
|
||
JOIN expeditions e ON e.id = m.expedition_id JOIN players p ON p.id = m.player_id LEFT JOIN player_alerts a ON a.player_id = m.player_id
|
||
WHERE e.status = 'running' AND e.returns_at <= ? AND m.claimed_at IS NULL AND m.alerted_at IS NULL`).all(this.now());
|
||
const mark = this.db.prepare("UPDATE expedition_members SET alerted_at = ? WHERE expedition_id = ? AND player_id = ?");
|
||
for (const row of rows) {
|
||
mark.run(this.now(), row.id, row.player_id);
|
||
if (!row.expedition_returned || !DISCORD_ID_PATTERN.test(row.discord_id)) continue;
|
||
const setup = JSON.parse(row.setup_json);
|
||
const message = expeditionReturnedMessage({ setup, result: JSON.parse(row.result_json || "null"), reward: JSON.parse(row.reward_json || "null"), expeditionId: row.id, origin: this.publicOrigin, catalog: this.cards.catalog });
|
||
this.enqueueInTx(row.player_id, "expedition_returned", message);
|
||
queued += 1;
|
||
}
|
||
});
|
||
return queued;
|
||
},
|
||
|
||
/**
|
||
* Messages à envoyer. Au moment de l'envoi, l'alerte doit encore être voulue : coupée par l'administration, ou désactivée par le
|
||
* joueur pour ce type de message, elle est abandonnée (marquée en échec, jamais renvoyée plus tard, quand elle serait périmée).
|
||
*/
|
||
pendingAlerts(limit = 20) {
|
||
const pending = () => this.db.prepare(`SELECT o.id, o.kind, o.content, o.extra_json, o.attempts, p.discord_id, a.group_opened, a.expedition_returned FROM alert_outbox o
|
||
JOIN players p ON p.id = o.player_id LEFT JOIN player_alerts a ON a.player_id = o.player_id
|
||
WHERE o.sent_at IS NULL AND o.failed_at IS NULL AND p.deleted_at IS NULL ORDER BY o.created_at`).all();
|
||
const drop = this.db.prepare("UPDATE alert_outbox SET failed_at = ?, last_error = ? WHERE id = ?");
|
||
const wanted = [];
|
||
this.cards.database.transaction(() => {
|
||
const active = this.alertsActive();
|
||
for (const row of pending()) {
|
||
const allowed = row.kind === "group_opened" ? row.group_opened : row.kind === "expedition_returned" ? row.expedition_returned : 0;
|
||
if (!active) drop.run(this.now(), "alerts disabled", row.id);
|
||
else if (!allowed) drop.run(this.now(), "player opted out", row.id);
|
||
else if (wanted.length < limit) wanted.push({ id: row.id, content: row.content, extra: JSON.parse(row.extra_json || "{}"), attempts: row.attempts, discordId: row.discord_id });
|
||
}
|
||
});
|
||
return wanted;
|
||
},
|
||
|
||
markAlertSent(id) {
|
||
this.db.prepare("UPDATE alert_outbox SET sent_at = ?, attempts = attempts + 1 WHERE id = ?").run(this.now(), id);
|
||
},
|
||
|
||
/** Échec : on réessaie plus tard, sauf si l'échec est définitif (compte inconnu, messages privés fermés) ou trop répété. */
|
||
markAlertFailed(id, error, { permanent = false } = {}) {
|
||
const row = this.db.prepare("SELECT attempts FROM alert_outbox WHERE id = ?").get(id);
|
||
const attempts = (row?.attempts ?? 0) + 1;
|
||
this.db.prepare("UPDATE alert_outbox SET attempts = ?, last_error = ?, failed_at = ? WHERE id = ?")
|
||
.run(attempts, String(error).slice(0, 200), permanent || attempts >= MAX_ALERT_ATTEMPTS ? this.now() : null, id);
|
||
},
|
||
|
||
forgetAlertsInTx(playerId) {
|
||
this.db.prepare("DELETE FROM player_alerts WHERE player_id = ?").run(playerId);
|
||
this.db.prepare("DELETE FROM alert_outbox WHERE player_id = ?").run(playerId);
|
||
},
|
||
|
||
purgeAlertOutbox() {
|
||
this.db.prepare("DELETE FROM alert_outbox WHERE COALESCE(sent_at, failed_at) <= ?").run(this.now() - OUTBOX_RETENTION_MS);
|
||
}
|
||
};
|