Let administrators set the opening reserve size

The reserve was fixed at 5 by CHECK constraints on players and
recharge_settings. Migration 21 rebuilds both tables with foreign keys
off and checks them before committing; the reserve now goes from 1 to 50
and is set next to the recharge delay. A raised reserve restarts the
recharge of full players at once, a reduced one keeps their extra
openings, and the player counter shows the configured maximum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-21 17:02:01 +01:00
parent fd47514d81
commit d2ef3b098c
13 changed files with 216 additions and 35 deletions

View file

@ -511,7 +511,8 @@ export function createCardsApiHandler({
return true;
}
if (req.method === "PUT" && url.pathname === "/api/cards/admin/recharge") {
json(res, 200, service.updateRechargeSetting(session.player.id, { intervalMs: (await readBody(req)).intervalMs }));
const body = await readBody(req);
json(res, 200, service.updateRechargeSetting(session.player.id, { intervalMs: body.intervalMs, maxOpenings: body.maxOpenings }));
return true;
}
const collectionState = routeMatch(url.pathname, /^\/api\/cards\/admin\/collections\/([^/]+)\/state$/);

View file

@ -444,7 +444,45 @@ const MIGRATIONS = [
`
ALTER TABLE expedition_members ADD COLUMN ready_at INTEGER;
UPDATE expedition_members SET ready_at = joined_at;
`,
// Réserve d'ouvertures réglable : players.openings_balance n'est plus plafonné à 5 (« positif ou nul ») et
// recharge_settings.max_openings va jusqu'à 50, comme MAX_RESERVE_OPENINGS. SQLite ne modifie pas une contrainte :
// les tables sont reconstruites, sans clés étrangères pendant la copie (sinon DROP TABLE viderait les tables qui référencent players).
{
withoutForeignKeys: true,
sql: `
CREATE TABLE players_next (
id TEXT PRIMARY KEY,
discord_id TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
avatar_url TEXT NOT NULL DEFAULT '',
is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)),
created_at INTEGER NOT NULL,
openings_balance INTEGER NOT NULL DEFAULT 1 CHECK (openings_balance >= 0),
recharge_anchor INTEGER,
stardust INTEGER NOT NULL DEFAULT 0 CHECK (stardust >= 0),
purchased_openings INTEGER NOT NULL DEFAULT 0 CHECK (purchased_openings >= 0),
deleted_at INTEGER,
last_login_at INTEGER,
eclats INTEGER NOT NULL DEFAULT 0 CHECK (eclats >= 0)
) STRICT;
INSERT INTO players_next(id, discord_id, display_name, avatar_url, is_admin, created_at, openings_balance, recharge_anchor, stardust, purchased_openings, deleted_at, last_login_at, eclats)
SELECT id, discord_id, display_name, avatar_url, is_admin, created_at, openings_balance, recharge_anchor, stardust, purchased_openings, deleted_at, last_login_at, eclats FROM players;
DROP TABLE players;
ALTER TABLE players_next RENAME TO players;
CREATE TABLE recharge_settings_next (
id INTEGER PRIMARY KEY CHECK (id = 1),
interval_ms INTEGER NOT NULL CHECK (interval_ms >= 60000),
max_openings INTEGER NOT NULL CHECK (max_openings BETWEEN 1 AND 50),
updated_at INTEGER NOT NULL,
updated_by TEXT REFERENCES players(id)
) STRICT;
INSERT INTO recharge_settings_next(id, interval_ms, max_openings, updated_at, updated_by)
SELECT id, interval_ms, max_openings, updated_at, updated_by FROM recharge_settings;
DROP TABLE recharge_settings;
ALTER TABLE recharge_settings_next RENAME TO recharge_settings;
`
}
];
export class CardsDatabase {
@ -458,13 +496,21 @@ export class CardsDatabase {
migrate() {
this.db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at INTEGER NOT NULL) STRICT;");
const applied = new Set(this.db.prepare("SELECT version FROM schema_migrations").all().map((row) => row.version));
MIGRATIONS.forEach((sql, index) => {
MIGRATIONS.forEach((migration, index) => {
const version = index + 1;
if (applied.has(version)) return;
this.transaction(() => {
this.db.exec(sql);
this.db.prepare("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)").run(version, Date.now());
});
const { sql, withoutForeignKeys = false } = typeof migration === "string" ? { sql: migration } : migration;
// Le pragma est sans effet dans une transaction : il est coupé avant, puis la cohérence est vérifiée avant de valider.
if (withoutForeignKeys) this.db.exec("PRAGMA foreign_keys = OFF");
try {
this.transaction(() => {
this.db.exec(sql);
if (withoutForeignKeys && this.db.prepare("PRAGMA foreign_key_check").all().length) throw new Error(`Migration ${version} left dangling foreign keys.`);
this.db.prepare("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)").run(version, Date.now());
});
} finally {
if (withoutForeignKeys) this.db.exec("PRAGMA foreign_keys = ON");
}
});
}

View file

@ -6,6 +6,8 @@ import { collectionDrawableEditions, shopPackPools } from "./catalog.js";
// Un changement de délai s'applique aussi au temps déjà écoulé depuis la dernière recharge du joueur.
export const MIN_RECHARGE_INTERVAL_MS = 60_000;
export const MAX_RECHARGE_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
// Borne aussi imposée par la base (recharge_settings.max_openings) : la changer demande une migration.
export const MAX_RESERVE_OPENINGS = 50;
function checkedSetting({ intervalMs, maxOpenings }) {
if (!Number.isInteger(intervalMs) || intervalMs < 1 || !Number.isInteger(maxOpenings) || maxOpenings < 1) throw new TypeError("Recharge setting is invalid.");
@ -15,7 +17,8 @@ function checkedSetting({ intervalMs, maxOpenings }) {
export function calculateRecharge(player, now, setting) {
const { intervalMs, maxOpenings } = checkedSetting(setting);
const balance = Math.max(0, Number(player.openingsBalance) || 0);
if (balance >= maxOpenings) return { openingsBalance: maxOpenings, rechargeAnchor: null, nextOpeningAt: null };
// Au-dessus d'une réserve réduite depuis, le joueur garde ses ouvertures en trop : la recharge reprend une fois redescendu sous le maximum.
if (balance >= maxOpenings) return { openingsBalance: balance, rechargeAnchor: null, nextOpeningAt: null };
const anchor = player.rechargeAnchor == null ? now : Number(player.rechargeAnchor);
const earned = Math.max(0, Math.floor((now - anchor) / intervalMs));
const openingsBalance = Math.min(maxOpenings, balance + earned);

View file

@ -4,7 +4,7 @@ import { normalizeReward } from "./rewards.js";
import { MASS_RECYCLE_RARITIES, planRecycling, spareQuantity, validateShopSetting } from "./stardust.js";
import { FULL_ART_FORMAT, buildPublishedCatalog, collectionDrawableEditions, createCatalogIndex, holographicFinishIds, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
import { computeStreak, DAILY_REPEAT_WINDOW_DAYS, dailyCandidates, dailyDayKey, dailyZoom, drawDailyPuzzle, guessHint, isDayKey, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "./daily.js";
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js";
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MAX_RESERVE_OPENINGS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js";
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
import { ExpeditionService } from "./expedition-service.js";
@ -99,16 +99,28 @@ export class CardsService {
}
// Le délai s'applique immédiatement à tous les joueurs, y compris au temps écoulé depuis leur dernière recharge.
updateRechargeSetting(playerId, { intervalMs } = {}) {
// Une réserve agrandie se remplit dès maintenant pour les joueurs qui étaient pleins ; réduite, elle laisse à chacun
// ses ouvertures en trop (voir calculateRecharge). Un champ absent garde sa valeur.
updateRechargeSetting(playerId, { intervalMs, maxOpenings } = {}) {
this.requireAdmin(playerId);
if (!Number.isInteger(intervalMs) || intervalMs < MIN_RECHARGE_INTERVAL_MS || intervalMs > MAX_RECHARGE_INTERVAL_MS || intervalMs % MIN_RECHARGE_INTERVAL_MS !== 0) {
const current = this.rechargeSetting;
const nextInterval = intervalMs ?? current.intervalMs;
const nextMax = maxOpenings ?? current.maxOpenings;
if (!Number.isInteger(nextInterval) || nextInterval < MIN_RECHARGE_INTERVAL_MS || nextInterval > MAX_RECHARGE_INTERVAL_MS || nextInterval % MIN_RECHARGE_INTERVAL_MS !== 0) {
fail(400, "RECHARGE_INTERVAL_INVALID", "Délai invalide : un nombre entier de minutes, entre 1 minute et 7 jours.");
}
const current = this.rechargeSetting;
if (current.intervalMs === intervalMs) fail(409, "RECHARGE_UNCHANGED", "Ce délai est déjà en vigueur.");
if (!Number.isInteger(nextMax) || nextMax < 1 || nextMax > MAX_RESERVE_OPENINGS) {
fail(400, "RECHARGE_RESERVE_INVALID", `Réserve invalide : un nombre entier d’ouvertures, entre 1 et ${MAX_RESERVE_OPENINGS}.`);
}
if (current.intervalMs === nextInterval && current.maxOpenings === nextMax) fail(409, "RECHARGE_UNCHANGED", "Ces réglages sont déjà en vigueur.");
this.database.transaction(() => {
this.db.prepare("UPDATE recharge_settings SET interval_ms = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(intervalMs, this.now(), playerId);
this.audit(playerId, "recharge_updated", "recharge", { previousIntervalMs: current.intervalMs, intervalMs });
const now = this.now();
// Un joueur plein n'a pas d'échéance : sans cette ancre, sa recharge ne partirait qu'à sa prochaine visite.
if (nextMax > current.maxOpenings) {
this.db.prepare("UPDATE players SET recharge_anchor = ? WHERE recharge_anchor IS NULL AND openings_balance < ? AND deleted_at IS NULL").run(now, nextMax);
}
this.db.prepare("UPDATE recharge_settings SET interval_ms = ?, max_openings = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(nextInterval, nextMax, now, playerId);
this.audit(playerId, "recharge_updated", "recharge", { previousIntervalMs: current.intervalMs, intervalMs: nextInterval, previousMaxOpenings: current.maxOpenings, maxOpenings: nextMax });
});
return { rechargeSetting: this.rechargeSetting };
}
@ -357,10 +369,11 @@ export class CardsService {
const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId);
if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
const pinned = this.devPerks && player.discord_id === DEV_DISCORD_ID;
const recharge = (pinned ? pinnedRecharge : calculateRecharge)({
const setting = this.rechargeSetting;
const recharge = { ...(pinned ? pinnedRecharge : calculateRecharge)({
openingsBalance: player.openings_balance,
rechargeAnchor: player.recharge_anchor
}, this.now(), this.rechargeSetting);
}, this.now(), setting), maxOpenings: setting.maxOpenings };
this.db.prepare("UPDATE players SET openings_balance = ?, recharge_anchor = ? WHERE id = ?")
.run(recharge.openingsBalance, recharge.rechargeAnchor, playerId);
if (pinned) {