sokko-g/services/cards/expedition-service.js
Shinuwa 21827a252b Add the Carnets des Veilleurs, the expedition-only Sokko TCG collection with power commons
- A new watchers-logbooks collection of category expedition never comes from packs, the shop or codes, and administrators cannot open it as a pack.
- Its six commons carry powers instead of stats (Longue-vue, Provisions, Carte au trésor, Talisman, Boussole folle, Filet à étoiles filantes); a card holds one power and each counts once per team.
- Powers change travel time, loot, score or tier, hide requirements, or catch a logbook card; each destination lists the logbook cards it can bring back.
- A workshop turns a plan and three duplicate commons into a power common.
- The fifteen cards ship without images with ready ChatGPT prompts; a card only drops or gets crafted once illustrated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:40:51 +01:00

499 lines
33 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, départ solo, 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 {
dangerCount, drawExpeditionDay, editionExpeditionData, evaluateTeam, expectedLoot, hasCondition, MAX_STARS, requirementsFor, resolveDayEntry,
HIDDEN_ITEMS, ITEM_IDS, pickItems, ROLE_BY_STAT, rollLoot, roundStochastic, soloRoles, STAT_BY_ROLE, teamPowers, teamSynergy, 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";
const HOUR_MS = 3_600_000;
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 du jour, tirées au premier appel du jour de Paris. À appeler dans une transaction.
ensureDay(day, settings) {
const stored = () => this.db.prepare("SELECT draw_json FROM expedition_days WHERE day = ?").get(day);
if (!stored()) {
const recentDays = settings.day.avoidRepeatDays ? this.db.prepare("SELECT draw_json FROM expedition_days WHERE day >= ? AND day < ?").all(shiftDayKey(day, -settings.day.avoidRepeatDays), day) : [];
const recent = recentDays.flatMap((row) => JSON.parse(row.draw_json).map((entry) => entry.destinationId));
const draw = drawExpeditionDay(this.destinations, settings, recent, (max) => this.random(max));
if (!draw.length) fail(409, "EXPEDITIONS_UNAVAILABLE", "Aucune destination n’est ouverte aujourd’hui.");
this.db.prepare("INSERT INTO expedition_days(day, draw_json, created_at) VALUES (?, ?, ?)").run(day, JSON.stringify(draw), this.now());
}
// Une destination retirée du contenu après le tirage disparaît simplement de la liste du jour.
return JSON.parse(stored().draw_json).map((draw) => resolveDayEntry(this.destinations, draw)).filter(Boolean);
}
// Destinations du jour ; avec `playerId`, ses destinations bonus en plus.
today(settings, playerId = null) {
const day = dailyDayKey(this.now());
return { day, entries: this.cards.database.transaction(() => (playerId ? this.playerEntries(playerId, day, settings) : this.ensureDay(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)?.level ?? 0, equipment.get(entry.editionId), settings, engravings);
if (!data) return null;
const busyEntry = busy.get(entry.editionId);
return { ...data, busy: Boolean(busyEntry), busyUntil: busyEntry?.returnsAt ?? null };
}).filter(Boolean);
}
activeCount(playerId, mode) {
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.mode = ? AND e.status IN ('forming', 'running') AND m.claimed_at IS NULL`).get(playerId, mode).count;
}
// Exigences, condition et dangers d'une destination pour chaque étoile d'une plage, avec les rôles des places.
starOptions(destination, entry, roles, minStars, maxStars, settings) {
const stars = {};
for (let star = minStars; star <= maxStars; star += 1) {
stars[star] = { requirements: requirementsFor(destination, star, roles, settings), condition: hasCondition(star) ? entry.condition : null, dangers: entry.dangers.slice(0, dangerCount(star)) };
}
return stars;
}
// Destination du jour vue par le joueur : rôles et exigences chiffrées du solo, puis du groupe complet (un rôle par place).
destinationView({ destination, entry, bonusSlot = null }, settings) {
const roles = soloRoles(destination, settings.solo.cards);
const groupRoles = destination.stats.slice(0, settings.group.slots);
return {
id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, stats: destination.stats, bonusSlot,
roles, stars: this.starOptions(destination, entry, roles, settings.solo.minStars, settings.solo.maxStars, settings),
groupRoles, groupStars: this.starOptions(destination, entry, groupRoles, settings.group.minStars, settings.group.maxStars, settings)
};
}
// Destination, étoiles et durée choisies pour le jour : communes au solo et au groupe.
validateChoice(body, settings, today, { minStars, maxStars }) {
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 = body.difficulty;
if (!Number.isInteger(stars) || stars < minStars || stars > maxStars) fail(400, "EXPEDITION_INVALID", "Difficulté invalide.");
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, collection de chaque paquet, objets (la partie cachée demande de l'Orientation),
// cartes des Carnets de la destination, puis ce qu'ajoutent les pouvoirs (Carte au trésor, Filet à étoiles filantes).
rollReward(expected, settings, { orientationPerSlot = 0, powers = [], destination = null } = {}) {
const random = (max) => this.random(max);
const loot = rollLoot(expected, settings, random);
const packs = [];
for (let index = 0; index < loot.packs; index += 1) {
const collectionId = this.packCollection();
if (collectionId) packs.push(collectionId);
}
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 cards = [];
const fromDestination = this.logbookEditions(destination?.logbookCards || []);
for (let index = roundStochastic(expected.cards, random); index > 0 && fromDestination.length; index -= 1) cards.push(this.pickLogbookEdition(fromDestination, random));
const anyLogbook = this.logbookEditions();
if (powers.includes("starNet") && anyLogbook.length && random(100) < settings.powers.starNetCardPct) cards.push(this.pickLogbookEdition(anyLogbook, random));
return { eclats: loot.eclats, stardust: loot.stardust, packs, items, cards };
}
// É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 && !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"];
}
// Valide une équipe solo et calcule son résultat (sans écriture) : base commune de l'aperçu et du départ.
// `today` : { day, entries }, les destinations du jour, lues par l'appelant (dans sa transaction pour un départ).
prepareSolo(playerId, body, settings, today) {
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
const { day, resolved, stars, durationIndex, hours } = this.validateChoice(body, settings, today, settings.solo);
const editionIds = body.slots;
if (!Array.isArray(editionIds) || editionIds.length !== settings.solo.cards || editionIds.some((id) => typeof id !== "string")) {
fail(400, "EXPEDITION_CARD_INVALID", `Choisissez ${settings.solo.cards} cartes.`);
}
const owned = new Map(this.eligibleCards(playerId, settings).map((card) => [card.editionId, card]));
const roles = soloRoles(resolved.destination, settings.solo.cards);
const slots = editionIds.map((editionId, position) => ({ ...this.ownedCard(playerId, editionId, settings, owned), role: roles[position], position }));
if (new Set(slots.map((slot) => slot.cardId)).size !== slots.length) fail(400, "EXPEDITION_CARD_INVALID", "Une même carte ne peut occuper qu’une place.");
const synergy = teamSynergy({ destination: resolved.destination, slots }, settings);
const powers = teamPowers(slots);
const evaluation = evaluateTeam({ destination: resolved.destination, entry: resolved.entry, stars, durationIndex, slots, synergyPct: synergy.totalPct, powers }, settings);
const expected = expectedLoot({ hours, stars, tier: evaluation.tier, fortune: evaluation.stats.fortune, slotCount: slots.length, bonusSlot: resolved.bonusSlot ?? null, powers }, settings);
return { day, resolved, stars, durationIndex, hours, slots, synergy, powers, evaluation, expected };
}
// `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), packChancePct: round1(Math.min(1, expected.packs) * 100), fortuneBonusPct: round1(expected.fortuneBonusPct) };
}
// Aperçu exact d'une équipe solo, ou d'un groupe que le joueur ouvrirait (les autres places tenues par le Veilleur).
preview(playerId, body) {
const settings = this.settings;
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
const today = this.today(settings, playerId);
const plan = body?.mode === "group" ? this.prepareGroup(playerId, body, settings, today) : this.prepareSolo(playerId, body, settings, today);
const travel = travelHours(plan.hours, plan.powers, settings);
// Boussole folle : les exigences et le résultat restent inconnus jusqu'au retour.
if (plan.powers.includes("madCompass")) return { preview: { hiddenRequirements: true, 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) } };
}
// Collection d'un paquet rapporté : une collection permanente ouverte, au hasard.
packCollection() {
const collections = this.cards.catalog.collections.filter((collection) => collection.active && collection.packCategory === "permanent" && collection.dropWeights);
return collections.length ? collections[this.random(collections.length)].id : null;
}
startSolo(playerId, body, requestKey) {
if (!requestKey || requestKey.length > 100) fail(400, "IDEMPOTENCY_REQUIRED", "Une clé d'idempotence est requise.");
const settings = this.settings;
let expeditionId;
this.cards.database.transaction(() => {
const previous = this.db.prepare("SELECT response_json FROM idempotency WHERE player_id = ? AND scope = 'expedition-start' AND request_key = ?").get(playerId, requestKey);
if (previous) {
expeditionId = JSON.parse(previous.response_json).expeditionId;
return;
}
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
const day = dailyDayKey(this.now());
const plan = this.prepareSolo(playerId, body, settings, { day, entries: this.playerEntries(playerId, day, settings) });
const busy = plan.slots.find((slot) => slot.busy);
if (busy) fail(409, "EXPEDITION_CARD_BUSY", "Cette carte est déjà en expédition.");
if (this.activeCount(playerId, "solo") >= settings.solo.maxConcurrent) fail(409, "EXPEDITION_LIMIT", "Récupérez d’abord le butin de votre expédition en cours.");
const now = this.now();
const reward = this.rollReward(plan.expected, settings, { orientationPerSlot: plan.evaluation.stats.orientation / plan.slots.length, powers: plan.powers, destination: plan.resolved.destination });
const travel = travelHours(plan.hours, plan.powers, settings);
const { destination } = plan.resolved;
const setup = {
destination: { id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, stats: destination.stats },
condition: plan.evaluation.condition,
stars: plan.stars,
hours: plan.hours,
bonusSlot: plan.resolved.bonusSlot ?? null,
roles: plan.slots.map((slot) => slot.role),
powers: plan.powers,
travelHours: travel
};
expeditionId = randomUUID();
this.db.prepare(`INSERT INTO expeditions(id, mode, day, destination_id, difficulty, duration_ms, creator_id, status, setup_json, result_json, created_at, departs_at, returns_at)
VALUES (?, 'solo', ?, ?, ?, ?, ?, 'running', ?, ?, ?, ?, ?)`)
.run(expeditionId, plan.day, destination.id, plan.stars, Math.round(travel * HOUR_MS), playerId, JSON.stringify(setup), JSON.stringify(this.resultView(plan.evaluation, { powers: plan.powers }, plan.synergy)), now, now, now + Math.round(travel * HOUR_MS));
this.db.prepare("INSERT INTO expedition_members(expedition_id, player_id, reward_json, joined_at) VALUES (?, ?, ?, ?)")
.run(expeditionId, playerId, JSON.stringify(reward), now);
const insertSlot = this.db.prepare("INSERT INTO expedition_slots(expedition_id, position, role, player_id, edition_id, card_id, level, stats_json, powers_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
for (const slot of plan.slots) insertSlot.run(expeditionId, slot.position, ROLE_BY_STAT[slot.role] ?? null, playerId, slot.editionId, slot.cardId, slot.level, JSON.stringify(slot.stats), JSON.stringify(slot.powers || []));
this.discoverResonancesInTx([playerId], plan.synergy);
this.db.prepare("INSERT INTO idempotency(player_id, scope, request_key, response_json, created_at) VALUES (?, 'expedition-start', ?, ?, ?)")
.run(playerId, requestKey, JSON.stringify({ expeditionId }), now);
});
return { expedition: this.expeditionView(expeditionId, playerId), expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
}
// 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.role, 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 = ? ORDER BY s.position`).all(row.id)
.map((slot) => ({
position: slot.position, role: slot.role ? STAT_BY_ROLE[slot.role] : null, 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, revenues sans butin récupéré, ou rentrées dans les dernières 24 heures.
playerExpeditionIds(playerId) {
const since = this.now() - 24 * HOUR_MS;
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) OR m.claimed_at >= ? OR (e.status = 'cancelled' AND e.completed_at >= ?))
ORDER BY e.created_at DESC LIMIT 10`).all(playerId, since, since).map((row) => row.id);
}
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.solo.minStars, max: settings.solo.maxStars, limit: MAX_STARS },
soloCards: settings.solo.cards,
soloLimit: settings.solo.maxConcurrent,
progression: { stardustPerEclat: settings.progression.stardustPerEclat },
group: {
stars: { min: settings.group.minStars, max: settings.group.maxStars },
slots: settings.group.slots, minPlayers: settings.group.minPlayers, limit: settings.group.maxConcurrent,
active: this.activeCount(playerId, "group"), recruitHours: settings.group.recruitHours, lootPct: settings.group.lootPct
},
expeditions: this.playerExpeditionIds(playerId).map((id) => this.expeditionView(id, playerId)),
groups: this.boardView(playerId, settings),
grimoire: this.grimoireOf(playerId),
items: this.itemsOf(playerId),
fragmentsForMap: settings.items.fragmentsForMap,
atelierAvailable: this.atelierAvailable()
};
// 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: [] };
const { day, entries } = this.today(settings, playerId);
return { ...base, day, 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,
soloCards: settings.solo.cards,
forming: this.activeCount(playerId, "group") - active.filter((row) => row.mode === "group").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 et Grimoire (expedition-equipment.js).
// Alertes Discord (expedition-alerts.js).
// Objets (expedition-items.js).
Object.assign(ExpeditionService.prototype, groupMethods, progressMethods, equipmentMethods, alertMethods, itemMethods);