A variation keeps its edition id when its holographic finish changes, so players keep their copies, duplicates, expedition progress and equipment. A unique index on (card_id, finish_id) replaces the id-derived uniqueness, and new variations get a suffixed id when the original one is taken. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1226 lines
79 KiB
JavaScript
1226 lines
79 KiB
JavaScript
// Rôle : applique les règles serveur de propriété, paquets, transferts et distributions Sokko TCG.
|
||
import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
|
||
import { normalizeReward } from "./rewards.js";
|
||
import { MASS_RECYCLE_RARITIES, planRecycling, spareQuantity, validateShopSetting } from "./stardust.js";
|
||
import { FULL_ART_FORMAT, buildPublishedCatalog, collectionDrawableEditions, createCatalogIndex, holographicFinishIds, isMythicEditionIdOf, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
|
||
import { computeStreak, DAILY_REPEAT_WINDOW_DAYS, dailyCandidates, dailyDayKey, dailyZoom, drawDailyPuzzle, guessHint, isDayKey, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "./daily.js";
|
||
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MAX_RESERVE_OPENINGS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js";
|
||
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
|
||
import { ExpeditionService } from "./expedition-service.js";
|
||
|
||
const TRANSFER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||
const RARITY_RANK = new Map(["common", "rare", "epic", "legendary", "mythic"].map((rarity, index) => [rarity, index]));
|
||
|
||
function fail(status, code, message) {
|
||
throw Object.assign(new Error(message), { status, code });
|
||
}
|
||
|
||
function token(bytes = 24) {
|
||
return randomBytes(bytes).toString("base64url");
|
||
}
|
||
|
||
function tokenHash(value) {
|
||
return createHash("sha256").update(value).digest("hex");
|
||
}
|
||
|
||
function publicPlayer(row) {
|
||
return { id: row.id, displayName: row.display_name, avatarUrl: row.avatar_url, isAdmin: Boolean(row.is_admin) };
|
||
}
|
||
|
||
// Compte de la connexion « Version développement » et son solde de poussière figé par `devPerks`.
|
||
export const DEV_DISCORD_ID = "dev-admin";
|
||
// Ouvertures achetées en une fois au plus : la Boutique limite aussi la quantité à ce que la poussière permet.
|
||
export const MAX_OPENINGS_PER_PURCHASE = 100;
|
||
const WELCOME_OPENINGS = 3;
|
||
const ADMIN_HISTORY_PAGE_SIZE = 50;
|
||
// Liste blanche : audit_log garde aussi les actions d'administration, qui n'ont pas leur place dans le journal d'un joueur.
|
||
// Les types gift_created, gift_joined, gift_cancelled et trade_joined ne sont plus écrits, mais restent lisibles dans les anciens comptes.
|
||
const PLAYER_HISTORY_EVENTS = Object.freeze([
|
||
"welcome_opening", "pack_opened", "gift_pack_opened", "cards_recycled", "opening_purchased", "campaign_claimed",
|
||
"trade_created", "trade_received", "trade_declined", "trade_joined", "trade_completed", "trade_cancelled",
|
||
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won", "expedition_completed", "expedition_cancelled_by_guild", "expedition_dissolved", "card_upgraded", "eclats_converted", "item_used", "destination_starter", "card_plan_changed", "item_bought"
|
||
]);
|
||
const DEV_STARDUST = 1000;
|
||
const DELETED_PLAYER_NAME = "Joueur supprimé";
|
||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||
// Une session dure 30 jours : un joueur actif se reconnecte donc au moins une fois par mois.
|
||
const INACTIVE_ACCOUNT_MS = 730 * DAY_MS;
|
||
const IDEMPOTENCY_TTL_MS = 30 * DAY_MS;
|
||
|
||
export class CardsService {
|
||
// `destinations` : destinations des Expéditions validées ; sans elles, celles du dépôt (services/cards/content).
|
||
// `alerts` : { available, publicOrigin } pour les alertes Discord des Expéditions (bot configuré, lien des messages).
|
||
constructor({ database, catalog, now = Date.now, random, devPerks = false, destinations = null, alerts = {} } = {}) {
|
||
// Serveur Vite local uniquement : ressources permanentes du compte de développement pour tester le jeu sans attendre.
|
||
this.devPerks = devPerks;
|
||
this.database = database;
|
||
this.db = database.db;
|
||
// Catalogue versionné préparé par loadCardsCatalog / prepareVersionedCatalog (finitions générées, sans mythiques).
|
||
this.versionedCatalog = catalog;
|
||
this.now = now;
|
||
// Tirage d'un entier de 0 à max − 1. Sans source fournie (le serveur), le hasard cryptographique, comme les paquets.
|
||
this.random = random ?? ((max) => randomInt(max));
|
||
this.reloadCatalog();
|
||
this.expeditions = new ExpeditionService(this, destinations || loadExpeditionDestinations(DEFAULT_DESTINATIONS_PATH, catalog), alerts);
|
||
}
|
||
|
||
// Valeurs citées par les astuces de l'Accueil, lues dans les réglages en cours : une astuce reste juste quand un réglage change.
|
||
// `expeditions` : les astuces des Expéditions ne s'affichent que si elles sont ouvertes.
|
||
tipValues() {
|
||
const expedition = this.expeditions.settings;
|
||
const shop = this.shopSetting;
|
||
const recharge = this.rechargeSetting;
|
||
const hours = (ms) => Math.round((ms / 3_600_000) * 10) / 10;
|
||
const count = (value, word) => `${value} ${word}${value > 1 ? "s" : ""}`;
|
||
const { awakening } = expedition;
|
||
return {
|
||
expeditions: expedition.enabled,
|
||
rechargeEvery: recharge.intervalMs === 3_600_000 ? "chaque heure" : `toutes les ${hours(recharge.intervalMs).toLocaleString("fr-FR")} h`,
|
||
maxOpenings: recharge.maxOpenings, fullHours: hours(recharge.intervalMs * recharge.maxOpenings).toLocaleString("fr-FR"),
|
||
shopPackShare: shop.shopPackShare, dailyReward: shop.dailyReward, maxGuesses: MAX_DAILY_GUESSES,
|
||
commonStardust: shop.stardustValues.common ?? 0, mythicStardust: shop.stardustValues.mythic ?? 0,
|
||
stardustPerEclat: expedition.progression.stardustPerEclat, oblivionPrice: expedition.progression.oblivionPrice, transferDays: TRANSFER_TTL_MS / 86_400_000,
|
||
groupJoinPct: expedition.destinationCards.groupJoinPct, dropPct: expedition.destinationCards.dropPct,
|
||
fortuneCapPct: expedition.loot.fortuneCapPct, capHours: expedition.loot.capHours,
|
||
conditionMissPct: expedition.requirements.conditionMissPct, dangerPct: expedition.danger.malusPct, durationMalusPct: Math.max(...expedition.durations.malusPct),
|
||
affinityPct: expedition.synergy.affinityPct, resonancePct: expedition.synergy.resonancePct, expertisePct: expedition.expertise.scorePct,
|
||
synergyBonus: expedition.equipment.synergyBonus, cohesionPct: expedition.group.cohesionPct,
|
||
groupLootMax: Math.max(...expedition.group.lootPct) / 100, groupSlots: expedition.group.slots,
|
||
fragmentsForMap: expedition.items.fragmentsForMap,
|
||
awakeningPowers: new Intl.ListFormat("fr", { type: "conjunction" }).format(awakening.powers.filter((power) => power > 0).map(String)),
|
||
awakeningRare: count(awakening.rare, "rare"), awakeningEpic: count(awakening.epic, "épique"), awakeningLegendary: count(awakening.legendary, "légendaire")
|
||
};
|
||
}
|
||
|
||
get rechargeSetting() {
|
||
const row = this.db.prepare("SELECT interval_ms, max_openings, updated_at FROM recharge_settings WHERE id = 1").get();
|
||
return { intervalMs: row.interval_ms, maxOpenings: row.max_openings, updatedAt: row.updated_at };
|
||
}
|
||
|
||
// Le délai s'applique immédiatement à tous les joueurs, y compris au temps écoulé depuis leur dernière recharge.
|
||
// Une réserve agrandie se remplit dès maintenant pour les joueurs qui étaient pleins ; réduite, elle laisse à chacun
|
||
// ses ouvertures en trop (voir calculateRecharge). Un champ absent garde sa valeur.
|
||
updateRechargeSetting(playerId, { intervalMs, maxOpenings } = {}) {
|
||
this.requireAdmin(playerId);
|
||
const current = this.rechargeSetting;
|
||
const nextInterval = intervalMs ?? current.intervalMs;
|
||
const nextMax = maxOpenings ?? current.maxOpenings;
|
||
if (!Number.isInteger(nextInterval) || nextInterval < MIN_RECHARGE_INTERVAL_MS || nextInterval > MAX_RECHARGE_INTERVAL_MS || nextInterval % MIN_RECHARGE_INTERVAL_MS !== 0) {
|
||
fail(400, "RECHARGE_INTERVAL_INVALID", "Délai invalide : un nombre entier de minutes, entre 1 minute et 7 jours.");
|
||
}
|
||
if (!Number.isInteger(nextMax) || nextMax < 1 || nextMax > MAX_RESERVE_OPENINGS) {
|
||
fail(400, "RECHARGE_RESERVE_INVALID", `Réserve invalide : un nombre entier d’ouvertures, entre 1 et ${MAX_RESERVE_OPENINGS}.`);
|
||
}
|
||
if (current.intervalMs === nextInterval && current.maxOpenings === nextMax) fail(409, "RECHARGE_UNCHANGED", "Ces réglages sont déjà en vigueur.");
|
||
this.database.transaction(() => {
|
||
const now = this.now();
|
||
// Un joueur plein n'a pas d'échéance : sans cette ancre, sa recharge ne partirait qu'à sa prochaine visite.
|
||
if (nextMax > current.maxOpenings) {
|
||
this.db.prepare("UPDATE players SET recharge_anchor = ? WHERE recharge_anchor IS NULL AND openings_balance < ? AND deleted_at IS NULL").run(now, nextMax);
|
||
}
|
||
this.db.prepare("UPDATE recharge_settings SET interval_ms = ?, max_openings = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(nextInterval, nextMax, now, playerId);
|
||
this.audit(playerId, "recharge_updated", "recharge", { previousIntervalMs: current.intervalMs, intervalMs: nextInterval, previousMaxOpenings: current.maxOpenings, maxOpenings: nextMax });
|
||
});
|
||
return { rechargeSetting: this.rechargeSetting };
|
||
}
|
||
|
||
get shopSetting() {
|
||
const row = this.db.prepare("SELECT stardust_values_json, opening_price, shop_pack_price, shop_pack_share, daily_reward, updated_at FROM shop_settings WHERE id = 1").get();
|
||
return { stardustValues: JSON.parse(row.stardust_values_json), openingPrice: row.opening_price, shopPackPrice: row.shop_pack_price, shopPackShare: row.shop_pack_share, dailyReward: row.daily_reward, updatedAt: row.updated_at };
|
||
}
|
||
|
||
updateShopSetting(playerId, { stardustValues, openingPrice, shopPackPrice, shopPackShare, dailyReward } = {}) {
|
||
this.requireAdmin(playerId);
|
||
const previous = this.shopSetting;
|
||
const next = { stardustValues, openingPrice, shopPackPrice: shopPackPrice ?? previous.shopPackPrice, shopPackShare: shopPackShare ?? previous.shopPackShare, dailyReward: dailyReward ?? previous.dailyReward };
|
||
const error = validateShopSetting(next, this.catalog.rarities.map((rarity) => rarity.id));
|
||
if (error) fail(400, "SHOP_SETTING_INVALID", error);
|
||
this.database.transaction(() => {
|
||
this.db.prepare("UPDATE shop_settings SET stardust_values_json = ?, opening_price = ?, shop_pack_price = ?, shop_pack_share = ?, daily_reward = ?, updated_at = ?, updated_by = ? WHERE id = 1")
|
||
.run(JSON.stringify(next.stardustValues), next.openingPrice, next.shopPackPrice, next.shopPackShare, next.dailyReward, this.now(), playerId);
|
||
this.audit(playerId, "shop_updated", "shop", { previous: { stardustValues: previous.stardustValues, openingPrice: previous.openingPrice, shopPackPrice: previous.shopPackPrice, shopPackShare: previous.shopPackShare, dailyReward: previous.dailyReward }, ...next });
|
||
});
|
||
return { shopSetting: this.shopSetting };
|
||
}
|
||
|
||
// Ignore les lignes devenues incohérentes avec le catalogue versionné (carte, finition, forme ou palette supprimées)
|
||
// pour que le serveur démarre toujours ; elles restent en base et réapparaissent si la cible revient.
|
||
adminContent() {
|
||
const versioned = this.versionedCatalog;
|
||
const holographic = holographicFinishIds(versioned);
|
||
const cardIds = new Set(versioned.cards.map((card) => card.id));
|
||
const collectionIds = new Set(versioned.collections.map((collection) => collection.id));
|
||
const shapeIds = new Set(versioned.particleShapes.map((shape) => shape.id));
|
||
const paletteIds = new Set([...versioned.particlePalettes.map((palette) => palette.id), MATCH_HOLO_PALETTE_ID]);
|
||
const variations = this.db.prepare("SELECT edition_id, card_id, finish_id, status FROM mythic_variations").all()
|
||
.map((row) => ({ editionId: row.edition_id, cardId: row.card_id, finishId: row.finish_id, status: row.status }))
|
||
.filter((row) => holographic.has(row.finishId) && legendaryParentEdition(versioned, row.cardId) && isMythicEditionIdOf(row.editionId, row.cardId));
|
||
const openingSettings = this.db.prepare("SELECT scope, target_id, particle_shape_id, particle_palette_id FROM mythic_opening_settings ORDER BY scope, target_id").all()
|
||
.map((row) => ({
|
||
scope: row.scope,
|
||
targetId: row.target_id,
|
||
particleShapeId: shapeIds.has(row.particle_shape_id) ? row.particle_shape_id : null,
|
||
particlePaletteId: paletteIds.has(row.particle_palette_id) ? row.particle_palette_id : null
|
||
}))
|
||
.filter((row) => (row.scope === "card" ? cardIds : collectionIds).has(row.targetId));
|
||
const collectionStates = this.db.prepare("SELECT collection_id, active FROM collection_states").all()
|
||
.filter((row) => collectionIds.has(row.collection_id))
|
||
.map((row) => ({ collectionId: row.collection_id, active: Boolean(row.active) }));
|
||
const rarityIds = new Set(versioned.rarities.map((rarity) => rarity.id));
|
||
const dropRates = this.db.prepare("SELECT collection_id, rarity_weights_json FROM drop_rates").all()
|
||
.map((row) => ({ collectionId: row.collection_id, rarityWeights: JSON.parse(row.rarity_weights_json) }))
|
||
.filter((rate) => {
|
||
if (!collectionIds.has(rate.collectionId)) return false;
|
||
try {
|
||
validateRarityWeights(rate.rarityWeights, rarityIds, rate.collectionId);
|
||
return true;
|
||
} catch {
|
||
return false;
|
||
}
|
||
});
|
||
return { variations, openingSettings, collectionStates, dropRates };
|
||
}
|
||
|
||
reloadCatalog() {
|
||
const catalog = buildPublishedCatalog(this.versionedCatalog, this.adminContent());
|
||
this.catalog = catalog;
|
||
this.index = createCatalogIndex(catalog);
|
||
return catalog;
|
||
}
|
||
|
||
requireAdmin(playerId) {
|
||
const player = this.db.prepare("SELECT is_admin FROM players WHERE id = ?").get(playerId);
|
||
if (!player?.is_admin) fail(403, "ADMIN_REQUIRED", "Accès administrateur requis.");
|
||
}
|
||
|
||
validateOpeningStyle({ particleShapeId = null, particlePaletteId = null } = {}) {
|
||
if (particleShapeId != null && !this.versionedCatalog.particleShapes.some((shape) => shape.id === particleShapeId)) fail(400, "PARTICLE_SHAPE_INVALID", "Forme de particules inconnue.");
|
||
if (particlePaletteId != null && particlePaletteId !== MATCH_HOLO_PALETTE_ID && !this.versionedCatalog.particlePalettes.some((palette) => palette.id === particlePaletteId)) fail(400, "PARTICLE_PALETTE_INVALID", "Palette de particules inconnue.");
|
||
return { particleShapeId, particlePaletteId };
|
||
}
|
||
|
||
writeOpeningSetting(playerId, scope, targetId, { particleShapeId, particlePaletteId }) {
|
||
if (!particleShapeId && !particlePaletteId) {
|
||
this.db.prepare("DELETE FROM mythic_opening_settings WHERE scope = ? AND target_id = ?").run(scope, targetId);
|
||
return;
|
||
}
|
||
this.db.prepare(`INSERT INTO mythic_opening_settings(scope, target_id, particle_shape_id, particle_palette_id, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?)
|
||
ON CONFLICT(scope, target_id) DO UPDATE SET particle_shape_id = excluded.particle_shape_id, particle_palette_id = excluded.particle_palette_id, updated_at = excluded.updated_at, updated_by = excluded.updated_by`)
|
||
.run(scope, targetId, particleShapeId, particlePaletteId, this.now(), playerId);
|
||
}
|
||
|
||
// Édition encore possédée, ou citée par une ouverture ou un transfert passés (même si l'exemplaire a été recyclé).
|
||
editionReferenced(editionId) {
|
||
return Boolean(this.db.prepare(`SELECT 1 FROM collection_cards WHERE edition_id = ?1
|
||
UNION ALL SELECT 1 FROM opening_cards WHERE edition_id = ?1
|
||
UNION ALL SELECT 1 FROM transfers WHERE offered_edition_id = ?1 OR requested_edition_id = ?1 LIMIT 1`).get(editionId));
|
||
}
|
||
|
||
// Nombre de campagnes qui citent chaque édition, comme carte offerte ou carte garantie d'un paquet.
|
||
// Les paquets offerts reprennent la récompense de leur campagne : ils sont couverts aussi.
|
||
editionCampaignCounts() {
|
||
const counts = {};
|
||
for (const row of this.db.prepare("SELECT reward_json FROM campaigns").all()) {
|
||
const ids = new Set(JSON.parse(row.reward_json).items.map((item) => (item.type === "card" ? item.editionId : item.guarantee?.editionId)).filter(Boolean));
|
||
for (const id of ids) counts[id] = (counts[id] || 0) + 1;
|
||
}
|
||
return counts;
|
||
}
|
||
|
||
setCardMythicConfig(playerId, cardId, { finishIds, opening = {} } = {}) {
|
||
this.requireAdmin(playerId);
|
||
const versioned = this.versionedCatalog;
|
||
const card = versioned.cards.find((item) => item.id === cardId);
|
||
if (!card) fail(404, "CARD_NOT_FOUND", "Carte introuvable.");
|
||
if (!legendaryParentEdition(versioned, cardId)) fail(400, "LEGENDARY_REQUIRED", "Seule une carte légendaire peut recevoir une version mythique.");
|
||
const holographic = holographicFinishIds(versioned);
|
||
if (!Array.isArray(finishIds) || finishIds.some((id) => typeof id !== "string" || !holographic.has(id))) fail(400, "FINISH_INVALID", "Choisissez uniquement des finitions holographiques.");
|
||
const needsFullImage = (id) => versioned.finishes.find((item) => item.id === id)?.formatId === FULL_ART_FORMAT;
|
||
if (!card.fullImage && finishIds.some(needsFullImage)) fail(400, "FULL_IMAGE_REQUIRED", "Cette carte n’a pas d’illustration pleine.");
|
||
const openingStyle = this.validateOpeningStyle(opening);
|
||
const wanted = new Set(finishIds);
|
||
const now = this.now();
|
||
this.database.transaction(() => {
|
||
// Une seule règle pour toutes les variations : retirée des tirages si un joueur la possède ou si une campagne
|
||
// la cite (sinon ses codes et paquets offerts ne fonctionneraient plus), supprimée sinon.
|
||
const campaignCounts = this.editionCampaignCounts();
|
||
// Une variation se retrouve par sa finition actuelle : son identifiant garde la finition de sa création.
|
||
const rows = new Map(this.db.prepare("SELECT edition_id, finish_id, status FROM mythic_variations WHERE card_id = ?").all(cardId).map((row) => [row.finish_id, row]));
|
||
for (const finishId of holographic) {
|
||
const row = rows.get(finishId);
|
||
if (wanted.has(finishId)) {
|
||
if (!row) {
|
||
this.db.prepare("INSERT INTO mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by) VALUES (?, ?, ?, 'active', ?, ?)")
|
||
.run(this.freeMythicEditionId(cardId, finishId), cardId, finishId, now, playerId);
|
||
} else if (row.status !== "active") {
|
||
this.db.prepare("UPDATE mythic_variations SET status = 'active', updated_at = ?, updated_by = ? WHERE edition_id = ?").run(now, playerId, row.edition_id);
|
||
}
|
||
} else if (row && (this.editionReferenced(row.edition_id) || campaignCounts[row.edition_id] > 0)) {
|
||
if (row.status !== "retired") this.db.prepare("UPDATE mythic_variations SET status = 'retired', updated_at = ?, updated_by = ? WHERE edition_id = ?").run(now, playerId, row.edition_id);
|
||
} else if (row) {
|
||
this.db.prepare("DELETE FROM mythic_variations WHERE edition_id = ?").run(row.edition_id);
|
||
}
|
||
}
|
||
this.writeOpeningSetting(playerId, "card", cardId, openingStyle);
|
||
this.audit(playerId, "catalog_card_mythic_updated", cardId, { finishIds: [...wanted], opening: openingStyle });
|
||
this.reloadCatalog();
|
||
});
|
||
return { catalog: publicCatalog(this.catalog) };
|
||
}
|
||
|
||
// Identifiant d'une nouvelle variation : `carte-finition`, suffixé si une variation dont la finition a changé le porte déjà
|
||
// ou si d'anciens exemplaires, ouvertures, transferts ou campagnes le citent encore.
|
||
freeMythicEditionId(cardId, finishId) {
|
||
const base = mythicEditionId(cardId, finishId);
|
||
const versionedIds = new Set(this.versionedCatalog.editions.map((edition) => edition.id));
|
||
const campaignCounts = this.editionCampaignCounts();
|
||
const taken = (id) => versionedIds.has(id) || campaignCounts[id] > 0 || this.editionReferenced(id)
|
||
|| Boolean(this.db.prepare("SELECT 1 FROM mythic_variations WHERE edition_id = ?").get(id));
|
||
let candidate = base;
|
||
for (let index = 2; taken(candidate); index += 1) candidate = `${base}-${index}`;
|
||
return candidate;
|
||
}
|
||
|
||
// Change la finition holographique d'une variation existante. Son identifiant ne change pas : les exemplaires des joueurs,
|
||
// leur nombre, leur progression d'expédition, leurs équipements et les campagnes qui la citent restent les mêmes.
|
||
setMythicFinish(playerId, editionId, finishId) {
|
||
this.requireAdmin(playerId);
|
||
const versioned = this.versionedCatalog;
|
||
const row = this.db.prepare("SELECT card_id, finish_id FROM mythic_variations WHERE edition_id = ?").get(editionId);
|
||
const card = row && versioned.cards.find((item) => item.id === row.card_id);
|
||
if (!card) fail(404, "MYTHIC_NOT_FOUND", "Variation mythique introuvable.");
|
||
const finish = versioned.finishes.find((item) => item.id === finishId);
|
||
if (!finish || !holographicFinishIds(versioned).has(finishId)) fail(400, "FINISH_INVALID", "Choisissez une finition holographique.");
|
||
if (finish.formatId === FULL_ART_FORMAT && !card.fullImage) fail(400, "FULL_IMAGE_REQUIRED", "Cette carte n’a pas d’illustration pleine.");
|
||
if (row.finish_id === finishId) fail(400, "FINISH_UNCHANGED", "La variation a déjà cette finition.");
|
||
if (this.db.prepare("SELECT 1 FROM mythic_variations WHERE card_id = ? AND finish_id = ?").get(row.card_id, finishId)) {
|
||
fail(409, "FINISH_TAKEN", "Cette carte a déjà une variation avec cette finition.");
|
||
}
|
||
this.database.transaction(() => {
|
||
this.db.prepare("UPDATE mythic_variations SET finish_id = ?, updated_at = ?, updated_by = ? WHERE edition_id = ?").run(finishId, this.now(), playerId, editionId);
|
||
this.audit(playerId, "catalog_mythic_finish_changed", row.card_id, { editionId, previousFinishId: row.finish_id, finishId });
|
||
this.reloadCatalog();
|
||
});
|
||
return { catalog: publicCatalog(this.catalog) };
|
||
}
|
||
|
||
requireCollection(collectionId) {
|
||
if (!this.versionedCatalog.collections.some((collection) => collection.id === collectionId)) fail(404, "COLLECTION_NOT_FOUND", "Collection introuvable.");
|
||
}
|
||
|
||
setCollectionActive(playerId, collectionId, active) {
|
||
this.requireAdmin(playerId);
|
||
this.requireCollection(collectionId);
|
||
if (typeof active !== "boolean") fail(400, "COLLECTION_STATE_INVALID", "État du paquet invalide.");
|
||
if (this.index.collections.get(collectionId)?.packCategory === "expedition") fail(409, "EXPEDITION_COLLECTION", "Cette collection ne s’obtient qu’en expédition : elle n’a pas de paquet.");
|
||
if (active && !this.index.collections.get(collectionId)?.dropWeights) fail(409, "DROP_RATES_REQUIRED", "Définissez d’abord les taux de tirage de ce paquet.");
|
||
this.database.transaction(() => {
|
||
this.db.prepare(`INSERT INTO collection_states(collection_id, active, updated_at, updated_by) VALUES (?, ?, ?, ?)
|
||
ON CONFLICT(collection_id) DO UPDATE SET active = excluded.active, updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(collectionId, active ? 1 : 0, this.now(), playerId);
|
||
this.audit(playerId, active ? "collection_opened" : "collection_closed", collectionId, {});
|
||
this.reloadCatalog();
|
||
});
|
||
return { catalog: publicCatalog(this.catalog) };
|
||
}
|
||
|
||
// Les taux de tirage se modifient directement ; le journal d'audit garde les anciens et les nouveaux poids.
|
||
setDropRates(playerId, collectionId, rarityWeights) {
|
||
this.requireAdmin(playerId);
|
||
this.requireCollection(collectionId);
|
||
const rarityIds = new Set(this.versionedCatalog.rarities.map((rarity) => rarity.id));
|
||
try {
|
||
validateRarityWeights(rarityWeights, rarityIds, collectionId);
|
||
} catch {
|
||
fail(400, "DROP_WEIGHTS_INVALID", "Poids invalides : un entier positif ou nul par rareté, pour un total strictement positif.");
|
||
}
|
||
const previous = this.index.collections.get(collectionId)?.dropWeights || null;
|
||
if (previous && [...rarityIds].every((rarity) => previous[rarity] === rarityWeights[rarity])) fail(409, "DROP_RATES_UNCHANGED", "Ces taux sont déjà en vigueur.");
|
||
const weights = Object.fromEntries([...rarityIds].map((rarity) => [rarity, rarityWeights[rarity]]));
|
||
this.database.transaction(() => {
|
||
this.db.prepare(`INSERT INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES (?, ?, ?, ?)
|
||
ON CONFLICT(collection_id) DO UPDATE SET rarity_weights_json = excluded.rarity_weights_json, updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(collectionId, JSON.stringify(weights), this.now(), playerId);
|
||
this.audit(playerId, "drop_rates_updated", collectionId, { previous, rarityWeights: weights });
|
||
this.reloadCatalog();
|
||
});
|
||
return { catalog: publicCatalog(this.catalog) };
|
||
}
|
||
|
||
setCollectionMythicOpening(playerId, collectionId, opening = {}) {
|
||
this.requireAdmin(playerId);
|
||
if (!this.versionedCatalog.collections.some((collection) => collection.id === collectionId)) fail(404, "COLLECTION_NOT_FOUND", "Collection introuvable.");
|
||
const openingStyle = this.validateOpeningStyle(opening);
|
||
this.database.transaction(() => {
|
||
this.writeOpeningSetting(playerId, "collection", collectionId, openingStyle);
|
||
this.audit(playerId, "catalog_collection_opening_updated", collectionId, { opening: openingStyle });
|
||
this.reloadCatalog();
|
||
});
|
||
return { catalog: publicCatalog(this.catalog) };
|
||
}
|
||
|
||
upsertPlayer({ discordId, displayName, avatarUrl = "", isAdmin = false }) {
|
||
const now = this.now();
|
||
let row = this.db.prepare("SELECT * FROM players WHERE discord_id = ?").get(discordId);
|
||
if (!row) {
|
||
const id = randomUUID();
|
||
this.db.prepare(`INSERT INTO players(id, discord_id, display_name, avatar_url, is_admin, created_at, openings_balance, recharge_anchor, last_login_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, discordId, displayName, avatarUrl, isAdmin ? 1 : 0, now, WELCOME_OPENINGS, now, now);
|
||
row = this.db.prepare("SELECT * FROM players WHERE id = ?").get(id);
|
||
this.audit(id, "welcome_opening", id, { amount: WELCOME_OPENINGS });
|
||
} else {
|
||
this.db.prepare("UPDATE players SET display_name = ?, avatar_url = ?, is_admin = ?, last_login_at = ? WHERE id = ?").run(displayName, avatarUrl, isAdmin ? 1 : 0, now, row.id);
|
||
row = this.db.prepare("SELECT * FROM players WHERE id = ?").get(row.id);
|
||
}
|
||
return publicPlayer(row);
|
||
}
|
||
|
||
// La liste des administrateurs vient de l'environnement et ne change qu'au redémarrage : elle s'applique alors aux sessions déjà ouvertes.
|
||
syncAdmins(adminDiscordIds, { keepDevAdmin = false } = {}) {
|
||
const ids = JSON.stringify([...adminDiscordIds, ...(keepDevAdmin ? [DEV_DISCORD_ID] : [])]);
|
||
this.db.prepare("UPDATE players SET is_admin = (discord_id IN (SELECT value FROM json_each(?1)))").run(ids);
|
||
}
|
||
|
||
createSession(playerId) {
|
||
const rawToken = token(32);
|
||
const csrfToken = token(24);
|
||
const now = this.now();
|
||
this.db.prepare("INSERT INTO sessions(token_hash, player_id, csrf_token, created_at, expires_at) VALUES (?, ?, ?, ?, ?)")
|
||
.run(tokenHash(rawToken), playerId, csrfToken, now, now + SESSION_TTL_MS);
|
||
return { token: rawToken, csrfToken, expiresAt: now + SESSION_TTL_MS };
|
||
}
|
||
|
||
getSession(rawToken) {
|
||
if (!rawToken) return null;
|
||
const row = this.db.prepare(`SELECT s.*, p.discord_id, p.display_name, p.avatar_url, p.is_admin
|
||
FROM sessions s JOIN players p ON p.id = s.player_id WHERE s.token_hash = ?`).get(tokenHash(rawToken));
|
||
if (!row || row.expires_at <= this.now()) {
|
||
if (row) this.db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(tokenHash(rawToken));
|
||
return null;
|
||
}
|
||
return { player: publicPlayer({ id: row.player_id, ...row }), csrfToken: row.csrf_token, expiresAt: row.expires_at };
|
||
}
|
||
|
||
deleteSession(rawToken) {
|
||
if (rawToken) this.db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(tokenHash(rawToken));
|
||
}
|
||
|
||
refreshRecharge(playerId) {
|
||
const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId);
|
||
if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
|
||
const pinned = this.devPerks && player.discord_id === DEV_DISCORD_ID;
|
||
const setting = this.rechargeSetting;
|
||
const recharge = { ...(pinned ? pinnedRecharge : calculateRecharge)({
|
||
openingsBalance: player.openings_balance,
|
||
rechargeAnchor: player.recharge_anchor
|
||
}, this.now(), setting), maxOpenings: setting.maxOpenings };
|
||
this.db.prepare("UPDATE players SET openings_balance = ?, recharge_anchor = ? WHERE id = ?")
|
||
.run(recharge.openingsBalance, recharge.rechargeAnchor, playerId);
|
||
if (pinned) {
|
||
this.db.prepare("UPDATE players SET stardust = ? WHERE id = ?").run(DEV_STARDUST, playerId);
|
||
this.expeditions.ensureDevItemsInTx(playerId);
|
||
}
|
||
return recharge;
|
||
}
|
||
|
||
// Compte de la connexion « Version développement », quand `devPerks` est actif.
|
||
isDevAccount(playerId) {
|
||
return this.devPerks && this.db.prepare("SELECT discord_id FROM players WHERE id = ?").get(playerId)?.discord_id === DEV_DISCORD_ID;
|
||
}
|
||
|
||
// Réserve rechargeable seule, pour la pastille du menu : bien plus légère que l'état complet.
|
||
getReserve(playerId) {
|
||
return this.database.transaction(() => this.refreshRecharge(playerId));
|
||
}
|
||
|
||
// Carte affichable à partir d'une édition (catalogue publié).
|
||
cardEntry(editionId, extra = {}) {
|
||
const edition = this.index.editions.get(editionId);
|
||
const card = edition ? this.index.cards.get(edition.cardId) : null;
|
||
return { editionId, edition, card, ...extra };
|
||
}
|
||
|
||
quantityOf(playerId, editionId) {
|
||
return this.db.prepare("SELECT quantity FROM collection_cards WHERE player_id = ? AND edition_id = ?").get(playerId, editionId)?.quantity ?? 0;
|
||
}
|
||
|
||
// Une carte de destination est unique : la recevoir une seconde fois ne fait rien (elle ne s'échange ni ne se donne).
|
||
// Renvoie false quand la carte n'a pas été ajoutée.
|
||
addCard(playerId, editionId) {
|
||
if (this.isDestinationEdition(editionId) && this.quantityOf(playerId, editionId)) return false;
|
||
this.db.prepare(`INSERT INTO collection_cards(player_id, edition_id, quantity, acquired_at) VALUES (?, ?, 1, ?)
|
||
ON CONFLICT(player_id, edition_id) DO UPDATE SET quantity = quantity + 1`).run(playerId, editionId, this.now());
|
||
return true;
|
||
}
|
||
|
||
isDestinationEdition(editionId) {
|
||
return this.index.cards.get(this.index.editions.get(editionId)?.cardId)?.kind === "destination";
|
||
}
|
||
|
||
// Cartes d'un paquet : une carte de destination déjà possédée, ou déjà tirée dans ce paquet, est remplacée par une autre carte de
|
||
// même rareté de sa collection (hors cartes de destination), pour ne jamais en montrer une que le joueur ne recevrait pas.
|
||
uniqueDestinationCards(playerId, editionIds) {
|
||
const seen = new Set();
|
||
return editionIds.map((editionId) => {
|
||
if (!this.isDestinationEdition(editionId)) return editionId;
|
||
if (!seen.has(editionId) && !this.quantityOf(playerId, editionId)) {
|
||
seen.add(editionId);
|
||
return editionId;
|
||
}
|
||
const edition = this.index.editions.get(editionId);
|
||
const collectionId = this.index.cards.get(edition.cardId).collectionId;
|
||
const others = collectionDrawableEditions(this.catalog, collectionId).filter((item) => item.rarity === edition.rarity && !this.isDestinationEdition(item.id));
|
||
return others.length ? others[this.random(others.length)].id : editionId;
|
||
});
|
||
}
|
||
|
||
// Retire des doublons : l'exemplaire conservé ne peut jamais partir.
|
||
removeDuplicates(playerId, editionId, count) {
|
||
const removed = this.db.prepare("UPDATE collection_cards SET quantity = quantity - ?1 WHERE player_id = ?2 AND edition_id = ?3 AND quantity - ?1 >= 1").run(count, playerId, editionId);
|
||
if (!removed.changes) fail(409, "COLLECTION_CHANGED", "Votre collection a changé, réessayez.");
|
||
}
|
||
|
||
// Doublons réservés par les transferts en cours du joueur, par carte.
|
||
reservedCounts(playerId) {
|
||
const rows = this.db.prepare(`SELECT edition_id, COUNT(*) AS count FROM (
|
||
SELECT offered_edition_id AS edition_id FROM transfers WHERE initiator_id = ?1 AND status = 'open'
|
||
) GROUP BY edition_id`).all(playerId);
|
||
return new Map(rows.map((row) => [row.edition_id, row.count]));
|
||
}
|
||
|
||
// Collection du joueur : quantité, doublons réservés et doublons disponibles (échange, don, recyclage) par carte.
|
||
collectionOf(playerId) {
|
||
const reserved = this.reservedCounts(playerId);
|
||
return this.db.prepare("SELECT edition_id, quantity, acquired_at FROM collection_cards WHERE player_id = ? ORDER BY acquired_at DESC, edition_id").all(playerId)
|
||
.map((row) => {
|
||
const entry = { editionId: row.edition_id, quantity: row.quantity, reserved: reserved.get(row.edition_id) || 0, acquiredAt: row.acquired_at };
|
||
return { ...entry, spare: spareQuantity(entry) };
|
||
});
|
||
}
|
||
|
||
requireSpare(playerId, editionId) {
|
||
const entry = this.collectionOf(playerId).find((item) => item.editionId === editionId);
|
||
if (!entry) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte.");
|
||
if (!entry.spare) fail(409, "NOT_A_DUPLICATE", "Seuls les doublons peuvent être échangés ou donnés : gardez au moins un exemplaire.");
|
||
}
|
||
|
||
openingById(openingId, playerId) {
|
||
const opening = this.db.prepare("SELECT * FROM openings WHERE id = ? AND player_id = ?").get(openingId, playerId);
|
||
if (!opening) return null;
|
||
const cards = this.db.prepare("SELECT * FROM opening_cards WHERE opening_id = ? ORDER BY position").all(opening.id);
|
||
const gift = this.db.prepare("SELECT options_json FROM gift_packs WHERE opening_id = ?").get(opening.id);
|
||
return {
|
||
id: opening.id,
|
||
collectionId: opening.collection_id,
|
||
options: gift ? JSON.parse(gift.options_json) : null,
|
||
status: opening.status,
|
||
createdAt: opening.created_at,
|
||
cards: cards.map((row) => this.cardEntry(row.edition_id, { id: `${opening.id}:${row.position}`, position: row.position, isNewCard: Boolean(row.was_new_card), isNewEdition: Boolean(row.was_new_edition), quantityBefore: row.quantity_before }))
|
||
};
|
||
}
|
||
|
||
rarestPull(playerId) {
|
||
const pulls = this.db.prepare(`SELECT oc.edition_id, oc.position, o.id AS opening_id, o.created_at AS opened_at
|
||
FROM opening_cards oc
|
||
JOIN openings o ON o.id = oc.opening_id
|
||
WHERE o.player_id = ? AND o.status = 'completed'
|
||
ORDER BY o.created_at DESC, oc.position DESC`).all(playerId);
|
||
let rarest = null;
|
||
for (const pull of pulls) {
|
||
const entry = this.cardEntry(pull.edition_id, { id: `${pull.opening_id}:${pull.position}`, openedAt: pull.opened_at });
|
||
if (!rarest || (RARITY_RANK.get(entry.edition?.rarity) ?? -1) > (RARITY_RANK.get(rarest.edition?.rarity) ?? -1)) rarest = entry;
|
||
}
|
||
return rarest;
|
||
}
|
||
|
||
// Un transfert expiré ou annulé libère simplement ses doublons réservés (la réservation découle du statut).
|
||
expireTransfers() {
|
||
this.db.prepare("UPDATE transfers SET status = 'expired' WHERE status = 'open' AND expires_at <= ?").run(this.now());
|
||
}
|
||
|
||
transferView(row, playerId) {
|
||
const initiator = this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id = ?").get(row.initiator_id);
|
||
const recipient = row.recipient_id ? this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id = ?").get(row.recipient_id) : null;
|
||
return {
|
||
id: row.id, type: row.type, status: row.status, declined: Boolean(row.declined), createdAt: row.created_at, expiresAt: row.expires_at, completedAt: row.completed_at,
|
||
direction: row.initiator_id === playerId ? "sent" : "received",
|
||
initiator: initiator && { id: initiator.id, displayName: initiator.display_name, avatarUrl: initiator.avatar_url },
|
||
recipient: recipient && { id: recipient.id, displayName: recipient.display_name, avatarUrl: recipient.avatar_url },
|
||
offered: this.cardEntry(row.offered_edition_id),
|
||
requested: row.requested_edition_id ? this.cardEntry(row.requested_edition_id) : null
|
||
};
|
||
}
|
||
|
||
// Les cartes d'une ouverture en attente sont déjà attribuées, mais ne doivent pas se dévoiler avant la révélation.
|
||
visibleCollection(playerId, pendingOpeningId) {
|
||
const collection = this.collectionOf(playerId);
|
||
if (!pendingOpeningId) return collection;
|
||
const hidden = new Map();
|
||
for (const { edition_id: editionId } of this.db.prepare("SELECT edition_id FROM opening_cards WHERE opening_id = ?").all(pendingOpeningId)) hidden.set(editionId, (hidden.get(editionId) || 0) + 1);
|
||
return collection.map((entry) => {
|
||
const visible = { ...entry, quantity: entry.quantity - (hidden.get(entry.editionId) || 0) };
|
||
return { ...visible, spare: spareQuantity(visible) };
|
||
}).filter((entry) => entry.quantity > 0);
|
||
}
|
||
|
||
getState(playerId) {
|
||
// Les sous-vues lisent toutes les réglages des Expéditions : une seule lecture pour tout l'état.
|
||
return this.expeditions.withSettingsSnapshot(() => this.buildState(playerId));
|
||
}
|
||
|
||
buildState(playerId) {
|
||
// Groupes arrivés au bout de leur inscription : départ ou dissolution avant de lire l'historique et le résumé.
|
||
this.expeditions.settleForming();
|
||
const recharge = this.database.transaction(() => this.refreshRecharge(playerId));
|
||
this.expireTransfers();
|
||
const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId);
|
||
if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
|
||
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(playerId);
|
||
const owned = this.visibleCollection(playerId, pending?.id);
|
||
const collection = owned.map((entry) => this.cardEntry(entry.editionId, entry));
|
||
const favorites = this.db.prepare("SELECT edition_id FROM favorites WHERE player_id = ?").all(playerId).map((row) => row.edition_id);
|
||
const history = this.db.prepare("SELECT event_type, entity_id, details_json, created_at FROM audit_log WHERE player_id = ? AND event_type IN (" + PLAYER_HISTORY_EVENTS.map(() => "?").join(", ") + ") ORDER BY created_at DESC LIMIT 100").all(playerId, ...PLAYER_HISTORY_EVENTS)
|
||
.map((row) => ({ type: row.event_type, entityId: row.entity_id, details: JSON.parse(row.details_json), createdAt: row.created_at }));
|
||
const transferRows = this.db.prepare("SELECT * FROM transfers WHERE initiator_id = ? OR recipient_id = ? ORDER BY created_at DESC LIMIT 50").all(playerId, playerId);
|
||
// Un paquet offert vient d'une campagne (son nom) ou d'une expédition (le nom de sa destination).
|
||
const giftPacks = this.db.prepare(`SELECT g.id, g.source, g.collection_id, g.options_json, g.created_at, c.name AS campaign_name, e.setup_json
|
||
FROM gift_packs g LEFT JOIN campaigns c ON c.id = g.campaign_id LEFT JOIN expeditions e ON e.id = g.expedition_id
|
||
WHERE g.player_id = ? AND g.opening_id IS NULL ORDER BY g.created_at`).all(playerId)
|
||
.map((row) => ({
|
||
id: row.id, source: row.source, collectionId: row.collection_id, receivedAt: row.created_at, options: JSON.parse(row.options_json),
|
||
campaignName: row.campaign_name ?? null, sourceName: row.source === "expedition" ? JSON.parse(row.setup_json).destination.name : row.campaign_name
|
||
}));
|
||
const openingsCount = this.db.prepare("SELECT COUNT(*) AS count FROM openings WHERE player_id = ?").get(playerId).count;
|
||
const shop = this.shopSetting;
|
||
const recycling = this.recyclingPlan(owned);
|
||
return {
|
||
player: publicPlayer(player), recharge, collection, favorites,
|
||
wallet: { stardust: player.stardust, purchasedOpenings: player.purchased_openings, eclats: player.eclats },
|
||
// Le Pont des Veilleurs (poussière vers Éclats) est vendu en boutique, au taux réglé dans les Expéditions.
|
||
shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare, dailyReward: shop.dailyReward, stardustPerEclat: this.expeditions.settings.progression.stardustPerEclat, oblivionPrice: this.expeditions.settings.progression.oblivionPrice, windRosePrice: this.expeditions.settings.progression.windRosePrice },
|
||
daily: this.dailySummary(playerId),
|
||
expeditions: this.expeditions.summary(playerId),
|
||
cardProgress: this.expeditions.cardProgressView(playerId),
|
||
equipment: this.expeditions.equipmentChoices(playerId),
|
||
alerts: this.expeditions.alertPreferences(playerId),
|
||
items: this.expeditions.itemsOf(playerId),
|
||
recycling: { count: recycling.count, stardust: recycling.stardust, byRarity: recycling.byRarity },
|
||
tipValues: this.tipValues(),
|
||
pendingOpening: pending ? this.openingById(pending.id, playerId) : null,
|
||
rarestPull: this.rarestPull(playerId), stats: { openingsCount },
|
||
history, transfers: transferRows.map((row) => this.transferView(row, playerId)), giftPacks
|
||
};
|
||
}
|
||
|
||
// Tout ce qui n'est pas un événement de jeu : une nouvelle action d'administration apparaît ici sans autre déclaration.
|
||
getAdminHistory(playerId, { before = null } = {}) {
|
||
this.requireAdmin(playerId);
|
||
const rows = this.db.prepare(`SELECT a.id, a.event_type, a.entity_id, a.details_json, a.created_at, p.display_name AS admin_name, c.name AS campaign_name
|
||
FROM audit_log a
|
||
LEFT JOIN players p ON p.id = a.player_id
|
||
LEFT JOIN campaigns c ON c.id = a.entity_id AND a.event_type LIKE 'campaign_%'
|
||
WHERE a.event_type NOT IN (${PLAYER_HISTORY_EVENTS.map(() => "?").join(", ")}) AND (? IS NULL OR a.id < ?)
|
||
ORDER BY a.id DESC LIMIT ?`).all(...PLAYER_HISTORY_EVENTS, before, before, ADMIN_HISTORY_PAGE_SIZE + 1);
|
||
const page = rows.slice(0, ADMIN_HISTORY_PAGE_SIZE);
|
||
return {
|
||
entries: page.map((row) => ({ id: row.id, type: row.event_type, entityId: row.entity_id, details: JSON.parse(row.details_json), createdAt: row.created_at, adminName: row.admin_name, campaignName: row.campaign_name })),
|
||
nextBefore: rows.length > ADMIN_HISTORY_PAGE_SIZE ? page.at(-1).id : null
|
||
};
|
||
}
|
||
|
||
getAdminDashboard(playerId) {
|
||
this.requireAdmin(playerId);
|
||
// Cartes possédées par joueur et par rareté (la rareté vient du catalogue publié).
|
||
const rarityCounts = new Map();
|
||
for (const row of this.db.prepare("SELECT player_id, edition_id, quantity FROM collection_cards").all()) {
|
||
const rarity = this.index.editions.get(row.edition_id)?.rarity;
|
||
if (!rarity) continue;
|
||
const counts = rarityCounts.get(row.player_id) || {};
|
||
counts[rarity] = (counts[rarity] || 0) + row.quantity;
|
||
rarityCounts.set(row.player_id, counts);
|
||
}
|
||
const players = this.database.transaction(() => this.db.prepare(`SELECT p.*,
|
||
(SELECT MAX(o.created_at) FROM openings o WHERE o.player_id = p.id) AS last_opening_at,
|
||
(SELECT COUNT(*) FROM openings o WHERE o.player_id = p.id) AS openings_count,
|
||
(SELECT COALESCE(SUM(c.quantity), 0) FROM collection_cards c WHERE c.player_id = p.id) AS total_cards,
|
||
(SELECT COUNT(*) FROM gift_packs g WHERE g.player_id = p.id AND g.opening_id IS NULL) AS gift_packs,
|
||
(SELECT COUNT(*) FROM transfers t WHERE t.status = 'completed' AND (t.initiator_id = p.id OR t.recipient_id = p.id)) AS transfers_count
|
||
FROM players p WHERE p.deleted_at IS NULL ORDER BY p.display_name COLLATE NOCASE`).all().map((row) => {
|
||
const recharge = this.refreshRecharge(row.id);
|
||
return {
|
||
id: row.id,
|
||
displayName: row.display_name,
|
||
avatarUrl: row.avatar_url,
|
||
isAdmin: Boolean(row.is_admin),
|
||
createdAt: row.created_at,
|
||
lastOpeningAt: row.last_opening_at ?? null,
|
||
openingsCount: row.openings_count,
|
||
openingsBalance: recharge.openingsBalance,
|
||
nextOpeningAt: recharge.nextOpeningAt,
|
||
totalCards: row.total_cards,
|
||
rarityCounts: rarityCounts.get(row.id) || {},
|
||
giftPacks: row.gift_packs,
|
||
transfersCount: row.transfers_count,
|
||
stardust: row.stardust,
|
||
purchasedOpenings: row.purchased_openings
|
||
};
|
||
}));
|
||
const now = this.now();
|
||
// Ouvertures des 7 derniers jours par paquet, dont les paquets offerts (campagnes et expéditions).
|
||
const since = now - 7 * 24 * 3_600_000;
|
||
const packActivity7d = {};
|
||
for (const row of this.db.prepare("SELECT collection_id, COUNT(*) AS count FROM openings WHERE created_at >= ? GROUP BY collection_id").all(since)) {
|
||
packActivity7d[row.collection_id] = { openings: row.count, gifted: 0 };
|
||
}
|
||
for (const row of this.db.prepare("SELECT collection_id, COUNT(*) AS count FROM gift_packs WHERE opened_at >= ? GROUP BY collection_id").all(since)) {
|
||
packActivity7d[row.collection_id] ??= { openings: 0, gifted: 0 };
|
||
packActivity7d[row.collection_id].gifted = row.count;
|
||
}
|
||
return {
|
||
generatedAt: now,
|
||
stats: {
|
||
totalPlayers: players.length,
|
||
activePlayers7d: this.db.prepare("SELECT COUNT(DISTINCT o.player_id) AS count FROM openings o JOIN players p ON p.id = o.player_id WHERE o.created_at >= ? AND p.deleted_at IS NULL").get(now - 7 * 24 * 3_600_000).count
|
||
},
|
||
players,
|
||
rechargeSetting: this.rechargeSetting,
|
||
shopSetting: this.shopSetting,
|
||
daily: this.dailyAdminSummary(),
|
||
expeditionSettings: this.expeditions.adminSettings(),
|
||
expeditionsToday: this.expeditions.adminSummary(),
|
||
packActivity7d,
|
||
campaigns: this.campaignSummaries(),
|
||
editionCampaigns: this.editionCampaignCounts(),
|
||
// Variations possédées ou citées par une ouverture ou un transfert passés : elles ne peuvent qu'être retirées.
|
||
recordedEditions: this.db.prepare(`SELECT edition_id FROM collection_cards UNION SELECT edition_id FROM opening_cards
|
||
UNION SELECT offered_edition_id FROM transfers UNION SELECT requested_edition_id FROM transfers WHERE requested_edition_id IS NOT NULL`).all().map((row) => row.edition_id),
|
||
editionOwners: Object.fromEntries(this.db.prepare("SELECT edition_id, COUNT(*) AS owners FROM collection_cards GROUP BY edition_id").all().map((row) => [row.edition_id, row.owners]))
|
||
};
|
||
}
|
||
|
||
// Crée une ouverture en attente de révélation avec les éditions tirées ; utilisé par les paquets normaux, achetés et offerts.
|
||
// Une carte ou une édition est « nouvelle » si le joueur ne la possédait pas : une carte obtenue n'est jamais perdue.
|
||
insertOpening(playerId, collectionId, drawnEditionIds) {
|
||
const editionIds = this.uniqueDestinationCards(playerId, drawnEditionIds);
|
||
const openingId = randomUUID();
|
||
this.db.prepare("INSERT INTO openings(id, player_id, collection_id, status, created_at) VALUES (?, ?, ?, 'pending', ?)")
|
||
.run(openingId, playerId, collectionId, this.now());
|
||
const ownsCard = this.db.prepare("SELECT 1 FROM collection_cards WHERE player_id = ? AND edition_id IN (SELECT value FROM json_each(?)) LIMIT 1");
|
||
editionIds.forEach((editionId, position) => {
|
||
const edition = this.index.editions.get(editionId);
|
||
const quantity = this.quantityOf(playerId, editionId);
|
||
const cardEditions = this.catalog.editions.filter((item) => item.cardId === edition.cardId).map((item) => item.id);
|
||
const knownCard = ownsCard.get(playerId, JSON.stringify(cardEditions));
|
||
this.db.prepare("INSERT INTO opening_cards(opening_id, position, edition_id, was_new_card, was_new_edition, quantity_before) VALUES (?, ?, ?, ?, ?, ?)")
|
||
.run(openingId, position, editionId, knownCard ? 0 : 1, quantity ? 0 : 1, quantity);
|
||
this.addCard(playerId, editionId);
|
||
});
|
||
return { openingId, editionIds };
|
||
}
|
||
|
||
// Rejoue une requête déjà traitée (même clé d'idempotence) ou exécute `create` qui renvoie l'identifiant d'ouverture.
|
||
idempotentOpening(playerId, scope, requestKey, create) {
|
||
if (!requestKey || requestKey.length > 100) fail(400, "IDEMPOTENCY_REQUIRED", "Une clé d'idempotence est requise.");
|
||
let openingId;
|
||
this.database.transaction(() => {
|
||
const previous = this.db.prepare("SELECT response_json FROM idempotency WHERE player_id = ? AND scope = ? AND request_key = ?").get(playerId, scope, requestKey);
|
||
if (previous) {
|
||
openingId = JSON.parse(previous.response_json).openingId;
|
||
return;
|
||
}
|
||
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId);
|
||
if (pending) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours.");
|
||
openingId = create();
|
||
this.db.prepare("INSERT INTO idempotency(player_id, scope, request_key, response_json, created_at) VALUES (?, ?, ?, ?, ?)")
|
||
.run(playerId, scope, requestKey, JSON.stringify({ openingId }), this.now());
|
||
});
|
||
return { opening: this.openingById(openingId, playerId), state: this.getState(playerId) };
|
||
}
|
||
|
||
// `purchased` : consomme une ouverture achetée en boutique au lieu de la réserve rechargeable.
|
||
openPack(playerId, collectionId, requestKey, { purchased = false } = {}) {
|
||
return this.idempotentOpening(playerId, purchased ? "open-purchased" : "open-pack", requestKey, () => {
|
||
const category = this.catalog.collections.find((item) => item.id === collectionId)?.packCategory;
|
||
if (category === "shop") fail(409, "SHOP_PACK_ONLY", "Ce paquet ne s’obtient que dans la boutique.");
|
||
if (category === "expedition") fail(409, "EXPEDITION_COLLECTION", "Cette collection ne s’obtient qu’en expédition.");
|
||
if (purchased) {
|
||
const spent = this.db.prepare("UPDATE players SET purchased_openings = purchased_openings - 1 WHERE id = ? AND purchased_openings > 0").run(playerId);
|
||
if (!spent.changes) fail(409, "NO_PURCHASED_OPENING", "Vous n’avez aucune ouverture achetée.");
|
||
} else {
|
||
const spent = spendOpening(this.refreshRecharge(playerId), this.now(), this.rechargeSetting);
|
||
this.db.prepare("UPDATE players SET openings_balance = ?, recharge_anchor = ? WHERE id = ?").run(spent.openingsBalance, spent.rechargeAnchor, playerId);
|
||
}
|
||
const { openingId, editionIds } = this.insertOpening(playerId, collectionId, drawPack(this.catalog, collectionId, this.random));
|
||
this.audit(playerId, "pack_opened", openingId, { collectionId, cards: editionIds, ...(purchased ? { purchased: true } : {}) });
|
||
return openingId;
|
||
});
|
||
}
|
||
|
||
recyclingPlan(collection, editionId = null, maxRarity = "legendary") {
|
||
return planRecycling(collection, { editionId, maxRarity, rarityOf: (id) => this.index.editions.get(id)?.rarity, stardustValues: this.shopSetting.stardustValues });
|
||
}
|
||
|
||
// Recycle en masse les doublons disponibles, des communes jusqu'à `maxRarity` (sans les mythiques), ou un seul doublon de
|
||
// `editionId` ; un exemplaire de chaque carte reste toujours.
|
||
recycleDuplicates(playerId, { editionId = null, maxRarity = "legendary" } = {}) {
|
||
if (editionId != null && !this.index.editions.has(editionId)) fail(404, "EDITION_NOT_FOUND", "Édition introuvable.");
|
||
if (!MASS_RECYCLE_RARITIES.includes(maxRarity)) fail(400, "RARITY_INVALID", "Rareté maximale invalide.");
|
||
let plan;
|
||
this.database.transaction(() => {
|
||
this.expireTransfers();
|
||
if (this.db.prepare("SELECT 1 FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId)) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours.");
|
||
plan = this.recyclingPlan(this.collectionOf(playerId), editionId, maxRarity);
|
||
if (!plan.count) fail(409, "NO_DUPLICATE", editionId ? "Aucun doublon disponible pour cette carte." : "Aucun doublon à recycler.");
|
||
for (const item of plan.items) this.removeDuplicates(playerId, item.editionId, item.count);
|
||
this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(plan.stardust, playerId);
|
||
this.audit(playerId, "cards_recycled", editionId || "duplicates", { count: plan.count, stardust: plan.stardust, editions: plan.items.map((item) => item.editionId), ...(editionId ? {} : { maxRarity }) });
|
||
});
|
||
return { recycled: { count: plan.count, stardust: plan.stardust }, state: this.getState(playerId) };
|
||
}
|
||
|
||
// Achète `count` ouvertures d'un coup, au prix unitaire réglé, si la poussière couvre le total.
|
||
buyOpening(playerId, { count = 1 } = {}) {
|
||
if (!Number.isInteger(count) || count < 1 || count > MAX_OPENINGS_PER_PURCHASE) fail(400, "OPENING_COUNT_INVALID", `Nombre d’ouvertures invalide : un entier entre 1 et ${MAX_OPENINGS_PER_PURCHASE}.`);
|
||
const { openingPrice } = this.shopSetting;
|
||
const cost = openingPrice * count;
|
||
this.database.transaction(() => {
|
||
// Compte de développement : son solde figé doit être appliqué avant de vérifier le prix.
|
||
this.refreshRecharge(playerId);
|
||
const bought = this.db.prepare("UPDATE players SET stardust = stardust - ?, purchased_openings = purchased_openings + ? WHERE id = ? AND stardust >= ?").run(cost, count, playerId, cost);
|
||
if (!bought.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles.");
|
||
this.audit(playerId, "opening_purchased", "shop", { price: openingPrice, count, stardust: cost });
|
||
});
|
||
return this.getState(playerId);
|
||
}
|
||
|
||
// Le paquet de la Boutique se paie en poussière et s'ouvre aussitôt ; il ne consomme aucune ouverture.
|
||
buyShopPack(playerId, requestKey) {
|
||
return this.idempotentOpening(playerId, "buy-shop-pack", requestKey, () => {
|
||
const collection = this.catalog.collections.find((item) => item.packCategory === "shop" && item.active);
|
||
if (!collection) fail(404, "COLLECTION_UNAVAILABLE", "Ce paquet n’est pas disponible.");
|
||
const { shopPackPrice, shopPackShare } = this.shopSetting;
|
||
// Compte de développement : son solde figé doit être appliqué avant de vérifier le prix.
|
||
this.refreshRecharge(playerId);
|
||
const paid = this.db.prepare("UPDATE players SET stardust = stardust - ? WHERE id = ? AND stardust >= ?").run(shopPackPrice, playerId, shopPackPrice);
|
||
if (!paid.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles.");
|
||
const { openingId, editionIds } = this.insertOpening(playerId, collection.id, drawShopPack(this.catalog, collection.id, this.random, shopPackShare));
|
||
this.audit(playerId, "pack_opened", openingId, { collectionId: collection.id, cards: editionIds, price: shopPackPrice });
|
||
return openingId;
|
||
});
|
||
}
|
||
|
||
// Un paquet offert ne consomme pas d'ouverture rechargeable et s'ouvre même si la collection est fermée.
|
||
openGiftPack(playerId, giftPackId, requestKey) {
|
||
return this.idempotentOpening(playerId, "open-gift", requestKey, () => {
|
||
const gift = this.db.prepare("SELECT * FROM gift_packs WHERE id = ? AND player_id = ? AND opening_id IS NULL").get(giftPackId, playerId);
|
||
if (!gift) fail(404, "GIFT_PACK_NOT_FOUND", "Ce paquet offert n'est plus disponible.");
|
||
const options = JSON.parse(gift.options_json);
|
||
const { openingId, editionIds } = this.insertOpening(playerId, gift.collection_id, drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights ?? options.packRates ?? null, guarantee: options.guarantee, requireActive: false }));
|
||
this.db.prepare("UPDATE gift_packs SET opening_id = ?, opened_at = ? WHERE id = ?").run(openingId, this.now(), gift.id);
|
||
this.audit(playerId, "gift_pack_opened", openingId, { collectionId: gift.collection_id, campaignId: gift.campaign_id, ...(gift.expedition_id ? { expeditionId: gift.expedition_id } : {}), cards: editionIds });
|
||
return openingId;
|
||
});
|
||
}
|
||
|
||
// Carte du jour : chaque joueur a sa propre carte, tirée à sa première visite du jour de Paris puis gardée avec sa partie ;
|
||
// une carte commune incitait à se passer la réponse. daily_days numérote les jours où quelqu'un a joué.
|
||
// À appeler dans une transaction : deux premières visites simultanées ne tirent qu'une carte.
|
||
ensureDailyDay(day) {
|
||
this.db.prepare("INSERT OR IGNORE INTO daily_days(day, created_at) VALUES (?, ?)").run(day, this.now());
|
||
return this.db.prepare("SELECT COUNT(*) AS count FROM daily_days WHERE day <= ?").get(day).count;
|
||
}
|
||
|
||
dailyAttemptRow(playerId, day) {
|
||
return this.db.prepare("SELECT card_id, focus_x, focus_y, guesses_json, status, reward FROM daily_attempts WHERE player_id = ? AND day = ?").get(playerId, day);
|
||
}
|
||
|
||
// Partie du joueur pour ce jour, tirée s'il n'en a pas encore : pas de carte qu'il a déjà eue ces 60 derniers jours.
|
||
ensureDailyPuzzle(playerId, day) {
|
||
const number = this.ensureDailyDay(day);
|
||
if (!this.dailyAttemptRow(playerId, day)) {
|
||
const recent = this.db.prepare("SELECT card_id FROM daily_attempts WHERE player_id = ? AND day >= ?").all(playerId, shiftDayKey(day, -DAILY_REPEAT_WINDOW_DAYS)).map((row) => row.card_id);
|
||
const drawn = drawDailyPuzzle(this.catalog, recent, this.random);
|
||
if (!drawn) fail(409, "DAILY_UNAVAILABLE", "Aucune carte ne peut être tirée aujourd’hui.");
|
||
this.db.prepare("INSERT INTO daily_attempts(player_id, day, card_id, focus_x, focus_y, guesses_json, status, reward, created_at, updated_at) VALUES (?, ?, ?, ?, ?, '[]', 'playing', 0, ?, ?)")
|
||
.run(playerId, day, drawn.cardId, drawn.focusX, drawn.focusY, this.now(), this.now());
|
||
}
|
||
const row = this.dailyAttemptRow(playerId, day);
|
||
// Une carte retirée du catalogue après son tirage ne peut plus être affichée.
|
||
if (!this.index.cards.has(row.card_id)) fail(503, "DAILY_UNAVAILABLE", "La Carte du jour est indisponible.");
|
||
return { day, number, cardId: row.card_id, focus: { x: row.focus_x, y: row.focus_y }, guesses: JSON.parse(row.guesses_json), status: row.status, earned: row.reward };
|
||
}
|
||
|
||
todayPuzzle(playerId) {
|
||
return this.database.transaction(() => this.ensureDailyPuzzle(playerId, dailyDayKey(this.now())));
|
||
}
|
||
|
||
// Collections dont le joueur peut proposer les cartes : celles qu'il voit (ouvertes ou dont il possède une carte) et
|
||
// celle de la réponse, au cas où elle aurait été fermée après le tirage.
|
||
dailyCollectionIds(playerId, answerCardId) {
|
||
const owned = new Set(this.collectionOf(playerId).map((entry) => this.index.cards.get(this.index.editions.get(entry.editionId)?.cardId)?.collectionId).filter(Boolean));
|
||
const ids = new Set(this.catalog.collections.filter((collection) => collection.active || owned.has(collection.id)).map((collection) => collection.id));
|
||
ids.add(this.index.cards.get(answerCardId).collectionId);
|
||
return [...ids];
|
||
}
|
||
|
||
dailyStreak(playerId, day) {
|
||
return computeStreak(this.db.prepare("SELECT day FROM daily_attempts WHERE player_id = ? AND status = 'won'").all(playerId).map((row) => row.day), day);
|
||
}
|
||
|
||
// Zoom de la partie : il se relâche à chaque essai raté et vaut 1 une fois la partie terminée.
|
||
dailyPuzzleZoom(puzzle) {
|
||
return dailyZoom(puzzle.guesses.length - (puzzle.status === "won" ? 1 : 0), puzzle.status !== "playing");
|
||
}
|
||
|
||
// La réponse n'est envoyée qu'une fois la partie terminée, et l'illustration n'arrive que recadrée (voir dailyImage).
|
||
dailyView(playerId, puzzle) {
|
||
const finished = puzzle.status !== "playing";
|
||
return {
|
||
day: puzzle.day,
|
||
number: puzzle.number,
|
||
maxGuesses: MAX_DAILY_GUESSES,
|
||
zoom: this.dailyPuzzleZoom(puzzle),
|
||
status: puzzle.status,
|
||
guesses: puzzle.guesses.map((cardId) => guessHint(this.catalog, puzzle.cardId, cardId)),
|
||
collectionIds: this.dailyCollectionIds(playerId, puzzle.cardId),
|
||
reward: this.shopSetting.dailyReward,
|
||
earned: puzzle.earned,
|
||
streak: this.dailyStreak(playerId, puzzle.day),
|
||
nextAt: nextDailyAt(this.now()),
|
||
answerCardId: finished ? puzzle.cardId : null
|
||
};
|
||
}
|
||
|
||
getDaily(playerId) {
|
||
return this.dailyView(playerId, this.todayPuzzle(playerId));
|
||
}
|
||
|
||
// Résumé pour le tableau de bord du joueur, sans tirer sa carte : il n'en a une qu'en ouvrant la Carte du jour.
|
||
dailySummary(playerId) {
|
||
const day = dailyDayKey(this.now());
|
||
if (!dailyCandidates(this.catalog).length) return null;
|
||
const number = this.database.transaction(() => this.ensureDailyDay(day));
|
||
const row = this.dailyAttemptRow(playerId, day);
|
||
const guesses = row ? JSON.parse(row.guesses_json) : [];
|
||
return { day, number, status: row?.status || "playing", guessCount: guesses.length, maxGuesses: MAX_DAILY_GUESSES, streak: this.dailyStreak(playerId, day) };
|
||
}
|
||
|
||
// Un essai vaut pour le jour annoncé par le client : après minuit, il doit recharger la nouvelle partie.
|
||
guessDaily(playerId, { day, cardId } = {}) {
|
||
if (!isDayKey(day) || typeof cardId !== "string" || !cardId) fail(400, "DAILY_GUESS_INVALID", "Essai invalide.");
|
||
const daily = this.database.transaction(() => {
|
||
const today = dailyDayKey(this.now());
|
||
if (day !== today) fail(409, "DAILY_EXPIRED", "Une nouvelle Carte du jour est arrivée : rechargez la partie.");
|
||
const puzzle = this.ensureDailyPuzzle(playerId, today);
|
||
if (puzzle.status !== "playing") fail(409, "DAILY_FINISHED", "Vous avez déjà terminé la Carte du jour.");
|
||
const card = this.index.cards.get(cardId);
|
||
if (!card || !this.dailyCollectionIds(playerId, puzzle.cardId).includes(card.collectionId)) fail(400, "DAILY_GUESS_INVALID", "Choisissez une carte de la liste.");
|
||
if (puzzle.guesses.includes(cardId)) fail(409, "DAILY_GUESS_REPEATED", "Vous avez déjà proposé cette carte.");
|
||
const guesses = [...puzzle.guesses, cardId];
|
||
const won = cardId === puzzle.cardId;
|
||
const status = won ? "won" : guesses.length >= MAX_DAILY_GUESSES ? "lost" : "playing";
|
||
const reward = won ? this.shopSetting.dailyReward : 0;
|
||
this.db.prepare("UPDATE daily_attempts SET guesses_json = ?, status = ?, reward = ?, updated_at = ? WHERE player_id = ? AND day = ?")
|
||
.run(JSON.stringify(guesses), status, reward, this.now(), playerId, today);
|
||
if (won) {
|
||
if (reward) this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(reward, playerId);
|
||
this.audit(playerId, "daily_won", today, { number: puzzle.number, cardId, guesses: guesses.length, stardust: reward });
|
||
}
|
||
return this.dailyView(playerId, { ...puzzle, guesses, status, earned: reward });
|
||
});
|
||
// L'état complet suit chaque essai : résumé de la quête du jour et, après une victoire, solde et historique.
|
||
return { daily, state: this.getState(playerId) };
|
||
}
|
||
|
||
// Ce que l'API doit envoyer de l'illustration du joueur : le fichier, le point de zoom et le zoom courant.
|
||
dailyImage(playerId) {
|
||
const puzzle = this.todayPuzzle(playerId);
|
||
return { image: this.index.cards.get(puzzle.cardId).image, focus: puzzle.focus, zoom: this.dailyPuzzleZoom(puzzle) };
|
||
}
|
||
|
||
// Joueurs : ceux qui ont proposé au moins une carte aujourd'hui (ouvrir la page tire une carte sans jouer).
|
||
dailyAdminSummary() {
|
||
const day = dailyDayKey(this.now());
|
||
const number = this.database.transaction(() => this.ensureDailyDay(day));
|
||
const counts = this.db.prepare("SELECT COALESCE(SUM(guesses_json <> '[]'), 0) AS players, COALESCE(SUM(status = 'won'), 0) AS winners FROM daily_attempts WHERE day = ?").get(day);
|
||
return { day, number, players: counts.players, winners: counts.winners };
|
||
}
|
||
|
||
completeOpening(playerId, openingId) {
|
||
const result = this.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE id = ? AND player_id = ? AND status = 'pending'").run(this.now(), openingId, playerId);
|
||
if (!result.changes && !this.openingById(openingId, playerId)) fail(404, "OPENING_NOT_FOUND", "Ouverture introuvable.");
|
||
return this.getState(playerId);
|
||
}
|
||
|
||
setFavorite(playerId, editionId, favorite) {
|
||
if (!this.index.editions.has(editionId)) fail(404, "EDITION_NOT_FOUND", "Édition introuvable.");
|
||
if (favorite) this.db.prepare("INSERT OR IGNORE INTO favorites(player_id, edition_id) VALUES (?, ?)").run(playerId, editionId);
|
||
else this.db.prepare("DELETE FROM favorites WHERE player_id = ? AND edition_id = ?").run(playerId, editionId);
|
||
return this.getState(playerId);
|
||
}
|
||
|
||
// Joueurs à qui donner ou proposer un échange : seuls leur identité publique et leurs doublons disponibles sont exposés, jamais leur collection.
|
||
listTraders(playerId) {
|
||
this.expireTransfers();
|
||
const rows = this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id != ? AND deleted_at IS NULL ORDER BY display_name COLLATE NOCASE").all(playerId);
|
||
// Une seule requête pour tous les joueurs : cette route est ouverte à tout joueur connecté et le serveur est bloqué pendant la lecture.
|
||
const duplicates = new Map();
|
||
for (const row of this.db.prepare(`SELECT c.player_id, c.edition_id, c.quantity, COUNT(t.id) AS reserved
|
||
FROM collection_cards c
|
||
LEFT JOIN transfers t ON t.initiator_id = c.player_id AND t.offered_edition_id = c.edition_id AND t.status = 'open'
|
||
WHERE c.quantity > 1
|
||
GROUP BY c.player_id, c.edition_id
|
||
ORDER BY c.acquired_at DESC, c.edition_id`).all()) {
|
||
const spare = spareQuantity(row);
|
||
if (!spare) continue;
|
||
if (!duplicates.has(row.player_id)) duplicates.set(row.player_id, []);
|
||
duplicates.get(row.player_id).push({ editionId: row.edition_id, spare });
|
||
}
|
||
return {
|
||
traders: rows.map((row) => ({
|
||
id: row.id,
|
||
displayName: row.display_name,
|
||
avatarUrl: row.avatar_url,
|
||
duplicates: duplicates.get(row.id) || []
|
||
}))
|
||
};
|
||
}
|
||
|
||
// Déplace un doublon d'un joueur à l'autre ; l'exemplaire conservé reste toujours.
|
||
moveDuplicate(fromId, toId, editionId) {
|
||
this.removeDuplicates(fromId, editionId, 1);
|
||
this.addCard(toId, editionId);
|
||
}
|
||
|
||
requireRecipient(playerId, recipientId) {
|
||
if (recipientId === playerId) fail(409, "SELF_TRANSFER", "Vous ne pouvez pas vous envoyer une carte.");
|
||
if (!recipientId || !this.db.prepare("SELECT 1 FROM players WHERE id = ? AND deleted_at IS NULL").get(recipientId)) fail(404, "PLAYER_NOT_FOUND", "Ce joueur est introuvable.");
|
||
}
|
||
|
||
// Efface l'identité Discord et les possessions du joueur. Sa ligne reste, anonymisée, pour que l'historique des autres joueurs garde son sens ;
|
||
// une reconnexion avec le même compte Discord crée un compte neuf.
|
||
deleteAccount(playerId) {
|
||
this.database.transaction(() => {
|
||
if (!this.db.prepare("SELECT 1 FROM players WHERE id = ? AND deleted_at IS NULL").get(playerId)) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
|
||
this.anonymizeAccount(playerId, {});
|
||
});
|
||
}
|
||
|
||
// Tâches périodiques sans lien avec une requête : comptes inactifs, sessions expirées, anciennes clés d'idempotence. Les administrateurs ne sont jamais anonymisés.
|
||
runMaintenance() {
|
||
const now = this.now();
|
||
this.database.transaction(() => {
|
||
for (const { id } of this.db.prepare("SELECT id FROM players WHERE deleted_at IS NULL AND is_admin = 0 AND last_login_at <= ?").all(now - INACTIVE_ACCOUNT_MS)) this.anonymizeAccount(id, { reason: "inactivity" });
|
||
this.db.prepare("DELETE FROM sessions WHERE expires_at <= ?").run(now);
|
||
this.db.prepare("DELETE FROM idempotency WHERE created_at <= ?").run(now - IDEMPOTENCY_TTL_MS);
|
||
this.expeditions.purgeAlertOutbox();
|
||
});
|
||
}
|
||
|
||
anonymizeAccount(playerId, auditDetails) {
|
||
for (const transfer of this.db.prepare("SELECT * FROM transfers WHERE status = 'open' AND (initiator_id = ?1 OR recipient_id = ?1)").all(playerId)) {
|
||
this.db.prepare("UPDATE transfers SET status = 'cancelled' WHERE id = ?").run(transfer.id);
|
||
const initiatorLeft = transfer.initiator_id === playerId;
|
||
this.audit(initiatorLeft ? transfer.recipient_id : transfer.initiator_id, "trade_cancelled", transfer.id, initiatorLeft
|
||
? { sent: transfer.requested_edition_id, received: transfer.offered_edition_id }
|
||
: { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
|
||
}
|
||
this.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE player_id = ? AND status = 'pending'").run(this.now(), playerId);
|
||
this.expeditions.forgetPlayer(playerId);
|
||
this.expeditions.forgetAlertsInTx(playerId);
|
||
this.expeditions.forgetItemsInTx(playerId);
|
||
for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts", "card_progress", "card_equipment"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
|
||
this.db.prepare("DELETE FROM gift_packs WHERE player_id = ? AND opening_id IS NULL").run(playerId);
|
||
this.db.prepare(`UPDATE players SET discord_id = ?, display_name = ?, avatar_url = '', is_admin = 0, openings_balance = 0, recharge_anchor = NULL, stardust = 0, purchased_openings = 0, eclats = 0, deleted_at = ? WHERE id = ?`)
|
||
.run(`deleted:${randomUUID()}`, DELETED_PLAYER_NAME, this.now(), playerId);
|
||
this.audit(playerId, "account_deleted", playerId, auditDetails);
|
||
}
|
||
|
||
// Un don arrive immédiatement. Un échange réserve le doublon proposé jusqu'à la réponse, l'annulation ou l'expiration.
|
||
createTransfer(playerId, { type, recipientId, editionId, requestedEditionId = null } = {}) {
|
||
if (!["trade", "gift"].includes(type)) fail(400, "TRANSFER_TYPE", "Type de transfert invalide.");
|
||
const transferId = randomUUID();
|
||
this.database.transaction(() => {
|
||
this.expireTransfers();
|
||
if (this.db.prepare("SELECT 1 FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId)) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours.");
|
||
this.requireRecipient(playerId, recipientId);
|
||
if ([editionId, requestedEditionId].some((id) => id && this.isDestinationEdition(id))) fail(409, "DESTINATION_CARD_LOCKED", "Les cartes de destination ne s’échangent pas et ne se donnent pas.");
|
||
this.requireSpare(playerId, editionId);
|
||
const now = this.now();
|
||
const insert = this.db.prepare(`INSERT INTO transfers(id, code, type, initiator_id, recipient_id, offered_edition_id, requested_edition_id, status, created_at, expires_at, completed_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||
if (type === "gift") {
|
||
insert.run(transferId, token(9).toUpperCase(), type, playerId, recipientId, editionId, null, "completed", now, now, now);
|
||
this.moveDuplicate(playerId, recipientId, editionId);
|
||
this.audit(playerId, "gift_completed", transferId, { sent: editionId, received: null });
|
||
this.audit(recipientId, "gift_completed", transferId, { sent: null, received: editionId });
|
||
return;
|
||
}
|
||
if (requestedEditionId === editionId) fail(400, "TRADE_SAME_CARD", "Choisissez deux cartes différentes.");
|
||
if (!this.collectionOf(recipientId).some((entry) => entry.editionId === requestedEditionId && entry.spare > 0)) fail(409, "TRADE_CARD_UNAVAILABLE", "Ce joueur n’a plus ce doublon disponible.");
|
||
insert.run(transferId, token(9).toUpperCase(), type, playerId, recipientId, editionId, requestedEditionId, "open", now, now + TRANSFER_TTL_MS, null);
|
||
this.audit(playerId, "trade_created", transferId, { sent: editionId, received: requestedEditionId });
|
||
this.audit(recipientId, "trade_received", transferId, { sent: requestedEditionId, received: editionId });
|
||
});
|
||
return { transfer: this.transferView(this.db.prepare("SELECT * FROM transfers WHERE id = ?").get(transferId), playerId), state: this.getState(playerId) };
|
||
}
|
||
|
||
openTrade(transferId) {
|
||
const transfer = this.db.prepare("SELECT * FROM transfers WHERE id = ? AND status = 'open'").get(transferId);
|
||
if (!transfer) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible.");
|
||
return transfer;
|
||
}
|
||
|
||
acceptTransfer(playerId, transferId) {
|
||
this.database.transaction(() => {
|
||
this.expireTransfers();
|
||
const transfer = this.openTrade(transferId);
|
||
if (transfer.recipient_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible.");
|
||
// Le doublon demandé n'est pas réservé tant que la proposition n'est pas acceptée : il a pu partir entre-temps.
|
||
this.requireSpare(playerId, transfer.requested_edition_id);
|
||
this.moveDuplicate(transfer.initiator_id, playerId, transfer.offered_edition_id);
|
||
this.moveDuplicate(playerId, transfer.initiator_id, transfer.requested_edition_id);
|
||
this.db.prepare("UPDATE transfers SET status = 'completed', completed_at = ? WHERE id = ?").run(this.now(), transferId);
|
||
this.audit(transfer.initiator_id, "trade_completed", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
|
||
this.audit(playerId, "trade_completed", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id });
|
||
});
|
||
return this.getState(playerId);
|
||
}
|
||
|
||
declineTransfer(playerId, transferId) {
|
||
this.database.transaction(() => {
|
||
this.expireTransfers();
|
||
const transfer = this.openTrade(transferId);
|
||
if (transfer.recipient_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible.");
|
||
this.db.prepare("UPDATE transfers SET status = 'cancelled', declined = 1 WHERE id = ?").run(transferId);
|
||
this.audit(transfer.initiator_id, "trade_declined", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
|
||
this.audit(playerId, "trade_declined", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id });
|
||
});
|
||
return this.getState(playerId);
|
||
}
|
||
|
||
cancelTransfer(playerId, transferId) {
|
||
this.database.transaction(() => {
|
||
this.expireTransfers();
|
||
const transfer = this.openTrade(transferId);
|
||
if (transfer.initiator_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible.");
|
||
this.db.prepare("UPDATE transfers SET status = 'cancelled' WHERE id = ?").run(transferId);
|
||
this.audit(playerId, "trade_cancelled", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
|
||
this.audit(transfer.recipient_id, "trade_cancelled", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id });
|
||
});
|
||
return this.getState(playerId);
|
||
}
|
||
|
||
// Toutes les campagnes, ou une seule si `campaignId` est donné.
|
||
campaignSummaries(campaignId = null) {
|
||
return this.db.prepare(`SELECT c.*, (SELECT COUNT(*) FROM campaign_claims cl WHERE cl.campaign_id = c.id) AS claimed_count
|
||
FROM campaigns c WHERE ? IS NULL OR c.id = ? ORDER BY c.created_at DESC`).all(campaignId, campaignId).map((row) => ({
|
||
id: row.id,
|
||
name: row.name,
|
||
code: row.code,
|
||
reward: JSON.parse(row.reward_json),
|
||
maxClaims: row.max_claims,
|
||
claimedCount: row.claimed_count,
|
||
createdAt: row.created_at,
|
||
expiresAt: row.expires_at,
|
||
revokedAt: row.revoked_at
|
||
}));
|
||
}
|
||
|
||
// Une campagne = un code lisible, partagé entre les joueurs, chacun ne l'utilisant qu'une fois.
|
||
// `maxClaims` null = utilisations illimitées ; `expiresAt` null = sans date d'expiration.
|
||
createCampaign(playerId, { name, reward, code: rawCode, maxClaims, expiresAt } = {}) {
|
||
this.requireAdmin(playerId);
|
||
const normalized = normalizeReward(reward, this.catalog);
|
||
if (!name?.trim() || name.trim().length > 80) fail(400, "CAMPAIGN_INVALID", "Donnez un nom de 1 à 80 caractères à la campagne.");
|
||
const code = String(rawCode || "").trim().toUpperCase();
|
||
// Un code court se devine : les anciens restent utilisables, seuls les nouveaux sont concernés.
|
||
if (!/^[A-Z0-9][A-Z0-9-]{7,23}$/.test(code)) fail(400, "CAMPAIGN_INVALID", "Code : 8 à 24 caractères, lettres, chiffres et tirets.");
|
||
const limit = maxClaims == null ? null : Number(maxClaims);
|
||
if (limit !== null && (!Number.isInteger(limit) || limit < 1 || limit > 100_000)) fail(400, "CAMPAIGN_INVALID", "Entre 1 et 100 000 utilisations, ou illimité.");
|
||
const expiry = this.campaignExpiry(expiresAt);
|
||
if (this.db.prepare("SELECT 1 FROM campaigns WHERE code = ?").get(code)) fail(409, "CODE_TAKEN", "Ce code est déjà utilisé par une autre campagne.");
|
||
const campaignId = randomUUID();
|
||
this.database.transaction(() => {
|
||
this.db.prepare(`INSERT INTO campaigns(id, name, code, reward_json, max_claims, created_by, created_at, expires_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(campaignId, name.trim(), code, JSON.stringify(normalized), limit, playerId, this.now(), expiry);
|
||
this.audit(playerId, "campaign_created", campaignId, { code, reward: normalized, maxClaims: limit });
|
||
});
|
||
return { campaign: this.campaignSummary(campaignId) };
|
||
}
|
||
|
||
campaignSummary(campaignId) {
|
||
const [campaign] = this.campaignSummaries(campaignId);
|
||
if (!campaign) fail(404, "CAMPAIGN_NOT_FOUND", "Campagne introuvable.");
|
||
return campaign;
|
||
}
|
||
|
||
campaignDetail(playerId, campaignId) {
|
||
this.requireAdmin(playerId);
|
||
const campaign = this.campaignSummary(campaignId);
|
||
const claims = this.db.prepare(`SELECT cl.claimed_at, p.display_name FROM campaign_claims cl JOIN players p ON p.id = cl.player_id
|
||
WHERE cl.campaign_id = ? ORDER BY cl.claimed_at, cl.rowid`).all(campaignId).map((row) => ({ playerName: row.display_name, claimedAt: row.claimed_at }));
|
||
return { campaign, claims };
|
||
}
|
||
|
||
revokeCampaign(playerId, campaignId) {
|
||
this.requireAdmin(playerId);
|
||
this.database.transaction(() => {
|
||
this.campaignSummary(campaignId);
|
||
this.db.prepare("UPDATE campaigns SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").run(this.now(), campaignId);
|
||
this.audit(playerId, "campaign_revoked", campaignId, {});
|
||
});
|
||
return { campaign: this.campaignSummary(campaignId) };
|
||
}
|
||
|
||
// Date d'expiration d'une campagne : null (sans expiration) ou un instant futur.
|
||
campaignExpiry(expiresAt) {
|
||
if (expiresAt == null) return null;
|
||
const expiry = Number(expiresAt);
|
||
if (!Number.isFinite(expiry) || expiry <= this.now()) fail(400, "CAMPAIGN_INVALID", "La date d’expiration doit être dans le futur.");
|
||
return expiry;
|
||
}
|
||
|
||
extendCampaign(playerId, campaignId, expiresAt) {
|
||
this.requireAdmin(playerId);
|
||
const expiry = this.campaignExpiry(expiresAt);
|
||
const result = this.db.prepare("UPDATE campaigns SET expires_at = ? WHERE id = ? AND revoked_at IS NULL").run(expiry, campaignId);
|
||
if (!result.changes) fail(404, "CAMPAIGN_NOT_FOUND", "Campagne introuvable ou révoquée.");
|
||
this.audit(playerId, "campaign_extended", campaignId, { expiresAt: expiry });
|
||
return { campaign: this.campaignSummary(campaignId) };
|
||
}
|
||
|
||
claimCampaign(playerId, rawCode) {
|
||
const code = String(rawCode || "").trim().toUpperCase();
|
||
let reward;
|
||
this.database.transaction(() => {
|
||
const row = this.db.prepare("SELECT * FROM campaigns WHERE code = ?").get(code);
|
||
if (!row || row.revoked_at || (row.expires_at != null && row.expires_at <= this.now())) fail(404, "CODE_INVALID", "Code invalide, expiré ou révoqué.");
|
||
if (this.db.prepare("SELECT 1 FROM campaign_claims WHERE campaign_id = ? AND player_id = ?").get(row.id, playerId)) fail(409, "CAMPAIGN_ALREADY_CLAIMED", "Vous avez déjà reçu cette récompense.");
|
||
const used = row.max_claims != null && this.db.prepare("SELECT COUNT(*) AS count FROM campaign_claims WHERE campaign_id = ?").get(row.id).count >= row.max_claims;
|
||
if (used) fail(409, "CODE_EXHAUSTED", "Ce code a atteint son nombre maximal d’utilisations.");
|
||
reward = JSON.parse(row.reward_json);
|
||
for (const item of reward.items) {
|
||
for (let copy = 0; copy < item.quantity; copy += 1) {
|
||
if (item.type === "card") {
|
||
const edition = this.index.editions.get(item.editionId);
|
||
if (!edition) fail(409, "REWARD_UNAVAILABLE", "Une carte de cette récompense n’existe plus dans le catalogue.");
|
||
this.addCard(playerId, edition.id);
|
||
} else {
|
||
// Les campagnes créées avant packRates gardent null : leurs paquets suivent les taux en vigueur à l'ouverture.
|
||
const options = { rarityWeights: item.rarityWeights, packRates: item.packRates ?? null, guarantee: item.guarantee };
|
||
this.db.prepare("INSERT INTO gift_packs(id, player_id, campaign_id, collection_id, options_json, created_at) VALUES (?, ?, ?, ?, ?, ?)")
|
||
.run(randomUUID(), playerId, row.id, item.collectionId, JSON.stringify(options), this.now());
|
||
}
|
||
}
|
||
}
|
||
this.db.prepare("INSERT INTO campaign_claims(id, campaign_id, player_id, claimed_at) VALUES (?, ?, ?, ?)").run(randomUUID(), row.id, playerId, this.now());
|
||
this.audit(playerId, "campaign_claimed", row.id, { campaignName: row.name, reward });
|
||
});
|
||
return { reward, state: this.getState(playerId) };
|
||
}
|
||
|
||
audit(playerId, eventType, entityId, details) {
|
||
this.db.prepare("INSERT INTO audit_log(player_id, event_type, entity_id, details_json, created_at) VALUES (?, ?, ?, ?, ?)")
|
||
.run(playerId, eventType, entityId, JSON.stringify(details), this.now());
|
||
}
|
||
}
|