- A new watchers-logbooks collection of category expedition never comes from packs, the shop or codes, and administrators cannot open it as a pack. - Its six commons carry powers instead of stats (Longue-vue, Provisions, Carte au trésor, Talisman, Boussole folle, Filet à étoiles filantes); a card holds one power and each counts once per team. - Powers change travel time, loot, score or tier, hide requirements, or catch a logbook card; each destination lists the logbook cards it can bring back. - A workshop turns a plan and three duplicate commons into a power common. - The fifteen cards ship without images with ready ChatGPT prompts; a card only drops or gets crafted once illustrated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
754 lines
54 KiB
JavaScript
754 lines
54 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";
|
||
import { createDiscordAlertSender, dispatchAlerts } from "../services/cards/discord-alerts.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, 14);
|
||
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");
|
||
});
|
||
|
||
test("commons equip open slots, add stats with synergies, move between cards and enter the Grimoire", async (t) => {
|
||
const { clock, service, player, open, rares, database } = expeditionService();
|
||
open();
|
||
const [card, other] = rares;
|
||
const tagsOf = (editionId) => service.catalog.cards.find((item) => item.id === service.index.editions.get(editionId).cardId).expedition.tags;
|
||
const commons = editionsOf("common");
|
||
// Une commune qui partage une étiquette avec la carte, et une autre qui n'en partage aucune.
|
||
const partner = commons.find((editionId) => tagsOf(editionId).some((tag) => tagsOf(card).includes(tag)));
|
||
const stranger = commons.find((editionId) => !tagsOf(editionId).some((tag) => tagsOf(card).includes(tag)) && !tagsOf(editionId).some((tag) => tagsOf(other).includes(tag)));
|
||
database.transaction(() => [partner, stranger].forEach((editionId) => service.addCard(player.id, editionId)));
|
||
const before = service.getState(player.id).cardProgress.find((item) => item.editionId === card);
|
||
assert.deepEqual([before.slots, before.maxSlots, before.equipment], [1, 3, []]);
|
||
assert.equal(service.getState(player.id).equipment.length, 2);
|
||
|
||
const equipped = service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: partner });
|
||
assert.equal(equipped.progress.equipment[0].editionId, partner);
|
||
assert.ok(equipped.progress.equipment[0].synergyTag);
|
||
const added = (stats) => Object.values(stats).reduce((sum, value) => sum + value, 0);
|
||
assert.equal(added(equipped.progress.stats) - added(equipped.progress.baseStats), 6 + 2);
|
||
assert.ok(service.expeditions.grimoireOf(player.id).some((entry) => entry.id.startsWith("pair:")));
|
||
assert.throws(() => service.expeditions.equip(player.id, { editionId: card, slot: 1, equipmentEditionId: stranger }), (error) => error.code === "EQUIPMENT_SLOT_LOCKED");
|
||
assert.throws(() => service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: other }), (error) => error.code === "EQUIPMENT_INVALID");
|
||
assert.throws(() => service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: commons.at(-1) }), (error) => error.code === "CARD_NOT_OWNED");
|
||
|
||
// Une commune ne pose qu'à un endroit : l'équiper ailleurs la déplace.
|
||
const moved = service.expeditions.equip(player.id, { editionId: other, slot: 0, equipmentEditionId: partner });
|
||
assert.equal(moved.state.cardProgress.find((item) => item.editionId === card).equipment.length, 0);
|
||
assert.equal(moved.state.equipment.find((item) => item.editionId === partner).equippedOn, other);
|
||
service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: stranger });
|
||
const strangerStats = service.getState(player.id).cardProgress.find((item) => item.editionId === card);
|
||
assert.equal(added(strangerStats.stats) - added(strangerStats.baseStats), 6);
|
||
|
||
// Les stats équipées partent en expédition, et l'équipement d'une carte en route ne change pas.
|
||
const view = service.expeditions.getExpeditions(player.id);
|
||
assert.deepEqual(view.cards.find((item) => item.editionId === card).stats, strangerStats.stats);
|
||
const started = service.expeditions.startSolo(player.id, soloBody(view, [card, other]), "equipped");
|
||
assert.throws(() => service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: null }), (error) => error.code === "EXPEDITION_CARD_BUSY");
|
||
clock.now += 2 * HOUR;
|
||
service.expeditions.claim(player.id, started.expedition.id);
|
||
service.expeditions.equip(player.id, { editionId: card, slot: 0, equipmentEditionId: null });
|
||
assert.deepEqual(service.getState(player.id).cardProgress.find((item) => item.editionId === card).equipment, []);
|
||
service.deleteAccount(player.id);
|
||
for (const table of ["card_equipment", "grimoire_entries"]) assert.equal(database.db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE player_id = ?`).get(player.id).count, 0);
|
||
|
||
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 };
|
||
const refused = await call(handler, { method: "PUT", path: "/api/cards/equipment", headers, body: { editionId: "nowhere", slot: 0, equipmentEditionId: null } });
|
||
assert.equal(refused.json.error.code, "CARD_NOT_OWNED");
|
||
});
|
||
|
||
test("resonances and destination affinity raise the score and are written to every player's Grimoire", () => {
|
||
const { service, player, open, database } = expeditionService();
|
||
open();
|
||
// Écho : le hamster de la Nébuleuse et sa version de l'Arcade des Rêves.
|
||
database.transaction(() => ["solar-seed-hamster-standard", "steel-ball-hamster-standard"].forEach((editionId) => service.addCard(player.id, editionId)));
|
||
const view = service.expeditions.getExpeditions(player.id);
|
||
const body = soloBody(view, ["solar-seed-hamster-standard", "steel-ball-hamster-standard"]);
|
||
const preview = service.expeditions.preview(player.id, body).preview;
|
||
assert.ok(preview.resonances.some((resonance) => resonance.type === "echo" && resonance.key === "personnage:hamster"));
|
||
assert.ok(preview.synergyPct >= 10);
|
||
service.expeditions.startSolo(player.id, body, "echo");
|
||
assert.ok(service.expeditions.getExpeditions(player.id).grimoire.some((entry) => entry.id === "resonance:echo:personnage:hamster"));
|
||
});
|
||
|
||
test("Discord alerts stay off until a player opts in, then queue group openings and returns once", async () => {
|
||
const context = expeditionService();
|
||
const { clock, service, player, open, rares, database } = context;
|
||
// Bot configuré : alertes disponibles ; lien des messages vers l'adresse publique.
|
||
service.expeditions.alertsAvailable = true;
|
||
service.expeditions.publicOrigin = "https://sokko.example";
|
||
open();
|
||
const friend = service.upsertPlayer({ discordId: "123456789012345678", displayName: "Friend" });
|
||
const silent = service.upsertPlayer({ discordId: "223456789012345678", displayName: "Silent" });
|
||
database.db.prepare("UPDATE players SET discord_id = '323456789012345678' WHERE id = ?").run(player.id);
|
||
database.transaction(() => editionsOf("rare").slice(8, 10).forEach((editionId) => service.addCard(friend.id, editionId)));
|
||
assert.deepEqual(service.getState(friend.id).alerts, { available: true, groupOpened: false, expeditionReturned: false });
|
||
assert.equal(service.expeditions.setAlertPreferences(friend.id, { groupOpened: true, expeditionReturned: true }).alerts.groupOpened, true);
|
||
service.expeditions.setAlertPreferences(player.id, { groupOpened: true, expeditionReturned: true });
|
||
assert.throws(() => service.expeditions.setAlertPreferences(friend.id, { groupOpened: "yes" }), (error) => error.code === "ALERTS_INVALID");
|
||
|
||
// Groupe ouvert par le joueur : seul l'ami qui a activé l'alerte est prévenu, jamais le créateur ni le joueur silencieux.
|
||
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]), "alert-group").expeditions.groups[0];
|
||
let pending = service.expeditions.pendingAlerts();
|
||
assert.equal(pending.length, 1);
|
||
assert.equal(pending[0].discordId, "123456789012345678");
|
||
assert.match(pending[0].content, /Player ouvre un groupe d’expédition vers .+ Rejoignez-le sur le tableau de la Guilde : https:\/\/sokko\.example\/#\/cards\/expeditions$/);
|
||
assert.equal(silent.id === friend.id, false);
|
||
|
||
// Retours : une alerte par membre qui l'a activée, une seule fois.
|
||
service.expeditions.joinGroup(friend.id, group.id, { editionId: editionsOf("rare")[8], role: roles[1] });
|
||
service.expeditions.departGroup(player.id, group.id);
|
||
assert.equal(service.expeditions.queueReturnAlerts(), 0);
|
||
clock.now += 2 * HOUR;
|
||
assert.equal(service.expeditions.queueReturnAlerts(), 2);
|
||
assert.equal(service.expeditions.queueReturnAlerts(), 0);
|
||
|
||
// Envoi : un succès, un échec définitif, un échec qu'on réessaie.
|
||
const outcomes = [null, Object.assign(new Error("palico-bot answered 422"), { permanent: true }), new Error("timeout")];
|
||
const sent = [];
|
||
const send = async (discordId, content) => {
|
||
const outcome = outcomes.shift();
|
||
if (outcome) throw outcome;
|
||
sent.push({ discordId, content });
|
||
};
|
||
assert.equal(await dispatchAlerts(service.expeditions, send), 1);
|
||
pending = service.expeditions.pendingAlerts();
|
||
assert.equal(pending.length, 1);
|
||
assert.equal(pending[0].attempts, 1);
|
||
const rows = database.db.prepare("SELECT kind, sent_at, failed_at, attempts FROM alert_outbox ORDER BY created_at, kind").all();
|
||
assert.equal(rows.filter((row) => row.sent_at).length, 1);
|
||
assert.equal(rows.filter((row) => row.failed_at).length, 1);
|
||
|
||
// Coupées par l'administration : plus rien n'est mis en file.
|
||
service.expeditions.updateSettings(context.admin.id, { ...service.expeditions.settings, alerts: { enabled: false } });
|
||
assert.equal(service.getState(friend.id).alerts.available, false);
|
||
service.deleteAccount(friend.id);
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM alert_outbox WHERE player_id = ?").get(friend.id).count, 0);
|
||
});
|
||
|
||
test("the alert sender posts to palico-bot with its key and flags permanent refusals", async () => {
|
||
const calls = [];
|
||
const answers = [204, 422, 503];
|
||
const send = createDiscordAlertSender({
|
||
url: "http://127.0.0.1:3000/api/notifications/dm",
|
||
key: "secret",
|
||
fetchImpl: async (url, options) => {
|
||
calls.push({ url, options });
|
||
return { ok: answers[0] < 300, status: answers.shift() };
|
||
}
|
||
});
|
||
await send("123456789012345678", "Bonjour");
|
||
assert.equal(calls[0].options.headers.Authorization, "Bearer secret");
|
||
assert.deepEqual(JSON.parse(calls[0].options.body), { userId: "123456789012345678", content: "Bonjour" });
|
||
await assert.rejects(send("123456789012345678", "x"), (error) => error.permanent === true);
|
||
await assert.rejects(send("123456789012345678", "x"), (error) => error.permanent === false);
|
||
});
|
||
|
||
test("the alerts API saves a player's choices, and the server dispatches queued alerts through its sender", async (t) => {
|
||
const delivered = [];
|
||
const handler = createCardsApiHandler({
|
||
projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test", CARDS_PUBLIC_ORIGIN: "http://localhost:5173" }, random: () => 0,
|
||
sendAlert: async (discordId, content) => { delivered.push({ discordId, content }); }
|
||
});
|
||
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 };
|
||
const saved = await call(handler, { method: "PUT", path: "/api/cards/alerts", headers, body: { groupOpened: true, expeditionReturned: false } });
|
||
assert.equal(saved.status, 200);
|
||
assert.deepEqual(saved.json.alerts, { available: true, groupOpened: true, expeditionReturned: false });
|
||
const refused = await call(handler, { method: "PUT", path: "/api/cards/alerts", headers, body: {} });
|
||
assert.equal(refused.json.error.code, "ALERTS_INVALID");
|
||
const { service } = handler;
|
||
const friend = service.upsertPlayer({ discordId: "123456789012345678", displayName: "Friend" });
|
||
service.expeditions.setAlertPreferences(friend.id, { groupOpened: true, expeditionReturned: true });
|
||
service.database.transaction(() => service.expeditions.enqueueInTx(friend.id, "group_opened", "Un groupe vous attend."));
|
||
await handler.runAlerts();
|
||
assert.deepEqual(delivered, [{ discordId: "123456789012345678", content: "Un groupe vous attend." }]);
|
||
});
|
||
|
||
test("objects add bonus destinations, recall an expedition with an anchor and engrave equipment", () => {
|
||
const { clock, service, player, open, rares, database } = expeditionService();
|
||
open();
|
||
const give = (items) => database.transaction(() => service.expeditions.addItemsInTx(player.id, items));
|
||
// Étoile guide : une 5e destination, pour ce joueur seulement ; une seule par jour.
|
||
give(["guideStar", "guideStar", "anchor", "engraving", "fragment", "fragment", "fragment", "fragment"]);
|
||
const before = service.expeditions.getExpeditions(player.id);
|
||
assert.equal(before.items.guideStar, 2);
|
||
const added = service.expeditions.addBonusDestination(player.id, { item: "guideStar" }).expeditions;
|
||
assert.equal(added.destinations.length, 5);
|
||
const bonus = added.destinations.find((destination) => destination.bonusSlot === "5");
|
||
assert.ok(!before.destinations.some((destination) => destination.id === bonus.id));
|
||
assert.throws(() => service.expeditions.addBonusDestination(player.id, { item: "guideStar" }), (error) => error.code === "BONUS_ALREADY_USED");
|
||
assert.throws(() => service.expeditions.addBonusDestination(player.id, { item: "skyChart" }), (error) => error.code === "NOT_ENOUGH_ITEMS");
|
||
assert.throws(() => service.expeditions.addBonusDestination(player.id, { item: "anchor" }), (error) => error.code === "ITEM_INVALID");
|
||
// Carte au trésor : 4 fragments ouvrent une destination cachée, au butin multiplié.
|
||
const hidden = service.expeditions.addBonusDestination(player.id, { item: "fragment" }).expeditions.destinations.find((destination) => destination.bonusSlot === "hidden");
|
||
assert.ok(["crimson-passage", "lost-observatory"].includes(hidden.id));
|
||
assert.equal(service.expeditions.getExpeditions(player.id).items.fragment, 0);
|
||
assert.deepEqual(service.expeditions.getExpeditions(service.upsertPlayer({ discordId: "other", displayName: "Other" }).id).destinations.map((destination) => destination.id), before.destinations.map((destination) => destination.id));
|
||
|
||
// Ancre : rappel à mi-chemin, la moitié des Éclats et de la poussière, sans paquet ni objet.
|
||
const view = service.expeditions.getExpeditions(player.id);
|
||
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2), { destinationId: hidden.id, durationHours: 12 }), "hidden-trip");
|
||
assert.equal(started.expedition.destination.id, hidden.id);
|
||
clock.now += 6 * HOUR;
|
||
const recalled = service.expeditions.recallExpedition(player.id, started.expedition.id);
|
||
assert.equal(recalled.expedition.status, "returned");
|
||
assert.equal(recalled.expedition.reward.recalledPct, 50);
|
||
assert.deepEqual([recalled.expedition.reward.packs, recalled.expedition.reward.items], [[], []]);
|
||
assert.throws(() => service.expeditions.recallExpedition(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_RETURNED");
|
||
service.expeditions.claim(player.id, started.expedition.id);
|
||
|
||
// Burin : une étiquette gravée crée la synergie avec la carte équipée.
|
||
const tagsOf = (editionId) => service.catalog.cards.find((item) => item.id === service.index.editions.get(editionId).cardId).expedition.tags;
|
||
const stranger = editionsOf("common").find((editionId) => !tagsOf(editionId).some((tag) => tagsOf(rares[0]).includes(tag)));
|
||
database.transaction(() => service.addCard(player.id, stranger));
|
||
service.expeditions.equip(player.id, { editionId: rares[0], slot: 0, equipmentEditionId: stranger });
|
||
assert.equal(service.getState(player.id).cardProgress.find((item) => item.editionId === rares[0]).equipment[0].synergyTag, null);
|
||
assert.throws(() => service.expeditions.engrave(player.id, { editionId: stranger, tag: tagsOf(stranger)[0] }), (error) => error.code === "ENGRAVING_INVALID");
|
||
const engraved = service.expeditions.engrave(player.id, { editionId: stranger, tag: tagsOf(rares[0])[0] });
|
||
assert.equal(engraved.cardProgress.find((item) => item.editionId === rares[0]).equipment[0].synergyTag, tagsOf(rares[0])[0]);
|
||
assert.throws(() => service.expeditions.engrave(player.id, { editionId: stranger, tag: "theme:voyage" }), (error) => error.code === "ENGRAVING_EXISTS");
|
||
assert.ok(service.getState(player.id).history.filter((entry) => entry.type === "item_used").length >= 4);
|
||
service.deleteAccount(player.id);
|
||
for (const table of ["player_items", "equipment_engravings", "player_bonus_destinations"]) assert.equal(database.db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE player_id = ?`).get(player.id).count, 0);
|
||
});
|
||
|
||
test("returned expeditions credit the objects they bring back", () => {
|
||
const { clock, service, player, open, rares } = expeditionService();
|
||
open({ items: { ...DEFAULT_EXPEDITION_SETTINGS.items, chancePerHourPermille: 1000, maxPerExpedition: 2, orientationPerSlot: 0 } });
|
||
const view = service.expeditions.getExpeditions(player.id);
|
||
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "objects");
|
||
clock.now += 2 * HOUR;
|
||
const claimed = service.expeditions.claim(player.id, started.expedition.id);
|
||
assert.equal(claimed.expedition.reward.items.length, 2);
|
||
// Le plan d'atelier n'est pas rapporté tant que l'atelier n'a pas de commune de pouvoir illustrée.
|
||
assert.ok(!claimed.expedition.reward.items.includes("plan"));
|
||
const items = service.expeditions.getExpeditions(player.id).items;
|
||
assert.equal(Object.values(items).reduce((sum, count) => sum + count, 0), 2);
|
||
});
|
||
|
||
// Les cartes des Carnets attendent leurs illustrations : les tests leur en donnent une, en mémoire, pour ce service seulement.
|
||
function illustrateLogbooks(service) {
|
||
for (const card of service.catalog.cards.filter((item) => item.collectionId === "watchers-logbooks")) card.image = `/static/img/cards/watchers-logbooks/${card.id}.webp`;
|
||
}
|
||
|
||
test("the Carnets des Veilleurs never come from packs, and their cards only drop once illustrated", () => {
|
||
const { clock, service, admin, player, open, rares } = expeditionService();
|
||
assert.throws(() => service.setCollectionActive(admin.id, "watchers-logbooks", true), (error) => error.code === "EXPEDITION_COLLECTION");
|
||
assert.throws(() => service.openPack(player.id, "watchers-logbooks", "logbook-pack"), (error) => error.code === "EXPEDITION_COLLECTION");
|
||
assert.throws(() => service.createCampaign(admin.id, { name: "Carnets", code: "CARNETS", reward: { items: [{ type: "pack", collectionId: "watchers-logbooks" }] } }), /expédition/);
|
||
open({ carnets: { cardPerHourPermille: 1000, maxCards: 1 } });
|
||
const view = service.expeditions.getExpeditions(player.id);
|
||
// Sans illustration, aucune carte des Carnets n'est rapportée, même avec une chance pleine.
|
||
const first = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "no-art");
|
||
clock.now += 2 * HOUR;
|
||
assert.deepEqual(service.expeditions.claim(player.id, first.expedition.id).expedition.reward.cards, []);
|
||
illustrateLogbooks(service);
|
||
const second = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "with-art");
|
||
clock.now += 2 * HOUR;
|
||
const reward = service.expeditions.claim(player.id, second.expedition.id).expedition.reward;
|
||
assert.equal(reward.cards.length, 1);
|
||
const logbook = service.catalog.cards.find((card) => card.id === service.index.editions.get(reward.cards[0]).cardId);
|
||
assert.equal(logbook.collectionId, "watchers-logbooks");
|
||
assert.ok(service.quantityOf(player.id, reward.cards[0]) >= 1);
|
||
});
|
||
|
||
test("power commons equip one per card, change travel time and hide requirements, and the workshop crafts them", () => {
|
||
const { service, player, open, rares, database } = expeditionService();
|
||
open();
|
||
illustrateLogbooks(service);
|
||
const [longsight, compass] = ["watchers-longsight-standard", "mad-compass-standard"];
|
||
database.transaction(() => {
|
||
[longsight, compass].forEach((editionId) => service.addCard(player.id, editionId));
|
||
service.expeditions.writeProgress(player.id, rares[0], { level: 6, fieldXp: 0 });
|
||
});
|
||
// Puissance 70 : deux emplacements ; un seul pouvoir par carte.
|
||
service.expeditions.equip(player.id, { editionId: rares[0], slot: 0, equipmentEditionId: longsight });
|
||
assert.throws(() => service.expeditions.equip(player.id, { editionId: rares[0], slot: 1, equipmentEditionId: compass }), (error) => error.code === "POWER_LIMIT");
|
||
const view = service.expeditions.getExpeditions(player.id);
|
||
assert.deepEqual(view.cards.find((card) => card.editionId === rares[0]).powers, ["longsight"]);
|
||
const body = soloBody(view, rares.slice(0, 2), { durationHours: 6 });
|
||
assert.equal(service.expeditions.preview(player.id, body).preview.travelHours, 8);
|
||
const started = service.expeditions.startSolo(player.id, body, "longsight");
|
||
assert.equal(started.expedition.returnsAt - started.expedition.departsAt, 8 * HOUR);
|
||
service.expeditions.cancel(service.upsertPlayer({ discordId: "expedition-admin", displayName: "Admin", isAdmin: true }).id, started.expedition.id);
|
||
// Boussole folle : l'aperçu ne montre ni exigences ni résultat.
|
||
service.expeditions.equip(player.id, { editionId: rares[0], slot: 0, equipmentEditionId: compass });
|
||
const hidden = service.expeditions.preview(player.id, body).preview;
|
||
assert.equal(hidden.hiddenRequirements, true);
|
||
assert.equal(hidden.requirements, undefined);
|
||
|
||
// Atelier : un plan et 3 doublons de communes donnent une commune de pouvoir illustrée.
|
||
const commons = editionsOf("common").slice(0, 2);
|
||
database.transaction(() => {
|
||
commons.forEach((editionId) => { service.addCard(player.id, editionId); service.addCard(player.id, editionId); });
|
||
service.addCard(player.id, commons[1]);
|
||
service.expeditions.addItemsInTx(player.id, ["plan"]);
|
||
});
|
||
assert.throws(() => service.expeditions.craft(player.id, { editionIds: [commons[0], commons[0], commons[1]] }), (error) => error.code === "NOT_A_DUPLICATE");
|
||
assert.throws(() => service.expeditions.craft(player.id, { editionIds: [rares[0], commons[1], commons[1]] }), (error) => error.code === "ATELIER_INVALID");
|
||
const crafted = service.expeditions.craft(player.id, { editionIds: [commons[0], commons[1], commons[1]] });
|
||
assert.ok(service.index.cards.get(service.index.editions.get(crafted.crafted).cardId).expedition.equipment.power);
|
||
assert.equal(crafted.state.items.plan, 0);
|
||
assert.equal(service.quantityOf(player.id, commons[1]), 1);
|
||
});
|