Add solo Expeditions, the second Guilde des Veilleurs quest of Sokko TCG

- Every catalog card carries expedition tags and every collection a stat profile, validated at load; twelve destinations live server-side so hidden ones stay secret.
- Pure rules compute card power, per-slot requirements, roles, dangers, the long-trip malus, the score (one more star never raises it) and loot proportional to the chosen duration.
- A simulator script and a balance test guard the design thresholds; agent docs and a new-card skill explain how to tag new cards.
- Migration 8 adds Éclats d'étoile, expedition settings stored as one validated JSON, daily destinations, expeditions, members and slots, and rebuilds gift_packs so a pack can come from an expedition.
- Players launch a solo expedition from the Guild, see an exact preview, and claim their loot when it returns; the card sheet shows cards away on an expedition.
- Administration › Guilde tunes every value with server-side bounds, toggles destinations and cancels running expeditions; expeditions stay closed until an administrator opens them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-15 14:29:05 +01:00
parent 0ef213cf4f
commit 8bb1d53d70
46 changed files with 4752 additions and 213 deletions

View file

@ -342,3 +342,6 @@
{"id":"int-fc8f33bf9d1c8430b05a605f18235998","kind":"field_change","created_at":"2026-11-13T14:14:53.924973488Z","actor":"Shinuwa","issue_id":"sokko-g-v745","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Closed"}} {"id":"int-fc8f33bf9d1c8430b05a605f18235998","kind":"field_change","created_at":"2026-11-13T14:14:53.924973488Z","actor":"Shinuwa","issue_id":"sokko-g-v745","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Closed"}}
{"id":"int-79c8d43e37370ddf8840cacd2bc4a923","kind":"field_change","created_at":"2026-11-14T09:45:12.274352406Z","actor":"Shinuwa","issue_id":"sokko-g-tabc","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}} {"id":"int-79c8d43e37370ddf8840cacd2bc4a923","kind":"field_change","created_at":"2026-11-14T09:45:12.274352406Z","actor":"Shinuwa","issue_id":"sokko-g-tabc","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-e9b4ee305fdf02151292a856d60926dc","kind":"field_change","created_at":"2026-11-14T15:21:07.54864269Z","actor":"Shinuwa","issue_id":"sokko-g-03ij","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}} {"id":"int-e9b4ee305fdf02151292a856d60926dc","kind":"field_change","created_at":"2026-11-14T15:21:07.54864269Z","actor":"Shinuwa","issue_id":"sokko-g-03ij","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-b85db20f07bf7f3813ce379b1a4cf2b5","kind":"field_change","created_at":"2026-11-15T12:45:03.198722539Z","actor":"Shinuwa","issue_id":"sokko-g-v3u4.1","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Doc de conception corrigé (étape 0 du plan)."}}
{"id":"int-2eb4267321abcd9d03371b62fdd602ef","kind":"field_change","created_at":"2026-11-15T12:58:18.78522507Z","actor":"Shinuwa","issue_id":"sokko-g-v3u4.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Étiquettes et profils dans le catalogue + validation, 12 destinations côté serveur + validation, réglages (schéma, défauts, fusion, validation, diff), règles pures, simulateur et test d'équilibrage, docs agent et skill new-card. npm test : 300/300."}}
{"id":"int-13028497227d5b47c5cac5cc0d43849f","kind":"field_change","created_at":"2026-11-15T13:19:13.339585179Z","actor":"Shinuwa","issue_id":"sokko-g-v3u4.3","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Expéditions solo livrées : migration 8, service + API, panneau joueur, tuile de Guilde, réglages et suivi en administration, historique, tests Node (309) et e2e (13/13), docs."}}

View file

@ -0,0 +1,12 @@
---
name: new-card
description: Ajouter ou modifier une carte Sokko TCG (catalog.json) en la rendant jouable dans les Expéditions — étiquettes, profil, vérification d'équilibre. À utiliser dès qu'une carte ou une collection est créée ou que sa description change.
---
Suivre la section « Ajouter une carte aux Expéditions » de `docs/collections/archipel-lore.md`, qui fait autorité :
1. Poser les étiquettes de la carte (`cards[].expedition.tags`) à partir de sa description et du lore, en réutilisant le vocabulaire `expeditionTags` du catalogue.
2. Ne donner un profil propre (`cards[].expedition.profile`) qu'aux cartes au caractère marqué ; sinon la carte prend le profil de sa collection.
3. Lancer `node scripts/simulate-expeditions.mjs`, puis `npm run test:cards`.
Pour une nouvelle collection : lui donner aussi `collections[].expedition.profile`.

View file

@ -1093,7 +1093,7 @@ car les attributs NDS sont chargés après `_nebula-cards.scss`. Le tableau de b
sections adressables (`/#/cards/admin/<section>`), dans une navigation par liens sections adressables (`/#/cards/admin/<section>`), dans une navigation par liens
avec `aria-current="page"`, sans intitulés de groupe : Vue d'ensemble avec `aria-current="page"`, sans intitulés de groupe : Vue d'ensemble
(`overview`), Collections (`collections`), Codes cadeaux (`codes`), Boutique (`overview`), Collections (`collections`), Codes cadeaux (`codes`), Boutique
(`shop`) et Guilde (`guild`, réglages des quêtes : partie du jour et récompense de la Carte du jour), puis, séparé par un filet, l'Atelier visuel (`visual-lab`), bac à sable (`shop`) et Guilde (`guild`, réglages des quêtes : partie du jour et récompense de la Carte du jour, réglages et suivi des Expéditions), puis, séparé par un filet, l'Atelier visuel (`visual-lab`), bac à sable
où rien n'est enregistré. Les anciennes adresses redirigent : `players` vers la où rien n'est enregistré. Les anciennes adresses redirigent : `players` vers la
vue d'ensemble, `cards`, `catalog` et `packs` vers Collections, `distributions` vue d'ensemble, `cards`, `catalog` et `packs` vers Collections, `distributions`
vers Codes cadeaux, `mythic-styles` et `opening-effects` vers l'Atelier visuel. Quand le tableau de bord dispose d'au vers Codes cadeaux, `mythic-styles` et `opening-effects` vers l'Atelier visuel. Quand le tableau de bord dispose d'au
@ -1476,3 +1476,16 @@ par indice. Sous 720 px de conteneur, les deux colonnes s'empilent. La fin de pa
le formulaire par un `nds-panel` : titre, réponse et description, badges (poussière gagnée, le formulaire par un `nds-panel` : titre, réponse et description, badges (poussière gagnée,
possession, série), bouton primaire « Copier le résultat » et compte à rebours, avec la carte possession, série), bouton primaire « Copier le résultat » et compte à rebours, avec la carte
en `md` à droite. en `md` à droite.
Les Expéditions (`expeditions`, sans entrée propre : le menu désigne la Guilde) ont leur tuile dans la
Guilde tant qu'elles sont ouvertes ou qu'une expédition du joueur n'est pas terminée. Leur page
(`_nebula-expeditions.scss`) reprend l'en-tête de la Carte du jour (solde d'Éclats en badge `gold`,
retour secondaire vers la Guilde), puis les expéditions du joueur en `nds-card` (couverture carrée de
la destination, palier et butin en badges, équipe en cartes `sm`, bouton primaire « Récupérer le
butin »), puis quatre étapes en `nds-panel` : destinations du jour (boutons à `aria-pressed`, contour
or quand choisis), difficulté et durée (`nds-toolbar` de boutons `sm`) avec les exigences, équipe
(une place par rôle, puis les cartes jouables en `sm` triées pour la place active) et aperçu (palier,
exigences atteintes en `success`, condition et dangers en `nds-inline-notice`, butin attendu).
En administration, la section Guilde ajoute sous la Carte du jour un panneau par groupe de réglages
des Expéditions (champs en grille, listes de valeurs côte à côte, `ApplyActions`), les destinations
(proposée ou retirée, poids) et le suivi du jour avec l'annulation d'une expédition en cours.

View file

@ -30,6 +30,10 @@ L'interface cible les fenêtres d'ordinateur en plein écran ou en demi-écran.
- Guilde des Veilleurs de Sokko TCG, qui confie des quêtes, dont la Carte du jour : un défi quotidien commun à tous les joueurs, qui consiste à - Guilde des Veilleurs de Sokko TCG, qui confie des quêtes, dont la Carte du jour : un défi quotidien commun à tous les joueurs, qui consiste à
retrouver une illustration zoomée en 6 essais, avec des indices de collection et retrouver une illustration zoomée en 6 essais, avec des indices de collection et
de rareté, une récompense en poussière d'étoiles et un résultat à partager. de rareté, une récompense en poussière d'étoiles et un résultat à partager.
- Expéditions de Sokko TCG, seconde quête de la Guilde : des cartes rares ou mieux partent en
solo vers une destination du jour (difficulté, durée, rôles, dangers) et rapportent des Éclats
d'étoile, de la poussière et parfois un paquet. Toutes les valeurs se règlent dans
l'administration ; `node scripts/simulate-expeditions.mjs` affiche le rapport d'équilibrage.
## Démarrage ## Démarrage

View file

@ -11,6 +11,10 @@ Cette zone contient les références projet.
`TEST_STRATEGY.md` définit les validations selon le risque et distingue tests `TEST_STRATEGY.md` définit les validations selon le risque et distingue tests
Node, E2E Vite, E2E du build et contrôles HTTP du serveur livré. Node, E2E Vite, E2E du build et contrôles HTTP du serveur livré.
`collections/archipel-lore.md` fait autorité pour le lore des cartes Sokko TCG
et, dans sa section « Ajouter une carte aux Expéditions », pour les étiquettes
et profils qu'une nouvelle carte doit porter.
`P06_USAGE_STUDY.md` consigne l'arbitrage conservateur des prochains usages et `P06_USAGE_STUDY.md` consigne l'arbitrage conservateur des prochains usages et
les conditions nécessaires pour le réexaminer. les conditions nécessaires pour le réexaminer.

View file

@ -19,9 +19,9 @@ Collections, ouvertures et transferts :
- `players.deleted_at` (migration 5) : date de suppression du compte. - `players.deleted_at` (migration 5) : date de suppression du compte.
`DELETE /api/cards/account` efface sessions, collection, favoris, clés `DELETE /api/cards/account` efface sessions, collection, favoris, clés
d'idempotence, parties de la Carte du jour et paquets offerts non ouverts, annule les échanges ouverts, clôt d'idempotence, parties de la Carte du jour et paquets offerts non ouverts, annule les échanges ouverts et les expéditions en cours, clôt
une ouverture en attente et anonymise la ligne (`discord_id = deleted:<uuid>`, une ouverture en attente et anonymise la ligne (`discord_id = deleted:<uuid>`,
nom « Joueur supprimé », avatar et soldes remis à zéro). Elle reste car ouvertures, nom « Joueur supprimé », avatar et soldes, Éclats compris, remis à zéro). Elle reste car ouvertures,
transferts, réclamations de codes et journaux la référencent. Le compte disparaît transferts, réclamations de codes et journaux la référencent. Le compte disparaît
des listes de joueurs ; une reconnexion Discord crée un compte neuf. des listes de joueurs ; une reconnexion Discord crée un compte neuf.
- `players.last_login_at` (migration 6) : dernière connexion Discord. - `players.last_login_at` (migration 6) : dernière connexion Discord.
@ -111,6 +111,52 @@ Carte du jour (migration 7, règles pures dans `services/cards/daily.js`) :
poussière) dans l'historique du joueur. Chaque essai renvoie aussi l'état complet, dont le poussière) dans l'historique du joueur. Chaque essai renvoie aussi l'état complet, dont le
résumé `daily` (statut, essais, série) qui alimente le bandeau et la page de la Guilde des Veilleurs. résumé `daily` (statut, essais, série) qui alimente le bandeau et la page de la Guilde des Veilleurs.
Expéditions (migration 8, règles pures dans `services/cards/expedition-rules.js`, service dans
`services/cards/expedition-service.js`, réglages dans `services/cards/expedition-settings.js`) :
- `players.eclats` : Éclats d'étoile du joueur (entier ≥ 0), monnaie des Expéditions, distincte de la poussière.
- `expedition_settings(id = 1, settings_json, updated_at, updated_by)` : tous les réglages des
Expéditions dans un JSON validé champ par champ (`EXPEDITION_SETTINGS_SCHEMA`, seule source des
bornes). À la lecture, un champ absent ou invalide reprend sa valeur par défaut
(`DEFAULT_EXPEDITION_SETTINGS`) : une valeur ajoutée plus tard ne demande pas de migration. Les
Expéditions sont fermées (`enabled: false`) jusqu'à ce qu'un administrateur les ouvre.
- `expedition_days(day, draw_json, created_at)` : destinations du jour de Paris, tirées au premier
appel (identifiant, indice de la condition, indices de deux dangers). Les exigences chiffrées sont
calculées à la lecture avec les réglages en vigueur, puis figées au départ.
- `expeditions(id, mode, day, destination_id, difficulty, duration_ms, creator_id, status, setup_json,
result_json, created_at, departs_at, returns_at, completed_at)` : `mode` `solo` ou `group`,
`status` `forming`, `running`, `completed` ou `cancelled` (« revenue » se déduit de `returns_at`).
`setup_json` fige la destination, la condition, les étoiles, la durée et les rôles ; `result_json`
(score, palier, exigences, dangers) est calculé au départ et n'est montré qu'au retour.
- `expedition_members(expedition_id, player_id, reward_json, joined_at, claimed_at)` : butin tiré au
départ (`{ eclats, stardust, packs: [collectionId…] }`), crédité une seule fois au retour.
- `expedition_slots(expedition_id, position, role, player_id, edition_id, card_id, level, stats_json)` :
une place par carte ; `player_id` nul pour une place tenue par le Veilleur de la Guilde. Une édition
est occupée tant qu'elle est dans une expédition `running` dont son propriétaire n'a pas récupéré le
butin. L'exemplaire gardé ne quitte jamais la collection : échanges et recyclage ne changent pas.
- `gift_packs.source` (`campaign` ou `expedition`) et `gift_packs.expedition_id` : la table est
reconstruite par la migration 8 ; `campaign_id` devient facultatif. Un paquet rapporté s'ouvre
comme un paquet offert ; `getState().giftPacks[]` donne `source` et `sourceName`.
- `GET /api/cards/expeditions` : réglages utiles au joueur, destinations du jour (rôles du solo et,
pour chaque étoile, exigences, condition et dangers), cartes jouables (rare ou mieux, Puissance,
stats, occupation) et expéditions du joueur. Fermées : aucune destination n'est tirée, mais le
butin des expéditions revenues se récupère.
- `POST /api/cards/expeditions/preview` : aperçu exact d'une équipe, sans écriture.
- `POST /api/cards/expeditions` (`Idempotency-Key`, `{ day, destinationId, difficulty, durationHours,
slots: [editionId…] }`) : `EXPEDITIONS_CLOSED`, `EXPEDITION_DAY_EXPIRED`, `EXPEDITION_INVALID`,
`EXPEDITION_CARD_INVALID`, `CARD_NOT_OWNED`, `EXPEDITION_CARD_BUSY`, `EXPEDITION_LIMIT`.
- `POST /api/cards/expeditions/:id/claim` : idempotent ; `EXPEDITION_NOT_FOUND`,
`EXPEDITION_NOT_RETURNED`. Inscrit `expedition_completed` dans l'historique du joueur.
- `PUT /api/cards/admin/expeditions/settings` (`{ settings }`, objet complet) :
`EXPEDITION_SETTINGS_INVALID`, `EXPEDITION_SETTINGS_UNCHANGED` ; l'historique d'administration
garde `expedition_settings_updated` avec la liste des changements (`{ path, previous, next }`).
- `POST /api/cards/admin/expeditions/:id/cancel` : libère les cartes sans butin ; `expedition_cancelled`
côté administration, `expedition_cancelled_by_guild` dans l'historique du joueur.
- `getState().expeditions` : résumé pour la tuile de la Guilde et la fiche de carte (ouverture, en
route, revenues, prochain retour, lancée aujourd'hui, cartes jouables, éditions occupées) ;
`getState().wallet.eclats`. Le tableau de bord d'administration ajoute `expeditionSettings`
(réglages, valeurs par défaut, schéma, destinations) et `expeditionsToday`.
Distributions par codes : Distributions par codes :
- `campaigns(id, name, code, reward_json, max_claims, created_by, created_at, expires_at, revoked_at)` : - `campaigns(id, name, code, reward_json, max_claims, created_by, created_at, expires_at, revoked_at)` :
@ -165,6 +211,13 @@ paquets (`collections[].active`), ni taux de tirage (`dropTables`,
`loadCardsCatalog` → `prepareVersionedCatalog` refuse un fichier qui en contient `loadCardsCatalog` → `prepareVersionedCatalog` refuse un fichier qui en contient
(`assertVersionedCatalogScope`). (`assertVersionedCatalogScope`).
Il porte aussi les données des Expéditions, validées au chargement : `expeditionTags`
(vocabulaire fermé d'étiquettes `famille:nom` et leurs libellés), `collections[].expedition.profile`
(part de la Puissance donnée à chaque stat, somme 100, obligatoire) et `cards[].expedition`
(`tags` obligatoires, 1 à 8 ; `profile` facultatif). Les destinations des Expéditions vivent
côté serveur, dans `services/cards/content/expedition-destinations.json`
(`validateExpeditionDestinations`) : elles ne sont jamais publiées en fichier statique.
Les finitions sont générées (`withGeneratedFinishes`) : `standard`, puis une Les finitions sont générées (`withGeneratedFinishes`) : `standard`, puis une
finition `<effet>-<palette>` par combinaison effet holographique × palette. Une finition `<effet>-<palette>` par combinaison effet holographique × palette. Une
finition ne porte pas de particules : les particules n'existent que pendant finition ne porte pas de particules : les particules n'existent que pendant

View file

@ -74,3 +74,19 @@ Les prompts d'illustration (style crayon et pastel, premier plan en papier déco
- **Genèse Astrale** : collection événement sur le plaisir de collectionner. C'est un à-côté : les Primordiaux (Dragon, Kitsune, Pie, Capybara, Panda) y ouvrent et échangent des paquets. Elle ne suit pas l'histoire de l'archipel, mais respecte les noms, le genre et le caractère des personnages (Lune Écarlate, Kitsune au masculin, Dragon toujours nommé en entier). On y dit « paquet », comme sur le reste du site. - **Genèse Astrale** : collection événement sur le plaisir de collectionner. C'est un à-côté : les Primordiaux (Dragon, Kitsune, Pie, Capybara, Panda) y ouvrent et échangent des paquets. Elle ne suit pas l'histoire de l'archipel, mais respecte les noms, le genre et le caractère des personnages (Lune Écarlate, Kitsune au masculin, Dragon toujours nommé en entier). On y dit « paquet », comme sur le reste du site.
- **Poussières d'étoiles** : collection de la boutique. Elle n'est pas rattachée au lore de l'archipel. - **Poussières d'étoiles** : collection de la boutique. Elle n'est pas rattachée au lore de l'archipel.
## Ajouter une carte aux Expéditions
Chaque carte du catalogue (`website/public/data/cards/catalog.json`) doit être jouable dans les Expéditions dès sa création. Le chargement du catalogue échoue, et donc `npm run test:cards`, si une carte n'a pas ses données d'expédition.
1. **Étiquettes** (`cards[].expedition.tags`, 1 à 8, obligatoires même pour une commune) : choisies dans `expeditionTags`, en haut du catalogue. Une étiquette suit la forme `famille:nom`, avec quatre familles :
- `personnage:` pour l'animal ou le Primordial montré (un même animal garde la même étiquette d'une collection à l'autre : c'est ce qui permettra les Échos) ;
- `lieu:` pour un lieu de l'archipel (Lune Écarlate, vide, îles de glace, îles-jeux…) ;
- `theme:` pour ce dont parle la description (Veilleurs, voyage, hiver, fête, rêves…) ;
- `objet:` pour une commune qui montre un objet (lunette, boussole, lanterne, cadeau…).
On part de la description de la carte et de ce document. Une étiquette nouvelle s'ajoute à `expeditionTags` (libellé de 40 caractères au plus) ; une étiquette que plus aucune carte n'utilise doit en être retirée (test « every catalog card carries expedition tags »).
2. **Profil** (`cards[].expedition.profile`, facultatif) : la part de la Puissance donnée à chaque stat, en entiers dont la somme vaut 100 : `{ "bravoure", "endurance", "fortune", "orientation" }`. Sans profil, la carte prend celui de sa collection (`collections[].expedition.profile`, obligatoire pour toute collection). On ne donne un profil propre qu'aux cartes au caractère marqué (un guide en Orientation, un gardien en Endurance…), sans dépasser 50 sur une stat.
3. **Vérifier l'équilibre** : `node scripts/simulate-expeditions.mjs`, puis `npm run test:cards`. Le test d'équilibrage (`tests/nebula-cards-expedition-balance.test.mjs`) échoue si une carte rare ou mieux ne peut atteindre « Réussite » en 2 ★ nulle part.
Les destinations (`services/cards/content/expedition-destinations.json`, côté serveur pour garder secrètes les destinations cachées) citent des étiquettes dans leurs conditions et leurs dangers : chacune doit rester portée par au moins 3 cartes rare ou mieux, sinon le chargement échoue. Une mythique reprend les étiquettes et le profil de sa carte légendaire.

View file

@ -1,5 +1,5 @@
// Rôle : valide l'ouverture, la reprise, l'album et l'administration de Sokko TCG. // Rôle : valide l'ouverture, la reprise, l'album et l'administration de Sokko TCG.
import { readFile } from "node:fs/promises"; import { readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { expect, test } from "@playwright/test"; import { expect, test } from "@playwright/test";
@ -1822,3 +1822,79 @@ test("a player finds the daily card with hints and copies the result", async ({
await expect(quest.locator(".nebula-quest-media .nds-badge")).toHaveText("Série : 1 jour"); await expect(quest.locator(".nebula-quest-media .nds-badge")).toHaveText("Série : 1 jour");
await expect(quest.getByRole("link", { name: "Voir le résultat", exact: true })).toBeVisible(); await expect(quest.getByRole("link", { name: "Voir le résultat", exact: true })).toBeVisible();
}); });
// Dernier parcours : il ouvre les Expéditions et décale l'horloge du serveur, deux réglages globaux qu'il remet en place à la fin.
test("an administrator opens expeditions and a player sends a team, then claims its loot", async ({ browser, page }) => {
const clockFile = join(tmpdir(), "sokkog-cards-e2e-clock.json");
const setServerClock = (offsetMs) => writeFile(clockFile, JSON.stringify({ offsetMs }));
await setServerClock(0);
await page.goto("/#/cards");
await page.getByRole("button", { name: "Version développement", exact: true }).click();
await page.goto("/#/cards/admin/guild");
const general = page.getByRole("region", { name: "Général", exact: true });
const openToggle = general.getByRole("button", { name: "Expéditions ouvertes aux joueurs", exact: true });
await expect(openToggle).toHaveAttribute("aria-pressed", "false");
await openToggle.click();
await general.getByRole("button", { name: "Appliquer", exact: true }).click();
await page.getByRole("dialog").getByRole("button", { name: "Appliquer", exact: true }).click();
await expect(general.getByRole("button", { name: "Expéditions ouvertes aux joueurs", exact: true })).toHaveAttribute("aria-pressed", "true");
await expect(page.getByRole("region", { name: "Destinations", exact: true }).getByRole("listitem")).toHaveCount(12);
// Le partenaire possède deux légendaires distinctes : de quoi partir en solo.
const { token } = JSON.parse(await readFile(join(tmpdir(), "sokkog-cards-e2e-partner.json"), "utf8"));
const partnerContext = await browser.newContext({ baseURL: "http://127.0.0.1:4180", viewport: { width: 1280, height: 900 } });
await partnerContext.addCookies([{ name: "__Host-sokkog_cards_session", value: token, domain: "127.0.0.1", path: "/", secure: true, httpOnly: true, sameSite: "Lax" }]);
const partner = await partnerContext.newPage();
await partner.goto("/#/cards/guild");
const quest = partner.getByRole("article", { name: "Expéditions" });
await expect(quest).toContainText("De nouvelles destinations vous attendent.");
await quest.getByRole("link", { name: "Préparer", exact: true }).click();
await expect(partner).toHaveURL(/#\/cards\/expeditions$/);
await expect(partner.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: /^Guilde/ })).toHaveAttribute("aria-current", "page");
const destinations = partner.getByRole("region", { name: "1. Destination du jour" }).getByRole("button");
await expect(destinations).toHaveCount(4);
await expect(destinations.first()).toHaveAttribute("aria-pressed", "true");
const settings = partner.getByRole("region", { name: "2. Difficulté et durée" });
await settings.getByRole("button", { name: "★", exact: true }).click();
await settings.getByRole("button", { name: "2 h", exact: true }).click();
const team = partner.getByRole("region", { name: "3. Équipe" });
await team.getByRole("button", { name: /^Placer Loup des Aurores en / }).click();
await team.getByRole("button", { name: /^Placer Dragon du Néant Étoilé en / }).first().click();
const preview = partner.getByRole("region", { name: "4. Aperçu" });
await expect(preview).toContainText(/Butin attendu : environ [\d,]+ Éclats/);
await expect(preview.locator(".nebula-expedition-preview .nds-badge").first()).toHaveText(/^(Retour difficile|Réussite|Triomphe)$/);
await preview.getByRole("button", { name: "Partir en expédition", exact: true }).click();
await expect(partner.getByRole("status").filter({ hasText: "Expédition lancée !" })).toBeVisible();
const report = partner.locator(".nebula-expedition-report").first();
await expect(report).toContainText(/En route, retour dans (1 h|2 h)/);
await expect(partner.getByText("Récupérez le butin de votre expédition avant d’en lancer une autre.")).toBeVisible();
// En demi-écran, la page reste sans défilement horizontal.
await partner.setViewportSize({ width: 768, height: 900 });
expect(await partner.locator(".nebula-expeditions").evaluate((element) => element.scrollWidth - element.clientWidth)).toBe(0);
await partner.setViewportSize({ width: 1280, height: 900 });
// Trois heures plus tard pour le serveur : l'expédition est revenue, son butin se récupère une fois.
await setServerClock(3 * 3_600_000);
await partner.reload();
await expect(report).toContainText("De retour ! Le butin vous attend.");
await report.getByRole("button", { name: "Récupérer le butin", exact: true }).click();
await expect(partner.getByRole("status").filter({ hasText: "Butin récupéré !" })).toBeVisible();
await expect(report).toContainText("Butin récupéré.");
await expect(report.locator(".nebula-expedition-rewards .nds-badge").filter({ hasText: /^\+[\d\s]+ Éclats$/ })).toBeVisible();
await expect(partner.locator(".nebula-expeditions .nds-section-heading .nds-badge")).not.toHaveText("0 Éclats d’étoile");
await partner.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Historique", exact: true }).click();
await expect(partner.locator(".nebula-history-list li").filter({ hasText: "Expédition terminée" })).toContainText("★ · 2 h");
await partnerContext.close();
// L'historique d'administration détaille le réglage ; on referme les Expéditions et on remet l'horloge.
await page.goto("/#/cards/admin/history");
await expect(page.locator(".nds-list-row").filter({ hasText: "Expéditions modifiées" }).first()).toContainText("Expéditions ouvertes aux joueurs : non → oui");
await page.goto("/#/cards/admin/guild");
await general.getByRole("button", { name: "Expéditions ouvertes aux joueurs", exact: true }).click();
await general.getByRole("button", { name: "Appliquer", exact: true }).click();
await page.getByRole("dialog").getByRole("button", { name: "Appliquer", exact: true }).click();
await expect(general.getByRole("button", { name: "Expéditions ouvertes aux joueurs", exact: true })).toHaveAttribute("aria-pressed", "false");
await setServerClock(0);
});

View file

@ -15,12 +15,12 @@
"preview": "vite preview", "preview": "vite preview",
"lists:index": "node scripts/generate-list-indexes.mjs", "lists:index": "node scripts/generate-list-indexes.mjs",
"lint": "eslint .", "lint": "eslint .",
"lint:cards": "eslint server.mjs vite.config.js services/http.js playwright.cards.config.js scripts/backup-nebula-cards.mjs scripts/start-cards-e2e-server.mjs services/cards tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/nebula-cards-daily.test.mjs tests/server-robustness.test.mjs e2e/nebula-cards.spec.js e2e/style-layouts.spec.js website/src/features/cards website/src/components/Shell.jsx website/src/main.jsx website/src/router/RouteContent.jsx", "lint:cards": "eslint server.mjs vite.config.js services/http.js playwright.cards.config.js scripts/backup-nebula-cards.mjs scripts/start-cards-e2e-server.mjs scripts/simulate-expeditions.mjs services/cards tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/nebula-cards-daily.test.mjs tests/nebula-cards-expeditions.test.mjs tests/nebula-cards-expedition-balance.test.mjs tests/nebula-cards-expedition-service.test.mjs tests/server-robustness.test.mjs e2e/nebula-cards.spec.js e2e/style-layouts.spec.js website/src/features/cards website/src/components/Shell.jsx website/src/main.jsx website/src/router/RouteContent.jsx",
"check": "node --check server.mjs && node --check vite.config.js && npm run lint && npm run lists:index && npm test && npm run build", "check": "node --check server.mjs && node --check vite.config.js && npm run lint && npm run lists:index && npm test && npm run build",
"check:cards": "node --check server.mjs && node --check vite.config.js && npm run lint:cards && npm run test:cards && npm run test:e2e:cards", "check:cards": "node --check server.mjs && node --check vite.config.js && npm run lint:cards && npm run test:cards && npm run test:e2e:cards",
"check:full": "npm run check && E2E_PORT=4181 npm run test:e2e && npm run test:e2e:production && npm run test:e2e:cards", "check:full": "npm run check && E2E_PORT=4181 npm run test:e2e && npm run test:e2e:production && npm run test:e2e:cards",
"test": "node --test", "test": "node --test",
"test:cards": "node --test tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/nebula-cards-daily.test.mjs tests/server-robustness.test.mjs && node --test --test-name-pattern=\"site content json is complete\" tests/data-validation.test.mjs", "test:cards": "node --test tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/nebula-cards-daily.test.mjs tests/nebula-cards-expeditions.test.mjs tests/nebula-cards-expedition-balance.test.mjs tests/nebula-cards-expedition-service.test.mjs tests/server-robustness.test.mjs && node --test --test-name-pattern=\"site content json is complete\" tests/data-validation.test.mjs",
"test:e2e": "playwright test", "test:e2e": "playwright test",
"test:e2e:production": "npm run build && playwright test --config playwright.production.config.js", "test:e2e:production": "npm run build && playwright test --config playwright.production.config.js",
"test:e2e:cards": "playwright test --config playwright.cards.config.js", "test:e2e:cards": "playwright test --config playwright.cards.config.js",

View file

@ -0,0 +1,27 @@
// Rôle : affiche le rapport d'équilibrage des Expéditions Sokko TCG (réglages par défaut, catalogue et destinations du dépôt).
// Usage : node scripts/simulate-expeditions.mjs. À relancer après l'ajout de cartes, d'étiquettes, de destinations ou un changement de réglages.
import { fileURLToPath } from "node:url";
import { loadCardsCatalog } from "../services/cards/catalog.js";
import { loadExpeditionDestinations } from "../services/cards/expedition-content.js";
import { DEFAULT_EXPEDITION_SETTINGS, mergeExpeditionSettings } from "../services/cards/expedition-settings.js";
import { simulate } from "../services/cards/expedition-simulation.js";
const root = fileURLToPath(new URL("..", import.meta.url));
const catalog = loadCardsCatalog(`${root}website/public/data/cards/catalog.json`);
const destinations = loadExpeditionDestinations(`${root}services/cards/content/expedition-destinations.json`, catalog);
const settings = mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, destinations.map((destination) => destination.id));
const report = simulate(catalog, destinations, settings);
const pct = (value) => `${value.toFixed(0).padStart(3)} %`;
console.log(`Paliers : Réussite à ${settings.score.successPct} %, Triomphe à ${settings.score.triumphPct} %.\n`);
console.log("Score des paires de même rareté (minimum / médiane / maximum sur les destinations, 2 h) :");
for (const row of report.byRarity) {
console.log(` ${row.level.padEnd(10)} ${row.rarity.padEnd(9)} ${row.stars} ★ ${pct(row.min)} / ${pct(row.median)} / ${pct(row.max)}`);
}
const weakest = [...report.cardBest].sort((a, b) => a.scorePct - b.scorePct).slice(0, 10);
console.log("\nCartes au meilleur score le plus bas en 2 ★ (niveau 0, partenaire de même rareté) :");
for (const card of weakest) console.log(` ${pct(card.scorePct)} ${card.cardId} (${card.rarity}) à ${card.destinationId} avec ${card.partnerId}`);
console.log(`\nDestinations où une paire de rares au plafond triomphe en 4 ★ : ${(report.triumphShareAt4 * 100).toFixed(0)} %`);
console.log(`Puissance au plafond : rare ${report.rareVsMythicAtMax.rare}, mythique ${report.rareVsMythicAtMax.mythic}`);
console.log("\nÉclats espérés par heure (durées " + settings.durations.hours.join(" / ") + " h) :");
for (const row of report.lootPerHour) console.log(` ${row.stars} ★ ${row.tier.padEnd(9)} ${row.perHour.map((value) => value.toFixed(2)).join(" / ")}`);

