sokko-g/services/cards/expedition-service.js
Shinuwa 30413de036 Rework the expedition screens: in-place return, illustrated bag and workshop, card sheet tabs and an engraving workshop
Expeditions
- The journey keeps the destination landscape still while a sky scenery
  (clouds, floating isles, shards, sparkles) drifts behind the cards.
- A returned expedition shows only what the player receives, in place and
  without a window; claiming it removes the card and confirms with a notice,
  and the page reloads by itself when an expedition comes back.
- The Guild Keeper slots are gone: group requirements scale with the players.
- Local development adds a 20-second test duration, a test player for groups
  and keeps the dev account stocked with every item.
- The Wind Rose has no daily limit and is used from the destinations step.
- The Guide Star opens a destination one level below the player's highest daily
  level, the Sky Chart one at that level; bonus destinations are badged with
  the item that opened them.

Bag and workshop
- The Watcher's bag is a grid of illustrated item cards, ordered from the
  destination items, with a short "Utiliser" button; the six missing item
  illustrations are added.
- The workshop opens in a window with illustrated commons, spare counts on the
  cards, cancel without spending anything, and shows the crafted card with its
  description and power.
- The engraving workshop picks a common first, then a tag from a chosen
  character card (in its tag colours) or from every tag, filtered by name and
  family; card lists filter by name, collection and stat.

Card sheet
- Two tabs: the card and its lore (default from the collection), and its
  improvement (default from the expeditions) with a summary of power, level,
  experience and stats.
- "Répartition des statistiques" offers Par défaut, Personnalisé and profiles,
  previews the change in the summary, and a Parchemin d'oubli resets it to
  Personnalisé so the next choice is free again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:36:01 +01:00

