- Each owned rare or better edition keeps a level and field experience; a level costs Éclats by current power, so every rarity reaches the same cap and a rare pays the longer road. - A duplicate of the same edition gives a whole level; every claimed expedition grants field experience to the cards it sent. - A one-way bridge turns stardust into Éclats at an admin-tuned rate. - The card sheet shows level, power, stats and experience with upgrade buttons; expeditions use the upgraded power. - Administration › Guilde tunes the cost formula, duplicate levels, field experience and the bridge rate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
462 lines
33 KiB
JavaScript
462 lines
33 KiB
JavaScript
// Rôle : vérifie le service et l'API des Expéditions Sokko TCG (destinations du jour, départ solo, retour, réglages, suppression de compte).
|
|
import assert from "node:assert/strict";
|
|
import { readFile } from "node:fs/promises";
|
|
import { resolve } from "node:path";
|
|
import { Readable } from "node:stream";
|
|
import { test } from "node:test";
|
|
import { createCardsApiHandler } from "../services/cards/api.js";
|
|
import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js";
|
|
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES } from "../services/cards/admin-seed.js";
|
|
import { CardsDatabase } from "../services/cards/database.js";
|
|
import { CardsService } from "../services/cards/service.js";
|
|
import { DEFAULT_EXPEDITION_SETTINGS } from "../services/cards/expedition-settings.js";
|
|
|
|
const DEFAULT_GROUP = DEFAULT_EXPEDITION_SETTINGS.group;
|
|
|
|
const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")));
|
|
const published = buildPublishedCatalog(baseCatalog, { collectionStates: INITIAL_COLLECTION_STATES, dropRates: INITIAL_DROP_RATES });
|
|
const HOUR = 3_600_000;
|
|
const rarityOf = (cardId) => published.editions.find((edition) => edition.cardId === cardId && !edition.promotional).rarity;
|
|
const editionsOf = (rarity, collectionId = "primordial-nebula") => published.editions
|
|
.filter((edition) => edition.rarity === rarity && published.cards.find((card) => card.id === edition.cardId).collectionId === collectionId)
|
|
.map((edition) => edition.id);
|
|
|
|
function expeditionService({ start = Date.parse("2026-11-15T09:00:00Z"), random = () => 0 } = {}) {
|
|
const clock = { now: start };
|
|
const database = new CardsDatabase(":memory:");
|
|
const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random });
|
|
const admin = service.upsertPlayer({ discordId: "expedition-admin", displayName: "Admin", isAdmin: true });
|
|
const player = service.upsertPlayer({ discordId: "expedition-player", displayName: "Player" });
|
|
const open = (changes = {}) => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, enabled: true, ...changes });
|
|
const rares = editionsOf("rare");
|
|
database.transaction(() => rares.slice(0, 4).forEach((editionId) => service.addCard(player.id, editionId)));
|
|
return { clock, database, service, admin, player, open, rares };
|
|
}
|
|
|
|
const soloBody = (view, slots, changes = {}) => ({ day: view.day, destinationId: view.destinations[0].id, difficulty: 1, durationHours: 2, slots, ...changes });
|
|
|
|
test("expeditions stay closed until an administrator opens them", () => {
|
|
const { service, player, open, rares } = expeditionService();
|
|
const closed = service.expeditions.getExpeditions(player.id);
|
|
assert.equal(closed.enabled, false);
|
|
assert.deepEqual(closed.destinations, []);
|
|
assert.equal(service.getState(player.id).expeditions.enabled, false);
|
|
assert.throws(() => service.expeditions.startSolo(player.id, soloBody({ day: closed.day, destinations: [{ id: "light-currents" }] }, rares.slice(0, 2)), "k1"), (error) => error.code === "EXPEDITIONS_CLOSED");
|
|
assert.throws(() => service.expeditions.updateSettings(player.id, { ...service.expeditions.settings, enabled: true }), (error) => error.code === "ADMIN_REQUIRED");
|
|
open();
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
assert.equal(view.enabled, true);
|
|
assert.equal(view.day, "2026-11-15");
|
|
assert.equal(view.destinations.length, 4);
|
|
assert.deepEqual(Object.keys(view.destinations[0].stars), ["1", "2", "3", "4"]);
|
|
assert.equal(view.destinations[0].stars[4].dangers.length, 1);
|
|
assert.equal(view.destinations[0].stars[2].condition, null);
|
|
assert.equal(view.cards.length, 4);
|
|
// Le tirage du jour est commun à tous et gardé en base.
|
|
assert.deepEqual(service.expeditions.getExpeditions(player.id).destinations.map((item) => item.id), view.destinations.map((item) => item.id));
|
|
});
|
|
|
|
test("a solo expedition freezes its team, hides its result until it returns and pays once", () => {
|
|
const { clock, service, player, open, rares, database } = expeditionService();
|
|
open();
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
const body = soloBody(view, rares.slice(0, 2), { difficulty: 2, durationHours: 6 });
|
|
const preview = service.expeditions.preview(player.id, body).preview;
|
|
assert.ok(["struggle", "success", "triumph"].includes(preview.tier));
|
|
assert.equal(preview.requirements.length, 2);
|
|
assert.ok(preview.expected.eclats > 0);
|
|
|
|
const started = service.expeditions.startSolo(player.id, body, "start-1");
|
|
assert.equal(started.expedition.status, "running");
|
|
assert.equal(started.expedition.result, null);
|
|
assert.equal(started.expedition.reward, null);
|
|
assert.equal(started.expedition.returnsAt, clock.now + 6 * HOUR);
|
|
assert.equal(started.state.expeditions.running, 1);
|
|
assert.equal(started.state.expeditions.launchedToday, true);
|
|
assert.deepEqual(started.state.expeditions.busyEditions.map((item) => item.editionId).sort(), rares.slice(0, 2).sort());
|
|
// Même clé : même expédition ; nouvelle clé : la limite solo s'applique, et les cartes sont occupées.
|
|
assert.equal(service.expeditions.startSolo(player.id, body, "start-1").expedition.id, started.expedition.id);
|
|
assert.throws(() => service.expeditions.startSolo(player.id, body, "start-2"), (error) => error.code === "EXPEDITION_CARD_BUSY");
|
|
assert.throws(() => service.expeditions.startSolo(player.id, { ...body, slots: rares.slice(2, 4) }, "start-3"), (error) => error.code === "EXPEDITION_LIMIT");
|
|
assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_RETURNED");
|
|
|
|
// Une amélioration des réglages pendant le trajet ne change rien : tout est figé au départ.
|
|
clock.now += 6 * HOUR;
|
|
const before = service.getState(player.id);
|
|
assert.equal(before.expeditions.returned, 1);
|
|
const returned = service.expeditions.getExpeditions(player.id).expeditions[0];
|
|
assert.equal(returned.status, "returned");
|
|
assert.equal(returned.result.tier, preview.tier);
|
|
const claimed = service.expeditions.claim(player.id, started.expedition.id);
|
|
assert.equal(claimed.expedition.status, "completed");
|
|
assert.equal(claimed.state.wallet.eclats, returned.reward.eclats);
|
|
assert.equal(claimed.state.wallet.stardust, before.wallet.stardust + returned.reward.stardust);
|
|
assert.ok(returned.reward.eclats >= Math.floor(preview.expected.eclats));
|
|
// random() = 0 : tous les tirages réussissent, donc un paquet rapporté, rangé avec les paquets offerts.
|
|
assert.equal(returned.reward.packs.length, 1);
|
|
assert.equal(claimed.state.giftPacks.length, 1);
|
|
assert.equal(claimed.state.giftPacks[0].source, "expedition");
|
|
assert.equal(claimed.state.giftPacks[0].sourceName, returned.destination.name);
|
|
const history = claimed.state.history.find((entry) => entry.type === "expedition_completed");
|
|
assert.equal(history.details.eclats, returned.reward.eclats);
|
|
// Deuxième retour : même rapport, aucun crédit en plus ; les cartes sont libres.
|
|
const again = service.expeditions.claim(player.id, started.expedition.id);
|
|
assert.equal(again.state.wallet.eclats, claimed.state.wallet.eclats);
|
|
assert.deepEqual(again.state.expeditions.busyEditions, []);
|
|
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM gift_packs WHERE source = 'expedition'").get().count, 1);
|
|
// Le paquet rapporté s'ouvre comme un paquet offert.
|
|
const opened = service.openGiftPack(player.id, claimed.state.giftPacks[0].id, "open-expedition-pack");
|
|
assert.equal(opened.opening.cards.length, 3);
|
|
});
|
|
|
|
test("unlucky rolls keep the average and never hand out a pack", () => {
|
|
const { clock, service, player, open, rares } = expeditionService({ random: (max) => max - 1 });
|
|
open();
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "unlucky");
|
|
clock.now += 2 * HOUR;
|
|
const returned = service.expeditions.claim(player.id, started.expedition.id).expedition;
|
|
assert.deepEqual(returned.reward.packs, []);
|
|
assert.equal(returned.reward.eclats, Math.floor(returned.reward.eclats));
|
|
});
|
|
|
|
test("solo departures refuse stale days, unknown destinations, commons, duplicates and cards the player lacks", () => {
|
|
const { clock, service, player, open, rares } = expeditionService();
|
|
open();
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
const start = (changes, key) => () => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2), changes), key);
|
|
assert.throws(start({ destinationId: "nowhere" }, "a"), (error) => error.code === "EXPEDITION_INVALID");
|
|
assert.throws(start({ difficulty: 5 }, "b"), (error) => error.code === "EXPEDITION_INVALID");
|
|
assert.throws(start({ durationHours: 3 }, "c"), (error) => error.code === "EXPEDITION_INVALID");
|
|
assert.throws(start({ slots: [rares[0]] }, "d"), (error) => error.code === "EXPEDITION_CARD_INVALID");
|
|
assert.throws(start({ slots: [rares[0], rares[0]] }, "e"), (error) => error.code === "EXPEDITION_CARD_INVALID");
|
|
assert.throws(start({ slots: [rares[0], editionsOf("common")[0]] }, "f"), (error) => error.code === "EXPEDITION_CARD_INVALID");
|
|
assert.throws(start({ slots: [rares[0], rares[10]] }, "g"), (error) => error.code === "CARD_NOT_OWNED");
|
|
assert.throws(() => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), ""), (error) => error.code === "IDEMPOTENCY_REQUIRED");
|
|
clock.now += 24 * HOUR;
|
|
assert.throws(start({}, "h"), (error) => error.code === "EXPEDITION_DAY_EXPIRED");
|
|
assert.equal(rarityOf("starvoid-dragon"), "legendary");
|
|
});
|
|
|
|
test("administrators tune settings with bounds and history, and can cancel an expedition", () => {
|
|
const { service, admin, player, open, rares, database } = expeditionService();
|
|
assert.throws(() => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, score: { ...service.expeditions.settings.score, successPct: 500 } }), (error) => error.code === "EXPEDITION_SETTINGS_INVALID");
|
|
open();
|
|
assert.throws(() => open(), (error) => error.code === "EXPEDITION_SETTINGS_UNCHANGED");
|
|
const audit = database.db.prepare("SELECT details_json FROM audit_log WHERE event_type = 'expedition_settings_updated'").get();
|
|
assert.deepEqual(JSON.parse(audit.details_json).changes, [{ path: "enabled", previous: false, next: true }]);
|
|
assert.ok(service.getAdminHistory(admin.id).entries.some((entry) => entry.type === "expedition_settings_updated"));
|
|
const dashboard = service.getAdminDashboard(admin.id);
|
|
assert.equal(dashboard.expeditionSettings.settings.enabled, true);
|
|
assert.equal(dashboard.expeditionSettings.destinations.length, 12);
|
|
assert.ok(dashboard.expeditionSettings.schema.some((field) => field.path === "loot.eclatsPerHourCents"));
|
|
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "cancel-me");
|
|
assert.equal(service.getAdminDashboard(admin.id).expeditionsToday.running, 1);
|
|
assert.throws(() => service.expeditions.cancel(player.id, started.expedition.id), (error) => error.code === "ADMIN_REQUIRED");
|
|
service.expeditions.cancel(admin.id, started.expedition.id);
|
|
const state = service.getState(player.id);
|
|
assert.deepEqual(state.expeditions.busyEditions, []);
|
|
assert.ok(state.history.some((entry) => entry.type === "expedition_cancelled_by_guild"));
|
|
assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_FOUND");
|
|
assert.throws(() => service.expeditions.cancel(admin.id, started.expedition.id), (error) => error.code === "EXPEDITION_FINISHED");
|
|
});
|
|
|
|
test("deleting an account cancels its expeditions and resets its Éclats", () => {
|
|
const { clock, service, player, open, rares, database } = expeditionService();
|
|
open();
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
const first = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "first");
|
|
clock.now += 2 * HOUR;
|
|
service.expeditions.claim(player.id, first.expedition.id);
|
|
const second = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(2, 4)), "second");
|
|
service.deleteAccount(player.id);
|
|
assert.equal(database.db.prepare("SELECT eclats FROM players WHERE id = ?").get(player.id).eclats, 0);
|
|
assert.equal(database.db.prepare("SELECT status FROM expeditions WHERE id = ?").get(second.expedition.id).status, "cancelled");
|
|
});
|
|
|
|
function mockRequest({ method = "GET", path, body, headers = {} }) {
|
|
const req = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body))]);
|
|
req.method = method;
|
|
req.url = path;
|
|
req.headers = { host: "localhost:5173", ...headers };
|
|
req.socket = { remoteAddress: "127.0.0.1" };
|
|
return req;
|
|
}
|
|
|
|
async function call(handler, options) {
|
|
const response = { status: 0, headers: {}, chunks: [] };
|
|
const res = {
|
|
setHeader(name, value) { response.headers[name.toLowerCase()] = value; },
|
|
writeHead(status, headers = {}) {
|
|
response.status = status;
|
|
for (const [name, value] of Object.entries(headers)) response.headers[name.toLowerCase()] = value;
|
|
},
|
|
end(value = "") { response.chunks.push(Buffer.from(value)); }
|
|
};
|
|
await handler(mockRequest(options), res);
|
|
response.raw = Buffer.concat(response.chunks);
|
|
response.json = response.headers["content-type"]?.startsWith("application/json") && response.raw.length ? JSON.parse(response.raw.toString("utf8")) : null;
|
|
return response;
|
|
}
|
|
|
|
test("the expeditions API requires a session, CSRF protection, an administrator for settings and an idempotency key to start", async (t) => {
|
|
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
|
|
t.after(() => handler.close());
|
|
assert.equal((await call(handler, { path: "/api/cards/expeditions" })).status, 401);
|
|
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
|
|
const cookie = login.headers["set-cookie"].split(";")[0];
|
|
const headers = { cookie, "x-csrf-token": login.json.csrfToken };
|
|
const closed = await call(handler, { path: "/api/cards/expeditions", headers: { cookie } });
|
|
assert.equal(closed.status, 200);
|
|
assert.equal(closed.json.enabled, false);
|
|
|
|
assert.equal((await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers: { cookie }, body: {} })).status, 403);
|
|
const dashboard = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie } });
|
|
const settings = { ...dashboard.json.expeditionSettings.settings, enabled: true };
|
|
const invalid = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings: { ...settings, solo: { ...settings.solo, maxStars: 9 } } } });
|
|
assert.equal(invalid.status, 400);
|
|
assert.equal(invalid.json.error.code, "EXPEDITION_SETTINGS_INVALID");
|
|
const opened = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings } });
|
|
assert.equal(opened.status, 200);
|
|
assert.equal(opened.json.expeditionSettings.settings.enabled, true);
|
|
|
|
const devId = handler.service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get().id;
|
|
handler.service.database.transaction(() => editionsOf("rare").slice(0, 2).forEach((editionId) => handler.service.addCard(devId, editionId)));
|
|
const view = (await call(handler, { path: "/api/cards/expeditions", headers: { cookie } })).json;
|
|
const slots = view.cards.slice(0, 2).map((card) => card.editionId);
|
|
assert.equal(slots.length, 2, "the development account owns rare or better cards");
|
|
const body = soloBody(view, slots);
|
|
const preview = await call(handler, { method: "POST", path: "/api/cards/expeditions/preview", headers, body });
|
|
assert.equal(preview.status, 200);
|
|
const noKey = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers, body });
|
|
assert.equal(noKey.json.error.code, "IDEMPOTENCY_REQUIRED");
|
|
const started = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-start" }, body });
|
|
assert.equal(started.status, 201);
|
|
assert.equal(started.json.expedition.status, "running");
|
|
const early = await call(handler, { method: "POST", path: `/api/cards/expeditions/${started.json.expedition.id}/claim`, headers });
|
|
assert.equal(early.status, 409);
|
|
assert.equal(early.json.error.code, "EXPEDITION_NOT_RETURNED");
|
|
const cancelled = await call(handler, { method: "POST", path: `/api/cards/admin/expeditions/${started.json.expedition.id}/cancel`, headers });
|
|
assert.equal(cancelled.status, 200);
|
|
});
|
|
|
|
// Groupe : deux joueurs de plus, avec chacun des cartes rares de collections différentes (Nébuleuse, Arcade des Rêves).
|
|
function groupService(options) {
|
|
const context = expeditionService(options);
|
|
const { service, database } = context;
|
|
const second = service.upsertPlayer({ discordId: "expedition-second", displayName: "Second" });
|
|
const third = service.upsertPlayer({ discordId: "expedition-third", displayName: "Third" });
|
|
const arcade = editionsOf("rare", "dream-arcade");
|
|
database.transaction(() => {
|
|
arcade.slice(0, 2).forEach((editionId) => service.addCard(second.id, editionId));
|
|
context.rares.slice(5, 7).forEach((editionId) => service.addCard(third.id, editionId));
|
|
});
|
|
return { ...context, second, third, arcade };
|
|
}
|
|
|
|
const groupBody = (view, editionId, role, changes = {}) => ({ mode: "group", day: view.day, destinationId: view.destinations[0].id, difficulty: 2, durationHours: 2, editionId, role, ...changes });
|
|
|
|
test("a group opens on the Guild board, fills its roles and leaves when its creator launches it", () => {
|
|
const { clock, service, player, second, third, open, rares, arcade, database } = groupService();
|
|
open();
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
assert.deepEqual(view.group.stars, { min: 2, max: 5 });
|
|
assert.equal(view.destinations[0].groupRoles.length, 4);
|
|
assert.deepEqual(Object.keys(view.destinations[0].groupStars), ["2", "3", "4", "5"]);
|
|
const [mainRole, secondRole] = view.destinations[0].groupRoles;
|
|
// Aperçu du groupe que le joueur ouvrirait : les trois autres places tenues par le Veilleur.
|
|
const preview = service.expeditions.preview(player.id, groupBody(view, rares[0], mainRole)).preview;
|
|
assert.equal(preview.requirements.length, 2);
|
|
assert.throws(() => service.expeditions.createGroup(player.id, groupBody(view, rares[0], mainRole, { difficulty: 1 }), "g0"), (error) => error.code === "EXPEDITION_INVALID");
|
|
assert.throws(() => service.expeditions.createGroup(player.id, groupBody(view, rares[0], "nothing"), "g0"), (error) => error.code === "EXPEDITION_INVALID");
|
|
|
|
const created = service.expeditions.createGroup(player.id, groupBody(view, rares[0], mainRole), "g1");
|
|
assert.equal(service.expeditions.createGroup(player.id, groupBody(view, rares[0], mainRole), "g1").expeditions.groups.length, 1);
|
|
const group = created.expeditions.groups[0];
|
|
assert.equal(group.isCreator, true);
|
|
assert.equal(group.canDepart, false);
|
|
assert.deepEqual(group.freeRoles, view.destinations[0].groupRoles.slice(1));
|
|
assert.equal(created.state.expeditions.busyEditions[0].editionId, rares[0]);
|
|
// La carte du créateur est occupée : elle ne peut pas partir en solo en même temps.
|
|
assert.throws(() => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "solo-busy"), (error) => error.code === "EXPEDITION_CARD_BUSY");
|
|
|
|
// Le tableau est visible des autres joueurs, et la Guilde le signale à ceux qui peuvent rejoindre.
|
|
assert.equal(service.getState(second.id).expeditions.joinableGroups, 1);
|
|
const board = service.expeditions.getExpeditions(second.id).groups[0];
|
|
assert.equal(board.canJoin, true);
|
|
assert.equal(board.creatorName, "Player");
|
|
assert.throws(() => service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: mainRole }), (error) => error.code === "EXPEDITION_ROLE_TAKEN");
|
|
assert.throws(() => service.expeditions.joinGroup(second.id, group.id, { editionId: rares[0], role: secondRole }), (error) => error.code === "CARD_NOT_OWNED");
|
|
assert.throws(() => service.expeditions.joinGroup(player.id, group.id, { editionId: rares[1], role: secondRole }), (error) => error.code === "EXPEDITION_ALREADY_JOINED");
|
|
service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: secondRole });
|
|
assert.throws(() => service.expeditions.departGroup(second.id, group.id), (error) => error.code === "EXPEDITION_NOT_CREATOR");
|
|
|
|
const before = service.expeditions.getExpeditions(player.id).groups[0];
|
|
assert.equal(before.members.length, 2);
|
|
assert.equal(before.canDepart, true);
|
|
// Collections différentes : bonus de cohésion.
|
|
assert.equal(before.projected.cohesionPct, 10);
|
|
service.expeditions.departGroup(player.id, group.id);
|
|
assert.deepEqual(service.expeditions.getExpeditions(third.id).groups, []);
|
|
const slots = database.db.prepare("SELECT player_id, role FROM expedition_slots WHERE expedition_id = ? ORDER BY position").all(group.id);
|
|
assert.equal(slots.length, 4);
|
|
// Le Veilleur tient les deux places vides, sans rôle.
|
|
assert.deepEqual(slots.filter((slot) => slot.player_id == null).map((slot) => slot.role), [null, null]);
|
|
assert.throws(() => service.expeditions.joinGroup(third.id, group.id, { editionId: rares[5], role: view.destinations[0].groupRoles[2] }), (error) => error.code === "EXPEDITION_GROUP_DEPARTED");
|
|
|
|
clock.now += 2 * HOUR;
|
|
const first = service.expeditions.claim(player.id, group.id);
|
|
assert.equal(first.expedition.result.players, 2);
|
|
assert.equal(first.expedition.result.lootPct, 150);
|
|
assert.equal(first.expedition.status, "returned");
|
|
assert.ok(first.state.wallet.eclats > 0);
|
|
const last = service.expeditions.claim(second.id, group.id);
|
|
assert.equal(last.expedition.status, "completed");
|
|
assert.equal(last.state.history.find((entry) => entry.type === "expedition_completed").details.mode, "group");
|
|
});
|
|
|
|
test("an unlaunched group departs alone with enough players at the end of recruitment, or dissolves", () => {
|
|
const { clock, service, player, second, third, open, rares, arcade } = groupService();
|
|
open({ group: { ...DEFAULT_GROUP, recruitHours: 1 } });
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
const roles = view.destinations[0].groupRoles;
|
|
const lonely = service.expeditions.createGroup(third.id, groupBody(view, rares[5], roles[0]), "lonely").expeditions.groups[0];
|
|
const full = service.expeditions.createGroup(player.id, groupBody(view, rares[0], view.destinations[1].groupRoles[0], { destinationId: view.destinations[1].id }), "full").expeditions.groups.find((group) => group.isCreator);
|
|
service.expeditions.joinGroup(second.id, full.id, { editionId: arcade[0], role: view.destinations[1].groupRoles[1] });
|
|
clock.now += HOUR + 1;
|
|
const state = service.getState(third.id);
|
|
assert.ok(state.history.some((entry) => entry.type === "expedition_dissolved"));
|
|
assert.deepEqual(state.expeditions.busyEditions, []);
|
|
const departed = service.expeditions.getExpeditions(player.id).expeditions.find((expedition) => expedition.id === full.id);
|
|
assert.equal(departed.status, "running");
|
|
// Le départ automatique a lieu à la fin de l'inscription, pas à la lecture.
|
|
assert.equal(departed.departsAt, departed.returnsAt - 2 * HOUR);
|
|
assert.equal(lonely.id === full.id, false);
|
|
});
|
|
|
|
test("leaving a forming group frees the card, and the creator leaving dissolves it", () => {
|
|
const { service, player, second, open, rares, arcade } = groupService();
|
|
open();
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
const roles = view.destinations[0].groupRoles;
|
|
const group = service.expeditions.createGroup(player.id, groupBody(view, rares[0], roles[0]), "leave").expeditions.groups[0];
|
|
service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: roles[1] });
|
|
service.expeditions.leaveGroup(second.id, group.id);
|
|
assert.deepEqual(service.getState(second.id).expeditions.busyEditions, []);
|
|
assert.equal(service.expeditions.getExpeditions(player.id).groups[0].members.length, 1);
|
|
service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: roles[1] });
|
|
service.expeditions.leaveGroup(player.id, group.id);
|
|
assert.deepEqual(service.expeditions.getExpeditions(second.id).groups, []);
|
|
assert.ok(service.getState(second.id).history.some((entry) => entry.type === "expedition_dissolved" && entry.details.reason === "creator_left"));
|
|
assert.ok(!service.getState(player.id).history.some((entry) => entry.type === "expedition_dissolved"));
|
|
});
|
|
|
|
test("a player deleted during a group expedition forfeits their share and the others still claim", () => {
|
|
const { clock, service, player, second, open, rares, arcade, database } = groupService();
|
|
open();
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
const roles = view.destinations[0].groupRoles;
|
|
const group = service.expeditions.createGroup(player.id, groupBody(view, rares[0], roles[0]), "forfeit").expeditions.groups[0];
|
|
service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0], role: roles[1] });
|
|
service.expeditions.departGroup(player.id, group.id);
|
|
service.deleteAccount(second.id);
|
|
clock.now += 2 * HOUR;
|
|
assert.equal(service.expeditions.claim(player.id, group.id).expedition.status, "completed");
|
|
assert.equal(database.db.prepare("SELECT status FROM expeditions WHERE id = ?").get(group.id).status, "completed");
|
|
});
|
|
|
|
test("the group API opens, joins, leaves and launches through dedicated routes", async (t) => {
|
|
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
|
|
t.after(() => handler.close());
|
|
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
|
|
const cookie = login.headers["set-cookie"].split(";")[0];
|
|
const headers = { cookie, "x-csrf-token": login.json.csrfToken };
|
|
const { service } = handler;
|
|
const devId = service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get().id;
|
|
const other = service.upsertPlayer({ discordId: "api-other", displayName: "Other" });
|
|
service.database.transaction(() => {
|
|
service.addCard(devId, editionsOf("rare")[0]);
|
|
service.addCard(other.id, editionsOf("rare")[1]);
|
|
});
|
|
service.expeditions.updateSettings(devId, { ...service.expeditions.settings, enabled: true });
|
|
const view = (await call(handler, { path: "/api/cards/expeditions", headers: { cookie } })).json;
|
|
const roles = view.destinations[0].groupRoles;
|
|
const created = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-group" }, body: groupBody(view, view.cards[0].editionId, roles[0]) });
|
|
assert.equal(created.status, 201);
|
|
const groupId = created.json.expeditions.groups[0].id;
|
|
const tooSmall = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/depart`, headers });
|
|
assert.equal(tooSmall.json.error.code, "EXPEDITION_GROUP_TOO_SMALL");
|
|
service.expeditions.joinGroup(other.id, groupId, { editionId: editionsOf("rare")[1], role: roles[1] });
|
|
const unknownRole = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/join`, headers, body: { editionId: view.cards[0].editionId, role: roles[2] } });
|
|
assert.equal(unknownRole.json.error.code, "EXPEDITION_ALREADY_JOINED");
|
|
const departed = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/depart`, headers });
|
|
assert.equal(departed.status, 200);
|
|
assert.equal(departed.json.expeditions.expeditions[0].status, "running");
|
|
const leave = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/leave`, headers });
|
|
assert.equal(leave.json.error.code, "EXPEDITION_GROUP_DEPARTED");
|
|
});
|
|
|
|
test("cards level up with Éclats or a duplicate, gain field experience and stronger expedition stats", () => {
|
|
const { clock, service, player, open, rares, database } = expeditionService();
|
|
open();
|
|
const [card] = rares;
|
|
database.transaction(() => service.addCard(player.id, card));
|
|
database.db.prepare("UPDATE players SET eclats = 25 WHERE id = ?").run(player.id);
|
|
const before = service.getState(player.id).cardProgress.find((item) => item.editionId === card);
|
|
assert.deepEqual([before.level, before.power, before.nextCost, before.maxLevel, before.spare], [0, 40, 10, 12, 1]);
|
|
const upgraded = service.expeditions.upgradeCard(player.id, { editionId: card, method: "eclats" });
|
|
assert.deepEqual([upgraded.progress.level, upgraded.progress.power, upgraded.progress.nextCost], [1, 45, 20]);
|
|
assert.equal(upgraded.state.wallet.eclats, 15);
|
|
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "eclats" }), (error) => error.code === "NOT_ENOUGH_ECLATS");
|
|
// Un doublon de la même édition donne un niveau entier, et part de la collection.
|
|
const byDuplicate = service.expeditions.upgradeCard(player.id, { editionId: card, method: "duplicate" });
|
|
assert.equal(byDuplicate.progress.level, 2);
|
|
assert.equal(service.quantityOf(player.id, card), 1);
|
|
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "duplicate" }), (error) => error.code === "NOT_A_DUPLICATE");
|
|
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: editionsOf("common")[0], method: "eclats" }), (error) => error.code === "CARD_NOT_OWNED");
|
|
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "magic" }), (error) => error.code === "UPGRADE_METHOD_INVALID");
|
|
const history = service.getState(player.id).history.filter((entry) => entry.type === "card_upgraded");
|
|
assert.deepEqual(history.map((entry) => entry.details.method).sort(), ["duplicate", "eclats"]);
|
|
|
|
// Les expéditions utilisent la Puissance améliorée, et chaque retour donne 10 % de niveau aux cartes envoyées.
|
|
const view = service.expeditions.getExpeditions(player.id);
|
|
assert.equal(view.cards.find((item) => item.editionId === card).power, 50);
|
|
const started = service.expeditions.startSolo(player.id, soloBody(view, [card, rares[1]]), "levelled");
|
|
clock.now += 2 * HOUR;
|
|
service.expeditions.claim(player.id, started.expedition.id);
|
|
const after = service.getState(player.id).cardProgress;
|
|
assert.equal(after.find((item) => item.editionId === card).fieldXp, 10);
|
|
assert.equal(after.find((item) => item.editionId === rares[1]).fieldXp, 10);
|
|
|
|
// Au plafond, plus de niveau ; la suppression du compte efface la progression.
|
|
database.db.prepare("UPDATE card_progress SET level = 12 WHERE player_id = ? AND edition_id = ?").run(player.id, card);
|
|
assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "eclats" }), (error) => error.code === "CARD_MAX_LEVEL");
|
|
assert.equal(service.getState(player.id).cardProgress.find((item) => item.editionId === card).nextCost, null);
|
|
service.deleteAccount(player.id);
|
|
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM card_progress WHERE player_id = ?").get(player.id).count, 0);
|
|
});
|
|
|
|
test("the one-way bridge turns stardust into Éclats at the configured rate", async (t) => {
|
|
const { service, player, admin, database } = expeditionService();
|
|
database.db.prepare("UPDATE players SET stardust = 40 WHERE id = ?").run(player.id);
|
|
const state = service.expeditions.convertStardust(player.id, { eclats: 10 });
|
|
assert.deepEqual([state.wallet.stardust, state.wallet.eclats], [10, 10]);
|
|
assert.throws(() => service.expeditions.convertStardust(player.id, { eclats: 4 }), (error) => error.code === "NOT_ENOUGH_STARDUST");
|
|
assert.throws(() => service.expeditions.convertStardust(player.id, { eclats: 0 }), (error) => error.code === "CONVERT_INVALID");
|
|
service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, progression: { ...service.expeditions.settings.progression, stardustPerEclat: 5 } });
|
|
assert.equal(service.expeditions.convertStardust(player.id, { eclats: 2 }).wallet.stardust, 0);
|
|
assert.ok(service.getState(player.id).history.some((entry) => entry.type === "eclats_converted" && entry.details.stardust === 30));
|
|
|
|
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
|
|
t.after(() => handler.close());
|
|
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
|
|
const headers = { cookie: login.headers["set-cookie"].split(";")[0], "x-csrf-token": login.json.csrfToken };
|
|
handler.service.db.prepare("UPDATE players SET stardust = 30 WHERE discord_id = 'dev-admin'").run();
|
|
const converted = await call(handler, { method: "POST", path: "/api/cards/eclats/convert", headers, body: { eclats: 3 } });
|
|
assert.equal(converted.status, 200);
|
|
assert.equal(converted.json.wallet.eclats, 3);
|
|
const upgrade = await call(handler, { method: "POST", path: "/api/cards/progress/upgrade", headers, body: { editionId: "nowhere", method: "eclats" } });
|
|
assert.equal(upgrade.json.error.code, "CARD_NOT_OWNED");
|
|
});
|