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>
1377 lines
100 KiB
JavaScript
1377 lines
100 KiB
JavaScript
// Rôle : vérifie les règles, la persistance et les mutations protégées de Sokko TCG.
|
||
import assert from "node:assert/strict";
|
||
import { access, readdir, readFile, writeFile } from "node:fs/promises";
|
||
import { mkdtemp, rm } from "node:fs/promises";
|
||
import { tmpdir } from "node:os";
|
||
import { join } from "node:path";
|
||
import { test } from "node:test";
|
||
import { spawnSync } from "node:child_process";
|
||
import { assertVersionedCatalogScope, buildPublishedCatalog, drawableRarities, publicCatalog, prepareVersionedCatalog, validateCardsCatalog, withGeneratedFinishes } from "../services/cards/catalog.js";
|
||
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "../services/cards/admin-seed.js";
|
||
import { planRecycling } from "../services/cards/stardust.js";
|
||
import { resolveMythicOpeningStyle, resolveOpeningEffect } from "../website/src/features/cards/openingEffects.js";
|
||
import { summarizeReward } from "../website/src/features/cards/rewardText.js";
|
||
import { CardsDatabase } from "../services/cards/database.js";
|
||
import { calculateRecharge, drawPack, drawShopPack } from "../services/cards/game-rules.js";
|
||
import { CardsService, DEV_DISCORD_ID } from "../services/cards/service.js";
|
||
import { rarityPercentages } from "../website/src/features/cards/dropRates.js";
|
||
import { visibleCollections } from "../website/src/features/cards/collectionState.js";
|
||
import { availableTips, TIP_SECTION_VARIANTS, tipOfDay } from "../website/src/features/cards/dailyTips.js";
|
||
import { backupCardsDatabase, restoreCardsDatabase, runScheduledBackup, verifyCardsDatabase } from "../services/cards/backup.js";
|
||
|
||
// Catalogue versionné (finitions générées, sans variation mythique) et catalogue publié avec une variation de test.
|
||
const rawCatalog = JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8"));
|
||
const baseCatalog = prepareVersionedCatalog(rawCatalog);
|
||
const TEST_MYTHIC_VARIATIONS = [{ editionId: "mythic-card-pull-spectral-prism-solar", cardId: "mythic-card-pull", finishId: "spectral-prism-solar", status: "active" }];
|
||
const catalog = buildPublishedCatalog(baseCatalog, { variations: TEST_MYTHIC_VARIATIONS, collectionStates: INITIAL_COLLECTION_STATES, dropRates: INITIAL_DROP_RATES });
|
||
|
||
test("Sokko TCG styles keep mask compositions in a form the production minifier preserves", async () => {
|
||
const styles = await readFile("website/src/styles/_nebula-cards.scss", "utf8");
|
||
// Lightning CSS retire un mask-composite séparé qui suit le raccourci mask : l'effet n'apparaît alors qu'en production.
|
||
for (const rule of styles.split("\n").filter((line) => /(^|[\s;{])mask:/.test(line))) {
|
||
assert.doesNotMatch(rule, /mask-composite:/, rule.slice(0, 80));
|
||
}
|
||
});
|
||
|
||
test("Sokko TCG uses design system dropdowns instead of native selects", async () => {
|
||
const entries = await readdir("website/src/features/cards", { recursive: true });
|
||
const sources = entries.filter((entry) => entry.endsWith(".jsx"));
|
||
assert.ok(sources.length > 10);
|
||
for (const source of sources) {
|
||
assert.doesNotMatch(await readFile(join("website/src/features/cards", source), "utf8"), /<select\b/, `${source} must use SelectDropdown or CardsFilterMenu`);
|
||
assert.doesNotMatch(await readFile(join("website/src/features/cards", source), "utf8"), /type="datetime-local"/, `${source} must use ExpiryField`);
|
||
}
|
||
});
|
||
|
||
test("closed collections stay hidden until the player owns one of their cards", () => {
|
||
const visibleCatalog = {
|
||
collections: [{ id: "open-event", packCategory: "event", active: true }, { id: "closed-event", packCategory: "event", active: false }, { id: "closed-permanent", packCategory: "permanent", active: false }],
|
||
cards: [{ id: "event-card", collectionId: "closed-event" }, { id: "permanent-card", collectionId: "closed-permanent" }]
|
||
};
|
||
const ids = (owned) => visibleCollections(visibleCatalog, new Set(owned)).map((collection) => collection.id);
|
||
assert.deepEqual(ids([]), ["open-event"]);
|
||
assert.deepEqual(ids(["event-card"]), ["open-event", "closed-event"]);
|
||
assert.deepEqual(ids(["permanent-card"]), ["open-event", "closed-permanent"]);
|
||
});
|
||
|
||
test("the shop pack mixes active collections with its featured cards at the configured share", () => {
|
||
const shopCatalog = buildPublishedCatalog(baseCatalog, {
|
||
variations: TEST_MYTHIC_VARIATIONS,
|
||
collectionStates: [...INITIAL_COLLECTION_STATES, { collectionId: "stardust", active: true }],
|
||
dropRates: [...INITIAL_DROP_RATES, { collectionId: "stardust", rarityWeights: { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 } }]
|
||
});
|
||
const sourceOf = (editionId) => shopCatalog.cards.find((card) => card.id === shopCatalog.editions.find((edition) => edition.id === editionId).cardId).collectionId;
|
||
const rarityOf = (editionId) => shopCatalog.editions.find((edition) => edition.id === editionId).rarity;
|
||
// Générateur déterministe : le test reste stable d'une exécution à l'autre.
|
||
let seed = 42;
|
||
const random = (max) => {
|
||
seed = (seed * 1664525 + 1013904223) % 4294967296;
|
||
return Math.floor(seed / 4294967296 * max);
|
||
};
|
||
const draws = Array.from({ length: 40000 }, () => drawShopPack(shopCatalog, "stardust", random, 50)).flat();
|
||
const legendaries = draws.filter((id) => rarityOf(id) === "legendary");
|
||
// La part réglée revient à l'ensemble des légendaires de la collection, partagée à égalité entre elles.
|
||
const featured = legendaries.filter((id) => sourceOf(id) === "stardust");
|
||
assert.ok(Math.abs(featured.length / legendaries.length - 0.5) < 0.03, `part observée : ${featured.length / legendaries.length}`);
|
||
const scintillants = new Set(featured);
|
||
assert.ok(scintillants.size >= 5 && scintillants.has("stardust-dragon-standard"));
|
||
for (const id of scintillants) assert.ok(Math.abs(featured.filter((drawn) => drawn === id).length / featured.length - 1 / scintillants.size) < 0.03, id);
|
||
assert.ok(Math.abs(legendaries.length / draws.length - 0.03) < 0.003);
|
||
assert.deepEqual(new Set(draws.map(sourceOf)), new Set(["primordial-nebula", "astral-genesis", "stardust"]));
|
||
// Seules les légendaires et mythiques de la collection sont mises en avant ; une part nulle n'en tire jamais.
|
||
assert.ok(draws.filter((id) => sourceOf(id) === "stardust").every((id) => ["legendary", "mythic"].includes(rarityOf(id))));
|
||
assert.ok(!Array.from({ length: 3000 }, () => drawShopPack(shopCatalog, "stardust", random, 0)).flat().some((id) => sourceOf(id) === "stardust"));
|
||
// Les Scintillants ne sortent d'aucun autre paquet, et une collection fermée quitte le paquet de la boutique.
|
||
assert.ok(!Array.from({ length: 3000 }, () => [...drawPack(shopCatalog, "primordial-nebula", random), ...drawPack(shopCatalog, "astral-genesis", random)]).flat().some((id) => sourceOf(id) === "stardust"));
|
||
const closed = structuredClone(shopCatalog);
|
||
closed.collections.find((item) => item.id === "astral-genesis").active = false;
|
||
assert.ok(!Array.from({ length: 3000 }, () => drawShopPack(closed, "stardust", random, 50)).flat().some((id) => sourceOf(id) === "astral-genesis"));
|
||
});
|
||
|
||
test("the shop pack is bought with stardust, opens at once and cannot be obtained elsewhere", async (t) => {
|
||
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-shop-pack-"));
|
||
const database = new CardsDatabase(join(directory, "cards.sqlite"));
|
||
t.after(async () => {
|
||
database.close();
|
||
await rm(directory, { recursive: true, force: true });
|
||
});
|
||
const service = new CardsService({ database, catalog: baseCatalog, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "buyer", displayName: "Acheteur" });
|
||
const giveStardust = (amount) => database.db.prepare("UPDATE players SET stardust = ? WHERE id = ?").run(amount, player.id);
|
||
|
||
assert.throws(() => service.buyShopPack(player.id, "broke"), /Pas assez/);
|
||
assert.throws(() => service.openPack(player.id, "stardust", "direct"), /boutique/);
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "Code", code: "SHOP-PACK", reward: { items: [{ type: "pack", collectionId: "stardust" }] } }), /boutique/);
|
||
|
||
giveStardust(130);
|
||
const balanceBefore = service.getState(player.id).recharge.openingsBalance;
|
||
const bought = service.buyShopPack(player.id, "buy-1");
|
||
assert.equal(bought.opening.collectionId, "stardust");
|
||
assert.equal(bought.opening.cards.length, 3);
|
||
assert.equal(bought.state.wallet.stardust, 70);
|
||
assert.equal(bought.state.recharge.openingsBalance, balanceBefore);
|
||
// Rejouer la même requête ne fait pas payer deux fois ; une ouverture en attente bloque un nouvel achat, sans rien débiter.
|
||
assert.equal(service.buyShopPack(player.id, "buy-1").opening.id, bought.opening.id);
|
||
assert.throws(() => service.buyShopPack(player.id, "buy-2"), /ouverture en cours/);
|
||
assert.equal(service.getState(player.id).wallet.stardust, 70);
|
||
service.completeOpening(player.id, bought.opening.id);
|
||
|
||
// Prix et part se règlent dans l'administration ; une collection fermée n'est plus en vente.
|
||
const { stardustValues, openingPrice } = service.shopSetting;
|
||
assert.throws(() => service.updateShopSetting(admin.id, { stardustValues, openingPrice, shopPackShare: 101 }), /Part/);
|
||
assert.equal(service.updateShopSetting(admin.id, { stardustValues, openingPrice, shopPackPrice: 70, shopPackShare: 25 }).shopSetting.shopPackShare, 25);
|
||
assert.equal(service.getState(player.id).shop.shopPackPrice, 70);
|
||
service.setCollectionActive(admin.id, "stardust", false);
|
||
assert.throws(() => service.buyShopPack(player.id, "buy-3"), /pas disponible/);
|
||
assert.equal(service.getState(player.id).wallet.stardust, 70);
|
||
});
|
||
|
||
test("full-art mythics need a full image and declare one per legendary card", async (t) => {
|
||
// Une carte encore sans illustration (les Carnets des Veilleurs attendent les leurs) n'a pas non plus de pleine illustration.
|
||
const legendaryIds = baseCatalog.editions.filter((edition) => edition.rarity === "legendary").map((edition) => edition.cardId)
|
||
.filter((cardId) => baseCatalog.cards.find((item) => item.id === cardId).image);
|
||
for (const cardId of legendaryIds) {
|
||
const card = baseCatalog.cards.find((item) => item.id === cardId);
|
||
assert.ok(card.fullImage, `${cardId} needs a full image`);
|
||
await access(`website/public${card.image}`);
|
||
await access(`website/public${card.fullImage}`);
|
||
if (card.cutoutImage) await access(`website/public${card.cutoutImage}`);
|
||
if (card.fullCutoutImage) await access(`website/public${card.fullCutoutImage}`);
|
||
}
|
||
// Une illustration à zones vides reprend le nom de l'illustration pleine, suffixé `__cutout`.
|
||
assert.ok(baseCatalog.cards.some((card) => card.fullCutoutImage?.endsWith("__full__cutout.webp")));
|
||
const wrongCutout = structuredClone(rawCatalog);
|
||
wrongCutout.cards.find((card) => card.id === "mythic-card-pull").fullCutoutImage = "/static/img/cards/astral-genesis/legendary/mythic_card_pull__cutout.webp";
|
||
assert.throws(() => prepareVersionedCatalog(wrongCutout), /suffixed with __cutout/);
|
||
const wrongStandardCutout = structuredClone(rawCatalog);
|
||
wrongStandardCutout.cards.find((card) => card.id === "mythic-card-pull").cutoutImage = "/static/img/cards/astral-genesis/legendary/mythic_card_pull__full__cutout.webp";
|
||
assert.throws(() => prepareVersionedCatalog(wrongStandardCutout), /cutout image must be its image suffixed/);
|
||
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-full-art-"));
|
||
const database = new CardsDatabase(join(directory, "cards.sqlite"));
|
||
t.after(async () => {
|
||
database.close();
|
||
await rm(directory, { recursive: true, force: true });
|
||
});
|
||
const withoutImage = structuredClone(baseCatalog);
|
||
delete withoutImage.cards.find((card) => card.id === "aurora-wolf").fullImage;
|
||
const service = new CardsService({ database, catalog: withoutImage, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
|
||
assert.throws(() => service.setCardMythicConfig(admin.id, "aurora-wolf", { finishIds: ["full-art-spectral-prism-aurora"] }), /illustration pleine/);
|
||
service.setCardMythicConfig(admin.id, "starvoid-dragon", { finishIds: ["full-art-spectral-prism-solar"] });
|
||
assert.ok(service.catalog.editions.some((edition) => edition.id === "starvoid-dragon-full-art-spectral-prism-solar" && edition.rarity === "mythic"));
|
||
const finish = service.catalog.finishes.find((item) => item.id === "full-art-spectral-prism-solar");
|
||
assert.deepEqual([finish.formatId, finish.effectPresetId, finish.paletteId], ["full-art", "spectral-prism", "solar"]);
|
||
});
|
||
|
||
test("dev perks pin the dev account resources without touching other players", async (t) => {
|
||
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-dev-perks-"));
|
||
const database = new CardsDatabase(join(directory, "cards.sqlite"));
|
||
t.after(async () => {
|
||
database.close();
|
||
await rm(directory, { recursive: true, force: true });
|
||
});
|
||
let now = Date.UTC(2026, 0, 1);
|
||
const hour = 60 * 60 * 1000;
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0, devPerks: true });
|
||
const dev = service.upsertPlayer({ discordId: DEV_DISCORD_ID, displayName: "Dev", isAdmin: true });
|
||
const other = service.upsertPlayer({ discordId: "player", displayName: "Joueur" });
|
||
|
||
const initial = service.getState(dev.id);
|
||
assert.equal(initial.wallet.stardust, 1000);
|
||
assert.equal(initial.recharge.openingsBalance, 4);
|
||
assert.equal(service.getState(other.id).wallet.stardust, 0);
|
||
// Un nouveau compte reçoit 3 ouvertures, et le journal garde la quantité offerte.
|
||
const otherState = service.getState(other.id);
|
||
assert.equal(otherState.recharge.openingsBalance, 3);
|
||
assert.deepEqual(otherState.history.find((entry) => entry.type === "welcome_opening").details, { amount: 3 });
|
||
|
||
// Dépenser ne réduit ni la poussière ni la réserve affichées.
|
||
const afterPurchase = service.buyOpening(dev.id);
|
||
assert.equal(afterPurchase.wallet.stardust, 1000);
|
||
assert.equal(afterPurchase.wallet.purchasedOpenings, 1);
|
||
const opened = service.openPack(dev.id, "primordial-nebula", "dev-open");
|
||
assert.equal(opened.state.recharge.openingsBalance, 4);
|
||
service.completeOpening(dev.id, opened.opening.id);
|
||
|
||
// Le minuteur continue de tourner et repart à chaque échéance, sans atteindre 5/5.
|
||
const nextOpeningAt = service.getState(dev.id).recharge.nextOpeningAt;
|
||
assert.ok(nextOpeningAt > now);
|
||
now = nextOpeningAt + 6 * hour;
|
||
const later = service.getState(dev.id).recharge;
|
||
assert.equal(later.openingsBalance, 4);
|
||
assert.ok(later.nextOpeningAt > now);
|
||
|
||
// Sans l'option, le même compte suit les règles normales.
|
||
const regular = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
regular.buyOpening(dev.id);
|
||
assert.equal(regular.getState(dev.id).wallet.stardust, 1000 - regular.shopSetting.openingPrice);
|
||
now += 6 * hour;
|
||
assert.equal(regular.getState(dev.id).recharge.openingsBalance, 5);
|
||
});
|
||
|
||
test("card catalog keeps mythic editions attached to legendary cards", async () => {
|
||
const nebulaCards = catalog.cards.filter((card) => card.collectionId === "primordial-nebula");
|
||
const primordialCollection = catalog.collections.find((collection) => collection.id === "primordial-nebula");
|
||
assert.equal(primordialCollection.name, "La Nébuleuse Originelle");
|
||
assert.equal(primordialCollection.systemName, "Primordial Nebula");
|
||
assert.equal(nebulaCards.length, 83);
|
||
assert.deepEqual(
|
||
Object.fromEntries(["common", "rare", "epic", "legendary"].map((rarity) => [rarity, catalog.editions.filter((edition) => !edition.promotional && edition.rarity === rarity && nebulaCards.some((card) => card.id === edition.cardId)).length])),
|
||
{ common: 36, rare: 21, epic: 20, legendary: 6 }
|
||
);
|
||
await Promise.all(nebulaCards.map((card) => access(`website/public${card.image}`)));
|
||
const mythics = catalog.editions.filter((edition) => edition.rarity === "mythic" && !edition.promotional);
|
||
assert.ok(mythics.length >= 1);
|
||
for (const mythic of mythics) {
|
||
const parent = catalog.editions.find((edition) => edition.id === mythic.legendaryEditionId);
|
||
assert.equal(parent.rarity, "legendary");
|
||
assert.equal(parent.cardId, mythic.cardId);
|
||
}
|
||
assert.equal(drawPack(catalog, "primordial-nebula", () => 0).length, 3);
|
||
const launchCollection = catalog.collections.find((collection) => collection.id === "astral-genesis");
|
||
assert.equal(launchCollection.packCategory, "event");
|
||
assert.equal(launchCollection.name, "Genèse Astrale");
|
||
assert.equal(launchCollection.systemName, "Astral Genesis");
|
||
const astralCards = catalog.cards.filter((card) => card.collectionId === launchCollection.id);
|
||
assert.equal(astralCards.length, 11);
|
||
assert.deepEqual(
|
||
Object.fromEntries(["common", "rare", "epic", "legendary"].map((rarity) => [rarity, catalog.editions.filter((edition) => edition.rarity === rarity && astralCards.some((card) => card.id === edition.cardId)).length])),
|
||
{ common: 4, rare: 4, epic: 2, legendary: 1 }
|
||
);
|
||
assert.deepEqual(drawPack(catalog, launchCollection.id, () => 0), Array(3).fill("astral-booster-standard"));
|
||
assert.deepEqual(drawPack(catalog, launchCollection.id, (maximum) => maximum - 1), Array(3).fill("mythic-card-pull-spectral-prism-solar"));
|
||
await Promise.all(astralCards.map((card) => access(`website/public${card.image}`)));
|
||
assert.deepEqual(new Set(catalog.collections.map((collection) => collection.packCategory)), new Set(["permanent", "event", "shop", "expedition"]));
|
||
assert.ok(catalog.collections.every((collection) => collection.systemName && /^#[0-9a-f]{6}$/i.test(collection.back.primary) && collection.back.symbol && /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/.test(collection.back.image)));
|
||
});
|
||
|
||
test("finishes are generated: standard plus one per holographic effect and seven-color palette", () => {
|
||
assert.equal("finishes" in rawCatalog, false);
|
||
const preset = catalog.effectPresets.find((effect) => effect.id === "spectral-prism");
|
||
assert.equal(preset.kind, "holographic");
|
||
assert.deepEqual(catalog.finishes.map((finish) => finish.id), ["standard", ...["", "full-art-"].flatMap((format) => ["spectral-prism", "diffraction-sheen", "prismatic-backdrop"].flatMap((effect) => ["rainbow", "solar", "dusk", "crimson", "nature", "aurora", "winter", "cosmic", "darkness"].map((palette) => `${format}${effect}-${palette}`)))]);
|
||
assert.deepEqual(catalog.finishes[0], { id: "standard", label: "Standard", effectPresetId: null, paletteId: null, formatId: "standard" });
|
||
assert.ok(catalog.finishes.every((finish) => !("particlePresetId" in finish)));
|
||
assert.ok(catalog.effectPalettes.every((palette) => palette.colors.length === 7 && new Set(palette.colors).size === 7));
|
||
assert.deepEqual(catalog.effectPalettes.find((palette) => palette.id === "solar").colors, ["#fff4c2", "#ffe14d", "#ffc400", "#ff9d00", "#ff6a00", "#ffab1a", "#ffd84d"]);
|
||
const solarEdition = catalog.editions.find((edition) => edition.id === "mythic-card-pull-spectral-prism-solar");
|
||
assert.equal(solarEdition.rarity, "mythic");
|
||
assert.equal(solarEdition.legendaryEditionId, "mythic-card-pull-standard");
|
||
|
||
const withNewEffect = structuredClone(rawCatalog);
|
||
withNewEffect.effectPresets.push({ id: "effect-x", kind: "holographic", label: "Effet X" });
|
||
withNewEffect.effectPalettes.push({ id: "ember", label: "Braise", colors: ["#7f1d1d", "#b91c1c", "#ef4444", "#f97316", "#fb923c", "#fdba74", "#fff7ed"], highlight: "#ffffff" });
|
||
const generated = prepareVersionedCatalog(withNewEffect).finishes;
|
||
assert.equal(generated.length, 1 + 2 * 4 * 10);
|
||
assert.deepEqual(generated.find((finish) => finish.id === "effect-x-ember"), { id: "effect-x-ember", label: "Effet X — Braise", effectPresetId: "effect-x", paletteId: "ember", formatId: "standard" });
|
||
|
||
const invalidPalette = structuredClone(rawCatalog);
|
||
invalidPalette.effectPalettes[0].colors = invalidPalette.effectPalettes[0].colors.slice(0, 6);
|
||
assert.throws(() => prepareVersionedCatalog(invalidPalette), /Invalid effect palette/);
|
||
const declaredFinishes = { ...structuredClone(rawCatalog), finishes: [] };
|
||
assert.throws(() => assertVersionedCatalogScope(declaredFinishes), /generated/);
|
||
const invalidFinish = withGeneratedFinishes(structuredClone(rawCatalog));
|
||
invalidFinish.finishes.find((finish) => finish.id === "spectral-prism-aurora").paletteId = "unknown-palette";
|
||
assert.throws(() => validateCardsCatalog(invalidFinish), /known palette/);
|
||
});
|
||
|
||
|
||
test("opening effects compose rarity auras with a single default mythic opening", () => {
|
||
const defaultEffects = catalog.openingEffects;
|
||
const customEffects = defaultEffects.filter((effect) => effect.rarity === "mythic");
|
||
assert.deepEqual(defaultEffects.map((effect) => effect.rarity), ["rare", "epic", "legendary", "mythic"]);
|
||
const collectionScoped = structuredClone(rawCatalog);
|
||
collectionScoped.openingEffects[3].collectionId = "astral-genesis";
|
||
assert.throws(() => prepareVersionedCatalog(collectionScoped), /Invalid opening effect/);
|
||
assert.equal(catalog.openingEffects.some((effect) => effect.rarity === "common"), false);
|
||
assert.deepEqual(defaultEffects.find((effect) => effect.rarity === "rare").auraColors, ["#3b82f6"]);
|
||
assert.deepEqual(defaultEffects.find((effect) => effect.rarity === "epic").auraColors, ["#d946ef"]);
|
||
assert.deepEqual(customEffects[0].auraColors, ["#67e8f9", "#8b5cf6", "#d946ef", "#f6c453"]);
|
||
assert.equal(defaultEffects.find((effect) => effect.rarity === "rare").particlePresetId, null);
|
||
const epicParticles = catalog.particlePresets.find((preset) => preset.id === defaultEffects.find((effect) => effect.rarity === "epic").particlePresetId);
|
||
const legendaryParticles = catalog.particlePresets.find((preset) => preset.id === defaultEffects.find((effect) => effect.rarity === "legendary").particlePresetId);
|
||
const mythicParticles = catalog.particlePresets.find((preset) => preset.id === customEffects[0].particlePresetId);
|
||
assert.deepEqual(catalog.particlePresets.map((preset) => preset.id), ["epic-opening-sparks", "legendary-opening-burst", "mythic-rainbow-sparks"]);
|
||
assert.equal(epicParticles.count, 18);
|
||
assert.equal(legendaryParticles.count, 32);
|
||
assert.equal(mythicParticles.count, 48);
|
||
assert.equal(mythicParticles.shapeId, "sparks");
|
||
assert.equal(mythicParticles.paletteId, "rainbow");
|
||
for (const mythicEffect of customEffects) {
|
||
assert.equal(mythicEffect.auraDurationMs, defaultEffects.find((effect) => effect.rarity === "legendary").auraDurationMs);
|
||
assert.equal(mythicEffect.particleDurationMs, defaultEffects.find((effect) => effect.rarity === "legendary").particleDurationMs);
|
||
}
|
||
assert.deepEqual(catalog.particleShapes.map((shape) => [shape.id, shape.kind]), [["sparks", "sparks"], ["snowflakes", "snowflakes"]]);
|
||
assert.equal(catalog.particlePalettes.find((palette) => palette.id === "rainbow").colors.length, 7);
|
||
|
||
const duplicateRarity = structuredClone(catalog);
|
||
duplicateRarity.openingEffects.push({ ...duplicateRarity.openingEffects[0], id: "another-rare-opening" });
|
||
assert.throws(() => validateCardsCatalog(duplicateRarity), /Duplicate opening effect for rarity rare/);
|
||
|
||
const unknownRarity = structuredClone(catalog);
|
||
unknownRarity.openingEffects[0].rarity = "unknown";
|
||
assert.throws(() => validateCardsCatalog(unknownRarity), /Invalid opening effect/);
|
||
|
||
const invalidCommon = structuredClone(catalog);
|
||
invalidCommon.openingEffects[0].rarity = "common";
|
||
assert.throws(() => validateCardsCatalog(invalidCommon), /Invalid opening effect/);
|
||
|
||
const unknownParticles = structuredClone(catalog);
|
||
unknownParticles.openingEffects[1].particlePresetId = "unknown-particles";
|
||
assert.throws(() => validateCardsCatalog(unknownParticles), /known particle preset/);
|
||
|
||
const unknownShape = structuredClone(catalog);
|
||
unknownShape.particlePresets[0].shapeId = "unknown-shape";
|
||
assert.throws(() => validateCardsCatalog(unknownShape), /Invalid particle preset/);
|
||
|
||
const unknownShapeKind = structuredClone(catalog);
|
||
unknownShapeKind.particleShapes[1].kind = "bubbles";
|
||
assert.throws(() => validateCardsCatalog(unknownShapeKind), /Invalid particle shape snowflakes/);
|
||
|
||
const unknownPalette = structuredClone(catalog);
|
||
unknownPalette.particlePresets[0].paletteId = "unknown-palette";
|
||
assert.throws(() => validateCardsCatalog(unknownPalette), /Invalid particle preset/);
|
||
|
||
const missingDefaultMythic = structuredClone(catalog);
|
||
missingDefaultMythic.openingEffects = missingDefaultMythic.openingEffects.filter((effect) => effect.id !== "mythic-default-opening");
|
||
assert.throws(() => validateCardsCatalog(missingDefaultMythic), /opening effect for rarity mythic/);
|
||
const defaultMythic = defaultEffects.find((effect) => effect.rarity === "mythic");
|
||
assert.equal(defaultMythic.particlePresetId, "mythic-rainbow-sparks");
|
||
});
|
||
|
||
test("recharge honors the cap and keeps partial elapsed time", () => {
|
||
const setting = { intervalMs: 60_000, maxOpenings: 5 };
|
||
assert.deepEqual(calculateRecharge({ openingsBalance: 1, rechargeAnchor: 10_000 }, 139_999, setting), {
|
||
openingsBalance: 3,
|
||
rechargeAnchor: 130_000,
|
||
nextOpeningAt: 190_000
|
||
});
|
||
assert.deepEqual(calculateRecharge({ openingsBalance: 4, rechargeAnchor: 10_000 }, 130_000, setting), {
|
||
openingsBalance: 5,
|
||
rechargeAnchor: null,
|
||
nextOpeningAt: null
|
||
});
|
||
});
|
||
|
||
test("recharge delay is a single admin setting applied immediately", () => {
|
||
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 });
|
||
assert.deepEqual({ intervalMs: service.rechargeSetting.intervalMs, maxOpenings: service.rechargeSetting.maxOpenings }, INITIAL_RECHARGE_SETTING);
|
||
const admin = service.upsertPlayer({ discordId: "recharge-admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "recharge-player", displayName: "Player" });
|
||
const opened = service.openPack(player.id, "primordial-nebula", "recharge-pack");
|
||
service.completeOpening(player.id, opened.opening.id);
|
||
assert.equal(service.getState(player.id).recharge.nextOpeningAt, now + hour);
|
||
|
||
assert.throws(() => service.updateRechargeSetting(player.id, { intervalMs: hour }), /administrateur/);
|
||
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: 30_000 }), /Délai invalide/);
|
||
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: 90_500 }), /Délai invalide/);
|
||
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: 8 * 24 * hour }), /Délai invalide/);
|
||
assert.throws(() => service.updateRechargeSetting(admin.id, { intervalMs: hour }), /déjà en vigueur/);
|
||
|
||
// Trente minutes écoulées, puis passage à 20 min : le nouveau délai s'applique aussi au temps déjà écoulé.
|
||
const minute = 60_000;
|
||
now += 30 * minute;
|
||
const updated = service.updateRechargeSetting(admin.id, { intervalMs: 20 * minute });
|
||
assert.deepEqual(updated.rechargeSetting, { intervalMs: 20 * minute, maxOpenings: 5, updatedAt: now });
|
||
const recharge = service.getState(player.id).recharge;
|
||
assert.equal(recharge.openingsBalance, 3);
|
||
assert.equal(recharge.nextOpeningAt, now + 10 * minute);
|
||
assert.equal(service.getAdminDashboard(admin.id).rechargeSetting.intervalMs, 20 * minute);
|
||
assert.equal(new CardsService({ database, catalog: baseCatalog, now: () => now }).rechargeSetting.intervalMs, 20 * minute);
|
||
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 });
|
||
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
|
||
service.updateRechargeSetting(admin.id, { intervalMs: 20 * 60_000 });
|
||
const adminEvents = ["recharge_updated", "shop_updated", "catalog_card_mythic_updated", "collection_opened", "collection_closed", "drop_rates_updated", "catalog_collection_opening_updated", "campaign_created", "campaign_revoked", "campaign_extended"];
|
||
// Plus de 100 actions d'administration ne doivent pas non plus évincer les entrées du joueur.
|
||
for (let index = 0; index < 101; index += 1) service.audit(admin.id, adminEvents[index % adminEvents.length], "entity", {});
|
||
assert.deepEqual(service.getState(admin.id).history.map((entry) => entry.type), ["welcome_opening"]);
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS total FROM audit_log WHERE player_id = ? AND event_type = 'campaign_revoked'").get(admin.id).total, 10);
|
||
database.close();
|
||
});
|
||
|
||
test("admin history lists administration events by page, without player events", () => {
|
||
const database = new CardsDatabase(":memory:");
|
||
let now = 1_800_000_000_000;
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "admin-discord-id", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "player-discord-id", displayName: "Joueur" });
|
||
assert.deepEqual(service.getAdminHistory(admin.id), { entries: [], nextBefore: null });
|
||
assert.throws(() => service.getAdminHistory(player.id), /administrateur/);
|
||
|
||
service.updateRechargeSetting(admin.id, { intervalMs: 20 * 60_000 });
|
||
service.audit(player.id, "pack_opened", "opening", {});
|
||
for (let index = 0; index < 50; index += 1) {
|
||
now += 1;
|
||
service.audit(admin.id, "future_admin_action", `entity-${index}`, {});
|
||
}
|
||
const first = service.getAdminHistory(admin.id);
|
||
assert.equal(first.entries.length, 50);
|
||
assert.equal(first.entries[0].entityId, "entity-49");
|
||
assert.equal(first.entries[0].adminName, "Admin");
|
||
assert.equal(first.entries.some((entry) => JSON.stringify(entry).includes("admin-discord-id")), false);
|
||
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, previousMaxOpenings: INITIAL_RECHARGE_SETTING.maxOpenings, maxOpenings: INITIAL_RECHARGE_SETTING.maxOpenings });
|
||
assert.equal(second.nextBefore, null);
|
||
database.close();
|
||
});
|
||
|
||
test("opening is idempotent and server inventory owns the result", () => {
|
||
let now = 1_800_000_000_000;
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const player = service.upsertPlayer({ discordId: "one", displayName: "One" });
|
||
const first = service.openPack(player.id, "primordial-nebula", "request-one");
|
||
assert.equal(first.opening.cards.length, 3);
|
||
assert.equal(first.state.recharge.openingsBalance, 2);
|
||
const repeated = service.openPack(player.id, "primordial-nebula", "request-one");
|
||
assert.equal(repeated.opening.id, first.opening.id);
|
||
assert.equal(repeated.state.stats.openingsCount, 1);
|
||
assert.equal(database.db.prepare("SELECT quantity FROM collection_cards WHERE player_id = ?").get(player.id).quantity, 3);
|
||
const completed = service.completeOpening(player.id, first.opening.id);
|
||
assert.deepEqual(completed.collection.map((entry) => entry.quantity), [3]);
|
||
assert.equal(completed.rarestPull.id, first.opening.cards[2].id);
|
||
assert.equal(completed.rarestPull.openedAt, now);
|
||
assert.equal(completed.rarestPull.edition.rarity, "common");
|
||
now += INITIAL_RECHARGE_SETTING.intervalMs;
|
||
assert.equal(service.getState(player.id).recharge.openingsBalance, 3);
|
||
database.close();
|
||
});
|
||
|
||
test("admin dashboard aggregates current player activity without Discord identifiers", () => {
|
||
let now = 1_800_000_000_000;
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "dashboard-admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "dashboard-player", displayName: "Player" });
|
||
service.openPack(player.id, "primordial-nebula", "dashboard-pack");
|
||
now += INITIAL_RECHARGE_SETTING.intervalMs;
|
||
|
||
const dashboard = service.getAdminDashboard(admin.id);
|
||
const playerRow = dashboard.players.find((item) => item.id === player.id);
|
||
assert.deepEqual(dashboard.stats, { totalPlayers: 2, activePlayers7d: 1 });
|
||
assert.equal(playerRow.transfersCount, 0);
|
||
assert.equal(playerRow.stardust, 0);
|
||
assert.equal(playerRow.purchasedOpenings, 0);
|
||
assert.equal(Object.values(playerRow.rarityCounts).reduce((total, count) => total + count, 0), 3);
|
||
assert.equal(playerRow.giftPacks, 0);
|
||
assert.equal(playerRow.openingsBalance, 3);
|
||
assert.equal(playerRow.totalCards, 3);
|
||
assert.equal(playerRow.lastOpeningAt, 1_800_000_000_000);
|
||
assert.equal("discordId" in playerRow, false);
|
||
assert.throws(() => service.getAdminDashboard(player.id), /administrateur/);
|
||
database.close();
|
||
});
|
||
|
||
test("daily tips cite only values from the current settings and hide expedition tips while expeditions are closed", async () => {
|
||
const site = JSON.parse(await readFile("website/public/data/site.json", "utf8"));
|
||
const { items, sections } = site.cards.tips;
|
||
// Chaque partie du jeu a son libellé et sa couleur de badge.
|
||
assert.deepEqual(Object.keys(sections).sort(), Object.keys(TIP_SECTION_VARIANTS).sort());
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000 });
|
||
const values = service.tipValues();
|
||
assert.ok(items.length >= 30);
|
||
for (const item of items) {
|
||
// La partie du jeu concernée s'affiche en badge, pour qui ne la connaît pas encore ; le sujet est facultatif.
|
||
assert.ok(Object.hasOwn(sections, item.section), item.text);
|
||
assert.ok(item.topic == null || (typeof item.topic === "string" && item.topic.length > 0 && item.topic.length <= 30), item.text);
|
||
for (const [, key] of item.text.matchAll(/\{(\w+)\}/g)) assert.ok(Object.hasOwn(values, key), `${key} : ${item.text}`);
|
||
assert.ok(item.text.length <= 190, `Astuce trop longue : ${item.text}`);
|
||
}
|
||
// Fermées par défaut : seules les astuces générales restent ; ouvertes, toutes.
|
||
assert.equal(values.expeditions, false);
|
||
assert.ok(availableTips(items, values).length > 0);
|
||
assert.ok(availableTips(items, values).every((item) => item.section !== "expeditions"));
|
||
assert.equal(availableTips(items, { ...values, expeditions: true }).length, items.length);
|
||
assert.equal(values.rechargeEvery, "chaque heure");
|
||
assert.equal(values.awakeningLegendary, "1 légendaire");
|
||
// L'astuce du jour reste la même toute la journée.
|
||
assert.equal(tipOfDay("2026-11-19", 39), tipOfDay("2026-11-19", 39));
|
||
assert.ok(tipOfDay("2026-11-19", 39) < 39);
|
||
database.close();
|
||
});
|
||
|
||
test("recycling plan only takes duplicates that are not reserved by a transfer", () => {
|
||
const options = { rarityOf: (id) => id.split("-")[0], stardustValues: { common: 1, rare: 3, epic: 10, mythic: 150 } };
|
||
const collection = [
|
||
{ editionId: "common-a", quantity: 3, reserved: 0 },
|
||
{ editionId: "rare-b", quantity: 3, reserved: 1 },
|
||
{ editionId: "common-single", quantity: 1, reserved: 0 },
|
||
{ editionId: "epic-c", quantity: 2, reserved: 0 },
|
||
{ editionId: "mythic-d", quantity: 2, reserved: 0 }
|
||
];
|
||
const all = planRecycling(collection, options);
|
||
assert.deepEqual(all.items, [{ editionId: "common-a", rarity: "common", count: 2, stardust: 2 }, { editionId: "rare-b", rarity: "rare", count: 1, stardust: 3 }, { editionId: "epic-c", rarity: "epic", count: 1, stardust: 10 }]);
|
||
assert.deepEqual([all.count, all.stardust], [4, 15]);
|
||
assert.deepEqual(all.byRarity, { common: { count: 2, stardust: 2 }, rare: { count: 1, stardust: 3 }, epic: { count: 1, stardust: 10 }, legendary: { count: 0, stardust: 0 } });
|
||
// En masse, jusqu'à une rareté : les plus rares restent, et une mythique ne part jamais avec le reste.
|
||
assert.deepEqual(planRecycling(collection, { ...options, maxRarity: "common" }).items.map((item) => item.editionId), ["common-a"]);
|
||
assert.deepEqual(planRecycling(collection, { ...options, maxRarity: "rare" }).items.map((item) => item.editionId), ["common-a", "rare-b"]);
|
||
assert.deepEqual(planRecycling(collection, { ...options, editionId: "common-a" }).items, [{ editionId: "common-a", rarity: "common", count: 1, stardust: 1 }]);
|
||
assert.deepEqual(planRecycling(collection, { ...options, editionId: "mythic-d" }).items, [{ editionId: "mythic-d", rarity: "mythic", count: 1, stardust: 150 }]);
|
||
assert.equal(planRecycling(collection, { ...options, editionId: "common-single" }).count, 0);
|
||
});
|
||
|
||
test("duplicates become stardust that buys openings kept apart from the recharge reserve", () => {
|
||
let now = 1_800_000_000_000;
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "shop-admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "shop-player", displayName: "Player" });
|
||
const opened = service.openPack(player.id, "primordial-nebula", "shop-pack");
|
||
assert.throws(() => service.recycleDuplicates(player.id), /ouverture en cours/);
|
||
service.completeOpening(player.id, opened.opening.id);
|
||
const [editionId] = new Set(opened.opening.cards.map((card) => card.editionId));
|
||
const rarity = service.index.editions.get(editionId).rarity;
|
||
const value = INITIAL_SHOP_SETTING.stardustValues[rarity];
|
||
|
||
const before = service.getState(player.id);
|
||
assert.deepEqual(before.wallet, { stardust: 0, purchasedOpenings: 0, eclats: 0 });
|
||
assert.deepEqual(before.shop, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: INITIAL_SHOP_SETTING.openingPrice, shopPackPrice: 60, shopPackShare: 50, dailyReward: 10, stardustPerEclat: 3, oblivionPrice: 150, windRosePrice: 60 });
|
||
assert.deepEqual([before.recycling.count, before.recycling.stardust, before.recycling.byRarity[rarity]], [2, 2 * value, { count: 2, stardust: 2 * value }]);
|
||
// Une favorite garde son exemplaire : ses doublons se recyclent comme les autres.
|
||
service.setFavorite(player.id, editionId, true);
|
||
|
||
const one = service.recycleDuplicates(player.id, { editionId });
|
||
assert.deepEqual(one.recycled, { count: 1, stardust: value });
|
||
assert.equal(one.state.collection[0].quantity, 2);
|
||
const all = service.recycleDuplicates(player.id);
|
||
assert.deepEqual(all.recycled, { count: 1, stardust: value });
|
||
assert.equal(all.state.collection[0].quantity, 1);
|
||
assert.equal(all.state.wallet.stardust, 2 * value);
|
||
assert.throws(() => service.recycleDuplicates(player.id), /Aucun doublon/);
|
||
assert.throws(() => service.recycleDuplicates(player.id, { maxRarity: "mythic" }), /Rareté maximale invalide/);
|
||
// L'ouverture garde sa référence à la carte tirée et reste lisible après le recyclage.
|
||
const history = service.openingById(opened.opening.id, player.id);
|
||
assert.deepEqual(history.cards.map((card) => card.card?.name), opened.opening.cards.map((card) => card.card.name));
|
||
assert.equal(service.getState(player.id).rarestPull.editionId, editionId);
|
||
|
||
service.updateShopSetting(admin.id, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: 2 * value });
|
||
assert.throws(() => service.updateShopSetting(player.id, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: 1 }), /administrateur/);
|
||
assert.throws(() => service.updateShopSetting(admin.id, { stardustValues: { ...INITIAL_SHOP_SETTING.stardustValues, rare: -1 }, openingPrice: 1 }), /rare/);
|
||
assert.throws(() => service.updateShopSetting(admin.id, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: 0 }), /Prix/);
|
||
// Vide les ouvertures de bienvenue restantes sans changer la collection vérifiée plus bas.
|
||
database.db.prepare("UPDATE players SET openings_balance = 0 WHERE id = ?").run(player.id);
|
||
const bought = service.buyOpening(player.id);
|
||
assert.deepEqual(bought.wallet, { stardust: 0, purchasedOpenings: 1, eclats: 0 });
|
||
assert.throws(() => service.buyOpening(player.id), /Pas assez/);
|
||
// Plusieurs ouvertures d'un coup : quantité entière bornée, payée en une fois, sinon rien n'est débité.
|
||
assert.throws(() => service.buyOpening(player.id, { count: 0 }), /Nombre d’ouvertures invalide/);
|
||
assert.throws(() => service.buyOpening(player.id, { count: 101 }), /Nombre d’ouvertures invalide/);
|
||
assert.throws(() => service.buyOpening(player.id, { count: 1.5 }), /Nombre d’ouvertures invalide/);
|
||
database.db.prepare("UPDATE players SET stardust = ? WHERE id = ?").run(5 * value, player.id);
|
||
assert.throws(() => service.buyOpening(player.id, { count: 3 }), /Pas assez/);
|
||
const several = service.buyOpening(player.id, { count: 2 });
|
||
assert.deepEqual(several.wallet, { stardust: value, purchasedOpenings: 3, eclats: 0 });
|
||
assert.deepEqual(several.history.find((entry) => entry.type === "opening_purchased" && entry.details.count === 2)?.details, { price: 2 * value, count: 2, stardust: 4 * value });
|
||
database.db.prepare("UPDATE players SET stardust = 0, purchased_openings = 1 WHERE id = ?").run(player.id);
|
||
|
||
// La réserve est vide : seule l'ouverture achetée permet d'ouvrir, sans toucher à la réserve.
|
||
assert.equal(bought.recharge.openingsBalance, 0);
|
||
assert.throws(() => service.openPack(player.id, "primordial-nebula", "reserve-pack"), /ouverture/i);
|
||
const purchased = service.openPack(player.id, "primordial-nebula", "purchased-pack", { purchased: true });
|
||
assert.equal(purchased.state.wallet.purchasedOpenings, 0);
|
||
assert.equal(purchased.state.recharge.openingsBalance, 0);
|
||
service.completeOpening(player.id, purchased.opening.id);
|
||
assert.throws(() => service.openPack(player.id, "primordial-nebula", "purchased-again", { purchased: true }), /aucune ouverture achetée/);
|
||
const row = service.getAdminDashboard(admin.id).players.find((item) => item.id === player.id);
|
||
assert.equal(row.stardust, 0);
|
||
assert.equal(row.totalCards, 4);
|
||
database.close();
|
||
});
|
||
|
||
test("trades and gifts move duplicates only and campaign claims add cards", () => {
|
||
let now = 1_800_000_000_000;
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const quantity = (playerId, editionId) => service.getState(playerId).collection.find((entry) => entry.editionId === editionId)?.quantity ?? 0;
|
||
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "player", displayName: "Player" });
|
||
const adminOpening = service.openPack(admin.id, "primordial-nebula", "admin-pack").opening;
|
||
service.completeOpening(admin.id, adminOpening.id);
|
||
// Le hasard fixe tire trois fois la même carte : un exemplaire et deux doublons.
|
||
const drawn = adminOpening.cards[0].editionId;
|
||
assert.deepEqual(adminOpening.cards.map((card) => [card.isNewEdition, card.quantityBefore]), [[true, 0], [false, 1], [false, 2]]);
|
||
assert.equal(quantity(admin.id, drawn), 3);
|
||
|
||
const campaign = service.createCampaign(admin.id, {
|
||
name: "Premiers explorateurs",
|
||
reward: { items: [{ type: "card", editionId: "aurora-wolf-standard" }] },
|
||
code: "explo-01",
|
||
maxClaims: 1,
|
||
expiresAt: now + 60_000
|
||
});
|
||
assert.equal(campaign.campaign.code, "EXPLO-01");
|
||
const claimed = service.claimCampaign(player.id, "explo-01");
|
||
assert.deepEqual(claimed.reward, { items: [{ type: "card", editionId: "aurora-wolf-standard", quantity: 1 }] });
|
||
assert.equal(quantity(player.id, "aurora-wolf-standard"), 1);
|
||
assert.throws(() => service.claimCampaign(player.id, "EXPLO-01"), /déjà reçu/);
|
||
assert.throws(() => service.claimCampaign(admin.id, "EXPLO-01"), /nombre maximal/);
|
||
|
||
// Un exemplaire unique ne part jamais, ni en don ni dans un échange.
|
||
assert.throws(() => service.createTransfer(player.id, { type: "gift", recipientId: admin.id, editionId: "aurora-wolf-standard" }), /doublons/);
|
||
assert.throws(() => service.createTransfer(admin.id, { type: "trade", recipientId: player.id, editionId: drawn, requestedEditionId: "aurora-wolf-standard" }), /plus ce doublon/);
|
||
assert.throws(() => service.createTransfer(admin.id, { type: "gift", recipientId: admin.id, editionId: drawn }), /vous envoyer/);
|
||
assert.throws(() => service.createTransfer(admin.id, { type: "trade", recipientId: player.id, editionId: drawn, requestedEditionId: drawn }), /différentes/);
|
||
assert.throws(() => service.createTransfer(admin.id, { type: "gift", recipientId: "inconnu", editionId: drawn }), /introuvable/);
|
||
|
||
// Seuls l'identité publique et les doublons disponibles des autres joueurs sont exposés.
|
||
const traders = service.listTraders(player.id).traders;
|
||
assert.deepEqual(traders.map((trader) => trader.id).includes(player.id), false);
|
||
const adminTrader = traders.find((trader) => trader.id === admin.id);
|
||
assert.deepEqual(Object.keys(adminTrader).sort(), ["avatarUrl", "displayName", "duplicates", "id"]);
|
||
assert.deepEqual(adminTrader.duplicates.find((entry) => entry.editionId === drawn), { editionId: drawn, spare: 2 });
|
||
|
||
// Don : le doublon arrive immédiatement, le donneur garde ses autres exemplaires et le journal cite la carte.
|
||
const gift = service.createTransfer(admin.id, { type: "gift", recipientId: player.id, editionId: drawn });
|
||
assert.equal(gift.transfer.status, "completed");
|
||
assert.equal(gift.state.collection.find((entry) => entry.editionId === drawn).spare, 1);
|
||
assert.equal(quantity(player.id, drawn), 1);
|
||
assert.equal(service.getState(player.id).transfers.find((item) => item.id === gift.transfer.id).direction, "received");
|
||
assert.equal(service.getState(player.id).history.find((item) => item.type === "gift_completed").details.received, drawn);
|
||
assert.equal(service.getAdminDashboard(admin.id).players.find((item) => item.id === player.id).transfersCount, 1);
|
||
service.createTransfer(admin.id, { type: "gift", recipientId: player.id, editionId: drawn });
|
||
assert.equal(quantity(player.id, drawn), 2);
|
||
assert.throws(() => service.createTransfer(admin.id, { type: "gift", recipientId: player.id, editionId: drawn }), /doublons/);
|
||
|
||
// Échange refusé, annulé puis accepté : le doublon proposé est réservé, puis libéré ou échangé.
|
||
const adminCard = adminOpening.cards.map((card) => card.edition.id).find((id) => id !== drawn) || drawn;
|
||
for (let copies = 0; copies < 3; copies += 1) service.addCard(admin.id, "aurora-wolf-standard");
|
||
const propose = () => service.createTransfer(admin.id, { type: "trade", recipientId: player.id, editionId: "aurora-wolf-standard", requestedEditionId: drawn });
|
||
const spareOf = (playerId, id) => service.getState(playerId).collection.find((entry) => entry.editionId === id)?.spare ?? 0;
|
||
const reservedBefore = spareOf(admin.id, "aurora-wolf-standard");
|
||
const declined = propose();
|
||
assert.equal(declined.transfer.status, "open");
|
||
assert.equal(spareOf(admin.id, "aurora-wolf-standard"), reservedBefore - 1);
|
||
assert.throws(() => service.acceptTransfer(admin.id, declined.transfer.id), /plus disponible/);
|
||
assert.throws(() => service.cancelTransfer(player.id, declined.transfer.id), /plus disponible/);
|
||
const afterDecline = service.declineTransfer(player.id, declined.transfer.id);
|
||
assert.equal(afterDecline.transfers.find((item) => item.id === declined.transfer.id).declined, true);
|
||
assert.equal(spareOf(admin.id, "aurora-wolf-standard"), reservedBefore);
|
||
const cancelled = propose();
|
||
service.cancelTransfer(admin.id, cancelled.transfer.id);
|
||
assert.throws(() => service.acceptTransfer(player.id, cancelled.transfer.id), /plus disponible/);
|
||
assert.equal(spareOf(admin.id, "aurora-wolf-standard"), reservedBefore);
|
||
|
||
const accepted = propose();
|
||
const playerWolves = quantity(player.id, "aurora-wolf-standard");
|
||
const adminDrawn = quantity(admin.id, drawn);
|
||
const afterAccept = service.acceptTransfer(player.id, accepted.transfer.id);
|
||
assert.equal(afterAccept.transfers.find((item) => item.id === accepted.transfer.id).status, "completed");
|
||
assert.equal(quantity(player.id, "aurora-wolf-standard"), playerWolves + 1);
|
||
assert.equal(quantity(player.id, drawn), 1);
|
||
assert.equal(quantity(admin.id, drawn), adminDrawn + 1);
|
||
assert.ok(adminCard);
|
||
|
||
// Le doublon demandé peut partir avant la réponse : l'acceptation est alors refusée, sans rien déplacer.
|
||
service.addCard(player.id, drawn);
|
||
const stale = propose();
|
||
service.recycleDuplicates(player.id, { editionId: drawn });
|
||
assert.throws(() => service.acceptTransfer(player.id, stale.transfer.id), /doublons/);
|
||
assert.equal(service.getState(admin.id).transfers.find((item) => item.id === stale.transfer.id).status, "open");
|
||
|
||
// Une proposition sans réponse expire au bout de 7 jours et libère le doublon réservé.
|
||
now += 7 * 24 * 60 * 60 * 1000;
|
||
assert.equal(service.getState(admin.id).transfers.find((item) => item.id === stale.transfer.id).status, "expired");
|
||
assert.equal(spareOf(admin.id, "aurora-wolf-standard"), reservedBefore - 1);
|
||
now += 24 * 60 * 60 * 1000;
|
||
database.close();
|
||
});
|
||
|
||
test("legacy in-progress transfers are cancelled by the migration and free their duplicates", async (t) => {
|
||
const directory = await mkdtemp(join(tmpdir(), "sokkog-cards-transfers-"));
|
||
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, random: () => 0 });
|
||
const player = service.upsertPlayer({ discordId: "legacy", displayName: "Ancien" });
|
||
for (const [id, status] of [["t-open", "open"], ["t-joined", "joined"], ["t-done", "completed"]]) {
|
||
database.db.prepare("INSERT INTO transfers(id, code, type, initiator_id, offered_edition_id, status, created_at, expires_at) VALUES (?, ?, 'gift', ?, 'aurora-wolf-standard', ?, 1, 1)").run(id, id, player.id, status);
|
||
}
|
||
database.db.prepare("DELETE FROM schema_migrations WHERE version = 3").run();
|
||
database.db.exec("ALTER TABLE transfers DROP COLUMN declined");
|
||
database.close();
|
||
database = new CardsDatabase(path);
|
||
assert.deepEqual(database.db.prepare("SELECT status FROM transfers ORDER BY id").all().map((row) => row.status), ["completed", "cancelled", "cancelled"]);
|
||
database.close();
|
||
});
|
||
|
||
test("database backup passes integrity checks and restores ownership", async () => {
|
||
const directory = await mkdtemp(join(tmpdir(), "sokko-cards-backup-"));
|
||
const source = join(directory, "source.sqlite");
|
||
const backup = join(directory, "backup.sqlite");
|
||
const restored = join(directory, "restored.sqlite");
|
||
try {
|
||
const database = new CardsDatabase(source);
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||
const player = service.upsertPlayer({ discordId: "backup-player", displayName: "Backup" });
|
||
service.openPack(player.id, "primordial-nebula", "backup-pack");
|
||
database.close();
|
||
await backupCardsDatabase(source, backup);
|
||
assert.equal(verifyCardsDatabase(backup), true);
|
||
restoreCardsDatabase(backup, restored);
|
||
const restoredDatabase = new CardsDatabase(restored);
|
||
assert.equal(restoredDatabase.db.prepare("SELECT SUM(quantity) AS count FROM collection_cards").get().count, 3);
|
||
restoredDatabase.close();
|
||
} finally {
|
||
await rm(directory, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("a pending opening stays hidden from the player state until it is completed", () => {
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||
const player = service.upsertPlayer({ discordId: "spoiler", displayName: "Spoiler" });
|
||
const other = service.upsertPlayer({ discordId: "spoiler-other", displayName: "Autre" });
|
||
const { opening, state: pendingState } = service.openPack(player.id, "primordial-nebula", "spoiler-pack");
|
||
const [editionId] = opening.cards.map((card) => card.editionId);
|
||
assert.equal(pendingState.pendingOpening.id, opening.id);
|
||
assert.equal(pendingState.rarestPull, null);
|
||
assert.deepEqual(pendingState.collection, []);
|
||
assert.equal(pendingState.recycling.count, 0);
|
||
assert.throws(() => service.createTransfer(player.id, { type: "gift", recipientId: other.id, editionId }), /ouverture en cours/);
|
||
|
||
const completed = service.completeOpening(player.id, opening.id);
|
||
assert.equal(completed.pendingOpening, null);
|
||
assert.ok(completed.rarestPull);
|
||
assert.equal(completed.collection.reduce((total, entry) => total + entry.quantity, 0), 3);
|
||
database.close();
|
||
});
|
||
|
||
test("displayed odds only count the rarities a pack can really give", () => {
|
||
const collectionOf = (published, id) => published.collections.find((collection) => collection.id === id);
|
||
const states = [...INITIAL_COLLECTION_STATES, { collectionId: "stardust", active: true }];
|
||
const rates = [...INITIAL_DROP_RATES, { collectionId: "stardust", rarityWeights: INITIAL_DROP_RATES[0].rarityWeights }];
|
||
const empty = buildPublishedCatalog(baseCatalog, { collectionStates: states, dropRates: rates });
|
||
assert.deepEqual(drawableRarities(empty, collectionOf(empty, "primordial-nebula")), ["common", "rare", "epic", "legendary"]);
|
||
assert.deepEqual(drawableRarities(empty, collectionOf(empty, "stardust")), ["common", "rare", "epic", "legendary"]);
|
||
assert.deepEqual(publicCatalog(empty).collections.find((collection) => collection.id === "primordial-nebula").drawableRarities, ["common", "rare", "epic", "legendary"]);
|
||
|
||
const withMythic = buildPublishedCatalog(baseCatalog, { variations: TEST_MYTHIC_VARIATIONS, collectionStates: states, dropRates: rates });
|
||
assert.equal(drawableRarities(withMythic, collectionOf(withMythic, "astral-genesis")).includes("mythic"), true);
|
||
assert.equal(drawableRarities(withMythic, collectionOf(withMythic, "primordial-nebula")).includes("mythic"), false);
|
||
assert.equal(drawableRarities(withMythic, collectionOf(withMythic, "stardust")).includes("mythic"), true);
|
||
const retired = buildPublishedCatalog(baseCatalog, { variations: TEST_MYTHIC_VARIATIONS.map((variation) => ({ ...variation, status: "retired" })), collectionStates: states, dropRates: rates });
|
||
assert.equal(drawableRarities(retired, collectionOf(retired, "astral-genesis")).includes("mythic"), false);
|
||
|
||
// Le paquet boutique tire aussi dans les autres collections actives : le décompte ne se limite pas à ses propres cartes.
|
||
const publishedEmpty = publicCatalog(empty);
|
||
const shopCounts = publishedEmpty.collections.find((collection) => collection.id === "stardust").drawableCounts;
|
||
const drawnCollectionIds = new Set(publishedEmpty.collections.filter((collection) => collection.active && collection.id !== "stardust").map((collection) => collection.id));
|
||
const othersCommon = publishedEmpty.editions.filter((edition) => edition.rarity === "common" && !edition.promotional && drawnCollectionIds.has(publishedEmpty.cards.find((card) => card.id === edition.cardId).collectionId)).length;
|
||
assert.equal(shopCounts.common, othersCommon);
|
||
assert.ok(othersCommon > 0);
|
||
assert.equal(shopCounts.mythic, 0);
|
||
assert.equal(publishedEmpty.collections.find((collection) => collection.id === "primordial-nebula").drawableCounts.common, 36);
|
||
|
||
const weights = { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 };
|
||
const percent = (drawable) => Object.fromEntries(rarityPercentages(empty.rarities, weights, drawable).map(({ rarity, percent: value }) => [rarity.id, value]));
|
||
assert.equal(percent(undefined).mythic, 1);
|
||
const filtered = percent(["common", "rare", "epic", "legendary"]);
|
||
assert.equal(filtered.mythic, 0);
|
||
assert.ok(Math.abs(Object.values(filtered).reduce((total, value) => total + value, 0) - 100) < 1e-9);
|
||
assert.ok(Math.abs(filtered.common - 64 / 99 * 100) < 1e-9);
|
||
});
|
||
|
||
test("deleting an account erases the identity and possessions but keeps shared history consistent", () => {
|
||
let now = 1_800_000_000_000;
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const leaver = service.upsertPlayer({ discordId: "leaver-discord", displayName: "Leaver", avatarUrl: "https://cdn.invalid/a.png" });
|
||
const friend = service.upsertPlayer({ discordId: "friend-discord", displayName: "Friend" });
|
||
const admin = service.upsertPlayer({ discordId: "admin-discord", displayName: "Admin", isAdmin: true });
|
||
const session = service.createSession(leaver.id);
|
||
const editionId = "aurora-wolf-standard";
|
||
for (const player of [leaver, friend]) for (let copy = 0; copy < 3; copy += 1) service.addCard(player.id, editionId);
|
||
service.addCard(friend.id, "starvoid-dragon-standard");
|
||
service.addCard(friend.id, "starvoid-dragon-standard");
|
||
service.setFavorite(leaver.id, editionId, true);
|
||
const { opening } = service.openPack(leaver.id, "primordial-nebula", "leaver-pack");
|
||
service.completeOpening(leaver.id, opening.id);
|
||
const trade = service.createTransfer(leaver.id, { type: "trade", recipientId: friend.id, editionId, requestedEditionId: "starvoid-dragon-standard" }).transfer;
|
||
database.db.prepare("UPDATE players SET stardust = 50, purchased_openings = 2 WHERE id = ?").run(leaver.id);
|
||
const campaign = service.createCampaign(admin.id, { name: "Gift", code: "LEAVER-GIFT", reward: { items: [{ type: "pack", collectionId: "primordial-nebula", quantity: 1 }] } }).campaign;
|
||
service.claimCampaign(leaver.id, "LEAVER-GIFT");
|
||
|
||
service.deleteAccount(leaver.id);
|
||
|
||
assert.equal(service.getSession(session.token), null);
|
||
const row = database.db.prepare("SELECT * FROM players WHERE id = ?").get(leaver.id);
|
||
assert.equal(row.discord_id.startsWith("deleted:"), true);
|
||
assert.equal(row.display_name, "Joueur supprimé");
|
||
assert.equal(row.avatar_url, "");
|
||
assert.equal(row.is_admin, 0);
|
||
assert.equal(row.stardust, 0);
|
||
assert.equal(row.purchased_openings, 0);
|
||
assert.equal(row.deleted_at, now);
|
||
for (const table of ["collection_cards", "favorites", "idempotency", "sessions"]) assert.equal(database.db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE player_id = ?`).get(leaver.id).count, 0, table);
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM gift_packs WHERE player_id = ? AND opening_id IS NULL").get(leaver.id).count, 0);
|
||
assert.equal(JSON.stringify(database.db.prepare("SELECT * FROM players WHERE id = ?").get(leaver.id)).includes("leaver-discord"), false);
|
||
|
||
const friendState = service.getState(friend.id);
|
||
const friendTrade = friendState.transfers.find((transfer) => transfer.id === trade.id);
|
||
assert.equal(friendTrade.status, "cancelled");
|
||
assert.equal(friendTrade.initiator.displayName, "Joueur supprimé");
|
||
assert.equal(service.listTraders(friend.id).traders.some((trader) => trader.id === leaver.id), false);
|
||
assert.throws(() => service.createTransfer(friend.id, { type: "gift", recipientId: leaver.id, editionId }), /introuvable/);
|
||
const dashboard = service.getAdminDashboard(admin.id);
|
||
assert.equal(dashboard.stats.totalPlayers, 2);
|
||
assert.equal(dashboard.stats.activePlayers7d, 0);
|
||
assert.equal(dashboard.players.some((player) => player.id === leaver.id), false);
|
||
assert.equal(service.campaignDetail(admin.id, campaign.id).claims[0].playerName, "Joueur supprimé");
|
||
|
||
now += 1000;
|
||
const returning = service.upsertPlayer({ discordId: "leaver-discord", displayName: "Leaver" });
|
||
assert.notEqual(returning.id, leaver.id);
|
||
assert.deepEqual(service.getState(returning.id).collection, []);
|
||
assert.throws(() => service.deleteAccount(leaver.id), /introuvable/);
|
||
database.close();
|
||
});
|
||
|
||
test("maintenance anonymises long inactive accounts and purges expired technical data", () => {
|
||
const day = 24 * 60 * 60 * 1000;
|
||
let now = 1_800_000_000_000;
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const stale = service.upsertPlayer({ discordId: "stale", displayName: "Stale" });
|
||
const returning = service.upsertPlayer({ discordId: "returning", displayName: "Returning" });
|
||
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
|
||
service.addCard(stale.id, "aurora-wolf-standard");
|
||
const expiredSession = service.createSession(stale.id);
|
||
const { opening } = service.openPack(returning.id, "primordial-nebula", "old-key");
|
||
service.completeOpening(returning.id, opening.id);
|
||
|
||
// Une reconnexion juste avant le seuil repousse l'échéance.
|
||
now += 400 * day;
|
||
service.upsertPlayer({ discordId: "returning", displayName: "Returning" });
|
||
service.runMaintenance();
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM sessions WHERE player_id = ?").get(stale.id).count, 0, "expired session");
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM idempotency").get().count, 0, "old idempotency key");
|
||
assert.equal(database.db.prepare("SELECT deleted_at FROM players WHERE id = ?").get(stale.id).deleted_at, null);
|
||
assert.equal(service.getSession(expiredSession.token), null);
|
||
|
||
now += 330 * day - 1;
|
||
service.runMaintenance();
|
||
assert.equal(database.db.prepare("SELECT deleted_at FROM players WHERE id = ?").get(stale.id).deleted_at, null, "just before the threshold");
|
||
|
||
now += 1;
|
||
service.runMaintenance();
|
||
const anonymised = database.db.prepare("SELECT * FROM players WHERE id = ?").get(stale.id);
|
||
assert.equal(anonymised.deleted_at, now);
|
||
assert.equal(anonymised.display_name, "Joueur supprimé");
|
||
assert.equal(anonymised.discord_id.startsWith("deleted:"), true);
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM collection_cards WHERE player_id = ?").get(stale.id).count, 0);
|
||
assert.deepEqual(JSON.parse(database.db.prepare("SELECT details_json FROM audit_log WHERE player_id = ? AND event_type = 'account_deleted'").get(stale.id).details_json), { reason: "inactivity" });
|
||
assert.equal(database.db.prepare("SELECT deleted_at FROM players WHERE id = ?").get(returning.id).deleted_at, null);
|
||
assert.equal(database.db.prepare("SELECT deleted_at FROM players WHERE id = ?").get(admin.id).deleted_at, null);
|
||
|
||
const logCount = () => database.db.prepare("SELECT COUNT(*) AS count FROM audit_log").get().count;
|
||
const before = logCount();
|
||
service.runMaintenance();
|
||
assert.equal(logCount(), before);
|
||
database.close();
|
||
});
|
||
|
||
test("restoring replaces the database even when the stopped service left a write-ahead log", async () => {
|
||
const directory = await mkdtemp(join(tmpdir(), "sokko-cards-restore-wal-"));
|
||
const live = join(directory, "live.sqlite");
|
||
const backup = join(directory, "backup.sqlite");
|
||
const countPlayers = (database) => database.db.prepare("SELECT COUNT(*) AS count FROM players").get().count;
|
||
try {
|
||
const database = new CardsDatabase(live);
|
||
new CardsService({ database, catalog: baseCatalog }).upsertPlayer({ discordId: "before-backup", displayName: "Avant" });
|
||
database.close();
|
||
await backupCardsDatabase(live, backup);
|
||
// Un process tué sans fermer la base laisse ses écritures dans le WAL : la restauration ne doit pas les rejouer.
|
||
const killedWriter = `import { DatabaseSync } from "node:sqlite";
|
||
const db = new DatabaseSync(${JSON.stringify(live)});
|
||
db.exec("PRAGMA journal_mode = WAL");
|
||
db.prepare("INSERT INTO players(id, discord_id, display_name, created_at) VALUES ('after', 'after', 'Après', 0)").run();
|
||
process.kill(process.pid, "SIGKILL");`;
|
||
const writer = spawnSync(process.execPath, ["--no-warnings", "--input-type=module", "-e", killedWriter]);
|
||
assert.equal(writer.signal, "SIGKILL", String(writer.stderr));
|
||
await access(`${live}-wal`);
|
||
restoreCardsDatabase(backup, live);
|
||
assert.deepEqual((await readdir(directory)).sort(), ["backup.sqlite", "live.sqlite"]);
|
||
const restored = new CardsDatabase(live);
|
||
assert.equal(countPlayers(restored), 1);
|
||
restored.close();
|
||
} finally {
|
||
await rm(directory, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("scheduled backups are dated, verified and pruned without touching other files", async () => {
|
||
const directory = await mkdtemp(join(tmpdir(), "sokko-cards-scheduled-"));
|
||
const source = join(directory, "source.sqlite");
|
||
const backups = join(directory, "backups");
|
||
try {
|
||
const database = new CardsDatabase(source);
|
||
database.close();
|
||
const written = [];
|
||
for (const day of ["2026-11-01", "2026-11-02", "2026-11-03", "2026-11-03"]) written.push(await runScheduledBackup(source, backups, { keep: 2, now: new Date(`${day}T04:00:00Z`) }));
|
||
assert.equal(written.at(-1), join(backups, "nebula-cards-2026-11-03.sqlite"));
|
||
assert.deepEqual((await readdir(backups)).sort(), ["nebula-cards-2026-11-02.sqlite", "nebula-cards-2026-11-03.sqlite"]);
|
||
await writeFile(join(backups, "nebula-cards-before-cleanup.sqlite"), "");
|
||
await runScheduledBackup(source, backups, { keep: 1, now: new Date("2026-11-04T04:00:00Z") });
|
||
assert.deepEqual((await readdir(backups)).sort(), ["nebula-cards-2026-11-04.sqlite", "nebula-cards-before-cleanup.sqlite"]);
|
||
assert.equal(verifyCardsDatabase(join(backups, "nebula-cards-2026-11-04.sqlite")), true);
|
||
await assert.rejects(runScheduledBackup(source, backups, { keep: 0 }), /keep/);
|
||
} finally {
|
||
await rm(directory, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("published catalog adds mythic variations and opening settings stored in the database", () => {
|
||
const legendary = baseCatalog.editions.find((edition) => edition.cardId === "starvoid-dragon" && edition.rarity === "legendary");
|
||
const published = buildPublishedCatalog(baseCatalog, {
|
||
variations: [
|
||
{ editionId: "starvoid-dragon-spectral-prism-solar", cardId: "starvoid-dragon", finishId: "spectral-prism-solar", status: "active" },
|
||
{ editionId: "starvoid-dragon-spectral-prism-aurora", cardId: "starvoid-dragon", finishId: "spectral-prism-aurora", status: "retired" }
|
||
],
|
||
openingSettings: [
|
||
{ scope: "card", targetId: "starvoid-dragon", particleShapeId: "snowflakes", particlePaletteId: null },
|
||
{ scope: "collection", targetId: "astral-genesis", particleShapeId: null, particlePaletteId: null }
|
||
]
|
||
});
|
||
const dragonEditions = published.editions.filter((edition) => edition.cardId === "starvoid-dragon");
|
||
// Les variations suivent leur légendaire, dans l'ordre des finitions.
|
||
assert.deepEqual(dragonEditions.map((edition) => [edition.id, edition.retired ?? false]), [
|
||
[legendary.id, false],
|
||
["starvoid-dragon-spectral-prism-solar", false],
|
||
["starvoid-dragon-spectral-prism-aurora", true]
|
||
]);
|
||
assert.equal(dragonEditions[2].legendaryEditionId, legendary.id);
|
||
assert.equal(baseCatalog.editions.some((edition) => edition.rarity === "mythic"), false);
|
||
assert.deepEqual(published.mythicOpeningSettings, [{ scope: "card", targetId: "starvoid-dragon", particleShapeId: "snowflakes", particlePaletteId: null }]);
|
||
const variation = (overrides) => ({ editionId: "starvoid-dragon-spectral-prism-solar", cardId: "starvoid-dragon", finishId: "spectral-prism-solar", status: "active", ...overrides });
|
||
assert.throws(() => buildPublishedCatalog(baseCatalog, { variations: [variation({ editionId: "astral-booster-spectral-prism-solar", cardId: "astral-booster" })] }), /legendary card/);
|
||
assert.throws(() => buildPublishedCatalog(baseCatalog, { variations: [variation({ editionId: "starvoid-dragon-standard", finishId: "standard" })] }), /legendary card/);
|
||
assert.throws(() => buildPublishedCatalog(baseCatalog, { variations: [variation(), variation()] }), /legendary card/);
|
||
assert.throws(() => buildPublishedCatalog(baseCatalog, { openingSettings: [{ scope: "card", targetId: "starvoid-dragon", particleShapeId: "bubbles" }] }), /Invalid mythic opening setting/);
|
||
assert.doesNotThrow(() => buildPublishedCatalog(baseCatalog, { openingSettings: [{ scope: "card", targetId: "starvoid-dragon", particlePaletteId: "match-holo" }] }));
|
||
|
||
const astral = structuredClone(catalog);
|
||
astral.editions.find((edition) => edition.id === "mythic-card-pull-spectral-prism-solar").retired = true;
|
||
assert.ok(drawPack(astral, "astral-genesis", (maximum) => maximum - 1).every((id) => id !== "mythic-card-pull-spectral-prism-solar"));
|
||
});
|
||
|
||
|
||
test("mythic opening style inherits shape and palette independently from card, collection and default", () => {
|
||
const cardId = "mythic-card-pull";
|
||
const collectionId = "astral-genesis";
|
||
const plain = resolveMythicOpeningStyle(catalog, cardId, collectionId);
|
||
assert.equal(plain.effect.id, "mythic-default-opening");
|
||
assert.deepEqual([plain.shape, plain.palette], [{ id: "sparks", source: "default" }, { id: "rainbow", source: "default" }]);
|
||
const configured = { ...catalog, mythicOpeningSettings: [
|
||
{ scope: "collection", targetId: collectionId, particleShapeId: "snowflakes", particlePaletteId: "epic-violet" },
|
||
{ scope: "card", targetId: cardId, particleShapeId: null, particlePaletteId: "match-holo" }
|
||
] };
|
||
const style = resolveMythicOpeningStyle(configured, cardId, collectionId);
|
||
assert.deepEqual([style.shape, style.palette], [{ id: "snowflakes", source: "collection" }, { id: "match-holo", source: "card" }]);
|
||
const sibling = resolveMythicOpeningStyle(configured, "astral-booster", collectionId);
|
||
assert.deepEqual([sibling.shape.source, sibling.palette], ["collection", { id: "epic-violet", source: "collection" }]);
|
||
assert.equal(resolveOpeningEffect(catalog, "rare").id, "rare-opening");
|
||
});
|
||
|
||
test("admin catalog mutations persist mythic variations and keep owned ones out of drops only", () => {
|
||
const now = 1_800_000_000_000;
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: (maximum) => maximum - 1 });
|
||
const admin = service.upsertPlayer({ discordId: "catalog-admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "catalog-player", displayName: "Player" });
|
||
assert.throws(() => service.setCardMythicConfig(player.id, "mythic-card-pull", { finishIds: [] }), /administrateur/);
|
||
assert.throws(() => service.setCardMythicConfig(admin.id, "astral-booster", { finishIds: [] }), /légendaire/);
|
||
assert.throws(() => service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["standard"] }), /holographiques/);
|
||
|
||
assert.throws(() => service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: [], opening: { particleShapeId: "bubbles" } }), /Forme/);
|
||
const result = service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-solar", "spectral-prism-aurora"], opening: { particleShapeId: "snowflakes", particlePaletteId: "match-holo" } });
|
||
assert.ok(result.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-aurora" && !edition.retired));
|
||
assert.deepEqual(result.catalog.mythicOpeningSettings, [{ scope: "card", targetId: "mythic-card-pull", particleShapeId: "snowflakes", particlePaletteId: "match-holo" }]);
|
||
|
||
const opened = service.openPack(player.id, "astral-genesis", "catalog-pack");
|
||
const ownedMythic = opened.opening.cards.find((card) => card.edition.rarity === "mythic").editionId;
|
||
assert.equal(service.getAdminDashboard(admin.id).editionOwners[ownedMythic], 1);
|
||
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: [], opening: {} });
|
||
const reloaded = new CardsService({ database, catalog: baseCatalog, now: () => now });
|
||
const owned = reloaded.catalog.editions.find((edition) => edition.id === ownedMythic);
|
||
assert.equal(owned.retired, true);
|
||
assert.ok(reloaded.catalog.editions.filter((edition) => edition.cardId === "mythic-card-pull" && edition.rarity === "mythic").every((edition) => edition.retired || edition.id === ownedMythic));
|
||
assert.equal(reloaded.catalog.mythicOpeningSettings.length, 0);
|
||
|
||
// Une variation que personne ne possède mais qu'une campagne cite est retirée, pas supprimée : le code reste utilisable.
|
||
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-cosmic"], opening: {} });
|
||
const cosmic = "mythic-card-pull-spectral-prism-cosmic";
|
||
service.createCampaign(admin.id, { name: "Cosmique", reward: { items: [{ type: "card", editionId: cosmic }, { type: "pack", collectionId: "astral-genesis", guarantee: { type: "edition", editionId: cosmic } }] }, code: "COSMIC-01", maxClaims: null, expiresAt: null });
|
||
assert.equal(service.getAdminDashboard(admin.id).editionCampaigns[cosmic], 1);
|
||
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: [], opening: {} });
|
||
assert.equal(service.catalog.editions.find((edition) => edition.id === cosmic)?.retired, true);
|
||
service.completeOpening(player.id, opened.opening.id);
|
||
const claimed = service.claimCampaign(player.id, "COSMIC-01");
|
||
assert.ok(claimed.state.collection.some((item) => item.editionId === cosmic));
|
||
const gift = service.openGiftPack(player.id, claimed.state.giftPacks[0].id, "cosmic-gift");
|
||
assert.ok(gift.opening.cards.some((card) => card.editionId === cosmic));
|
||
assert.equal(service.getState(player.id).collection.some((item) => item.editionId === ownedMythic && item.edition), true);
|
||
|
||
service.setCollectionMythicOpening(admin.id, "astral-genesis", { particleShapeId: "snowflakes" });
|
||
assert.deepEqual(service.catalog.mythicOpeningSettings, [{ scope: "collection", targetId: "astral-genesis", particleShapeId: "snowflakes", particlePaletteId: null }]);
|
||
assert.throws(() => service.setCollectionMythicOpening(admin.id, "astral-genesis", { particlePaletteId: "unknown" }), /inconnue/);
|
||
service.setCollectionMythicOpening(admin.id, "astral-genesis", {});
|
||
assert.deepEqual(service.catalog.mythicOpeningSettings, []);
|
||
database.close();
|
||
});
|
||
|
||
test("mythic variations live only in the database and a new database starts without any", () => {
|
||
const versionedMythic = structuredClone(rawCatalog);
|
||
versionedMythic.editions.push({ id: "starvoid-dragon-spectral-prism-solar", cardId: "starvoid-dragon", rarity: "mythic", finishIds: ["spectral-prism-solar"], promotional: false, transferable: true, legendaryEditionId: "starvoid-dragon-standard" });
|
||
assert.throws(() => assertVersionedCatalogScope(versionedMythic), /admin database/);
|
||
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000 });
|
||
assert.equal(service.catalog.editions.some((edition) => edition.rarity === "mythic"), false);
|
||
assert.deepEqual(service.catalog.mythicOpeningSettings, []);
|
||
// Le poids mythique reste en place : le tirage ignore la rareté tant qu'aucune variation n'existe.
|
||
for (const collectionId of ["primordial-nebula", "astral-genesis"]) {
|
||
assert.equal(service.catalog.collections.find((collection) => collection.id === collectionId).dropWeights.mythic, 1);
|
||
assert.ok(drawPack(service.catalog, collectionId, (maximum) => maximum - 1).every((id) => service.catalog.editions.find((edition) => edition.id === id).rarity !== "mythic"));
|
||
}
|
||
|
||
// Une variation que personne ne possède suit la règle commune : elle est supprimée, pas seulement retirée.
|
||
const admin = service.upsertPlayer({ discordId: "seed-admin", displayName: "Admin", isAdmin: true });
|
||
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-solar"] });
|
||
assert.ok(service.catalog.editions.find((edition) => edition.id === "mythic-card-pull-spectral-prism-solar").legendaryEditionId === "mythic-card-pull-standard");
|
||
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-aurora"] });
|
||
assert.equal(service.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-solar"), false);
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM mythic_variations WHERE edition_id = 'mythic-card-pull-spectral-prism-solar'").get().count, 0);
|
||
database.close();
|
||
});
|
||
|
||
test("pack availability and drop rates live in the database and apply immediately", () => {
|
||
assert.equal("dropTables" in rawCatalog, false);
|
||
assert.ok(rawCatalog.collections.every((collection) => !("active" in collection) && !("dropWeights" in collection)));
|
||
assert.deepEqual(rawCatalog.rarities.map((rarity) => rarity.recommendedWeight), [64, 24, 8, 3, 1]);
|
||
assert.throws(() => assertVersionedCatalogScope({ ...structuredClone(rawCatalog), dropTables: [] }), /dropTables/);
|
||
const withState = structuredClone(rawCatalog);
|
||
withState.collections[0].active = true;
|
||
assert.throws(() => assertVersionedCatalogScope(withState), /availability/);
|
||
const withRates = structuredClone(rawCatalog);
|
||
withRates.collections[0].dropWeights = { common: 1, rare: 0, epic: 0, legendary: 0, mythic: 0 };
|
||
assert.throws(() => assertVersionedCatalogScope(withRates), /drop rates/);
|
||
const badRecommendation = structuredClone(rawCatalog);
|
||
badRecommendation.rarities[0].recommendedWeight = -1;
|
||
assert.throws(() => prepareVersionedCatalog(badRecommendation), /recommended weights/);
|
||
|
||
// Une collection sans état est fermée ; un paquet ouvert doit avoir des taux de tirage.
|
||
assert.ok(buildPublishedCatalog(baseCatalog).collections.every((collection) => collection.active === false && !collection.dropWeights));
|
||
assert.throws(() => buildPublishedCatalog(baseCatalog, { collectionStates: [{ collectionId: "astral-genesis", active: true }] }), /needs drop rates/);
|
||
assert.deepEqual(catalog.collections.find((collection) => collection.id === "astral-genesis").dropWeights, { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 });
|
||
|
||
let now = Date.parse("2026-11-04T12:00:00.000Z");
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "packs-admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "packs-player", displayName: "Player" });
|
||
|
||
assert.throws(() => service.setDropRates(player.id, "astral-genesis", { common: 1, rare: 0, epic: 0, legendary: 0, mythic: 0 }), /administrateur/);
|
||
assert.throws(() => service.setDropRates(admin.id, "astral-genesis", { common: 1, rare: 0, epic: 0, legendary: 0 }), /Poids invalides/);
|
||
assert.throws(() => service.setDropRates(admin.id, "astral-genesis", { common: 0, rare: 0, epic: 0, legendary: 0, mythic: 0 }), /Poids invalides/);
|
||
assert.throws(() => service.setDropRates(admin.id, "astral-genesis", { common: 1.5, rare: 0, epic: 0, legendary: 0, mythic: 1 }), /Poids invalides/);
|
||
assert.throws(() => service.setDropRates(admin.id, "astral-genesis", { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 }), /déjà en vigueur/);
|
||
|
||
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-solar"] });
|
||
service.setDropRates(admin.id, "astral-genesis", { common: 0, rare: 0, epic: 0, legendary: 0, mythic: 1 });
|
||
const opening = service.openPack(player.id, "astral-genesis", "packs-mythic");
|
||
assert.ok(opening.opening.cards.every((card) => card.edition.rarity === "mythic"));
|
||
// Le journal d'audit garde les anciens et les nouveaux poids.
|
||
const audit = database.db.prepare("SELECT details_json FROM audit_log WHERE event_type = 'drop_rates_updated' AND entity_id = 'astral-genesis'").get();
|
||
assert.deepEqual(JSON.parse(audit.details_json), { previous: { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 }, rarityWeights: { common: 0, rare: 0, epic: 0, legendary: 0, mythic: 1 } });
|
||
|
||
service.completeOpening(player.id, opening.opening.id);
|
||
service.setCollectionActive(admin.id, "astral-genesis", false);
|
||
assert.equal(service.catalog.collections.find((collection) => collection.id === "astral-genesis").active, false);
|
||
now += INITIAL_RECHARGE_SETTING.intervalMs;
|
||
assert.throws(() => service.openPack(player.id, "astral-genesis", "packs-closed"), /pas disponible/);
|
||
service.setCollectionActive(admin.id, "astral-genesis", true);
|
||
assert.throws(() => service.setCollectionActive(admin.id, "astral-genesis", "yes"), /invalide/);
|
||
assert.throws(() => service.setCollectionActive(admin.id, "unknown", true), /introuvable/);
|
||
const reloaded = new CardsService({ database, catalog: baseCatalog, now: () => now });
|
||
assert.equal(reloaded.catalog.collections.find((collection) => collection.id === "astral-genesis").dropWeights.mythic, 1);
|
||
database.close();
|
||
});
|
||
|
||
|
||
test("gift packs apply custom rates and guarantees without spending recharge", () => {
|
||
const rank = (rarity) => catalog.rarities.findIndex((item) => item.id === rarity);
|
||
const rarityOf = (id) => catalog.editions.find((edition) => edition.id === id).rarity;
|
||
const commonOnly = { common: 1, rare: 0, epic: 0, legendary: 0, mythic: 0 };
|
||
assert.ok(drawPack(catalog, "astral-genesis", () => 0, { weights: commonOnly }).every((id) => rarityOf(id) === "common"));
|
||
// « Au moins 2 cartes rares ou mieux » : les cartes les plus communes sont améliorées.
|
||
const upgraded = drawPack(catalog, "astral-genesis", () => 0, { weights: commonOnly, guarantee: { type: "rarity", rarity: "rare", count: 2 } });
|
||
assert.equal(upgraded.filter((id) => rank(rarityOf(id)) >= rank("rare")).length, 2);
|
||
const legendaryOrBetter = drawPack(catalog, "astral-genesis", () => 0, { guarantee: { type: "rarity", rarity: "legendary", count: 3 } });
|
||
assert.ok(legendaryOrBetter.every((id) => rank(rarityOf(id)) >= rank("legendary")));
|
||
const withCard = drawPack(catalog, "astral-genesis", () => 0, { weights: commonOnly, guarantee: { type: "edition", editionId: "mythic-card-pull-spectral-prism-solar" } });
|
||
assert.ok(withCard.includes("mythic-card-pull-spectral-prism-solar"));
|
||
const closed = { ...catalog, collections: catalog.collections.map((collection) => ({ ...collection, active: false })) };
|
||
assert.throws(() => drawPack(closed, "astral-genesis", () => 0), /pas disponible/);
|
||
assert.equal(drawPack(closed, "astral-genesis", () => 0, { requireActive: false }).length, 3);
|
||
// Si les cartes tirables avec les poids personnalisés ont été retirées, le paquet reprend les taux de la collection.
|
||
const withoutCommons = { ...catalog, editions: catalog.editions.filter((edition) => edition.rarity !== "common") };
|
||
const fallback = drawPack(withoutCommons, "astral-genesis", () => 0, { weights: commonOnly });
|
||
assert.equal(fallback.length, 3);
|
||
assert.ok(fallback.every((id) => rank(rarityOf(id)) > rank("common")));
|
||
|
||
let now = 1_800_000_000_000;
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "gift-admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "gift-player", displayName: "Player" });
|
||
const other = service.upsertPlayer({ discordId: "gift-other", displayName: "Other" });
|
||
const pack = { type: "pack", collectionId: "astral-genesis", rarityWeights: commonOnly, guarantee: { type: "rarity", rarity: "legendary", count: 1 } };
|
||
const reward = { items: [pack] };
|
||
assert.throws(() => service.createCampaign(player.id, { name: "X", reward, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /administrateur/);
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward: { items: [{ ...pack, guarantee: { type: "rarity", rarity: "legendary", count: 4 } }] }, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /Garantie invalide/);
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward: { items: [{ ...pack, guarantee: { type: "edition", editionId: "starvoid-dragon-standard" } }] }, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /appartenir/);
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward, code: "x", maxClaims: 2, expiresAt: now + 60_000 }), /8 à 24/);
|
||
const shared = service.createCampaign(admin.id, { name: "Live", reward, code: "live-2026", maxClaims: 2, expiresAt: now + 60_000 });
|
||
assert.equal(shared.campaign.code, "LIVE-2026");
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "Copie", reward, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /déjà utilisé/);
|
||
|
||
// Le paquet est mis de côté, puis ouvert sans consommer la réserve, même collection fermée.
|
||
const before = service.getState(player.id).recharge.openingsBalance;
|
||
const claim = service.claimCampaign(player.id, "LIVE-2026");
|
||
assert.equal(claim.reward.items[0].type, "pack");
|
||
assert.equal(claim.state.giftPacks.length, 1);
|
||
service.claimCampaign(other.id, "LIVE-2026");
|
||
assert.throws(() => service.claimCampaign(admin.id, "LIVE-2026"), /nombre maximal/);
|
||
service.setCollectionActive(admin.id, "astral-genesis", false);
|
||
const opened = service.openGiftPack(player.id, claim.state.giftPacks[0].id, "gift-1");
|
||
// L'ouverture porte les options du paquet offert : l'écran de révélation affiche les taux réellement appliqués.
|
||
assert.deepEqual(opened.opening.options, claim.state.giftPacks[0].options);
|
||
assert.equal(opened.state.recharge.openingsBalance, before);
|
||
assert.equal(opened.state.giftPacks.length, 0);
|
||
assert.ok(opened.opening.cards.some((card) => rank(card.edition.rarity) >= rank("legendary")));
|
||
assert.equal(service.openGiftPack(player.id, claim.state.giftPacks[0].id, "gift-1").opening.id, opened.opening.id);
|
||
assert.throws(() => service.openGiftPack(player.id, claim.state.giftPacks[0].id, "gift-2"), /ouverture en cours/);
|
||
service.completeOpening(player.id, opened.opening.id);
|
||
assert.throws(() => service.openGiftPack(player.id, claim.state.giftPacks[0].id, "gift-2"), /plus disponible/);
|
||
// L'activité du paquet compte l'ouverture offerte ; elle sort de la fenêtre après 7 jours.
|
||
assert.deepEqual(service.getAdminDashboard(admin.id).packActivity7d["astral-genesis"], { openings: 1, gifted: 1 });
|
||
now += 8 * 24 * 3_600_000;
|
||
assert.equal(service.getAdminDashboard(admin.id).packActivity7d["astral-genesis"], undefined);
|
||
now -= 8 * 24 * 3_600_000;
|
||
|
||
const detail = service.campaignDetail(admin.id, shared.campaign.id);
|
||
assert.equal(detail.campaign.claimedCount, 2);
|
||
assert.deepEqual(detail.claims.map((item) => item.playerName), ["Player", "Other"]);
|
||
|
||
// Révocation et expiration.
|
||
const revoked = service.createCampaign(admin.id, { name: "Révoquée", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "REVOKED-1", maxClaims: null, expiresAt: null });
|
||
service.revokeCampaign(admin.id, revoked.campaign.id);
|
||
assert.throws(() => service.claimCampaign(other.id, "REVOKED-1"), /révoqué/);
|
||
const short = service.createCampaign(admin.id, { name: "Courte", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "SHORT-01", maxClaims: null, expiresAt: now + 60_000 }).campaign;
|
||
service.claimCampaign(other.id, "SHORT-01");
|
||
now += 120_000;
|
||
assert.throws(() => service.claimCampaign(admin.id, "SHORT-01"), /expiré/);
|
||
assert.throws(() => service.extendCampaign(admin.id, short.id, now - 1), /futur/);
|
||
service.extendCampaign(admin.id, short.id, now + 60_000);
|
||
assert.equal(service.campaignDetail(admin.id, short.id).campaign.expiresAt, now + 60_000);
|
||
// Sans date d'expiration : le code reste valable indéfiniment, et une campagne peut perdre son échéance.
|
||
service.extendCampaign(admin.id, short.id, null);
|
||
assert.equal(service.campaignDetail(admin.id, short.id).campaign.expiresAt, null);
|
||
const forever = service.createCampaign(admin.id, { name: "Permanent", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "FOREVER-1", maxClaims: null, expiresAt: null });
|
||
now += 10 * 365 * 24 * 3_600_000;
|
||
service.claimCampaign(other.id, "FOREVER-1");
|
||
assert.equal(service.campaignDetail(admin.id, forever.campaign.id).campaign.claimedCount, 1);
|
||
|
||
// Plusieurs éléments et quantités dans une même récompense, code partagé sans limite (une utilisation par joueur).
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "Vide", reward: { items: [] }, code: "EMPTY-01", maxClaims: null, expiresAt: now + 60_000 }), /au moins une/);
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "Trop", reward: { items: [{ type: "pack", collectionId: "primordial-nebula", quantity: 11 }] }, code: "TOO-MANY", maxClaims: null, expiresAt: now + 60_000 }), /Quantité invalide/);
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "Double", reward: { items: [{ type: "card", editionId: "astral-booster-standard", quantity: 2 }] }, code: "DOUBLE-01", maxClaims: null, expiresAt: now + 60_000 }), /un seul exemplaire/);
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "Doublon", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }, { type: "card", editionId: "astral-booster-standard" }] }, code: "DOUBLON-1", maxClaims: null, expiresAt: now + 60_000 }), /qu’une fois/);
|
||
const bundle = service.createCampaign(admin.id, {
|
||
name: "Pack de bienvenue",
|
||
reward: { items: [{ type: "card", editionId: "astral-booster-standard" }, { type: "card", editionId: "aurora-wolf-standard" }, { type: "pack", collectionId: "primordial-nebula", quantity: 3 }] },
|
||
code: "WELCOME-1", maxClaims: null, expiresAt: now + 60_000
|
||
});
|
||
assert.equal(service.campaignDetail(admin.id, bundle.campaign.id).campaign.maxClaims, null);
|
||
const players = Array.from({ length: 3 }, (_, index) => service.upsertPlayer({ discordId: `bundle-${index}`, displayName: `Bundle ${index}` }));
|
||
for (const member of players) {
|
||
const received = service.claimCampaign(member.id, "WELCOME-1");
|
||
assert.equal(received.state.collection.filter((item) => ["astral-booster-standard", "aurora-wolf-standard"].includes(item.editionId)).length, 2);
|
||
assert.equal(received.state.giftPacks.length, 3);
|
||
}
|
||
assert.throws(() => service.claimCampaign(players[0].id, "WELCOME-1"), /déjà reçu/);
|
||
assert.equal(service.campaignDetail(admin.id, bundle.campaign.id).campaign.claimedCount, 3);
|
||
assert.equal(service.getAdminDashboard(admin.id).campaigns.length, 5);
|
||
assert.equal("campaigns" in service.getState(admin.id), false);
|
||
const published = service.catalog;
|
||
assert.equal(summarizeReward(bundle.campaign.reward, published), "Carte Paquet Astral (Commun) + Carte Loup des Aurores (Légendaire) + 3 × Paquet La Nébuleuse Originelle");
|
||
const many = { items: [...["astral-booster-standard", "aurora-wolf-standard", "starvoid-dragon-standard"].map((editionId) => ({ type: "card", editionId, quantity: 1 })), { type: "pack", collectionId: "primordial-nebula", quantity: 2 }] };
|
||
assert.equal(summarizeReward(many, published), "3 cartes + 2 paquets");
|
||
database.close();
|
||
});
|
||
|
||
test("campaign packs keep the pack rates in force when the campaign was created", () => {
|
||
const rarityOf = (id) => catalog.editions.find((edition) => edition.id === id).rarity;
|
||
const only = (rarity) => Object.fromEntries(catalog.rarities.map((item) => [item.id, item.id === rarity ? 1 : 0]));
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "frozen-admin", displayName: "Admin", isAdmin: true });
|
||
const early = service.upsertPlayer({ discordId: "frozen-early", displayName: "Early" });
|
||
const late = service.upsertPlayer({ discordId: "frozen-late", displayName: "Late" });
|
||
service.setDropRates(admin.id, "astral-genesis", only("legendary"));
|
||
const frozen = service.createCampaign(admin.id, { name: "Figée", code: "FROZEN-RATES", reward: { items: [{ type: "pack", collectionId: "astral-genesis" }] } }).campaign;
|
||
assert.deepEqual(frozen.reward.items[0].packRates, only("legendary"));
|
||
// Des taux personnalisés s'appliquent tels quels : rien à copier.
|
||
const custom = service.createCampaign(admin.id, { name: "Perso", code: "CUSTOM-RATES", reward: { items: [{ type: "pack", collectionId: "astral-genesis", rarityWeights: only("rare") }] } }).campaign;
|
||
assert.equal(custom.reward.items[0].packRates, null);
|
||
|
||
// L'un reçoit son paquet avant le changement des taux, l'autre après : tous deux tirent avec les taux de la création.
|
||
const earlyGift = service.claimCampaign(early.id, "FROZEN-RATES").state.giftPacks[0];
|
||
service.setDropRates(admin.id, "astral-genesis", only("common"));
|
||
const lateGift = service.claimCampaign(late.id, "FROZEN-RATES").state.giftPacks[0];
|
||
for (const [player, gift] of [[early, earlyGift], [late, lateGift]]) {
|
||
const { opening } = service.openGiftPack(player.id, gift.id, `frozen-${player.id}`);
|
||
assert.deepEqual(opening.cards.map((card) => rarityOf(card.editionId)), ["legendary", "legendary", "legendary"]);
|
||
// La révélation affiche les taux réellement appliqués.
|
||
assert.deepEqual(opening.options.packRates, only("legendary"));
|
||
}
|
||
// Un nouveau paquet de la campagne personnalisée suit ses propres taux.
|
||
const customGift = service.claimCampaign(early.id, "CUSTOM-RATES").state.giftPacks[0];
|
||
service.completeOpening(early.id, service.getState(early.id).pendingOpening.id);
|
||
assert.ok(service.openGiftPack(early.id, customGift.id, "custom-1").opening.cards.every((card) => rarityOf(card.editionId) === "rare"));
|
||
|
||
// Une campagne créée avant la copie des taux garde le comportement d'origine : les taux en vigueur à l'ouverture.
|
||
const legacyReward = { items: [{ type: "pack", collectionId: "astral-genesis", rarityWeights: null, guarantee: null, quantity: 1 }] };
|
||
database.db.prepare("UPDATE campaigns SET reward_json = ? WHERE id = ?").run(JSON.stringify(legacyReward), frozen.id);
|
||
const legacy = service.upsertPlayer({ discordId: "frozen-legacy", displayName: "Legacy" });
|
||
const legacyGift = service.claimCampaign(legacy.id, "FROZEN-RATES").state.giftPacks[0];
|
||
assert.equal(legacyGift.options.packRates, null);
|
||
assert.ok(service.openGiftPack(legacy.id, legacyGift.id, "legacy-1").opening.cards.every((card) => rarityOf(card.editionId) === "common"));
|
||
database.close();
|
||
});
|
||
|
||
test("traders list the same available duplicates as each collection, without reserved ones", () => {
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||
const owner = service.upsertPlayer({ discordId: "owner", displayName: "Owner" });
|
||
const partner = service.upsertPlayer({ discordId: "partner", displayName: "Partner" });
|
||
const viewer = service.upsertPlayer({ discordId: "viewer", displayName: "Viewer" });
|
||
service.addCard(owner.id, "aurora-wolf-standard");
|
||
service.addCard(owner.id, "aurora-wolf-standard");
|
||
service.addCard(owner.id, "aurora-wolf-standard");
|
||
service.addCard(partner.id, "astral-booster-standard");
|
||
service.addCard(partner.id, "astral-booster-standard");
|
||
service.addCard(partner.id, "aurora-wolf-standard");
|
||
service.createTransfer(owner.id, { type: "trade", recipientId: partner.id, editionId: "aurora-wolf-standard", requestedEditionId: "astral-booster-standard" });
|
||
|
||
const { traders } = service.listTraders(viewer.id);
|
||
for (const trader of traders) {
|
||
const expected = service.collectionOf(trader.id).filter((entry) => entry.spare > 0).map(({ editionId, spare }) => ({ editionId, spare }));
|
||
assert.deepEqual(trader.duplicates, expected, trader.displayName);
|
||
}
|
||
assert.deepEqual(traders.find((trader) => trader.id === owner.id).duplicates, [{ editionId: "aurora-wolf-standard", spare: 1 }]);
|
||
assert.deepEqual(traders.find((trader) => trader.id === partner.id).duplicates, [{ editionId: "astral-booster-standard", spare: 1 }]);
|
||
});
|
||
|
||
test("new campaign codes need eight characters while existing short ones keep working", () => {
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "player", displayName: "Player" });
|
||
const reward = { items: [{ type: "card", editionId: "aurora-wolf-standard" }] };
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "Courte", reward, code: "SEVEN77" }), /8 à 24/);
|
||
const { campaign } = service.createCampaign(admin.id, { name: "Ancienne", reward, code: "EIGHT888" });
|
||
database.db.prepare("UPDATE campaigns SET code = 'OLD1' WHERE id = ?").run(campaign.id);
|
||
assert.equal(service.claimCampaign(player.id, "old1").reward.items[0].editionId, "aurora-wolf-standard");
|
||
});
|