558 lines
36 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Rôle : applique les règles des Expéditions Sokko TCG avec la base (destinations du jour, aperçu, retour, réglages d'administration).
// Branché sur CardsService (`service.expeditions`) : il réutilise sa base, son horloge, son hasard, son audit et sa collection.
import { randomInt, randomUUID } from "node:crypto";
import { dailyDayKey, nextDailyAt, shiftDayKey } from "./daily.js";
import { drawCollectionCard } from "./game-rules.js";
import {
dangerCount, drawExpeditionDay, MAX_ACTIVE_EXPEDITIONS, editionExpeditionData, hasCondition, MAX_STARS, requirementsFor, resolveDayEntry,
HIDDEN_ITEMS, ITEM_IDS, levelCount, pickItems, starsForLevel, rollLoot, roundStochastic, TEST_DURATION, travelHours
} from "./expedition-rules.js";
import {
DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, validateExpeditionSettings
} from "./expedition-settings.js";
import { groupMethods } from "./expedition-group.js";
import { progressMethods } from "./expedition-progress.js";
import { equipmentMethods } from "./expedition-equipment.js";
import { alertMethods } from "./expedition-alerts.js";
import { itemMethods } from "./expedition-items.js";
// Taille du Journal des Expéditions : les dernières expéditions terminées.
const JOURNAL_SIZE = 20;
function fail(status, code, message) {
throw Object.assign(new Error(message), { status, code });
}
const parse = (value) => (value == null ? null : JSON.parse(value));
const round1 = (value) => Math.round(value * 10) / 10;
export class ExpeditionService {
// `alerts` : { available } si le bot Discord est configuré, et `publicOrigin` pour le lien des messages.
constructor(cards, destinations, alerts = {}) {
this.cards = cards;
this.alertsAvailable = Boolean(alerts.available);
this.publicOrigin = alerts.publicOrigin || null;
this.db = cards.db;
this.destinations = destinations;
this.destinationIds = destinations.map((destination) => destination.id);
}
now() {
return this.cards.now();
}
random(max) {
return this.cards.random ? this.cards.random(max) : randomInt(max);
}
// Réglages en vigueur : un champ stocké invalide reprend sa valeur par défaut, pour que le jeu reste jouable.
get settings() {
const row = this.db.prepare("SELECT settings_json FROM expedition_settings WHERE id = 1").get();
return mergeExpeditionSettings(parse(row?.settings_json) || {}, this.destinationIds, (path) => console.error(`Invalid stored expedition setting ${path}; using its default.`));
}
settingsUpdatedAt() {
return this.db.prepare("SELECT updated_at FROM expedition_settings WHERE id = 1").get()?.updated_at ?? 0;
}
updateSettings(adminId, settings) {
this.cards.requireAdmin(adminId);
const error = validateExpeditionSettings(settings, this.destinationIds);
if (error) fail(400, "EXPEDITION_SETTINGS_INVALID", error);
const previous = this.settings;
const next = mergeExpeditionSettings(settings, this.destinationIds);
const changes = diffExpeditionSettings(previous, next);
if (!changes.length) fail(409, "EXPEDITION_SETTINGS_UNCHANGED", "Ces réglages sont déjà en vigueur.");
this.cards.database.transaction(() => {
this.db.prepare("UPDATE expedition_settings SET settings_json = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(JSON.stringify(next), this.now(), adminId);
this.cards.audit(adminId, "expedition_settings_updated", "expeditions", { changes });
});
return { expeditionSettings: this.adminSettings() };
}
// Ce que l'administration affiche et modifie : réglages, valeurs par défaut, bornes et destinations (définies côté serveur).
adminSettings() {
return {
settings: this.settings,
defaults: mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, this.destinationIds),
schema: EXPEDITION_SETTINGS_SCHEMA,
destinations: this.destinations.map((destination) => ({ id: destination.id, name: destination.name, hidden: destination.hidden })),
updatedAt: this.settingsUpdatedAt()
};
}
// Destinations débloquées d'un joueur : les visibles dont il possède la carte de destination. Une destination qui n'a pas
// encore de carte dans le catalogue reste ouverte à tous.
unlockedDestinationIds(playerId) {
const cardOf = new Map(this.cards.catalog.cards.filter((card) => card.kind === "destination").map((card) => [card.destinationId, card.id]));
const cardOfEdition = new Map(this.cards.catalog.editions.map((edition) => [edition.id, edition.cardId]));
const owned = new Set(this.db.prepare("SELECT edition_id FROM collection_cards WHERE player_id = ?").all(playerId).map((row) => cardOfEdition.get(row.edition_id)));
return new Set(this.destinations
.filter((destination) => !destination.hidden && (!cardOf.has(destination.id) || owned.has(cardOf.get(destination.id))))
.map((destination) => destination.id));
}
// Destinations du jour d'un joueur, tirées parmi celles qu'il a débloquées (4 au plus, moins s'il en a moins), avec un niveau
// de chaque. Une carte de destination obtenue dans la journée complète le tirage, et une carte donnée retire sa destination.
// À appeler dans une transaction.
// Destinations que le tirage du jour peut proposer au joueur : débloquées, visibles, actives et de poids positif.
proposedDestinationIds(unlocked, settings) {
return this.destinations.filter((destination) => {
const setting = settings.destinations[destination.id] || { active: true, weight: 1 };
return !destination.hidden && unlocked.has(destination.id) && setting.active && setting.weight > 0;
}).map((destination) => destination.id);
}
// Destinations tirées par le joueur pendant les `day.avoidRepeatDays` jours précédents.
recentDestinationIds(playerId, day, settings) {
if (!settings.day.avoidRepeatDays) return [];
return this.db.prepare("SELECT draw_json FROM player_expedition_days WHERE player_id = ? AND day >= ? AND day < ?").all(playerId, shiftDayKey(day, -settings.day.avoidRepeatDays), day)
.flatMap((row) => JSON.parse(row.draw_json).map((entry) => entry.destinationId));
}
ensureDay(playerId, day, settings) {
// Les expéditions référencent le jour : sa ligne existe dès le premier tirage.
this.db.prepare("INSERT OR IGNORE INTO expedition_days(day, draw_json, created_at) VALUES (?, '[]', ?)").run(day, this.now());
const unlocked = this.unlockedDestinationIds(playerId);
const target = Math.min(settings.day.destinationsPerDay, this.proposedDestinationIds(unlocked, settings).length);
const read = () => this.db.prepare("SELECT draw_json FROM player_expedition_days WHERE player_id = ? AND day = ?").get(playerId, day);
const playable = (row) => JSON.parse(row.draw_json).filter((entry) => unlocked.has(entry.destinationId));
let stored = read();
if (!stored || playable(stored).length < target) {
const draw = drawExpeditionDay(this.destinations, settings, this.recentDestinationIds(playerId, day, settings), (max) => this.random(max), unlocked);
this.db.prepare(`INSERT INTO player_expedition_days(player_id, day, draw_json, created_at) VALUES (?, ?, ?, ?)
ON CONFLICT(player_id, day) DO UPDATE SET draw_json = excluded.draw_json`).run(playerId, day, JSON.stringify(draw), this.now());
stored = read();
}
// Une destination retirée du contenu après le tirage disparaît simplement de la liste du jour.
const levels = levelCount(settings);
return playable(stored).map((draw, index) => resolveDayEntry(this.destinations, draw, index % levels)).filter(Boolean);
}
// Destinations du jour du joueur, ses destinations bonus comprises.
today(settings, playerId) {
const day = dailyDayKey(this.now());
return { day, entries: this.cards.database.transaction(() => this.playerEntries(playerId, day, settings)) };
}
// Éditions occupées : celles d'un groupe en formation ou d'une expédition en route dont le butin n'a pas encore été récupéré.
busyEditions(playerId) {
return new Map(this.db.prepare(`SELECT s.edition_id, e.id, e.returns_at FROM expedition_slots s
JOIN expeditions e ON e.id = s.expedition_id
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = s.player_id
WHERE s.player_id = ? AND e.status IN ('forming', 'running') AND m.claimed_at IS NULL AND s.edition_id IS NOT NULL`).all(playerId)
.map((row) => [row.edition_id, { expeditionId: row.id, returnsAt: row.returns_at }]));
}
// Cartes du joueur jouables en expédition (rare ou mieux, révélées), avec leur Puissance et leurs stats.
eligibleCards(playerId, settings) {
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' LIMIT 1").get(playerId);
const busy = this.busyEditions(playerId);
const levels = this.levelsOf(playerId);
const equipment = this.equipmentOf(playerId);
const engravings = this.engravingsOf(playerId);
return this.cards.visibleCollection(playerId, pending?.id).map((entry) => {
const data = this.loadout(entry.editionId, levels.get(entry.editionId), equipment.get(entry.editionId), settings, engravings);
if (!data) return null;
const busyEntry = busy.get(entry.editionId);
return { ...data, plan: levels.get(entry.editionId)?.plan ?? null, busy: Boolean(busyEntry), busyUntil: busyEntry?.returnsAt ?? null };
}).filter(Boolean);
}
// Expéditions du joueur ouvertes ou en route (butin pas encore récupéré), seul ou en groupe.
activeCount(playerId) {
return this.db.prepare(`SELECT COUNT(*) AS count FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND e.status IN ('forming', 'running') AND m.claimed_at IS NULL`).get(playerId).count;
}
// Destination du jour vue par le joueur : ses étoiles (celles de son niveau, seul ou en groupe), son thème (Affinité), sa condition
// et ses dangers, et ses exigences chiffrées pour une carte seule (`requirements`) ; en groupe, elles sont multipliées par le
// nombre de joueurs.
destinationView({ destination, entry, level = 0, bonusSlot = null }, settings) {
const star = starsForLevel(level, settings);
return {
id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, image: destination.image ?? null, stats: destination.stats, bonusSlot,
specialty: destination.specialty ?? null, rewardCollectionId: destination.rewardCollectionId ?? null, themeTags: destination.themeTags ?? [],
level, star,
condition: hasCondition(star) ? entry.condition : null,
dangers: entry.dangers.slice(0, dangerCount(star)),
requirements: requirementsFor(destination, star, 1, settings)
};
}
// Destination et durée choisies pour le jour. Les étoiles viennent du niveau de la destination : la difficulté envoyée par un ancien
// client est ignorée. En local, la durée de test (`testTrip`) prend les règles de la plus courte.
validateChoice(body, settings, today) {
const { day, entries } = today;
if (body?.day !== day) fail(409, "EXPEDITION_DAY_EXPIRED", "Les destinations ont changé : rechargez les Expéditions du jour.");
const resolved = entries.find((item) => item.destination.id === body.destinationId);
if (!resolved) fail(400, "EXPEDITION_INVALID", "Cette destination n’est pas proposée aujourd’hui.");
const stars = starsForLevel(resolved.level ?? 0, settings);
if (body.durationHours === TEST_DURATION && this.cards.devPerks) return { day, resolved, stars, durationIndex: 0, hours: settings.durations.hours[0], testTrip: true };
const durationIndex = settings.durations.hours.indexOf(body.durationHours);
if (durationIndex < 0) fail(400, "EXPEDITION_INVALID", "Durée invalide.");
return { day, resolved, stars, durationIndex, hours: settings.durations.hours[durationIndex] };
}
// Carte jouable du joueur : rare ou mieux, révélée et possédée (occupée ou non : l'appelant décide).
ownedCard(playerId, editionId, settings, owned = null) {
if (typeof editionId !== "string" || !editionExpeditionData(this.cards.catalog, editionId, 0, settings)) {
fail(400, "EXPEDITION_CARD_INVALID", "Seules les cartes rares, épiques, légendaires et mythiques partent en expédition.");
}
const card = (owned || new Map(this.eligibleCards(playerId, settings).map((item) => [item.editionId, item]))).get(editionId);
if (!card) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte.");
return card;
}
// Butin tiré au départ : arrondi au hasard, cartes à l'unité (de la collection de la destination, sinon de ses Carnets des
// Veilleurs), objets (la partie cachée demande de l'Orientation), puis ce qu'ajoutent les pouvoirs (Carte au trésor, Filet).
// Cartes de destination : avec `playerId`, une chance d'en rapporter une qu'il n'a pas, et, dans un groupe (`group`), une forte
// chance d'obtenir celle de la destination s'il ne l'a pas.
rollReward(expected, settings, { orientationPerSlot = 0, powers = [], destination = null, playerId = null, group = false } = {}) {
const random = (max) => this.random(max);
const loot = rollLoot(expected, settings, random);
const cards = [];
for (let index = 0; index < loot.cards; index += 1) {
const editionId = this.drawRewardCard(playerId, destination, settings, random);
if (editionId) cards.push(editionId);
}
const items = pickItems(roundStochastic(expected.objects, random), { orientationPerSlot, excluded: this.excludedItems() }, settings, random);
if (powers.includes("treasureMap")) {
const notHidden = ITEM_IDS.filter((id) => !HIDDEN_ITEMS.includes(id));
items.push(...pickItems(1, { orientationPerSlot: Infinity, excluded: [...notHidden, ...this.excludedItems()] }, settings, random));
}
const anyLogbook = this.logbookEditions();
if (powers.includes("starNet") && anyLogbook.length && random(100) < settings.powers.starNetCardPct) cards.push(this.pickLogbookEdition(anyLogbook, random));
if (playerId) cards.push(...this.rollDestinationCards(playerId, destination, settings, { group, random }));
return { eclats: loot.eclats, stardust: loot.stardust, packs: [], items, cards };
}
// Collection rattachée à une destination, d'où une expédition peut tirer ses cartes pour ce joueur : ouverte, ou fermée si le
// joueur possède la carte de la destination (rattrapage d'une collection manquée : un autre joueur l'aide à obtenir la carte
// de destination en groupe, puis il y retourne). Null sinon, ou sans taux de tirage.
linkedCollectionFor(playerId, destination) {
const collection = destination?.rewardCollectionId && this.cards.catalog.collections.find((item) => item.id === destination.rewardCollectionId);
if (!collection?.dropWeights) return null;
if (collection.active) return collection;
const own = playerId && this.destinationCardEditions().find((edition) => this.cards.index.cards.get(edition.cardId).destinationId === destination.id);
return own && this.ownedCardIds(playerId).has(own.cardId) ? collection : null;
}
// Carte à l'unité. Une destination rattachée à une collection (ouverte, ou fermée pour qui possède la carte de la destination)
// la tire dans cette collection avec la probabilité `rewardCards.linkedCollectionPct` (taux de rareté de la collection, cartes
// que le joueur n'a pas favorisées), sinon dans ses Carnets des Veilleurs ; une destination sans collection, toujours dans ses
// Carnets. Null si aucune carte n'est disponible.
drawRewardCard(playerId, destination, settings, random) {
const linked = this.linkedCollectionFor(playerId, destination);
const logbooks = this.logbookEditions(destination?.logbookCards || []);
if (!linked || (logbooks.length && random(100) >= settings.rewardCards.linkedCollectionPct)) {
return logbooks.length ? this.pickLogbookEdition(logbooks, random) : null;
}
const owned = new Set(playerId ? this.db.prepare("SELECT edition_id FROM collection_cards WHERE player_id = ?").all(playerId).map((row) => row.edition_id) : []);
// Une carte de destination déjà possédée n'est jamais tirée : elle est unique.
const weightOf = (edition) => (!owned.has(edition.id) ? settings.rewardCards.missingWeightPct : this.cards.isDestinationEdition(edition.id) ? 0 : 100);
return drawCollectionCard(this.cards.catalog, linked.id, random, { weightOf, requireActive: false });
}
// Éditions des cartes de destination illustrées ; avec `expeditionOnly`, seulement celles à trouver en expédition (collections des
// Expéditions, hors trophées des destinations cachées, qui ne s'obtiennent qu'en y allant).
destinationCardEditions({ expeditionOnly = false } = {}) {
const expeditionCollections = new Set(this.cards.catalog.collections.filter((collection) => collection.packCategory === "expedition").map((collection) => collection.id));
const hidden = new Set(this.destinations.filter((destination) => destination.hidden).map((destination) => destination.id));
return this.cards.catalog.editions.filter((edition) => {
const card = this.cards.index.cards.get(edition.cardId);
return card?.kind === "destination" && card.image && !edition.promotional
&& (!expeditionOnly || (expeditionCollections.has(card.collectionId) && !hidden.has(card.destinationId)));
});
}
ownedCardIds(playerId) {
return new Set(this.db.prepare("SELECT edition_id FROM collection_cards WHERE player_id = ?").all(playerId).map((row) => this.cards.index.editions.get(row.edition_id)?.cardId));
}
rollDestinationCards(playerId, destination, settings, { group, random }) {
const owned = this.ownedCardIds(playerId);
const cards = [];
const own = this.destinationCardEditions().find((edition) => this.cards.index.cards.get(edition.cardId).destinationId === destination?.id);
// Trophée : la carte d'une destination cachée revient à coup sûr à qui y va sans l'avoir.
const hidden = this.destinations.find((item) => item.id === destination?.id)?.hidden;
if (own && !owned.has(own.cardId) && (hidden || (group && random(100) < settings.destinationCards.groupJoinPct))) cards.push(own.id);
const missing = this.destinationCardEditions({ expeditionOnly: true }).filter((edition) => !owned.has(edition.cardId) && !cards.includes(edition.id));
if (missing.length && random(100) < settings.destinationCards.dropPct) cards.push(missing[random(missing.length)].id);
return cards;
}
// Carte de destination de départ : offerte une fois, au hasard parmi celles des Expéditions, à un joueur qui n'en a aucune.
// À appeler dans une transaction. La page la présente une fois (`starterCard`), jusqu'à `markStarterSeen`.
grantStarterDestination(playerId) {
const editions = this.destinationCardEditions({ expeditionOnly: true });
if (!editions.length) return;
if (this.db.prepare("SELECT 1 FROM audit_log WHERE player_id = ? AND event_type = 'destination_starter' LIMIT 1").get(playerId)) return;
const owned = this.ownedCardIds(playerId);
if (this.destinationCardEditions().some((edition) => owned.has(edition.cardId))) return;
const edition = editions[this.random(editions.length)];
this.cards.addCard(playerId, edition.id);
this.cards.audit(playerId, "destination_starter", edition.cardId, { editionId: edition.id });
}
// Éditions standard des cartes des Carnets (rare ou mieux) déjà illustrées ; sans `cardIds`, toutes celles des collections des Expéditions.
logbookEditions(cardIds = null) {
const expeditionCollections = new Set(this.cards.catalog.collections.filter((collection) => collection.packCategory === "expedition").map((collection) => collection.id));
return this.cards.catalog.editions.filter((edition) => {
const card = this.cards.index.cards.get(edition.cardId);
return card?.image && card.kind !== "destination" && !edition.promotional && edition.rarity !== "mythic" && edition.rarity !== "common" && expeditionCollections.has(card.collectionId) && (!cardIds || cardIds.includes(card.id));
});
}
// Tirage pondéré par les poids recommandés des raretés : une légendaire reste rare.
pickLogbookEdition(editions, random) {
const weight = (edition) => this.cards.catalog.rarities.find((rarity) => rarity.id === edition.rarity)?.recommendedWeight || 1;
let cursor = random(editions.reduce((sum, edition) => sum + weight(edition), 0));
return (editions.find((edition) => (cursor -= weight(edition)) < 0) || editions.at(-1)).id;
}
// Objets qui ne peuvent pas encore être rapportés : le plan d'atelier attend des communes de pouvoir illustrées.
excludedItems() {
return this.atelierAvailable?.() ? [] : ["plan"];
}
// `synergy` : Affinité, Résonances et cohésion qui ont donné le bonus de score.
resultView(evaluation, extra = {}, synergy = null) {
return {
...extra,
affinity: synergy?.affinity ?? null,
powers: extra.powers ?? [],
resonances: synergy?.resonances ?? [],
scorePct: round1(evaluation.scorePct),
synergyPct: evaluation.synergyPct,
tier: evaluation.tier,
limitedByStars: evaluation.limitedByStars,
conditionMet: evaluation.conditionMet,
durationFactor: evaluation.durationFactor,
stats: Object.fromEntries(Object.entries(evaluation.stats).map(([stat, value]) => [stat, round1(value)])),
requirements: evaluation.perRequirement.map((item) => ({ stat: item.stat, main: item.main, value: item.value, team: round1(item.team), ratioPct: round1(item.ratioPct) })),
dangers: evaluation.dangers.map((danger) => ({ id: danger.id, label: danger.label, stat: danger.stat, unlessTags: danger.unlessTags, countered: danger.countered }))
};
}
expectedView(expected) {
return { eclats: round1(expected.eclats), stardust: round1(expected.stardust), cardChancePct: round1(Math.min(1, expected.cards) * 100), fortuneBonusPct: round1(expected.fortuneBonusPct) };
}
// Aperçu exact de l'expédition que le joueur ouvrirait, si elle partait seule.
preview(playerId, body) {
const settings = this.settings;
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
const plan = this.prepareGroup(playerId, body, settings, this.today(settings, playerId));
// La durée de test ne montre pas de trajet en heures.
const travel = plan.setup.testTrip ? null : travelHours(plan.hours, plan.powers, settings);
// Coup de folie : les exigences réelles seront tirées au départ dans cette fourchette ; pas de prévision avant le retour.
if (plan.powers.includes("madCompass")) {
const requirementRange = { min: settings.powers.madCompassMinPct, max: settings.powers.madCompassMaxPct };
return { preview: { hiddenRequirements: true, requirementRange, powers: plan.powers, travelHours: travel, expected: this.expectedView(plan.expected) } };
}
return { preview: { ...this.resultView(plan.evaluation, { ...(plan.cohesion != null ? { cohesionPct: plan.cohesion } : {}), powers: plan.powers }, plan.synergy), travelHours: travel, expected: this.expectedView(plan.expected) } };
}
// Vue d'une expédition pour un participant : le résultat et le butin n'apparaissent qu'au retour.
expeditionView(expeditionId, playerId) {
const row = this.db.prepare(`SELECT e.*, m.reward_json, m.claimed_at FROM expeditions e
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = ? WHERE e.id = ?`).get(playerId, expeditionId);
if (!row) return null;
const now = this.now();
const returned = row.status === "completed" || (row.status === "running" && row.returns_at <= now);
const status = row.status === "running" ? (returned ? "returned" : "running") : row.status;
const setup = JSON.parse(row.setup_json);
const slots = this.db.prepare(`SELECT s.position, s.player_id, s.edition_id, s.card_id, s.level, s.stats_json, p.display_name FROM expedition_slots s
LEFT JOIN players p ON p.id = s.player_id WHERE s.expedition_id = ? AND s.player_id IS NOT NULL ORDER BY s.position`).all(row.id)
.map((slot) => ({
position: slot.position, own: slot.player_id === playerId, playerName: slot.display_name ?? null,
editionId: slot.edition_id, cardId: slot.card_id, level: slot.level, stats: JSON.parse(slot.stats_json)
}));
return {
id: row.id, mode: row.mode, status, day: row.day, destination: setup.destination, condition: setup.condition, stars: row.difficulty, hours: setup.hours,
departsAt: row.departs_at, returnsAt: row.returns_at, claimedAt: row.claimed_at, slots,
result: returned ? parse(row.result_json) : null,
reward: returned ? parse(row.reward_json) : null
};
}
// Expéditions à suivre : en route, ou revenues sans butin récupéré.
playerExpeditionIds(playerId) {
return this.db.prepare(`SELECT e.id FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND e.status = 'running' AND m.claimed_at IS NULL ORDER BY e.created_at DESC LIMIT 10`).all(playerId).map((row) => row.id);
}
// Journal : les dernières expéditions terminées du joueur (butin récupéré) ou annulées par la Guilde, des plus récentes aux plus
// anciennes.
journalIds(playerId, limit = JOURNAL_SIZE) {
return this.db.prepare(`SELECT e.id FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND (m.claimed_at IS NOT NULL OR (e.status = 'cancelled' AND e.departs_at IS NOT NULL))
ORDER BY COALESCE(m.claimed_at, e.completed_at) DESC LIMIT ?`).all(playerId, limit).map((row) => row.id);
}
// Carte de destination offerte que le joueur n'a pas encore vue présentée, ou null.
starterCard(playerId) {
const rows = this.db.prepare("SELECT event_type, details_json FROM audit_log WHERE player_id = ? AND event_type IN ('destination_starter', 'destination_starter_seen')").all(playerId);
const starter = rows.find((row) => row.event_type === "destination_starter");
if (!starter || rows.some((row) => row.event_type === "destination_starter_seen")) return null;
return JSON.parse(starter.details_json).editionId ?? null;
}
markStarterSeen(playerId) {
this.cards.database.transaction(() => {
const editionId = this.starterCard(playerId);
if (editionId) this.cards.audit(playerId, "destination_starter_seen", editionId, {});
});
return { expeditions: this.getExpeditions(playerId) };
}
getExpeditions(playerId) {
const settings = this.settings;
this.settleForming();
const now = this.now();
const base = {
enabled: settings.enabled,
nextDayAt: nextDailyAt(now),
durations: settings.durations.hours,
stars: { min: settings.stars.min, max: settings.stars.max, limit: MAX_STARS },
progression: { stardustPerEclat: settings.progression.stardustPerEclat },
specialty: { ...settings.specialty },
// Effet de chaque palier sur le butin, pour l'aperçu.
tierLootPct: { struggle: settings.loot.tierPct[0], success: settings.loot.tierPct[1], triumph: settings.loot.tierPct[2] },
// Valeurs des pouvoirs des communes, pour en détailler les effets exacts au survol.
powers: { ...settings.powers },
group: { slots: settings.group.slots, limit: MAX_ACTIVE_EXPEDITIONS, active: this.activeCount(playerId), recruitHours: settings.group.recruitHours, lootPct: settings.group.lootPct },
expeditions: this.playerExpeditionIds(playerId).map((id) => this.expeditionView(id, playerId)),
journal: this.journalIds(playerId).map((id) => this.expeditionView(id, playerId)),
groups: this.boardView(playerId, settings),
items: this.itemsOf(playerId),
fragmentsForMap: settings.items.fragmentsForMap,
atelierAvailable: this.atelierAvailable(),
// Serveur Vite local : un bouton ajoute un joueur de test à une expédition ouverte au groupe.
testPlayers: Boolean(this.cards.devPerks),
testDuration: this.cards.devPerks ? TEST_DURATION : null
};
// Fermées : le joueur peut encore récupérer le butin de ses expéditions, mais aucune destination n'est tirée.
if (!settings.enabled) return { ...base, day: dailyDayKey(now), destinations: [], cards: [] };
this.cards.database.transaction(() => this.grantStarterDestination(playerId));
const { day, entries } = this.today(settings, playerId);
// Progression : destinations débloquées par les cartes de destination, sur toutes les destinations visibles.
const unlocked = { count: this.unlockedDestinationIds(playerId).size, total: this.destinations.filter((destination) => !destination.hidden).length };
return { ...base, day, unlocked, starterCard: this.starterCard(playerId), destinations: entries.map((entry) => this.destinationView(entry, settings)), cards: this.eligibleCards(playerId, settings) };
}
claim(playerId, expeditionId) {
this.cards.database.transaction(() => {
const row = this.db.prepare(`SELECT e.*, m.reward_json, m.claimed_at FROM expeditions e
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = ? WHERE e.id = ?`).get(playerId, expeditionId);
if (!row || row.status === "cancelled") fail(404, "EXPEDITION_NOT_FOUND", "Cette expédition n’existe pas.");
// Déjà récupéré : on renvoie le même rapport.
if (row.claimed_at != null) return;
const now = this.now();
if (row.status !== "running" || row.returns_at > now) fail(409, "EXPEDITION_NOT_RETURNED", "Cette expédition n’est pas encore rentrée.");
const reward = JSON.parse(row.reward_json);
const setup = JSON.parse(row.setup_json);
const result = JSON.parse(row.result_json);
this.db.prepare("UPDATE players SET eclats = eclats + ?, stardust = stardust + ? WHERE id = ?").run(reward.eclats, reward.stardust, playerId);
const insertPack = this.db.prepare("INSERT INTO gift_packs(id, player_id, source, expedition_id, collection_id, options_json, created_at) VALUES (?, ?, 'expedition', ?, ?, ?, ?)");
for (const collectionId of reward.packs) insertPack.run(randomUUID(), playerId, row.id, collectionId, JSON.stringify({ rarityWeights: null, guarantee: null }), now);
this.addItemsInTx(playerId, reward.items || []);
for (const editionId of reward.cards || []) if (this.cards.index.editions.has(editionId)) this.cards.addCard(playerId, editionId);
this.db.prepare("UPDATE expedition_members SET claimed_at = ? WHERE expedition_id = ? AND player_id = ?").run(now, row.id, playerId);
const waiting = this.db.prepare("SELECT COUNT(*) AS count FROM expedition_members WHERE expedition_id = ? AND claimed_at IS NULL").get(row.id).count;
if (!waiting) this.db.prepare("UPDATE expeditions SET status = 'completed', completed_at = ? WHERE id = ?").run(now, row.id);
const editionIds = this.db.prepare("SELECT edition_id FROM expedition_slots WHERE expedition_id = ? AND player_id = ? ORDER BY position").all(row.id, playerId).map((slot) => slot.edition_id);
this.gainFieldXpInTx(playerId, editionIds, this.settings);
this.cards.audit(playerId, "expedition_completed", row.id, {
destinationId: setup.destination.id, destinationName: setup.destination.name, difficulty: row.difficulty, hours: setup.hours,
mode: row.mode, players: result.players ?? 1, tier: result.tier, scorePct: result.scorePct, eclats: reward.eclats, stardust: reward.stardust, packs: reward.packs.length, items: reward.items || [], cards: reward.cards || [], editionIds
});
});
return { expedition: this.expeditionView(expeditionId, playerId), expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
}
// Annulation par un administrateur : les cartes sont libérées, sans butin.
cancel(adminId, expeditionId) {
this.cards.requireAdmin(adminId);
this.cards.database.transaction(() => {
const row = this.db.prepare("SELECT * FROM expeditions WHERE id = ?").get(expeditionId);
if (!row) fail(404, "EXPEDITION_NOT_FOUND", "Cette expédition n’existe pas.");
if (!["forming", "running"].includes(row.status)) fail(409, "EXPEDITION_FINISHED", "Cette expédition est déjà terminée.");
this.cancelRow(row);
this.cards.audit(adminId, "expedition_cancelled", row.id, { destinationId: row.destination_id, mode: row.mode, creatorId: row.creator_id });
});
return { expeditionsToday: this.adminSummary() };
}
// Annule une expédition et prévient ceux qui n'avaient pas encore récupéré leur butin.
cancelRow(row, { notify = true } = {}) {
this.db.prepare("UPDATE expeditions SET status = 'cancelled', completed_at = ? WHERE id = ?").run(this.now(), row.id);
if (!notify) return;
const setup = JSON.parse(row.setup_json);
for (const member of this.db.prepare("SELECT player_id FROM expedition_members WHERE expedition_id = ? AND claimed_at IS NULL").all(row.id)) {
this.cards.audit(member.player_id, "expedition_cancelled_by_guild", row.id, { destinationId: setup.destination.id, destinationName: setup.destination.name });
}
}
// Suppression du compte : ses expéditions solo sont annulées ; en groupe, il quitte un groupe en formation (le dissout s'il l'a ouvert)
// et renonce à son butin d'une expédition en route, que les autres gardent.
forgetPlayer(playerId) {
const rows = this.db.prepare(`SELECT e.* FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND e.status IN ('forming', 'running') AND m.claimed_at IS NULL`).all(playerId);
for (const row of rows) {
if (row.mode === "solo") this.cancelRow(row, { notify: false });
else if (row.status === "forming") this.leaveGroupInTx(row, playerId);
else this.forfeitInTx(row, playerId);
}
}
// Résumé pour l'état du joueur (tuile de la Guilde, fiche de carte), sans tirer les destinations du jour.
summary(playerId) {
const settings = this.settings;
this.settleForming();
const now = this.now();
const active = this.db.prepare(`SELECT e.returns_at, e.mode FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND e.status = 'running' AND m.claimed_at IS NULL`).all(playerId);
const running = active.filter((row) => row.returns_at > now);
const launchedToday = Boolean(this.db.prepare("SELECT 1 FROM expeditions WHERE creator_id = ? AND day = ? AND status != 'cancelled' LIMIT 1").get(playerId, dailyDayKey(now)));
const busy = this.busyEditions(playerId);
const eligibleCards = new Set(this.cards.collectionOf(playerId)
.map((entry) => editionExpeditionData(this.cards.catalog, entry.editionId, 0, settings)?.cardId).filter(Boolean));
return {
enabled: settings.enabled,
running: running.length,
returned: active.length - running.length,
nextReturnAt: running.length ? Math.min(...running.map((row) => row.returns_at)) : null,
launchedToday,
eligible: eligibleCards.size,
forming: this.activeCount(playerId) - active.length,
joinableGroups: settings.enabled ? this.joinableGroupCount(playerId, settings, busy) : 0,
busyEditions: [...busy].map(([editionId, entry]) => ({ editionId, returnsAt: entry.returnsAt }))
};
}
adminSummary() {
this.settleForming();
const now = this.now();
const day = dailyDayKey(now);
return {
day,
launches: this.db.prepare("SELECT COUNT(*) AS count FROM expeditions WHERE day = ? AND status != 'forming'").get(day).count,
running: this.db.prepare("SELECT COUNT(*) AS count FROM expeditions WHERE status = 'running' AND returns_at > ?").get(now).count,
returnedUnclaimed: this.db.prepare(`SELECT COUNT(*) AS count FROM expedition_members m JOIN expeditions e ON e.id = m.expedition_id
WHERE e.status = 'running' AND e.returns_at <= ? AND m.claimed_at IS NULL`).get(now).count,
forming: this.db.prepare("SELECT COUNT(*) AS count FROM expeditions WHERE status = 'forming'").get().count,
runningList: this.db.prepare(`SELECT e.id, e.mode, e.status, e.destination_id, e.difficulty, e.returns_at, p.display_name FROM expeditions e JOIN players p ON p.id = e.creator_id
WHERE e.status IN ('forming', 'running') ORDER BY e.status, e.returns_at LIMIT 20`).all()
.map((row) => ({ id: row.id, mode: row.mode, status: row.status, destinationId: row.destination_id, stars: row.difficulty, returnsAt: row.returns_at, creatorName: row.display_name }))
};
}
}
// Expéditions de groupe : tableau de la Guilde, inscription, départ, garde-fou d'inscription (expedition-group.js).
// Améliorations : niveaux, expérience de terrain et pont depuis la poussière (expedition-progress.js).
// Équipements (expedition-equipment.js).
// Alertes Discord (expedition-alerts.js).
// Objets (expedition-items.js).
Object.assign(ExpeditionService.prototype, groupMethods, progressMethods, equipmentMethods, alertMethods, itemMethods);