Add the server-backed card game: Discord login, recharging pack openings, album, trades, gifts, stardust shop, campaign codes and its administration, stored in SQLite and disabled in production until configured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
229 lines
10 KiB
JavaScript
229 lines
10 KiB
JavaScript
// 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";
|
|
|
|
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);
|
|
`
|
|
];
|
|
|
|
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();
|
|
}
|
|
}
|