View file

@ -1,5 +1,5 @@
// Rôle : démarre le build avec une base Sokko TCG temporaire pour les parcours Playwright. // Rôle : démarre le build avec une base Sokko TCG temporaire pour les parcours Playwright.
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
@ -34,11 +34,30 @@ insertVariation.run("mythic-card-pull-spectral-prism-solar", "mythic-card-pull",
seedService.addCard(partner.id, "starvoid-dragon-spectral-prism-aurora"); seedService.addCard(partner.id, "starvoid-dragon-spectral-prism-aurora");
seedDatabase.close(); seedDatabase.close();
// Horloge du serveur décalable par les parcours (retour d'une expédition sans attendre des heures) : le décalage, en millisecondes,
// est lu dans ce fichier, relu au plus toutes les 200 ms. Il repart de zéro à chaque démarrage.
const clockFile = join(tmpdir(), "sokkog-cards-e2e-clock.json");
writeFileSync(clockFile, JSON.stringify({ offsetMs: 0 }));
let clockOffset = 0;
let clockReadAt = 0;
function now() {
const real = Date.now();
if (real - clockReadAt > 200) {
clockReadAt = real;
try {
clockOffset = Number(JSON.parse(readFileSync(clockFile, "utf8")).offsetMs) || 0;
} catch {
clockOffset = 0;
}
}
return real + clockOffset;
}
const { startServer } = await import("../server.mjs"); const { startServer } = await import("../server.mjs");
const draws = [0.999, 0, 0.999, 0.999, 0.999, 0]; const draws = [0.999, 0, 0.999, 0.999, 0.999, 0];
let drawIndex = 0; let drawIndex = 0;
// Tous les parcours et leurs deux comptes partagent la même adresse IP : la limite par minute les ferait échouer au hasard. // Tous les parcours et leurs deux comptes partagent la même adresse IP : la limite par minute les ferait échouer au hasard.
const server = startServer({ cardsApiOptions: { allowProductionDevAuth: true, apiRateLimit: 100_000, random: (max) => Math.min(max - 1, Math.floor(draws[drawIndex++ % draws.length] * max)) } }); const server = startServer({ cardsApiOptions: { allowProductionDevAuth: true, apiRateLimit: 100_000, now, random: (max) => Math.min(max - 1, Math.floor(draws[drawIndex++ % draws.length] * max)) } });
let stopping = false; let stopping = false;
function stop() { function stop() {

View file

@ -4,6 +4,7 @@ import { readFile } from "node:fs/promises";
import { join, resolve } from "node:path"; import { join, resolve } from "node:path";
import { CardsDatabase } from "./database.js"; import { CardsDatabase } from "./database.js";
import { loadCardsCatalog, publicCatalog } from "./catalog.js"; import { loadCardsCatalog, publicCatalog } from "./catalog.js";
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
import { CardsService, DEV_DISCORD_ID } from "./service.js"; import { CardsService, DEV_DISCORD_ID } from "./service.js";
import { bool, createRateLimiter, json } from "../http.js"; import { bool, createRateLimiter, json } from "../http.js";
@ -104,6 +105,7 @@ export function createCardsApiHandler({
allowProductionDevAuth = false, allowProductionDevAuth = false,
databasePath = env.CARDS_DB_PATH || join(projectRoot, ".local", "nebula-cards.sqlite"), databasePath = env.CARDS_DB_PATH || join(projectRoot, ".local", "nebula-cards.sqlite"),
catalogPath = join(projectRoot, "website", "public", "data", "cards", "catalog.json"), catalogPath = join(projectRoot, "website", "public", "data", "cards", "catalog.json"),
destinationsPath = DEFAULT_DESTINATIONS_PATH,
now = Date.now, now = Date.now,
random, random,
fetchImpl = fetch, fetchImpl = fetch,
@ -127,7 +129,8 @@ export function createCardsApiHandler({
if (env.NODE_ENV === "production" && !privacyController) throw new TypeError("CARDS_PRIVACY_CONTROLLER is required when Sokko TCG is enabled in production."); if (env.NODE_ENV === "production" && !privacyController) throw new TypeError("CARDS_PRIVACY_CONTROLLER is required when Sokko TCG is enabled in production.");
const catalog = loadCardsCatalog(catalogPath); const catalog = loadCardsCatalog(catalogPath);
database = new CardsDatabase(databasePath); database = new CardsDatabase(databasePath);
service = new CardsService({ database, catalog, now, random, devPerks }); const destinations = loadExpeditionDestinations(destinationsPath, catalog);
service = new CardsService({ database, catalog, now, random, devPerks, destinations });
} }
const secureCookies = env.NODE_ENV === "production" || String(env.CARDS_PUBLIC_ORIGIN || "").startsWith("https://"); const secureCookies = env.NODE_ENV === "production" || String(env.CARDS_PUBLIC_ORIGIN || "").startsWith("https://");
const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean)); const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean));
@ -295,6 +298,34 @@ export function createCardsApiHandler({
json(res, 200, service.guessDaily(session.player.id, { day: body.day, cardId: body.cardId })); json(res, 200, service.guessDaily(session.player.id, { day: body.day, cardId: body.cardId }));
return true; return true;
} }
if (req.method === "GET" && url.pathname === "/api/cards/expeditions") {
json(res, 200, service.expeditions.getExpeditions(session.player.id));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/expeditions/preview") {
rateLimit(req, "expedition-preview", 120);
json(res, 200, service.expeditions.preview(session.player.id, await readBody(req)));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/expeditions") {
rateLimit(req, "expedition-start", 30);
json(res, 201, service.expeditions.startSolo(session.player.id, await readBody(req), String(req.headers["idempotency-key"] || "")));
return true;
}
const expeditionClaim = routeMatch(url.pathname, /^\/api\/cards\/expeditions\/([^/]+)\/claim$/);
if (req.method === "POST" && expeditionClaim) {
json(res, 200, service.expeditions.claim(session.player.id, expeditionClaim[0]));
return true;
}
if (req.method === "PUT" && url.pathname === "/api/cards/admin/expeditions/settings") {
json(res, 200, service.expeditions.updateSettings(session.player.id, (await readBody(req)).settings));
return true;
}
const expeditionCancel = routeMatch(url.pathname, /^\/api\/cards\/admin\/expeditions\/([^/]+)\/cancel$/);
if (req.method === "POST" && expeditionCancel) {
json(res, 200, service.expeditions.cancel(session.player.id, expeditionCancel[0]));
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/admin/dashboard") { if (req.method === "GET" && url.pathname === "/api/cards/admin/dashboard") {
json(res, 200, service.getAdminDashboard(session.player.id)); json(res, 200, service.getAdminDashboard(session.player.id));
return true; return true;

View file

@ -1,5 +1,6 @@
// Rôle : charge et valide le catalogue public, ses finitions et effets Sokko TCG. // Rôle : charge et valide le catalogue public, ses finitions et effets Sokko TCG.
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { STAT_IDS } from "./expedition-rules.js";
const RARITY_IDS = new Set(["common", "rare", "epic", "legendary", "mythic"]); const RARITY_IDS = new Set(["common", "rare", "epic", "legendary", "mythic"]);
const PARTICLE_SHAPE_KINDS = new Set(["sparks", "snowflakes"]); const PARTICLE_SHAPE_KINDS = new Set(["sparks", "snowflakes"]);
@ -13,6 +14,9 @@ export const FULL_ART_FORMAT = "full-art";
export const MATCH_HOLO_PALETTE_ID = "match-holo"; export const MATCH_HOLO_PALETTE_ID = "match-holo";
const CARD_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/(?:common|rare|epic|legendary)\/[a-z0-9_]+\.webp$/; const CARD_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/(?:common|rare|epic|legendary)\/[a-z0-9_]+\.webp$/;
const PACK_BACK_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/; const PACK_BACK_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/;
// Étiquettes d'expédition : vocabulaire fermé, par famille (personnage, lieu, thème, objet).
export const EXPEDITION_TAG_PATTERN = /^(personnage|lieu|theme|objet):[a-z0-9-]+$/;
const MAX_CARD_TAGS = 8;
function requireUnique(items, label) { function requireUnique(items, label) {
const ids = new Set(); const ids = new Set();
@ -24,6 +28,35 @@ function requireUnique(items, label) {
return ids; return ids;
} }
// Profil d'expédition : la part de la Puissance donnée à chaque stat, en entiers dont la somme vaut 100.
export function validExpeditionProfile(profile) {
if (!profile || typeof profile !== "object" || Array.isArray(profile) || Object.keys(profile).length !== STAT_IDS.length) return false;
if (STAT_IDS.some((stat) => !Number.isInteger(profile[stat]) || profile[stat] < 0 || profile[stat] > 100)) return false;
return STAT_IDS.reduce((sum, stat) => sum + profile[stat], 0) === 100;
}
function validateExpeditionTags(tags) {
if (!Array.isArray(tags) || !tags.length) throw new TypeError("Cards catalog expeditionTags must be a non-empty array.");
const ids = requireUnique(tags, "expeditionTags");
for (const tag of tags) {
if (!EXPEDITION_TAG_PATTERN.test(tag.id) || typeof tag.label !== "string" || !tag.label || tag.label.length > 40) {
throw new TypeError(`Invalid expedition tag ${tag.id}: family:name id and a 1 to 40 character label.`);
}
}
return ids;
}
function validateCardExpedition(card, tagIds) {
const expedition = card.expedition;
if (!expedition || !Array.isArray(expedition.tags) || !expedition.tags.length || expedition.tags.length > MAX_CARD_TAGS) {
throw new TypeError(`Card ${card.id} needs 1 to ${MAX_CARD_TAGS} expedition tags.`);
}
if (new Set(expedition.tags).size !== expedition.tags.length) throw new TypeError(`Card ${card.id} repeats an expedition tag.`);
const unknown = expedition.tags.find((tag) => !tagIds.has(tag));
if (unknown) throw new TypeError(`Card ${card.id} uses unknown expedition tag ${unknown}.`);
if (expedition.profile != null && !validExpeditionProfile(expedition.profile)) throw new TypeError(`Card ${card.id} expedition profile must give integer shares of the four stats summing to 100.`);
}
export function validateCardsCatalog(catalog) { export function validateCardsCatalog(catalog) {
if (!catalog || catalog.version !== 1) throw new TypeError("Cards catalog version must be 1."); if (!catalog || catalog.version !== 1) throw new TypeError("Cards catalog version must be 1.");
for (const key of ["rarities", "effectPresets", "effectPalettes", "particleShapes", "particlePalettes", "particlePresets", "openingEffects", "finishes", "collections", "cards", "editions"]) { for (const key of ["rarities", "effectPresets", "effectPalettes", "particleShapes", "particlePalettes", "particlePresets", "openingEffects", "finishes", "collections", "cards", "editions"]) {
@ -40,6 +73,7 @@ export function validateCardsCatalog(catalog) {
const collectionIds = requireUnique(catalog.collections, "collections"); const collectionIds = requireUnique(catalog.collections, "collections");
const cardIds = requireUnique(catalog.cards, "cards"); const cardIds = requireUnique(catalog.cards, "cards");
requireUnique(catalog.editions, "editions"); requireUnique(catalog.editions, "editions");
const expeditionTagIds = validateExpeditionTags(catalog.expeditionTags);
if ([...RARITY_IDS].some((id) => !rarityIds.has(id))) throw new TypeError("Cards catalog must declare all supported rarities."); if ([...RARITY_IDS].some((id) => !rarityIds.has(id))) throw new TypeError("Cards catalog must declare all supported rarities.");
// Poids recommandés, proposés par l'administration pour réinitialiser les taux de tirage d'un paquet. // Poids recommandés, proposés par l'administration pour réinitialiser les taux de tirage d'un paquet.
validateRarityWeights(Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, rarity.recommendedWeight])), rarityIds, "recommended weights"); validateRarityWeights(Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, rarity.recommendedWeight])), rarityIds, "recommended weights");
@ -116,6 +150,7 @@ export function validateCardsCatalog(catalog) {
|| !COLOR_PATTERN.test(collection.back?.secondary)) { || !COLOR_PATTERN.test(collection.back?.secondary)) {
throw new TypeError(`Invalid pack presentation for collection ${collection.id}.`); throw new TypeError(`Invalid pack presentation for collection ${collection.id}.`);
} }
if (!validExpeditionProfile(collection.expedition?.profile)) throw new TypeError(`Collection ${collection.id} needs an expedition profile giving integer shares of the four stats summing to 100.`);
} }
for (const card of catalog.cards) { for (const card of catalog.cards) {
@ -130,6 +165,7 @@ export function validateCardsCatalog(catalog) {
throw new TypeError(`Card ${card.id} ${cutoutKey === "cutoutImage" ? "cutout" : "full cutout"} image must be its ${label} suffixed with __cutout.`); throw new TypeError(`Card ${card.id} ${cutoutKey === "cutoutImage" ? "cutout" : "full cutout"} image must be its ${label} suffixed with __cutout.`);
} }
} }
validateCardExpedition(card, expeditionTagIds);
} }
for (const edition of catalog.editions) { for (const edition of catalog.editions) {

View file

@ -0,0 +1,158 @@
[
{
"id": "light-currents",
"name": "Les Courants de Lumière",
"description": "Les courants qui relient les îles changent de route chaque nuit. Il faut lire les étoiles pour ne pas s'y perdre.",
"coverCardId": "stellar-current-otter",
"stats": ["orientation", "bravoure", "endurance", "fortune"],
"conditions": [{ "type": "tag", "tag": "theme:voyage" }],
"dangers": [
{ "id": "crosscurrent", "label": "Courant contraire", "stat": "orientation", "unlessTags": ["lieu:vide"] },
{ "id": "drifting-isle", "label": "Île à la dérive", "stat": "bravoure", "unlessTags": ["theme:constellations"] }
],
"hidden": false
},
{
"id": "scale-crater",
"name": "Le Cratère de l'Écaille",
"description": "Le cratère où la Salamandre a trouvé l'Écaille du Néant. Les météorites y tombent encore, toutes brûlantes.",
"coverCardId": "astral-ember-salamander",
"stats": ["bravoure", "orientation", "fortune", "endurance"],
"conditions": [{ "type": "tag", "tag": "theme:veilleurs" }],
"dangers": [
{ "id": "meteor-shower", "label": "Pluie de météores", "stat": "bravoure", "unlessTags": ["theme:cometes"] },
{ "id": "crater-smoke", "label": "Fumées du cratère", "stat": "orientation", "unlessTags": ["theme:veilleurs"] }
],
"hidden": false
},
{
"id": "long-night-ice",
"name": "Les Glaces de la Longue Nuit",
"description": "Loin du Soleil, les îles se couvrent de glace. Seuls les plus endurants traversent les lacs gelés jusqu'au bout.",
"coverCardId": "starlit-ice-penguin",
"stats": ["endurance", "bravoure", "orientation", "fortune"],
"conditions": [{ "type": "tag", "tag": "theme:hiver" }],
"dangers": [
{ "id": "blizzard", "label": "Blizzard", "stat": "orientation", "unlessTags": ["theme:hiver"] },
{ "id": "thin-ice", "label": "Glace fragile", "stat": "endurance", "unlessTags": ["lieu:glaces"] }
],
"hidden": false
},
{
"id": "level-isles",
"name": "Les Îles-Niveaux",
"description": "Les rêves de jeu du Panda forment des îles pleines de blocs, de pièces et de coffres. Chaque niveau cache un trésor.",
"coverCardId": "island-arcade-cabinet",
"stats": ["fortune", "bravoure", "endurance", "orientation"],
"conditions": [{ "type": "tag", "tag": "lieu:iles-jeux" }],
"dangers": [
{ "id": "final-boss", "label": "Boss de fin", "stat": "bravoure", "unlessTags": ["theme:aventure"] },
{ "id": "falling-blocks", "label": "Pluie de blocs", "stat": "fortune", "unlessTags": ["personnage:cameleon", "theme:tresor"] }
],
"hidden": false
},
{
"id": "milky-way-band",
"name": "La Bande de la Voie Lactée",
"description": "Là où dort le Panda, la poussière d'étoiles s'assemble en rêves. On y trouve parfois une île qui vient de naître.",
"coverCardId": "milky-way-panda",
"stats": ["fortune", "orientation", "bravoure", "endurance"],
"conditions": [{ "type": "tag", "tag": "theme:reves" }],
"dangers": [
{ "id": "deep-sleep", "label": "Sommeil profond", "stat": "endurance", "unlessTags": ["theme:nuit"] },
{ "id": "dust-storm", "label": "Tempête de poussière", "stat": "orientation", "unlessTags": ["theme:poussiere"] }
],
"hidden": false
},
{
"id": "dawn-shore",
"name": "Le Rivage de l'Aube",
"description": "Sur les îles tournées vers le Soleil, le jour se lève avant partout ailleurs. Le vent brûlant y souffle fort.",
"coverCardId": "solar-dawn-capybara",
"stats": ["endurance", "fortune", "bravoure", "orientation"],
"conditions": [{ "type": "tag", "tag": "lieu:soleil" }],
"dangers": [
{ "id": "scorching-wind", "label": "Vent brûlant", "stat": "endurance", "unlessTags": ["personnage:loup"] },
{ "id": "blinding-light", "label": "Lumière aveuglante", "stat": "orientation", "unlessTags": ["lieu:soleil"] }
],
"hidden": false
},
{
"id": "comet-lakes",
"name": "Les Lacs des Comètes",
"description": "L'eau des îles est arrivée avec les comètes. Leurs lacs les plus anciens gardent des pierres aux reflets argentés.",
"coverCardId": "cosmic-water-axolotl",
"stats": ["fortune", "endurance", "orientation", "bravoure"],
"conditions": [{ "type": "tag", "tag": "theme:eau" }],
"dangers": [
{ "id": "flash-flood", "label": "Crue soudaine", "stat": "fortune", "unlessTags": ["personnage:loutre"] },
{ "id": "comet-tail", "label": "Queue de comète", "stat": "endurance", "unlessTags": ["theme:cometes"] }
],
"hidden": false
},
{
"id": "great-void",
"name": "Le Grand Vide",
"description": "Entre les îles, le noir est profond et les repères rares. Les bateaux du ciel y voyagent lentement.",
"coverCardId": "deep-sky-ray",
"stats": ["orientation", "endurance", "bravoure", "fortune"],
"conditions": [{ "type": "tag", "tag": "lieu:vide" }],
"dangers": [
{ "id": "void-mist", "label": "Brume du vide", "stat": "orientation", "unlessTags": ["theme:constellations"] },
{ "id": "silent-dark", "label": "Noir silencieux", "stat": "endurance", "unlessTags": ["theme:nuit"] }
],
"hidden": false
},
{
"id": "old-observatories",
"name": "Les Vieux Observatoires",
"description": "Les premiers observatoires des Veilleurs sont pleins de cartes, de carnets et d'instruments oubliés.",
"coverCardId": "watchers-spyglass",
"stats": ["orientation", "fortune", "endurance", "bravoure"],
"conditions": [{ "type": "tag", "tag": "theme:veilleurs" }],
"dangers": [
{ "id": "starless-night", "label": "Nuit sans étoiles", "stat": "orientation", "unlessTags": ["personnage:hibou"] },
{ "id": "crumbling-tower", "label": "Tour qui s'effrite", "stat": "fortune", "unlessTags": ["theme:veilleurs"] }
],
"hidden": false
},
{
"id": "reunited-isles-feast",
"name": "La Fête des Îles Réunies",
"description": "Pendant la Longue Nuit, les îles se rapprochent pour la grande fête. Il y a des cadeaux à livrer dans tout l'archipel.",
"coverCardId": "celestial-fox-mask",
"stats": ["bravoure", "fortune", "orientation", "endurance"],
"conditions": [{ "type": "tag", "tag": "theme:fete" }],
"dangers": [
{ "id": "feast-crowd", "label": "Foule du réveillon", "stat": "orientation", "unlessTags": ["theme:hiver"] },
{ "id": "lost-gifts", "label": "Cadeaux égarés", "stat": "fortune", "unlessTags": ["theme:fete"] }
],
"hidden": false
},
{
"id": "forgotten-ruins",
"name": "Les Ruines Oubliées",
"description": "Des temples rêvés se cachent sous la végétation des îles-jeux. Leurs pièges gardent toujours un trésor.",
"coverCardId": "lost-ruins-meerkat",
"stats": ["bravoure", "endurance", "orientation", "fortune"],
"conditions": [{ "type": "tag", "tag": "theme:tresor" }],
"dangers": [
{ "id": "ancient-trap", "label": "Piège ancien", "stat": "endurance", "unlessTags": ["theme:aventure"] },
{ "id": "maze-corridors", "label": "Couloirs en labyrinthe", "stat": "orientation", "unlessTags": ["personnage:herisson", "personnage:suricate"] }
],
"hidden": false
},
{
"id": "pale-moon-slope",
"name": "Le Versant de la Lune Pâle",
"description": "Sous la Lune Pâle, les roches bleues brillent dans le noir. Il fait froid, mais on y voit loin.",
"coverCardId": "pale-moon-owl",
"stats": ["endurance", "orientation", "fortune", "bravoure"],
"conditions": [{ "type": "tag", "tag": "theme:nuit" }],
"dangers": [
{ "id": "lunar-cold", "label": "Froid lunaire", "stat": "endurance", "unlessTags": ["lieu:glaces"] },
{ "id": "veiled-moon", "label": "Lune voilée", "stat": "orientation", "unlessTags": ["lieu:lune-pale", "personnage:hibou"] }
],
"hidden": false
}
]

View file

@ -3,6 +3,7 @@ import { mkdirSync } from "node:fs";
import { dirname } from "node:path"; import { dirname } from "node:path";
import { DatabaseSync } from "node:sqlite"; import { DatabaseSync } from "node:sqlite";
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "./admin-seed.js"; 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 = [ const MIGRATIONS = [
` `
@ -219,6 +220,84 @@ const MIGRATIONS = [
PRIMARY KEY (player_id, day) PRIMARY KEY (player_id, day)
) STRICT; ) STRICT;
CREATE INDEX daily_attempts_day_idx ON daily_attempts(day, status); 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);
` `
]; ];

View file

