sokko-g/services/cards/service.js
Shinuwa 320498d878 Send opt-in Discord alerts for Sokko TCG Expeditions through palico-bot
- Players turn on alerts one by one in their account: someone opens an expedition group, or one of their expeditions returns; both stay off until chosen.
- Opening a group queues a direct message for each other subscribed player; every 30 seconds the server queues returned expeditions once and sends pending messages to palico-bot's direct message route.
- Permanent refusals (unknown account, closed direct messages) or five failures stop retries; only real Discord accounts receive alerts, and sent rows are purged after 30 days.
- CARDS_DISCORD_ALERTS_URL and CARDS_DISCORD_ALERTS_KEY enable the feature; Administration › Guilde can turn every alert off, and the privacy notice explains what is sent.

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

1077 lines
67 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 serveur de propriété, paquets, transferts et distributions Sokko TCG.
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { normalizeReward } from "./rewards.js";
import { planRecycling, spareQuantity, validateShopSetting } from "./stardust.js";
import { FULL_ART_FORMAT, buildPublishedCatalog, createCatalogIndex, holographicFinishIds, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
import { computeStreak, DAILY_REPEAT_WINDOW_DAYS, dailyDayKey, dailyZoom, drawDailyPuzzle, guessHint, isDayKey, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "./daily.js";
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, 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";
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"
]);
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;
this.random = random;
this.reloadCatalog();
this.expeditions = new ExpeditionService(this, destinations || loadExpeditionDestinations(DEFAULT_DESTINATIONS_PATH, catalog), alerts);
}
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.
updateRechargeSetting(playerId, { intervalMs } = {}) {
this.requireAdmin(playerId);
if (!Number.isInteger(intervalMs) || intervalMs < MIN_RECHARGE_INTERVAL_MS || intervalMs > MAX_RECHARGE_INTERVAL_MS || intervalMs % MIN_RECHARGE_INTERVAL_MS !== 0) {
fail(400, "RECHARGE_INTERVAL_INVALID", "Délai invalide : un nombre entier de minutes, entre 1 minute et 7 jours.");
}
const current = this.rechargeSetting;
if (current.intervalMs === intervalMs) fail(409, "RECHARGE_UNCHANGED", "Ce délai est déjà en vigueur.");
this.database.transaction(() => {
this.db.prepare("UPDATE recharge_settings SET interval_ms = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(intervalMs, this.now(), playerId);
this.audit(playerId, "recharge_updated", "recharge", { previousIntervalMs: current.intervalMs, intervalMs });
});
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) && row.editionId === mythicEditionId(row.cardId, row.finishId));
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();
for (const finishId of holographic) {
const editionId = mythicEditionId(cardId, finishId);
const row = this.db.prepare("SELECT status FROM mythic_variations WHERE edition_id = ?").get(editionId);
if (wanted.has(finishId)) {
if (row?.status !== "active") {
this.db.prepare(`INSERT INTO mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by) VALUES (?, ?, ?, 'active', ?, ?)
ON CONFLICT(edition_id) DO UPDATE SET status = 'active', updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(editionId, cardId, finishId, now, playerId);
}
} else if (row && (this.editionReferenced(editionId) || campaignCounts[editionId] > 0)) {
if (row.status !== "retired") this.db.prepare("UPDATE mythic_variations SET status = 'retired', updated_at = ?, updated_by = ? WHERE edition_id = ?").run(now, playerId, editionId);
} else if (row) {
this.db.prepare("DELETE FROM mythic_variations WHERE edition_id = ?").run(editionId);
}
}
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) };
}
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 (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 recharge = (pinned ? pinnedRecharge : calculateRecharge)({
openingsBalance: player.openings_balance,
rechargeAnchor: player.recharge_anchor
}, this.now(), this.rechargeSetting);
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);
return recharge;
}
// 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;
}
addCard(playerId, editionId) {
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());
}
// 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) {
// 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 },
shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare, dailyReward: shop.dailyReward },
daily: this.dailySummary(playerId),
expeditions: this.expeditions.summary(playerId),
cardProgress: this.expeditions.cardProgressView(playerId),
equipment: this.expeditions.equipmentChoices(playerId),
alerts: this.expeditions.alertPreferences(playerId),
recycling: { count: recycling.count, stardust: recycling.stardust },
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();
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(),
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, editionIds) {
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;
}
// 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, () => {
if (this.catalog.collections.find((item) => item.id === collectionId)?.packCategory === "shop") fail(409, "SHOP_PACK_ONLY", "Ce paquet ne s’obtient que dans la boutique.");
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 editionIds = drawPack(this.catalog, collectionId, this.random);
const openingId = this.insertOpening(playerId, collectionId, editionIds);
this.audit(playerId, "pack_opened", openingId, { collectionId, cards: editionIds, ...(purchased ? { purchased: true } : {}) });
return openingId;
});
}
recyclingPlan(collection, editionId = null) {
return planRecycling(collection, { editionId, rarityOf: (id) => this.index.editions.get(id)?.rarity, stardustValues: this.shopSetting.stardustValues });
}
// Recycle tous les doublons disponibles, ou un seul doublon de `editionId` ; un exemplaire de chaque carte reste toujours.
recycleDuplicates(playerId, { editionId = null } = {}) {
if (editionId != null && !this.index.editions.has(editionId)) fail(404, "EDITION_NOT_FOUND", "Édition introuvable.");
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);
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) });
});
return { recycled: { count: plan.count, stardust: plan.stardust }, state: this.getState(playerId) };
}
buyOpening(playerId) {
const { openingPrice } = this.shopSetting;
this.database.transaction(() => {
const bought = this.db.prepare("UPDATE players SET stardust = stardust - ?, purchased_openings = purchased_openings + 1 WHERE id = ? AND stardust >= ?").run(openingPrice, playerId, openingPrice);
if (!bought.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles.");
this.audit(playerId, "opening_purchased", "shop", { price: openingPrice });
});
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 editionIds = drawShopPack(this.catalog, collection.id, this.random, shopPackShare);
const openingId = this.insertOpening(playerId, collection.id, editionIds);
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 editionIds = drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights, guarantee: options.guarantee, requireActive: false });
const openingId = this.insertOpening(playerId, gift.collection_id, editionIds);
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 : une carte commune à tous les joueurs, tirée au premier appel du jour de Paris puis gardée en base.
// À appeler dans une transaction : deux premiers appels simultanés ne tirent qu'une carte.
ensureDailyPuzzle(day) {
const stored = () => this.db.prepare("SELECT day, card_id, focus_x, focus_y FROM daily_puzzles WHERE day = ?").get(day);
if (!stored()) {
const recent = this.db.prepare("SELECT card_id FROM daily_puzzles WHERE day >= ?").all(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_puzzles(day, card_id, focus_x, focus_y, created_at) VALUES (?, ?, ?, ?, ?)").run(day, drawn.cardId, drawn.focusX, drawn.focusY, this.now());
}
const row = stored();
// 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.");
const number = this.db.prepare("SELECT COUNT(*) AS count FROM daily_puzzles WHERE day <= ?").get(day).count;
return { day: row.day, cardId: row.card_id, focus: { x: row.focus_x, y: row.focus_y }, number };
}
todayPuzzle() {
return this.database.transaction(() => this.ensureDailyPuzzle(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];
}
dailyAttempt(playerId, day) {
const row = this.db.prepare("SELECT guesses_json, status, reward FROM daily_attempts WHERE player_id = ? AND day = ?").get(playerId, day);
return { guesses: row ? JSON.parse(row.guesses_json) : [], status: row?.status || "playing", earned: row?.reward ?? 0 };
}
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);
}
// La réponse n'est envoyée qu'une fois la partie terminée.
dailyView(playerId, puzzle) {
const { guesses, status, earned } = this.dailyAttempt(playerId, puzzle.day);
const finished = status !== "playing";
return {
day: puzzle.day,
number: puzzle.number,
maxGuesses: MAX_DAILY_GUESSES,
focus: puzzle.focus,
zoom: dailyZoom(guesses.length - (status === "won" ? 1 : 0), finished),
status,
guesses: guesses.map((cardId) => guessHint(this.catalog, puzzle.cardId, cardId)),
collectionIds: this.dailyCollectionIds(playerId, puzzle.cardId),
reward: this.shopSetting.dailyReward,
earned,
streak: this.dailyStreak(playerId, puzzle.day),
nextAt: nextDailyAt(this.now()),
answerCardId: finished ? puzzle.cardId : null
};
}
getDaily(playerId) {
return this.dailyView(playerId, this.todayPuzzle());
}
// Résumé pour le tableau de bord du joueur ; l'état reste lisible si aucune carte ne peut être tirée.
dailySummary(playerId) {
try {
const puzzle = this.todayPuzzle();
const { guesses, status } = this.dailyAttempt(playerId, puzzle.day);
return { day: puzzle.day, number: puzzle.number, status, guessCount: guesses.length, maxGuesses: MAX_DAILY_GUESSES, streak: this.dailyStreak(playerId, puzzle.day) };
} catch (error) {
if (error.code === "DAILY_UNAVAILABLE") return null;
throw error;
}
}
// 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(today);
const attempt = this.dailyAttempt(playerId, today);
if (attempt.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 (attempt.guesses.includes(cardId)) fail(409, "DAILY_GUESS_REPEATED", "Vous avez déjà proposé cette carte.");
const guesses = [...attempt.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(`INSERT INTO daily_attempts(player_id, day, guesses_json, status, reward, updated_at) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(player_id, day) DO UPDATE SET guesses_json = excluded.guesses_json, status = excluded.status, reward = excluded.reward, updated_at = excluded.updated_at`)
.run(playerId, today, JSON.stringify(guesses), status, reward, this.now());
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);
});
// 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) };
}
// Illustration de la carte du jour, servie par l'API sous une adresse qui ne révèle pas la carte.
dailyImage() {
return this.index.cards.get(this.todayPuzzle().cardId).image;
}
dailyAdminSummary() {
try {
const puzzle = this.todayPuzzle();
const counts = this.db.prepare("SELECT COUNT(*) AS players, COALESCE(SUM(status = 'won'), 0) AS winners FROM daily_attempts WHERE day = ?").get(puzzle.day);
return { day: puzzle.day, number: puzzle.number, cardId: puzzle.cardId, players: counts.players, winners: counts.winners };
} catch (error) {
if (error.code === "DAILY_UNAVAILABLE") return null;
throw error;
}
}
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);
for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts", "card_progress", "card_equipment", "grimoire_entries"]) 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);
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 {
const options = { rarityWeights: item.rarityWeights, 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());
}
}