/** * @file Vérifie le service et l'API des Expéditions Sokko TCG (destinations du jour, ouverture et départ seul * ou en groupe, 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, mythicEditionId, prepareVersionedCatalog } from "../services/cards/catalog.js"; import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES } from "../services/cards/admin-seed.js"; import { CardsDatabase, MIGRATIONS } from "../services/cards/database.js"; import { CardsService } from "../services/cards/service.js"; import { applyProgressReset, planProgressReset } from "../services/cards/progress-reset.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 rawCatalogText = await readFile("website/public/data/cards/catalog.json", "utf8"); const baseCatalog = prepareVersionedCatalog(JSON.parse(rawCatalogText)); 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); // Par défaut, le joueur a toutes les cartes de destination : ses 4 destinations du jour sont tirées parmi toutes. const destinationEditions = published.editions.filter((edition) => published.cards.find((card) => card.id === edition.cardId).kind === "destination").map((edition) => edition.id); function expeditionService({ start = Date.parse("2026-11-15T09:00:00Z"), random = () => 0, catalog = baseCatalog, allDestinations = true, devPerks = false } = {}) { const clock = { now: start }; const database = new CardsDatabase(":memory:"); const service = new CardsService({ database, catalog, now: () => clock.now, random, devPerks }); 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))); if (allDestinations) database.transaction(() => destinationEditions.forEach((editionId) => service.addCard(player.id, editionId))); return { clock, database, service, admin, player, open, rares }; } // Ouverture d'une expédition : une destination du jour, une durée et une carte. const soloBody = (view, editionId, changes = {}) => ({ day: view.day, destinationId: view.destinations[0].id, durationHours: 2, editionId, ...changes }); // Départ seul : l'expédition s'ouvre au tableau de la Guilde, puis son créateur la lance aussitôt. function goSolo(service, playerId, body, key) { const opened = service.expeditions.createGroup(playerId, body, key); const group = opened.expeditions.groups.filter((item) => item.isCreator).at(-1); const departed = service.expeditions.departGroup(playerId, group.id); return { ...departed, expedition: service.expeditions.expeditionView(group.id, playerId) }; } test("a state reads the expedition settings once, and the next state sees an administrator's change", () => { const { service, player, open } = expeditionService(); const settingsQuery = "SELECT settings_json FROM expedition_settings WHERE id = 1"; const prepare = service.db.prepare.bind(service.db); let reads = 0; service.db.prepare = (sql) => { if (sql === settingsQuery) reads += 1; return prepare(sql); }; assert.equal(service.getState(player.id).expeditions.enabled, false); assert.equal(reads, 1); open(); reads = 0; assert.equal(service.getState(player.id).expeditions.enabled, true); assert.equal(reads, 1); // Hors d'une construction d'état, chaque accès relit la base, même après un état interrompu par une erreur. assert.throws(() => service.getState("missing-player"), (error) => error.code === "PLAYER_NOT_FOUND"); assert.equal(service.expeditions.settingsSnapshot, null); reads = 0; void service.expeditions.settings; void service.expeditions.settings; assert.equal(reads, 2); }); 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.createGroup(player.id, soloBody({ day: closed.day, destinations: [{ id: "light-currents" }] }, rares[0]), "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); // La difficulté est tirée avec les destinations : un niveau de chaque, les mêmes étoiles seul ou en groupe. Exigences d'une carte // seule (la part d'une place) ; en groupe, une part par joueur. assert.deepEqual(view.destinations.map((item) => item.level).sort(), [0, 1, 2, 3]); assert.ok(view.destinations.every((item) => item.star === item.level + 1 && !("groupRequirements" in item))); const sample = view.destinations.find((item) => item.star === 2); assert.deepEqual(sample.requirements.map((item) => item.value), DEFAULT_EXPEDITION_SETTINGS.requirements.star2); assert.equal(view.destinations.find((item) => item.star === 4).dangers.length, 1); assert.equal(sample.condition, null); assert.equal(view.cards.length, 4); // Le tirage du jour du joueur est gardé en base. assert.deepEqual(service.expeditions.getExpeditions(player.id).destinations.map((item) => item.id), view.destinations.map((item) => item.id)); }); // Cartes de destination : on ne tire que les destinations débloquées (une destination sans carte au catalogue reste ouverte), // avec un niveau de chaque jusqu'au nombre de destinations tirées ; une carte obtenue dans la journée complète le tirage. test("each player draws the day among the destinations their cards unlock", () => { const { service, player, open, database } = expeditionService({ allDestinations: false }); const other = service.upsertPlayer({ discordId: "expedition-other", displayName: "Other" }); // Avant sa première visite : aucune carte, seules les destinations encore sans carte au catalogue sont ouvertes. const unlocked = service.expeditions.unlockedDestinationIds(player.id); assert.equal(unlocked.has("light-currents"), false); assert.equal(unlocked.has("cosmic-cloud-heart"), false); assert.equal(unlocked.has("crimson-passage"), false); // Seules trois destinations restent proposées : les Courants, le Grand Vide et le Cœur du Nuage. const kept = new Set(["light-currents", "great-void", "cosmic-cloud-heart"]); open({ destinations: Object.fromEntries(Object.entries(service.expeditions.settings.destinations).map(([id, value]) => [id, { ...value, active: kept.has(id) }])) }); // Première visite : la carte de départ (random() = 0, les Courants) ouvre une seule destination, au niveau le plus facile. const before = service.expeditions.getExpeditions(player.id); assert.deepEqual(before.destinations.map((item) => [item.id, item.level, item.star]), [["light-currents", 0, 1]]); assert.ok(before.unlocked.count >= 1); assert.equal(before.unlocked.total, 16); // Sa carte du Cœur du Nuage complète le tirage du jour, avec les niveaux 1 et 2 ; l'autre joueur, sans la carte, ne la voit pas. database.transaction(() => service.addCard(player.id, "cosmic-cloud-heart-standard")); const after = service.expeditions.getExpeditions(player.id).destinations; assert.deepEqual(after.map((item) => item.id).sort(), ["cosmic-cloud-heart", "light-currents"]); assert.deepEqual(after.map((item) => item.level).sort(), [0, 1]); const view = service.expeditions.getExpeditions(other.id); assert.deepEqual(view.destinations.map((item) => item.id), ["light-currents"]); // Une destination qui n'est pas dans son tirage ne se lance pas. assert.throws(() => service.expeditions.preview(other.id, { day: view.day, destinationId: "cosmic-cloud-heart", durationHours: 2, slots: [] }), (error) => error.code === "EXPEDITION_INVALID"); }); const destinationCardsOf = (service, playerId) => service.getState(playerId).collection.map((entry) => entry.editionId).filter((id) => destinationEditions.includes(id)); // Obtention : une carte de destination de départ offerte une fois, une carte non possédée rapportée d'expédition, et la carte de la // destination d'un groupe rejoint sans l'avoir. test("players receive a starter destination card, then find more on expeditions and in groups", () => { const { clock, service, player, open, rares, database, second, arcade } = groupService({ allDestinations: false }); open({ destinationCards: { dropPct: 100, groupJoinPct: 100 } }); // random() = 0 : la carte de départ est la première des Carnets, les Courants de Lumière. service.expeditions.getExpeditions(player.id); assert.deepEqual(destinationCardsOf(service, player.id), ["light-currents-standard"]); service.expeditions.getExpeditions(player.id); assert.equal(destinationCardsOf(service, player.id).length, 1); assert.equal(service.getState(player.id).history.filter((entry) => entry.type === "destination_starter").length, 1); assert.ok(service.expeditions.unlockedDestinationIds(player.id).has("light-currents")); assert.equal(service.expeditions.unlockedDestinationIds(player.id).has("dawn-shore"), false); // Une carte de destination de paquet ne compte pas : un joueur qui n'a que celle du Cœur du Nuage reçoit aussi sa carte de départ. const packOnly = service.upsertPlayer({ discordId: "expedition-pack-only", displayName: "Pack only" }); database.transaction(() => service.addCard(packOnly.id, "cosmic-cloud-heart-standard")); service.expeditions.getExpeditions(packOnly.id); assert.deepEqual(destinationCardsOf(service, packOnly.id).sort(), ["cosmic-cloud-heart-standard", "light-currents-standard"]); // Un groupe vers les Courants : le second joueur, sans leur carte, la gagne ; le créateur gagne une carte qu'il n'a pas. const view = service.expeditions.getExpeditions(player.id); const destination = view.destinations.find((item) => item.id === "light-currents"); const created = service.expeditions.createGroup(player.id, { day: view.day, destinationId: destination.id, durationHours: 2, editionId: rares[0] }, "dest-group"); const groupId = created.expeditions.groups[0].id; // Le second joueur a déjà reçu sa carte de départ, une autre : il n'a pas celle des Courants. database.db.prepare("INSERT INTO audit_log(player_id, event_type, entity_id, details_json, created_at) VALUES (?, 'destination_starter', 'other', '{}', 0)").run(second.id); service.expeditions.joinGroup(second.id, groupId, { editionId: arcade[0] }); service.expeditions.departGroup(player.id, groupId); const rewardOf = (playerId) => JSON.parse(database.db.prepare("SELECT reward_json FROM expedition_members WHERE expedition_id = ? AND player_id = ?").get(groupId, playerId).reward_json).cards; // Le second gagne la carte des Courants (groupe rejoint), puis une carte qu'il n'a pas, la première restante : le Rivage de l'Aube. assert.deepEqual(rewardOf(second.id).filter((id) => destinationEditions.includes(id)), ["light-currents-standard", "dawn-shore-standard"]); assert.deepEqual(rewardOf(player.id).filter((id) => destinationEditions.includes(id)), ["dawn-shore-standard"]); clock.now += 3 * HOUR; service.expeditions.claim(second.id, groupId); assert.ok(destinationCardsOf(service, second.id).includes("light-currents-standard")); // Trophée : la carte d'une destination cachée revient à coup sûr à qui y va sans l'avoir, mais n'est jamais tirée au hasard. const settings = { ...service.expeditions.settings, destinationCards: { dropPct: 0, groupJoinPct: 0 } }; assert.deepEqual(service.expeditions.rollDestinationCards(second.id, { id: "lost-observatory" }, settings, { group: false, random: () => 99 }), ["lost-observatory-standard"]); assert.ok(!service.expeditions.destinationCardEditions({ expeditionOnly: true }).some((edition) => edition.id === "lost-observatory-standard")); // Toutes les cartes des Carnets possédées : plus rien à trouver. database.transaction(() => destinationEditions.forEach((editionId) => service.addCard(player.id, editionId))); assert.deepEqual(service.expeditions.rollDestinationCards(player.id, { id: "light-currents" }, service.expeditions.settings, { group: true, random: () => 0 }), []); assert.deepEqual(service.expeditions.rollDestinationCards(player.id, { id: "lost-observatory" }, settings, { group: false, random: () => 0 }), []); }); test("an expedition launched alone is a solo: one card, its result hidden until it returns, paid once", () => { const { clock, service, player, open, rares, database } = expeditionService(); open(); const view = service.expeditions.getExpeditions(player.id); // Une difficulté envoyée par un ancien client est ignorée : les étoiles sont celles de la destination. const body = soloBody(view, rares[0], { difficulty: 4, durationHours: 6 }); const preview = service.expeditions.preview(player.id, body).preview; assert.ok(["struggle", "success", "triumph"].includes(preview.tier)); assert.deepEqual(preview.requirements.map((item) => item.value), view.destinations[0].requirements.map((item) => item.value)); assert.ok(preview.expected.eclats > 0); // L'expédition s'ouvre au tableau ; son créateur peut partir tout de suite, seul. const opened = service.expeditions.createGroup(player.id, body, "start-1"); const group = opened.expeditions.groups[0]; assert.equal(group.canDepart, true); assert.deepEqual(group.requirements, preview.requirements.map(({ stat, main, value }) => ({ stat, main, value }))); assert.equal(group.projected.scorePct, preview.scorePct); // Même clé : même expédition ; nouvelle clé : la carte est occupée, puis la limite d'expéditions s'applique. assert.equal(service.expeditions.createGroup(player.id, body, "start-1").expeditions.groups.length, 1); assert.throws(() => service.expeditions.createGroup(player.id, body, "start-2"), (error) => error.code === "EXPEDITION_CARD_BUSY"); assert.throws(() => service.expeditions.createGroup(player.id, { ...body, editionId: rares[1] }, "start-3"), (error) => error.code === "EXPEDITION_LIMIT"); service.expeditions.departGroup(player.id, group.id); const started = { expedition: service.expeditions.expeditionView(group.id, player.id), state: service.getState(player.id) }; assert.equal(started.expedition.mode, "solo"); assert.equal(started.expedition.status, "running"); assert.equal(started.expedition.stars, view.destinations[0].star); // Seule, une place : pas de Veilleur de la Guilde. assert.equal(started.expedition.slots.length, 1); 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), [rares[0]]); 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); assert.equal(returned.result.players, undefined); 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 une carte rapportée à l'unité (des Carnets de cette destination sans // collection), ajoutée à la collection ; plus de paquet offert. const rewardCards = returned.reward.cards.filter((editionId) => !destinationEditions.includes(editionId)); assert.equal(rewardCards.length, 1); assert.deepEqual(returned.reward.packs, []); assert.equal(claimed.state.giftPacks.length, 0); assert.ok(service.quantityOf(player.id, rewardCards[0]) >= 1); 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, 0); }); // Parcours du joueur : la carte de destination offerte se présente une fois ; « Partir seul maintenant » ouvre et lance l'expédition // d'un coup, sans alerte d'ouverture ; une seule expédition à la fois ; une fois le butin récupéré, elle passe au Journal. test("a player sees the offered destination card once, leaves alone at once, one expedition at a time, then finds it in the Journal", () => { const { clock, service, player, open, rares, database } = expeditionService({ allDestinations: false }); open(); // Une ancienne limite enregistrée dans les réglages (avant qu'elle devienne une règle fixe) n'a plus d'effet. const stored = JSON.parse(database.db.prepare("SELECT settings_json FROM expedition_settings").get().settings_json); database.db.prepare("UPDATE expedition_settings SET settings_json = ?").run(JSON.stringify({ ...stored, group: { ...stored.group, maxConcurrent: 3 } })); const first = service.expeditions.getExpeditions(player.id); assert.equal(first.starterCard, "light-currents-standard"); assert.equal(service.expeditions.getExpeditions(player.id).starterCard, "light-currents-standard"); assert.equal(service.expeditions.markStarterSeen(player.id).expeditions.starterCard, null); assert.ok(!service.getState(player.id).history.some((entry) => entry.type === "destination_starter_seen")); const view = service.expeditions.getExpeditions(player.id); assert.equal(view.group.limit, 1); const departed = service.expeditions.createGroup(player.id, { ...soloBody(view, rares[0]), departNow: true }, "now"); assert.deepEqual(departed.expeditions.groups, []); const [running] = departed.expeditions.expeditions; assert.equal(running.mode, "solo"); assert.equal(running.status, "running"); assert.equal(service.expeditions.pendingAlerts().length, 0); // Une seule expédition à la fois : ni ouvrir ni rejoindre tant que le butin n'est pas récupéré. assert.throws(() => service.expeditions.createGroup(player.id, soloBody(view, rares[1]), "second"), (error) => error.code === "EXPEDITION_LIMIT"); assert.deepEqual(departed.expeditions.journal, []); clock.now += 2 * HOUR; const claimed = service.expeditions.claim(player.id, running.id); assert.deepEqual(claimed.expeditions.expeditions, []); assert.deepEqual(claimed.expeditions.journal.map((item) => [item.id, item.status]), [[running.id, "completed"]]); assert.ok(claimed.expeditions.journal[0].reward.eclats >= 0); service.expeditions.createGroup(player.id, soloBody(view, rares[1]), "after"); }); // Une carte rapportée vient des Carnets de la destination ; une destination rattachée à une collection ouverte la tire le plus // souvent dans sa collection (rewardCards.linkedCollectionPct), sinon dans ses Carnets. Fermée, sa collection reste dans le // butin de qui possède la carte de la destination : un joueur qui a manqué la collection peut la rattraper. test("reward cards come from the Carnets, or mostly from the destination's collection when it is open or its destination card is owned", () => { const { service, admin, player, open, database } = expeditionService(); open(); const collectionOf = (editionId) => editionId && service.catalog.cards.find((card) => card.id === service.index.editions.get(editionId).cardId).collectionId; const settings = service.expeditions.settings; const draw = (destination, random, who = player) => collectionOf(service.expeditions.drawRewardCard(who.id, destination, settings, random)); const linked = (max) => (max === 100 ? settings.rewardCards.linkedCollectionPct - 1 : 0); // Les Îles de niveau, rattachées à l'Arcade : le joueur en possède la carte de destination, le nouveau venu non. const isles = { id: "level-isles", rewardCollectionId: "dream-arcade", logbookCards: ["cartographer-gecko"] }; const newcomer = service.upsertPlayer({ discordId: "expedition-newcomer", displayName: "Newcomer" }); // Sans collection, ou collection sans taux de tirage (l'Arcade, au départ) : une carte des Carnets de la destination. assert.equal(draw({ logbookCards: ["cartographer-gecko"] }, () => 0), "watchers-logbooks"); assert.equal(draw(isles, linked), "watchers-logbooks"); assert.equal(service.expeditions.drawRewardCard(player.id, { logbookCards: [] }, settings, () => 0), null); service.setDropRates(admin.id, "dream-arcade", { common: 70, rare: 20, epic: 7, legendary: 2, mythic: 1 }); // Fermée : sa collection seulement pour qui possède la carte de la destination. assert.equal(draw(isles, linked), "dream-arcade"); assert.equal(draw(isles, linked, newcomer), "watchers-logbooks"); assert.equal(draw({ ...isles, logbookCards: [] }, linked, newcomer), null); // Ouverte : sa collection sous linkedCollectionPct (75 par défaut) pour tous, les Carnets au-dessus. service.setCollectionActive(admin.id, "dream-arcade", true); assert.equal(draw(isles, linked, newcomer), "dream-arcade"); assert.equal(draw(isles, (max) => (max === 100 ? settings.rewardCards.linkedCollectionPct : 0)), "watchers-logbooks"); // Sans carte des Carnets, toujours sa collection. assert.equal(draw({ ...isles, logbookCards: [] }, (max) => max - 1, newcomer), "dream-arcade"); // Refermée : le nouveau venu qui obtient la carte de destination (en groupe, par exemple) peut rattraper la collection. service.setCollectionActive(admin.id, "dream-arcade", false); assert.equal(draw(isles, linked, newcomer), "watchers-logbooks"); const islesCard = service.expeditions.destinationCardEditions().find((edition) => service.index.cards.get(edition.cardId).destinationId === "level-isles"); database.transaction(() => service.addCard(newcomer.id, islesCard.id)); assert.equal(draw(isles, linked, newcomer), "dream-arcade"); }); // Serveur Vite local : une durée de test, aux règles de la plus courte, revient au bout de vingt secondes pour suivre un trajet et // son retour sans attendre ; l'inscription garde sa vraie durée. Ailleurs, cette durée est refusée. test("in local development a test duration returns after twenty seconds with the rules of the shortest one", () => { const { service, player, open, rares, clock } = expeditionService({ devPerks: true }); open(); const view = service.expeditions.getExpeditions(player.id); assert.equal(view.testDuration, "test"); const body = soloBody(view, rares[0], { durationHours: view.testDuration }); assert.equal(service.expeditions.preview(player.id, body).preview.travelHours, null); const opened = service.expeditions.createGroup(player.id, body, "test-open"); const group = opened.expeditions.groups.find((item) => item.isCreator); assert.equal(group.hours, view.durations[0]); assert.equal(group.recruitUntil, clock.now + service.expeditions.settings.group.recruitHours * 3_600_000); const [expedition] = service.expeditions.departGroup(player.id, group.id).expeditions.expeditions; assert.equal(expedition.returnsAt - expedition.departsAt, 20_000); const plain = expeditionService(); plain.open(); const plainView = plain.service.expeditions.getExpeditions(plain.player.id); assert.equal(plainView.testDuration, null); assert.throws(() => plain.service.expeditions.createGroup(plain.player.id, soloBody(plainView, plain.rares[0], { durationHours: "test" }), "test-closed"), (error) => error.code === "EXPEDITION_INVALID"); }); // Serveur Vite local : le compte de développement a toujours au moins un exemplaire de chaque objet (et assez de fragments pour une // carte au trésor), complété au chargement et après chaque usage ; les autres joueurs ne reçoivent rien. test("in local development the dev account always keeps every item", () => { const { service, player, open } = expeditionService({ devPerks: true }); open(); const dev = service.upsertPlayer({ discordId: "dev-admin", displayName: "Dev", isAdmin: true }); service.getState(dev.id); const items = service.expeditions.itemsOf(dev.id); assert.ok(Object.entries(items).every(([id, count]) => count >= (id === "fragment" ? service.expeditions.settings.items.fragmentsForMap : 1))); service.expeditions.rerollDestinations(dev.id); service.expeditions.rerollDestinations(dev.id); assert.equal(service.expeditions.itemsOf(dev.id).windRose, 1); service.getState(player.id); assert.ok(Object.values(service.expeditions.itemsOf(player.id)).every((count) => count === 0)); }); // Serveur Vite local : un joueur de test rejoint une expédition ouverte au groupe, avec une carte reçue s'il n'en a pas ; un joueur // de test déjà en expédition laisse la place à un nouveau. Ailleurs, l'action n'existe pas. test("in local development a test player joins a group expedition with a card of its own", () => { const { service, player, open, rares } = expeditionService({ devPerks: true }); open(); const view = service.expeditions.getExpeditions(player.id); assert.equal(view.testPlayers, true); const opened = service.expeditions.createGroup(player.id, soloBody(view, rares[0]), "test-player"); const group = opened.expeditions.groups.find((item) => item.isCreator); service.expeditions.addTestPlayer(player.id, group.id); const joined = service.expeditions.addTestPlayer(player.id, group.id).expeditions.groups.find((item) => item.id === group.id); assert.deepEqual(joined.members.map((member) => member.playerName).sort(), ["Joueur de test 1", "Joueur de test 2", "Player"]); const departed = service.expeditions.departGroup(player.id, group.id).expeditions.expeditions[0]; assert.equal(departed.mode, "group"); const plain = expeditionService(); plain.open(); assert.equal(plain.service.expeditions.getExpeditions(plain.player.id).testPlayers, false); assert.throws(() => plain.service.expeditions.addTestPlayer(plain.player.id, group.id), (error) => error.code === "NOT_FOUND"); assert.throws(() => plain.service.expeditions.openTestGroup(plain.player.id), (error) => error.code === "NOT_FOUND"); }); // Serveur Vite local : un joueur de test ouvre une expédition à la durée de test ; le joueur qui la rejoint (prêt d'emblée) ne peut // pas la lancer, elle part d'elle-même au bout de cinq minutes. test("in local development a test player opens a group that the player joins ready and that departs by itself", () => { const { service, player, open, rares, clock } = expeditionService({ devPerks: true }); open(); const board = service.expeditions.openTestGroup(player.id).expeditions.groups; assert.equal(board.length, 1); const [group] = board; assert.match(group.creatorName, /^Joueur de test \d+$/); assert.equal(group.canJoin, true); assert.equal(group.canDepart, false); assert.throws(() => service.expeditions.departGroup(player.id, group.id), (error) => error.code === "EXPEDITION_NOT_CREATOR"); assert.equal(group.recruitUntil, clock.now + 5 * 60_000); const joined = service.expeditions.joinGroup(player.id, group.id, { editionId: rares[0], ready: true }).expeditions.groups.find((item) => item.id === group.id); assert.equal(joined.isMember, true); assert.deepEqual(joined.ownSlot, { editionId: rares[0], ready: true }); assert.equal(joined.canDepart, false); assert.throws(() => service.expeditions.departGroup(player.id, group.id), (error) => error.code === "EXPEDITION_NOT_CREATOR"); const second = service.expeditions.openTestGroup(player.id).expeditions.groups.find((item) => item.id !== group.id); assert.notEqual(second.creatorName, group.creatorName); clock.now += 5 * 60_000; const departed = service.expeditions.getExpeditions(player.id).expeditions.find((item) => item.id === group.id); assert.equal(departed.mode, "group"); assert.equal(departed.returnsAt - departed.departsAt, 20_000); }); // Une carte de destination est unique : jamais en double, remplacée dans un paquet, jamais échangée ni donnée. test("destination cards are unique: never twice in a collection, replaced in packs, never traded", () => { const { service, player, database } = expeditionService({ allDestinations: false }); const other = service.upsertPlayer({ discordId: "unique-other", displayName: "Other" }); const cloud = "cosmic-cloud-heart-standard"; database.transaction(() => { assert.equal(service.addCard(player.id, cloud), true); assert.equal(service.addCard(player.id, cloud), false); }); assert.equal(service.quantityOf(player.id, cloud), 1); // Dans un paquet : déjà possédée, elle devient une autre rare de la Nébuleuse ; tirée deux fois, la seconde est remplacée. const rarity = (editionId) => service.index.editions.get(editionId).rarity; const collectionOf = (editionId) => service.index.cards.get(service.index.editions.get(editionId).cardId).collectionId; const first = database.transaction(() => service.insertOpening(player.id, "primordial-nebula", [cloud, rares(service)[0], cloud])); service.completeOpening(player.id, first.openingId); const replaced = first.editionIds; assert.ok(replaced.every((editionId) => !service.isDestinationEdition(editionId) || editionId !== cloud)); assert.ok(replaced.every((editionId) => rarity(editionId) === "rare" && collectionOf(editionId) === "primordial-nebula")); const second = database.transaction(() => service.insertOpening(other.id, "primordial-nebula", [cloud, cloud, rares(service)[0]])); service.completeOpening(other.id, second.openingId); const fresh = second.editionIds; assert.deepEqual(fresh.filter((editionId) => editionId === cloud), [cloud]); assert.equal(service.quantityOf(other.id, cloud), 1); // Ni échange ni don, même avec un ancien doublon. database.db.prepare("UPDATE collection_cards SET quantity = 2 WHERE player_id = ? AND edition_id = ?").run(player.id, cloud); assert.throws(() => service.createTransfer(player.id, { type: "gift", recipientId: other.id, editionId: cloud }), (error) => error.code === "DESTINATION_CARD_LOCKED"); }); const rares = (service) => editionsOf("rare").filter((editionId) => !service.isDestinationEdition(editionId)); test("unlucky rolls keep the average and never hand out a collection card", () => { const { clock, service, player, open, rares } = expeditionService({ random: (max) => max - 1 }); open(); const view = service.expeditions.getExpeditions(player.id); const started = goSolo(service, player.id, soloBody(view, rares[0]), "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("opening an expedition refuses stale days, unknown destinations, commons 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.createGroup(player.id, soloBody(view, rares[0], changes), key); assert.throws(start({ destinationId: "nowhere" }, "a"), (error) => error.code === "EXPEDITION_INVALID"); assert.throws(start({ durationHours: 3 }, "c"), (error) => error.code === "EXPEDITION_INVALID"); assert.throws(start({ editionId: editionsOf("common")[0] }, "f"), (error) => error.code === "EXPEDITION_CARD_INVALID"); assert.throws(start({ editionId: rares[10] }, "g"), (error) => error.code === "CARD_NOT_OWNED"); assert.throws(() => service.expeditions.createGroup(player.id, soloBody(view, rares[0]), ""), (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, 18); assert.ok(dashboard.expeditionSettings.schema.some((field) => field.path === "loot.eclatsPerHourCents")); const view = service.expeditions.getExpeditions(player.id); const started = goSolo(service, player.id, soloBody(view, rares[0]), "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 = goSolo(service, player.id, soloBody(view, rares[0]), "first"); clock.now += 2 * HOUR; service.expeditions.claim(player.id, first.expedition.id); const second = goSolo(service, player.id, soloBody(view, rares[1]), "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, stars: { ...settings.stars, max: 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; assert.ok(view.cards.length > 0, "the development account owns rare or better cards"); const body = soloBody(view, view.cards[0].editionId); 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 created = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-start" }, body }); assert.equal(created.status, 201); const expeditionId = created.json.expeditions.groups[0].id; const started = await call(handler, { method: "POST", path: `/api/cards/expeditions/${expeditionId}/depart`, headers }); assert.equal(started.json.expeditions.expeditions[0].status, "running"); const early = await call(handler, { method: "POST", path: `/api/cards/expeditions/${expeditionId}/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/${expeditionId}/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)); // Mêmes cartes de destination que le premier joueur : les trois tirent les mêmes destinations du jour. if (options?.allDestinations !== false) destinationEditions.forEach((editionId) => [second, third].forEach((member) => service.addCard(member.id, editionId))); }); return { ...context, second, third, arcade }; } const groupBody = soloBody; test("a group opens on the Guild board, fills its places 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.stars, { min: 1, max: 5, limit: 5 }); const created = service.expeditions.createGroup(player.id, groupBody(view, rares[0]), "g1"); assert.equal(service.expeditions.createGroup(player.id, groupBody(view, rares[0]), "g1").expeditions.groups.length, 1); const group = created.expeditions.groups[0]; assert.equal(group.isCreator, true); assert.equal(group.canDepart, true); assert.equal(group.freeSlots, DEFAULT_GROUP.slots - 1); assert.equal(created.state.expeditions.busyEditions[0].editionId, rares[0]); // Seule, l'expédition a les exigences d'une carte ; chaque joueur qui rejoint ajoute la part d'une place. assert.deepEqual(group.requirements.map((item) => item.value), view.destinations[0].requirements.map((item) => item.value)); // La carte du créateur est occupée : elle ne peut pas partir dans une autre expédition en même temps. assert.throws(() => service.expeditions.createGroup(player.id, soloBody(view, rares[0], { destinationId: view.destinations[1].id }), "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"); // Avant de rejoindre : les exigences du groupe avec ce joueur, et le résultat exact avec sa carte, sans l'inscrire. const withOne = view.destinations[0].requirements.map((item) => Math.round(item.value * 2 * 1.1)); assert.deepEqual(board.joinRequirements.map((item) => item.value), withOne); assert.equal(service.expeditions.getExpeditions(player.id).groups[0].joinRequirements, null); const { preview } = service.expeditions.previewJoin(second.id, group.id, { editionId: arcade[0] }); assert.deepEqual(preview.requirements.map((item) => item.value), withOne); assert.equal(service.expeditions.getExpeditions(second.id).groups[0].members.length, 1); assert.throws(() => service.expeditions.previewJoin(second.id, group.id, { editionId: rares[0] }), (error) => error.code === "CARD_NOT_OWNED"); assert.throws(() => service.expeditions.previewJoin(player.id, group.id, { editionId: rares[1] }), (error) => error.code === "EXPEDITION_ALREADY_JOINED"); assert.throws(() => service.expeditions.joinGroup(second.id, group.id, { editionId: rares[0] }), (error) => error.code === "CARD_NOT_OWNED"); assert.throws(() => service.expeditions.joinGroup(player.id, group.id, { editionId: rares[1] }), (error) => error.code === "EXPEDITION_ALREADY_JOINED"); service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0] }); 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); // Deux joueurs : deux places, et l'exigence de chacune relevée de `extraPlayerPct` (10 %). assert.deepEqual(before.requirements.map((item) => item.value), view.destinations[0].requirements.map((item) => Math.round(item.value * 2 * 1.1))); // Collections différentes : bonus de cohésion. assert.equal(before.projected.cohesionPct, 10); // L'aperçu d'avant l'inscription annonçait ce même résultat. assert.deepEqual(preview.projected, before.projected); service.expeditions.departGroup(player.id, group.id); assert.deepEqual(service.expeditions.getExpeditions(third.id).groups, []); const slots = database.db.prepare("SELECT player_id FROM expedition_slots WHERE expedition_id = ? ORDER BY position").all(group.id); // Une place par joueur : les places restées libres disparaissent au départ. assert.equal(slots.length, 2); assert.ok(slots.every((slot) => slot.player_id != null)); assert.throws(() => service.expeditions.joinGroup(third.id, group.id, { editionId: rares[5] }), (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("a player who joins a group sets up their card and equipment, then says they are ready, which freezes its stats", () => { const { service, player, second, open, rares, arcade, database } = groupService(); open(); const view = service.expeditions.getExpeditions(player.id); const group = service.expeditions.createGroup(player.id, groupBody(view, rares[0]), "ready").expeditions.groups[0]; const common = editionsOf("common", "dream-arcade")[0]; database.transaction(() => service.addCard(second.id, common)); service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0] }); const boardOf = (playerId) => service.expeditions.getExpeditions(playerId).groups[0]; const statsOf = () => service.expeditions.memberSlots(group.id, { live: true }).find((slot) => slot.playerId === second.id).stats; const sum = (stats) => Object.values(stats).reduce((total, value) => total + value, 0); // Le créateur est prêt dès l'ouverture ; le joueur qui rejoint, pas encore. assert.deepEqual(boardOf(player.id).members.map((member) => member.ready), [true, false]); assert.equal(boardOf(player.id).ownSlot, null); assert.deepEqual(boardOf(second.id).ownSlot, { editionId: arcade[0], ready: false }); assert.throws(() => service.expeditions.updateGroupMember(player.id, group.id, { ready: false }), (error) => error.code === "EXPEDITION_CREATOR_READY"); assert.throws(() => service.expeditions.updateGroupMember(second.id, group.id, {}), (error) => error.code === "EXPEDITION_MEMBER_INVALID"); // Pas encore prêt : sa carte s'équipe, et le groupe compte aussitôt ses nouvelles stats ; il peut aussi changer de carte. const bare = sum(statsOf()); service.expeditions.equip(second.id, { editionId: arcade[0], slot: 0, equipmentEditionId: common }); assert.ok(sum(statsOf()) > bare); service.expeditions.updateGroupMember(second.id, group.id, { editionId: arcade[1] }); assert.equal(boardOf(second.id).ownSlot.editionId, arcade[1]); assert.deepEqual(service.getState(second.id).expeditions.busyEditions.map((entry) => entry.editionId), [arcade[1]]); service.expeditions.updateGroupMember(second.id, group.id, { editionId: arcade[0] }); // Prêt : les stats sont figées, l'équipement et la carte ne changent plus. service.expeditions.updateGroupMember(second.id, group.id, { ready: true }); assert.deepEqual(boardOf(player.id).members.map((member) => member.ready), [true, true]); const frozen = statsOf(); assert.equal(sum(frozen), sum(JSON.parse(database.db.prepare("SELECT stats_json FROM expedition_slots WHERE expedition_id = ? AND player_id = ?").get(group.id, second.id).stats_json))); assert.throws(() => service.expeditions.equip(second.id, { editionId: arcade[0], slot: 0, equipmentEditionId: null }), (error) => error.code === "EXPEDITION_CARD_BUSY"); assert.throws(() => service.expeditions.updateGroupMember(second.id, group.id, { editionId: arcade[1] }), (error) => error.code === "EXPEDITION_MEMBER_READY"); // Revenu sur sa préparation, il retire l'équipement ; le créateur lance sans attendre : la carte part telle qu'elle est. service.expeditions.updateGroupMember(second.id, group.id, { ready: false }); service.expeditions.equip(second.id, { editionId: arcade[0], slot: 0, equipmentEditionId: null }); service.expeditions.departGroup(player.id, group.id); const departed = JSON.parse(database.db.prepare("SELECT stats_json FROM expedition_slots WHERE expedition_id = ? AND player_id = ?").get(group.id, second.id).stats_json); assert.equal(sum(departed), bare); assert.throws(() => service.expeditions.equip(second.id, { editionId: arcade[0], slot: 0, equipmentEditionId: common }), (error) => error.code === "EXPEDITION_CARD_BUSY"); }); test("an unlaunched expedition departs by itself at the end of recruitment, alone as a solo or as a group", () => { const { clock, service, player, second, third, open, rares, arcade, database } = groupService(); open({ group: { ...DEFAULT_GROUP, recruitHours: 1 } }); const view = service.expeditions.getExpeditions(player.id); const lonely = service.expeditions.createGroup(third.id, groupBody(view, rares[5]), "lonely").expeditions.groups[0]; const full = service.expeditions.createGroup(player.id, groupBody(view, rares[0], { destinationId: view.destinations[1].id }), "full").expeditions.groups.find((group) => group.isCreator); service.expeditions.joinGroup(second.id, full.id, { editionId: arcade[0] }); clock.now += HOUR + 1; // Seule, elle part en solo, sans Veilleur de la Guilde, et n'est plus dissoute. const alone = service.expeditions.getExpeditions(third.id).expeditions.find((expedition) => expedition.id === lonely.id); assert.equal(alone.mode, "solo"); assert.equal(alone.status, "running"); assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM expedition_slots WHERE expedition_id = ?").get(lonely.id).count, 1); assert.ok(!service.getState(third.id).history.some((entry) => entry.type === "expedition_dissolved")); const departed = service.expeditions.getExpeditions(player.id).expeditions.find((expedition) => expedition.id === full.id); assert.equal(departed.mode, "group"); 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); }); 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 group = service.expeditions.createGroup(player.id, groupBody(view, rares[0]), "leave").expeditions.groups[0]; service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0] }); 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] }); 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 group = service.expeditions.createGroup(player.id, groupBody(view, rares[0]), "forfeit").expeditions.groups[0]; service.expeditions.joinGroup(second.id, group.id, { editionId: arcade[0] }); 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, readies, 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 created = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-group" }, body: groupBody(view, view.cards[0].editionId) }); assert.equal(created.status, 201); const groupId = created.json.expeditions.groups[0].id; service.expeditions.joinGroup(other.id, groupId, { editionId: editionsOf("rare")[1] }); const again = await call(handler, { method: "POST", path: `/api/cards/expeditions/${groupId}/join`, headers, body: { editionId: view.cards[0].editionId } }); assert.equal(again.json.error.code, "EXPEDITION_ALREADY_JOINED"); // « Prêt » passe par sa route ; le créateur, prêt dès l'ouverture, ne l'utilise pas. const ready = await call(handler, { method: "PUT", path: `/api/cards/expeditions/${groupId}/member`, headers, body: { ready: false } }); assert.equal(ready.json.error.code, "EXPEDITION_CREATOR_READY"); 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 = goSolo(service, player.id, soloBody(view, card), "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 ?? 0, 0); // 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("a pack that draws a destination card already owned replaces it, also without an injected random source", () => { // Le serveur crée le service sans source de hasard : le remplacement d'une carte de destination déjà possédée doit tout de même tirer. const database = new CardsDatabase(":memory:"); const service = new CardsService({ database, catalog: baseCatalog, now: () => Date.parse("2026-11-15T09:00:00Z") }); const player = service.upsertPlayer({ discordId: "destination-owner", displayName: "Player" }); const [destination] = destinationEditions; database.transaction(() => service.addCard(player.id, destination)); const [replaced] = service.uniqueDestinationCards(player.id, [destination]); const edition = published.editions.find((item) => item.id === replaced); assert.notEqual(replaced, destination); assert.equal(edition.rarity, published.editions.find((item) => item.id === destination).rarity); database.close(); }); test("a card at an awakening tier awakens with its own duplicate or duplicates of its collection and rarity, never with Éclats", () => { const { service, player, open, rares, database } = expeditionService(); open(); const [card, second, third] = rares; const progressOf = (editionId = card) => service.getState(player.id).cardProgress.find((item) => item.editionId === editionId); database.db.prepare("UPDATE players SET eclats = 1000 WHERE id = ?").run(player.id); // Niveau 5 d'une rare : Puissance 65, le niveau suivant atteint le palier de 70. database.db.prepare("INSERT INTO card_progress(player_id, edition_id, level, field_xp, updated_at) VALUES (?, ?, 5, 0, 0)").run(player.id, card); assert.deepEqual(progressOf().awakening, { power: 70, exact: null, anyCollection: false, needed: 6, available: 0, candidates: [] }); assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "eclats" }), (error) => error.code === "AWAKENING_REQUIRED"); assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "awaken" }), (error) => error.code === "NOT_ENOUGH_DUPLICATES"); assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: second, method: "awaken" }), (error) => error.code === "NOT_AT_AWAKENING"); // Six doublons rares de la Nébuleuse, choisis par le joueur parmi les candidats (les plus nombreux d'abord), sans Éclats ; // une rare d'une autre collection ne compte pas. database.transaction(() => { for (let count = 0; count < 4; count += 1) service.addCard(player.id, second); for (let count = 0; count < 3; count += 1) service.addCard(player.id, third); service.addCard(player.id, editionsOf("rare", "dream-arcade")[0]); service.addCard(player.id, editionsOf("rare", "dream-arcade")[0]); }); assert.deepEqual(progressOf().awakening, { power: 70, exact: null, anyCollection: false, needed: 6, available: 7, candidates: [{ editionId: second, spare: 4 }, { editionId: third, spare: 3 }] }); const invalid = (editionIds) => assert.throws(() => service.expeditions.upgradeCard(player.id, { editionId: card, method: "awaken", editionIds }), (error) => error.code === "AWAKENING_SELECTION_INVALID"); invalid([second, second, third, third, third]); invalid([second, second, second, second, second, third]); invalid([second, second, second, third, third, editionsOf("rare", "dream-arcade")[0]]); invalid("all"); const awakened = service.expeditions.upgradeCard(player.id, { editionId: card, method: "awaken", editionIds: [third, second, third, second, third, second] }); assert.deepEqual([awakened.progress.level, awakened.progress.power, awakened.progress.awakening, awakened.state.wallet.eclats], [6, 70, null, 1000]); assert.deepEqual([service.quantityOf(player.id, second), service.quantityOf(player.id, third)], [2, 1]); assert.deepEqual(awakened.progress.awakeningsAhead, [85, 100]); // Le doublon de la carte elle-même éveille aussi, et un doublon ordinaire ne franchit jamais un palier. database.db.prepare("UPDATE card_progress SET level = 7 WHERE player_id = ? AND edition_id = ?").run(player.id, card); database.transaction(() => { service.addCard(player.id, card); service.addCard(player.id, card); }); const byDuplicate = service.expeditions.upgradeCard(player.id, { editionId: card, method: "duplicate" }); assert.equal(byDuplicate.progress.level, 8); assert.equal(byDuplicate.progress.awakening.power, 85); const awakenedByCopy = service.expeditions.upgradeCard(player.id, { editionId: card, method: "duplicate" }); assert.deepEqual([awakenedByCopy.progress.level, awakenedByCopy.progress.power, service.quantityOf(player.id, card)], [9, 85, 1]); const history = service.getState(player.id).history.filter((entry) => entry.type === "card_upgraded"); assert.deepEqual(history.map((entry) => entry.details.awakened ?? null), [70, null, 85]); // Une mythique s'éveille avec sa version légendaire, ou avec une légendaire de sa collection. const legendary = editionsOf("legendary")[0]; const cardId = published.editions.find((edition) => edition.id === legendary).cardId; const mythic = mythicEditionId(cardId, "spectral-prism-solar"); database.db.prepare("INSERT INTO mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by) VALUES (?, ?, 'spectral-prism-solar', 'active', 0, NULL)").run(mythic, cardId); service.reloadCatalog(); database.transaction(() => { service.addCard(player.id, mythic); service.addCard(player.id, legendary); service.addCard(player.id, legendary); }); database.db.prepare("INSERT INTO card_progress(player_id, edition_id, level, field_xp, updated_at) VALUES (?, ?, 2, 0, 0)").run(player.id, mythic); assert.deepEqual(progressOf(mythic).awakening, { power: 100, exact: legendary, anyCollection: false, needed: 1, available: 0, candidates: [] }); const mythicAwakened = service.expeditions.upgradeCard(player.id, { editionId: mythic, method: "duplicate" }); assert.deepEqual([mythicAwakened.progress.level, mythicAwakened.progress.power, service.quantityOf(player.id, legendary)], [3, 100, 1]); }); test("a card of a closed, expedition or shop collection awakens with duplicates of its rarity from any collection, at the same count", () => { const { service, admin, player, open, rares, database } = expeditionService(); open(); const [card] = rares; const arcade = editionsOf("rare", "dream-arcade")[0]; const logbook = editionsOf("legendary", "watchers-logbooks")[0]; const shopLegendary = editionsOf("legendary", "stardust")[0]; const nebulaLegendary = editionsOf("legendary")[0]; const awakeningOf = (editionId) => service.getState(player.id).cardProgress.find((item) => item.editionId === editionId).awakening; // Une rare de la Nébuleuse devant le palier de 70, six rares de l'Arcade en double ; une légendaire des Carnets et une de la boutique devant celui de 85. database.transaction(() => { for (let count = 0; count < 7; count += 1) service.addCard(player.id, arcade); service.addCard(player.id, logbook); service.addCard(player.id, shopLegendary); service.addCard(player.id, nebulaLegendary); service.addCard(player.id, nebulaLegendary); }); database.db.prepare("INSERT INTO card_progress(player_id, edition_id, level, field_xp, updated_at) VALUES (?, ?, 5, 0, 0), (?, ?, 2, 0, 0), (?, ?, 2, 0, 0)").run(player.id, card, player.id, logbook, player.id, shopLegendary); assert.deepEqual([awakeningOf(card).anyCollection, awakeningOf(card).candidates], [false, []]); // La Nébuleuse fermée, ses paquets ne s'ouvrent plus : les rares de toute collection conviennent, toujours six. service.setCollectionActive(admin.id, "primordial-nebula", false); assert.deepEqual(awakeningOf(card), { power: 70, exact: null, anyCollection: true, needed: 6, available: 6, candidates: [{ editionId: arcade, spare: 6 }] }); // Rouverte, elle reprend la règle de sa collection. service.setCollectionActive(admin.id, "primordial-nebula", true); assert.deepEqual([awakeningOf(card).anyCollection, awakeningOf(card).candidates], [false, []]); service.setCollectionActive(admin.id, "primordial-nebula", false); const awakened = service.expeditions.upgradeCard(player.id, { editionId: card, method: "awaken", editionIds: Array(6).fill(arcade) }); assert.deepEqual([awakened.progress.level, awakened.progress.power, service.quantityOf(player.id, arcade)], [6, 70, 1]); // Les Carnets des Veilleurs (expéditions) et les Scintillants (boutique, même ouverte) ne sortent pas des ouvertures : toute collection // convient, toujours une seule légendaire ; le doublon exact reste accepté. service.setCollectionActive(admin.id, "stardust", true); for (const editionId of [logbook, shopLegendary]) { assert.deepEqual(awakeningOf(editionId), { power: 85, exact: null, anyCollection: true, needed: 1, available: 1, candidates: [{ editionId: nebulaLegendary, spare: 1 }] }); } const logbookAwakened = service.expeditions.upgradeCard(player.id, { editionId: logbook, method: "awaken", editionIds: [nebulaLegendary] }); assert.deepEqual([logbookAwakened.progress.level, logbookAwakened.progress.power, service.quantityOf(player.id, nebulaLegendary)], [3, 85, 1]); assert.deepEqual([awakeningOf(shopLegendary).anyCollection, awakeningOf(shopLegendary).available], [true, 0]); database.transaction(() => service.addCard(player.id, shopLegendary)); assert.equal(awakeningOf(shopLegendary).exact, shopLegendary); database.close(); }); test("progression plans spread level points by vocation or by hand, and a Parchemin d'oubli pays for each change", () => { const { service, player, open, rares, database } = expeditionService(); open(); const [card] = rares; // Niveau 4 d'une rare : Puissance 60, dont 20 points de niveau, 12 au plus dans une stat (60 %). database.db.prepare("INSERT INTO card_progress(player_id, edition_id, level, field_xp, updated_at) VALUES (?, ?, 4, 0, 0)").run(player.id, card); const progressOf = () => service.getState(player.id).cardProgress.find((item) => item.editionId === card); const sum = (stats) => Object.values(stats).reduce((total, value) => total + value, 0); const before = progressOf(); assert.deepEqual([before.power, before.plan.id, before.plan.points, before.plan.maxStatPoints, before.plan.paid], [60, "collection", 20, 12, false]); assert.deepEqual(before.stats, before.plan.previews.collection); assert.equal(sum(before.plan.levelBase), 40); // Tant que la carte suit sa collection, choisir une vocation est gratuit et s'applique aux points déjà gagnés. const guardian = service.expeditions.setCardPlan(player.id, { editionId: card, plan: "guardian" }).progress; const base = before.plan.levelBase; assert.deepEqual(guardian.stats, { bravoure: base.bravoure + 4, endurance: base.endurance + 12, fortune: base.fortune + 4, orientation: base.orientation }); assert.deepEqual(guardian.stats, before.plan.previews.guardian); assert.equal(guardian.plan.paid, true); assert.deepEqual(service.expeditions.getExpeditions(player.id).cards.find((item) => item.editionId === card).stats, guardian.stats); // Ensuite, changer de plan consomme un Parchemin d'oubli, acheté en boutique avec de la poussière. assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "navigator" }), (error) => error.code === "NOT_ENOUGH_ITEMS"); database.db.prepare("UPDATE players SET stardust = 400 WHERE id = ?").run(player.id); assert.throws(() => service.expeditions.buyShopItem(player.id, { item: "oblivion", count: 3 }), (error) => error.code === "NOT_ENOUGH_STARDUST"); assert.throws(() => service.expeditions.buyShopItem(player.id, { item: "oblivion", count: 0 }), (error) => error.code === "PURCHASE_INVALID"); assert.equal(service.expeditions.buyShopItem(player.id, { item: "oblivion", count: 2 }).wallet.stardust, 100); assert.equal(service.expeditions.itemsOf(player.id).oblivion, 2); assert.equal(service.expeditions.setCardPlan(player.id, { editionId: card, plan: "navigator" }).progress.stats.orientation, base.orientation + 12); assert.equal(service.expeditions.itemsOf(player.id).oblivion, 1); // Reprendre le même plan ne coûte rien. service.expeditions.setCardPlan(player.id, { editionId: card, plan: "navigator" }); assert.equal(service.expeditions.itemsOf(player.id).oblivion, 1); // En libre : au plus 12 points dans une stat et 20 en tout ; ajouter des points est gratuit, en retirer coûte un Parchemin. const allocation = (bravoure, fortune) => ({ bravoure, endurance: 0, fortune, orientation: 0 }); assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(13, 0) }), (error) => error.code === "ALLOCATION_INVALID"); assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: { bravoure: 12, fortune: 12 } }), (error) => error.code === "ALLOCATION_INVALID"); assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: { bravoure: 1.5 } }), (error) => error.code === "ALLOCATION_INVALID"); const free = service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(12, 3) }).progress; assert.equal(service.expeditions.itemsOf(player.id).oblivion, 0); assert.deepEqual(free.plan.allocation, allocation(12, 3)); assert.equal(sum(free.stats), 55, "5 points restent à placer"); service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(12, 8) }); assert.equal(sum(progressOf().stats), 60); assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(10, 8) }), (error) => error.code === "NOT_ENOUGH_ITEMS"); assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "wizard" }), (error) => error.code === "PLAN_INVALID"); // Un niveau de plus en libre : 5 nouveaux points à placer, les anciens restent. database.db.prepare("UPDATE card_progress SET level = 5 WHERE player_id = ? AND edition_id = ?").run(player.id, card); assert.deepEqual([progressOf().plan.points, sum(progressOf().stats)], [25, 60]); // Réinitialiser (un Parchemin) remet la carte en libre sans point placé : le choix suivant, un profil par exemple, est gratuit. database.db.prepare("UPDATE players SET stardust = 400 WHERE id = ?").run(player.id); service.expeditions.buyShopItem(player.id, { item: "oblivion", count: 1 }); const reset = service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(0, 0) }).progress; assert.deepEqual([reset.plan.id, reset.plan.paid, service.expeditions.itemsOf(player.id).oblivion], ["free", false, 0]); assert.equal(service.expeditions.setCardPlan(player.id, { editionId: card, plan: "seeker" }).progress.plan.paid, true); assert.equal(service.expeditions.itemsOf(player.id).oblivion, 0); // Le plan d'une carte en expédition ne change pas avant son retour. const view = service.expeditions.getExpeditions(player.id); goSolo(service, player.id, soloBody(view, card), "planned"); assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: card, plan: "free", allocation: allocation(12, 13) }), (error) => error.code === "EXPEDITION_CARD_BUSY"); assert.throws(() => service.expeditions.setCardPlan(player.id, { editionId: editionsOf("common")[0], plan: "guardian" }), (error) => error.code === "CARD_NOT_OWNED"); const history = service.getState(player.id).history; assert.deepEqual(history.filter((entry) => entry.type === "card_plan_changed").map((entry) => [entry.details.plan, entry.details.oblivion]), [["guardian", false], ["navigator", true], ["free", true], ["free", false], ["free", true], ["seeker", false]]); assert.ok(history.some((entry) => entry.type === "item_bought" && entry.details.item === "oblivion" && entry.details.count === 2 && entry.details.stardust === 300)); assert.equal(service.getState(player.id).shop.oblivionPrice, 150); }); test("each Rose des vents draws new destinations for the day, as many times as the player has some, and bonus destinations stay", () => { const { service, player, open, database } = expeditionService(); open(); const daily = (view) => view.destinations.filter((item) => !item.bonusSlot).map((item) => item.id); const bonusOf = (view) => view.destinations.filter((item) => item.bonusSlot).map((item) => item.id); assert.throws(() => service.expeditions.rerollDestinations(player.id), (error) => error.code === "NOT_ENOUGH_ITEMS"); // La Rose des vents s'achète en boutique, comme le Parchemin. database.db.prepare("UPDATE players SET stardust = 200 WHERE id = ?").run(player.id); assert.throws(() => service.expeditions.buyShopItem(player.id, { item: "anchor", count: 1 }), (error) => error.code === "ITEM_INVALID"); assert.equal(service.expeditions.buyShopItem(player.id, { item: "windRose", count: 2 }).wallet.stardust, 80); database.transaction(() => service.expeditions.addItemsInTx(player.id, ["guideStar"])); service.expeditions.addBonusDestination(player.id, { item: "guideStar" }); const before = service.expeditions.getExpeditions(player.id); // De nouvelles destinations, aucune déjà vue aujourd'hui, un niveau de chaque ; la 5e destination reste. const after = service.expeditions.rerollDestinations(player.id).expeditions; assert.equal(daily(after).length, daily(before).length); assert.ok(daily(after).every((id) => !daily(before).includes(id) && !bonusOf(before).includes(id))); assert.deepEqual(bonusOf(after), bonusOf(before)); assert.deepEqual(after.destinations.filter((item) => !item.bonusSlot).map((item) => item.level).sort(), [0, 1, 2, 3]); assert.throws(() => service.expeditions.preview(player.id, { day: after.day, destinationId: daily(before)[0], durationHours: 2, slots: [] }), (error) => error.code === "EXPEDITION_INVALID"); // Pas de limite par jour : la seconde Rose tire aussitôt d'autres destinations ; sans Rose, plus de tirage. assert.equal(service.expeditions.itemsOf(player.id).windRose, 1); const again = service.expeditions.rerollDestinations(player.id).expeditions; assert.equal(daily(again).length, daily(after).length); assert.deepEqual(bonusOf(again), bonusOf(before)); assert.equal(service.expeditions.itemsOf(player.id).windRose, 0); assert.throws(() => service.expeditions.rerollDestinations(player.id), (error) => error.code === "NOT_ENOUGH_ITEMS"); const history = service.getState(player.id).history; assert.equal(history.filter((entry) => entry.type === "item_used" && entry.details.item === "windRose").length, 2); assert.ok(history.some((entry) => entry.type === "item_bought" && entry.details.item === "windRose" && entry.details.stardust === 120)); }); 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 and move between cards", 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.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 = goSolo(service, player.id, soloBody(view, card), "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"]) 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"); }); // Les Résonances lient les cartes d'une même équipe : seule, une carte n'en a pas ; en groupe, elles comptent dans le score. test("resonances raise a group's score", () => { const { service, player, second, open, database } = groupService(); open(); // Écho : le hamster de la Nébuleuse et sa version de l'Arcade des Rêves, apportés par deux joueurs. database.transaction(() => { service.addCard(player.id, "solar-seed-hamster-standard"); service.addCard(second.id, "steel-ball-hamster-standard"); }); const view = service.expeditions.getExpeditions(player.id); const body = groupBody(view, "solar-seed-hamster-standard"); assert.deepEqual(service.expeditions.preview(player.id, body).preview.resonances, []); const group = service.expeditions.createGroup(player.id, body, "echo").expeditions.groups[0]; service.expeditions.joinGroup(second.id, group.id, { editionId: "steel-ball-hamster-standard" }); const projected = service.expeditions.getExpeditions(player.id).groups[0].projected; assert.ok(projected.resonances.some((resonance) => resonance.type === "echo" && resonance.key === "personnage:hamster")); assert.ok(projected.synergyPct >= 10); service.expeditions.departGroup(player.id, group.id); // Le Grimoire est retiré : plus de table ni de liste des découvertes. assert.equal(service.expeditions.getExpeditions(player.id).grimoire, undefined); assert.equal(service.db.prepare("SELECT COUNT(*) AS count FROM sqlite_master WHERE name = 'grimoire_entries'").get().count, 0); }); 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 group = service.expeditions.createGroup(player.id, groupBody(view, rares[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\/[0-9a-f-]{36}$/); // L'embed montre la destination en vignette ; le bouton ouvre directement le groupe. assert.match(pending[0].extra.embed.title, /^Nouveau groupe vers /); assert.match(pending[0].extra.embed.thumbnail, /^https:\/\/sokko\.example\/static\/img\//); assert.deepEqual(pending[0].extra.link, { label: "Rejoindre le groupe", url: `https://sokko.example/#/cards/expeditions/${group.id}` }); 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] }); 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); const returned = JSON.parse(database.db.prepare("SELECT extra_json FROM alert_outbox WHERE kind = 'expedition_returned' LIMIT 1").get().extra_json); assert.equal(returned.embed.title, "Votre expédition est de retour !"); assert.deepEqual(returned.embed.fields.map((field) => field.name), ["Résultat", "Butin"]); assert.equal(returned.link.label, "Voir l’expédition"); // 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); }); // Passage périodique des alertes, sans aucune visite de joueur : un groupe dont l'inscription est échue part, puis son retour est // annoncé. Un message déjà en file n'est envoyé que s'il est encore voulu : désactivé par le joueur ou coupé par l'administration, // il est abandonné, et ne repart pas plus tard. test("periodic alerts settle due groups without any visit and drop messages no longer wanted", async () => { const context = expeditionService(); const { clock, service, player, open, rares, database } = context; service.expeditions.alertsAvailable = true; open(); const friend = service.upsertPlayer({ discordId: "123456789012345678", displayName: "Friend" }); database.db.prepare("UPDATE players SET discord_id = '323456789012345678' WHERE id = ?").run(player.id); service.expeditions.setAlertPreferences(player.id, { groupOpened: false, expeditionReturned: true }); service.expeditions.setAlertPreferences(friend.id, { groupOpened: true, expeditionReturned: false }); const sent = []; const send = async (discordId, content) => { sent.push({ discordId, content }); }; // Groupe ouvert : l'ami est prévenu, mais désactive l'alerte avant l'envoi ; le message est abandonné. const view = service.expeditions.getExpeditions(player.id); const group = service.expeditions.createGroup(player.id, groupBody(view, rares[0]), "auto-depart").expeditions.groups[0]; service.expeditions.setAlertPreferences(friend.id, { groupOpened: false, expeditionReturned: false }); assert.equal(await dispatchAlerts(service.expeditions, send), 0); assert.deepEqual({ ...database.db.prepare("SELECT kind, last_error FROM alert_outbox WHERE player_id = ?").get(friend.id) }, { kind: "group_opened", last_error: "player opted out" }); service.expeditions.setAlertPreferences(friend.id, { groupOpened: true, expeditionReturned: false }); assert.equal(await dispatchAlerts(service.expeditions, send), 0); // Personne ne revient sur le site : l'inscription puis le voyage s'achèvent, le passage fait partir le groupe et annonce son retour. clock.now = group.recruitUntil + 3 * HOUR; assert.equal(await dispatchAlerts(service.expeditions, send), 1); assert.equal(sent[0].discordId, "323456789012345678"); assert.match(sent[0].content, /est de retour/); assert.equal(database.db.prepare("SELECT status FROM expeditions WHERE id = ?").get(group.id).status, "running"); // Coupées par l'administration après la mise en file : le message n'est pas envoyé, ni plus tard une fois les alertes rouvertes. const later = service.expeditions.getExpeditions(player.id); service.expeditions.claim(player.id, later.expeditions[0].id); service.expeditions.createGroup(player.id, groupBody(service.expeditions.getExpeditions(player.id), rares[1]), "second-group"); service.expeditions.updateSettings(context.admin.id, { ...service.expeditions.settings, alerts: { enabled: false } }); assert.equal(await dispatchAlerts(service.expeditions, send), 0); service.expeditions.updateSettings(context.admin.id, { ...service.expeditions.settings, alerts: { enabled: true } }); assert.equal(await dispatchAlerts(service.expeditions, send), 0); assert.equal(sent.length, 1); assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM alert_outbox WHERE last_error = 'alerts disabled'").get().count, 1); }); 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", { embed: { title: "Retour" }, link: { label: "Voir", url: "https://sokko.example/#/cards/expeditions/abc" } }); assert.equal(calls[0].options.headers.Authorization, "Bearer secret"); assert.deepEqual(JSON.parse(calls[0].options.body), { userId: "123456789012345678", content: "Bonjour", embed: { title: "Retour" }, link: { label: "Voir", url: "https://sokko.example/#/cards/expeditions/abc" } }); 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 destination de plus, un niveau sous le plus haut de ses destinations du jour (★★★★ avec 4 destinations), // pour ce joueur seulement ; une seule par jour. Carte céleste : une autre, au plus haut niveau du jour. give(["guideStar", "guideStar", "skyChart", "anchor", "engraving", "fragment", "fragment", "fragment", "fragment"]); const before = service.expeditions.getExpeditions(player.id); assert.equal(before.items.guideStar, 2); // Propositions sous les destinations du jour : ce que chaque objet ajouterait (étoiles, butin), avant de l'utiliser. const offer = (view, item) => view.bonusOffers.find((entry) => entry.item === item); assert.deepEqual(before.bonusOffers.map(({ item, used, required, stars, lootPct }) => [item, used, required, stars, lootPct]), [["guideStar", false, 1, 3, 100], ["skyChart", false, 1, 4, 125], ["fragment", false, 4, 5, 150]]); 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.deepEqual([bonus.level, bonus.star], [2, 3]); assert.equal(offer(added, "guideStar").used, true); assert.equal(offer(added, "skyChart").used, false); assert.throws(() => service.expeditions.addBonusDestination(player.id, { item: "guideStar" }), (error) => error.code === "BONUS_ALREADY_USED"); const sky = service.expeditions.addBonusDestination(player.id, { item: "skyChart" }).expeditions.destinations.find((destination) => destination.bonusSlot === "6"); assert.deepEqual([sky.level, sky.star], [3, 4]); assert.throws(() => service.expeditions.addBonusDestination(player.id, { item: "skyChart" }), (error) => error.code === "BONUS_ALREADY_USED"); 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); // Les destinations bonus restent à ce joueur. assert.ok(service.expeditions.getExpeditions(service.upsertPlayer({ discordId: "other", displayName: "Other" }).id).destinations.every((destination) => !destination.bonusSlot)); // 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 = goSolo(service, player.id, soloBody(view, rares[0], { 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 = goSolo(service, player.id, soloBody(view, rares[0]), "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); }); // Toutes les cartes des Carnets n'ont pas encore leur illustration : les tests leur en donnent une, ou la leur retirent, // 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`; } function unillustrateLogbooks(service) { for (const card of service.catalog.cards.filter((item) => item.collectionId === "watchers-logbooks")) { delete card.image; delete card.fullImage; } } 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({ loot: { ...service.expeditions.settings.loot, 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. unillustrateLogbooks(service); const first = goSolo(service, player.id, soloBody(view, rares[0]), "no-art"); clock.now += 2 * HOUR; const logbooksOf = (cards) => cards.filter((editionId) => service.catalog.cards.find((card) => card.id === service.index.editions.get(editionId).cardId).collectionId === "watchers-logbooks"); assert.deepEqual(logbooksOf(service.expeditions.claim(player.id, first.expedition.id).expedition.reward.cards), []); illustrateLogbooks(service); const second = goSolo(service, player.id, soloBody(view, rares[0]), "with-art"); clock.now += 2 * HOUR; const reward = service.expeditions.claim(player.id, second.expedition.id).expedition.reward; assert.equal(logbooksOf(reward.cards).length, 1); assert.ok(service.quantityOf(player.id, logbooksOf(reward.cards)[0]) >= 1); }); test("a treasure map brings its rare object back only from a successful expedition", () => { const { service, open } = expeditionService(); open(); const settings = service.expeditions.settings; const expected = { eclats: 0, stardust: 0, cards: 0, objects: 0 }; const hidden = ["fragment", "engraving", "plan"]; const won = service.expeditions.rollReward(expected, settings, { powers: ["treasureMap"], tier: "success" }); assert.equal(won.items.length, 1); assert.ok(hidden.includes(won.items[0])); assert.deepEqual(service.expeditions.rollReward(expected, settings, { powers: ["treasureMap"], tier: "struggle" }).items, []); }); test("a collection's own power shows its effect before departure, and Étude counts when the loot is claimed", () => { const { service, player, open, rares, clock, database } = expeditionService(); open(); const notebook = "astronomers-notebook-standard"; const [mask, comb] = ["first-visitor-mask-standard", "red-moon-comb-standard"]; database.transaction(() => [notebook, mask, comb].forEach((editionId) => service.addCard(player.id, editionId))); // La fiche d'une commune lit les valeurs des pouvoirs dans l'état du joueur. const { powers, equipment } = service.expeditions.settings; assert.deepEqual(service.getState(player.id).equipmentValues, { ...powers, synergyBonus: equipment.synergyBonus }); const preview = (editionId) => { if (editionId) service.expeditions.equip(player.id, { editionId: rares[0], slot: 0, equipmentEditionId: editionId }); return service.expeditions.preview(player.id, soloBody(service.expeditions.getExpeditions(player.id), rares[0], { durationHours: 2 })).preview; }; const plain = preview(null); assert.equal(plain.expected.xpPct, 10); assert.ok(plain.expected.objects >= 0); assert.equal(plain.tierLootPct, service.expeditions.settings.loot.tierPct[["struggle", "success", "triumph"].indexOf(plain.tier)]); assert.equal(preview(notebook).expected.xpPct, 15); assert.equal(preview(mask).attunement.length, 1); // Aux étoiles faciles, la Chance de l'aube ne change rien. assert.equal(preview(comb).expected.xpPct, 10); service.expeditions.equip(player.id, { editionId: rares[0], slot: 0, equipmentEditionId: notebook }); const started = goSolo(service, player.id, soloBody(service.expeditions.getExpeditions(player.id), rares[0], { durationHours: 2 }), "study"); clock.now += 2 * HOUR; service.expeditions.claim(player.id, started.expedition.id); assert.equal(service.expeditions.progressOf(player.id, rares[0]).fieldXp, 15); }); test("commons that became power commons are taken off the cards that carried them", () => { const { service, player, open, rares, database } = expeditionService(); open(); database.transaction(() => ["astronomers-notebook-standard", "star-compass-standard"].forEach((editionId) => service.addCard(player.id, editionId))); service.expeditions.writeProgress(player.id, rares[0], { level: 6, fieldXp: 0 }); ["astronomers-notebook-standard", "star-compass-standard"].forEach((equipmentEditionId, slot) => service.expeditions.equip(player.id, { editionId: rares[0], slot, equipmentEditionId })); const version = MIGRATIONS.findIndex((migration) => typeof migration === "string" && migration.includes("DELETE FROM card_equipment WHERE equipment_edition_id IN")) + 1; assert.ok(version > 0); database.db.prepare("DELETE FROM schema_migrations WHERE version = ?").run(version); database.migrate(); assert.deepEqual(database.db.prepare("SELECT equipment_edition_id FROM card_equipment WHERE player_id = ?").all(player.id).map((row) => row.equipment_edition_id), ["star-compass-standard"]); }); 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[0], { durationHours: 6 }); assert.equal(service.expeditions.preview(player.id, body).preview.travelHours, 7.5); const started = goSolo(service, player.id, body, "longsight"); assert.equal(started.expedition.returnsAt - started.expedition.departsAt, 7.5 * HOUR); service.expeditions.cancel(service.upsertPlayer({ discordId: "expedition-admin", displayName: "Admin", isAdmin: true }).id, started.expedition.id); // Coup de folie : l'aperçu ne montre ni exigences ni résultat, mais la fourchette des exigences réelles. 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); assert.deepEqual(hidden.requirementRange, { min: 80, max: 130 }); // Au départ, les exigences réelles sont tirées (random() = 0 : 80 %), et révélées avec le résultat. const daring = goSolo(service, player.id, body, "mad-compass"); const settled = service.expeditions.getExpeditions(player.id); assert.ok(settled.expeditions.some((item) => item.id === daring.expedition.id)); const stored = JSON.parse(service.db.prepare("SELECT result_json FROM expeditions WHERE id = ?").get(daring.expedition.id).result_json); assert.equal(stored.requirementFactorPct, 80); // 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); }); test("a full progress reset refunds what each upgrade cost, converts field experience to Éclats and clears the old history", () => { const { service, player, open, rares, database } = expeditionService(); open(); const [card] = rares; const common = editionsOf("common")[0]; database.transaction(() => { service.addCard(player.id, card); service.addCard(player.id, card); service.expeditions.addItemsInTx(player.id, ["oblivion"]); }); database.db.prepare("UPDATE players SET eclats = 100 WHERE id = ?").run(player.id); // Niveau 1 payé en Éclats (10), niveau 2 par un doublon ; le premier plan est gratuit, le second coûte un Parchemin d'oubli. service.expeditions.upgradeCard(player.id, { editionId: card, method: "eclats" }); service.expeditions.upgradeCard(player.id, { editionId: card, method: "duplicate" }); service.expeditions.setCardPlan(player.id, { editionId: card, plan: "leader" }); service.expeditions.setCardPlan(player.id, { editionId: card, plan: "seeker" }); // Puis deux niveaux et demi d'expérience de terrain : niveaux 3 et 4 (30 + 40 Éclats) et la moitié du suivant (25). database.db.prepare("UPDATE card_progress SET level = 4, field_xp = 50 WHERE player_id = ? AND edition_id = ?").run(player.id, card); // À la Puissance de départ, seul le premier emplacement d'équipement reste ouvert. const equip = database.db.prepare("INSERT INTO card_equipment(player_id, edition_id, slot, equipment_edition_id, equipped_at) VALUES (?, ?, ?, ?, 0)"); equip.run(player.id, card, 0, common); equip.run(player.id, card, 1, editionsOf("common")[1]); const before = service.getState(player.id); const copies = service.quantityOf(player.id, card); // La simulation ne touche à rien. const [dryRun] = applyProgressReset(service); assert.deepEqual({ ...dryRun, playerId: undefined, name: undefined }, { playerId: undefined, name: undefined, eclats: 10, xpEclats: 95, duplicates: [{ editionId: card, count: 1 }], oblivion: 1, cards: 1, unequipped: 1 }); assert.equal(service.getState(player.id).cardProgress.find((item) => item.editionId === card).level, 4); applyProgressReset(service, { apply: true }); const after = service.getState(player.id); const progress = after.cardProgress.find((item) => item.editionId === card); assert.deepEqual([progress.level, progress.fieldXp, progress.plan.id], [0, 0, "collection"]); assert.equal(after.wallet.eclats, before.wallet.eclats + 105); assert.equal(service.quantityOf(player.id, card), copies + 1); assert.equal(after.items.oblivion, 1); assert.deepEqual(database.db.prepare("SELECT slot FROM card_equipment WHERE player_id = ?").all(player.id).map((row) => row.slot), [0]); assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM audit_log WHERE event_type IN ('card_upgraded', 'card_plan_changed')").get().count, 0); const reset = after.history.filter((entry) => entry.type === "card_progress_reset"); assert.deepEqual(reset.map((entry) => entry.details), [{ eclats: 10, xpEclats: 95, duplicates: 1, oblivion: 1, cards: 1, unequipped: 1 }]); // Rien à rembourser deux fois : un second passage ne trouve plus rien. assert.deepEqual(applyProgressReset(service), []); }); test("a progress reset gives back the duplicates of each awakening and never charges awakening levels as experience", () => { const settings = DEFAULT_EXPEDITION_SETTINGS; const audit = (details) => ({ player_id: "p", event_type: "card_upgraded", entity_id: "rare-a", details_json: JSON.stringify(details) }); // Rare au niveau 6 : niveaux 0 à 4 par l'expérience, le palier 5 → 6 par un Éveil de six doublons. const plans = planProgressReset({ progress: [{ player_id: "p", edition_id: "rare-a", level: 6, field_xp: 0 }], audits: [audit({ method: "awaken", awakened: 70, used: [{ editionId: "rare-b", count: 4 }, { editionId: "rare-c", count: 2 }], level: 6 })], rarityOf: () => "rare", settings }); const plan = plans.get("p"); assert.deepEqual([...plan.duplicates], [["rare-b", 4], ["rare-c", 2]]); assert.equal(plan.eclats, 0); assert.equal(plan.xpEclats, 10 + 20 + 30 + 40 + 50); }); test("a mythic edition follows the mythicProfile of its legendary, which only a legendary may carry", () => { const legendary = editionsOf("legendary")[0]; const cardId = published.editions.find((edition) => edition.id === legendary).cardId; const mythicProfile = { bravoure: 25, endurance: 25, fortune: 25, orientation: 25 }; const raw = JSON.parse(rawCatalogText); raw.cards.find((card) => card.id === cardId).expedition.mythicProfile = mythicProfile; const { service, player, open, database } = expeditionService({ catalog: prepareVersionedCatalog(raw) }); open(); const mythic = mythicEditionId(cardId, "spectral-prism-solar"); database.db.prepare("INSERT INTO mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by) VALUES (?, ?, 'spectral-prism-solar', 'active', 0, NULL)").run(mythic, cardId); service.reloadCatalog(); database.transaction(() => { service.addCard(player.id, mythic); service.addCard(player.id, legendary); }); const progress = service.getState(player.id).cardProgress; // Puissance 85 répartie à parts égales pour la mythique ; la légendaire garde le profil de sa carte. assert.deepEqual(progress.find((item) => item.editionId === mythic).baseStats, { bravoure: 22, endurance: 21, fortune: 21, orientation: 21 }); assert.notDeepEqual(progress.find((item) => item.editionId === legendary).plan.levelBase, { bravoure: 18, endurance: 17, fortune: 18, orientation: 17 }); const rare = published.cards.find((card) => rarityOf(card.id) === "rare" && card.kind !== "destination"); const invalid = JSON.parse(rawCatalogText); invalid.cards.find((card) => card.id === rare.id).expedition.mythicProfile = mythicProfile; assert.throws(() => prepareVersionedCatalog(invalid), /cannot have a mythicProfile/); });