sokko-g/services/cards/expedition-service.js
Shinuwa 8bb1d53d70 Add solo Expeditions, the second Guilde des Veilleurs quest of Sokko TCG
- Every catalog card carries expedition tags and every collection a stat profile, validated at load; twelve destinations live server-side so hidden ones stay secret.
- Pure rules compute card power, per-slot requirements, roles, dangers, the long-trip malus, the score (one more star never raises it) and loot proportional to the chosen duration.
- A simulator script and a balance test guard the design thresholds; agent docs and a new-card skill explain how to tag new cards.
- Migration 8 adds Éclats d'étoile, expedition settings stored as one validated JSON, daily destinations, expeditions, members and slots, and rebuilds gift_packs so a pack can come from an expedition.
- Players launch a solo expedition from the Guild, see an exact preview, and claim their loot when it returns; the card sheet shows cards away on an expedition.
- Administration › Guilde tunes every value with server-side bounds, toggles destinations and cancels running expeditions; expeditions stay closed until an administrator opens them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:29:05 +01:00

384 lines
24 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,
ROLE_BY_STAT, rollLoot, soloRoles, STAT_BY_ROLE
} from "./expedition-rules.js";
import {
DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, validateExpeditionSettings
} from "./expedition-settings.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 {
constructor(cards, destinations) {
this.cards = cards;
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);
}
today(settings) {
const day = dailyDayKey(this.now());
return { day, entries: this.cards.database.transaction(() => this.ensureDay(day, settings)) };
}
// Éditions occupées : celles d'une expédition en route dont le butin n'a pas encore été récupéré par leur propriétaire.
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 = '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);
return this.cards.visibleCollection(playerId, pending?.id).map((entry) => {
const data = editionExpeditionData(this.cards.catalog, entry.editionId, 0, settings);
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 = 'running' AND m.claimed_at IS NULL`).get(playerId, mode).count;
}
// Destination du jour vue par le joueur : rôles du solo et exigences chiffrées pour chaque étoile autorisée.
destinationView({ destination, entry }, settings) {
const roles = soloRoles(destination, settings.solo.cards);
const stars = {};
for (let star = settings.solo.minStars; star <= settings.solo.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 { id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, stats: destination.stats, roles, stars };
}
// 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, 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 < settings.solo.minStars || stars > settings.solo.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.");
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) => {
const data = editionExpeditionData(this.cards.catalog, editionId, 0, settings);
if (!data) fail(400, "EXPEDITION_CARD_INVALID", "Seules les cartes rares, épiques, légendaires et mythiques partent en expédition.");
const card = owned.get(editionId);
if (!card) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte.");
return { ...card, 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 evaluation = evaluateTeam({ destination: resolved.destination, entry: resolved.entry, stars, durationIndex, slots }, settings);
const hours = settings.durations.hours[durationIndex];
const expected = expectedLoot({ hours, stars, tier: evaluation.tier, fortune: evaluation.stats.fortune, slotCount: slots.length }, settings);
return { day, resolved, stars, durationIndex, hours, slots, evaluation, expected };
}
resultView(evaluation) {
return {
scorePct: round1(evaluation.scorePct),
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 }))
};
}
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.prepareSolo(playerId, body, settings, this.today(settings));
return {
preview: {
...this.resultView(plan.evaluation),
expected: { eclats: round1(plan.expected.eclats), stardust: round1(plan.expected.stardust), packChancePct: round1(Math.min(1, plan.expected.packs) * 100), fortuneBonusPct: round1(plan.expected.fortuneBonusPct) }
}
};
}
// 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.ensureDay(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 loot = rollLoot(plan.expected, settings, (max) => this.random(max));
const packs = [];
for (let index = 0; index < loot.packs; index += 1) {
const collectionId = this.packCollection();
if (collectionId) packs.push(collectionId);
}
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: null,
roles: plan.slots.map((slot) => slot.role)
};
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, plan.hours * HOUR_MS, playerId, JSON.stringify(setup), JSON.stringify(this.resultView(plan.evaluation)), now, now, now + plan.hours * HOUR_MS);
this.db.prepare("INSERT INTO expedition_members(expedition_id, player_id, reward_json, joined_at) VALUES (?, ?, ?, ?)")
.run(expeditionId, playerId, JSON.stringify({ eclats: loot.eclats, stardust: loot.stardust, packs }), now);
const insertSlot = this.db.prepare("INSERT INTO expedition_slots(expedition_id, position, role, player_id, edition_id, card_id, level, stats_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));
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 position, role, player_id, edition_id, card_id, level, stats_json FROM expedition_slots WHERE expedition_id = ? ORDER BY position").all(row.id)
.map((slot) => ({
position: slot.position, role: slot.role ? STAT_BY_ROLE[slot.role] : null, own: slot.player_id === playerId,
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;
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,
expeditions: this.playerExpeditionIds(playerId).map((id) => this.expeditionView(id, playerId))
};
// 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);
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.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.cards.audit(playerId, "expedition_completed", row.id, {
destinationId: setup.destination.id, destinationName: setup.destination.name, difficulty: row.difficulty, hours: setup.hours,
tier: result.tier, scorePct: result.scorePct, eclats: reward.eclats, stardust: reward.stardust, packs: reward.packs.length, 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 en cours sont annulées (ses cartes n'existent plus).
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) this.cancelRow(row, { notify: false });
}
// 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;
const now = this.now();
const active = this.db.prepare(`SELECT e.returns_at 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,
busyEditions: [...busy].map(([editionId, entry]) => ({ editionId, returnsAt: entry.returnsAt }))
};
}
adminSummary() {
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,
runningList: this.db.prepare(`SELECT e.id, 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 = 'running' ORDER BY e.returns_at LIMIT 20`).all()
.map((row) => ({ id: row.id, destinationId: row.destination_id, stars: row.difficulty, returnsAt: row.returns_at, creatorName: row.display_name }))
};
}
}