@ -0,0 +1,72 @@
// Rôle : charge et valide les destinations des Expéditions Sokko TCG, définies dans un fichier du serveur pour garder secrètes les destinations cachées.
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { cardExpeditionData, isExpeditionCard, STAT_IDS } from "./expedition-rules.js";
export const DEFAULT_DESTINATIONS_PATH = fileURLToPath(new URL("./content/expedition-destinations.json", import.meta.url));
const ID_PATTERN = /^[a-z0-9-]+$/;
// Une condition ou un danger doit pouvoir être rempli par au moins ce nombre de cartes rare ou mieux.
export const MIN_MATCHING_CARDS = 3;
function fail(destination, message) {
throw new TypeError(`Expedition destination ${destination?.id ?? "?"}: ${message}`);
}
// Cartes rare ou mieux qui portent une des étiquettes, ou qui appartiennent à la collection.
function matchingCards(catalog, { tags = [], collectionId = null }) {
return catalog.cards.filter((card) => {
if (!isExpeditionCard(catalog, card.id)) return false;
const data = cardExpeditionData(catalog, card.id);
return collectionId ? data.collectionId === collectionId : data.tags.some((tag) => tags.includes(tag));
});
}
export function validateExpeditionDestinations(destinations, catalog) {
if (!Array.isArray(destinations) || !destinations.length) throw new TypeError("Expedition destinations must be a non-empty array.");
const tagIds = new Set(catalog.expeditionTags.map((tag) => tag.id));
const collectionIds = new Set(catalog.collections.map((collection) => collection.id));
const cardIds = new Set(catalog.cards.map((card) => card.id));
const ids = new Set();
for (const destination of destinations) {
if (!ID_PATTERN.test(destination?.id ?? "")) fail(destination, "needs a lowercase id.");
if (ids.has(destination.id)) fail(destination, "duplicate id.");
ids.add(destination.id);
if (typeof destination.name !== "string" || !destination.name || destination.name.length > 60) fail(destination, "name must contain 1 to 60 characters.");
if (typeof destination.description !== "string" || !destination.description || destination.description.length > 200) fail(destination, "description must contain 1 to 200 characters.");
if (destination.coverCardId != null && !cardIds.has(destination.coverCardId)) fail(destination, "unknown cover card.");
if (typeof destination.hidden !== "boolean") fail(destination, "hidden must be a boolean.");
if (!Array.isArray(destination.stats) || destination.stats.length !== STAT_IDS.length || new Set(destination.stats).size !== STAT_IDS.length
|| destination.stats.some((stat) => !STAT_IDS.includes(stat))) {
fail(destination, "stats must order the four stats.");
}
if (!Array.isArray(destination.conditions) || !destination.conditions.length) fail(destination, "needs at least one condition.");
for (const condition of destination.conditions) {
if (condition?.type === "tag") {
if (!tagIds.has(condition.tag)) fail(destination, `unknown condition tag ${condition.tag}.`);
if (matchingCards(catalog, { tags: [condition.tag] }).length < MIN_MATCHING_CARDS) fail(destination, `condition ${condition.tag} matches fewer than ${MIN_MATCHING_CARDS} rare or better cards.`);
} else if (condition?.type === "collection") {
if (!collectionIds.has(condition.collectionId)) fail(destination, `unknown condition collection ${condition.collectionId}.`);
if (matchingCards(catalog, { collectionId: condition.collectionId }).length < MIN_MATCHING_CARDS) fail(destination, `condition ${condition.collectionId} matches fewer than ${MIN_MATCHING_CARDS} rare or better cards.`);
} else {
fail(destination, "condition type must be tag or collection.");
}
}
if (!Array.isArray(destination.dangers) || !destination.dangers.length) fail(destination, "needs at least one danger.");
const dangerIds = new Set();
for (const danger of destination.dangers) {
if (!ID_PATTERN.test(danger?.id ?? "") || dangerIds.has(danger.id)) fail(destination, "every danger needs a unique lowercase id.");
dangerIds.add(danger.id);
if (typeof danger.label !== "string" || !danger.label || danger.label.length > 40) fail(destination, `danger ${danger.id} label must contain 1 to 40 characters.`);
if (!STAT_IDS.includes(danger.stat)) fail(destination, `danger ${danger.id} needs a known stat.`);
if (!Array.isArray(danger.unlessTags) || !danger.unlessTags.length || danger.unlessTags.some((tag) => !tagIds.has(tag))) fail(destination, `danger ${danger.id} needs known counter tags.`);
if (matchingCards(catalog, { tags: danger.unlessTags }).length < MIN_MATCHING_CARDS) fail(destination, `danger ${danger.id} can be countered by fewer than ${MIN_MATCHING_CARDS} rare or better cards.`);
}
}
if (!destinations.some((destination) => !destination.hidden)) throw new TypeError("Expedition destinations need at least one visible destination.");
return destinations;
}
export function loadExpeditionDestinations(path, catalog) {
return validateExpeditionDestinations(JSON.parse(readFileSync(path, "utf8")), catalog);
}

View file

@ -0,0 +1,258 @@
// Rôle : règles pures des Expéditions Sokko TCG (Puissance, stats, exigences par place, dangers, score, palier, butin, tirage du jour).
// Aucune fonction ne lit la base ni l'horloge, et le hasard est toujours passé en paramètre : `random(max)` renvoie un entier dans [0, max).
import { cardRarity } from "./daily.js";
export const STAT_IDS = Object.freeze(["bravoure", "endurance", "fortune", "orientation"]);
// Rôle d'une place : il double la stat correspondante de la carte qui l'occupe.
export const ROLE_BY_STAT = Object.freeze({ bravoure: "leader", endurance: "guardian", fortune: "seeker", orientation: "navigator" });
export const STAT_BY_ROLE = Object.freeze(Object.fromEntries(Object.entries(ROLE_BY_STAT).map(([stat, role]) => [role, stat])));
export const TIER_IDS = Object.freeze(["struggle", "success", "triumph"]);
export const MAX_STARS = 5;
// Nombre de stats exigées selon les étoiles : la 4e étoile ajoute un danger, la 5e la dernière stat et un second danger.
const REQUIRED_STATS = Object.freeze([1, 2, 3, 3, 4]);
const DANGER_COUNT = Object.freeze([0, 0, 0, 1, 2]);
export const EXPEDITION_RARITIES = Object.freeze(["rare", "epic", "legendary", "mythic"]);
export const requiredStatCount = (stars) => REQUIRED_STATS[stars - 1];
export const dangerCount = (stars) => DANGER_COUNT[stars - 1];
export const hasCondition = (stars) => stars >= 3;
// Puissance d'une carte selon sa rareté et son niveau ; une commune n'en a pas (elle servira d'équipement).
export function cardPower(rarity, level, settings) {
const base = settings.power[rarity];
if (!Number.isInteger(base)) return 0;
return Math.min(settings.power.cap, base + Math.max(0, level) * settings.power.perLevel);
}
// Niveau qui amène une rareté au plafond.
export function maxLevel(rarity, settings) {
const base = settings.power[rarity];
if (!Number.isInteger(base) || base >= settings.power.cap) return 0;
return Math.ceil((settings.power.cap - base) / settings.power.perLevel);
}
// Répartit la Puissance selon le profil (pourcentages), au plus grand reste : la somme des stats vaut exactement la Puissance.
export function splitPower(power, profile) {
const raw = STAT_IDS.map((stat) => (power * profile[stat]) / 100);
const stats = raw.map(Math.floor);
let left = power - stats.reduce((sum, value) => sum + value, 0);
const order = raw.map((value, index) => [value - Math.floor(value), index]).sort((a, b) => b[0] - a[0] || a[1] - b[1]);
for (const [, index] of order) {
if (left <= 0) break;
stats[index] += 1;
left -= 1;
}
return Object.fromEntries(STAT_IDS.map((stat, index) => [stat, stats[index]]));
}
// Données d'expédition d'une carte : son profil (ou celui de sa collection), ses étiquettes et sa collection.
export function cardExpeditionData(catalog, cardId) {
const card = catalog.cards.find((item) => item.id === cardId);
if (!card) return null;
const collection = catalog.collections.find((item) => item.id === card.collectionId);
return {
cardId,
collectionId: card.collectionId,
tags: card.expedition?.tags || [],
profile: card.expedition?.profile || collection?.expedition?.profile || null
};
}
// Ce qu'une édition apporte à une expédition : rareté de l'édition (une mythique garde la sienne), Puissance et stats.
export function editionExpeditionData(catalog, editionId, level, settings) {
const edition = catalog.editions.find((item) => item.id === editionId);
if (!edition) return null;
const data = cardExpeditionData(catalog, edition.cardId);
if (!data?.profile || !EXPEDITION_RARITIES.includes(edition.rarity)) return null;
const power = cardPower(edition.rarity, level, settings);
return { ...data, editionId, rarity: edition.rarity, level, power, stats: splitPower(power, data.profile) };
}
export const isExpeditionCard = (catalog, cardId) => EXPEDITION_RARITIES.includes(cardRarity(catalog, cardId));
// Rôles des places en solo : la destination fixe ceux de ses deux premières stats.
export function soloRoles(destination, slotCount) {
return destination.stats.slice(0, slotCount);
}
// Exigence d'une stat = valeur par place × (nombre de places + places dont le rôle double cette stat).
// Le solo et le groupe gardent ainsi le même rapport ; une place sans rôle (Veilleur de la Guilde) n'ajoute que sa part.
export function requirementsFor(destination, stars, slotRoles, settings) {
const perSlot = settings.requirements[`star${stars}`];
return destination.stats.slice(0, requiredStatCount(stars)).map((stat, index) => ({
stat,
main: index === 0,
value: perSlot[index] * (slotRoles.length + slotRoles.filter((role) => role === stat).length)
}));
}
// Somme des stats de l'équipe ; le rôle d'une place multiplie la stat correspondante de sa carte.
export function teamStats(slots, settings) {
const total = Object.fromEntries(STAT_IDS.map((stat) => [stat, 0]));
for (const slot of slots) {
for (const stat of STAT_IDS) {
const multiplier = slot.role === stat ? settings.roles.multiplierPct / 100 : 1;
total[stat] += (slot.stats?.[stat] || 0) * multiplier;
}
}
return total;
}
const slotMatches = (slot, condition) => (condition.type === "tag" ? slot.tags?.includes(condition.tag) : slot.collectionId === condition.collectionId);
export function conditionMet(slots, condition) {
return slots.some((slot) => slotMatches(slot, condition));
}
export function dangerCountered(slots, danger) {
return slots.some((slot) => danger.unlessTags.some((tag) => slot.tags?.includes(tag)));
}
// Malus de durée et dangers. L'Endurance de l'équipe (avant malus) efface le malus de durée et sert de bouclier contre un danger.
export function applyHazards(stats, { slotCount, durationIndex, dangers = [] }, settings) {
const endurance = stats.endurance;
const result = { ...stats };
const durationMalus = settings.durations.malusPct[durationIndex] / 100;
const durationCover = Math.min(1, endurance / (settings.durations.endurancePerSlot * slotCount));
const durationFactor = 1 - durationMalus * (1 - durationCover);
for (const stat of STAT_IDS) result[stat] *= durationFactor;
const shield = Math.min(1, endurance / (settings.danger.endurancePerSlot * slotCount)) * (settings.danger.shieldMaxPct / 100);
const dangerFactor = 1 - (settings.danger.malusPct / 100) * (1 - shield);
const appliedDangers = dangers.map((danger) => {
if (!danger.countered) result[danger.stat] *= dangerFactor;
return { ...danger, factor: danger.countered ? 1 : dangerFactor };
});
return { stats: result, durationFactor, dangers: appliedDangers };
}
// Rendement d'une exigence : plein jusqu'à 100 %, puis réduit, jusqu'au plafond.
export function efficiency(ratio, settings) {
const over = Math.min(Math.max(ratio - 1, 0), settings.score.overflowSpanPct / 100);
return Math.min(ratio, 1) + (settings.score.overflowPct / 100) * over;
}
export function tierFor(scorePct, settings) {
if (scorePct >= settings.score.triumphPct) return "triumph";
if (scorePct >= settings.score.successPct) return "success";
return "struggle";
}
// Score de l'équipe : moyenne pondérée des rendements (stat principale plus lourde), condition, bonus de synergies, plafond.
export function scoreExpedition({ requirements, stats, conditionMet: met = null, synergyPct = 0 }, settings) {
let weighted = 0;
let weights = 0;
const perRequirement = requirements.map((requirement) => {
const ratio = requirement.value > 0 ? stats[requirement.stat] / requirement.value : 1;
const weight = requirement.main ? settings.score.mainWeight : settings.score.otherWeight;
const value = efficiency(ratio, settings);
weighted += value * weight;
weights += weight;
return { ...requirement, team: stats[requirement.stat], ratioPct: ratio * 100, efficiencyPct: value * 100 };
});
const conditionFactor = met === false ? 1 - settings.requirements.conditionMissPct / 100 : 1;
const raw = (weights ? weighted / weights : 0) * 100 * conditionFactor * (1 + synergyPct / 100);
const scorePct = Math.min(settings.score.capPct, raw);
return { perRequirement, conditionFactor, scorePct, tier: tierFor(scorePct, settings) };
}
function evaluateAt({ destination, entry, stars, durationIndex, slots }, base, settings) {
const slotRoles = slots.map((slot) => slot.role ?? null);
const requirements = requirementsFor(destination, stars, slotRoles, settings);
const condition = hasCondition(stars) ? entry.condition : null;
const dangers = (entry.dangers || []).slice(0, dangerCount(stars)).map((danger) => ({ ...danger, countered: dangerCountered(slots, danger) }));
const hazards = applyHazards(base, { slotCount: slots.length, durationIndex, dangers }, settings);
const met = condition ? conditionMet(slots, condition) : null;
const score = scoreExpedition({ requirements, stats: hazards.stats, conditionMet: met }, settings);
return { requirements, baseStats: base, stats: hazards.stats, durationFactor: hazards.durationFactor, dangers: hazards.dangers, condition, conditionMet: met, ...score };
}
// Évalue une équipe sur une destination du jour : c'est le calcul complet du départ et de l'aperçu.
// `slots` : [{ stats, role (stat doublée ou null), tags, collectionId }]. `entry` : { condition, dangers } de la destination du jour.
// Une étoile de plus ne peut jamais améliorer le score : sans cette règle, une équipe faible sur la stat principale
// gagnerait des points en ajoutant une stat où elle est forte. Le score retenu est donc le plus bas des niveaux 1 à `stars`.
export function evaluateTeam(input, settings) {
const base = teamStats(input.slots, settings);
const result = evaluateAt(input, base, settings);
let scorePct = result.scorePct;
let limitedByStars = null;
for (let stars = input.stars - 1; stars >= 1; stars -= 1) {
const lower = evaluateAt({ ...input, stars }, base, settings).scorePct;
if (lower < scorePct) {
scorePct = lower;
limitedByStars = stars;
}
}
return { ...result, scorePct, limitedByStars, tier: tierFor(scorePct, settings) };
}
// Butin espéré (valeurs fractionnaires) : il est proportionnel à la durée choisie, donc identique par heure.
export function expectedLoot({ hours, stars, tier, fortune, slotCount, bonusSlot = null }, settings) {
const { loot } = settings;
const bonus = bonusSlot ? loot.bonusSlotPct[bonusSlot - 5] / 100 : 1;
const base = hours * (loot.difficultyPct[stars - 1] / 100) * (loot.tierPct[TIER_IDS.indexOf(tier)] / 100) * bonus;
const fortuneBonusPct = Math.min(loot.fortuneCapPct, (fortune / Math.max(1, slotCount)) * loot.fortunePerPointPct);
return {
eclats: base * (loot.eclatsPerHourCents / 100),
stardust: base * (loot.stardustPerHourCents / 100),
packs: Math.min(loot.maxPacks, base * (loot.packPerHourPermille / 1000) * (1 + fortuneBonusPct / 100)),
fortuneBonusPct
};
}
// Arrondi aléatoire qui conserve la moyenne : partie entière, plus une unité avec la probabilité de la partie décimale.
export function roundStochastic(value, random) {
const whole = Math.floor(value);
return whole + (random(1000) < Math.round((value - whole) * 1000) ? 1 : 0);
}
export function rollLoot(expected, settings, random) {
return {
eclats: roundStochastic(expected.eclats, random),
stardust: roundStochastic(expected.stardust, random),
packs: Math.min(settings.loot.maxPacks, roundStochastic(expected.packs, random))
};
}
function weightedPick(entries, random) {
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
let cursor = random(total);
for (const entry of entries) {
cursor -= entry.weight;
if (cursor < 0) return entry;
}
return entries.at(-1);
}
// Destinations du jour : tirées selon leur poids parmi les destinations actives et non cachées, en évitant celles des jours précédents
// tant qu'il en reste assez. Pour chacune : l'indice de sa condition et ceux de deux dangers (le second sert au 5 ★).
export function drawExpeditionDay(destinations, settings, recentIds, random) {
const candidates = destinations
.filter((destination) => !destination.hidden)
.map((destination) => ({ destination, ...(settings.destinations[destination.id] || { active: true, weight: 1 }) }))
.filter((entry) => entry.active && entry.weight > 0);
const count = Math.min(settings.day.destinationsPerDay, candidates.length);
const recent = new Set(recentIds);
const fresh = candidates.filter((entry) => !recent.has(entry.destination.id));
let pool = fresh.length >= count ? fresh : candidates;
const picked = [];
while (picked.length < count && pool.length) {
const entry = weightedPick(pool, random);
picked.push(entry.destination);
pool = pool.filter((item) => item !== entry);
}
return picked.map((destination) => {
const first = random(destination.dangers.length);
const second = destination.dangers.length > 1 ? (first + 1 + random(destination.dangers.length - 1)) % destination.dangers.length : first;
return { destinationId: destination.id, conditionIndex: random(destination.conditions.length), dangerIndexes: [first, second] };
});
}
// Destination du jour prête à jouer : condition et dangers résolus. Null si la destination a disparu du contenu.
export function resolveDayEntry(destinations, draw) {
const destination = destinations.find((item) => item.id === draw.destinationId);
if (!destination) return null;
const condition = destination.conditions[draw.conditionIndex] || destination.conditions[0];
const indexes = [...new Set(draw.dangerIndexes)];
const dangers = indexes.map((index) => destination.dangers[index]).filter(Boolean);
return { destination, entry: { condition, dangers } };
}

View file

