sokko-g/services/cards/expedition-alerts.js
Shinuwa 84b0d69b1f Keep the expedition view in sync with other players and only send alerts players still want
- The expeditions page rereads its view on its own: every 10 seconds while a
  group is shown, every 20 seconds otherwise, on tab return and at the next
  recruitment deadline; late responses no longer overwrite a newer action. A
  failed load offers "Réessayer" and a failed refresh keeps the last view.
- The periodic alert pass first departs groups whose recruitment ended, so
  their return is announced even if nobody visits the site.
- Queued alerts are checked again at sending time: a player who opted out or
  alerts switched off by the administration drop the message for good.
- The engraving confirmation sticks to the bottom of its window, the workshop
  lists commons by spare count, the guild expeditions card shows the Great
  Void, and stale help texts and comments are fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:24:39 +01:00

112 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Rôle : alertes Discord des Expéditions Sokko TCG : choix de chaque joueur, file des messages à envoyer (groupe ouvert, expédition de retour).
// Ces méthodes s'ajoutent à ExpeditionService (Object.assign sur son prototype) ; l'envoi lui-même est fait par discord-alerts.js.
import { randomUUID } from "node:crypto";
// 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);
},
expeditionsLink() {
return this.publicOrigin ? ` ${this.publicOrigin}/#/cards/expeditions` : "";
},
enqueueInTx(playerId, kind, content) {
this.db.prepare("INSERT INTO alert_outbox(id, player_id, kind, content, created_at) VALUES (?, ?, ?, ?, ?)").run(randomUUID(), playerId, kind, content, this.now());
},
// Groupe ouvert : prévient les autres joueurs qui ont activé cette alerte.
queueGroupOpenedInTx(creatorId, setup) {
if (!this.alertsActive()) return;
const creator = this.db.prepare("SELECT display_name FROM players WHERE id = ?").get(creatorId);
const content = `${creator?.display_name || "Un joueur"} ouvre un groupe d’expédition vers ${setup.destination.name} (${"★".repeat(setup.stars)}, ${setup.hours} h). Rejoignez-le sur le tableau de la Guilde :${this.expeditionsLink()}`;
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", content);
}
},
// 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, 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);
this.enqueueInTx(row.player_id, "expedition_returned", `Votre expédition vers ${setup.destination.name} est de retour ! Récupérez son butin :${this.expeditionsLink()}`);
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.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, 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);
}
};