// Rôle : encapsule la base SQLite et les migrations du mini-jeu Sokko TCG. import { mkdirSync } from "node:fs"; import { dirname } from "node:path"; import { DatabaseSync } from "node:sqlite"; import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "./admin-seed.js"; import { DEFAULT_EXPEDITION_SETTINGS } from "./expedition-settings.js"; const MIGRATIONS = [ ` CREATE TABLE players ( id TEXT PRIMARY KEY, discord_id TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, avatar_url TEXT NOT NULL DEFAULT '', is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)), created_at INTEGER NOT NULL, openings_balance INTEGER NOT NULL DEFAULT 1 CHECK (openings_balance BETWEEN 0 AND 5), recharge_anchor INTEGER, stardust INTEGER NOT NULL DEFAULT 0 CHECK (stardust >= 0), purchased_openings INTEGER NOT NULL DEFAULT 0 CHECK (purchased_openings >= 0) ) STRICT; CREATE TABLE sessions ( token_hash TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, csrf_token TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ) STRICT; CREATE INDEX sessions_player_idx ON sessions(player_id); CREATE TABLE openings ( id TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id), collection_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'completed')), created_at INTEGER NOT NULL, completed_at INTEGER ) STRICT; CREATE INDEX openings_player_idx ON openings(player_id, created_at DESC); -- Collection : une ligne par carte possédée, avec sa quantité. Un joueur garde toujours au moins un exemplaire de -- chaque carte obtenue (seuls les doublons s'échangent, se donnent ou se recyclent) : une ligne n'est jamais supprimée. CREATE TABLE collection_cards ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, edition_id TEXT NOT NULL, quantity INTEGER NOT NULL CHECK (quantity >= 1), acquired_at INTEGER NOT NULL, PRIMARY KEY (player_id, edition_id) ) STRICT; CREATE TABLE opening_cards ( opening_id TEXT NOT NULL REFERENCES openings(id) ON DELETE CASCADE, position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 2), edition_id TEXT NOT NULL, was_new_card INTEGER NOT NULL CHECK (was_new_card IN (0, 1)), was_new_edition INTEGER NOT NULL CHECK (was_new_edition IN (0, 1)), quantity_before INTEGER NOT NULL, PRIMARY KEY (opening_id, position) ) STRICT; CREATE TABLE favorites ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, edition_id TEXT NOT NULL, PRIMARY KEY (player_id, edition_id) ) STRICT; CREATE TABLE transfers ( id TEXT PRIMARY KEY, code TEXT NOT NULL UNIQUE, type TEXT NOT NULL CHECK (type IN ('trade', 'gift')), initiator_id TEXT NOT NULL REFERENCES players(id), recipient_id TEXT REFERENCES players(id), offered_edition_id TEXT NOT NULL, requested_edition_id TEXT, initiator_confirmed INTEGER NOT NULL DEFAULT 0 CHECK (initiator_confirmed IN (0, 1)), recipient_confirmed INTEGER NOT NULL DEFAULT 0 CHECK (recipient_confirmed IN (0, 1)), status TEXT NOT NULL CHECK (status IN ('open', 'joined', 'completed', 'cancelled', 'expired')), created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, completed_at INTEGER ) STRICT; CREATE INDEX transfers_participants_idx ON transfers(initiator_id, recipient_id, status); -- Un transfert en cours (open, joined) réserve un doublon de chaque carte engagée. CREATE TABLE campaigns ( id TEXT PRIMARY KEY, name TEXT NOT NULL, code TEXT NOT NULL UNIQUE, reward_json TEXT NOT NULL, max_claims INTEGER CHECK (max_claims IS NULL OR max_claims > 0), created_by TEXT NOT NULL REFERENCES players(id), created_at INTEGER NOT NULL, expires_at INTEGER, revoked_at INTEGER ) STRICT; CREATE TABLE campaign_claims ( id TEXT PRIMARY KEY, campaign_id TEXT NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, player_id TEXT NOT NULL REFERENCES players(id), claimed_at INTEGER NOT NULL, UNIQUE (campaign_id, player_id) ) STRICT; CREATE TABLE gift_packs ( id TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id), campaign_id TEXT NOT NULL REFERENCES campaigns(id), collection_id TEXT NOT NULL, options_json TEXT NOT NULL, created_at INTEGER NOT NULL, opening_id TEXT REFERENCES openings(id), opened_at INTEGER ) STRICT; CREATE INDEX gift_packs_player_idx ON gift_packs(player_id, opened_at); CREATE TABLE idempotency ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, scope TEXT NOT NULL, request_key TEXT NOT NULL, response_json TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (player_id, scope, request_key) ) STRICT; CREATE TABLE audit_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, player_id TEXT REFERENCES players(id), event_type TEXT NOT NULL, entity_id TEXT NOT NULL, details_json TEXT NOT NULL, created_at INTEGER NOT NULL ) STRICT; CREATE INDEX audit_player_idx ON audit_log(player_id, created_at DESC); `, // Contenu géré depuis l'administration : variations mythiques, réglages d'ouverture, état des paquets, // tables de tirage, recharge des ouvertures et boutique (barème de poussière d'étoiles, prix d'une ouverture). Ces données n'existent qu'ici ; la migration insère le contenu de départ (admin-seed.js). ` CREATE INDEX collection_cards_edition_idx ON collection_cards(edition_id); CREATE INDEX opening_cards_edition_idx ON opening_cards(edition_id); CREATE TABLE mythic_variations ( edition_id TEXT PRIMARY KEY, card_id TEXT NOT NULL, finish_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('active', 'retired')), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; CREATE TABLE mythic_opening_settings ( scope TEXT NOT NULL CHECK (scope IN ('collection', 'card')), target_id TEXT NOT NULL, particle_shape_id TEXT, particle_palette_id TEXT, updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id), PRIMARY KEY (scope, target_id) ) STRICT; CREATE TABLE collection_states ( collection_id TEXT PRIMARY KEY, active INTEGER NOT NULL CHECK (active IN (0, 1)), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; CREATE TABLE drop_rates ( collection_id TEXT PRIMARY KEY, rarity_weights_json TEXT NOT NULL, updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; CREATE TABLE recharge_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), interval_ms INTEGER NOT NULL CHECK (interval_ms >= 60000), max_openings INTEGER NOT NULL CHECK (max_openings BETWEEN 1 AND 5), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; CREATE TABLE shop_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), stardust_values_json TEXT NOT NULL, opening_price INTEGER NOT NULL CHECK (opening_price > 0), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; INSERT INTO shop_settings(id, stardust_values_json, opening_price, updated_at, updated_by) VALUES (1, '${JSON.stringify(INITIAL_SHOP_SETTING.stardustValues)}', ${INITIAL_SHOP_SETTING.openingPrice}, 0, NULL); INSERT INTO recharge_settings(id, interval_ms, max_openings, updated_at, updated_by) VALUES (1, ${INITIAL_RECHARGE_SETTING.intervalMs}, ${INITIAL_RECHARGE_SETTING.maxOpenings}, 0, NULL); ${INITIAL_COLLECTION_STATES.map(({ collectionId, active }) => `INSERT INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('${collectionId}', ${active ? 1 : 0}, 0, NULL);`).join("\n ")} ${INITIAL_DROP_RATES.map(({ collectionId, rarityWeights }) => `INSERT INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('${collectionId}', '${JSON.stringify(rarityWeights)}', 0, NULL);`).join("\n ")} `, // Propositions directes : plus de code à rejoindre. Les transferts en cours de l'ancien système sont annulés, // ce qui libère leurs doublons réservés. Les anciens statuts et colonnes restent pour relire l'historique. ` ALTER TABLE transfers ADD COLUMN declined INTEGER NOT NULL DEFAULT 0 CHECK (declined IN (0, 1)); UPDATE transfers SET status = 'cancelled' WHERE status IN ('open', 'joined'); `, // Paquet de la Boutique : la collection stardust s'ouvre avec les poids recommandés ; prix et part de ses cartes se règlent dans l'administration. ` ALTER TABLE shop_settings ADD COLUMN shop_pack_price INTEGER NOT NULL DEFAULT 60 CHECK (shop_pack_price >= 1); ALTER TABLE shop_settings ADD COLUMN shop_pack_share INTEGER NOT NULL DEFAULT 50 CHECK (shop_pack_share BETWEEN 0 AND 100); INSERT OR IGNORE INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('stardust', 1, 0, NULL); INSERT OR IGNORE INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('stardust', '{"common":64,"rare":24,"epic":8,"legendary":3,"mythic":1}', 0, NULL); `, // Suppression de compte : la ligne du joueur reste, anonymisée, car les ouvertures, échanges et journaux y font référence. ` ALTER TABLE players ADD COLUMN deleted_at INTEGER; `, // Dernière connexion Discord : un compte resté 24 mois sans connexion est anonymisé (runMaintenance). ` ALTER TABLE players ADD COLUMN last_login_at INTEGER; UPDATE players SET last_login_at = created_at; `, // Carte du jour : une carte commune à tous les joueurs par jour de Paris, la partie de chaque joueur et la récompense // d'une victoire, réglée avec la boutique. ` ALTER TABLE shop_settings ADD COLUMN daily_reward INTEGER NOT NULL DEFAULT 10 CHECK (daily_reward BETWEEN 0 AND 100000); CREATE TABLE daily_puzzles ( day TEXT PRIMARY KEY, card_id TEXT NOT NULL, focus_x INTEGER NOT NULL CHECK (focus_x BETWEEN 0 AND 100), focus_y INTEGER NOT NULL CHECK (focus_y BETWEEN 0 AND 100), created_at INTEGER NOT NULL ) STRICT; -- guesses_json : identifiants des cartes proposées, dans l'ordre ; reward : poussière créditée par la victoire. CREATE TABLE daily_attempts ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, day TEXT NOT NULL REFERENCES daily_puzzles(day), guesses_json TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('playing', 'won', 'lost')), reward INTEGER NOT NULL DEFAULT 0 CHECK (reward >= 0), updated_at INTEGER NOT NULL, PRIMARY KEY (player_id, day) ) STRICT; CREATE INDEX daily_attempts_day_idx ON daily_attempts(day, status); `, // Expéditions : Éclats d'étoile, réglages (un JSON validé par expedition-settings.js, Expéditions fermées au départ), destinations du jour, // expéditions, participants et places. Les CHECK prévoient déjà le groupe (mode, inscription, 5 ★, 4 places, rôles). // gift_packs est reconstruite : un paquet offert vient d'une campagne ou d'une expédition. ` ALTER TABLE players ADD COLUMN eclats INTEGER NOT NULL DEFAULT 0 CHECK (eclats >= 0); CREATE TABLE expedition_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), settings_json TEXT NOT NULL CHECK (json_valid(settings_json)), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; INSERT INTO expedition_settings(id, settings_json, updated_at, updated_by) VALUES (1, '${JSON.stringify(DEFAULT_EXPEDITION_SETTINGS)}', 0, NULL); -- draw_json : destinations tirées (identifiant, condition et dangers) ; les exigences chiffrées sont calculées à la lecture. CREATE TABLE expedition_days ( day TEXT PRIMARY KEY, draw_json TEXT NOT NULL CHECK (json_valid(draw_json)), created_at INTEGER NOT NULL ) STRICT; -- setup_json fige la destination, les exigences et les réglages du départ ; result_json n'est montré qu'au retour. CREATE TABLE expeditions ( id TEXT PRIMARY KEY, mode TEXT NOT NULL CHECK (mode IN ('solo', 'group')), day TEXT NOT NULL REFERENCES expedition_days(day), destination_id TEXT NOT NULL, difficulty INTEGER NOT NULL CHECK (difficulty BETWEEN 1 AND 5), duration_ms INTEGER NOT NULL CHECK (duration_ms > 0), creator_id TEXT NOT NULL REFERENCES players(id), status TEXT NOT NULL CHECK (status IN ('forming', 'running', 'completed', 'cancelled')), setup_json TEXT NOT NULL CHECK (json_valid(setup_json)), result_json TEXT CHECK (result_json IS NULL OR json_valid(result_json)), created_at INTEGER NOT NULL, departs_at INTEGER, returns_at INTEGER, completed_at INTEGER ) STRICT; CREATE INDEX expeditions_status_idx ON expeditions(status, returns_at); CREATE INDEX expeditions_day_idx ON expeditions(day, creator_id); CREATE TABLE expedition_members ( expedition_id TEXT NOT NULL REFERENCES expeditions(id) ON DELETE CASCADE, player_id TEXT NOT NULL REFERENCES players(id), reward_json TEXT CHECK (reward_json IS NULL OR json_valid(reward_json)), joined_at INTEGER NOT NULL, claimed_at INTEGER, PRIMARY KEY (expedition_id, player_id) ) STRICT; CREATE INDEX expedition_members_player_idx ON expedition_members(player_id, claimed_at); -- player_id nul : place tenue par le Veilleur de la Guilde, sans carte ni rôle. CREATE TABLE expedition_slots ( expedition_id TEXT NOT NULL REFERENCES expeditions(id) ON DELETE CASCADE, position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 3), role TEXT CHECK (role IS NULL OR role IN ('leader', 'guardian', 'seeker', 'navigator')), player_id TEXT REFERENCES players(id), edition_id TEXT, card_id TEXT, level INTEGER NOT NULL DEFAULT 0 CHECK (level >= 0), stats_json TEXT NOT NULL CHECK (json_valid(stats_json)), PRIMARY KEY (expedition_id, position) ) STRICT; CREATE INDEX expedition_slots_player_idx ON expedition_slots(player_id, edition_id); CREATE TABLE gift_packs_next ( id TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id), source TEXT NOT NULL DEFAULT 'campaign' CHECK (source IN ('campaign', 'expedition')), campaign_id TEXT REFERENCES campaigns(id), expedition_id TEXT REFERENCES expeditions(id), collection_id TEXT NOT NULL, options_json TEXT NOT NULL, created_at INTEGER NOT NULL, opening_id TEXT REFERENCES openings(id), opened_at INTEGER, CHECK ((source = 'campaign' AND campaign_id IS NOT NULL) OR (source = 'expedition' AND expedition_id IS NOT NULL)) ) STRICT; INSERT INTO gift_packs_next(id, player_id, source, campaign_id, collection_id, options_json, created_at, opening_id, opened_at) SELECT id, player_id, 'campaign', campaign_id, collection_id, options_json, created_at, opening_id, opened_at FROM gift_packs; DROP TABLE gift_packs; ALTER TABLE gift_packs_next RENAME TO gift_packs; CREATE INDEX gift_packs_player_idx ON gift_packs(player_id, opened_at); `, // Améliorations des Expéditions : niveau et expérience de terrain (en % du niveau suivant) de chaque édition possédée par un joueur. // La progression suit l'exemplaire gardé : seuls les doublons quittent une collection. ` CREATE TABLE card_progress ( player_id TEXT NOT NULL REFERENCES players(id), edition_id TEXT NOT NULL, level INTEGER NOT NULL DEFAULT 0 CHECK (level >= 0), field_xp INTEGER NOT NULL DEFAULT 0 CHECK (field_xp BETWEEN 0 AND 99), updated_at INTEGER NOT NULL, PRIMARY KEY (player_id, edition_id) ) STRICT; `, // Équipements et Grimoire des Expéditions : une commune possédée est posée sur un seul emplacement d'une carte à la fois // (l'exemplaire gardé, jamais détruit) ; le Grimoire garde les paires et Résonances découvertes par chaque joueur. ` CREATE TABLE card_equipment ( player_id TEXT NOT NULL REFERENCES players(id), edition_id TEXT NOT NULL, slot INTEGER NOT NULL CHECK (slot BETWEEN 0 AND 2), equipment_edition_id TEXT NOT NULL, equipped_at INTEGER NOT NULL, PRIMARY KEY (player_id, edition_id, slot), UNIQUE (player_id, equipment_edition_id) ) STRICT; CREATE TABLE grimoire_entries ( player_id TEXT NOT NULL REFERENCES players(id), entry_id TEXT NOT NULL, discovered_at INTEGER NOT NULL, PRIMARY KEY (player_id, entry_id) ) STRICT; `, // Alertes Discord des Expéditions : choix de chaque joueur (désactivées tant qu'il ne les active pas), file des messages // privés à envoyer par le bot, et marque des retours déjà annoncés. ` CREATE TABLE player_alerts ( player_id TEXT PRIMARY KEY REFERENCES players(id), group_opened INTEGER NOT NULL DEFAULT 0 CHECK (group_opened IN (0, 1)), expedition_returned INTEGER NOT NULL DEFAULT 0 CHECK (expedition_returned IN (0, 1)), updated_at INTEGER NOT NULL ) STRICT; CREATE TABLE alert_outbox ( id TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id), kind TEXT NOT NULL CHECK (kind IN ('group_opened', 'expedition_returned')), content TEXT NOT NULL, created_at INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, sent_at INTEGER, failed_at INTEGER, last_error TEXT ) STRICT; CREATE INDEX alert_outbox_pending_idx ON alert_outbox(sent_at, failed_at, created_at); ALTER TABLE expedition_members ADD COLUMN alerted_at INTEGER; `, // Objets des Expéditions : inventaire de chaque joueur, gravures posées sur ses équipements (une par commune) et destinations // bonus ajoutées à sa journée (5e, 6e, ou une destination cachée ouverte par une carte au trésor). ` CREATE TABLE player_items ( player_id TEXT NOT NULL REFERENCES players(id), item_id TEXT NOT NULL, quantity INTEGER NOT NULL CHECK (quantity >= 0), PRIMARY KEY (player_id, item_id) ) STRICT; CREATE TABLE equipment_engravings ( player_id TEXT NOT NULL REFERENCES players(id), edition_id TEXT NOT NULL, tag TEXT NOT NULL, engraved_at INTEGER NOT NULL, PRIMARY KEY (player_id, edition_id) ) STRICT; CREATE TABLE player_bonus_destinations ( player_id TEXT NOT NULL REFERENCES players(id), day TEXT NOT NULL, slot TEXT NOT NULL CHECK (slot IN ('5', '6', 'hidden')), destination_id TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (player_id, day, slot) ) STRICT; ` ]; export class CardsDatabase { constructor(path) { if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true }); this.db = new DatabaseSync(path); this.db.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"); this.migrate(); } migrate() { this.db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at INTEGER NOT NULL) STRICT;"); const applied = new Set(this.db.prepare("SELECT version FROM schema_migrations").all().map((row) => row.version)); MIGRATIONS.forEach((sql, index) => { const version = index + 1; if (applied.has(version)) return; this.transaction(() => { this.db.exec(sql); this.db.prepare("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)").run(version, Date.now()); }); }); } transaction(callback) { this.db.exec("BEGIN IMMEDIATE"); try { const result = callback(); this.db.exec("COMMIT"); return result; } catch (error) { this.db.exec("ROLLBACK"); throw error; } } close() { this.db.close(); } }