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:
parent
fd47514d81
commit
d2ef3b098c
13 changed files with 216 additions and 35 deletions
|
|
@ -445,3 +445,4 @@
|
|||
{"id":"int-69217a57aeec202222623a728c687d53","kind":"field_change","created_at":"2026-11-21T12:00:30.441841462Z","actor":"Shinuwa","issue_id":"sokko-g-eecb.7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Budgets split into transfer (home 1.75 MB, Aniimo 3 MB, CSS 100 kB gzip) and storage (per-file 1 MB, per-folder report, no total cap); npm run test:assets runs in check:full. Home dragons recompressed (-35 kB), home back to ~1.71-1.72 MB."}}
|
||||
{"id":"int-7df73fef6bd9c552de1b6e1883717bf0","kind":"field_change","created_at":"2026-11-21T12:01:09.432506407Z","actor":"Shinuwa","issue_id":"sokko-g-eecb","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Les 9 correctifs côté projet de l'audit du 2026-11-19 sont faits ; le découpage du CSS est suivi à part."}}
|
||||
{"id":"int-9f1de441cc2470beb7af669a5f3368a5","kind":"field_change","created_at":"2026-11-21T15:49:39.069539167Z","actor":"Shinuwa","issue_id":"sokko-g-2td","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Already in place: pack items in campaign rewards, atomic claim limited to one per player and 20/min, idempotent opening that can be resumed. Added: pack rates copied into the campaign at creation (packRates), applied at opening and shown at reveal."}}
|
||||
{"id":"int-0f993bd73dad678e8f26836475670eeb","kind":"field_change","created_at":"2026-11-21T16:00:22.800681626Z","actor":"Shinuwa","issue_id":"sokko-g-3jc.23","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Reserve size editable in admin (1–50) next to the delay; players and recharge_settings rebuilt by migration 21 with foreign keys off; a reduced reserve keeps players' extra openings; a raised reserve restarts recharge right away for full players."}}
|
||||
|
|
|
|||
|
|
@ -451,9 +451,15 @@ l'administration.
|
|||
- `recharge_settings(id = 1, interval_ms, max_openings, updated_at, updated_by)` :
|
||||
réglage unique de recharge des ouvertures, commun à tous les paquets et non
|
||||
versionné. Le délai, saisi en minutes dans l'administration, est un nombre
|
||||
entier de minutes entre 1 et 10 080 (7 jours) ; la réserve reste plafonnée à 5 (`players.openings_balance`). Un
|
||||
entier de minutes entre 1 et 10 080 (7 jours) ; la réserve maximale (`max_openings`)
|
||||
va de 1 à 50 ouvertures (`MAX_RESERVE_OPENINGS`, la base n'impose plus que
|
||||
`players.openings_balance >= 0`). Un
|
||||
nouveau délai s'applique immédiatement, y compris au temps écoulé depuis la
|
||||
dernière recharge du joueur (`players.recharge_anchor`). Ce réglage ne passe
|
||||
dernière recharge du joueur (`players.recharge_anchor`). Une réserve agrandie
|
||||
remet en recharge, dès le changement, les joueurs qui étaient pleins ; une
|
||||
réserve réduite laisse à chacun ses ouvertures en trop, la recharge ne reprenant
|
||||
qu'une fois le solde redescendu sous le maximum. `getState().recharge` donne
|
||||
`maxOpenings`. Ce réglage ne passe
|
||||
plus par l'environnement (`CARDS_RECHARGE_*` supprimées) ; le tableau de bord
|
||||
admin l'expose dans `rechargeSetting`.
|
||||
- `mythic_opening_settings(scope, target_id, particle_shape_id, particle_palette_id, updated_at, updated_by)` :
|
||||
|
|
|
|||
|
|
@ -1215,10 +1215,20 @@ test("administrator navigates sections, manages mythic content and previews visu
|
|||
await expect(recharge.getByRole("combobox")).toHaveCount(0);
|
||||
const applyRecharge = recharge.getByRole("button", { name: "Appliquer", exact: true });
|
||||
await expect(applyRecharge).toBeDisabled();
|
||||
// La réserve se règle à côté du délai ; le serveur de test est partagé : elle reste à 5 pour les autres scénarios.
|
||||
const reserveInput = recharge.getByLabel("Réserve maximale");
|
||||
await expect(reserveInput).toHaveValue("5");
|
||||
await reserveInput.fill("51");
|
||||
await expect(recharge.getByRole("status")).toHaveText("Réserve : entre 1 et 50 ouvertures.");
|
||||
await expect(applyRecharge).toBeDisabled();
|
||||
await reserveInput.fill("8");
|
||||
await expect(recharge.getByRole("status")).toHaveText("1 h · 24 ouvertures par jour · réserve vide remplie en 8 h");
|
||||
await expect(applyRecharge).toBeEnabled();
|
||||
await reserveInput.fill("5");
|
||||
await recharge.getByLabel("Délai en minutes").fill("30");
|
||||
await expect(recharge.getByRole("status")).toHaveText("30 min · 48 ouvertures par jour · réserve vide remplie en 2 h 30 min");
|
||||
await applyRecharge.click();
|
||||
await page.getByRole("dialog", { name: "Passer à 1 ouverture toutes les 30 min ?" }).getByRole("button", { name: "Appliquer le délai" }).click();
|
||||
await page.getByRole("dialog", { name: "Passer à 1 ouverture toutes les 30 min ?" }).getByRole("button", { name: "Appliquer la recharge" }).click();
|
||||
await expect(recharge.locator(".nebula-admin-recharge-current")).toHaveText("1 ouverture toutes les 30 min · réserve de 5");
|
||||
await expect(recharge.getByRole("button", { name: "Appliquer", exact: true })).toBeDisabled();
|
||||
|
||||
|
|
|
|||
|
|
@ -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$/);
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -385,6 +385,84 @@ test("recharge delay is a single admin setting applied immediately", () => {
|
|||
database.close();
|
||||
});
|
||||
|
||||
test("a reduced reserve keeps the openings players already had", () => {
|
||||
assert.deepEqual(calculateRecharge({ openingsBalance: 8, rechargeAnchor: null }, 1_000_000, { intervalMs: 60_000, maxOpenings: 5 }), {
|
||||
openingsBalance: 8,
|
||||
rechargeAnchor: null,
|
||||
nextOpeningAt: null
|
||||
});
|
||||
});
|
||||
|
||||
test("the opening reserve size is an admin setting that never takes openings away", () => {
|
||||
let now = 1_800_000_000_000;
|
||||
const hour = 60 * 60 * 1000;
|
||||
const database = new CardsDatabase(":memory:");
|
||||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||||
const admin = service.upsertPlayer({ discordId: "reserve-admin", displayName: "Admin", isAdmin: true });
|
||||
const full = service.upsertPlayer({ discordId: "reserve-full", displayName: "Full" });
|
||||
database.db.prepare("UPDATE players SET openings_balance = 5, recharge_anchor = NULL WHERE id = ?").run(full.id);
|
||||
assert.equal(service.getState(full.id).recharge.maxOpenings, 5);
|
||||
|
||||
assert.throws(() => service.updateRechargeSetting(full.id, { maxOpenings: 8 }), /administrateur/);
|
||||
for (const maxOpenings of [0, 51, 2.5, "8"]) assert.throws(() => service.updateRechargeSetting(admin.id, { maxOpenings }), /Réserve invalide/);
|
||||
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: hour, maxOpenings: 5 }), /déjà en vigueur/);
|
||||
|
||||
// Agrandie : le joueur plein recharge dès le changement, pas seulement à sa prochaine visite.
|
||||
const raised = service.updateRechargeSetting(admin.id, { maxOpenings: 8 });
|
||||
assert.deepEqual(raised.rechargeSetting, { intervalMs: hour, maxOpenings: 8, updatedAt: now });
|
||||
now += 2 * hour;
|
||||
assert.deepEqual(service.getState(full.id).recharge, { openingsBalance: 7, rechargeAnchor: now, nextOpeningAt: now + hour, maxOpenings: 8 });
|
||||
now += hour;
|
||||
assert.equal(service.getState(full.id).recharge.openingsBalance, 8);
|
||||
|
||||
// Réduite : le joueur garde ses 8 ouvertures, et ne recharge qu'une fois redescendu sous la nouvelle réserve.
|
||||
service.updateRechargeSetting(admin.id, { maxOpenings: 3 });
|
||||
now += 5 * hour;
|
||||
assert.deepEqual(service.getState(full.id).recharge, { openingsBalance: 8, rechargeAnchor: null, nextOpeningAt: null, maxOpenings: 3 });
|
||||
for (let index = 0; index < 6; index += 1) {
|
||||
const opened = service.openPack(full.id, "primordial-nebula", `reserve-${index}`);
|
||||
service.completeOpening(full.id, opened.opening.id);
|
||||
}
|
||||
assert.deepEqual(service.getState(full.id).recharge, { openingsBalance: 2, rechargeAnchor: now, nextOpeningAt: now + hour, maxOpenings: 3 });
|
||||
|
||||
// Le délai et la réserve se règlent ensemble ou séparément ; l'historique garde les deux.
|
||||
service.updateRechargeSetting(admin.id, { intervalMs: 30 * 60_000 });
|
||||
assert.equal(service.rechargeSetting.maxOpenings, 3);
|
||||
const details = database.db.prepare("SELECT details_json FROM audit_log WHERE event_type = 'recharge_updated' ORDER BY id").all().map((row) => JSON.parse(row.details_json));
|
||||
assert.deepEqual(details.map(({ previousMaxOpenings, maxOpenings }) => [previousMaxOpenings, maxOpenings]), [[5, 8], [8, 3], [3, 3]]);
|
||||
assert.deepEqual([details[2].previousIntervalMs, details[2].intervalMs], [hour, 30 * 60_000]);
|
||||
database.close();
|
||||
});
|
||||
|
||||
test("rebuilding the players table keeps every row that references a player", async (t) => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-players-"));
|
||||
const path = join(directory, "cards.sqlite");
|
||||
t.after(() => rm(directory, { recursive: true, force: true }));
|
||||
let database = new CardsDatabase(path);
|
||||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||||
const player = service.upsertPlayer({ discordId: "rebuild", displayName: "Rebuild" });
|
||||
service.createSession(player.id);
|
||||
const opened = service.openPack(player.id, "primordial-nebula", "rebuild-pack");
|
||||
service.completeOpening(player.id, opened.opening.id);
|
||||
const counts = () => Object.fromEntries(["players", "sessions", "openings", "collection_cards", "audit_log"].map((table) => [table, database.db.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get().count]));
|
||||
const before = counts();
|
||||
const version = database.db.prepare("SELECT MAX(version) AS version FROM schema_migrations").get().version;
|
||||
// La reconstruction est la dernière migration : la rejouer refait la copie sur des données existantes.
|
||||
database.db.prepare("DELETE FROM schema_migrations WHERE version = ?").run(version);
|
||||
database.close();
|
||||
|
||||
database = new CardsDatabase(path);
|
||||
assert.deepEqual(counts(), before);
|
||||
assert.equal(database.db.prepare("PRAGMA foreign_keys").get().foreign_keys, 1);
|
||||
assert.deepEqual(database.db.prepare("PRAGMA foreign_key_check").all(), []);
|
||||
database.db.prepare("UPDATE players SET openings_balance = 50 WHERE id = ?").run(player.id);
|
||||
assert.throws(() => database.db.prepare("UPDATE players SET openings_balance = -1 WHERE id = ?").run(player.id), /CHECK/);
|
||||
assert.deepEqual({ ...database.db.prepare("SELECT interval_ms, max_openings FROM recharge_settings").get() }, { interval_ms: 3_600_000, max_openings: 5 });
|
||||
database.db.prepare("UPDATE recharge_settings SET max_openings = 50").run();
|
||||
assert.throws(() => database.db.prepare("UPDATE recharge_settings SET max_openings = 51").run(), /CHECK/);
|
||||
database.close();
|
||||
});
|
||||
|
||||
test("player history hides administration events without losing them", () => {
|
||||
const database = new CardsDatabase(":memory:");
|
||||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||||
|
|
@ -421,7 +499,7 @@ test("admin history lists administration events by page, without player events",
|
|||
assert.ok(first.nextBefore);
|
||||
const second = service.getAdminHistory(admin.id, { before: first.nextBefore });
|
||||
assert.deepEqual(second.entries.map((entry) => entry.type), ["recharge_updated"]);
|
||||
assert.deepEqual(second.entries[0].details, { previousIntervalMs: INITIAL_RECHARGE_SETTING.intervalMs, intervalMs: 20 * 60_000 });
|
||||
assert.deepEqual(second.entries[0].details, { previousIntervalMs: INITIAL_RECHARGE_SETTING.intervalMs, intervalMs: 20 * 60_000, previousMaxOpenings: INITIAL_RECHARGE_SETTING.maxOpenings, maxOpenings: INITIAL_RECHARGE_SETTING.maxOpenings });
|
||||
assert.equal(second.nextBefore, null);
|
||||
database.close();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -18,11 +18,13 @@ export function OpeningReserve({ recharge, content, children, compact = false })
|
|||
return () => window.clearInterval(interval);
|
||||
}, [recharge.nextOpeningAt]);
|
||||
|
||||
// La réserve maximale est réglée par l'administration ; un joueur peut la dépasser si elle a été réduite depuis.
|
||||
const maxOpenings = recharge.maxOpenings ?? 5;
|
||||
return <section className={`nds-panel nebula-opening-reserve ${compact ? "is-compact" : ""}`} aria-label={content.available}>
|
||||
<div className="nebula-opening-reserve-value"><strong>{recharge.openingsBalance}</strong><span>/ 5</span></div>
|
||||
<div className="nebula-opening-reserve-value"><strong>{recharge.openingsBalance}</strong><span>/ {maxOpenings}</span></div>
|
||||
<div className="nebula-opening-reserve-copy">
|
||||
<h2>{content.available}</h2>
|
||||
<div className="nds-progress" role="progressbar" aria-valuemin="0" aria-valuemax="5" aria-valuenow={recharge.openingsBalance}><span style={{ width: `${recharge.openingsBalance / 5 * 100}%` }} /></div>
|
||||
<div className="nds-progress" role="progressbar" aria-valuemin="0" aria-valuemax={maxOpenings} aria-valuenow={Math.min(recharge.openingsBalance, maxOpenings)}><span style={{ width: `${Math.min(1, recharge.openingsBalance / maxOpenings) * 100}%` }} /></div>
|
||||
{/* Sous le menu, le libellé court garde le compte à rebours sur la même ligne. */}
|
||||
<p>{recharge.nextOpeningAt ? <>{compact ? content.nextShort : content.next} <strong>{formatRemaining(recharge.nextOpeningAt, now)}</strong></> : content.full}</p>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -44,7 +44,11 @@ function mythicDetail(entry, catalog) {
|
|||
function eventDetail(entry, catalog) {
|
||||
const { details, campaignName } = entry;
|
||||
switch (entry.type) {
|
||||
case "recharge_updated": return `${formatDuration(details.previousIntervalMs)} → ${formatDuration(details.intervalMs)}`;
|
||||
case "recharge_updated": return [
|
||||
details.previousIntervalMs !== details.intervalMs && `${formatDuration(details.previousIntervalMs)} → ${formatDuration(details.intervalMs)}`,
|
||||
// Les entrées d'avant la réserve réglable n'ont que le délai.
|
||||
details.maxOpenings != null && details.previousMaxOpenings !== details.maxOpenings && `réserve ${details.previousMaxOpenings} → ${details.maxOpenings}`
|
||||
].filter(Boolean).join(" · ");
|
||||
case "shop_updated": return shopChanges(details, catalog).filter(Boolean).join(" · ");
|
||||
case "catalog_card_mythic_updated": return mythicDetail(entry, catalog);
|
||||
case "catalog_collection_opening_updated":
|
||||
|
|
|
|||
|
|
@ -60,15 +60,29 @@ export function DropRatesEditor({ catalog, collection, busy, mutateCatalog }) {
|
|||
}
|
||||
|
||||
const MAX_RECHARGE_MINUTES = 7 * 24 * 60;
|
||||
// Même borne que le serveur (MAX_RESERVE_OPENINGS).
|
||||
const MAX_RESERVE_OPENINGS = 50;
|
||||
|
||||
function reserveMessage(setting, intervalMs, reserve) {
|
||||
const changes = [];
|
||||
if (intervalMs !== setting.intervalMs) changes.push("Le nouveau délai s’applique immédiatement à tous les joueurs, y compris au temps déjà écoulé depuis leur dernière recharge.");
|
||||
if (reserve > setting.maxOpenings) changes.push(`Les joueurs dont la réserve était pleine recommencent à recharger jusqu’à ${reserve}.`);
|
||||
if (reserve < setting.maxOpenings) changes.push(`Les joueurs qui ont plus de ${reserve} ouvertures les gardent ; leur réserve ne se recharge qu’une fois redescendue sous ${reserve}.`);
|
||||
return changes.join(" ");
|
||||
}
|
||||
|
||||
export function RechargeSetting({ setting, busy, runMutation, refreshDashboard }) {
|
||||
const [minutes, setMinutes] = useState(() => (setting ? String(setting.intervalMs / 60_000) : ""));
|
||||
const [reserveDraft, setReserveDraft] = useState(() => (setting ? String(setting.maxOpenings) : ""));
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
if (!setting) return <aside className="nds-panel nebula-admin-recharge" aria-busy="true"><p className="nebula-admin-empty">Chargement de la recharge…</p></aside>;
|
||||
const parsed = /^\d+$/.test(minutes) ? Number(minutes) : NaN;
|
||||
const valid = Number.isInteger(parsed) && parsed >= 1 && parsed <= MAX_RECHARGE_MINUTES;
|
||||
const reserve = /^\d+$/.test(reserveDraft) ? Number(reserveDraft) : NaN;
|
||||
const intervalValid = Number.isInteger(parsed) && parsed >= 1 && parsed <= MAX_RECHARGE_MINUTES;
|
||||
const reserveValid = Number.isInteger(reserve) && reserve >= 1 && reserve <= MAX_RESERVE_OPENINGS;
|
||||
const valid = intervalValid && reserveValid;
|
||||
const intervalMs = parsed * 60_000;
|
||||
const changed = valid && intervalMs !== setting.intervalMs;
|
||||
const changed = valid && (intervalMs !== setting.intervalMs || reserve !== setting.maxOpenings);
|
||||
const perDay = valid ? 1440 / parsed : 0;
|
||||
|
||||
return <aside className="nds-panel nebula-admin-recharge" aria-labelledby="nebula-admin-recharge-title">
|
||||
|
|
@ -76,19 +90,22 @@ export function RechargeSetting({ setting, busy, runMutation, refreshDashboard }
|
|||
<h4 id="nebula-admin-recharge-title">Recharge des ouvertures</h4>
|
||||
<span className="nebula-admin-recharge-current">{formatRechargeInterval(setting.intervalMs)} · réserve de {setting.maxOpenings}</span>
|
||||
</div>
|
||||
<p className="nebula-form-help">Commune à tous les paquets. Un nouveau délai s’applique immédiatement, y compris au temps déjà écoulé depuis la dernière recharge.</p>
|
||||
<p className="nebula-form-help">Commune à tous les paquets. Un nouveau délai s’applique immédiatement, y compris au temps déjà écoulé depuis la dernière recharge. Réduire la réserve ne retire aucune ouverture aux joueurs.</p>
|
||||
<div className="nebula-admin-recharge-form">
|
||||
<label><span>Délai en minutes</span><input className="nds-input" type="number" inputMode="numeric" min="1" max={MAX_RECHARGE_MINUTES} step="1" value={minutes} disabled={busy} onChange={(event) => setMinutes(event.target.value)} /></label>
|
||||
<label><span>Réserve maximale</span><input className="nds-input" type="number" inputMode="numeric" min="1" max={MAX_RESERVE_OPENINGS} step="1" value={reserveDraft} disabled={busy} onChange={(event) => setReserveDraft(event.target.value)} /></label>
|
||||
<button className="nds-button" data-variant="primary" type="button" disabled={busy || !changed} onClick={() => setConfirming(true)}>Appliquer</button>
|
||||
</div>
|
||||
<p className="nebula-admin-recharge-preview" role="status">{valid ? `${formatDuration(intervalMs)} · ${perDay.toLocaleString("fr-FR", { maximumFractionDigits: 1 })} ouverture${perDay >= 2 ? "s" : ""} par jour · réserve vide remplie en ${formatDuration(intervalMs * setting.maxOpenings)}` : `Entre 1 et ${MAX_RECHARGE_MINUTES.toLocaleString("fr-FR")} minutes (7 jours).`}</p>
|
||||
<p className="nebula-admin-recharge-preview" role="status">{valid
|
||||
? `${formatDuration(intervalMs)} · ${perDay.toLocaleString("fr-FR", { maximumFractionDigits: 1 })} ouverture${perDay >= 2 ? "s" : ""} par jour · réserve vide remplie en ${formatDuration(intervalMs * reserve)}`
|
||||
: [!intervalValid && `Délai : entre 1 et ${MAX_RECHARGE_MINUTES.toLocaleString("fr-FR")} minutes (7 jours).`, !reserveValid && `Réserve : entre 1 et ${MAX_RESERVE_OPENINGS} ouvertures.`].filter(Boolean).join(" ")}</p>
|
||||
{confirming && <ConfirmModal
|
||||
title={`Passer à ${formatRechargeInterval(intervalMs)} ?`}
|
||||
message="Le nouveau délai s’applique immédiatement à tous les joueurs, y compris au temps déjà écoulé depuis leur dernière recharge."
|
||||
confirmLabel="Appliquer le délai"
|
||||
title={`Passer à ${[intervalMs !== setting.intervalMs && formatRechargeInterval(intervalMs), reserve !== setting.maxOpenings && `une réserve de ${reserve}`].filter(Boolean).join(" et ")} ?`}
|
||||
message={reserveMessage(setting, intervalMs, reserve)}
|
||||
confirmLabel="Appliquer la recharge"
|
||||
onClose={async (confirmed) => {
|
||||
setConfirming(false);
|
||||
if (confirmed && (await runMutation(() => updateRechargeSetting(intervalMs)))) await refreshDashboard();
|
||||
if (confirmed && (await runMutation(() => updateRechargeSetting({ intervalMs, maxOpenings: reserve })))) await refreshDashboard();
|
||||
}}
|
||||
/>}
|
||||
</aside>;
|
||||
|
|
|
|||
|
|
@ -155,8 +155,8 @@ export function setDropRates(collectionId, rarityWeights) {
|
|||
return request(`/admin/collections/${encodeURIComponent(collectionId)}/drop-rates`, { method: "PUT", body: JSON.stringify({ rarityWeights }) });
|
||||
}
|
||||
|
||||
export function updateRechargeSetting(intervalMs) {
|
||||
return request("/admin/recharge", { method: "PUT", body: JSON.stringify({ intervalMs }) });
|
||||
export function updateRechargeSetting({ intervalMs, maxOpenings }) {
|
||||
return request("/admin/recharge", { method: "PUT", body: JSON.stringify({ intervalMs, maxOpenings }) });
|
||||
}
|
||||
|
||||
export function loadCampaignDetail(campaignId) {
|
||||
|
|
|
|||
|
|
@ -597,9 +597,9 @@ $diffraction-glitter-b: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/
|
|||
.nebula-admin-recharge-head h4 { margin: 0; font-size: var(--font-size-lg); }
|
||||
.nebula-admin-recharge-current { color: var(--color-accent-gold); font-size: var(--font-size-sm); font-weight: 800; }
|
||||
.nebula-admin-recharge .nebula-form-help { margin: 0; }
|
||||
.nebula-admin-recharge-form { display: flex; align-items: flex-end; gap: var(--space-3); margin-top: var(--space-2); }
|
||||
.nebula-admin-recharge-form { display: flex; flex-wrap: wrap; align-items: flex-end; gap: var(--space-3); margin-top: var(--space-2); }
|
||||
.nebula-admin-recharge-form > label { display: grid; gap: 6px; color: var(--color-text-secondary); font-size: var(--font-size-sm); }
|
||||
.nebula-admin-recharge-form > label { flex: 0 1 200px; }
|
||||
.nebula-admin-recharge-form > label { flex: 0 1 200px; min-width: 140px; }
|
||||
.nebula-admin-recharge-form .nds-input { width: 100%; }
|
||||
.nebula-admin-recharge-preview { margin: 0; color: var(--color-text-secondary); font-size: var(--font-size-sm); }
|
||||
.nebula-admin-pack-switch { display: inline-flex; flex: none; align-items: center; gap: var(--space-2); color: var(--color-text-secondary); font-size: var(--font-size-sm); font-weight: 700; }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue