sokko-g/services/cards/team-service.js
Shinuwa 22b397ebfa Document Sokko G's architecture and folders, and move JavaScript file headers to JSDoc @file blocks
Add ARCHITECTURE.md (layers, flows, folder map, glossary), CONTRIBUTING.md
(setup and step-by-step recipes) and a README in each main folder, with an
index of docs/. Convert the 511 JavaScript headers from "// Rôle :" lines to
JSDoc @file blocks, define a three-level header template in website/AGENTS.md
and check the header in tests/file-headers.test.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:42:13 +01:00

289 lines
16 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.

/**
* @file Applique les règles de l'Équipe du jour avec la base (parcours du jour, recrutement, étoiles en
* réserve, réglages).
*
* Branché sur CardsService (`service.team`) : il réutilise sa base, son horloge, son hasard, son audit et sa
* collection.
*/
import { dailyDayKey, isDayKey, nextDailyAt, shiftDayKey } from "./daily.js";
import { drawZones } from "./race-rules.js";
import {
canRevealStar, chooseCharacter, companionStats, healCompanion, hiddenStars, keepCompanion, MAX_GOLD_RESERVE, recruitmentFinished, repairRecruitment, rerollOffer, revealStar, specialtiesOf,
startRecruitment, TEAM_DAYS, TEAM_SIZE, teamCharacters, teamDay, visibleSky
} from "./team-rules.js";
import { raceMethods } from "./team-race.js";
import { dailyTeamSettingsError, DEFAULT_DAILY_TEAM_SETTINGS, normalizeDailyTeamSettings, readDailyTeamSettings } from "./team-settings.js";
function fail(status, code, message) {
throw Object.assign(new Error(message), { status, code });
}
export class TeamService {
constructor(cards) {
this.cards = cards;
this.db = cards.db;
this.random = (max) => cards.random(max);
}
get today() {
return dailyDayKey(this.cards.now());
}
// --- Réglages -----------------------------------------------------------------------------------------------------------
get settings() {
const row = this.db.prepare("SELECT settings_json FROM team_settings WHERE id = 1").get();
return readDailyTeamSettings(JSON.parse(row?.settings_json || "{}"), (error) => console.error(`Invalid stored team settings, using defaults: ${error}`));
}
// Activité du jour : équipes utilisables, courses lancées et étoiles dorées choisies à la Carte du jour.
adminSummary() {
const day = this.today;
const count = (sql, ...values) => this.db.prepare(sql).get(...values).count;
return {
teams: count("SELECT COUNT(*) AS count FROM player_teams WHERE ready_day BETWEEN ? AND ?", shiftDayKey(day, 1 - TEAM_DAYS), day),
races: count("SELECT COUNT(*) AS count FROM team_races WHERE day = ?", day),
stars: count("SELECT COUNT(*) AS count FROM daily_attempts WHERE day = ? AND reward_choice = 'star'", day)
};
}
adminSettings() {
return { today: this.adminSummary(), race: this.raceAdminSummary(), settings: this.settings, defaults: normalizeDailyTeamSettings(DEFAULT_DAILY_TEAM_SETTINGS), updatedAt: this.db.prepare("SELECT updated_at FROM team_settings WHERE id = 1").get()?.updated_at ?? 0 };
}
// Un recrutement commencé garde les réglages de son début (voir startRecruitment).
updateSettings(adminId, settings) {
this.cards.requireAdmin(adminId);
const error = dailyTeamSettingsError(settings);
if (error) fail(400, "TEAM_SETTINGS_INVALID", error);
const previous = this.settings;
const next = normalizeDailyTeamSettings(settings);
if (JSON.stringify(previous) === JSON.stringify(next)) fail(409, "TEAM_SETTINGS_UNCHANGED", "Ces réglages sont déjà en vigueur.");
this.cards.database.transaction(() => {
this.db.prepare("UPDATE team_settings SET settings_json = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(JSON.stringify(next), this.cards.now(), adminId);
this.cards.audit(adminId, "team_settings_updated", "team", { previous, next });
});
return { teamSettings: this.adminSettings() };
}
requireOpen() {
if (!this.settings.enabled) fail(409, "TEAM_CLOSED", "L’Équipe du jour est fermée pour le moment.");
}
// --- Lectures -----------------------------------------------------------------------------------------------------------
// Parcours de la Course, commun à tous les joueurs d'un jour. À appeler dans une transaction.
ensureZones(day) {
const read = () => this.db.prepare("SELECT zones_json FROM team_days WHERE day = ?").get(day);
if (!read()) this.db.prepare("INSERT INTO team_days(day, zones_json, created_at) VALUES (?, ?, ?)").run(day, JSON.stringify(drawZones(this.random)), this.cards.now());
return JSON.parse(read().zones_json);
}
goldStars(playerId) {
return this.db.prepare("SELECT gold_stars FROM players WHERE id = ?").get(playerId)?.gold_stars ?? 0;
}
teamRow(playerId) {
const row = this.db.prepare("SELECT started_day, ready_day, state_json FROM player_teams WHERE player_id = ?").get(playerId);
return row ? { startedDay: row.started_day, readyDay: row.ready_day, state: JSON.parse(row.state_json) } : null;
}
// L'équipe du joueur, son recrutement en cours réparé s'il cite une carte retirée du catalogue. À appeler dans une transaction.
repairedRow(playerId, { characters, owned }) {
const row = this.teamRow(playerId);
if (!row || row.readyDay) return row;
const state = repairRecruitment(characters, owned, row.state, this.random);
if (state !== row.state) this.saveState(playerId, state, null);
return { ...row, state };
}
saveState(playerId, state, readyDay) {
this.db.prepare("UPDATE player_teams SET ready_day = ?, state_json = ?, updated_at = ? WHERE player_id = ?").run(readyDay, JSON.stringify(state), this.cards.now(), playerId);
}
// Cartes que le joueur voit dans son album : celles d'un paquet pas encore révélé ne comptent pas.
ownedCardIds(playerId) {
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(playerId);
return new Set(this.cards.visibleCollection(playerId, pending?.id).map((entry) => this.cards.index.editions.get(entry.editionId)?.cardId).filter(Boolean));
}
// Équipe utilisable aujourd'hui : recrutement terminé et pas plus de TEAM_DAYS jours. `day` : son rang, de 1 à TEAM_DAYS.
activeTeam(playerId, day = this.today) {
const row = this.teamRow(playerId);
const rank = row?.readyDay ? teamDay(row.readyDay, day) : 0;
return rank ? { day: rank, companions: row.state.team } : null;
}
companionView({ cardId, profile, power, step = 0, fallen = false, healed = false, lent = false }) {
return { cardId, power, step, fallen, healed, lent, stats: companionStats(profile, power), specialties: specialtiesOf(profile) };
}
// Le client ne reçoit ni la place des étoiles cachées, ni les personnages suivants.
recruitmentView(playerId, state, characters, owned) {
const byId = new Map(characters.map((character) => [character.id, character]));
const preview = (cardId) => this.companionView({ cardId, profile: byId.get(cardId).profile, power: state.settings.powers[0], lent: !owned.has(cardId) });
return {
size: TEAM_SIZE, powers: state.settings.powers, fallPower: state.settings.fallPower, dustValue: state.settings.dustValue, extraGold: state.extraGold, dust: state.dust, rerolls: state.rerolls ?? 0, balms: this.cards.expeditions.itemsOf(playerId).balm,
offer: state.current ? [] : state.offer.map(preview),
current: state.current ? this.companionView({ ...state.current, profile: byId.get(state.current.cardId).profile, lent: !owned.has(state.current.cardId) }) : null,
// Stats du compagnon en cours à chaque palier de Puissance.
ladder: state.current ? state.settings.powers.map((power) => companionStats(byId.get(state.current.cardId).profile, power)) : [],
sky: visibleSky(state), hidden: hiddenStars(state)
};
}
view(playerId) {
const day = this.today;
const settings = this.settings;
const zones = this.cards.database.transaction(() => this.ensureZones(day));
const recruitable = { characters: teamCharacters(this.cards.catalog), owned: this.ownedCardIds(playerId) };
const row = this.cards.database.transaction(() => {
this.settleAbandonedRace(playerId);
return this.repairedRow(playerId, recruitable);
});
const recruiting = Boolean(row && !row.readyDay);
const rank = row?.readyDay ? teamDay(row.readyDay, day) : 0;
const base = {
enabled: settings.enabled, raceEnabled: settings.enabled && settings.raceEnabled, day, nextAt: nextDailyAt(this.cards.now()), zones, goldStars: this.goldStars(playerId), maxGoldStars: MAX_GOLD_RESERVE, maxDays: TEAM_DAYS,
// Baumes du Sac : ils soignent un compagnon affaibli pendant le recrutement.
balms: this.cards.expeditions.itemsOf(playerId).balm,
// Un recrutement par jour, et jamais deux à la fois.
canRecruit: settings.enabled && !recruiting && row?.startedDay !== day,
status: recruiting ? "recruiting" : rank ? "ready" : row ? "expired" : "none",
// Serveur Vite local : remise à zéro pour les essais.
devReset: Boolean(this.cards.devPerks),
teamDay: rank, companions: row ? row.state.team.map((companion) => this.companionView(companion)) : [], recruitment: null,
race: this.raceView(playerId)
};
if (!recruiting) return { ...base, lastSky: row ? visibleSky(row.state) : null, lastDust: row?.state.dust ?? 0 };
return { ...base, recruitment: this.recruitmentView(playerId, row.state, recruitable.characters, recruitable.owned) };
}
// Résumé pour le tableau de bord et la Guilde, sans rien tirer.
summary(playerId) {
const row = this.teamRow(playerId);
const rank = row?.readyDay ? teamDay(row.readyDay, this.today) : 0;
const race = this.runningRace(playerId) || this.raceRow(playerId, this.today);
return { enabled: this.settings.enabled, raceEnabled: this.settings.enabled && this.settings.raceEnabled, race: race?.status ?? "none", status: row && !row.readyDay ? "recruiting" : rank ? "ready" : row ? "expired" : "none", teamDay: rank, maxDays: TEAM_DAYS, goldStars: this.goldStars(playerId), maxGoldStars: MAX_GOLD_RESERVE,
// Compagnons d'une équipe utilisable ou en cours de recrutement, pour la Guilde.
companions: rank || (row && !row.readyDay) ? row.state.team.map((companion) => this.companionView(companion)) : [] };
}
// --- Recrutement --------------------------------------------------------------------------------------------------------
// Remplace l'équipe du joueur, perdue pour de bon, et dépense toute sa réserve d'étoiles dorées.
startRecruitment(playerId, { day } = {}) {
if (!isDayKey(day)) fail(400, "TEAM_INVALID", "Demande invalide.");
this.requireOpen();
this.cards.database.transaction(() => {
const today = this.today;
if (day !== today) fail(409, "TEAM_EXPIRED", "Un nouveau jour a commencé : rechargez la page.");
const row = this.teamRow(playerId);
if (row && !row.readyDay) fail(409, "TEAM_RECRUITING", "Un recrutement est déjà en cours.");
if (row?.startedDay === today) fail(409, "TEAM_ALREADY_RECRUITED", "Vous avez déjà recruté une équipe aujourd’hui.");
const characters = teamCharacters(this.cards.catalog);
const state = startRecruitment(characters, { ownedIds: this.ownedCardIds(playerId), goldReserve: this.goldStars(playerId), settings: this.settings.recruitment }, this.random);
if (!state.offer.length) fail(409, "TEAM_UNAVAILABLE", "Aucun personnage ne peut être recruté aujourd’hui.");
this.db.prepare("UPDATE players SET gold_stars = 0 WHERE id = ?").run(playerId);
const now = this.cards.now();
this.db.prepare(`INSERT INTO player_teams(player_id, started_day, ready_day, state_json, created_at, updated_at) VALUES (?, ?, NULL, ?, ?, ?)
ON CONFLICT(player_id) DO UPDATE SET started_day = excluded.started_day, ready_day = NULL, state_json = excluded.state_json, created_at = excluded.created_at, updated_at = excluded.updated_at`)
.run(playerId, today, JSON.stringify(state), now, now);
});
return this.result(playerId);
}
// `offer` : les personnages que le client affiche, pour qu'un double clic ne consomme pas deux nouvelles propositions.
rerollOffer(playerId, { offer } = {}) {
return this.change(playerId, (state, characters, owned) => {
if (!Array.isArray(offer) || offer.join() !== state.offer.join()) return state;
return rerollOffer(characters, owned, state, this.random) ?? fail(409, "TEAM_REROLL_UNAVAILABLE", "Vous ne pouvez plus redemander de personnages.");
});
}
chooseCharacter(playerId, { cardId } = {}) {
return this.change(playerId, (state) => {
// Choisir deux fois le même personnage (double clic, deux onglets) ne change rien.
if (state.current?.cardId === cardId) return state;
return chooseCharacter(state, cardId) ?? fail(409, "TEAM_CHOICE_INVALID", "Ce personnage ne peut plus être recruté.");
});
}
revealStar(playerId, { index } = {}) {
return this.change(playerId, (state) => {
if (state.current && state.revealed.includes(index)) return state;
if (!canRevealStar(state, index)) fail(409, "TEAM_STAR_INVALID", "Cette étoile ne peut pas être révélée.");
const result = revealStar(state, index);
if (result.star === "dust" && state.settings.dustValue) this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(state.settings.dustValue, playerId);
return result.state;
});
}
// Baume des Veilleurs : soigne le compagnon que le client croit affaibli. Le soigner deux fois n'en consomme pas deux.
healCompanion(playerId, { cardId } = {}) {
return this.change(playerId, (state) => {
if (state.current?.cardId !== cardId) fail(409, "TEAM_CHOICE_INVALID", "Ce compagnon n’est plus en cours de recrutement.");
if (state.current.healed) return state;
const next = healCompanion(state) ?? fail(409, "TEAM_HEAL_INVALID", "Ce compagnon n’est pas affaibli.");
this.cards.expeditions.consumeItemInTx(playerId, "balm");
this.cards.audit(playerId, "item_used", "balm", { item: "balm", cardId });
return next;
});
}
// `cardId` : le compagnon que le client croit garder, pour qu'un double clic ne garde pas le suivant.
keepCompanion(playerId, { cardId } = {}) {
return this.change(playerId, (state, characters, owned) => {
if (state.current?.cardId !== cardId) fail(409, "TEAM_CHOICE_INVALID", "Ce compagnon n’est plus en cours de recrutement.");
return keepCompanion(characters, owned, state, this.random);
});
}
change(playerId, apply) {
this.cards.database.transaction(() => {
const characters = teamCharacters(this.cards.catalog);
const owned = this.ownedCardIds(playerId);
const row = this.repairedRow(playerId, { characters, owned });
if (!row || row.readyDay) fail(409, "TEAM_NOT_RECRUITING", "Aucun recrutement n’est en cours.");
const next = apply(row.state, characters, owned);
if (next === row.state) return;
const finished = recruitmentFinished(next);
// L'équipe sert à partir du jour où elle est complète.
this.saveState(playerId, next, finished ? this.today : null);
if (finished) {
this.cards.audit(playerId, "team_recruited", this.today, { cards: next.team.map((companion) => companion.cardId), power: Math.round(next.team.reduce((sum, companion) => sum + companion.power, 0) / next.team.length), stardust: next.dust, goldStars: next.extraGold });
}
});
return this.result(playerId);
}
result(playerId) {
return { team: this.view(playerId), state: this.cards.getState(playerId) };
}
// Serveur Vite local (`devPerks`) : efface l'équipe et les courses du joueur, pour recruter et courir à nouveau le même jour.
resetForTests(playerId) {
if (!this.cards.devPerks) fail(404, "NOT_FOUND", "Remise à zéro indisponible.");
this.cards.database.transaction(() => {
for (const table of ["player_teams", "team_races"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
});
return this.result(playerId);
}
// Développement : efface les courses du joueur (en cours ou finies) et garde son équipe, pour recourir aussitôt. La poussière
// déjà gagnée reste acquise.
resetRaceForTests(playerId) {
if (!this.cards.devPerks) fail(404, "NOT_FOUND", "Remise à zéro indisponible.");
this.db.prepare("DELETE FROM team_races WHERE player_id = ?").run(playerId);
return this.result(playerId);
}
// Suppression de compte : l'équipe disparaît, la réserve est remise à zéro avec le reste des possessions.
forgetPlayer(playerId) {
for (const table of ["player_teams", "team_races"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
this.db.prepare("UPDATE players SET gold_stars = 0 WHERE id = ?").run(playerId);
}
}
Object.assign(TeamService.prototype, raceMethods);