@ -0,0 +1,384 @@
// Rôle : applique les règles des Expéditions Sokko TCG avec la base (destinations du jour, départ solo, retour, réglages d'administration).
// Branché sur CardsService (`service.expeditions`) : il réutilise sa base, son horloge, son hasard, son audit et sa collection.
import { randomInt, randomUUID } from "node:crypto";
import { dailyDayKey, nextDailyAt, shiftDayKey } from "./daily.js";
import {
dangerCount, drawExpeditionDay, editionExpeditionData, evaluateTeam, expectedLoot, hasCondition, MAX_STARS, requirementsFor, resolveDayEntry,
ROLE_BY_STAT, rollLoot, soloRoles, STAT_BY_ROLE
} from "./expedition-rules.js";
import {
DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, validateExpeditionSettings
} from "./expedition-settings.js";
const HOUR_MS = 3_600_000;
function fail(status, code, message) {
throw Object.assign(new Error(message), { status, code });
}
const parse = (value) => (value == null ? null : JSON.parse(value));
const round1 = (value) => Math.round(value * 10) / 10;
export class ExpeditionService {
constructor(cards, destinations) {
this.cards = cards;
this.db = cards.db;
this.destinations = destinations;
this.destinationIds = destinations.map((destination) => destination.id);
}
now() {
return this.cards.now();
}
random(max) {
return this.cards.random ? this.cards.random(max) : randomInt(max);
}
// Réglages en vigueur : un champ stocké invalide reprend sa valeur par défaut, pour que le jeu reste jouable.
get settings() {
const row = this.db.prepare("SELECT settings_json FROM expedition_settings WHERE id = 1").get();
return mergeExpeditionSettings(parse(row?.settings_json) || {}, this.destinationIds, (path) => console.error(`Invalid stored expedition setting ${path}; using its default.`));
}
settingsUpdatedAt() {
return this.db.prepare("SELECT updated_at FROM expedition_settings WHERE id = 1").get()?.updated_at ?? 0;
}
updateSettings(adminId, settings) {
this.cards.requireAdmin(adminId);
const error = validateExpeditionSettings(settings, this.destinationIds);
if (error) fail(400, "EXPEDITION_SETTINGS_INVALID", error);
const previous = this.settings;
const next = mergeExpeditionSettings(settings, this.destinationIds);
const changes = diffExpeditionSettings(previous, next);
if (!changes.length) fail(409, "EXPEDITION_SETTINGS_UNCHANGED", "Ces réglages sont déjà en vigueur.");
this.cards.database.transaction(() => {
this.db.prepare("UPDATE expedition_settings SET settings_json = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(JSON.stringify(next), this.now(), adminId);
this.cards.audit(adminId, "expedition_settings_updated", "expeditions", { changes });
});
return { expeditionSettings: this.adminSettings() };
}
// Ce que l'administration affiche et modifie : réglages, valeurs par défaut, bornes et destinations (définies côté serveur).
adminSettings() {
return {
settings: this.settings,
defaults: mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, this.destinationIds),
schema: EXPEDITION_SETTINGS_SCHEMA,
destinations: this.destinations.map((destination) => ({ id: destination.id, name: destination.name, hidden: destination.hidden })),
updatedAt: this.settingsUpdatedAt()
};
}
// Destinations du jour, tirées au premier appel du jour de Paris. À appeler dans une transaction.
ensureDay(day, settings) {
const stored = () => this.db.prepare("SELECT draw_json FROM expedition_days WHERE day = ?").get(day);
if (!stored()) {
const recentDays = settings.day.avoidRepeatDays ? this.db.prepare("SELECT draw_json FROM expedition_days WHERE day >= ? AND day < ?").all(shiftDayKey(day, -settings.day.avoidRepeatDays), day) : [];
const recent = recentDays.flatMap((row) => JSON.parse(row.draw_json).map((entry) => entry.destinationId));
const draw = drawExpeditionDay(this.destinations, settings, recent, (max) => this.random(max));
if (!draw.length) fail(409, "EXPEDITIONS_UNAVAILABLE", "Aucune destination n’est ouverte aujourd’hui.");
this.db.prepare("INSERT INTO expedition_days(day, draw_json, created_at) VALUES (?, ?, ?)").run(day, JSON.stringify(draw), this.now());
}
// Une destination retirée du contenu après le tirage disparaît simplement de la liste du jour.
return JSON.parse(stored().draw_json).map((draw) => resolveDayEntry(this.destinations, draw)).filter(Boolean);
}
today(settings) {
const day = dailyDayKey(this.now());
return { day, entries: this.cards.database.transaction(() => this.ensureDay(day, settings)) };
}
// Éditions occupées : celles d'une expédition en route dont le butin n'a pas encore été récupéré par leur propriétaire.
busyEditions(playerId) {
return new Map(this.db.prepare(`SELECT s.edition_id, e.id, e.returns_at FROM expedition_slots s
JOIN expeditions e ON e.id = s.expedition_id
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = s.player_id
WHERE s.player_id = ? AND e.status = 'running' AND m.claimed_at IS NULL AND s.edition_id IS NOT NULL`).all(playerId)
.map((row) => [row.edition_id, { expeditionId: row.id, returnsAt: row.returns_at }]));
}
// Cartes du joueur jouables en expédition (rare ou mieux, révélées), avec leur Puissance et leurs stats.
eligibleCards(playerId, settings) {
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' LIMIT 1").get(playerId);
const busy = this.busyEditions(playerId);
return this.cards.visibleCollection(playerId, pending?.id).map((entry) => {
const data = editionExpeditionData(this.cards.catalog, entry.editionId, 0, settings);
if (!data) return null;
const busyEntry = busy.get(entry.editionId);
return { ...data, busy: Boolean(busyEntry), busyUntil: busyEntry?.returnsAt ?? null };
}).filter(Boolean);
}
activeCount(playerId, mode) {
return this.db.prepare(`SELECT COUNT(*) AS count FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND e.mode = ? AND e.status = 'running' AND m.claimed_at IS NULL`).get(playerId, mode).count;
}
// Destination du jour vue par le joueur : rôles du solo et exigences chiffrées pour chaque étoile autorisée.
destinationView({ destination, entry }, settings) {
const roles = soloRoles(destination, settings.solo.cards);
const stars = {};
for (let star = settings.solo.minStars; star <= settings.solo.maxStars; star += 1) {
stars[star] = {
requirements: requirementsFor(destination, star, roles, settings),
condition: hasCondition(star) ? entry.condition : null,
dangers: entry.dangers.slice(0, dangerCount(star))
};
}
return { id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, stats: destination.stats, roles, stars };
}
// Valide une équipe solo et calcule son résultat (sans écriture) : base commune de l'aperçu et du départ.
// `today` : { day, entries }, les destinations du jour, lues par l'appelant (dans sa transaction pour un départ).
prepareSolo(playerId, body, settings, today) {
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
const { day, entries } = today;
if (body?.day !== day) fail(409, "EXPEDITION_DAY_EXPIRED", "Les destinations ont changé : rechargez les Expéditions du jour.");
const resolved = entries.find((item) => item.destination.id === body.destinationId);
if (!resolved) fail(400, "EXPEDITION_INVALID", "Cette destination n’est pas proposée aujourd’hui.");
const stars = body.difficulty;
if (!Number.isInteger(stars) || stars < settings.solo.minStars || stars > settings.solo.maxStars) fail(400, "EXPEDITION_INVALID", "Difficulté invalide.");
const durationIndex = settings.durations.hours.indexOf(body.durationHours);
if (durationIndex < 0) fail(400, "EXPEDITION_INVALID", "Durée invalide.");
const editionIds = body.slots;
if (!Array.isArray(editionIds) || editionIds.length !== settings.solo.cards || editionIds.some((id) => typeof id !== "string")) {
fail(400, "EXPEDITION_CARD_INVALID", `Choisissez ${settings.solo.cards} cartes.`);
}
const owned = new Map(this.eligibleCards(playerId, settings).map((card) => [card.editionId, card]));
const roles = soloRoles(resolved.destination, settings.solo.cards);
const slots = editionIds.map((editionId, position) => {
const data = editionExpeditionData(this.cards.catalog, editionId, 0, settings);
if (!data) fail(400, "EXPEDITION_CARD_INVALID", "Seules les cartes rares, épiques, légendaires et mythiques partent en expédition.");
const card = owned.get(editionId);
if (!card) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte.");
return { ...card, role: roles[position], position };
});
if (new Set(slots.map((slot) => slot.cardId)).size !== slots.length) fail(400, "EXPEDITION_CARD_INVALID", "Une même carte ne peut occuper qu’une place.");
const evaluation = evaluateTeam({ destination: resolved.destination, entry: resolved.entry, stars, durationIndex, slots }, settings);
const hours = settings.durations.hours[durationIndex];
const expected = expectedLoot({ hours, stars, tier: evaluation.tier, fortune: evaluation.stats.fortune, slotCount: slots.length }, settings);
return { day, resolved, stars, durationIndex, hours, slots, evaluation, expected };
}
resultView(evaluation) {
return {
scorePct: round1(evaluation.scorePct),
tier: evaluation.tier,
limitedByStars: evaluation.limitedByStars,
conditionMet: evaluation.conditionMet,
durationFactor: evaluation.durationFactor,
stats: Object.fromEntries(Object.entries(evaluation.stats).map(([stat, value]) => [stat, round1(value)])),
requirements: evaluation.perRequirement.map((item) => ({ stat: item.stat, main: item.main, value: item.value, team: round1(item.team), ratioPct: round1(item.ratioPct) })),
dangers: evaluation.dangers.map((danger) => ({ id: danger.id, label: danger.label, stat: danger.stat, unlessTags: danger.unlessTags, countered: danger.countered }))
};
}
preview(playerId, body) {
const settings = this.settings;
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
const plan = this.prepareSolo(playerId, body, settings, this.today(settings));
return {
preview: {
...this.resultView(plan.evaluation),
expected: { eclats: round1(plan.expected.eclats), stardust: round1(plan.expected.stardust), packChancePct: round1(Math.min(1, plan.expected.packs) * 100), fortuneBonusPct: round1(plan.expected.fortuneBonusPct) }
}
};
}
// Collection d'un paquet rapporté : une collection permanente ouverte, au hasard.
packCollection() {
const collections = this.cards.catalog.collections.filter((collection) => collection.active && collection.packCategory === "permanent" && collection.dropWeights);
return collections.length ? collections[this.random(collections.length)].id : null;
}
startSolo(playerId, body, requestKey) {
if (!requestKey || requestKey.length > 100) fail(400, "IDEMPOTENCY_REQUIRED", "Une clé d'idempotence est requise.");
const settings = this.settings;
let expeditionId;
this.cards.database.transaction(() => {
const previous = this.db.prepare("SELECT response_json FROM idempotency WHERE player_id = ? AND scope = 'expedition-start' AND request_key = ?").get(playerId, requestKey);
if (previous) {
expeditionId = JSON.parse(previous.response_json).expeditionId;
return;
}
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
const day = dailyDayKey(this.now());
const plan = this.prepareSolo(playerId, body, settings, { day, entries: this.ensureDay(day, settings) });
const busy = plan.slots.find((slot) => slot.busy);
if (busy) fail(409, "EXPEDITION_CARD_BUSY", "Cette carte est déjà en expédition.");
if (this.activeCount(playerId, "solo") >= settings.solo.maxConcurrent) fail(409, "EXPEDITION_LIMIT", "Récupérez d’abord le butin de votre expédition en cours.");
const now = this.now();
const loot = rollLoot(plan.expected, settings, (max) => this.random(max));
const packs = [];
for (let index = 0; index < loot.packs; index += 1) {
const collectionId = this.packCollection();
if (collectionId) packs.push(collectionId);
}
const { destination } = plan.resolved;
const setup = {
destination: { id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, stats: destination.stats },
condition: plan.evaluation.condition,
stars: plan.stars,
hours: plan.hours,
bonusSlot: null,
roles: plan.slots.map((slot) => slot.role)
};
expeditionId = randomUUID();
this.db.prepare(`INSERT INTO expeditions(id, mode, day, destination_id, difficulty, duration_ms, creator_id, status, setup_json, result_json, created_at, departs_at, returns_at)
VALUES (?, 'solo', ?, ?, ?, ?, ?, 'running', ?, ?, ?, ?, ?)`)
.run(expeditionId, plan.day, destination.id, plan.stars, plan.hours * HOUR_MS, playerId, JSON.stringify(setup), JSON.stringify(this.resultView(plan.evaluation)), now, now, now + plan.hours * HOUR_MS);
this.db.prepare("INSERT INTO expedition_members(expedition_id, player_id, reward_json, joined_at) VALUES (?, ?, ?, ?)")
.run(expeditionId, playerId, JSON.stringify({ eclats: loot.eclats, stardust: loot.stardust, packs }), now);
const insertSlot = this.db.prepare("INSERT INTO expedition_slots(expedition_id, position, role, player_id, edition_id, card_id, level, stats_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
for (const slot of plan.slots) insertSlot.run(expeditionId, slot.position, ROLE_BY_STAT[slot.role] ?? null, playerId, slot.editionId, slot.cardId, slot.level, JSON.stringify(slot.stats));
this.db.prepare("INSERT INTO idempotency(player_id, scope, request_key, response_json, created_at) VALUES (?, 'expedition-start', ?, ?, ?)")
.run(playerId, requestKey, JSON.stringify({ expeditionId }), now);
});
return { expedition: this.expeditionView(expeditionId, playerId), expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
}
// Vue d'une expédition pour un participant : le résultat et le butin n'apparaissent qu'au retour.
expeditionView(expeditionId, playerId) {
const row = this.db.prepare(`SELECT e.*, m.reward_json, m.claimed_at FROM expeditions e
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = ? WHERE e.id = ?`).get(playerId, expeditionId);
if (!row) return null;
const now = this.now();
const returned = row.status === "completed" || (row.status === "running" && row.returns_at <= now);
const status = row.status === "running" ? (returned ? "returned" : "running") : row.status;
const setup = JSON.parse(row.setup_json);
const slots = this.db.prepare("SELECT position, role, player_id, edition_id, card_id, level, stats_json FROM expedition_slots WHERE expedition_id = ? ORDER BY position").all(row.id)
.map((slot) => ({
position: slot.position, role: slot.role ? STAT_BY_ROLE[slot.role] : null, own: slot.player_id === playerId,
editionId: slot.edition_id, cardId: slot.card_id, level: slot.level, stats: JSON.parse(slot.stats_json)
}));
return {
id: row.id, mode: row.mode, status, day: row.day, destination: setup.destination, condition: setup.condition, stars: row.difficulty, hours: setup.hours,
departsAt: row.departs_at, returnsAt: row.returns_at, claimedAt: row.claimed_at, slots,
result: returned ? parse(row.result_json) : null,
reward: returned ? parse(row.reward_json) : null
};
}
// Expéditions à suivre : en route, revenues sans butin récupéré, ou rentrées dans les dernières 24 heures.
playerExpeditionIds(playerId) {
const since = this.now() - 24 * HOUR_MS;
return this.db.prepare(`SELECT e.id FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND ((e.status = 'running' AND m.claimed_at IS NULL) OR m.claimed_at >= ? OR (e.status = 'cancelled' AND e.completed_at >= ?))
ORDER BY e.created_at DESC LIMIT 10`).all(playerId, since, since).map((row) => row.id);
}
getExpeditions(playerId) {
const settings = this.settings;
const now = this.now();
const base = {
enabled: settings.enabled,
nextDayAt: nextDailyAt(now),
durations: settings.durations.hours,
stars: { min: settings.solo.minStars, max: settings.solo.maxStars, limit: MAX_STARS },
soloCards: settings.solo.cards,
soloLimit: settings.solo.maxConcurrent,
expeditions: this.playerExpeditionIds(playerId).map((id) => this.expeditionView(id, playerId))
};
// Fermées : le joueur peut encore récupérer le butin de ses expéditions, mais aucune destination n'est tirée.
if (!settings.enabled) return { ...base, day: dailyDayKey(now), destinations: [], cards: [] };
const { day, entries } = this.today(settings);
return { ...base, day, destinations: entries.map((entry) => this.destinationView(entry, settings)), cards: this.eligibleCards(playerId, settings) };
}
claim(playerId, expeditionId) {
this.cards.database.transaction(() => {
const row = this.db.prepare(`SELECT e.*, m.reward_json, m.claimed_at FROM expeditions e
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = ? WHERE e.id = ?`).get(playerId, expeditionId);
if (!row || row.status === "cancelled") fail(404, "EXPEDITION_NOT_FOUND", "Cette expédition n’existe pas.");
// Déjà récupéré : on renvoie le même rapport.
if (row.claimed_at != null) return;
const now = this.now();
if (row.status !== "running" || row.returns_at > now) fail(409, "EXPEDITION_NOT_RETURNED", "Cette expédition n’est pas encore rentrée.");
const reward = JSON.parse(row.reward_json);
const setup = JSON.parse(row.setup_json);
const result = JSON.parse(row.result_json);
this.db.prepare("UPDATE players SET eclats = eclats + ?, stardust = stardust + ? WHERE id = ?").run(reward.eclats, reward.stardust, playerId);
const insertPack = this.db.prepare("INSERT INTO gift_packs(id, player_id, source, expedition_id, collection_id, options_json, created_at) VALUES (?, ?, 'expedition', ?, ?, ?, ?)");
for (const collectionId of reward.packs) insertPack.run(randomUUID(), playerId, row.id, collectionId, JSON.stringify({ rarityWeights: null, guarantee: null }), now);
this.db.prepare("UPDATE expedition_members SET claimed_at = ? WHERE expedition_id = ? AND player_id = ?").run(now, row.id, playerId);
const waiting = this.db.prepare("SELECT COUNT(*) AS count FROM expedition_members WHERE expedition_id = ? AND claimed_at IS NULL").get(row.id).count;
if (!waiting) this.db.prepare("UPDATE expeditions SET status = 'completed', completed_at = ? WHERE id = ?").run(now, row.id);
const editionIds = this.db.prepare("SELECT edition_id FROM expedition_slots WHERE expedition_id = ? AND player_id = ? ORDER BY position").all(row.id, playerId).map((slot) => slot.edition_id);
this.cards.audit(playerId, "expedition_completed", row.id, {
destinationId: setup.destination.id, destinationName: setup.destination.name, difficulty: row.difficulty, hours: setup.hours,
tier: result.tier, scorePct: result.scorePct, eclats: reward.eclats, stardust: reward.stardust, packs: reward.packs.length, editionIds
});
});
return { expedition: this.expeditionView(expeditionId, playerId), expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
}
// Annulation par un administrateur : les cartes sont libérées, sans butin.
cancel(adminId, expeditionId) {
this.cards.requireAdmin(adminId);
this.cards.database.transaction(() => {
const row = this.db.prepare("SELECT * FROM expeditions WHERE id = ?").get(expeditionId);
if (!row) fail(404, "EXPEDITION_NOT_FOUND", "Cette expédition n’existe pas.");
if (!["forming", "running"].includes(row.status)) fail(409, "EXPEDITION_FINISHED", "Cette expédition est déjà terminée.");
this.cancelRow(row);
this.cards.audit(adminId, "expedition_cancelled", row.id, { destinationId: row.destination_id, mode: row.mode, creatorId: row.creator_id });
});
return { expeditionsToday: this.adminSummary() };
}
// Annule une expédition et prévient ceux qui n'avaient pas encore récupéré leur butin.
cancelRow(row, { notify = true } = {}) {
this.db.prepare("UPDATE expeditions SET status = 'cancelled', completed_at = ? WHERE id = ?").run(this.now(), row.id);
if (!notify) return;
const setup = JSON.parse(row.setup_json);
for (const member of this.db.prepare("SELECT player_id FROM expedition_members WHERE expedition_id = ? AND claimed_at IS NULL").all(row.id)) {
this.cards.audit(member.player_id, "expedition_cancelled_by_guild", row.id, { destinationId: setup.destination.id, destinationName: setup.destination.name });
}
}
// Suppression du compte : ses expéditions en cours sont annulées (ses cartes n'existent plus).
forgetPlayer(playerId) {
const rows = this.db.prepare(`SELECT e.* FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND e.status IN ('forming', 'running') AND m.claimed_at IS NULL`).all(playerId);
for (const row of rows) this.cancelRow(row, { notify: false });
}
// Résumé pour l'état du joueur (tuile de la Guilde, fiche de carte), sans tirer les destinations du jour.
summary(playerId) {
const settings = this.settings;
const now = this.now();
const active = this.db.prepare(`SELECT e.returns_at FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
WHERE m.player_id = ? AND e.status = 'running' AND m.claimed_at IS NULL`).all(playerId);
const running = active.filter((row) => row.returns_at > now);
const launchedToday = Boolean(this.db.prepare("SELECT 1 FROM expeditions WHERE creator_id = ? AND day = ? AND status != 'cancelled' LIMIT 1").get(playerId, dailyDayKey(now)));
const busy = this.busyEditions(playerId);
const eligibleCards = new Set(this.cards.collectionOf(playerId)
.map((entry) => editionExpeditionData(this.cards.catalog, entry.editionId, 0, settings)?.cardId).filter(Boolean));
return {
enabled: settings.enabled,
running: running.length,
returned: active.length - running.length,
nextReturnAt: running.length ? Math.min(...running.map((row) => row.returns_at)) : null,
launchedToday,
eligible: eligibleCards.size,
soloCards: settings.solo.cards,
busyEditions: [...busy].map(([editionId, entry]) => ({ editionId, returnsAt: entry.returnsAt }))
};
}
adminSummary() {
const now = this.now();
const day = dailyDayKey(now);
return {
day,
launches: this.db.prepare("SELECT COUNT(*) AS count FROM expeditions WHERE day = ? AND status != 'forming'").get(day).count,
running: this.db.prepare("SELECT COUNT(*) AS count FROM expeditions WHERE status = 'running' AND returns_at > ?").get(now).count,
returnedUnclaimed: this.db.prepare(`SELECT COUNT(*) AS count FROM expedition_members m JOIN expeditions e ON e.id = m.expedition_id
WHERE e.status = 'running' AND e.returns_at <= ? AND m.claimed_at IS NULL`).get(now).count,
runningList: this.db.prepare(`SELECT e.id, e.destination_id, e.difficulty, e.returns_at, p.display_name FROM expeditions e JOIN players p ON p.id = e.creator_id
WHERE e.status = 'running' ORDER BY e.returns_at LIMIT 20`).all()
.map((row) => ({ id: row.id, destinationId: row.destination_id, stars: row.difficulty, returnsAt: row.returns_at, creatorName: row.display_name }))
};
}
}

View file

@ -0,0 +1,172 @@
// Rôle : valeurs par défaut, bornes, fusion, validation et différences des réglages des Expéditions Sokko TCG.
// Règles pures : aucune lecture de la base ni de l'horloge. Le schéma est la seule source des bornes, pour le serveur comme pour l'administration.
// Valeurs du document de conception. Une clé ajoutée plus tard prend sa valeur par défaut à la fusion, sans migration.
export const DEFAULT_EXPEDITION_SETTINGS = Object.freeze({
enabled: false,
day: { destinationsPerDay: 4, avoidRepeatDays: 1 },
durations: { hours: [2, 6, 12], malusPct: [0, 0, 15], endurancePerSlot: 12 },
solo: { maxConcurrent: 1, cards: 2, minStars: 1, maxStars: 4 },
power: { rare: 40, epic: 55, legendary: 70, mythic: 85, perLevel: 5, cap: 100 },
roles: { multiplierPct: 200 },
// Exigence d'une stat, par place, pour chaque nombre d'étoiles : stat principale, puis seconde, troisième et quatrième.
requirements: { star1: [9], star2: [11, 10], star3: [15, 14, 11], star4: [19, 18, 14], star5: [22, 21, 17, 14], conditionMissPct: 25 },
danger: { malusPct: 20, shieldMaxPct: 50, endurancePerSlot: 14 },
score: { mainWeight: 2, otherWeight: 1, overflowPct: 50, overflowSpanPct: 100, capPct: 150, successPct: 80, triumphPct: 120 },
loot: {
eclatsPerHourCents: 200,
stardustPerHourCents: 25,
packPerHourPermille: 12,
maxPacks: 2,
difficultyPct: [100, 130, 170, 220, 300],
tierPct: [40, 100, 150],
fortunePerPointPct: 2,
fortuneCapPct: 50,
// Multiplicateur de butin des destinations bonus : 5e, puis 6e.
bonusSlotPct: [100, 125]
},
destinations: {}
});
export const DEFAULT_DESTINATION_SETTING = Object.freeze({ active: true, weight: 1 });
export const MAX_DESTINATION_WEIGHT = 100;
const int = (path, min, max) => ({ path, kind: "int", min, max });
const ints = (path, length, min, max) => ({ path, kind: "ints", length, min, max });
// Bornes de chaque réglage. `ints` : liste de longueur fixe. Les réglages par destination sont validés à part.
export const EXPEDITION_SETTINGS_SCHEMA = Object.freeze([
{ path: "enabled", kind: "bool" },
int("day.destinationsPerDay", 1, 8),
int("day.avoidRepeatDays", 0, 7),
ints("durations.hours", 3, 1, 48),
ints("durations.malusPct", 3, 0, 50),
int("durations.endurancePerSlot", 1, 1000),
int("solo.maxConcurrent", 1, 3),
int("solo.cards", 1, 4),
int("solo.minStars", 1, 5),
int("solo.maxStars", 1, 5),
int("power.rare", 1, 300),
int("power.epic", 1, 300),
int("power.legendary", 1, 300),
int("power.mythic", 1, 300),
int("power.perLevel", 0, 50),
int("power.cap", 1, 300),
int("roles.multiplierPct", 100, 400),
ints("requirements.star1", 1, 1, 1000),
ints("requirements.star2", 2, 1, 1000),
ints("requirements.star3", 3, 1, 1000),
ints("requirements.star4", 3, 1, 1000),
ints("requirements.star5", 4, 1, 1000),
int("requirements.conditionMissPct", 0, 100),
int("danger.malusPct", 0, 90),
int("danger.shieldMaxPct", 0, 100),
int("danger.endurancePerSlot", 1, 1000),
int("score.mainWeight", 1, 10),
int("score.otherWeight", 1, 10),
int("score.overflowPct", 0, 100),
int("score.overflowSpanPct", 0, 300),
int("score.capPct", 100, 300),
int("score.successPct", 1, 300),
int("score.triumphPct", 1, 300),
int("loot.eclatsPerHourCents", 0, 100_000),
int("loot.stardustPerHourCents", 0, 100_000),
int("loot.packPerHourPermille", 0, 1000),
int("loot.maxPacks", 0, 10),
ints("loot.difficultyPct", 5, 0, 1000),
ints("loot.tierPct", 3, 0, 1000),
int("loot.fortunePerPointPct", 0, 100),
int("loot.fortuneCapPct", 0, 500),
ints("loot.bonusSlotPct", 2, 0, 1000)
]);
const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
export function readPath(source, path) {
return path.split(".").reduce((value, key) => (isObject(value) ? value[key] : undefined), source);
}
function writePath(target, path, value) {
const keys = path.split(".");
let node = target;
for (const key of keys.slice(0, -1)) {
if (!isObject(node[key])) node[key] = {};
node = node[key];
}
node[keys.at(-1)] = value;
}
function validField(field, value) {
if (field.kind === "bool") return typeof value === "boolean";
const inRange = (item) => Number.isInteger(item) && item >= field.min && item <= field.max;
if (field.kind === "int") return inRange(value);
return Array.isArray(value) && value.length === field.length && value.every(inRange);
}
const validDestinationSetting = (value) => isObject(value) && typeof value.active === "boolean"
&& Number.isInteger(value.weight) && value.weight >= 0 && value.weight <= MAX_DESTINATION_WEIGHT;
const copy = (value) => (Array.isArray(value) ? [...value] : value);
// Réglages complets : chaque champ stocké et valide est gardé, sinon il reprend sa valeur par défaut ; les clés inconnues disparaissent.
export function mergeExpeditionSettings(stored, destinationIds = [], onInvalid = null) {
const merged = {};
for (const field of EXPEDITION_SETTINGS_SCHEMA) {
const value = readPath(stored, field.path);
const fallback = readPath(DEFAULT_EXPEDITION_SETTINGS, field.path);
if (value !== undefined && !validField(field, value)) onInvalid?.(field.path);
writePath(merged, field.path, copy(value !== undefined && validField(field, value) ? value : fallback));
}
merged.destinations = {};
for (const id of destinationIds) {
const value = isObject(stored?.destinations) ? stored.destinations[id] : undefined;
if (value !== undefined && !validDestinationSetting(value)) onInvalid?.(`destinations.${id}`);
merged.destinations[id] = validDestinationSetting(value) ? { active: value.active, weight: value.weight } : { ...DEFAULT_DESTINATION_SETTING };
}
return merged;
}
// Message en français, ou null si les réglages sont valides (bornes, puis contraintes entre réglages).
export function validateExpeditionSettings(settings, destinationIds = []) {
if (!isObject(settings)) return "Réglages des Expéditions invalides.";
for (const field of EXPEDITION_SETTINGS_SCHEMA) {
if (!validField(field, readPath(settings, field.path))) {
return field.kind === "bool"
? `Réglage ${field.path} invalide : oui ou non.`
: `Réglage ${field.path} invalide : ${field.kind === "ints" ? `${field.length} entiers` : "un entier"} entre ${field.min.toLocaleString("fr-FR")} et ${field.max.toLocaleString("fr-FR")}.`;
}
}
if (!isObject(settings.destinations)) return "Réglages des destinations invalides.";
for (const id of Object.keys(settings.destinations)) {
if (!destinationIds.includes(id)) return `Destination inconnue : ${id}.`;
if (!validDestinationSetting(settings.destinations[id])) return `Réglage de la destination ${id} invalide : active oui ou non, poids entre 0 et ${MAX_DESTINATION_WEIGHT}.`;
}
const { hours } = settings.durations;
if (hours.some((value, index) => index > 0 && value <= hours[index - 1])) return "Les durées doivent être croissantes.";
if (settings.solo.minStars > settings.solo.maxStars) return "L'étoile minimale du solo dépasse l'étoile maximale.";
const { successPct, triumphPct, capPct } = settings.score;
if (!(successPct < triumphPct && triumphPct <= capPct)) return "Les seuils doivent respecter Réussite < Triomphe ≤ plafond du score.";
const { perLevel, cap, ...bases } = settings.power;
if (Object.values(bases).some((base) => base > cap)) return "Une Puissance de base dépasse le plafond.";
if (perLevel === 0 && Object.values(bases).some((base) => base < cap)) return "Le gain par niveau doit être positif tant qu'une Puissance de base est sous le plafond.";
return null;
}
// Différences champ par champ, pour l'historique d'administration.
export function diffExpeditionSettings(previous, next) {
const changes = [];
for (const field of EXPEDITION_SETTINGS_SCHEMA) {
const before = readPath(previous, field.path);
const after = readPath(next, field.path);
if (JSON.stringify(before) !== JSON.stringify(after)) changes.push({ path: field.path, previous: before, next: after });
}
const ids = new Set([...Object.keys(previous?.destinations || {}), ...Object.keys(next?.destinations || {})]);
for (const id of ids) {
for (const key of ["active", "weight"]) {
const before = previous?.destinations?.[id]?.[key];
const after = next?.destinations?.[id]?.[key];
if (before !== after) changes.push({ path: `destinations.${id}.${key}`, previous: before, next: after });
}
}
return changes;
}

View file

@ -0,0 +1,107 @@
// Rôle : simule les Expéditions Sokko TCG sur toutes les équipes possibles pour vérifier l'équilibre (script et test d'équilibrage).
// Module pur : il appelle les mêmes règles que le serveur, sans base ni hasard.
import { cardRarity } from "./daily.js";
import {
cardExpeditionData, cardPower, evaluateTeam, EXPEDITION_RARITIES, expectedLoot, maxLevel, MAX_STARS, soloRoles, splitPower, TIER_IDS
} from "./expedition-rules.js";
// Cartes jouables : chaque carte rare ou mieux à sa rareté, plus une mythique virtuelle pour chaque légendaire.
export function simulationCards(catalog) {
const cards = [];
for (const card of catalog.cards) {
const rarity = cardRarity(catalog, card.id);
if (!EXPEDITION_RARITIES.includes(rarity)) continue;
const data = cardExpeditionData(catalog, card.id);
cards.push({ ...data, rarity });
if (rarity === "legendary") cards.push({ ...data, rarity: "mythic" });
}
return cards;
}
const atLevel = (card, level, settings) => {
const power = cardPower(card.rarity, level, settings);
return { ...card, level, power, stats: splitPower(power, card.profile) };
};
const entryFor = (destination) => ({ condition: destination.conditions[0], dangers: destination.dangers.slice(0, 2) });
// Meilleur score d'une paire sur une destination : les deux façons de placer les cartes sur les deux rôles du solo.
export function bestPairScore(first, second, destination, stars, durationIndex, settings) {
const roles = soloRoles(destination, 2);
let best = null;
for (const [a, b] of [[first, second], [second, first]]) {
const result = evaluateTeam({
destination, entry: entryFor(destination), stars, durationIndex,
slots: [{ ...a, role: roles[0] }, { ...b, role: roles[1] }]
}, settings);
if (!best || result.scorePct > best.scorePct) best = result;
}
return best;
}
function pairsOf(cards, filter) {
const pairs = [];
for (let i = 0; i < cards.length; i += 1) {
for (let j = i + 1; j < cards.length; j += 1) {
if (cards[i].cardId !== cards[j].cardId && filter(cards[i], cards[j])) pairs.push([cards[i], cards[j]]);
}
}
return pairs;
}
// Rapport complet : meilleur score de chaque carte en 2 ★, extrêmes par rareté et étoiles, butin par heure, écart rare / mythique au plafond.
export function simulate(catalog, destinations, settings) {
const visible = destinations.filter((destination) => !destination.hidden);
const base = simulationCards(catalog);
const atZero = base.map((card) => atLevel(card, 0, settings));
const atMax = base.map((card) => atLevel(card, maxLevel(card.rarity, settings), settings));
// 1. Chaque carte doit atteindre Réussite en 2 ★ quelque part, avec un partenaire de même rareté, au niveau 0.
const cardBest = atZero.map((card) => {
let best = { scorePct: 0, destinationId: null, partnerId: null };
for (const partner of atZero) {
if (partner.cardId === card.cardId || partner.rarity !== card.rarity) continue;
for (const destination of visible) {
const result = bestPairScore(card, partner, destination, 2, 0, settings);
if (result.scorePct > best.scorePct) best = { scorePct: result.scorePct, destinationId: destination.id, partnerId: partner.cardId };
}
}
return { cardId: card.cardId, rarity: card.rarity, ...best };
});
// 2. Score par rareté (paires de même rareté), étoiles et niveau : minimum, médiane et maximum sur toutes les destinations.
const byRarity = [];
for (const [label, cards] of [["niveau 0", atZero], ["niveau max", atMax]]) {
for (const rarity of EXPEDITION_RARITIES) {
const pairs = pairsOf(cards, (a, b) => a.rarity === rarity && b.rarity === rarity);
for (let stars = 1; stars <= MAX_STARS; stars += 1) {
const scores = [];
for (const [a, b] of pairs) for (const destination of visible) scores.push(bestPairScore(a, b, destination, stars, 0, settings).scorePct);
scores.sort((x, y) => x - y);
byRarity.push({ level: label, rarity, stars, min: scores[0] ?? 0, median: scores[Math.floor(scores.length / 2)] ?? 0, max: scores.at(-1) ?? 0 });
}
}
}
// 3. Triomphe en 4 ★ au niveau maximum : part des destinations où au moins une paire de rares au plafond triomphe.
const maxRares = atMax.filter((card) => card.rarity === "rare");
const triumphDestinations = visible.filter((destination) => pairsOf(maxRares, () => true)
.some(([a, b]) => bestPairScore(a, b, destination, 4, 0, settings).tier === "triumph")).length;
// 4. Butin espéré par heure, pour chaque durée, étoile et palier.
const lootPerHour = [];
for (let stars = 1; stars <= MAX_STARS; stars += 1) {
for (const tier of TIER_IDS) {
const perHour = settings.durations.hours.map((hours) => expectedLoot({ hours, stars, tier, fortune: 0, slotCount: 2 }, settings).eclats / hours);
lootPerHour.push({ stars, tier, perHour });
}
}
return {
cardBest,
byRarity,
triumphShareAt4: visible.length ? triumphDestinations / visible.length : 0,
lootPerHour,
rareVsMythicAtMax: { rare: cardPower("rare", maxLevel("rare", settings), settings), mythic: cardPower("mythic", maxLevel("mythic", settings), settings) }
};
}

View file

@ -5,6 +5,8 @@ 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 { 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 { 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 { 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 TRANSFER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
@ -35,7 +37,7 @@ const ADMIN_HISTORY_PAGE_SIZE = 50;
const PLAYER_HISTORY_EVENTS = Object.freeze([ const PLAYER_HISTORY_EVENTS = Object.freeze([
"welcome_opening", "pack_opened", "gift_pack_opened", "cards_recycled", "opening_purchased", "campaign_claimed", "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", "trade_created", "trade_received", "trade_declined", "trade_joined", "trade_completed", "trade_cancelled",
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won" "gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won", "expedition_completed", "expedition_cancelled_by_guild"
]); ]);
const DEV_STARDUST = 1000; const DEV_STARDUST = 1000;
const DELETED_PLAYER_NAME = "Joueur supprimé"; const DELETED_PLAYER_NAME = "Joueur supprimé";
@ -45,7 +47,8 @@ const INACTIVE_ACCOUNT_MS = 730 * DAY_MS;
const IDEMPOTENCY_TTL_MS = 30 * DAY_MS; const IDEMPOTENCY_TTL_MS = 30 * DAY_MS;
export class CardsService { export class CardsService {
constructor({ database, catalog, now = Date.now, random, devPerks = false } = {}) { // `destinations` : destinations des Expéditions validées ; sans elles, celles du dépôt (services/cards/content).
constructor({ database, catalog, now = Date.now, random, devPerks = false, destinations = null } = {}) {
// Serveur Vite local uniquement : ressources permanentes du compte de développement pour tester le jeu sans attendre. // Serveur Vite local uniquement : ressources permanentes du compte de développement pour tester le jeu sans attendre.
this.devPerks = devPerks; this.devPerks = devPerks;
this.database = database; this.database = database;
@ -55,6 +58,7 @@ export class CardsService {
this.now = now; this.now = now;
this.random = random; this.random = random;
this.reloadCatalog(); this.reloadCatalog();
this.expeditions = new ExpeditionService(this, destinations || loadExpeditionDestinations(DEFAULT_DESTINATIONS_PATH, catalog));
} }
get rechargeSetting() { get rechargeSetting() {
@ -452,17 +456,23 @@ export class CardsService {
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) 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 })); .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); const transferRows = this.db.prepare("SELECT * FROM transfers WHERE initiator_id = ? OR recipient_id = ? ORDER BY created_at DESC LIMIT 50").all(playerId, playerId);
const giftPacks = this.db.prepare(`SELECT g.id, g.collection_id, g.options_json, g.created_at, c.name AS campaign_name // Un paquet offert vient d'une campagne (son nom) ou d'une expédition (le nom de sa destination).
FROM gift_packs g JOIN campaigns c ON c.id = g.campaign_id WHERE g.player_id = ? AND g.opening_id IS NULL ORDER BY g.created_at`).all(playerId) 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
.map((row) => ({ id: row.id, collectionId: row.collection_id, campaignName: row.campaign_name, receivedAt: row.created_at, options: JSON.parse(row.options_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 openingsCount = this.db.prepare("SELECT COUNT(*) AS count FROM openings WHERE player_id = ?").get(playerId).count;
const shop = this.shopSetting; const shop = this.shopSetting;
const recycling = this.recyclingPlan(owned); const recycling = this.recyclingPlan(owned);
return { return {
player: publicPlayer(player), recharge, collection, favorites, player: publicPlayer(player), recharge, collection, favorites,
wallet: { stardust: player.stardust, purchasedOpenings: player.purchased_openings }, 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 }, shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare, dailyReward: shop.dailyReward },
daily: this.dailySummary(playerId), daily: this.dailySummary(playerId),
expeditions: this.expeditions.summary(playerId),
recycling: { count: recycling.count, stardust: recycling.stardust }, recycling: { count: recycling.count, stardust: recycling.stardust },
pendingOpening: pending ? this.openingById(pending.id, playerId) : null, pendingOpening: pending ? this.openingById(pending.id, playerId) : null,
rarestPull: this.rarestPull(playerId), stats: { openingsCount }, rarestPull: this.rarestPull(playerId), stats: { openingsCount },
@ -534,6 +544,8 @@ export class CardsService {
rechargeSetting: this.rechargeSetting, rechargeSetting: this.rechargeSetting,
shopSetting: this.shopSetting, shopSetting: this.shopSetting,
daily: this.dailyAdminSummary(), daily: this.dailyAdminSummary(),
expeditionSettings: this.expeditions.adminSettings(),
expeditionsToday: this.expeditions.adminSummary(),
campaigns: this.campaignSummaries(), campaigns: this.campaignSummaries(),
editionCampaigns: this.editionCampaignCounts(), 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. // Variations possédées ou citées par une ouverture ou un transfert passés : elles ne peuvent qu'être retirées.
@ -655,7 +667,7 @@ export class CardsService {
const editionIds = drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights, guarantee: options.guarantee, requireActive: false }); 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); 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.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, cards: editionIds }); 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; return openingId;
}); });
} }
@ -860,9 +872,10 @@ export class CardsService {
: { sent: transfer.offered_edition_id, received: transfer.requested_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.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE player_id = ? AND status = 'pending'").run(this.now(), playerId);
this.expeditions.forgetPlayer(playerId);
for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId); for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts"]) 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("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, deleted_at = ? WHERE id = ?`) 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); .run(`deleted:${randomUUID()}`, DELETED_PLAYER_NAME, this.now(), playerId);
this.audit(playerId, "account_deleted", playerId, auditDetails); this.audit(playerId, "account_deleted", playerId, auditDetails);
} }

View file

@ -242,6 +242,94 @@ export function validateSiteContent(site) {
"cards.packs.giftDescription", "cards.packs.giftDescription",
"cards.packs.giftOpen", "cards.packs.giftOpen",
"cards.packs.noOpening", "cards.packs.noOpening",
"cards.guild.expeditionsKind",
"cards.guild.expeditionsTitle",
"cards.guild.expeditionsDescription",
"cards.guild.expeditionsToLaunch",
"cards.guild.expeditionsRunning",
"cards.guild.expeditionsReturned",
"cards.guild.expeditionsIdle",
"cards.guild.expeditionsNoCards",
"cards.guild.expeditionsClosed",
"cards.guild.expeditionsAction",
"cards.guild.expeditionsClaim",
"cards.guild.expeditionsOpen",
"cards.packs.giftFromExpedition",
"cards.expeditions.eyebrow",
"cards.expeditions.title",
"cards.expeditions.intro",
"cards.expeditions.back",
"cards.expeditions.eclatsBalance",
"cards.expeditions.eclatsHelp",
"cards.expeditions.closedTitle",
"cards.expeditions.closedText",
"cards.expeditions.expired",
"cards.expeditions.reload",
"cards.expeditions.activeTitle",
"cards.expeditions.reportMeta",
"cards.expeditions.running",
"cards.expeditions.returned",
"cards.expeditions.completed",
"cards.expeditions.cancelled",
"cards.expeditions.claim",
"cards.expeditions.claimed",
"cards.expeditions.started",
"cards.expeditions.rewardEclats",
"cards.expeditions.rewardStardust",
"cards.expeditions.rewardPacks",
"cards.expeditions.limitReached",
"cards.expeditions.planTitle",
"cards.expeditions.nextDay",
"cards.expeditions.noDestination",
"cards.expeditions.destinationsTitle",
"cards.expeditions.difficultyTitle",
"cards.expeditions.difficultyLabel",
"cards.expeditions.durationLabel",
"cards.expeditions.hours",
"cards.expeditions.requirementsTitle",
"cards.expeditions.main",
"cards.expeditions.conditionTag",
"cards.expeditions.conditionCollection",
"cards.expeditions.dangerText",
"cards.expeditions.or",
"cards.expeditions.teamTitle",
"cards.expeditions.teamHelp",
"cards.expeditions.roleBadge",
"cards.expeditions.slotEmpty",
"cards.expeditions.remove",
"cards.expeditions.cardsLabel",
"cards.expeditions.chooseCard",
"cards.expeditions.power",
"cards.expeditions.busy",
"cards.expeditions.noRole",
"cards.expeditions.noCards",
"cards.expeditions.previewTitle",
"cards.expeditions.previewEmpty",
"cards.expeditions.score",
"cards.expeditions.teamVersus",
"cards.expeditions.limitedByStars",
"cards.expeditions.conditionMet",
"cards.expeditions.conditionUnmet",
"cards.expeditions.dangerCountered",
"cards.expeditions.dangerActive",
"cards.expeditions.durationMalus",
"cards.expeditions.expected",
"cards.expeditions.start",
"cards.expeditions.tiers.struggle",
"cards.expeditions.tiers.success",
"cards.expeditions.tiers.triumph",
"cards.expeditions.stats.bravoure",
"cards.expeditions.stats.endurance",
"cards.expeditions.stats.fortune",
"cards.expeditions.stats.orientation",
"cards.expeditions.statShort.bravoure",
"cards.expeditions.statShort.endurance",
"cards.expeditions.statShort.fortune",
"cards.expeditions.statShort.orientation",
"cards.expeditions.roles.bravoure",
"cards.expeditions.roles.endurance",
"cards.expeditions.roles.fortune",
"cards.expeditions.roles.orientation",
"guideChecklist.label", "guideChecklist.label",
"guideChecklist.selectLabel", "guideChecklist.selectLabel",
"guideChecklist.selectPlaceholder", "guideChecklist.selectPlaceholder",

View file

@ -0,0 +1,43 @@
// Rôle : garde l'équilibre des Expéditions Sokko TCG avec le simulateur (seuils du document de conception).
// En cas d'échec après un ajout de cartes ou un changement de réglages : lancer `node scripts/simulate-expeditions.mjs` pour le détail.
import assert from "node:assert/strict";
import { test } from "node:test";
import { loadCardsCatalog } from "../services/cards/catalog.js";
import { loadExpeditionDestinations } from "../services/cards/expedition-content.js";
import { DEFAULT_EXPEDITION_SETTINGS, mergeExpeditionSettings } from "../services/cards/expedition-settings.js";
import { simulate } from "../services/cards/expedition-simulation.js";
const catalog = loadCardsCatalog("website/public/data/cards/catalog.json");
const destinations = loadExpeditionDestinations("services/cards/content/expedition-destinations.json", catalog);
const settings = mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, destinations.map((destination) => destination.id));
const report = simulate(catalog, destinations, settings);
const row = (level, rarity, stars) => report.byRarity.find((item) => item.level === level && item.rarity === rarity && item.stars === stars);
test("every rare or better card reaches Réussite at 2 stars somewhere at level 0", () => {
const weak = report.cardBest.filter((card) => card.scorePct < settings.score.successPct);
assert.deepEqual(weak.map((card) => `${card.cardId} (${card.rarity}) ${card.scorePct.toFixed(0)} %`), []);
});
test("expected loot per hour is the same for every duration", () => {
for (const { stars, tier, perHour } of report.lootPerHour) {
assert.ok(perHour.every((value) => Math.abs(value - perHour[0]) < 1e-9), `${stars} ★ ${tier}`);
}
});
test("a rare and a mythic end within 5 % of each other at the cap", () => {
const { rare, mythic } = report.rareVsMythicAtMax;
assert.ok(Math.abs(rare - mythic) / mythic <= 0.05);
});
test("rarer cards never score lower than commoner ones at the same level and stars", () => {
const order = ["rare", "epic", "legendary", "mythic"];
for (let stars = 1; stars <= 5; stars += 1) {
const medians = order.map((rarity) => row("niveau 0", rarity, stars).median);
for (let index = 1; index < medians.length; index += 1) assert.ok(medians[index] >= medians[index - 1], `${order[index]} ${stars} ★`);
}
});
test("4 stars stay out of reach for level 0 rares but open to capped cards", () => {
assert.ok(row("niveau 0", "rare", 4).max < settings.score.successPct, "a level 0 rare pair reaches Réussite at 4 stars");
assert.ok(report.triumphShareAt4 >= 0.5, `only ${(report.triumphShareAt4 * 100).toFixed(0)} % of destinations allow a capped rare pair to triumph at 4 stars`);
});

View file

@ -0,0 +1,240 @@
// Rôle : vérifie le service et l'API des Expéditions Sokko TCG (destinations du jour, départ solo, retour, réglages, suppression de compte).
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { Readable } from "node:stream";
import { test } from "node:test";
import { createCardsApiHandler } from "../services/cards/api.js";
import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js";
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES } from "../services/cards/admin-seed.js";
import { CardsDatabase } from "../services/cards/database.js";
import { CardsService } from "../services/cards/service.js";
const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")));
const published = buildPublishedCatalog(baseCatalog, { collectionStates: INITIAL_COLLECTION_STATES, dropRates: INITIAL_DROP_RATES });
const HOUR = 3_600_000;
const rarityOf = (cardId) => published.editions.find((edition) => edition.cardId === cardId && !edition.promotional).rarity;
const editionsOf = (rarity, collectionId = "primordial-nebula") => published.editions
.filter((edition) => edition.rarity === rarity && published.cards.find((card) => card.id === edition.cardId).collectionId === collectionId)
.map((edition) => edition.id);
function expeditionService({ start = Date.parse("2026-11-15T09:00:00Z"), random = () => 0 } = {}) {
const clock = { now: start };
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random });
const admin = service.upsertPlayer({ discordId: "expedition-admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "expedition-player", displayName: "Player" });
const open = (changes = {}) => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, enabled: true, ...changes });
const rares = editionsOf("rare");
database.transaction(() => rares.slice(0, 4).forEach((editionId) => service.addCard(player.id, editionId)));
return { clock, database, service, admin, player, open, rares };
}
const soloBody = (view, slots, changes = {}) => ({ day: view.day, destinationId: view.destinations[0].id, difficulty: 1, durationHours: 2, slots, ...changes });
test("expeditions stay closed until an administrator opens them", () => {
const { service, player, open, rares } = expeditionService();
const closed = service.expeditions.getExpeditions(player.id);
assert.equal(closed.enabled, false);
assert.deepEqual(closed.destinations, []);
assert.equal(service.getState(player.id).expeditions.enabled, false);
assert.throws(() => service.expeditions.startSolo(player.id, soloBody({ day: closed.day, destinations: [{ id: "light-currents" }] }, rares.slice(0, 2)), "k1"), (error) => error.code === "EXPEDITIONS_CLOSED");
assert.throws(() => service.expeditions.updateSettings(player.id, { ...service.expeditions.settings, enabled: true }), (error) => error.code === "ADMIN_REQUIRED");
open();
const view = service.expeditions.getExpeditions(player.id);
assert.equal(view.enabled, true);
assert.equal(view.day, "2026-11-15");
assert.equal(view.destinations.length, 4);
assert.deepEqual(Object.keys(view.destinations[0].stars), ["1", "2", "3", "4"]);
assert.equal(view.destinations[0].stars[4].dangers.length, 1);
assert.equal(view.destinations[0].stars[2].condition, null);
assert.equal(view.cards.length, 4);
// Le tirage du jour est commun à tous et gardé en base.
assert.deepEqual(service.expeditions.getExpeditions(player.id).destinations.map((item) => item.id), view.destinations.map((item) => item.id));
});
test("a solo expedition freezes its team, hides its result until it returns and pays once", () => {
const { clock, service, player, open, rares, database } = expeditionService();
open();
const view = service.expeditions.getExpeditions(player.id);
const body = soloBody(view, rares.slice(0, 2), { difficulty: 2, durationHours: 6 });
const preview = service.expeditions.preview(player.id, body).preview;
assert.ok(["struggle", "success", "triumph"].includes(preview.tier));
assert.equal(preview.requirements.length, 2);
assert.ok(preview.expected.eclats > 0);
const started = service.expeditions.startSolo(player.id, body, "start-1");
assert.equal(started.expedition.status, "running");
assert.equal(started.expedition.result, null);
assert.equal(started.expedition.reward, null);
assert.equal(started.expedition.returnsAt, clock.now + 6 * HOUR);
assert.equal(started.state.expeditions.running, 1);
assert.equal(started.state.expeditions.launchedToday, true);
assert.deepEqual(started.state.expeditions.busyEditions.map((item) => item.editionId).sort(), rares.slice(0, 2).sort());
// Même clé : même expédition ; nouvelle clé : la limite solo s'applique, et les cartes sont occupées.
assert.equal(service.expeditions.startSolo(player.id, body, "start-1").expedition.id, started.expedition.id);
assert.throws(() => service.expeditions.startSolo(player.id, body, "start-2"), (error) => error.code === "EXPEDITION_CARD_BUSY");
assert.throws(() => service.expeditions.startSolo(player.id, { ...body, slots: rares.slice(2, 4) }, "start-3"), (error) => error.code === "EXPEDITION_LIMIT");
assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_RETURNED");
// Une amélioration des réglages pendant le trajet ne change rien : tout est figé au départ.
clock.now += 6 * HOUR;
const before = service.getState(player.id);
assert.equal(before.expeditions.returned, 1);
const returned = service.expeditions.getExpeditions(player.id).expeditions[0];
assert.equal(returned.status, "returned");
assert.equal(returned.result.tier, preview.tier);
const claimed = service.expeditions.claim(player.id, started.expedition.id);
assert.equal(claimed.expedition.status, "completed");
assert.equal(claimed.state.wallet.eclats, returned.reward.eclats);
assert.equal(claimed.state.wallet.stardust, before.wallet.stardust + returned.reward.stardust);
assert.ok(returned.reward.eclats >= Math.floor(preview.expected.eclats));
// random() = 0 : tous les tirages réussissent, donc un paquet rapporté, rangé avec les paquets offerts.
assert.equal(returned.reward.packs.length, 1);
assert.equal(claimed.state.giftPacks.length, 1);
assert.equal(claimed.state.giftPacks[0].source, "expedition");
assert.equal(claimed.state.giftPacks[0].sourceName, returned.destination.name);
const history = claimed.state.history.find((entry) => entry.type === "expedition_completed");
assert.equal(history.details.eclats, returned.reward.eclats);
// Deuxième retour : même rapport, aucun crédit en plus ; les cartes sont libres.
const again = service.expeditions.claim(player.id, started.expedition.id);
assert.equal(again.state.wallet.eclats, claimed.state.wallet.eclats);
assert.deepEqual(again.state.expeditions.busyEditions, []);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM gift_packs WHERE source = 'expedition'").get().count, 1);
// Le paquet rapporté s'ouvre comme un paquet offert.
const opened = service.openGiftPack(player.id, claimed.state.giftPacks[0].id, "open-expedition-pack");
assert.equal(opened.opening.cards.length, 3);
});
test("unlucky rolls keep the average and never hand out a pack", () => {
const { clock, service, player, open, rares } = expeditionService({ random: (max) => max - 1 });
open();
const view = service.expeditions.getExpeditions(player.id);
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "unlucky");
clock.now += 2 * HOUR;
const returned = service.expeditions.claim(player.id, started.expedition.id).expedition;
assert.deepEqual(returned.reward.packs, []);
assert.equal(returned.reward.eclats, Math.floor(returned.reward.eclats));
});
test("solo departures refuse stale days, unknown destinations, commons, duplicates and cards the player lacks", () => {
const { clock, service, player, open, rares } = expeditionService();
open();
const view = service.expeditions.getExpeditions(player.id);
const start = (changes, key) => () => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2), changes), key);
assert.throws(start({ destinationId: "nowhere" }, "a"), (error) => error.code === "EXPEDITION_INVALID");
assert.throws(start({ difficulty: 5 }, "b"), (error) => error.code === "EXPEDITION_INVALID");
assert.throws(start({ durationHours: 3 }, "c"), (error) => error.code === "EXPEDITION_INVALID");
assert.throws(start({ slots: [rares[0]] }, "d"), (error) => error.code === "EXPEDITION_CARD_INVALID");
assert.throws(start({ slots: [rares[0], rares[0]] }, "e"), (error) => error.code === "EXPEDITION_CARD_INVALID");
assert.throws(start({ slots: [rares[0], editionsOf("common")[0]] }, "f"), (error) => error.code === "EXPEDITION_CARD_INVALID");
assert.throws(start({ slots: [rares[0], rares[10]] }, "g"), (error) => error.code === "CARD_NOT_OWNED");
assert.throws(() => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), ""), (error) => error.code === "IDEMPOTENCY_REQUIRED");
clock.now += 24 * HOUR;
assert.throws(start({}, "h"), (error) => error.code === "EXPEDITION_DAY_EXPIRED");
assert.equal(rarityOf("starvoid-dragon"), "legendary");
});
test("administrators tune settings with bounds and history, and can cancel an expedition", () => {
const { service, admin, player, open, rares, database } = expeditionService();
assert.throws(() => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, score: { ...service.expeditions.settings.score, successPct: 500 } }), (error) => error.code === "EXPEDITION_SETTINGS_INVALID");
open();
assert.throws(() => open(), (error) => error.code === "EXPEDITION_SETTINGS_UNCHANGED");
const audit = database.db.prepare("SELECT details_json FROM audit_log WHERE event_type = 'expedition_settings_updated'").get();
assert.deepEqual(JSON.parse(audit.details_json).changes, [{ path: "enabled", previous: false, next: true }]);
assert.ok(service.getAdminHistory(admin.id).entries.some((entry) => entry.type === "expedition_settings_updated"));
const dashboard = service.getAdminDashboard(admin.id);
assert.equal(dashboard.expeditionSettings.settings.enabled, true);
assert.equal(dashboard.expeditionSettings.destinations.length, 12);
assert.ok(dashboard.expeditionSettings.schema.some((field) => field.path === "loot.eclatsPerHourCents"));
const view = service.expeditions.getExpeditions(player.id);
const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "cancel-me");
assert.equal(service.getAdminDashboard(admin.id).expeditionsToday.running, 1);
assert.throws(() => service.expeditions.cancel(player.id, started.expedition.id), (error) => error.code === "ADMIN_REQUIRED");
service.expeditions.cancel(admin.id, started.expedition.id);
const state = service.getState(player.id);
assert.deepEqual(state.expeditions.busyEditions, []);
assert.ok(state.history.some((entry) => entry.type === "expedition_cancelled_by_guild"));
assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_FOUND");
assert.throws(() => service.expeditions.cancel(admin.id, started.expedition.id), (error) => error.code === "EXPEDITION_FINISHED");
});
test("deleting an account cancels its expeditions and resets its Éclats", () => {
const { clock, service, player, open, rares, database } = expeditionService();
open();
const view = service.expeditions.getExpeditions(player.id);
const first = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "first");
clock.now += 2 * HOUR;
service.expeditions.claim(player.id, first.expedition.id);
const second = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(2, 4)), "second");
service.deleteAccount(player.id);
assert.equal(database.db.prepare("SELECT eclats FROM players WHERE id = ?").get(player.id).eclats, 0);
assert.equal(database.db.prepare("SELECT status FROM expeditions WHERE id = ?").get(second.expedition.id).status, "cancelled");
});
function mockRequest({ method = "GET", path, body, headers = {} }) {
const req = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body))]);
req.method = method;
req.url = path;
req.headers = { host: "localhost:5173", ...headers };
req.socket = { remoteAddress: "127.0.0.1" };
return req;
}
async function call(handler, options) {
const response = { status: 0, headers: {}, chunks: [] };
const res = {
setHeader(name, value) { response.headers[name.toLowerCase()] = value; },
writeHead(status, headers = {}) {
response.status = status;
for (const [name, value] of Object.entries(headers)) response.headers[name.toLowerCase()] = value;
},
end(value = "") { response.chunks.push(Buffer.from(value)); }
};
await handler(mockRequest(options), res);
response.raw = Buffer.concat(response.chunks);
response.json = response.headers["content-type"]?.startsWith("application/json") && response.raw.length ? JSON.parse(response.raw.toString("utf8")) : null;
return response;
}
test("the expeditions API requires a session, CSRF protection, an administrator for settings and an idempotency key to start", async (t) => {
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
t.after(() => handler.close());
assert.equal((await call(handler, { path: "/api/cards/expeditions" })).status, 401);
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
const cookie = login.headers["set-cookie"].split(";")[0];
const headers = { cookie, "x-csrf-token": login.json.csrfToken };
const closed = await call(handler, { path: "/api/cards/expeditions", headers: { cookie } });
assert.equal(closed.status, 200);
assert.equal(closed.json.enabled, false);
assert.equal((await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers: { cookie }, body: {} })).status, 403);
const dashboard = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie } });
const settings = { ...dashboard.json.expeditionSettings.settings, enabled: true };
const invalid = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings: { ...settings, solo: { ...settings.solo, maxStars: 9 } } } });
assert.equal(invalid.status, 400);
assert.equal(invalid.json.error.code, "EXPEDITION_SETTINGS_INVALID");
const opened = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings } });
assert.equal(opened.status, 200);
assert.equal(opened.json.expeditionSettings.settings.enabled, true);
const devId = handler.service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get().id;
handler.service.database.transaction(() => editionsOf("rare").slice(0, 2).forEach((editionId) => handler.service.addCard(devId, editionId)));
const view = (await call(handler, { path: "/api/cards/expeditions", headers: { cookie } })).json;
const slots = view.cards.slice(0, 2).map((card) => card.editionId);
assert.equal(slots.length, 2, "the development account owns rare or better cards");
const body = soloBody(view, slots);
const preview = await call(handler, { method: "POST", path: "/api/cards/expeditions/preview", headers, body });
assert.equal(preview.status, 200);
const noKey = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers, body });
assert.equal(noKey.json.error.code, "IDEMPOTENCY_REQUIRED");
const started = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-start" }, body });
assert.equal(started.status, 201);
assert.equal(started.json.expedition.status, "running");
const early = await call(handler, { method: "POST", path: `/api/cards/expeditions/${started.json.expedition.id}/claim`, headers });
assert.equal(early.status, 409);
assert.equal(early.json.error.code, "EXPEDITION_NOT_RETURNED");
const cancelled = await call(handler, { method: "POST", path: `/api/cards/admin/expeditions/${started.json.expedition.id}/cancel`, headers });
assert.equal(cancelled.status, 200);
});

View file

@ -0,0 +1,222 @@
// Rôle : vérifie les données, les réglages et les règles pures des Expéditions Sokko TCG.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { test } from "node:test";
import { prepareVersionedCatalog } from "../services/cards/catalog.js";
import { loadExpeditionDestinations, validateExpeditionDestinations } from "../services/cards/expedition-content.js";
import {
applyHazards, cardPower, drawExpeditionDay, editionExpeditionData, efficiency, evaluateTeam, expectedLoot, maxLevel,
requirementsFor, resolveDayEntry, rollLoot, roundStochastic, scoreExpedition, soloRoles, splitPower, STAT_IDS, teamStats
} from "../services/cards/expedition-rules.js";
import {
DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, readPath, validateExpeditionSettings
} from "../services/cards/expedition-settings.js";
import { EXPEDITION_SETTING_GROUPS, expeditionSettingLabel } from "../website/src/features/cards/admin/expeditionSettingFields.js";
import { expeditionsPending, guildQuests } from "../website/src/features/cards/guildQuests.js";
const rawCatalog = JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8"));
const catalog = prepareVersionedCatalog(rawCatalog);
const destinationsPath = "services/cards/content/expedition-destinations.json";
const destinations = loadExpeditionDestinations(destinationsPath, catalog);
const destinationIds = destinations.map((destination) => destination.id);
const settings = mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, destinationIds);
const profile = (bravoure, endurance, fortune, orientation) => ({ bravoure, endurance, fortune, orientation });
test("every catalog card carries expedition tags and every collection a profile", () => {
const tagIds = new Set(rawCatalog.expeditionTags.map((tag) => tag.id));
assert.ok(rawCatalog.cards.every((card) => card.expedition.tags.length >= 1 && card.expedition.tags.every((tag) => tagIds.has(tag))));
assert.ok(rawCatalog.collections.every((collection) => STAT_IDS.reduce((sum, stat) => sum + collection.expedition.profile[stat], 0) === 100));
// Aucune étiquette inutilisée : le vocabulaire reste celui des cartes.
const used = new Set(rawCatalog.cards.flatMap((card) => card.expedition.tags));
assert.deepEqual(rawCatalog.expeditionTags.filter((tag) => !used.has(tag.id)), []);
});
test("catalog validation refuses broken expedition data", () => {
const unknownTag = structuredClone(rawCatalog);
unknownTag.cards[0].expedition.tags = ["theme:inconnu"];
assert.throws(() => prepareVersionedCatalog(unknownTag), /unknown expedition tag theme:inconnu/);
const noTags = structuredClone(rawCatalog);
delete noTags.cards[0].expedition;
assert.throws(() => prepareVersionedCatalog(noTags), /needs 1 to 8 expedition tags/);
const repeated = structuredClone(rawCatalog);
repeated.cards[0].expedition.tags = ["theme:voyage", "theme:voyage"];
assert.throws(() => prepareVersionedCatalog(repeated), /repeats an expedition tag/);
const badProfile = structuredClone(rawCatalog);
badProfile.cards[0].expedition.profile = profile(50, 50, 10, 0);
assert.throws(() => prepareVersionedCatalog(badProfile), /summing to 100/);
const noCollectionProfile = structuredClone(rawCatalog);
delete noCollectionProfile.collections[0].expedition;
assert.throws(() => prepareVersionedCatalog(noCollectionProfile), /needs an expedition profile/);
const badTagId = structuredClone(rawCatalog);
badTagId.expeditionTags.push({ id: "Voyage", label: "Voyage" });
assert.throws(() => prepareVersionedCatalog(badTagId), /family:name id/);
});
test("destinations order the four stats and stay satisfiable by rare or better cards", () => {
assert.equal(destinations.length, 12);
// Une destination par couple (stat principale, seconde stat) : chaque paire de rôles du solo existe.
assert.equal(new Set(destinations.map((destination) => destination.stats.slice(0, 2).join("+"))).size, 12);
const broken = (change) => {
const copy = structuredClone(destinations);
change(copy[0]);
return () => validateExpeditionDestinations(copy, catalog);
};
assert.throws(broken((destination) => { destination.stats = ["bravoure", "bravoure", "fortune", "orientation"]; }), /order the four stats/);
assert.throws(broken((destination) => { destination.conditions = [{ type: "tag", tag: "personnage:ours" }]; }), /fewer than 3/);
assert.throws(broken((destination) => { destination.dangers[0].unlessTags = ["theme:inconnu"]; }), /known counter tags/);
assert.throws(broken((destination) => { destination.coverCardId = "missing"; }), /unknown cover card/);
assert.throws(() => validateExpeditionDestinations(destinations.map((destination) => ({ ...destination, hidden: true })), catalog), /visible destination/);
});
test("expedition settings merge stored values with defaults and validate bounds and cross rules", () => {
assert.equal(validateExpeditionSettings(settings, destinationIds), null);
assert.equal(settings.enabled, false);
assert.deepEqual(settings.destinations[destinationIds[0]], { active: true, weight: 1 });
// Champ manquant ou invalide : valeur par défaut, signalée ; clé inconnue : supprimée.
const invalid = [];
const merged = mergeExpeditionSettings({ power: { rare: 45, cap: "x" }, extra: 1, destinations: { [destinationIds[0]]: { active: false, weight: 3 }, gone: { active: true, weight: 1 } } }, destinationIds, (path) => invalid.push(path));
assert.equal(merged.power.rare, 45);
assert.equal(merged.power.cap, 100);
assert.deepEqual(invalid, ["power.cap"]);
assert.equal("extra" in merged, false);
assert.equal("gone" in merged.destinations, false);
assert.deepEqual(merged.destinations[destinationIds[0]], { active: false, weight: 3 });
// Chaque champ du schéma a une valeur par défaut valide.
for (const field of EXPEDITION_SETTINGS_SCHEMA) assert.notEqual(readPath(DEFAULT_EXPEDITION_SETTINGS, field.path), undefined, field.path);
const withChange = (path, value) => {
const copy = structuredClone(settings);
const keys = path.split(".");
keys.slice(0, -1).reduce((node, key) => node[key], copy)[keys.at(-1)] = value;
return copy;
};
assert.match(validateExpeditionSettings(withChange("day.destinationsPerDay", 0), destinationIds), /day\.destinationsPerDay/);
assert.match(validateExpeditionSettings(withChange("durations.hours", [6, 2, 12]), destinationIds), /croissantes/);
assert.match(validateExpeditionSettings(withChange("requirements.star3", [1, 2]), destinationIds), /3 entiers/);
assert.match(validateExpeditionSettings(withChange("score.successPct", 130), destinationIds), /Réussite < Triomphe/);
assert.match(validateExpeditionSettings(withChange("solo.minStars", 5), destinationIds), /étoile minimale/);
assert.match(validateExpeditionSettings(withChange("power.rare", 120), destinationIds), /plafond/);
assert.match(validateExpeditionSettings(withChange("destinations", { unknown: { active: true, weight: 1 } }), destinationIds), /inconnue/);
const next = withChange("loot.eclatsPerHourCents", 300);
next.destinations[destinationIds[1]].weight = 4;
assert.deepEqual(diffExpeditionSettings(settings, next), [
{ path: "loot.eclatsPerHourCents", previous: 200, next: 300 },
{ path: `destinations.${destinationIds[1]}.weight`, previous: 1, next: 4 }
]);
});
test("power grows with levels up to the shared cap and splits exactly by profile", () => {
assert.equal(cardPower("rare", 0, settings), 40);
assert.equal(cardPower("rare", 4, settings), 60);
assert.equal(cardPower("rare", 99, settings), 100);
assert.equal(cardPower("common", 3, settings), 0);
assert.deepEqual(["rare", "epic", "legendary", "mythic"].map((rarity) => maxLevel(rarity, settings)), [12, 9, 6, 3]);
assert.deepEqual(splitPower(40, profile(25, 25, 20, 30)), { bravoure: 10, endurance: 10, fortune: 8, orientation: 12 });
const odd = splitPower(55, profile(33, 33, 17, 17));
assert.equal(Object.values(odd).reduce((sum, value) => sum + value, 0), 55);
// Une mythique garde sa propre rareté, mais le profil et les étiquettes de sa carte.
const legendary = editionExpeditionData(catalog, "starvoid-dragon-standard", 0, settings);
assert.equal(legendary.power, 70);
assert.deepEqual(legendary.tags, ["personnage:dragon", "lieu:nebuleuse", "lieu:soleil"]);
assert.equal(editionExpeditionData(catalog, "dragon-constellation-standard", 0, settings), null);
});
test("requirements scale per slot, roles double a stat, hazards and conditions weigh on the score", () => {
const destination = destinations.find((item) => item.id === "light-currents");
const roles = soloRoles(destination, 2);
assert.deepEqual(roles, ["orientation", "bravoure"]);
assert.deepEqual(requirementsFor(destination, 2, roles, settings), [
{ stat: "orientation", main: true, value: 33 },
{ stat: "bravoure", main: false, value: 30 }
]);
// Une place sans rôle (Veilleur de la Guilde) n'ajoute que sa part.
assert.equal(requirementsFor(destination, 1, ["orientation", null, null, null], settings)[0].value, 45);
const slot = { stats: { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }, tags: [], collectionId: "primordial-nebula" };
assert.deepEqual(teamStats([{ ...slot, role: "orientation" }, { ...slot, role: null }], settings), { bravoure: 20, endurance: 20, fortune: 20, orientation: 30 });
// 12 h sans Endurance : −15 % ; Endurance suffisante : aucun malus. Danger non paré : −20 %, moins le bouclier.
assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 10, orientation: 10 }, { slotCount: 2, durationIndex: 2 }, settings).durationFactor, 0.85);
assert.equal(applyHazards({ bravoure: 10, endurance: 24, fortune: 10, orientation: 10 }, { slotCount: 2, durationIndex: 2 }, settings).durationFactor, 1);
const danger = { id: "d", label: "D", stat: "bravoure", unlessTags: ["theme:hiver"] };
assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: false }] }, settings).stats.bravoure, 8);
assert.equal(applyHazards({ bravoure: 10, endurance: 28, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: false }] }, settings).stats.bravoure, 9);
assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: true }] }, settings).stats.bravoure, 10);
assert.equal(efficiency(0.5, settings), 0.5);
assert.equal(efficiency(1.5, settings), 1.25);
assert.equal(efficiency(3, settings), 1.5);
const requirements = [{ stat: "bravoure", main: true, value: 10 }, { stat: "fortune", main: false, value: 10 }];
const full = scoreExpedition({ requirements, stats: { bravoure: 10, fortune: 10 } }, settings);
assert.equal(full.scorePct, 100);
assert.equal(full.tier, "success");
assert.equal(scoreExpedition({ requirements, stats: { bravoure: 10, fortune: 10 }, conditionMet: false }, settings).scorePct, 75);
assert.equal(scoreExpedition({ requirements, stats: { bravoure: 40, fortune: 40 } }, settings).tier, "triumph");
assert.equal(scoreExpedition({ requirements, stats: { bravoure: 5, fortune: 5 } }, settings).tier, "struggle");
});
test("one more star never raises the score of the same team", () => {
const destination = destinations[0];
const entry = { condition: destination.conditions[0], dangers: destination.dangers };
// Équipe faible sur la stat principale, forte sur la seconde : sans la règle, 2 ★ ferait mieux que 1 ★.
const slots = [
{ stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, role: destination.stats[0], tags: [], collectionId: "primordial-nebula" },
{ stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, role: destination.stats[1], tags: [], collectionId: "primordial-nebula" }
];
const scores = [1, 2, 3, 4].map((stars) => evaluateTeam({ destination, entry, stars, durationIndex: 0, slots }, settings));
for (let index = 1; index < scores.length; index += 1) assert.ok(scores[index].scorePct <= scores[index - 1].scorePct);
assert.equal(scores[1].limitedByStars, 1);
});
test("loot is proportional to the chosen duration and rounds without changing its average", () => {
const short = expectedLoot({ hours: 2, stars: 2, tier: "success", fortune: 0, slotCount: 2 }, settings);
const long = expectedLoot({ hours: 12, stars: 2, tier: "success", fortune: 0, slotCount: 2 }, settings);
assert.equal(long.eclats / 12, short.eclats / 2);
assert.equal(short.eclats, 5.2);
// Fortune : +2 % par point moyen par place, plafonné ; destinations bonus : multiplicateur propre.
assert.equal(expectedLoot({ hours: 2, stars: 1, tier: "success", fortune: 20, slotCount: 2 }, settings).fortuneBonusPct, 20);
assert.equal(expectedLoot({ hours: 2, stars: 1, tier: "success", fortune: 200, slotCount: 2 }, settings).fortuneBonusPct, 50);
assert.equal(expectedLoot({ hours: 4, stars: 1, tier: "success", fortune: 0, slotCount: 2, bonusSlot: 6 }, settings).eclats, 10);
assert.equal(roundStochastic(2.3, () => 0), 3);
assert.equal(roundStochastic(2.3, (max) => max - 1), 2);
assert.equal(roundStochastic(4, () => 0), 4);
assert.deepEqual(rollLoot({ eclats: 1.5, stardust: 0.2, packs: 5 }, settings, () => 0), { eclats: 2, stardust: 1, packs: 2 });
});
test("the day draw picks active visible destinations and avoids yesterday's when it can", () => {
const draw = drawExpeditionDay(destinations, settings, [], () => 0);
assert.equal(draw.length, 4);
assert.equal(new Set(draw.map((entry) => entry.destinationId)).size, 4);
const recent = draw.map((entry) => entry.destinationId);
const next = drawExpeditionDay(destinations, settings, recent, () => 0);
assert.ok(next.every((entry) => !recent.includes(entry.destinationId)));
// Destinations retirées ou de poids nul : jamais tirées.
const closed = structuredClone(settings);
for (const id of destinationIds.slice(1)) closed.destinations[id].active = false;
assert.deepEqual(drawExpeditionDay(destinations, closed, [destinationIds[0]], () => 0).map((entry) => entry.destinationId), [destinationIds[0]]);
// Le second danger diffère du premier quand la destination en a deux.
assert.ok(draw.every((entry) => entry.dangerIndexes[0] !== entry.dangerIndexes[1]));
const resolved = resolveDayEntry(destinations, draw[0]);
assert.equal(resolved.entry.dangers.length, 2);
assert.equal(resolveDayEntry(destinations, { destinationId: "missing", conditionIndex: 0, dangerIndexes: [0, 0] }), null);
});
test("every server setting has its label in the administration, and nothing else", () => {
const labelled = EXPEDITION_SETTING_GROUPS.flatMap((group) => group.fields.map((field) => field.path));
assert.deepEqual([...labelled].sort(), EXPEDITION_SETTINGS_SCHEMA.map((field) => field.path).sort());
assert.equal(expeditionSettingLabel(`destinations.${destinations[0].id}.weight`, destinations), `${destinations[0].name} · poids`);
});
test("the guild shows expeditions when open and flags them once a day or when one is back", () => {
const now = Date.parse("2026-11-15T10:00:00Z");
const summary = { enabled: true, running: 0, returned: 0, nextReturnAt: null, launchedToday: false, eligible: 3, soloCards: 2, busyEditions: [] };
assert.equal(expeditionsPending(summary, now), true);
assert.equal(expeditionsPending({ ...summary, launchedToday: true }, now), false);
assert.equal(expeditionsPending({ ...summary, eligible: 1 }, now), false);
assert.equal(expeditionsPending({ ...summary, running: 1, launchedToday: true, nextReturnAt: now + 1000 }, now), false);
assert.equal(expeditionsPending({ ...summary, running: 1, launchedToday: true, nextReturnAt: now - 1000 }, now), true);
// Fermées : la tuile disparaît, sauf tant qu'une expédition du joueur n'est pas terminée.
assert.deepEqual(guildQuests({ expeditions: { ...summary, enabled: false } }, now), []);
assert.equal(guildQuests({ expeditions: { ...summary, enabled: false, returned: 1 } }, now)[0].pending, true);
});

View file

@ -494,7 +494,7 @@ test("duplicates become stardust that buys openings kept apart from the recharge
const value = INITIAL_SHOP_SETTING.stardustValues[rarity]; const value = INITIAL_SHOP_SETTING.stardustValues[rarity];
const before = service.getState(player.id); const before = service.getState(player.id);
assert.deepEqual(before.wallet, { stardust: 0, purchasedOpenings: 0 }); assert.deepEqual(before.wallet, { stardust: 0, purchasedOpenings: 0, eclats: 0 });
assert.deepEqual(before.shop, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: INITIAL_SHOP_SETTING.openingPrice, shopPackPrice: 60, shopPackShare: 50, dailyReward: 10 }); assert.deepEqual(before.shop, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: INITIAL_SHOP_SETTING.openingPrice, shopPackPrice: 60, shopPackShare: 50, dailyReward: 10 });
assert.deepEqual(before.recycling, { count: 2, stardust: 2 * value }); assert.deepEqual(before.recycling, { count: 2, stardust: 2 * value });
// Une favorite garde son exemplaire : ses doublons se recyclent comme les autres. // Une favorite garde son exemplaire : ses doublons se recyclent comme les autres.
@ -520,7 +520,7 @@ test("duplicates become stardust that buys openings kept apart from the recharge
// Vide les ouvertures de bienvenue restantes sans changer la collection vérifiée plus bas. // Vide les ouvertures de bienvenue restantes sans changer la collection vérifiée plus bas.
database.db.prepare("UPDATE players SET openings_balance = 0 WHERE id = ?").run(player.id); database.db.prepare("UPDATE players SET openings_balance = 0 WHERE id = ?").run(player.id);
const bought = service.buyOpening(player.id); const bought = service.buyOpening(player.id);
assert.deepEqual(bought.wallet, { stardust: 0, purchasedOpenings: 1 }); assert.deepEqual(bought.wallet, { stardust: 0, purchasedOpenings: 1, eclats: 0 });
assert.throws(() => service.buyOpening(player.id), /Pas assez/); assert.throws(() => service.buyOpening(player.id), /Pas assez/);
// La réserve est vide : seule l'ouverture achetée permet d'ouvrir, sans toucher à la réserve. // La réserve est vide : seule l'ouverture achetée permet d'ouvrir, sans toucher à la réserve.

View file

@ -109,7 +109,8 @@ test("large sass files stay split by stable responsibility", async () => {
"website/src/styles/toolboxes/calendar/_form-layout.scss", "website/src/styles/toolboxes/calendar/_form-layout.scss",
"website/src/styles/toolboxes/calendar/_date-picker.scss", "website/src/styles/toolboxes/calendar/_date-picker.scss",
"website/src/styles/toolboxes/calendar/_event-controls.scss", "website/src/styles/toolboxes/calendar/_event-controls.scss",
"website/src/styles/toolboxes/calendar/_form-actions.scss" "website/src/styles/toolboxes/calendar/_form-actions.scss",
"website/src/styles/_nebula-expeditions.scss"
]; ];
for (const path of orchestrators) { for (const path of orchestrators) {

File diff suppressed because it is too large Load diff

View file

@ -211,7 +211,85 @@
"dailyLost": "Pas trouvée aujourd’hui.", "dailyLost": "Pas trouvée aujourd’hui.",
"dailyStreak": "Série : {streak}", "dailyStreak": "Série : {streak}",
"dailyAction": "Jouer", "dailyAction": "Jouer",
"dailyResult": "Voir le résultat" "dailyResult": "Voir le résultat",
"expeditionsKind": "Quête de longue durée",
"expeditionsTitle": "Expéditions",
"expeditionsDescription": "Envoyez vos cartes explorer l’archipel et rapportez des Éclats d’étoile.",
"expeditionsToLaunch": "De nouvelles destinations vous attendent.",
"expeditionsRunning": "En route, retour dans {time}.",
"expeditionsReturned": "Une expédition est de retour !",
"expeditionsIdle": "Expédition du jour lancée.",
"expeditionsNoCards": "Il faut {count} cartes rares ou mieux pour partir.",
"expeditionsClosed": "Les Expéditions sont fermées pour le moment.",
"expeditionsAction": "Préparer",
"expeditionsClaim": "Récupérer le butin",
"expeditionsOpen": "Voir"
},
"expeditions": {
"eyebrow": "Quête de la Guilde",
"title": "Expéditions",
"intro": "Choisissez une destination du jour, composez une équipe et laissez-la explorer l’archipel pendant quelques heures.",
"back": "Retour à la Guilde",
"eclatsBalance": "{value} Éclats d’étoile",
"eclatsHelp": "Les Éclats d’étoile serviront bientôt à améliorer vos cartes.",
"closedTitle": "Les Expéditions sont fermées",
"closedText": "Les Veilleurs préparent les prochaines destinations. Revenez bientôt.",
"expired": "Les destinations du jour ont changé.",
"reload": "Recharger",
"activeTitle": "Vos expéditions",
"reportMeta": "{stars} · {hours} h",
"running": "En route, retour dans {time}.",
"returned": "De retour ! Le butin vous attend.",
"completed": "Butin récupéré.",
"cancelled": "Annulée par la Guilde : vos cartes sont libres.",
"claim": "Récupérer le butin",
"claimed": "Butin récupéré !",
"started": "Expédition lancée ! Revenez à son retour.",
"rewardEclats": "+{value} Éclats",
"rewardStardust": "+{value} d’étoiles",
"rewardPacks": "{count} paquet{s} offert{s}",
"limitReached": "Récupérez le butin de votre expédition avant d’en lancer une autre.",
"planTitle": "Préparer une expédition",
"nextDay": "Nouvelles destinations dans {time}.",
"noDestination": "Aucune destination n’est proposée aujourd’hui.",
"destinationsTitle": "1. Destination du jour",
"difficultyTitle": "2. Difficulté et durée",
"difficultyLabel": "Difficulté",
"durationLabel": "Durée",
"hours": "{hours} h",
"requirementsTitle": "Exigences de l’équipe",
"main": "principale",
"conditionTag": "Condition : une carte « {tag} » dans l’équipe, sinon le score baisse.",
"conditionCollection": "Condition : une carte de {collection} dans l’équipe, sinon le score baisse.",
"dangerText": "Danger, {label} : la {stat} baisse, sauf avec une carte « {tags} ».",
"or": " » ou « ",
"teamTitle": "3. Équipe",
"teamHelp": "Choisissez {count} cartes rares ou mieux. Chaque place double une stat de la carte qui l’occupe.",
"roleBadge": "{role} · {stat} ×2",
"slotEmpty": "Place libre",
"remove": "Retirer",
"cardsLabel": "Cartes disponibles",
"chooseCard": "Placer {card} en {role}",
"power": "Puissance {power}",
"busy": "En expédition",
"noRole": "Sans rôle",
"noCards": "Il vous faut au moins {count} cartes rares, épiques, légendaires ou mythiques.",
"previewTitle": "4. Aperçu",
"previewEmpty": "Choisissez une destination et {count} cartes pour voir le résultat attendu.",
"score": "Score {score} %",
"teamVersus": "{team} / {value}",
"limitedByStars": "Limité au score de {stars} ★",
"conditionMet": "Condition remplie.",
"conditionUnmet": "Condition non remplie : le score baisse.",
"dangerCountered": "{label} : paré.",
"dangerActive": "{label} : subi, la stat visée baisse.",
"durationMalus": "Expédition longue : l’Endurance de l’équipe ne suffit pas, toutes les stats baissent.",
"expected": "Butin attendu : environ {eclats} Éclats, {stardust} d’étoiles et {pack} % de chance de rapporter un paquet.",
"start": "Partir en expédition",
"tiers": { "struggle": "Retour difficile", "success": "Réussite", "triumph": "Triomphe" },
"stats": { "bravoure": "Bravoure", "endurance": "Endurance", "fortune": "Fortune", "orientation": "Orientation" },
"statShort": { "bravoure": "Bra", "endurance": "End", "fortune": "For", "orientation": "Ori" },
"roles": { "bravoure": "Meneur", "endurance": "Gardien", "fortune": "Chercheur", "orientation": "Navigateur" }
}, },
"daily": { "daily": {
"eyebrow": "Quête quotidienne", "eyebrow": "Quête quotidienne",
@ -280,7 +358,8 @@
"redeemWhere": "Les cartes sont dans votre collection, les paquets dans « Paquets offerts ».", "redeemWhere": "Les cartes sont dans votre collection, les paquets dans « Paquets offerts ».",
"giftTitle": "Paquets offerts", "giftTitle": "Paquets offerts",
"giftDescription": "Ils s’ouvrent quand vous le souhaitez, sans utiliser vos ouvertures disponibles.", "giftDescription": "Ils s’ouvrent quand vous le souhaitez, sans utiliser vos ouvertures disponibles.",
"giftOpen": "Ouvrir" "giftOpen": "Ouvrir",
"giftFromExpedition": "Rapporté d’expédition"
} }
}, },
"library": { "library": {

View file

@ -11,6 +11,7 @@ export function CardDetailModal({ catalog, state, entry, runMutation, busy, onCl
const spare = owned?.spare || 0; const spare = owned?.spare || 0;
const value = state.shop.stardustValues[entry.edition.rarity] ?? 0; const value = state.shop.stardustValues[entry.edition.rarity] ?? 0;
const favorites = new Set(state.favorites); const favorites = new Set(state.favorites);
const expedition = state.expeditions?.busyEditions?.find((item) => item.editionId === entry.edition.id);
return <Modal dialogClassName="confirm-modal nds-modal nebula-card-detail" labelledBy="nebula-card-detail-title" onRequestClose={onClose}> return <Modal dialogClassName="confirm-modal nds-modal nebula-card-detail" labelledBy="nebula-card-detail-title" onRequestClose={onClose}>
<div className="nebula-card-detail-layout"><NebulaCard catalog={catalog} entry={entry} size="lg" /> <div className="nebula-card-detail-layout"><NebulaCard catalog={catalog} entry={entry} size="lg" />
@ -23,6 +24,7 @@ export function CardDetailModal({ catalog, state, entry, runMutation, busy, onCl
<button className="nds-button" data-variant="secondary" type="button" onClick={() => onStartTransfer("trade", entry.edition.id)}>Échanger</button> <button className="nds-button" data-variant="secondary" type="button" onClick={() => onStartTransfer("trade", entry.edition.id)}>Échanger</button>
</>} </>}
<button className="nds-button" data-variant="secondary" type="button" onClick={onClose}>Fermer</button> <button className="nds-button" data-variant="secondary" type="button" onClick={onClose}>Fermer</button>
{expedition && <p className="nebula-form-help">En expédition jusqu’à {new Date(expedition.returnsAt).toLocaleString("fr-FR", { weekday: "long", hour: "2-digit", minute: "2-digit" })}.</p>}
{quantity > 1 && !spare && <p className="nebula-form-help">Les doublons de cette carte sont réservés par une proposition d’échange en cours.</p>} {quantity > 1 && !spare && <p className="nebula-form-help">Les doublons de cette carte sont réservés par une proposition d’échange en cours.</p>}
</div> </div>
</div> </div>

View file

@ -9,6 +9,7 @@ import { CardsAccount, CardsDashboardLayout } from "./CardsDashboard.jsx";
import { CardsHomePanel } from "./CardsHomePanel.jsx"; import { CardsHomePanel } from "./CardsHomePanel.jsx";
import { CollectionPanel } from "./CollectionPanel.jsx"; import { CollectionPanel } from "./CollectionPanel.jsx";
import { DailyPanel } from "./DailyPanel.jsx"; import { DailyPanel } from "./DailyPanel.jsx";
import { ExpeditionsPanel } from "./ExpeditionsPanel.jsx";
import { HistoryPanel } from "./HistoryPanel.jsx"; import { HistoryPanel } from "./HistoryPanel.jsx";
import { PackPanel } from "./PackPanel.jsx"; import { PackPanel } from "./PackPanel.jsx";
import { publishCardsReserve } from "./cardsReserve.js"; import { publishCardsReserve } from "./cardsReserve.js";
@ -21,7 +22,7 @@ import { TransfersPanel } from "./TransfersPanel.jsx";
// Le jeu, puis l'économie et les échanges, puis le journal : mêmes groupes séparés par un filet que l'administration. // Le jeu, puis l'économie et les échanges, puis le journal : mêmes groupes séparés par un filet que l'administration.
const PLAYER_NAVIGATION = [["home", "guild", "packs", "collection"], ["shop", "transfers"], ["history", "account"]]; const PLAYER_NAVIGATION = [["home", "guild", "packs", "collection"], ["shop", "transfers"], ["history", "account"]];
// Sections sans entrée de menu, ouvertes depuis une autre : le menu y désigne cette section parente. // Sections sans entrée de menu, ouvertes depuis une autre : le menu y désigne cette section parente.
const SUBSECTION_PARENTS = { daily: "guild" }; const SUBSECTION_PARENTS = { daily: "guild", expeditions: "guild" };
const PLAYER_SECTIONS = new Set([...PLAYER_NAVIGATION.flat(), ...Object.keys(SUBSECTION_PARENTS)]); const PLAYER_SECTIONS = new Set([...PLAYER_NAVIGATION.flat(), ...Object.keys(SUBSECTION_PARENTS)]);
// Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection. // Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection.
const PLAYER_SECTION_ALIASES = { recycling: "collection" }; const PLAYER_SECTION_ALIASES = { recycling: "collection" };
@ -274,6 +275,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", adminM
{section === "home" && <CardsHomePanel {...panelProps} content={content.home} guildContent={content.guild} onOpenPacks={openPacks} />} {section === "home" && <CardsHomePanel {...panelProps} content={content.home} guildContent={content.guild} onOpenPacks={openPacks} />}
{section === "guild" && <GuildPanel catalog={catalog} state={state} content={content.guild} />} {section === "guild" && <GuildPanel catalog={catalog} state={state} content={content.guild} />}
{section === "daily" && <DailyPanel {...panelProps} content={content.daily} />} {section === "daily" && <DailyPanel {...panelProps} content={content.daily} />}
{section === "expeditions" && <ExpeditionsPanel {...panelProps} content={content.expeditions} />}
{section === "packs" && <PackPanel {...panelProps} content={content.packs} reserveContent={content.home} />} {section === "packs" && <PackPanel {...panelProps} content={content.packs} reserveContent={content.home} />}
{section === "collection" && <CollectionPanel {...panelProps} headingContent={content.collection} recyclingContent={content.recycling} onStartTransfer={startTransfer} />} {section === "collection" && <CollectionPanel {...panelProps} headingContent={content.collection} recyclingContent={content.recycling} onStartTransfer={startTransfer} />}
{section === "shop" && <ShopPanel {...panelProps} content={content.shop} onOpenPacks={openPacks} />} {section === "shop" && <ShopPanel {...panelProps} content={content.shop} onOpenPacks={openPacks} />}

View file

@ -0,0 +1,143 @@
// Rôle : prépare une expédition solo : destination du jour, difficulté, durée, équipe par rôle et aperçu exact avant le départ.
import { useEffect, useMemo, useState } from "react";
import { previewExpedition } from "./cardsApi.js";
import { fillTemplate } from "./dailyShare.js";
import { conditionText, coverEntry, dangerText, editionEntry, formatDecimal, formatEclats, STAT_IDS } from "./expeditionFormat.js";
import { NebulaCard } from "./NebulaCard.jsx";
const PREVIEW_DELAY_MS = 250;
const TIER_VARIANTS = { struggle: "neutral", success: "success", triumph: "gold" };
function StatLine({ stats, content }) {
return <span className="nebula-expedition-stats">{STAT_IDS.map((stat) => <span key={stat} title={content.stats[stat]}>{content.statShort[stat]} {formatDecimal(stats[stat])}</span>)}</span>;
}
function Requirements({ catalog, option, content }) {
return <div className="nebula-expedition-requirements">
<h4>{content.requirementsTitle}</h4>
<ul>{option.requirements.map((requirement) => <li key={requirement.stat}>
<span>{content.stats[requirement.stat]}{requirement.main && <span className="nds-badge" data-variant="neutral">{content.main}</span>}</span>
<strong>{requirement.value}</strong>
</li>)}</ul>
{option.condition && <p>{conditionText(option.condition, catalog, content)}</p>}
{option.dangers.map((danger) => <p key={danger.id}>{dangerText(danger, catalog, content)}</p>)}
</div>;
}
function Preview({ preview, content }) {
return <div className="nebula-expedition-preview" aria-live="polite">
<div className="nebula-expedition-rewards">
<span className="nds-badge" data-variant={TIER_VARIANTS[preview.tier]}>{content.tiers[preview.tier]}</span>
<span className="nds-badge" data-variant="neutral">{fillTemplate(content.score, { score: formatEclats(preview.scorePct) })}</span>
{preview.limitedByStars && <span className="nds-badge" data-variant="warning">{fillTemplate(content.limitedByStars, { stars: preview.limitedByStars })}</span>}
</div>
<ul className="nebula-expedition-checks">{preview.requirements.map((requirement) => <li key={requirement.stat} data-met={requirement.ratioPct >= 100 || undefined}>
<span>{content.stats[requirement.stat]}</span><strong>{fillTemplate(content.teamVersus, { team: formatDecimal(requirement.team), value: requirement.value })}</strong>
</li>)}</ul>
{preview.conditionMet != null && <p className="nds-inline-notice" data-variant={preview.conditionMet ? "success" : "warning"}>{preview.conditionMet ? content.conditionMet : content.conditionUnmet}</p>}
{preview.dangers.map((danger) => <p key={danger.id} className="nds-inline-notice" data-variant={danger.countered ? "success" : "warning"}>{fillTemplate(danger.countered ? content.dangerCountered : content.dangerActive, { label: danger.label })}</p>)}
{preview.durationFactor < 1 && <p className="nds-inline-notice" data-variant="warning">{content.durationMalus}</p>}
<p className="nebula-expedition-expected">{fillTemplate(content.expected, { eclats: formatEclats(preview.expected.eclats), stardust: formatEclats(preview.expected.stardust), pack: formatEclats(preview.expected.packChancePct) })}</p>
</div>;
}
export function ExpeditionPlanner({ catalog, view, content, busy, onStart }) {
const [destinationId, setDestinationId] = useState(view.destinations[0]?.id || "");
const [stars, setStars] = useState(view.stars.min);
const [hours, setHours] = useState(view.durations[0]);
const [slots, setSlots] = useState(() => Array.from({ length: view.soloCards }, () => null));
const [activeSlot, setActiveSlot] = useState(0);
const [preview, setPreview] = useState({ key: "", value: null, error: "" });
const destination = view.destinations.find((item) => item.id === destinationId) || view.destinations[0];
const option = destination?.stars[stars];
const complete = Boolean(destination && slots.every(Boolean));
const body = useMemo(() => ({ day: view.day, destinationId: destination?.id, difficulty: stars, durationHours: hours, slots }), [view.day, destination?.id, stars, hours, slots]);
const bodyKey = JSON.stringify(body);
// Aperçu demandé au serveur dès que l'équipe est complète, après une courte pause pour ne pas l'interroger à chaque clic.
useEffect(() => {
if (!complete) return undefined;
let active = true;
const timer = setTimeout(() => {
previewExpedition(JSON.parse(bodyKey))
.then((result) => { if (active) setPreview({ key: bodyKey, value: result.preview, error: "" }); })
.catch((error) => { if (active) setPreview({ key: bodyKey, value: null, error: error.message }); });
}, PREVIEW_DELAY_MS);
return () => { active = false; clearTimeout(timer); };
}, [bodyKey, complete]);
const roleStat = destination?.roles[activeSlot];
const cards = useMemo(() => [...view.cards].sort((a, b) => Number(a.busy) - Number(b.busy) || (b.stats[roleStat] ?? 0) - (a.stats[roleStat] ?? 0) || b.power - a.power), [view.cards, roleStat]);
if (!destination) return <div className="nds-empty-state"><p>{content.noDestination}</p></div>;
function choose(card) {
const next = slots.map((editionId, index) => (index !== activeSlot && editionId && editionEntry(catalog, editionId)?.card.id === card.cardId ? null : editionId));
next[activeSlot] = card.editionId;
setSlots(next);
const empty = next.findIndex((editionId) => !editionId);
if (empty >= 0) setActiveSlot(empty);
}
const shownPreview = complete && preview.key === bodyKey ? preview : null;
return <div className="nebula-expedition-planner">
<section className="nds-panel nebula-expedition-step" aria-labelledby="nebula-expedition-destinations-title">
<h3 id="nebula-expedition-destinations-title">{content.destinationsTitle}</h3>
<div className="nebula-expedition-destinations">{view.destinations.map((item) => {
const cover = item.coverCardId && coverEntry(catalog, item.coverCardId);
return <button key={item.id} type="button" className="nebula-expedition-destination" aria-pressed={item.id === destination.id} onClick={() => setDestinationId(item.id)}>
{cover && <img src={cover.card.image} alt="" />}
<span className="nebula-expedition-destination-copy">
<strong>{item.name}</strong>
<span>{item.description}</span>
<span className="nebula-expedition-destination-roles">{item.roles.map((stat) => <span key={stat} className="nds-badge" data-variant="neutral">{fillTemplate(content.roleBadge, { role: content.roles[stat], stat: content.stats[stat] })}</span>)}</span>
</span>
</button>;
})}</div>
</section>
<section className="nds-panel nebula-expedition-step" aria-labelledby="nebula-expedition-settings-title">
<h3 id="nebula-expedition-settings-title">{content.difficultyTitle}</h3>
<div className="nebula-expedition-choices">
<div role="group" aria-label={content.difficultyLabel} className="nds-toolbar">{Object.keys(destination.stars).map(Number).map((value) => <button key={value} type="button" className="nds-button" data-size="sm" data-variant={value === stars ? "primary" : "secondary"} aria-pressed={value === stars} onClick={() => setStars(value)}>{"★".repeat(value)}</button>)}</div>
<div role="group" aria-label={content.durationLabel} className="nds-toolbar">{view.durations.map((value) => <button key={value} type="button" className="nds-button" data-size="sm" data-variant={value === hours ? "primary" : "secondary"} aria-pressed={value === hours} onClick={() => setHours(value)}>{fillTemplate(content.hours, { hours: value })}</button>)}</div>
</div>
{option && <Requirements catalog={catalog} option={option} content={content} />}
</section>
<section className="nds-panel nebula-expedition-step" aria-labelledby="nebula-expedition-team-title">
<h3 id="nebula-expedition-team-title">{content.teamTitle}</h3>
<p className="nebula-form-help">{fillTemplate(content.teamHelp, { count: view.soloCards })}</p>
<div className="nebula-expedition-slots">{slots.map((editionId, index) => {
const entry = editionId && editionEntry(catalog, editionId);
const stat = destination.roles[index];
return <div key={index} className="nebula-expedition-slot" data-active={index === activeSlot || undefined}>
<button type="button" className="nds-button" data-size="sm" data-variant={index === activeSlot ? "primary" : "secondary"} aria-pressed={index === activeSlot} onClick={() => setActiveSlot(index)}>
{fillTemplate(content.roleBadge, { role: content.roles[stat], stat: content.stats[stat] })}
</button>
<span>{entry ? entry.card.name : content.slotEmpty}</span>
{entry && <button type="button" className="nds-button" data-size="sm" data-variant="secondary" onClick={() => { setSlots(slots.map((value, position) => (position === index ? null : value))); setActiveSlot(index); }}>{content.remove}</button>}
</div>;
})}</div>
{cards.length ? <ul className="nebula-expedition-cards" aria-label={content.cardsLabel}>{cards.map((card) => {
const entry = editionEntry(catalog, card.editionId);
if (!entry) return null;
const selected = slots.includes(card.editionId);
return <li key={card.editionId} data-busy={card.busy || undefined}>
<NebulaCard catalog={catalog} entry={entry} size="sm" selected={selected} disabled={card.busy} onSelect={card.busy ? undefined : () => choose(card)} selectLabel={fillTemplate(content.chooseCard, { card: entry.card.name, role: content.roles[roleStat] })} />
<span className="nebula-expedition-card-power">{card.busy ? content.busy : fillTemplate(content.power, { power: card.power })}</span>
<StatLine stats={card.stats} content={content} />
</li>;
})}</ul> : <p className="nds-inline-notice" data-variant="info">{fillTemplate(content.noCards, { count: view.soloCards })}</p>}
</section>
<section className="nds-panel nebula-expedition-step" aria-labelledby="nebula-expedition-preview-title">
<h3 id="nebula-expedition-preview-title">{content.previewTitle}</h3>
{!complete && <p className="nebula-form-help">{fillTemplate(content.previewEmpty, { count: view.soloCards })}</p>}
{shownPreview?.error && <p className="nds-inline-notice" data-variant="warning" role="status">{shownPreview.error}</p>}
{shownPreview?.value && <Preview preview={shownPreview.value} content={content} />}
<div className="nds-toolbar">
<button className="nds-button" data-variant="primary" type="button" disabled={busy || !complete} onClick={async () => { if (await onStart(body)) setSlots(slots.map(() => null)); }}>{content.start}</button>
</div>
</section>
</div>;
}

View file

@ -0,0 +1,45 @@
// Rôle : présente une expédition du joueur : en route (compte à rebours), revenue (butin à récupérer), terminée ou annulée.
import { fillTemplate, formatCountdown } from "./dailyShare.js";
import { coverEntry, editionEntry, formatEclats } from "./expeditionFormat.js";
import { NebulaCard } from "./NebulaCard.jsx";
import { formatStardust } from "./stardustFormat.js";
const TIER_VARIANTS = { struggle: "neutral", success: "success", triumph: "gold" };
function RewardBadges({ reward, content }) {
return <div className="nebula-expedition-rewards">
<span className="nds-badge" data-variant="gold">{fillTemplate(content.rewardEclats, { value: formatEclats(reward.eclats) })}</span>
{reward.stardust > 0 && <span className="nds-badge" data-variant="neutral">{fillTemplate(content.rewardStardust, { value: formatStardust(reward.stardust) })}</span>}
{reward.packs.length > 0 && <span className="nds-badge" data-variant="success">{fillTemplate(content.rewardPacks, { count: reward.packs.length, s: reward.packs.length > 1 ? "s" : "" })}</span>}
</div>;
}
export function ExpeditionReport({ catalog, expedition, content, now, busy, onClaim }) {
// Le serveur dit « en route » au chargement ; passé l'heure du retour, la page propose déjà de récupérer le butin.
const status = expedition.status === "running" && expedition.returnsAt <= now ? "returned" : expedition.status;
const cover = expedition.destination.coverCardId && coverEntry(catalog, expedition.destination.coverCardId);
const stars = "★".repeat(expedition.stars);
return <article className="nds-card nebula-expedition-report" data-status={status} aria-labelledby={`nebula-expedition-${expedition.id}`}>
{cover && <div className="nds-card-cover nebula-expedition-report-cover" aria-hidden="true"><img src={cover.card.image} alt="" /></div>}
<div className="nds-card-body nebula-expedition-report-body">
<p className="eyebrow">{fillTemplate(content.reportMeta, { stars, hours: expedition.hours })}</p>
<h3 id={`nebula-expedition-${expedition.id}`}>{expedition.destination.name}</h3>
{status === "running" && <p className="nebula-expedition-report-status">{fillTemplate(content.running, { time: formatCountdown(expedition.returnsAt - now) })}</p>}
{status === "returned" && <p className="nebula-expedition-report-status">{content.returned}</p>}
{status === "completed" && <p className="nebula-expedition-report-status">{content.completed}</p>}
{status === "cancelled" && <p className="nebula-expedition-report-status">{content.cancelled}</p>}
{expedition.result && <div className="nebula-expedition-rewards">
<span className="nds-badge" data-variant={TIER_VARIANTS[expedition.result.tier]}>{content.tiers[expedition.result.tier]}</span>
<span className="nds-badge" data-variant="neutral">{fillTemplate(content.score, { score: formatEclats(expedition.result.scorePct) })}</span>
</div>}
{expedition.reward && <RewardBadges reward={expedition.reward} content={content} />}
<ul className="nebula-expedition-report-team" aria-label={content.teamTitle}>{expedition.slots.filter((slot) => slot.editionId).map((slot) => {
const entry = editionEntry(catalog, slot.editionId);
return entry && <li key={slot.position}><NebulaCard catalog={catalog} entry={entry} size="sm" /><span>{slot.role ? content.roles[slot.role] : content.noRole}</span></li>;
})}</ul>
{status === "returned" && !expedition.claimedAt && <div className="nds-card-actions">
<button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy} onClick={() => onClaim(expedition.id)}>{content.claim}</button>
</div>}
</div>
</article>;
}

View file

@ -0,0 +1,90 @@
// Rôle : présente les Expéditions, quête de la Guilde : expéditions du joueur (retour, butin) et préparation d'une expédition solo.
import { useEffect, useState } from "react";
import { claimExpedition, loadExpeditions, startExpedition } from "./cardsApi.js";
import { fillTemplate, formatCountdown } from "./dailyShare.js";
import { ExpeditionPlanner } from "./ExpeditionPlanner.jsx";
import { ExpeditionReport } from "./ExpeditionReport.jsx";
import { formatEclats } from "./expeditionFormat.js";
const COUNTDOWN_TICK_MS = 30_000;
// Les refus propres aux Expéditions restent dans ce panneau ; runMutation garde le reste (réseau, session).
const expeditionCall = (call) => async () => {
try {
return await call();
} catch (error) {
if (String(error.code || "").startsWith("EXPEDITION")) return { expeditionError: error };
throw error;
}
};
export function ExpeditionsPanel({ catalog, state, runMutation, busy, content }) {
const [view, setView] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const [notice, setNotice] = useState(null);
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
let active = true;
loadExpeditions()
.then((result) => { if (active) { setView(result); setLoadError(""); setNow(Date.now()); } })
.catch((error) => { if (active) setLoadError(error.message); });
return () => { active = false; };
}, [reloadKey]);
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), COUNTDOWN_TICK_MS);
return () => clearInterval(timer);
}, []);
if (loadError) return <section className="nds-empty-state" role="alert"><h2>{content.title}</h2><p>{loadError}</p></section>;
if (!view) return <section className="nds-empty-state" aria-busy="true"><h2>{content.title}</h2></section>;
const reload = () => { setNotice(null); setReloadKey((key) => key + 1); };
const handle = (result, success) => {
if (result?.expeditions) {
setView(result.expeditions);
setNow(Date.now());
setNotice(success ? { variant: "success", text: success } : null);
return true;
}
if (result?.expeditionError?.code === "EXPEDITION_DAY_EXPIRED") setNow(view.nextDayAt);
else if (result?.expeditionError) setNotice({ variant: "warning", text: result.expeditionError.message });
return false;
};
const start = async (body) => handle(await runMutation(expeditionCall(() => startExpedition(body))), content.started);
const claim = async (id) => handle(await runMutation(expeditionCall(() => claimExpedition(id))), content.claimed);
const expired = view.enabled && now >= view.nextDayAt;
const active = view.expeditions.filter((expedition) => expedition.status === "running" && !expedition.claimedAt);
const limitReached = active.length >= view.soloLimit;
return <section className="nebula-expeditions" aria-labelledby="nebula-expeditions-title">
<div className="nds-section-heading nebula-section-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-expeditions-title">{content.title}</h2><p className="nebula-guild-intro">{content.intro}</p></div>
<div className="nebula-daily-heading-actions">
<span className="nds-badge" data-variant="gold" title={content.eclatsHelp}>{fillTemplate(content.eclatsBalance, { value: formatEclats(state.wallet.eclats ?? 0) })}</span>
<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a>
</div>
</div>
<p className="nebula-form-help">{content.eclatsHelp}</p>
{notice && <p className="nds-inline-notice" data-variant={notice.variant} role="status">{notice.text}</p>}
{expired && <div className="nds-inline-notice nebula-daily-expired" data-variant="warning" role="status"><span>{content.expired}</span><button className="nds-button" data-size="sm" data-variant="primary" type="button" onClick={reload}>{content.reload}</button></div>}
{view.expeditions.length > 0 && <section className="nebula-expedition-active" aria-labelledby="nebula-expedition-active-title">
<h3 id="nebula-expedition-active-title">{content.activeTitle}</h3>
<div className="nebula-expedition-reports">{view.expeditions.map((expedition) => <ExpeditionReport key={expedition.id} catalog={catalog} expedition={expedition} content={content} now={now} busy={busy} onClaim={claim} />)}</div>
</section>}
{!view.enabled ? <div className="nds-empty-state"><h3>{content.closedTitle}</h3><p>{content.closedText}</p></div>
: limitReached ? <p className="nds-inline-notice" data-variant="info">{content.limitReached}</p>
: !expired && <>
<div className="nebula-expedition-plan-heading">
<h3>{content.planTitle}</h3>
<span className="nebula-form-help">{fillTemplate(content.nextDay, { time: formatCountdown(view.nextDayAt - now) })}</span>
</div>
<ExpeditionPlanner key={view.day} catalog={catalog} view={view} content={content} busy={busy} onStart={start} />
</>}
</section>;
}

View file

@ -1,5 +1,7 @@
// Rôle : présente la Guilde des Veilleurs et la tuile de chacune de ses quêtes, avec leur état. // Rôle : présente la Guilde des Veilleurs et la tuile de chacune de ses quêtes, avec leur état.
import { useState } from "react";
import { dailyQuestStatus, fillTemplate, formatStreak } from "./dailyShare.js"; import { dailyQuestStatus, fillTemplate, formatStreak } from "./dailyShare.js";
import { expeditionQuestStatus } from "./expeditionFormat.js";
import { guildQuests } from "./guildQuests.js"; import { guildQuests } from "./guildQuests.js";
// Carte du jour : un dos vierge, propre à aucune collection et marqué d'un « ? », figure la carte cachée à retrouver. // Carte du jour : un dos vierge, propre à aucune collection et marqué d'un « ? », figure la carte cachée à retrouver.
@ -28,18 +30,41 @@ function DailyQuest({ summary: daily, content }) {
</article>; </article>;
} }
// Expéditions : la couverture montre le Grand Vide, et le bouton mène au butin dès qu'une expédition est revenue.
const EXPEDITIONS_COVER = "/static/img/cards/primordial-nebula/epic/deep_sky_ray.webp";
function ExpeditionsQuest({ summary, pending, content, now }) {
const returned = summary.returned > 0 || (summary.nextReturnAt != null && summary.nextReturnAt <= now);
return <article className="nds-card nebula-quest" data-status={returned ? "returned" : summary.running ? "running" : "idle"} aria-labelledby="nebula-quest-expeditions-title">
<div className="nebula-quest-media">
<div className="nds-card-cover nebula-quest-cover" aria-hidden="true"><img src={EXPEDITIONS_COVER} alt="" /></div>
</div>
<div className="nds-card-body nebula-quest-body">
<p className="eyebrow">{content.expeditionsKind}</p>
<h3 id="nebula-quest-expeditions-title">{content.expeditionsTitle}</h3>
<p>{content.expeditionsDescription}</p>
<p className="nebula-quest-status">{expeditionQuestStatus(summary, content, now)}</p>
<div className="nds-card-actions">
<a className="nds-button" data-size="sm" data-variant={pending ? "primary" : "secondary"} href="#/cards/expeditions">{returned ? content.expeditionsClaim : summary.enabled ? content.expeditionsAction : content.expeditionsOpen}</a>
</div>
</div>
</article>;
}
// Tuile de chaque type de quête, choisie par l'identifiant donné dans guildQuests. // Tuile de chaque type de quête, choisie par l'identifiant donné dans guildQuests.
const QUEST_TILES = { daily: DailyQuest }; const QUEST_TILES = { daily: DailyQuest, expeditions: ExpeditionsQuest };
export function GuildPanel({ catalog, state, content }) { export function GuildPanel({ catalog, state, content }) {
const quests = guildQuests(state).filter((quest) => QUEST_TILES[quest.id]); // Heure d'affichage de la page : elle suffit pour savoir si une expédition est déjà rentrée.
const [now] = useState(() => Date.now());
const quests = guildQuests(state, now).filter((quest) => QUEST_TILES[quest.id]);
return <section className="nebula-quests" aria-labelledby="nebula-guild-title"> return <section className="nebula-quests" aria-labelledby="nebula-guild-title">
<div className="nds-section-heading nebula-section-heading"> <div className="nds-section-heading nebula-section-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-guild-title">{content.title}</h2><p className="nebula-guild-intro">{content.intro}</p></div> <div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-guild-title">{content.title}</h2><p className="nebula-guild-intro">{content.intro}</p></div>
</div> </div>
{quests.length ? <div className="nebula-quests-grid">{quests.map(({ id, summary }) => { {quests.length ? <div className="nebula-quests-grid">{quests.map(({ id, summary, pending }) => {
const Tile = QUEST_TILES[id]; const Tile = QUEST_TILES[id];
return <Tile key={id} catalog={catalog} summary={summary} content={content} />; return <Tile key={id} catalog={catalog} summary={summary} pending={pending} content={content} now={now} />;
})}</div> })}</div>
: <div className="nds-empty-state"><p>{content.empty}</p></div>} : <div className="nds-empty-state"><p>{content.empty}</p></div>}
</section>; </section>;

View file

@ -16,7 +16,9 @@ const EVENT_LABELS = {
gift_pack_opened: "Paquet offert ouvert", gift_pack_opened: "Paquet offert ouvert",
cards_recycled: "Doublons recyclés", cards_recycled: "Doublons recyclés",
opening_purchased: "Ouverture achetée", opening_purchased: "Ouverture achetée",
daily_won: "Carte du jour trouvée" daily_won: "Carte du jour trouvée",
expedition_completed: "Expédition terminée",
expedition_cancelled_by_guild: "Expédition annulée par la Guilde"
}; };
// Le journal garde la quantité réellement offerte : les comptes plus anciens n'ont reçu qu'une ouverture. // Le journal garde la quantité réellement offerte : les comptes plus anciens n'ont reçu qu'une ouverture.
@ -52,6 +54,12 @@ function HistoryDetail({ entry, catalog }) {
if (details.sent || details.received) return <span>{[details.sent && `Donnée : ${cardReference(details.sent, catalog)}`, details.received && `Reçue : ${cardReference(details.received, catalog)}`].filter(Boolean).join(" · ")}</span>; if (details.sent || details.received) return <span>{[details.sent && `Donnée : ${cardReference(details.sent, catalog)}`, details.received && `Reçue : ${cardReference(details.received, catalog)}`].filter(Boolean).join(" · ")}</span>;
if (entry.type === "cards_recycled") return <span>{details.count} exemplaire{details.count > 1 ? "s" : ""} · +{formatStardust(details.stardust)} d’étoiles</span>; if (entry.type === "cards_recycled") return <span>{details.count} exemplaire{details.count > 1 ? "s" : ""} · +{formatStardust(details.stardust)} d’étoiles</span>;
if (entry.type === "daily_won") return <span>{`Défi n° ${details.number} · ${details.guesses}/6`}{details.stardust > 0 && ` · +${formatStardust(details.stardust)} d’étoiles`}</span>; if (entry.type === "daily_won") return <span>{`Défi n° ${details.number} · ${details.guesses}/6`}{details.stardust > 0 && ` · +${formatStardust(details.stardust)} d’étoiles`}</span>;
if (entry.type === "expedition_completed") {
const tier = { struggle: "Retour difficile", success: "Réussite", triumph: "Triomphe" }[details.tier];
const gains = [`+${details.eclats} Éclats`, details.stardust > 0 && `+${formatStardust(details.stardust)} d’étoiles`, details.packs > 0 && `${details.packs} paquet${details.packs > 1 ? "s" : ""} offert${details.packs > 1 ? "s" : ""}`].filter(Boolean);
return <span>{[`${details.destinationName} · ${"★".repeat(details.difficulty)} · ${details.hours} h`, tier, ...gains].filter(Boolean).join(" · ")}</span>;
}
if (entry.type === "expedition_cancelled_by_guild") return <span>{details.destinationName} · cartes libérées, sans butin</span>;
if (entry.type === "opening_purchased") return <span>−{formatStardust(details.price)} d’étoiles</span>; if (entry.type === "opening_purchased") return <span>−{formatStardust(details.price)} d’étoiles</span>;
if (!details.collectionId) return null; if (!details.collectionId) return null;
const name = catalog.collections.find((item) => item.id === details.collectionId)?.name; const name = catalog.collections.find((item) => item.id === details.collectionId)?.name;

View file

@ -71,10 +71,10 @@ export function PackPanel({ catalog, state, runMutation, busy, content, reserveC
<div className="nebula-pack-grid">{giftPacks.map((gift) => { <div className="nebula-pack-grid">{giftPacks.map((gift) => {
const collection = catalog.collections.find((item) => item.id === gift.collectionId); const collection = catalog.collections.find((item) => item.id === gift.collectionId);
const details = packDetails(gift.options, catalog); const details = packDetails(gift.options, catalog);
return <button key={gift.id} type="button" className="nebula-pack nebula-gift-pack" disabled={busy} aria-label={`${content.giftOpen} : ${collection?.name} (${gift.campaignName})`} onClick={() => runMutation(() => openGiftPack(gift.id))}> return <button key={gift.id} type="button" className="nebula-pack nebula-gift-pack" disabled={busy} aria-label={`${content.giftOpen} : ${collection?.name} (${gift.sourceName ?? gift.campaignName})`} onClick={() => runMutation(() => openGiftPack(gift.id))}>
<span className="nebula-pack-back" data-card-size="md"><CollectionCardBack collection={collection} /></span> <span className="nebula-pack-back" data-card-size="md"><CollectionCardBack collection={collection} /></span>
<span className="nebula-pack-note"> <span className="nebula-pack-note">
<span className="nebula-pack-copy">{gift.campaignName}</span> <span className="nebula-pack-copy">{gift.source === "expedition" ? `${content.giftFromExpedition} · ${gift.sourceName}` : gift.campaignName}</span>
{details.length > 0 && <span className="nebula-gift-pack-details">{details.join(" · ")}</span>} {details.length > 0 && <span className="nebula-gift-pack-details">{details.join(" · ")}</span>}
</span> </span>
</button>; </button>;

View file

@ -2,6 +2,7 @@
import { useState } from "react"; import { useState } from "react";
import { ApplyActions } from "./adminSettingForm.jsx"; import { ApplyActions } from "./adminSettingForm.jsx";
import { inRange, MAX_VALUE, parse, shopSettingSaver } from "./adminSettings.js"; import { inRange, MAX_VALUE, parse, shopSettingSaver } from "./adminSettings.js";
import { ExpeditionSettings } from "./ExpeditionSettings.jsx";
// Carte du jour : la partie du jour (joueurs et gagnants), puis la récompense d'une victoire. // Carte du jour : la partie du jour (joueurs et gagnants), puis la récompense d'une victoire.
function DailyQuestSettings({ setting, daily, busy, save }) { function DailyQuestSettings({ setting, daily, busy, save }) {
@ -31,7 +32,10 @@ export function AdminGuild({ dashboard, busy, runMutation, refreshDashboard }) {
const save = shopSettingSaver(setting, runMutation, refreshDashboard); const save = shopSettingSaver(setting, runMutation, refreshDashboard);
return <div className="nebula-admin-shop-page"> return <div className="nebula-admin-shop-page">
{setting {setting
? <DailyQuestSettings key={setting.dailyReward} setting={setting} daily={dashboard.daily} busy={busy} save={save} /> ? <>
<DailyQuestSettings key={setting.dailyReward} setting={setting} daily={dashboard.daily} busy={busy} save={save} />
{dashboard.expeditionSettings && <ExpeditionSettings dashboard={dashboard} busy={busy} runMutation={runMutation} refreshDashboard={refreshDashboard} />}
</>
: <div className="nds-empty-state" aria-busy="true"><p>Chargement des quêtes…</p></div>} : <div className="nds-empty-state" aria-busy="true"><p>Chargement des quêtes…</p></div>}
</div>; </div>;
} }

View file

@ -3,6 +3,7 @@ import { useEffect, useState } from "react";
import { loadAdminHistory } from "../cardsApi.js"; import { loadAdminHistory } from "../cardsApi.js";
import { summarizeReward } from "../rewardText.js"; import { summarizeReward } from "../rewardText.js";
import { DATE_FORMATTER, formatDuration } from "./adminFormat.js"; import { DATE_FORMATTER, formatDuration } from "./adminFormat.js";
import { expeditionSettingLabel, formatSettingValue } from "./expeditionSettingFields.js";
const EVENT_LABELS = { const EVENT_LABELS = {
recharge_updated: "Recharge modifiée", recharge_updated: "Recharge modifiée",
@ -15,7 +16,9 @@ const EVENT_LABELS = {
campaign_created: "Campagne créée", campaign_created: "Campagne créée",
campaign_revoked: "Campagne révoquée", campaign_revoked: "Campagne révoquée",
campaign_extended: "Campagne prolongée", campaign_extended: "Campagne prolongée",
account_deleted: "Compte joueur supprimé" account_deleted: "Compte joueur supprimé",
expedition_settings_updated: "Expéditions modifiées",
expedition_cancelled: "Expédition annulée"
}; };
const collectionName = (entry, catalog) => catalog.collections.find((item) => item.id === entry.entityId)?.name || entry.entityId; const collectionName = (entry, catalog) => catalog.collections.find((item) => item.id === entry.entityId)?.name || entry.entityId;
@ -51,6 +54,8 @@ function eventDetail(entry, catalog) {
case "campaign_created": return `${campaignName || entry.entityId} · ${summarizeReward(details.reward, catalog)}`; case "campaign_created": return `${campaignName || entry.entityId} · ${summarizeReward(details.reward, catalog)}`;
case "campaign_extended": return `${campaignName || entry.entityId} · ${details.expiresAt == null ? "sans expiration" : `jusqu’au ${DATE_FORMATTER.format(details.expiresAt)}`}`; case "campaign_extended": return `${campaignName || entry.entityId} · ${details.expiresAt == null ? "sans expiration" : `jusqu’au ${DATE_FORMATTER.format(details.expiresAt)}`}`;
case "campaign_revoked": return campaignName || entry.entityId; case "campaign_revoked": return campaignName || entry.entityId;
case "expedition_settings_updated": return (details.changes || []).map((item) => change(expeditionSettingLabel(item.path), formatSettingValue(item.previous), formatSettingValue(item.next))).filter(Boolean).join(" · ");
case "expedition_cancelled": return details.destinationId;
default: return ""; default: return "";
} }
} }

View file

@ -0,0 +1,128 @@
// Rôle : règle les Expéditions depuis Administration › Guilde : un panneau par groupe de réglages, les destinations, et le suivi du jour.
import { useState } from "react";
import { ConfirmModal } from "../../../components/ToolboxModals.jsx";
import { cancelExpedition, updateExpeditionSettings } from "../cardsApi.js";
import { DATE_FORMATTER } from "./adminFormat.js";
import { ApplyActions } from "./adminSettingForm.jsx";
import { inRange, parse } from "./adminSettings.js";
import { EXPEDITION_SETTING_GROUPS } from "./expeditionSettingFields.js";
const readPath = (source, path) => path.split(".").reduce((value, key) => value?.[key], source);
function writePath(target, path, value) {
const keys = path.split(".");
keys.slice(0, -1).reduce((node, key) => node[key], target)[keys.at(-1)] = value;
}
const toDraft = (value) => (typeof value === "boolean" ? value : Array.isArray(value) ? value.map(String) : String(value));
const fromDraft = (value) => (typeof value === "boolean" ? value : Array.isArray(value) ? value.map(parse) : parse(value));
const validValue = (field, value) => (field.kind === "bool" ? typeof value === "boolean" : (Array.isArray(value) ? value : [value]).every((item) => inRange(item, field.min, field.max)));
// Un panneau : brouillon de ses réglages, vérifiés avec les bornes du serveur ; les contraintes entre réglages sont vérifiées par le serveur.
function SettingsGroup({ group, settings, schema, busy, save }) {
const fields = group.fields.map((field) => ({ ...field, ...schema.find((item) => item.path === field.path) }));
const initial = () => Object.fromEntries(fields.map((field) => [field.path, toDraft(readPath(settings, field.path))]));
const [draft, setDraft] = useState(initial);
const values = Object.fromEntries(fields.map((field) => [field.path, fromDraft(draft[field.path])]));
const invalid = fields.filter((field) => !validValue(field, values[field.path]));
const changed = !invalid.length && fields.some((field) => JSON.stringify(values[field.path]) !== JSON.stringify(readPath(settings, field.path)));
const set = (path, value) => setDraft((current) => ({ ...current, [path]: value }));
return <section className="nds-panel nebula-admin-shop nebula-admin-expedition-group" aria-labelledby={`nebula-admin-expedition-${group.id}`}>
<div className="nds-section-heading nebula-admin-panel-heading"><h3 id={`nebula-admin-expedition-${group.id}`}>{group.title}</h3></div>
<p className="nebula-form-help">{group.help}</p>
<div className="nebula-admin-expedition-fields">{fields.map((field) => {
const value = draft[field.path];
if (field.kind === "bool") return <div key={field.path} className="nebula-admin-expedition-field">
<span>{field.label}</span>
<button className="nds-button" data-size="sm" data-variant={value ? "primary" : "secondary"} type="button" aria-pressed={value} aria-label={field.label} disabled={busy} onClick={() => set(field.path, !value)}>{value ? "Oui" : "Non"}</button>
</div>;
if (Array.isArray(value)) return <fieldset key={field.path} className="nebula-admin-expedition-field">
<legend>{field.label}</legend>
<div className="nebula-admin-expedition-items">{value.map((item, index) => <label key={index}><span>{field.items?.[index] ?? index + 1}</span>
<input className="nds-input" type="number" inputMode="numeric" min={field.min} max={field.max} step="1" value={item} disabled={busy} onChange={(event) => set(field.path, value.map((current, position) => (position === index ? event.target.value : current)))} />
</label>)}</div>
</fieldset>;
return <label key={field.path} className="nebula-admin-expedition-field"><span>{field.label}</span>
<input className="nds-input" type="number" inputMode="numeric" min={field.min} max={field.max} step="1" value={value} disabled={busy} onChange={(event) => set(field.path, event.target.value)} />
</label>;
})}</div>
{invalid.length > 0 && <p className="nebula-form-help" role="alert">{invalid.map((field) => `${field.label} : entier de ${field.min.toLocaleString("fr-FR")} à ${field.max.toLocaleString("fr-FR")}`).join(" · ")}</p>}
<ApplyActions
busy={busy}
changed={changed}
onCancel={() => setDraft(initial())}
onApply={() => save((next) => fields.forEach((field) => writePath(next, field.path, values[field.path])))}
confirmTitle={`Appliquer les réglages « ${group.title} » ?`}
confirmMessage="Les nouveaux réglages s’appliquent aux prochains départs. Les expéditions en route gardent ceux de leur départ."
/>
</section>;
}
// Destinations : proposées ou non, et poids dans le tirage du jour. Leurs textes vivent dans le fichier du serveur.
function DestinationSettings({ settings, destinations, busy, save }) {
const initial = () => Object.fromEntries(destinations.map((destination) => [destination.id, { active: settings.destinations[destination.id].active, weight: String(settings.destinations[destination.id].weight) }]));
const [draft, setDraft] = useState(initial);
const invalid = destinations.filter((destination) => !inRange(parse(draft[destination.id].weight), 0, 100));
const changed = !invalid.length && destinations.some((destination) => draft[destination.id].active !== settings.destinations[destination.id].active || parse(draft[destination.id].weight) !== settings.destinations[destination.id].weight);
const set = (id, changes) => setDraft((current) => ({ ...current, [id]: { ...current[id], ...changes } }));
return <section className="nds-panel nebula-admin-shop nebula-admin-expedition-group" aria-labelledby="nebula-admin-expedition-destinations">
<div className="nds-section-heading nebula-admin-panel-heading"><h3 id="nebula-admin-expedition-destinations">Destinations</h3></div>
<p className="nebula-form-help">Une destination retirée n’est plus tirée ; le poids règle sa fréquence parmi les destinations proposées. Les destinations cachées ne sont jamais tirées.</p>
<ul className="nebula-admin-expedition-destinations">{destinations.map((destination) => <li key={destination.id} className="nds-list-row">
<strong>{destination.name}{destination.hidden && <span className="nds-badge" data-variant="neutral">Cachée</span>}</strong>
<button className="nds-button" data-size="sm" data-variant={draft[destination.id].active ? "primary" : "secondary"} type="button" aria-pressed={draft[destination.id].active} aria-label={`${destination.name} proposée`} disabled={busy} onClick={() => set(destination.id, { active: !draft[destination.id].active })}>{draft[destination.id].active ? "Proposée" : "Retirée"}</button>
<label><span>Poids</span><input className="nds-input" type="number" inputMode="numeric" min="0" max="100" step="1" value={draft[destination.id].weight} disabled={busy} aria-label={`Poids de ${destination.name}`} onChange={(event) => set(destination.id, { weight: event.target.value })} /></label>
</li>)}</ul>
{invalid.length > 0 && <p className="nebula-form-help" role="alert">Poids : entier de 0 à 100.</p>}
<ApplyActions
busy={busy}
changed={changed}
onCancel={() => setDraft(initial())}
onApply={() => save((next) => destinations.forEach((destination) => { next.destinations[destination.id] = { active: draft[destination.id].active, weight: parse(draft[destination.id].weight) }; }))}
confirmTitle="Appliquer les destinations ?"
confirmMessage="Le changement vaut pour les prochains tirages : les destinations déjà proposées aujourd’hui restent jusqu’à minuit."
/>
</section>;
}
function ExpeditionsToday({ today, destinations, busy, onCancel }) {
const [cancelling, setCancelling] = useState(null);
const name = (id) => destinations.find((destination) => destination.id === id)?.name || id;
return <section className="nds-panel nebula-admin-shop nebula-admin-expedition-group" aria-labelledby="nebula-admin-expedition-today">
<div className="nds-section-heading nebula-admin-panel-heading"><h3 id="nebula-admin-expedition-today">Aujourd’hui</h3></div>
<p className="nebula-admin-guild-today"><strong>{today.launches}</strong> départ{today.launches > 1 ? "s" : ""} · <strong>{today.running}</strong> en route · <strong>{today.returnedUnclaimed}</strong> butin{today.returnedUnclaimed > 1 ? "s" : ""} à récupérer.</p>
{today.runningList.length > 0 && <ul className="nebula-admin-expedition-destinations">{today.runningList.map((expedition) => <li key={expedition.id} className="nds-list-row">
<strong>{name(expedition.destinationId)} · {"★".repeat(expedition.stars)}</strong>
<span>{expedition.creatorName} · retour le {DATE_FORMATTER.format(expedition.returnsAt)}</span>
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={() => setCancelling(expedition)}>Annuler</button>
</li>)}</ul>}
{cancelling && <ConfirmModal
title="Annuler cette expédition ?"
message={`L’expédition vers ${name(cancelling.destinationId)} de ${cancelling.creatorName} s’arrête : les cartes sont libérées, sans butin.`}
confirmLabel="Annuler l’expédition"
onClose={async (confirmed) => {
const target = cancelling;
setCancelling(null);
if (confirmed) await onCancel(target.id);
}}
/>}
</section>;
}
export function ExpeditionSettings({ dashboard, busy, runMutation, refreshDashboard }) {
const { settings, schema, destinations, updatedAt } = dashboard.expeditionSettings;
const save = async (apply) => {
const next = structuredClone(settings);
apply(next);
if (await runMutation(() => updateExpeditionSettings(next))) await refreshDashboard();
};
const cancel = async (id) => {
if (await runMutation(() => cancelExpedition(id))) await refreshDashboard();
};
return <div className="nebula-admin-expeditions" aria-labelledby="nebula-admin-expeditions-title">
<h2 id="nebula-admin-expeditions-title">Expéditions</h2>
<ExpeditionsToday today={dashboard.expeditionsToday} destinations={destinations} busy={busy} onCancel={cancel} />
{EXPEDITION_SETTING_GROUPS.map((group) => <SettingsGroup key={`${group.id}-${updatedAt}`} group={group} settings={settings} schema={schema} busy={busy} save={save} />)}
<DestinationSettings key={`destinations-${updatedAt}`} settings={settings} destinations={destinations} busy={busy} save={save} />
</div>;
}

View file

@ -0,0 +1,99 @@
// Rôle : libellés et regroupement des réglages des Expéditions pour l'administration et son historique.
// Les bornes viennent du schéma du serveur (tableau de bord) ; un test vérifie que chaque réglage du schéma a ici son libellé.
const STARS = ["1 ★", "2 ★", "3 ★", "4 ★", "5 ★"];
const STATS_IN_ORDER = ["principale", "2e stat", "3e stat", "4e stat"];
export const EXPEDITION_SETTING_GROUPS = [
{
id: "general",
title: "Général",
help: "Ouverture, destinations proposées chaque jour, durées et règles du solo.",
fields: [
{ path: "enabled", label: "Expéditions ouvertes aux joueurs" },
{ path: "day.destinationsPerDay", label: "Destinations proposées par jour" },
{ path: "day.avoidRepeatDays", label: "Jours avant qu’une destination revienne" },
{ path: "durations.hours", label: "Durées proposées (heures)", items: ["Courte", "Moyenne", "Longue"] },
{ path: "solo.cards", label: "Cartes en solo" },
{ path: "solo.maxConcurrent", label: "Expéditions solo en même temps" },
{ path: "solo.minStars", label: "Étoile minimale en solo" },
{ path: "solo.maxStars", label: "Étoile maximale en solo" }
]
},
{
id: "power",
title: "Puissance et rôles",
help: "Puissance de base de chaque rareté, gain par niveau et plafond commun ; multiplicateur du rôle d’une place.",
fields: [
{ path: "power.rare", label: "Puissance de base d’une rare" },
{ path: "power.epic", label: "Puissance de base d’une épique" },
{ path: "power.legendary", label: "Puissance de base d’une légendaire" },
{ path: "power.mythic", label: "Puissance de base d’une mythique" },
{ path: "power.perLevel", label: "Gain de Puissance par niveau" },
{ path: "power.cap", label: "Plafond de Puissance" },
{ path: "roles.multiplierPct", label: "Multiplicateur du rôle (%)" }
]
},
{
id: "requirements",
title: "Exigences",
help: "Exigence d’une stat par place : elle est multipliée par le nombre de places, plus les places dont le rôle double cette stat.",
fields: [
...STARS.map((stars, index) => ({ path: `requirements.star${index + 1}`, label: `Exigences par place en ${stars}`, items: STATS_IN_ORDER })),
{ path: "requirements.conditionMissPct", label: "Baisse du score si la condition de 3 ★ manque (%)" }
]
},
{
id: "score",
title: "Score, durée et dangers",
help: "Paliers, rendement au-delà de 100 %, malus des longues expéditions et des dangers, et ce que l’Endurance en efface.",
fields: [
{ path: "score.successPct", label: "Seuil de Réussite (%)" },
{ path: "score.triumphPct", label: "Seuil de Triomphe (%)" },
{ path: "score.capPct", label: "Plafond du score (%)" },
{ path: "score.mainWeight", label: "Poids de la stat principale" },
{ path: "score.otherWeight", label: "Poids des autres stats" },
{ path: "score.overflowPct", label: "Valeur d’un point au-delà de 100 % (%)" },
{ path: "score.overflowSpanPct", label: "Dépassement pris en compte (%)" },
{ path: "durations.malusPct", label: "Malus de durée (%)", items: ["Courte", "Moyenne", "Longue"] },
{ path: "durations.endurancePerSlot", label: "Endurance par place qui efface le malus de durée" },
{ path: "danger.malusPct", label: "Malus d’un danger (%)" },
{ path: "danger.shieldMaxPct", label: "Part du malus que l’Endurance peut effacer (%)" },
{ path: "danger.endurancePerSlot", label: "Endurance par place pour le bouclier complet" }
]
},
{
id: "loot",
title: "Butin",
help: "Butin par heure (proportionnel à la durée choisie), multiplié par la difficulté et le palier ; la Fortune n’améliore que la chance de paquet.",
fields: [
{ path: "loot.eclatsPerHourCents", label: "Éclats par heure (en centièmes : 200 = 2)" },
{ path: "loot.stardustPerHourCents", label: "Poussière par heure (en centièmes : 25 = 0,25)" },
{ path: "loot.packPerHourPermille", label: "Chance de paquet par heure (‰)" },
{ path: "loot.maxPacks", label: "Paquets au plus par expédition" },
{ path: "loot.difficultyPct", label: "Multiplicateur de difficulté (%)", items: STARS },
{ path: "loot.tierPct", label: "Multiplicateur du palier (%)", items: ["Retour difficile", "Réussite", "Triomphe"] },
{ path: "loot.fortunePerPointPct", label: "Bonus de paquet par point de Fortune par place (%)" },
{ path: "loot.fortuneCapPct", label: "Bonus de Fortune maximal (%)" },
{ path: "loot.bonusSlotPct", label: "Multiplicateur des destinations bonus (%)", items: ["5e destination", "6e destination"] }
]
}
];
const LABELS = new Map(EXPEDITION_SETTING_GROUPS.flatMap((group) => group.fields.map((field) => [field.path, field.label])));
// Libellé d'un réglage dans l'historique ; une destination se nomme par son nom.
export function expeditionSettingLabel(path, destinations = []) {
const destination = path.match(/^destinations\.([^.]+)\.(active|weight)$/);
if (destination) {
const name = destinations.find((item) => item.id === destination[1])?.name || destination[1];
return `${name} · ${destination[2] === "active" ? "proposée" : "poids"}`;
}
return LABELS.get(path) || path;
}
export function formatSettingValue(value) {
if (typeof value === "boolean") return value ? "oui" : "non";
if (Array.isArray(value)) return value.join(" / ");
return value ?? "—";
}

View file

@ -166,3 +166,28 @@ export function loadCampaignDetail(campaignId) {
export function extendCampaign(campaignId, expiresAt) { export function extendCampaign(campaignId, expiresAt) {
return request(`/admin/campaigns/${encodeURIComponent(campaignId)}/expiry`, { method: "PUT", body: JSON.stringify({ expiresAt }) }); return request(`/admin/campaigns/${encodeURIComponent(campaignId)}/expiry`, { method: "PUT", body: JSON.stringify({ expiresAt }) });
} }
export function loadExpeditions() {
return request("/expeditions");
}
// Aperçu exact d'une équipe : le palier ne dépend d'aucun tirage, seul le butin est arrondi au hasard au départ.
export function previewExpedition(body) {
return request("/expeditions/preview", { method: "POST", body: JSON.stringify(body) });
}
export function startExpedition(body) {
return request("/expeditions", { method: "POST", headers: { "Idempotency-Key": crypto.randomUUID() }, body: JSON.stringify(body) });
}
export function claimExpedition(expeditionId) {
return request(`/expeditions/${encodeURIComponent(expeditionId)}/claim`, { method: "POST" });
}
export function updateExpeditionSettings(settings) {
return request("/admin/expeditions/settings", { method: "PUT", body: JSON.stringify({ settings }) });
}
export function cancelExpedition(expeditionId) {
return request(`/admin/expeditions/${encodeURIComponent(expeditionId)}/cancel`, { method: "POST" });
}

View file

@ -0,0 +1,44 @@
// Rôle : règles d'affichage des Expéditions Sokko TCG (libellés des stats, rôles et paliers, conditions, statut de la tuile de Guilde).
import { fillTemplate, formatCountdown } from "./dailyShare.js";
export const STAT_IDS = ["bravoure", "endurance", "fortune", "orientation"];
export const formatEclats = (value) => Number(value).toLocaleString("fr-FR", { maximumFractionDigits: 1 });
export const formatDecimal = (value) => Number(value).toLocaleString("fr-FR", { maximumFractionDigits: 1 });
export function tagLabel(catalog, tagId) {
return catalog.expeditionTags?.find((tag) => tag.id === tagId)?.label || tagId;
}
// Condition de 3 ★ : une carte qui porte une étiquette, ou une carte d'une collection.
export function conditionText(condition, catalog, content) {
if (!condition) return "";
if (condition.type === "collection") return fillTemplate(content.conditionCollection, { collection: catalog.collections.find((item) => item.id === condition.collectionId)?.name || condition.collectionId });
return fillTemplate(content.conditionTag, { tag: tagLabel(catalog, condition.tag) });
}
export function dangerText(danger, catalog, content) {
return fillTemplate(content.dangerText, { label: danger.label, stat: content.stats[danger.stat], tags: danger.unlessTags.map((tag) => tagLabel(catalog, tag)).join(content.or) });
}
// Statut de la tuile Expéditions dans la Guilde (textes cards.guild).
export function expeditionQuestStatus(summary, content, now = Date.now()) {
if (!summary.enabled && !summary.running && !summary.returned) return content.expeditionsClosed;
if (summary.returned > 0 || (summary.nextReturnAt != null && summary.nextReturnAt <= now)) return content.expeditionsReturned;
if (summary.running) return fillTemplate(content.expeditionsRunning, { time: formatCountdown(summary.nextReturnAt - now) });
if (summary.eligible < summary.soloCards) return fillTemplate(content.expeditionsNoCards, { count: summary.soloCards });
return summary.launchedToday ? content.expeditionsIdle : content.expeditionsToLaunch;
}
// Édition de référence d'une carte (la standard), pour illustrer une destination.
export function coverEntry(catalog, cardId) {
const card = catalog.cards.find((item) => item.id === cardId);
const edition = catalog.editions.find((item) => item.cardId === cardId && item.rarity !== "mythic" && !item.promotional);
return card && edition ? { editionId: edition.id, edition, card } : null;
}
export function editionEntry(catalog, editionId) {
const edition = catalog.editions.find((item) => item.id === editionId);
const card = edition && catalog.cards.find((item) => item.id === edition.cardId);
return card ? { editionId, edition, card } : null;
}

View file

@ -1,10 +1,21 @@
// Rôle : recense les quêtes que la Guilde des Veilleurs propose au joueur et celles qui l'attendent. // Rôle : recense les quêtes que la Guilde des Veilleurs propose au joueur et celles qui l'attendent.
// La Carte du jour est la première ; chaque nouvelle quête (Expéditions…) s'ajoute à cette liste avec sa tuile dans GuildPanel. // Chaque quête (Carte du jour, Expéditions…) s'ajoute à cette liste avec sa tuile dans GuildPanel.
// Une quête : identifiant (qui choisit sa tuile), état du jour fourni par le serveur et `pending` tant qu'elle attend le joueur. // Expéditions en attente : un butin à récupérer, ou aucune expédition lancée aujourd'hui alors que le joueur a de quoi partir.
export function guildQuests(state) { // Au plus un rappel par jour, plus les retours ; un joueur sans cartes jouables n'est jamais sollicité.
export function expeditionsPending(summary, now = Date.now()) {
if (!summary) return false;
if (summary.returned > 0 || (summary.nextReturnAt != null && summary.nextReturnAt <= now)) return true;
return summary.enabled && !summary.running && !summary.launchedToday && summary.eligible >= summary.soloCards;
}
// Une quête : identifiant (qui choisit sa tuile), état fourni par le serveur et `pending` tant qu'elle attend le joueur.
// Les Expéditions n'apparaissent que si elles sont ouvertes, ou tant qu'une expédition du joueur n'est pas terminée.
export function guildQuests(state, now = Date.now()) {
const quests = []; const quests = [];
if (state.daily) quests.push({ id: "daily", pending: state.daily.status === "playing", summary: state.daily }); if (state.daily) quests.push({ id: "daily", pending: state.daily.status === "playing", summary: state.daily });
const expeditions = state.expeditions;
if (expeditions && (expeditions.enabled || expeditions.running || expeditions.returned)) quests.push({ id: "expeditions", pending: expeditionsPending(expeditions, now), summary: expeditions });
return quests; return quests;
} }

View file

@ -0,0 +1,79 @@
// Rôle : met en page les Expéditions de Sokko TCG (expéditions du joueur, destinations du jour, équipe par rôle, aperçu).
// Les composants restent ceux du design system (nds-panel, nds-card, nds-button, nds-badge, nds-inline-notice) ; ce fichier ne règle que la disposition.
.nebula-expeditions { display: grid; gap: var(--space-4); min-width: 0; }
.nebula-expeditions .nds-section-heading.nebula-section-heading { margin-bottom: 0; }
.nebula-expeditions > .nebula-form-help { margin: 0; }
.nebula-expeditions > .nds-inline-notice { margin: 0; }
.nebula-expeditions h3, .nebula-expeditions h4 { margin: 0; }
// Expéditions du joueur : une carte par expédition, couverture de la destination, équipe et butin.
.nebula-expedition-active { display: grid; gap: var(--space-3); }
.nebula-expedition-reports { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); gap: var(--space-4); }
.nds-card.nebula-expedition-report { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: var(--space-4); align-items: start; padding: var(--space-4); }
.nds-card-cover.nebula-expedition-report-cover { width: 88px; overflow: hidden; aspect-ratio: 1; border-radius: var(--radius-md); }
.nebula-expedition-report-cover img { display: block; width: 100%; height: 100%; object-fit: cover; }
.nds-card-body.nebula-expedition-report-body { display: grid; gap: var(--space-2); justify-items: start; min-width: 0; padding: 0; }
.nebula-expedition-report-body p { margin: 0; }
.nebula-expedition-report-status { color: var(--color-text-primary); font-weight: 700; }
.nebula-expedition-report-body .nds-card-actions { padding: 0; }
.nebula-expedition-report-team { display: flex; flex-wrap: wrap; gap: var(--space-3); margin: 0; padding: 0; list-style: none; }
.nebula-expedition-report-team li { display: grid; gap: var(--space-1); justify-items: center; color: var(--color-text-secondary); font-size: var(--font-size-xs); }
.nebula-expedition-rewards { display: flex; flex-wrap: wrap; gap: var(--space-2); }
// Préparation : quatre étapes empilées.
.nebula-expedition-plan-heading { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: var(--space-2) var(--space-4); }
.nebula-expedition-planner { display: grid; gap: var(--space-4); }
.nds-panel.nebula-expedition-step { display: grid; gap: var(--space-3); padding: var(--space-5); }
.nebula-expedition-step > .nebula-form-help, .nebula-expedition-step > .nds-inline-notice { margin: 0; }
.nebula-expedition-destinations { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr)); gap: var(--space-3); }
.nebula-expedition-destination { display: grid; grid-template-columns: 72px minmax(0, 1fr); gap: var(--space-3); align-items: start; padding: var(--space-3); border: 1px solid var(--color-border); border-radius: var(--radius-md); background: var(--color-bg-surface-alt); color: inherit; font: inherit; text-align: left; cursor: pointer; transition: border-color 160ms var(--ease-standard), background 160ms var(--ease-standard); }
.nebula-expedition-destination:hover { background: var(--color-bg-hover); }
.nebula-expedition-destination[aria-pressed="true"] { border-color: rgba(246, 196, 83, 0.54); background: rgba(246, 196, 83, 0.12); }
.nebula-expedition-destination img { width: 72px; aspect-ratio: 1; border-radius: var(--radius-sm); object-fit: cover; }
.nebula-expedition-destination-copy { display: grid; gap: var(--space-1); min-width: 0; }
.nebula-expedition-destination-copy > span:not(.nebula-expedition-destination-roles) { color: var(--color-text-secondary); font-size: var(--font-size-sm); text-wrap: pretty; }
.nebula-expedition-destination-roles { display: flex; flex-wrap: wrap; gap: var(--space-1); margin-top: var(--space-1); }
.nebula-expedition-choices { display: flex; flex-wrap: wrap; gap: var(--space-3); }
.nebula-expedition-requirements { display: grid; gap: var(--space-2); }
.nebula-expedition-requirements ul, .nebula-expedition-checks { display: grid; gap: var(--space-1); margin: 0; padding: 0; list-style: none; }
.nebula-expedition-requirements li, .nebula-expedition-checks li { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); padding: var(--space-2) var(--space-3); border-radius: var(--radius-sm); background: var(--color-bg-surface-alt); }
.nebula-expedition-requirements li > span { display: inline-flex; align-items: center; gap: var(--space-2); }
.nebula-expedition-requirements p { margin: 0; color: var(--color-text-secondary); font-size: var(--font-size-sm); }
.nebula-expedition-checks li[data-met] strong { color: var(--color-success); }
// Équipe : une place par rôle, puis les cartes jouables, triées pour la place choisie.
.nebula-expedition-slots { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); gap: var(--space-3); }
.nebula-expedition-slot { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-3); padding: var(--space-3); border: 1px solid var(--color-border); border-radius: var(--radius-md); }
.nebula-expedition-slot[data-active] { border-color: rgba(246, 196, 83, 0.54); }
.nebula-expedition-slot > span { flex: 1 1 120px; min-width: 0; color: var(--color-text-secondary); font-size: var(--font-size-sm); }
.nebula-expedition-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(132px, 1fr)); gap: var(--space-4) var(--space-3); max-height: 640px; margin: 0; padding: var(--space-1); overflow-y: auto; list-style: none; }
.nebula-expedition-cards li { display: grid; gap: var(--space-1); justify-items: center; text-align: center; }
.nebula-expedition-cards li[data-busy] { opacity: 0.55; }
.nebula-expedition-card-power { color: var(--color-text-primary); font-size: var(--font-size-xs); font-weight: 700; }
.nebula-expedition-stats { display: flex; flex-wrap: wrap; justify-content: center; gap: var(--space-1) var(--space-2); color: var(--color-text-muted); font-size: var(--font-size-xs); }
.nebula-expedition-preview { display: grid; gap: var(--space-3); }
.nebula-expedition-preview .nds-inline-notice { margin: 0; }
.nebula-expedition-expected { margin: 0; color: var(--color-text-primary); }
// Administration › Guilde : un panneau par groupe de réglages, des champs alignés en grille.
.nebula-admin-expeditions { display: grid; gap: var(--space-4); }
.nebula-admin-expeditions > h2 { margin: var(--space-4) 0 0; }
.nebula-admin-expedition-group > .nebula-form-help { margin: 0; }
.nebula-admin-expedition-fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr)); gap: var(--space-3) var(--space-4); }
.nebula-admin-expedition-field { display: grid; gap: var(--space-1); align-content: start; min-width: 0; margin: 0; padding: 0; border: 0; }
.nebula-admin-expedition-field > span, .nebula-admin-expedition-field > legend { color: var(--color-text-secondary); font-size: var(--font-size-sm); }
.nebula-admin-expedition-field > legend { margin-bottom: var(--space-1); padding: 0; }
.nebula-admin-expedition-field > .nds-button { justify-self: start; }
.nebula-admin-expedition-items { display: flex; flex-wrap: wrap; gap: var(--space-2); }
.nebula-admin-expedition-items label { display: grid; flex: 1 1 72px; gap: 2px; min-width: 64px; color: var(--color-text-muted); font-size: var(--font-size-xs); }
.nebula-admin-expedition-destinations { display: grid; gap: var(--space-2); margin: 0; padding: 0; list-style: none; }
.nebula-admin-expedition-destinations .nds-list-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-4); padding: var(--space-3); }
.nebula-admin-expedition-destinations .nds-list-row > strong { display: inline-flex; flex: 1 1 200px; align-items: center; gap: var(--space-2); }
.nebula-admin-expedition-destinations .nds-list-row > span { flex: 1 1 200px; color: var(--color-text-secondary); font-size: var(--font-size-sm); }
.nebula-admin-expedition-destinations label { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--color-text-secondary); font-size: var(--font-size-sm); }
.nebula-admin-expedition-destinations input { width: 80px; }
.nebula-admin-expedition-destinations .nds-list-row > .nds-button { flex: 0 0 auto; width: auto; }

View file

@ -14,6 +14,7 @@
@use "diablo4"; @use "diablo4";
@use "aniimo"; @use "aniimo";
@use "nebula-cards"; @use "nebula-cards";
@use "nebula-expeditions";
@use "games/checklist"; @use "games/checklist";
@use "design-system/attributes"; @use "design-system/attributes";
@use "responsive"; @use "responsive";