diff --git a/.env.example b/.env.example index e37b69d..9ebbf29 100644 --- a/.env.example +++ b/.env.example @@ -1 +1,13 @@ PORT=5173 + +# Sokko TCG reste désactivé en production tant que ces valeurs ne sont pas configurées. +CARDS_ENABLED=false +CARDS_DB_PATH=/var/lib/sokko-g/nebula-cards.sqlite +# La recharge des ouvertures, l'ouverture des paquets et les taux de tirage se règlent depuis l'administration. +CARDS_PUBLIC_ORIGIN=https://sokkog.example.com +DISCORD_CLIENT_ID= +DISCORD_CLIENT_SECRET= +DISCORD_REDIRECT_URI=https://sokkog.example.com/api/cards/auth/callback +CARDS_ADMIN_DISCORD_IDS= +# Ne jamais activer cette connexion factice en production : elle accorde les droits administrateur. +CARDS_DEV_AUTH=false diff --git a/DESIGN_SYSTEM.md b/DESIGN_SYSTEM.md index 9c9b120..2a9ff61 100644 --- a/DESIGN_SYSTEM.md +++ b/DESIGN_SYSTEM.md @@ -192,6 +192,13 @@ Les surfaces de cards reutilisent les mixins `card-surface`, `card-surface-hover Eviter les cards dans des cards. Les sections de page doivent rester des layouts ou panneaux, pas des empilements de cartes decoratives. +Les cartes de jeu Sokko TCG conservent leur ratio `5:7` et exposent trois formats metier : + +- `sm` sur l'accueil : illustration et symbole de rarete uniquement ; +- `md` dans l'album : illustration puis bandeau de nom fixe en bas ; le fond de carte aux nuages diffus reste visible dans ce bandeau, le titre compact est centre horizontalement et verticalement sur toute sa largeur, et le symbole de rarete de 13 px est superpose dans son angle inferieur droit ; la quantite reste superposee en haut de l'illustration ; +- `lg` pendant une ouverture et dans le detail : le gabarit `standard` utilise un meme fond de carte compose de nuages diffus teintes par la rarete sous le nom centre dans son bandeau et la description, autour d'une illustration encadree et en retrait sur les cotes ; la quantite d'inventaire n'est jamais superposee sur ce format ; +- le format mythique `full-art` etend l'illustration a toute la surface sans modifier les tailles `sm`, `md` et `lg`. + ## 8. Modules Toolbox Les modules sont des panneaux de travail, pas des cards classiques. @@ -421,6 +428,7 @@ Regles : - conserver un trigger compact, idealement icone seule avec tooltip ; - fermer au clic exterieur, a `Escape`, a la selection et quand le focus sort du menu ; +- `autoPlace` garde le menu entierement visible : decalage horizontal pres des bords, ouverture vers le haut s'il manque de place en bas, hauteur limitee avec defilement en dernier recours ; il prend en compte la fenetre, la barre superieure et les ancetres qui coupent leur contenu (`SelectDropdown`, `SwatchDropdown` et `GameFilterDropdown` l'activent) ; - garder le contenu interne libre pour supporter grilles d'icones, swatches, libelles de categories ou choix d'epaisseur ; - reutiliser les classes visuelles existantes du contexte quand le menu appartient a un outil precis. @@ -735,6 +743,14 @@ Selects : - fond sombre Nebula force via `background-color`, hover/focus violet avec chevron dore ; - focus visible global dore conserve. +Groupes de boutons radio (`nds-radio-button-group`) : en tailles `sm` et `xs`, une option de texte garde 8 px et 6 px de marge intérieure ; une option avec icône conserve son padding nul. + +Sélecteur à choix unique (`SelectDropdown`, `website/src/components/SelectDropdown.jsx`) : + +- à préférer au `` ni `datetime-local` : un test le vérifie ; ses infobulles passent par `Tooltip`, ses dates d'expiration par `MonthDateDropdown` et `nds-time`, la quantité d'un paquet par `nds-quantity-stepper`. Ses barres de filtres suivent `horizontal-menu` comme les jeux (`GameFilterDropdown`, `ActiveFilterBadges`, gomme). + Select triggers : - utiliser `select-trigger` pour les boutons qui ouvrent une liste, un picker ou un calendrier avec le langage visuel d'un select ; @@ -1019,3 +1035,386 @@ Minimum attendu : - scroll horizontal sur les tableaux de donnees critiques. Les chips `nds-chip[data-size="sm"]` utilisent une hauteur minimale de 30 px, un padding de 4 × 8 px, une police `xs` et des icônes/images de 16 px. Le catalogue interactif expose cette taille à côté de la taille par défaut. + +## 22. Sokko TCG + +Les cartes collectionnables utilisent un ratio vertical `5 / 7`. Le gabarit +`standard` applique un fond de nuages diffus teintes selon la rarete. En `lg`, +ce fond reste continu sous le nom limite a deux lignes et la description, tandis +que l'illustration est encadree et en retrait sur les cotes. En `md`, il reste +visible uniquement dans le bandeau de nom sous l'illustration. Le symbole de +rarete y est plus petit, superpose dans l'angle inferieur droit pour laisser les +noms longs utiliser toute la largeur, et conserve son libelle accessible. Dans +la liste des paquets, le dos de collection utilise également la largeur `md` de +180 px. Les +noms sont centres horizontalement et verticalement dans leur bandeau fixe en +`md` comme en `lg`, tout en restant limites a deux lignes. Le verso est propre à +chaque collection, utilise son image WebP 5:7 et superpose uniquement le nom de +la collection dans la zone calme inférieure, avec une position proportionnelle +identique quelle que soit la taille du dos. Dans l'album, les éditions non +découvertes conservent ce verso avec une légère désaturation et une luminosité +réduite pour matérialiser leur état indisponible. + +Le format mythique « Pleine illustration » (`cardFormats`, indépendant de l'effet et de la palette) affiche `card.fullImage` sur toute la carte, au ratio 5:7 : plus de description ni de finition, seul le nom reste en bas, en dégradé doré façon gravure métallique, sur un voile sombre. L'éditeur et l'Atelier visuel masquent le choix du format pour une carte sans cette image (`__full.webp`). + +La modale de detail utilise une largeur maximale de 1040 px sans defilement +horizontal. La quantite possedee y figure dans les metadonnees, hors de la carte +`lg`; elle reste superposee a l'illustration uniquement dans les apercus `md` de +l'album. + +L'administration est un tableau de bord reserve aux comptes administrateurs sur +la route dédiée `/#/cards/admin`, distincte du parcours joueur `/#/cards`. Le lien +Administration du parcours joueur ouvre cette route. Le hero du jeu n'y est pas +affiché : un en-tête compact `nds-panel` le remplace, avec à gauche l'icône TCG, +« Sokko TCG · Administration », le titre `h1` « Tableau de bord Sokko TCG » et +une ligne discrète « Données mises à jour … » suivie d'un bouton `nds-button` `xs` secondaire « Actualiser » ; à droite, séparés +par un filet, le joueur connecté et « Déconnexion ». Le lien « Administration » +du parcours joueur et « Retour au jeu » de l'administration sont placés au-dessus +du menu latéral collant. La section « Historique » liste les actions +d'administration avec leur auteur et leur détail lisible. En +demi-écran, le bloc joueur passe sous le titre, sans filet. Les contrôles du TCG utilisent exclusivement les composants NDS : les actions +secondaires (Fermer, Annuler, Détails, Voir, Copier le code, Déconnexion…) sont des +`nds-button` `secondary` bordés, jamais `ghost` (réservé aux handles discrets) ; +l'ajout d'une variation mythique utilise la variante `dashed`. Les en-têtes de section utilisent `nds-section-heading`, les rangées d'actions +`nds-toolbar`, les barres de recherche/tri (catalogue, joueurs, sélecteur de cartes) +`nds-filter-panel` `horizontal-compact`, les points d'attention `nds-inline-notice`, les +lignes de liste (derniers tirages, campagnes en cours, cartes cochées) `nds-list-row` et +l'état vide de la récompense `nds-empty-state`. Les classes `nebula-*` ne portent plus +que la mise en page ; elles sont préfixées par la classe NDS (`.nds-section-heading.nebula-…`) +car les attributs NDS sont chargés après `_nebula-cards.scss`. Le tableau de bord est organisé en cinq +sections adressables (`/#/cards/admin/
`), dans une navigation par liens +avec `aria-current="page"`, sans intitulés de groupe : Vue d'ensemble +(`overview`), Collections (`collections`), Codes cadeaux (`codes`) et Boutique +(`shop`), 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 +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 +moins 960 px (container query `nebula-dashboard`), la navigation devient une colonne +de 200 px collante ; en demi-écran, elle reste une rangée unique sans défilement +horizontal ; pour que les entrées y tiennent, les liens utilisent 12,8 px de +texte et 5 px de marge latérale (14 px et 12 px dans la colonne large). + +La vue d'ensemble commence par « Points d'attention » (campagne qui expire sous +72 h, collection active sans mythique tirable, aucun paquet ouvert, variations +retirées), sur une seule ligne avec une coche verte quand il n'y a « Rien à +signaler ». Viennent ensuite trois chiffres clés, chacun avec un intitulé, la +valeur en or et une ligne de contexte : « Joueurs » (actifs sur 7 jours), +« Collections actives » (sur le total) et « Cartes différentes » (variations du +catalogue publié hors mythiques retirées, dont les variantes mythiques). + +Dessous, le tableau des joueurs, dans un `nds-panel`, avec un tri compact sur la +ligne du titre (pas de recherche : une dizaine de joueurs) : Joueur (identité +publique, admin, inscription), Paquets (ouverts, puis paquets offerts ou achetés +en attente), Dernier (paquet ouvert, date relative), Cartes (total et cartes +rares), Échanges (dons et échanges terminés), Réserve (« 2 / 5 » et prochaine +recharge) et Poussière (poussière d'étoiles). Les dates récentes sont relatives +et courtes (« à l'instant », « il y a 5 min », « dans 1 h ») avec la date +complète en infobulle. En demi-écran le tableau défile horizontalement dans son +panneau s'il ne tient pas. L'identifiant Discord n'est jamais exposé. + +La Boutique (`/#/cards/admin/shop`) affiche la poussière en circulation et les +ouvertures achetées non utilisées, puis deux panneaux indépendants, chacun avec son +« Appliquer » (confirmation, effet immédiat) et son brouillon. « Recyclage des +doublons » : un champ par rareté (poussière gagnée par doublon recyclé, entier de 0 +à 100 000, liseré à la couleur de la rareté). « Articles de la boutique » : les +articles en `nds-card` avec les illustrations de la boutique des joueurs +(`ShopPackCover`, `ShopOpeningCover`), leur prix (entier de 1 à 100 000) et, pour +le paquet, la part de ses cartes ; un repère indique combien de doublons communs +valent une ouverture. + +L'espace joueur partage le cadre de l'administration (`CardsDashboard.jsx`, +classes `nebula-dashboard*`) : même menu de sections par liens avec +`aria-current="page"`, même bloc compte et mêmes chiffres clés. Il s'ouvre sur le +hero commun `nds-page-hero` des autres pages, avec le compte à droite ; le texte +et le compte s'empilent quand le tableau de bord fait moins de 900 px. Les +sections sont adressables (`/#/cards` pour l'Accueil, puis `/#/cards/
`) +et groupées par filets : Accueil, Paquets (`packs`), Collection (`collection`) ; +Boutique (`shop`), Échanges et dons (`transfers`) ; +Historique (`history`). Le hero et le menu disparaissent pendant l'ouverture d'un +paquet, qui garde toute la largeur. + +Sur l'Accueil, la réserve d'ouvertures occupe un tiers de la largeur (230 px minimum) et +le meilleur tirage les deux tiers ; les deux s'empilent sous 560 px. La carte la +plus rare, en taille `md`, ouvre la même fiche détaillée que l'album de la Collection. Cet album regroupe les +cartes par collection, chaque groupe sous un simple titre avec de l'espace au-dessus et un `nds-badge` +« éditions différentes possédées / total », indépendant des filtres ; un groupe +sans carte correspondant aux filtres est masqué. +Les six chiffres clés tiennent sur une ligne, ou sur deux lignes de trois quand le +tableau de bord fait moins de 720 px. + +Une collection `shop` (Poussières d'étoiles) n'apparaît jamais dans Paquets : son article de Boutique, illustré par son dos, s'achète en poussière et mène directement à la révélation. La section Boutique affiche son solde de poussière sous le menu, puis une grille de `nds-card` illustrées d'au moins 230 px : +illustration WebP entière dans `nds-card-cover` (`static/img/cards/shop/`), nom, courte +description, prix et « Acheter », poussière manquante. + +Une section peut placer un encart sous le menu (`DashboardAside`, côté joueur) : il colle avec le +menu dans la colonne de 200 px et devient un bandeau sous le menu horizontal en demi-écran. Paquets y +met la réserve d'ouvertures puis les ouvertures achetées (nombre et rappel de priorité), la Boutique le solde de poussière ; l'Accueil garde sa propre réserve. + +La Collection s'ouvre sur l'en-tête de section « Mes cartes / Ma collection ». Son panneau de filtres se termine par le bouton gomme `nds-filter-reset`, qui remet la recherche et tous les filtres à zéro. Chaque collection de l'album a sous son titre un rail `nds-progress` `sm`, ses cartes découvertes étant +dans l'infobulle du badge. Une collection temporaire (`event`) fermée dont le joueur ne possède aucune +carte disparaît de toute la page ; une collection permanente fermée reste affichée. + +Le recyclage vit dans la Collection (`/#/cards/recycling` y mène) : quand des doublons sont +recyclables, l'encart sous le menu montre le solde, le nombre de doublons et le gain, « Tout recycler » +et « Voir les doublons » (active le filtre Possession). La confirmation de « Tout recycler » affiche le barème par rareté. Le recyclage carte par carte se fait depuis +la fiche d'une carte. « Tout recycler » est suspendu tant qu'une ouverture attend d'être révélée. Échanges et dons s'ouvre sur « À traiter » (Accepter, Refuser), « Envoyées » (temps restant, +Annuler) et « Terminées », repliées, avec les vraies cartes et leur rareté ; un `nds-badge` doré +compte dans le menu les propositions à traiter. « Faire un don » et « Proposer un échange » ouvrent une +même modale : joueur, doublon donné puis, pour un échange, doublon voulu, ceux qui manquent d'abord. +Un don est immédiat ; la fiche d'une carte en double y mène avec « Donner » et « Échanger ». Dans Historique, +une ouverture liste ses cartes en simples références textuelles (`nds-badge` : +pastille à la couleur de la rareté, avec son nom en infobulle et pour les lecteurs +d'écran, nom de la carte, finition hors standard) ; tant qu'elle n'est pas révélée, elle affiche +« Cartes à révéler » pour ne rien dévoiler. Échanges, dons et recyclage ne +concernent que les doublons : un exemplaire de chaque variation est toujours +conservé. Le formulaire d'échange ne liste que les doublons, une option par +carte avec leur nombre. Les doublons réservés par un échange en cours ne sont +pas recyclés. La fiche d'une carte en double propose « Recycler un +doublon (+N poussières) ». Dans la section Paquets, les paquets offerts s'affichent sous « Utiliser un code » et les +ouvertures achetées sous la réserve : elles ne comptent pas dans le plafond de la réserve et ne se +rechargent pas. + +Chaque type de paquets a sa section `nds-panel` : « Paquets permanents » et « Paquets +événements » sont côte à côte, empilées quand le tableau de bord fait moins de 500 px ; +« Paquets offerts » reste au-dessus, sur toute la largeur. Chaque paquet est un bouton +de 180 px sans conteneur, entièrement cliquable : le dos `md` et la description de la +collection, et c'est tout (un paquet offert affiche le nom de la campagne et sa garantie). +Le survol illumine uniquement le dos en or, sans fond de bouton derrière le texte. La +description, en petite taille dans un conteneur très peu contrasté, se limite à trois lignes : le texte complet reste en infobulle. Le clic ouvre le paquet sans +confirmation, sur la réserve d'abord, puis sur une ouverture achetée ; les tuiles sont +désactivées quand il ne reste ni l'une ni l'autre. L'étape d'ouverture garde le hero, +masque le menu et affiche les trois cartes au format `lg` (300 x 420 px, réduites +seulement si la largeur manque), puis un `nds-panel` compact « Probabilités » +(les taux et la garantie du paquet offert s'il y en a). « Retour » ramène à la liste +une fois toutes les cartes révélées. + +Chaque collection fournit un dos illustré WebP au ratio 5:7 sous +`static/img/cards//back.webp`; le composant conserve le nom en +surimpression et un fallback graphique piloté par le catalogue. La section +Collections a deux niveaux, puisque chaque collection est un paquet. +`/#/cards/admin/collections` affiche d'abord le panneau commun « Recharge des +ouvertures » (`aside`) : délai en vigueur (« 1 ouverture toutes les heures · +réserve de 5 »), un seul champ « Délai en minutes » (1 à 10 080), « Appliquer » +avec confirmation et, sous le champ, un aperçu en direct (durée lisible, +ouvertures par jour, temps pour remplir une réserve vide). Suit une tuile-lien +par collection : dos du paquet au format `md` (180 px, 140 px sous 900 px de tableau +de bord), badges de catégorie et de disponibilité alignés en tête, nom, trois +compteurs (cartes, variations, mythiques tirables) et la répartition des +variations par rareté, puis « Voir la collection → ». Chaque tuile ouvre la page +de la collection, `/#/cards/admin/collections/`, précédée d'un fil +d'Ariane « Collections › Collection ». Cette page empile : + +- l'en-tête de la collection (dos, badges « Ouverte » / « Fermée », nom système, + description, volumes) avec, à droite des badges, l'interrupteur `nds-switch` + (`aria-pressed`) « Ouvert / Fermé aux joueurs » ; fermer un paquet passe par + une confirmation, l'ouvrir exige des taux de tirage ; +- « Taux de tirage » (`nds-panel`) : chaque rareté avec son poids (champ + entier), sa chance par carte tirée (et « avant X % » pendant une + modification), le nombre de variations tirables et la chance d'obtenir une + variation précise ; un poids non nul sans carte tirable est signalé. + « Appliquer » ouvre une confirmation récapitulant les nouveaux pourcentages ; + les taux ne sont pas versionnés et s'appliquent immédiatement. « Taux + recommandés » préremplit le tableau avec les poids recommandés du catalogue, + sans rien enregistrer ; +- « Ouverture mythique de la collection » : à partir de 1100 px de tableau de + bord, à droite de « Taux de tirage » en deux colonnes égales (50:50), alignées + en haut et étirées à la même hauteur. L'aperçu (carte `md` de 180 px) est + au-dessus des réglages, et les deux menus sont côte à côte ; la valeur héritée + porte le suffixe court « (défaut) » pour tenir dans un menu de 140 px de texte + à 1440 px. Les boutons des taux descendent en bas de leur panneau, alignés sur + les menus, de sorte que l'écart éventuel se loge entre le tableau et les + boutons. Le + tableau des taux y devient + compact (en-têtes courts « Par carte », « Tirables », « Variation » avec + l'intitulé complet en infobulle, champ de poids de 56 px) et défile + horizontalement s'il ne tient pas. En dessous de 1100 px, sous les taux, en + pleine largeur, avec à gauche une carte mythique de la + collection au format `md` (180 px), face cachée, pour jouer l'ouverture ; à + droite, les menus de forme puis de palette de particules empilés, enregistrés + à chaque changement. Le panneau laisse déborder l'aura et les particules + au-dessus des blocs voisins ; la zone principale coupe seulement le + débordement horizontal (`main:has(.nebula-dashboard)`, + `overflow-x: clip`) pour que l'animation n'élargisse jamais la page ; +- « Versions mythiques » : une grille des légendaires au format `md` (180 px), + avec pour seul repère le nombre de mythiques tirables sous la carte (« 2 + mythiques » en cyan, « Aucune mythique » atténué) ; cliquer sur une carte la sélectionne (fond et contour + cyan, `aria-pressed`) et ouvre sous la grille, en pleine largeur, le panneau + « Version mythique · Nom » avec « Fermer » ; la page défile jusqu'à lui. Le + panneau contient d'abord « Ouverture mythique de la carte » : à gauche la + carte d'aperçu `md` (180 px) face cachée (avec le nom de la variation prévisualisée), à + droite les menus de forme et de palette empilés. En dessous, « Variations + mythiques » présente une tuile par variation avec sa carte `sm` cliquable, qui + la sélectionne pour l'aperçu. Il n'y a pas de bouton « Enregistrer » global : + chaque action est enregistrée aussitôt, une variation à la fois. Les menus + d'ouverture de la carte s'enregistrent à chaque changement. Une variation + enregistrée est en lecture seule : nom de la palette, pastilles, liste + « Effet / Particules », statut « Tirable », « Possédée par N joueurs » et « N campagnes » ; en + tête, collé à droite, un `nds-icon-button` `data-size="sm"` + `data-variant="danger"` avec l'icône corbeille ouvre une confirmation + (`ConfirmModal`) pour « Supprimer » la variation, ou la « Retirer des + tirages » si elle est possédée ou citée par une campagne ; la confirmation signale aussi une collection + qui n'aurait plus de mythique tirable. « + Ajouter une variation » crée une + seule variation en cours (badge « Nouvelle ») et disparaît jusqu'à sa + validation ou son annulation. Cette variation propose trois menus compacts, + intitulé court et champ sur la même ligne : « Effet », « Palette » et + « Particules » (désactivé), dont les noms accessibles restent « Effet + holographique » et « Palette holographique ». En tête, une coche + (`nds-icon-button` `data-variant="primary"`, icône `ui-icon-check`) valide et + enregistre la variation, désactivée si la combinaison existe déjà (message + « Cette combinaison existe déjà. ») ; la corbeille à sa droite annule la + création. Les variations retirées peuvent être réactivées d'un clic ; +- « Cartes de la collection » : cartes `sm` filtrables par texte, rareté et + statut (retirées, promotionnelles). La tuile affiche le nom et le libellé + rareté + finition, qui passe à la ligne au lieu d'être tronqué ; + l'identifiant d'édition n'apparaît que dans la fiche détail. La modale de détail affiche la variation + au format `lg` et propose « Configurer la version mythique », qui ferme la + modale et déplie la légendaire correspondante. + +Les menus d'ouverture mythique ne listent chaque valeur qu'une fois : la valeur +héritée porte sa provenance entre parenthèses (« Étincelles (défaut) », +« Flocons de neige (hérité de la collection) ») et la choisir revient à suivre le +niveau supérieur ; une valeur enregistrée identique à la valeur héritée +s'affiche comme héritée. + +La grille des variations compte au plus trois colonnes (au moins un tiers de +la largeur ou 190 px par tuile) : trois par ligne en plein écran comme en +demi-écran. Chaque tuile est un conteneur (`nebula-variation`) : à partir de +280 px utiles (grands écrans), le texte se place à droite de la carte `sm` ; en dessous, carte centrée +puis en-tête, pastilles, liste et statut. Dans tout le tableau de bord, une +carte ou un panneau qui contient un menu de palette ouvert laisse déborder ce +menu et passe au-dessus de ses voisins (`:has(.nebula-admin-palette-dropdown.is-open)`). + +L'Atelier visuel regroupe deux bancs d'essai distincts. La section « Effets +holographiques mythiques », en premier, affiche une carte `lg` (300 x 420 px) de « La Pioche +Mythique » par effet holographique, y compris ceux qu'aucune édition n'utilise +encore, avec le menu de palette de sept couleurs et un menu « Particules au +survol » désactivé, réservé au réglage à venir. La section « Effets d'ouverture » suit avec +une carte face cachée par rareté, la Mythique en tête : seule sur sa ligne, +limitée à 760 px et centrée, aperçu à gauche et menus de forme puis de palette +de particules empilés (dont « Comme la palette holo »), puis Rare, Épique et Légendaire partagent une ligne de trois colonnes à +partir de 1000 px de tableau de bord (deux colonnes en demi-écran). Chaque carte +rejoue l'ouverture joueur et peut être retournée après l'animation. Rien n'y est +enregistré : les associations réelles se règlent dans Cartes. + +La page Codes cadeaux (`/#/cards/admin/codes`) montre d'abord la liste : +titre « Campagnes » avec leur nombre et, à droite, le bouton principal +« + Nouvelle campagne ». Ce bouton ouvre le formulaire entre le titre et la +liste ; « Annuler » le referme, et il se referme seul après la création. Une +campagne a un seul code lisible, à annoncer (stream, Discord), que chaque joueur +utilise une fois. Le formulaire « Nouvelle campagne » suit trois étapes numérotées : + +1. « La campagne » : + - le nom (visible par les joueurs), puis le « Code à annoncer » juste en + dessous (560 px de large au plus), avec à sa droite un bouton « Générer » + qui propose un code aléatoire « XXXX-XXXX » sans caractères ambigus ; le + code passe en majuscules, les espaces deviennent des tirets ; + - les cases « Sans limite d’utilisations » et « Sans date + d’expiration », cochées par défaut ; décocher une case fait apparaître son + champ juste à côté (« Utilisations maximum », « Valable jusqu’au »). Le + détail d'une campagne permet aussi de changer ou de retirer son échéance. +2. « Ce que reçoit le joueur » : vide au départ (encart pointillé « Rien pour + l’instant »), avec les boutons « + Ajouter des cartes » et « + Ajouter un + paquet » ; le formulaire revient à cet état après la création d'une campagne. + - « Cartes offertes » (`nds-card`, ouvert par « + Ajouter des cartes », retiré + avec sa corbeille qui décoche tout) : un sélecteur « Collection affichée » + puis la grille visuelle « Cartes à offrir » : variations en `sm` (96 px), + grille défilante de 380 px au plus, filtrable par rareté (« Toutes » ou une + rareté) et par nom. Un clic coche ou décoche une carte (`aria-pressed`, + contour or et pastille or avec l'icône `check`) ; les cartes cochées restent + cochées quand on change de collection. Le compteur « N cartes cochées » s'affiche en or à côté de l'intitulé. Sous la grille, la liste + « Cartes cochées » donne pour chaque carte son nom, sa collection et une corbeille (`nds-icon-button` `danger`) pour la + décocher. Toutes les cartes offertes s'échangent comme les autres. + - Paquets : jusqu'à 10 paquets ajoutés un par un avec « + Ajouter + un paquet ». Chaque paquet est une carte groupée `nds-card` (« Paquet 1 »…) + avec une quantité de 1 à 10, une corbeille, sa collection, les taux « Ceux + du paquet » ou « Personnalisés » (poids par rareté, pourcentage en direct, + bouton « Taux recommandés ») et une garantie : « Aucune », « Une rareté + minimum » (au moins 1 à 3 cartes de la rareté choisie ou mieux) ou « Une + carte précise » de la collection, choisie avec la même grille en sélection + unique. +3. « Récapitulatif » : une phrase décrit la récompense, le code, la limite et + l'échéance ; s'il manque quelque chose, un `nds-inline-notice` `warning` le liste + au-dessus du bouton « Créer la campagne ». + +Après création, une confirmation compacte sur une ligne (coche verte, « Campagne +« … » créée », code en or) propose « Copier le code » et « Fermer ». La liste +des campagnes affiche pour chacune la récompense (résumée au-delà de trois +éléments), le code, les dates, les utilisations, le statut (Active, Épuisée, +Expirée, Révoquée), « Détails », « Copier le code » et « Révoquer » (avec +confirmation). Le +détail donne la récompense complète, le changement ou le retrait de l'échéance +et la liste des joueurs qui ont utilisé le code, avec la date. + +Côté joueur, la section Paquets commence par « Utiliser un code ». Une carte +arrive directement dans la collection ; un paquet rejoint « Paquets offerts », +qui s'ouvre sans consommer d'ouverture, même si la collection est fermée. Sa +garantie figure sur sa tuile, ses taux personnalisés à l'étape d'ouverture. + +L'écran de connexion présente l'illustration `login.webp`, décorative et carrée, +avec « Trading Card Game » et « Sokko TCG ». L'action +Discord utilise le blurple `#5865f2`, le pictogramme Discord et un libellé +explicite ; sans identifiants Discord sur le serveur, un avis `warning` le remplace. +Un retour Discord annulé, expiré ou échoué affiche un avis `danger` sur cet écran. +Le bouton secondaire « Version développement » n'est rendu que si le +serveur expose l'authentification de développement ; cette session possède les +droits administrateur et ne doit jamais être proposée en production. + +La rareté est exprimée simultanément par couleur, texte et symbole céleste : +astre gris pour Commun, étoile bleu franc à quatre branches pour Rare, étoile violet-magenta +saturé à six branches pour Épique, étoile dorée avec anneau pour Légendaire et étoile +cyan avec deux orbites pour Mythique. Cette dernière rareté combine une base +cyan lumineuse avec des ombres magenta irisées, afin de rester distincte du gris Commun +et de dépasser visuellement l'or Légendaire. Les finitions mythiques restent +nommées en texte même lorsque leurs placeholders partagent cette identité. + +L'ouverture affiche trois cartes retournables. Les Communes utilisent uniquement +le retournement standard. Rare charge une aura bleue, Épique ajoute une gerbe +d’étincelles violet-magenta et Légendaire combine une aura dorée plus intense avec +une explosion dense de particules plus largement dispersées. Mythique utilise un +effet propre à la collection : aura cyan irisée et étincelles arc-en-ciel. Une +configuration d'ouverture associe indépendamment une forme et une palette de +particules, afin de pouvoir ajouter plus tard étoiles ou flocons sans modifier le +simulateur. Ces effets de rareté sont distincts des finitions et +leur fin observable précède l'affichage du résumé d'ouverture. Sur +un pointeur fin, les cartes suivent la position du pointeur avec un tilt contenu +à environ cinq degrés et un reflet localisé. Le preset **Reflet diffractif** +n'a aucune animation automatique : sa teinte dépend de l'angle de la carte, une +bande de lumière suit le pointeur, des rayons fins pivotent autour de lui et son +intensité croît avec l'inclinaison (`--card-tilt-energy`). Le preset holographique **Prisme +spectral** superpose un spectre oblique animé et une grille irisée fine, avec un +mélange `color-dodge`, sans passer devant les aplats protégeant le nom et la +description. Son opacité et sa saturation restent volontairement modérées pour +préserver les couleurs de la carte. Le fond de description reste sous le spectre +tandis que son texte reste au-dessus : l'effet traverse ainsi toute la carte sans +coupure horizontale. +Le gradient surdimensionné se déplace uniquement de `0 %` à `100 %`, sans +répétition visible. Les couleurs de la palette sont répétées et espacées +automatiquement, sans paliers explicites, afin de conserver des bandes régulières +et des transitions continues. Une marge interactive discrète absorbe le +débordement du tilt aux bords. Ses couleurs viennent de palettes éditoriales de +sept teintes : +**Arc-en-ciel** (les sept couleurs du spectre) ouvre la liste, suivie des palettes +chaudes puis froides : **Solaire** (blancs chauds, jaunes et oranges), +**Crépuscule** (du bleu nuit à l'or de l'horizon), **Cramoisi** (rouges profonds à +vifs), **Nature** (verts de la forêt à la jeune pousse), **Aurore** (verts et +turquoises de l'aurore boréale, frange violette), **Hiver** (blancs et bleus +glacés), **Cosmique** (indigos, violets, magentas et cyans de nébuleuse) et +**Ténèbres** (noirs et violets sombres, une seule teinte claire). Toutes utilisent +le même CSS, sauf Ténèbres qui passe en `hard-light` à 62 % au survol : `color-dodge` +n'aurait aucun effet avec des teintes presque noires, alors que ce mode assombrit +réellement la carte. +De nouvelles variantes s'ajoutent dans le catalogue sans dupliquer le composant. Une finition associe trois références indépendantes : +un preset d'effet holographique, une palette et un preset de particules. Les deux +couches holographiques rendues par la carte sont génériques puis spécialisées en +CSS via `data-holo-effect`; les particules suivent le même principe via +`data-particle-preset`. Un nouvel effet peut ainsi réutiliser toutes les palettes +et tous les presets de particules existants. Le focus +clavier applique une inclinaison fixe légère. Les contrôles restent de vrais +boutons utilisables au clavier et « Tout révéler » offre une alternative directe. +Sous `prefers-reduced-motion: reduce`, le tilt, le mouvement du prisme, le flip +animé, les particules et les transitions non essentielles sont supprimés ; la +finition holographique reste visible sous une forme statique (le Reflet diffractif +aussi sur écran tactile, faute de tilt) et la révélation se +termine immédiatement. Les pages +Paquets, Collection, Échanges, Historique et Administration partagent les panels, +chips et focus du NDS et sont validées sans débordement à partir de 768 px. diff --git a/README.md b/README.md index f7a7bc7..d3eb7c9 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,11 @@ # Sokko G -Webapp React locale pour préparer et accompagner des sessions gaming sur second écran. +Webapp React pour préparer et accompagner des sessions gaming sur second écran. -Sokko G propose des toolboxes modulaires stockées dans le navigateur, ainsi que des pages de guides de jeu maintenues dans le dépôt. Aucune donnée utilisateur n’est envoyée côté serveur. +Sokko G propose des toolboxes modulaires stockées uniquement dans le navigateur, +des guides maintenus dans le dépôt et Sokko TCG, un mini-jeu de collection +avec compte Discord. Seul Sokko TCG stocke côté serveur les données requises +pour l'identité, les possessions et les échanges ; les toolboxes restent locales. L'interface cible les fenêtres d'ordinateur en plein écran ou en demi-écran. Les mises en page sont validées à partir de 768 px ; le projet ne prévoit pas d'interface ni de navigation dédiées au téléphone. @@ -18,6 +21,8 @@ L'interface cible les fenêtres d'ordinateur en plein écran ou en demi-écran. - Suivi d’un budget de stockage recommandé, avec quota navigateur en information. - Guides Monster Hunter Wilds, Diablo IV et Aniimo alimentés par des données JSON. - Listes et résultats de jeu copiables ou transformables en checklists. +- Sokko TCG : recharge serveur, paquets de trois cartes, album, historique, + échanges/dons protégés et distributions promotionnelles administrées. ## Démarrage @@ -34,7 +39,8 @@ npm run build ``` Le build est généré dans `website/dist`. -`npm start` sert cette version statique avec `server.mjs`. +`npm start` sert cette version avec `server.mjs` et expose l'API Cards lorsqu'elle +est activée. La politique de cache HTTP et les vérifications attendues côté proxy sont documentées dans [`docs/DELIVERY.md`](docs/DELIVERY.md). @@ -54,6 +60,14 @@ Exemple : PORT=5173 ``` +Sokko TCG reste désactivé tant que `CARDS_ENABLED` vaut `false`. Les variables +Discord, SQLite, cadence, administration et origine publique sont décrites dans +`.env.example`; la procédure d'activation et de sauvegarde se trouve dans +[`docs/DELIVERY.md`](docs/DELIVERY.md). + +Le parcours joueur est accessible sur `/#/cards`. Les comptes autorisés disposent +d'un tableau de bord séparé sur `/#/cards/admin`. + Le fichier `.env` est ignoré par git. Pour changer le port localement, modifier `PORT`. ## Vérifications @@ -67,9 +81,22 @@ npm run check Cette commande vérifie la configuration Node/Vite, lance le lint et les tests Node, régénère les index de listes, puis exécute le build React. +Pendant le développement de Sokko TCG, utiliser le gate ciblé : + +```bash +npm run check:cards +``` + +Il limite le lint et les tests Node au catalogue, à l'API, à l'intégration Cards +et aux données éditoriales concernées, puis construit l'application et exécute +uniquement les deux parcours Playwright Sokko TCG sur le vrai serveur Node. +Il ne remplace pas le contrôle complet avant un push. + Pour inclure les parcours navigateur, lancer `npm run check:full`. Le check, les E2E de développement et les E2E de production sont exécutés successivement pour éviter la concurrence avec le build. +Le gate complet réserve le port `4181` à Vite afin de ne jamais réutiliser par +erreur un serveur de développement déjà ouvert sur `5173`. La suite E2E utilise deux workers par défaut pour limiter la contention lors du chargement initial des outils par Vite. Le parallélisme reste ajustable avec `npm run test:e2e -- --workers=4`. Les traces des tests en échec sont conservées @@ -78,6 +105,8 @@ dans `test-results` et consultables depuis le rapport Playwright. Les changements de stockage, d'import, d'interaction ou de livraison doivent aller jusqu'à `npm run check:full`. La matrice de validation par risque et le rôle de chaque couche sont détaillés dans [`docs/TEST_STRATEGY.md`](docs/TEST_STRATEGY.md). +Sur la branche Sokko TCG, ce gate complet est lancé à la demande lors de la +revue pré-push ; les itérations courantes utilisent `npm run check:cards`. `npm run test:e2e:production` reconstruit l'application puis teste les comportements propres à la production, notamment la visibilité de la prise en main. Cette suite @@ -139,6 +168,7 @@ Les contenus maintenus à la main sont regroupés dans `website/public/data`. | `website/public/data/library.json` | Exemples interactifs des 17 outils de la Librairie. | | `website/public/data/library-toolbox-export.json` | Version importable et canonique des exemples de la Librairie. | | `website/public/data/toolbox-icons.json` | Manifeste des icônes SVG réutilisables. | +| `website/public/data/cards/catalog.json` | Collections, cartes, éditions, effets holographiques, palettes de sept couleurs, particules, finitions combinées et tables de tirage versionnées de Sokko TCG. | Les images publiques sont dans `website/public/static`. Les images raster livrées par le site utilisent WebP ; les icônes vectorielles utilisent SVG. diff --git a/docs/DELIVERY.md b/docs/DELIVERY.md index 59b3312..ec93705 100644 --- a/docs/DELIVERY.md +++ b/docs/DELIVERY.md @@ -158,11 +158,94 @@ ainsi que `data/site.json` sur l'origine publique. Si ce contrôle échoue, ne p relancer vers une nouvelle tête : redéployer le dernier SHA connu comme sain, puis diagnostiquer la version défaillante séparément. -## Serveur statique +## Activation de Sokko TCG + +Sokko TCG est désactivé par défaut. Avant activation, créer un fichier +`/etc/sokko-g/cards.env`, lisible uniquement par l'administrateur et le compte du +service, à partir de `.env.example`. L'unité systemd le charge sans rendre son +absence bloquante afin que les toolboxes continuent de fonctionner lorsque le +jeu est désactivé. + +Les prérequis d'activation sont : + +- `CARDS_ENABLED=true`, `CARDS_DEV_AUTH=false` et une origine HTTPS exacte dans + `CARDS_PUBLIC_ORIGIN` ; +- une application Discord avec le callback + `https:///api/cards/auth/callback`, le scope `identify`, son client ID + et son secret ; aucun bot n'est requis ; +- `CARDS_DB_PATH` dans un répertoire persistant hors du dépôt et de + `website/dist`, possédé par l'utilisateur `shinuwa` ; +- `CARDS_ADMIN_DISCORD_IDS` limité aux identifiants Discord autorisés ; +- la cadence de recharge, l'ouverture des paquets et les taux de tirage ne + passent plus par l'environnement : ils se règlent depuis l'administration + (Opérations › Paquets) et sont versionnés en base. Une base neuve démarre + avec une ouverture toutes les 12 heures, 5 au maximum. Chaque nouveau compte + reçoit 3 ouvertures de bienvenue ; +- un proxy qui transmet les cookies, l'en-tête `Origin`, le protocole d'origine + et les routes `/api/cards/*` sans cache. + +`CARDS_DEV_AUTH=true` expose un bouton « Version développement » qui ouvre une +session locale avec les droits administrateur. Ce mode est réservé aux tests et +reste désactivé en production ; les vrais administrateurs sont reconnus par leur +identifiant dans `CARDS_ADMIN_DISCORD_IDS`. + +Sur le serveur Vite local uniquement (`npm run dev`), ce compte garde en permanence +1000 poussières d'étoiles et 4 ouvertures sur 5 : le minuteur tourne, mais la réserve +n'atteint jamais le maximum. `server.mjs` n'active jamais ce comportement, même avec +`CARDS_DEV_AUTH=true`. + +Pour tester le parcours Discord réel en local, ajouter le callback +`http://localhost:5173/api/cards/auth/callback` à l'application Discord, renseigner +`DISCORD_CLIENT_ID`, `DISCORD_CLIENT_SECRET` et `DISCORD_REDIRECT_URI` avec cette +adresse dans le `.env` non versionné, puis ouvrir le site sur `localhost:5173` +et non `127.0.0.1` : les cookies de la tentative dépendent de l'hôte. Sans ces +identifiants, le bouton Discord est remplacé par un avis. + +Après installation du fichier d'environnement et avant de rendre la navigation +visible, redémarrer le service puis vérifier `/api/cards/config`, le parcours +Discord, une ouverture et les journaux. La réponse de configuration reste +`no-store`. Une désactivation remet `CARDS_ENABLED=false` : l'entrée de +navigation disparaît et les toolboxes restent disponibles, sans supprimer la +base. + +### Sauvegarde et restauration Cards + +Une sauvegarde cohérente peut être réalisée pendant le fonctionnement grâce à +l'API de sauvegarde SQLite : + +```bash +node scripts/backup-nebula-cards.mjs backup \ + /var/lib/sokko-g/nebula-cards.sqlite \ + /var/backups/sokko-g/nebula-cards-$(date +%F).sqlite +node scripts/backup-nebula-cards.mjs verify \ + /var/backups/sokko-g/nebula-cards-$(date +%F).sqlite +``` + +La restauration est volontairement une opération hors ligne. Arrêter le +service, conserver une copie de la base courante, restaurer et vérifier, puis +redémarrer : + +```bash +sudo systemctl stop sokko-g +node scripts/backup-nebula-cards.mjs restore \ + /var/backups/sokko-g/nebula-cards-2026-11-01.sqlite \ + /var/lib/sokko-g/nebula-cards.sqlite +node scripts/backup-nebula-cards.mjs verify \ + /var/lib/sokko-g/nebula-cards.sqlite +sudo systemctl start sokko-g +``` + +Le script vérifie `PRAGMA integrity_check` et la présence du schéma avant le +remplacement atomique. Le test Node restaure une vraie sauvegarde et relit les +exemplaires ; une restauration d'exploitation doit aussi être répétée sur un +environnement non public avant l'activation. + +## Serveur Node et fichiers statiques `npm run build` produit l'application dans `website/dist`. `npm start` sert ce -répertoire avec `server.mjs`. Les tests de Vite Preview couvrent le comportement -du build dans le navigateur, mais pas les en-têtes HTTP de ce serveur Node. +répertoire avec `server.mjs` et, lorsque la fonctionnalité est activée, expose +l'API `/api/cards`. Les tests de Vite Preview couvrent le comportement du build +dans le navigateur, mais ni les en-têtes HTTP ni l'API de ce serveur Node. La politique de cache du serveur est la suivante : diff --git a/docs/STORAGE_SCHEMA.md b/docs/STORAGE_SCHEMA.md index d7cc38c..5bcd0ae 100644 --- a/docs/STORAGE_SCHEMA.md +++ b/docs/STORAGE_SCHEMA.md @@ -1,7 +1,197 @@ # Storage Schema -Ce document décrit les données persistées dans IndexedDB pour les toolboxes. -Il doit être mis à jour à chaque ajout ou modification d'outil. +Ce document décrit les données persistées dans IndexedDB pour les toolboxes et +le cache local de Sokko TCG. Il doit être mis à jour à chaque ajout ou +modification d'outil ou de stockage Cards. + +## Sokko TCG : propriété serveur et cache local + +La propriété des cartes est enregistrée dans la base SQLite définie par +`CARDS_DB_PATH`. Le serveur conserve les joueurs Discord, sessions, compteurs de +recharge, ouvertures, collections (quantité par carte), favoris, +transferts, campagnes, codes et journal d'audit. L'historique joueur n'en expose que les +événements de jeu ; les actions d'administration sont lues par `GET /api/cards/admin/history`, +réservée aux administrateurs et paginée par `before` (50 entrées). Les migrations versionnées se +trouvent dans `services/cards/database.js`; les clés étrangères et le mode WAL +sont activés à l'ouverture. + +Collections, ouvertures et transferts : + +- `collection_cards(player_id, edition_id, quantity, acquired_at)` : une ligne par + carte possédée, avec sa quantité (≥ 1). Les exemplaires n'ont pas d'identité + propre et aucune carte n'est « non échangeable ». +- Seuls les doublons quittent une collection : échange, don ou recyclage. Un + joueur garde toujours au moins un exemplaire de chaque carte obtenue, donc une + ligne n'est jamais supprimée. « Découverte » et « possédée » se confondent : + il n'y a pas de table de découvertes. +- Doublons disponibles d'une carte : `quantity - 1 - réservés`. Les doublons + réservés sont ceux proposés par le joueur dans ses échanges au statut `open`. + La réservation découle du statut : accepter, refuser, annuler ou laisser expirer + (7 jours) un échange libère son doublon. Le doublon demandé n'est pas réservé : + il est revérifié quand la proposition est acceptée. +- `opening_cards(opening_id, position, edition_id, was_new_card, was_new_edition, quantity_before)` : + la carte tirée à chaque position. Une carte ou une édition est « nouvelle » si + le joueur ne la possédait pas. +- `transfers(…, offered_edition_id, requested_edition_id, …)` : la carte proposée + et, pour un échange, la carte demandée, avec le destinataire choisi dès la création. + Un don est immédiat (`completed`) ; un échange reste `open` jusqu'à Accepter, Refuser + (`cancelled`, `declined = 1`) ou Annuler. Une carte ne part que si le joueur en a un + doublon disponible (`NOT_A_DUPLICATE` sinon) ; à l'acceptation, un doublon quitte + chaque collection et s'ajoute à l'autre. La migration 3 annule les transferts encore + en cours de l'ancien système à code ; `code`, `joined` et les colonnes de confirmation + ne servent plus qu'à relire l'historique. `GET /api/cards/traders` n'expose des autres + joueurs que leur identité publique et leurs doublons disponibles. +- `cardFormats` : formats d'une variation mythique, qui multiplient les finitions générées + (format × effet × palette). `cards[].fullImage` : illustration du format `full-art` ; une + variation de ce format est refusée (`FULL_IMAGE_REQUIRED`) pour une carte qui n'en a pas. +- Paquet de la Boutique : une collection `packCategory: "shop"` ne s'obtient que par + `POST /api/cards/shop/pack` (ni paquet offert ni ouverture). Il tire dans les collections + actives et les légendaires et mythiques de sa collection, qui reçoivent + `shop_settings.shop_pack_share` % de ces raretés, au prix `shop_pack_price`. Ses cartes + ne sortent d'aucun autre paquet. +- Une variation mythique possédée, ou citée par une ouverture, un transfert ou + une campagne, est retirée des tirages plutôt que supprimée, pour que ces + références restent affichables. + +Poussière d'étoiles et boutique : + +- `players.stardust` : poussière d'étoiles du joueur (entier ≥ 0). + `players.purchased_openings` : ouvertures achetées en boutique, non + utilisées. Elles sont séparées de la réserve rechargeable + (`players.openings_balance`), sans plafond et sans recharge ; une ouverture + normale peut en consommer une (`purchased: true`) au lieu de la réserve. +- Recyclage (`services/cards/stardust.js`, `planRecycling`) : les doublons + disponibles de chaque carte (tous, ou un seul depuis la fiche de la carte) + rapportent la valeur de leur rareté. Les favorites n'ont pas de protection + particulière, puisque leur exemplaire reste toujours. Le recyclage est refusé + pendant une ouverture en cours. Le journal d'audit garde `cards_recycled` + (nombre, poussière, éditions) et `opening_purchased` (prix). +- `shop_settings(id = 1, stardust_values_json, opening_price, updated_at, updated_by)` : + barème de poussière par rareté (entiers de 0 à 100 000) et prix d'une + ouverture (entier de 1 à 100 000), réglés depuis l'administration et + appliqués immédiatement. Valeurs de départ (`INITIAL_SHOP_SETTING`) : + Commun 1, Rare 3, Épique 10, Légendaire 40, Mythique 150 ; une ouverture coûte 30. + +Distributions par codes : + +- `campaigns(id, name, code, reward_json, max_claims, created_by, created_at, expires_at, revoked_at)` : + une campagne a un seul code lisible (`code`, unique, 4 à 24 caractères), + utilisable une fois par joueur ; `max_claims` limite le nombre total + d'utilisations (`NULL` = sans limite). + `reward_json` vaut `{ items: [élément, …] }` (1 à 50 éléments), chaque élément + étant `{ type: "card", editionId, quantity: 1 }` (chaque carte au plus une fois) ou + `{ type: "pack", collectionId, rarityWeights | null, guarantee | null, quantity }`, + avec une quantité de 1 à 10 et `guarantee` = `{ type: "rarity", rarity, count }` + (au moins `count` cartes de cette rareté ou mieux) ou `{ type: "edition", editionId }`. + La récompense est validée et normalisée par `services/cards/rewards.js`. + `expires_at` est nul pour une campagne sans date d'expiration. +- `campaign_claims(id, campaign_id, player_id, claimed_at)` : une ligne + par utilisation, au plus une par joueur et par campagne. +- `gift_packs(id, player_id, campaign_id, collection_id, options_json, created_at, opening_id, opened_at)` : + paquets offerts en attente. Leur ouverture ne consomme pas la recharge, ignore + la fermeture de la collection et applique les taux et la garantie de + `options_json` ; `opening_id` les marque comme ouverts. + +Le navigateur utilise une base IndexedDB distincte, `sokkog-nebula-cards`, avec +un object store `players`. Chaque entrée est indexée par l'identifiant interne +du joueur et contient le dernier état renvoyé par l'API ainsi qu'un horodatage. +Ce snapshot sert uniquement à consulter le dernier état connu hors connexion. +Il est remplaçable intégralement et ne prouve jamais une possession : une +modification directe du cache n'est envoyée à aucune mutation serveur. + +Le tableau de bord administrateur lit un agrégat calculé depuis ces tables. + +- `stats` : nombre de joueurs et joueurs actifs sur 7 jours. +- Par joueur : identité publique, date d'inscription, dernier tirage, paquets + ouverts, paquets offerts et ouvertures achetées en attente, solde + d'ouvertures après recharge serveur, cartes possédées par rareté (somme des quantités), + transferts terminés (`transfersCount`) et poussière d'étoiles. +- `shopSetting`, et le nombre de joueurs possédant chaque édition (`editionOwners`). +- `recordedEditions` : éditions possédées ou citées par une ouverture ou un transfert. + +Cet agrégat ne renvoie pas l'identifiant Discord au navigateur. + +### Partage entre catalogue versionné et base (migration 2) + +`website/public/data/cards/catalog.json` décrit le contenu lié au code et aux +fichiers du dépôt : raretés, effets holographiques et palettes (qui demandent +du CSS), formes et palettes de particules, effets d'ouverture et leurs presets, +identité des collections, cartes et éditions communes à légendaires (liées aux +images). Il ne déclare ni finitions, ni variations mythiques, ni activation des +paquets (`collections[].active`), ni taux de tirage (`dropTables`, +`collections[].dropWeights`) : +`loadCardsCatalog` → `prepareVersionedCatalog` refuse un fichier qui en contient +(`assertVersionedCatalogScope`). + +Les finitions sont générées (`withGeneratedFinishes`) : `standard`, puis une +finition `-` par combinaison effet holographique × palette. Une +finition ne porte pas de particules : les particules n'existent que pendant +l'ouverture, réglées par l'effet d'ouverture. + +La migration 2 crée les tables du contenu géré depuis l'administration. Le +serveur les combine au catalogue versionné au démarrage et après chaque +modification (`buildPublishedCatalog`) ; elles survivent aux déploiements et +sont incluses dans les sauvegardes SQLite. + +- `mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by)` : + seule source des variations mythiques. Chaque ligne crée l'édition + `-` (finition holographique, parent légendaire non + promotionnel), placée après sa légendaire dans l'ordre des finitions. + `active` la rend tirable ; `retired` la retire des tirages tout en la gardant + publiée avec `retired: true`, pour que les cartes déjà possédées restent + affichés. Règle unique : une variation que personne ne possède et qu'aucune + campagne ne cite (carte offerte ou carte garantie) est supprimée ; sinon elle + est retirée, peut être réactivée, et les codes et paquets offerts qui la + citent continuent de fonctionner. + +La migration insère le contenu de départ décrit dans `services/cards/admin-seed.js` : +les deux paquets ouverts, leurs taux de tirage (les poids recommandés : Commun 64, +Rare 24, Épique 8, Légendaire 3, Mythique 1) et la recharge de départ (1 ouverture +toutes les 60 minutes, réserve de 5). Aucune variation mythique ni réglage +d'ouverture n'est inséré : toutes les collections partent de la même base, et la +rareté mythique ne sort d'un paquet qu'une fois ses variations créées dans +l'administration. +- `collection_states(collection_id, active, updated_at, updated_by)` : paquet + ouvert ou fermé aux joueurs, publié dans `collections[].active`. Une + collection sans ligne est fermée ; un paquet ne peut être ouvert que s'il a + une table de tirage. +- `drop_rates(collection_id, rarity_weights_json, updated_at, updated_by)` : + taux de tirage de chaque paquet, non versionnés, publiés sur la collection + dans `dropWeights`. Les poids sont des entiers de 0 à 1 000 000, un par + rareté, de total strictement positif ; un nouveau réglage s'applique + immédiatement aux paquets suivants. Le journal d'audit + (`drop_rates_updated`) garde les anciens et les nouveaux poids. Les poids + recommandés sont déclarés dans `catalog.json` (`rarities[].recommendedWeight`) + et proposés par l'administration pour réinitialiser un paquet. +- `recharge_settings(id = 1, interval_ms, max_openings, updated_at, updated_by)` : + réglage unique de recharge des ouvertures, commun à tous les paquets et non + versionné. Le délai, saisi en minutes dans l'administration, est un nombre + entier de minutes entre 1 et 10 080 (7 jours) ; la réserve reste plafonnée à 5 (`players.openings_balance`). Un + nouveau délai s'applique immédiatement, y compris au temps écoulé depuis la + dernière recharge du joueur (`players.recharge_anchor`). Ce réglage ne passe + plus par l'environnement (`CARDS_RECHARGE_*` supprimées) ; le tableau de bord + admin l'expose dans `rechargeSetting`. +- `mythic_opening_settings(scope, target_id, particle_shape_id, particle_palette_id, updated_at, updated_by)` : + forme et palette des particules d'ouverture mythique d'une collection + (`scope = 'collection'`) ou d'une carte et de toutes ses variations + (`scope = 'card'`). Une valeur `NULL` signifie « hérité » ; une ligne sans + aucune valeur est supprimée. La palette `match-holo` reprend les couleurs de + la palette holographique de la variation ouverte. + +Le catalogue versionné déclare un seul effet d'ouverture par rareté, sans +variante par collection (`collectionId` est refusé) : les variantes mythiques +passent par ces réglages. Le catalogue publié les expose dans `mythicOpeningSettings`. +L'ouverture mythique repose sur un seul effet de base, `mythic-default-opening` +(aura, durées, 48 particules), dont le preset fixe le défaut : Étincelles et +Arc-en-ciel. La forme et la palette s'héritent indépendamment : réglage de la +carte, sinon de la collection, sinon défaut. Les lignes devenues incohérentes +avec le catalogue versionné (carte, finition, forme ou palette supprimées) sont +ignorées au chargement sans être effacées. + +Le cache Cards n'appartient pas à la base `sokkog`, n'est inclus dans aucun +export ou import de toolbox et n'est jamais converti en inventaire de +production. Les toolboxes restent entièrement locales et leur contrat ci-dessous +ne change pas. ## Préférences locales hors toolbox diff --git a/docs/TEST_STRATEGY.md b/docs/TEST_STRATEGY.md index 6aef969..1e46ba6 100644 --- a/docs/TEST_STRATEGY.md +++ b/docs/TEST_STRATEGY.md @@ -19,6 +19,7 @@ not bugs, missing scenarios or a percentage of work remaining. | React lifecycle, shared editing and navigation | `e2e/editor-lifecycle.spec.js`, `inline-edit.spec.js`, `form-reorder.spec.js`, `shell-behavior.spec.js`, `session-state.spec.js` | | Public data loading, retry and stale responses | `e2e/app-data.spec.js` | | HTTP cache policy of the delivered Node server | `tests/server-cache.test.mjs`; production E2E remains responsible for stale bundle recovery | +| Sokko TCG ownership, recharge, idempotence, transfers, campaign codes and backup/restore | `tests/nebula-cards.test.mjs`, `tests/nebula-cards-api.test.mjs`, then `e2e/nebula-cards.spec.js` against the delivered Node API and a temporary SQLite database | | Shared reorder policy and module order | `e2e/grouped-reorder.spec.js`, `module-order.spec.js` | | Toolbox creation, import/export, text exchange | `e2e/toolbox.spec.js`, `text-exchange.spec.js`; Node toolbox module tests | | Links: creation, copy, category removal preserving links, deletion and reload | `e2e/basic-tools.spec.js` | @@ -55,13 +56,24 @@ change affects persisted data, imports, user interaction or delivery. ## Validation Layers +- `npm run check:cards` est le gate d'itération de Sokko TCG. Il exécute le + lint ciblé, les tests Node du catalogue, des règles, de l'API, des sauvegardes + et des données publiques, puis le build et les deux parcours Cards contre le + serveur Node avec une base SQLite temporaire. Il n'exécute pas les E2E des + toolboxes et des guides. - `npm test` runs Node tests for pure logic, data contracts, architecture guards and the direct `server.mjs` cache test. The latter opens a local ephemeral port. - `npm run test:e2e` uses Vite in development and therefore includes React `StrictMode`; it validates interactive behavior against source modules. + `npm run check:full` lui réserve le port 4181 pour ne pas réutiliser une + instance personnelle éventuellement ouverte sur 5173. - `npm run test:e2e:production` rebuilds the client and exercises the Vite Preview result. It catches build-only behavior and stale-bundle recovery, but does not run the Node static server or the production proxy. +- `npm run test:e2e:cards` construit l'application puis lance `server.mjs` avec + une base SQLite temporaire, la connexion de test et Sokko TCG activé. Il + valide la reprise d'ouverture, l'album, l'administration et le layout à + 768 px sans utiliser une API simulée. - `tests/server-cache.test.mjs` exercises the HTTP policy implemented by `server.mjs`. It does not prove headers added or replaced by the public proxy. - Public `curl` checks after deployment validate the delivered origin and remain @@ -84,3 +96,5 @@ and Beads task. Keep historical results dated instead of presenting them as a current run. Close only the task whose acceptance criteria were actually met. Do not introduce visual snapshots solely to prove that a page loads. Keep detailed command logs outside tracked source and report concise results. +Pour les itérations exclusivement limitées à Sokko TCG, `check:cards` suffit +jusqu'à la demande explicite de pré-push, qui rétablit `check:full` comme gate. diff --git a/e2e/nebula-cards.spec.js b/e2e/nebula-cards.spec.js new file mode 100644 index 0000000..5464975 --- /dev/null +++ b/e2e/nebula-cards.spec.js @@ -0,0 +1,1463 @@ +// Rôle : valide l'ouverture, la reprise, l'album et l'administration de Sokko TCG. +import { readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "@playwright/test"; + +// Sélecteurs à choix unique du design system (`SelectDropdown`). +const selectTrigger = (scope, label) => scope.getByRole("button", { name: new RegExp(`^${label} : `) }); +async function chooseOption(scope, label, option) { + await selectTrigger(scope, label).click(); + await scope.getByRole("option", typeof option === "string" ? { name: option, exact: true } : { name: option }).click(); +} +async function expectOptions(page, scope, label, options) { + await selectTrigger(scope, label).click(); + await expect(scope.getByRole("option")).toHaveText(options); + await page.keyboard.press("Escape"); +} +const INHERITED = /hérité|défaut/; + +// Le menu ouvert reste entièrement visible et personne ne le recouvre, quel que soit le bord dont il est proche. +async function expectOpenMenuVisible(page, selector) { + const result = await page.locator(selector).evaluate((menu) => { + const box = menu.getBoundingClientRect(); + const clip = menu.ownerDocument.querySelector("main").getBoundingClientRect(); + const points = [[box.left + 8, box.top + 8], [box.right - 8, box.top + 8], [box.left + 8, box.bottom - 8], [box.right - 8, box.bottom - 8]]; + return { + inside: box.left >= clip.left && box.right <= Math.min(clip.right, globalThis.innerWidth) && box.top >= 0 && box.bottom <= globalThis.innerHeight, + covered: points.filter(([x, y]) => !menu.contains(menu.ownerDocument.elementFromPoint(x, y))).length + }; + }); + expect(result).toEqual({ inside: true, covered: 0 }); +} + +// Rend un anneau légendaire et un anneau mythique figés au même instant, avec une palette unie identique, +// puis compare leurs profils de luminance radiaux : la silhouette (trait + lueur) doit être la même. +async function expectMythicRingSilhouetteToMatchLegendary(page) { + const color = "#f6c453"; + await page.evaluate((probeColor) => { + const style = globalThis.document.createElement("style"); + style.dataset.ringProbe = ""; + style.textContent = "[data-ring-probe] .nebula-card-particles::after, [data-ring-probe] .nebula-card-particles i { display: none !important; } [data-ring-probe] *, [data-ring-probe] *::before { animation-play-state: paused !important; animation-delay: -400ms !important; }"; + globalThis.document.head.append(style); + for (const [index, rarity] of ["legendary", "mythic"].entries()) { + const probe = globalThis.document.createElement("div"); + probe.className = "nebula-card"; + probe.dataset.ringProbe = rarity; + probe.dataset.rarity = rarity; + probe.dataset.particleShape = "sparks"; + probe.style.cssText = `position: fixed; z-index: 2147483647; top: 0; left: ${index * 320}px; width: 320px; height: 320px; max-width: none; aspect-ratio: auto; background: #000; --opening-aura: ${probeColor}; --particle-gradient: ${probeColor}; --opening-particle-duration: 1200ms;`; + const particles = globalThis.document.createElement("span"); + particles.className = "nebula-card-particles"; + if (rarity === "mythic") particles.innerHTML = ''; + probe.append(particles); + globalThis.document.body.append(probe); + } + }, color); + const shot = await page.screenshot({ clip: { x: 0, y: 0, width: 640, height: 320 } }); + const profiles = await page.evaluate(async (base64) => { + const image = new globalThis.Image(); + image.src = `data:image/png;base64,${base64}`; + await image.decode(); + const canvas = globalThis.document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0); + const scale = image.width / 640; + const directions = Array.from({ length: 8 }, (_, index) => [Math.cos(index * Math.PI / 4), Math.sin(index * Math.PI / 4)]); + const profile = (centerX) => Array.from({ length: 50 }, (_, step) => { + const radius = step * 3; + const total = directions.reduce((sum, [dx, dy]) => { + const [red, green, blue] = context.getImageData(Math.round((centerX + dx * radius) * scale), Math.round((160 + dy * radius) * scale), 1, 1).data; + return sum + (red + green + blue) / 3; + }, 0); + return total / directions.length; + }); + globalThis.document.querySelectorAll("[data-ring-probe]").forEach((element) => element.remove()); + return { legendary: profile(160), mythic: profile(480) }; + }, shot.toString("base64")); + expect(Math.max(...profiles.legendary)).toBeGreaterThan(100); + const differences = profiles.legendary.map((value, index) => Math.abs(value - profiles.mythic[index])); + expect(Math.max(...differences)).toBeLessThan(24); + expect(differences.reduce((sum, value) => sum + value, 0) / differences.length).toBeLessThan(4); +} + +async function expectArtworkFramed(card) { + const layout = await card.evaluate((element) => { + const bounds = (selector) => { + const rect = element.querySelector(selector).getBoundingClientRect(); + return { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.width }; + }; + const artwork = element.querySelector(".nebula-card-art img, .nebula-card-placeholder-mark"); + return { face: bounds(".nebula-card-face"), art: bounds(".nebula-card-art"), artwork: bounds(artwork.matches("img") ? ".nebula-card-art img" : ".nebula-card-placeholder-mark"), image: artwork.matches("img"), size: element.dataset.cardSize, title: bounds("h3") }; + }); + expect(layout.artwork.bottom).toBeLessThanOrEqual(layout.art.bottom + 0.5); + expect(layout.artwork.left).toBeGreaterThanOrEqual(layout.art.left - 0.5); + expect(layout.artwork.right).toBeLessThanOrEqual(layout.art.right + 0.5); + if (layout.image) { + expect(layout.artwork.width / layout.art.width).toBeGreaterThan(0.98); + } else if (layout.size === "md") { + expect(layout.artwork.bottom).toBeLessThanOrEqual(layout.title.top + 0.5); + expect(layout.artwork.width / layout.face.width).toBeLessThan(0.46); + } else { + expect(layout.artwork.top).toBeGreaterThanOrEqual(layout.title.bottom - 0.5); + expect(layout.artwork.width / layout.face.width).toBeLessThan(0.46); + } +} + +async function expectFixedTitleBand(card, position) { + const layout = await card.evaluate((element) => { + const title = element.querySelector("h3").getBoundingClientRect(); + const art = element.querySelector(".nebula-card-art").getBoundingClientRect(); + return { title: { top: title.top, bottom: title.bottom, height: title.height }, art: { top: art.top, bottom: art.bottom } }; + }); + expect(Math.abs(layout.title.height - 52)).toBeLessThan(0.6); + if (position === "top") { + expect(Math.abs(layout.title.bottom - layout.art.top)).toBeLessThan(0.6); + } else { + expect(Math.abs(layout.art.bottom - layout.title.top)).toBeLessThan(0.6); + } +} + +async function expectStandardCardFrame(card, size) { + const layout = await card.evaluate((element) => { + const face = element.querySelector(".nebula-card-face"); + const art = element.querySelector(".nebula-card-art"); + const title = element.querySelector("h3"); + const copy = element.querySelector(".nebula-card-copy"); + const rarity = element.querySelector(".nebula-card-rarity-symbol"); + const faceBounds = face.getBoundingClientRect(); + const artBounds = art.getBoundingClientRect(); + const styles = element.ownerDocument.defaultView; + const titleStyles = styles.getComputedStyle(title); + const titleTextStyles = styles.getComputedStyle(title.querySelector("span")); + const rarityStyles = styles.getComputedStyle(rarity); + return { + layout: face.dataset.cardLayout, + facePattern: styles.getComputedStyle(face).backgroundImage, + titleBackground: titleStyles.backgroundColor, + titleDisplay: titleStyles.display, + titleAlignItems: titleStyles.alignItems, + titleJustifyItems: titleStyles.justifyItems, + titleFontSize: Number.parseFloat(titleStyles.fontSize), + titlePaddingRight: Number.parseFloat(titleStyles.paddingRight), + titleTextAlign: titleTextStyles.textAlign, + titleLineClamp: titleTextStyles.webkitLineClamp, + copyBackground: copy ? styles.getComputedStyle(copy).backgroundColor : null, + rarityPosition: rarityStyles.position, + rarityWidth: Number.parseFloat(rarityStyles.width), + leftInset: artBounds.left - faceBounds.left, + rightInset: faceBounds.right - artBounds.right + }; + }); + expect(layout.layout).toBe("standard"); + expect(layout.facePattern).not.toBe("none"); + expect(layout.facePattern).not.toContain("repeating-linear-gradient"); + expect(layout.facePattern.match(/radial-gradient/g)).toHaveLength(4); + expect(layout.titleBackground).toBe("rgba(0, 0, 0, 0)"); + expect(layout.titleDisplay).toBe("grid"); + expect(layout.titleAlignItems).toBe("center"); + expect(layout.titleJustifyItems).toBe("center"); + expect(layout.titleTextAlign).toBe("center"); + expect(layout.titleLineClamp).toBe("2"); + if (size === "lg") { + expect(layout.copyBackground).toBe("rgba(0, 0, 0, 0)"); + expect(layout.leftInset).toBeGreaterThan(10); + expect(layout.rightInset).toBeGreaterThan(10); + } else { + expect(layout.leftInset).toBeLessThan(3); + expect(layout.rightInset).toBeLessThan(3); + expect(layout.titleFontSize).toBeLessThan(14); + expect(layout.titlePaddingRight).toBeLessThan(12); + expect(layout.rarityPosition).toBe("absolute"); + expect(layout.rarityWidth).toBe(13); + } +} + +test("a failed Discord return explains the failure once on the login screen", async ({ page }) => { + await page.goto("/?cardsAuth=denied#/cards/shop"); + await expect(page.getByRole("alert")).toHaveText("Connexion annulée : vous n’avez pas autorisé l’accès depuis Discord."); + await expect(page.getByRole("link", { name: "Se connecter avec Discord", exact: true })).toHaveAttribute("href", "/api/cards/auth/discord?returnTo=%2Fcards%2Fshop"); + await expect(page).toHaveURL(/:\d+\/#\/cards\/shop$/); + await page.reload(); + await expect(page.getByRole("heading", { name: "Sokko TCG", exact: true })).toBeVisible(); + await expect(page.getByRole("alert")).toHaveCount(0); +}); + +test("player opens and reveals a three-card pack", async ({ page }) => { + test.setTimeout(60_000); + await page.goto("/#/cards"); + await expect(page.locator(".nav-icon-cards")).toHaveCSS("mask-image", /tcg\.svg/); + await expect(page.getByRole("heading", { name: "Sokko TCG", exact: true })).toBeVisible(); + await expect(page.getByText("Trading Card Game", { exact: true })).toBeVisible(); + const loginArt = page.locator('.nebula-login-art img[src="/static/img/cards/login.webp"]'); + await expect(loginArt).toBeVisible(); + await expect.poll(() => loginArt.evaluate((image) => image.naturalWidth)).toBeGreaterThan(0); + const discordLogin = page.getByRole("link", { name: "Se connecter avec Discord", exact: true }); + await expect(discordLogin).toHaveCSS("background-color", "rgb(88, 101, 242)"); + await expect(discordLogin.locator("span")).toHaveCSS("color", "rgb(255, 255, 255)"); + const discordIcon = discordLogin.locator('img[src="/static/icons/discord.svg"]'); + await expect(discordIcon).toBeVisible(); + await expect(discordIcon).toHaveCSS("width", "26px"); + await expect(discordIcon).toHaveCSS("height", "26px"); + await expect(page.getByRole("button", { name: "Test administrateur", exact: true })).toHaveCount(0); + await page.getByRole("button", { name: "Version développement", exact: true }).click(); + const administrationButton = page.getByRole("link", { name: "Administration", exact: true }); + const logoutButton = page.getByRole("button", { name: "Déconnexion", exact: true }); + await expect(administrationButton).toBeVisible(); + await expect(administrationButton).toHaveAttribute("href", "#/cards/admin"); + await expect(logoutButton).toHaveAttribute("data-variant", "secondary"); + // Le lien de bascule précède le menu latéral collant et l'accompagne au défilement. + expect(await administrationButton.evaluate((element) => element.nextElementSibling?.getAttribute("aria-label"))).toBe("Sections de Sokko TCG"); + await expect(page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Accueil", exact: true })).toHaveAttribute("aria-current", "page"); + await expect(page.locator(".nebula-player-hero.nds-page-hero")).toBeVisible(); + await expect(page.getByRole("heading", { name: "Vue d’ensemble", exact: true })).toBeVisible(); + await expect(page.locator('.nebula-opening-reserve[aria-label="Ouvertures disponibles"] .nebula-opening-reserve-value')).toContainText("3/ 5"); + await expect(page.getByText("Probabilités", { exact: true })).toHaveCount(0); + expect(await page.locator(".nebula-home").evaluate((element) => element.getBoundingClientRect().bottom <= element.ownerDocument.defaultView.innerHeight + 1)).toBe(true); + + await page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Paquets", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Paquets permanents", exact: true })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Paquets événements", exact: true })).toBeVisible(); + // Les ouvertures disponibles sont sous le menu, et non plus dans le titre de la page. + await expect(page.locator(".nebula-dashboard-aside-slot .nebula-opening-reserve")).toBeVisible(); + // Les deux catégories sont côte à côte : elles commencent à la même hauteur. + const packCategoryBoxes = await page.locator(".nebula-pack-category").evaluateAll((sections) => sections.map((section) => section.getBoundingClientRect()).map(({ top, left }) => ({ top, left }))); + expect(packCategoryBoxes[0].top).toBeCloseTo(packCategoryBoxes[1].top, 0); + expect(packCategoryBoxes[1].left).toBeGreaterThan(packCategoryBoxes[0].left); + // Titres et paquets restent alignés d'une section à l'autre, même si un sous-titre passe à la ligne. + for (const selector of [".nebula-pack-category h3", ".nebula-pack-category .nebula-pack"]) { + const [first, second] = await page.locator(selector).evaluateAll((elements) => elements.map((element) => element.getBoundingClientRect().top)); + expect(first).toBeCloseTo(second, 0); + } + await expect(page.locator(".nebula-pack .nebula-collection-back")).toHaveCount(2); + await expect(page.locator('.nebula-pack-back img[src="/static/img/cards/primordial-nebula/back.webp"]')).toBeVisible(); + await expect(page.locator('.nebula-pack-back img[src="/static/img/cards/astral-genesis/back.webp"]')).toBeVisible(); + await expect(page.locator('.nebula-pack-back[data-card-size="md"]')).toHaveCount(2); + expect((await page.locator(".nebula-pack-back").first().boundingBox()).width).toBeCloseTo(180, 0); + await expect(page.locator(".nebula-pack").filter({ hasText: "Genèse Astrale" })).toBeVisible(); + const originsPack = page.locator(".nebula-pack").filter({ hasText: "La Nébuleuse Originelle" }); + await expect(originsPack.locator(".nebula-collection-back-copy")).toHaveText("La Nébuleuse Originelle"); + await expect(originsPack.locator(".nebula-collection-back-copy")).not.toContainText("Sokko TCG"); + expect(await originsPack.locator(".nebula-collection-back").evaluate((back) => { + const backBox = back.getBoundingClientRect(); + const copyBox = back.querySelector(".nebula-collection-back-copy").getBoundingClientRect(); + return (copyBox.top + copyBox.height / 2 - backBox.top) / backBox.height; + })).toBeGreaterThan(0.68); + // La tuile compacte se limite au dos de carte et à la description : elle est entièrement cliquable. + expect((await originsPack.boundingBox()).width).toBeCloseTo(180, 0); + await expect(originsPack).not.toHaveClass(/nds-card/); + // Le survol illumine le dos sans peindre le bouton derrière la description. + await originsPack.hover(); + await expect(originsPack).toHaveCSS("background-image", "none"); + await expect(originsPack).toHaveCSS("box-shadow", "none"); + await expect(originsPack.locator(".nebula-pack-back")).toHaveCSS("box-shadow", /246, 196, 83/); + await expect(originsPack.locator(".nebula-pack-copy")).toHaveCSS("-webkit-line-clamp", "3"); + // Les descriptions actuelles tiennent sur ces trois lignes, sans points de suspension. + expect(await page.locator(".nebula-pack-copy").evaluateAll((copies) => copies.every((copy) => copy.scrollHeight <= copy.clientHeight))).toBe(true); + await expect(page.locator(".nebula-pack-categories > .nds-panel")).toHaveCount(2); + await expect(page.getByText("Probabilités", { exact: true })).toHaveCount(0); + await page.getByRole("button", { name: "Ouvrir ce paquet : La Nébuleuse Originelle", exact: true }).click(); + // L'étape d'ouverture garde le hero, affiche les probabilités et ne propose le retour qu'une fois les cartes révélées. + await expect(page.locator(".nebula-player-hero")).toBeVisible(); + const openingOdds = page.getByRole("list", { name: "Probabilités" }).getByRole("listitem"); + await expect(openingOdds).toHaveCount(5); + await expect(openingOdds.first()).toContainText(/Commun.*%/); + await expect(page.getByRole("button", { name: "Retour", exact: true })).toHaveCount(0); + await expect(page.getByRole("button", { name: "Révéler la carte" })).toHaveCount(3); + await expect(page.locator('.nebula-card-back img[src="/static/img/cards/primordial-nebula/back.webp"]')).toHaveCount(3); + await expect(page.locator(".nebula-card-back").first()).toHaveCSS("background-image", /primordial-nebula\/back\.webp/); + await expect(page.locator(".nebula-card-back .nebula-collection-back-copy strong")).toHaveText(["La Nébuleuse Originelle", "La Nébuleuse Originelle", "La Nébuleuse Originelle"]); + expect(await page.locator(".nebula-card-back .nebula-collection-back").first().evaluate((back) => { + const backBox = back.getBoundingClientRect(); + const copyBox = back.querySelector(".nebula-collection-back-copy").getBoundingClientRect(); + return (copyBox.top + copyBox.height / 2 - backBox.top) / backBox.height; + })).toBeLessThan(0.9); + // L'adresse de section survit au rechargement : l'ouverture en attente réapparaît, et l'accueil propose aussi de la reprendre. + await page.reload(); + await expect(page.getByRole("button", { name: "Révéler la carte" })).toHaveCount(3); + // Le journal ne dévoile pas les cartes d'une ouverture encore en attente. + await page.goto("/#/cards/history"); + await expect(page.getByText("Cartes à révéler", { exact: true })).toBeVisible(); + await expect(page.getByRole("list", { name: "Cartes obtenues" })).toHaveCount(0); + await page.goto("/#/cards"); + await page.getByRole("button", { name: "Reprendre l’ouverture", exact: true }).click(); + await expect(page.getByRole("button", { name: "Révéler la carte" })).toHaveCount(3); + await page.getByRole("button", { name: "Tout révéler" }).click(); + const openingStage = page.locator(".nebula-opening-stage"); + const revealedCards = page.locator('.nebula-opening-cards .nebula-card[data-card-size="lg"]'); + await expect(revealedCards).toHaveCount(3); + await expect(page.getByRole("button", { name: "Retour", exact: true })).toHaveCount(0); + await expect(revealedCards.first()).toHaveAttribute("data-reveal-phase", /aura|revealing/); + // L'ouverture montre le vrai format `lg`, 300 x 420 px, dès que les trois cartes tiennent. + const revealedBox = await revealedCards.first().boundingBox(); + expect([Math.round(revealedBox.width), Math.round(revealedBox.height)]).toEqual([300, 420]); + expect(await revealedCards.evaluateAll((cards) => cards.map((card) => card.ownerDocument.defaultView.getComputedStyle(card).opacity))).toEqual(["1", "1", "1"]); + await expect(revealedCards.first().locator(".nebula-card-face")).toHaveCSS("border-top-color", "rgb(103, 232, 249)"); + await expect(revealedCards.first().locator(".nebula-card-rarity-symbol")).toHaveCSS("color", "rgb(103, 232, 249)"); + await expect(revealedCards.first().locator(".nebula-card-particles i").first()).toHaveCSS("color", "rgb(255, 59, 48)"); + await expect(page.getByRole("button", { name: "Retour", exact: true })).toBeVisible(); + const revealedNames = await revealedCards.evaluateAll((cards) => cards.map((card) => card.getAttribute("aria-label").replace(/ révélée$/, ""))); + await expect.poll(() => page.evaluate(async () => (await globalThis.fetch("/api/cards/state")).json().then((state) => state.pendingOpening))).toBeNull(); + expect((await openingStage.boundingBox()).width).toBeLessThanOrEqual(1000); + await expect(page.locator(".nebula-opening-summary")).toHaveCount(0); + await page.setViewportSize({ width: 768, height: 900 }); + await expect(page.getByRole("button", { name: "Retour", exact: true })).toBeVisible(); + expect(await page.evaluate(() => globalThis.document.documentElement.scrollWidth <= globalThis.document.documentElement.clientWidth)).toBe(true); + await page.setViewportSize({ width: 1280, height: 720 }); + await page.getByRole("button", { name: "Retour", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Paquets permanents", exact: true })).toBeVisible(); + await expect(page).toHaveURL(/#\/cards\/packs$/); + // Une fois révélées, les cartes apparaissent en référence dans le journal. + await page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Historique", exact: true }).click(); + const historyCards = page.getByRole("list", { name: "Cartes obtenues" }).getByRole("listitem"); + await expect(historyCards).toHaveCount(3); + await expect(historyCards.first().getByRole("img")).toHaveAttribute("aria-label", /^(Commun|Rare|Épique|Légendaire|Mythique)$/); + await expect(historyCards.locator(".nds-badge").filter({ hasText: /· (Commun|Rare|Épique|Légendaire|Mythique)\b/ })).toHaveCount(0); + // La pastille de chaque carte prend la couleur de sa rareté (une légendaire n'a pas la couleur d'une commune). + expect(await historyCards.evaluateAll((items) => items.every((item) => { + const color = item.ownerDocument.defaultView.getComputedStyle(item.querySelector(".nebula-history-rarity")).backgroundColor; + return color === { common: "rgb(156, 163, 175)", rare: "rgb(59, 130, 246)", epic: "rgb(217, 70, 239)", legendary: "rgb(246, 196, 83)", mythic: "rgb(103, 232, 249)" }[item.dataset.rarity]; + }))).toBe(true); + for (const name of revealedNames) await expect(historyCards.filter({ hasText: name }).first()).toBeVisible(); + await expect(page.getByText("Cartes à révéler", { exact: true })).toHaveCount(0); + await page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Accueil", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Carte la plus rare tirée", exact: true })).toBeVisible(); + expect(revealedNames).toContain(await page.locator(".nebula-home-rarest-copy > strong").textContent()); + const rarestCard = page.locator('.nebula-home-rarest-card .nebula-card[data-card-size="md"]'); + await expect(rarestCard.locator(".nebula-card-art")).toBeVisible(); + await expect(rarestCard.locator(".nebula-card-art img")).toBeVisible(); + await expect(rarestCard.locator(".nebula-card-rarity-symbol")).toBeVisible(); + await expect(rarestCard.locator("h3")).toBeVisible(); + // La réserve occupe un tiers de la largeur et le meilleur tirage les deux tiers. + const homeReserveWidth = await page.locator(".nebula-home-grid .nebula-opening-reserve").evaluate((element) => element.getBoundingClientRect().width); + const homeRarestWidth = await page.locator(".nebula-home-rarest").evaluate((element) => element.getBoundingClientRect().width); + expect(homeRarestWidth / homeReserveWidth).toBeCloseTo(2, 0); + // La carte la plus rare ouvre la même fiche que l'album, en grand format. + const rarestName = await page.locator(".nebula-home-rarest-copy > strong").textContent(); + await page.getByRole("button", { name: `Voir ${rarestName}`, exact: true }).click(); + const rarestDialog = page.getByRole("dialog", { name: rarestName, exact: true }); + await expect(rarestDialog.locator('.nebula-card[data-card-size="lg"]')).toBeVisible(); + await expect(rarestDialog.locator("dl > div").filter({ hasText: "Exemplaires possédés" }).locator("dd")).toHaveText(/^[1-9]\d*$/); + await expect(rarestDialog.getByRole("button", { name: "Ajouter aux favoris" })).toBeVisible(); + await rarestDialog.getByRole("button", { name: "Fermer" }).click(); + await expect(rarestDialog).toHaveCount(0); + await page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Collection", exact: true }).click(); + await expect(page.getByRole("heading", { name: /Album/ })).toHaveCount(0); + await expect(page.getByRole("heading", { name: "Ma collection", exact: true, level: 2 })).toBeVisible(); + // L'album sépare les cartes par collection, dans l'ordre du catalogue ; un filtre masque les groupes vides. + await expect(page.locator(".nebula-album-group > h3")).toHaveText([/^La Nébuleuse Originelle \d+ \/ \d+$/, /^Genèse Astrale \d+ \/ \d+$/, /^Poussières d'étoiles \d+ \/ \d+$/]); + // Le titre porte le badge des éditions différentes possédées et une fine barre de progression. + const nebulaBadge = page.locator(".nebula-album-group > h3 .nds-badge").first(); + await expect(page.locator(".nebula-progress-tile")).toHaveCount(0); + await expect(page.locator(".nebula-album-group > .nds-progress")).toHaveCount(3); + await expect(nebulaBadge).toHaveText(/^[1-9]\d* \/ \d+$/); + await expect(page.locator(".nebula-album-group", { hasText: "Genèse Astrale" }).locator(".nebula-album-entry").first()).toBeVisible(); + // Les filtres reprennent les menus à cases à cocher des pages de jeux, avec leurs badges actifs. + await expect(page.locator(".nebula-album-filters")).toHaveAttribute("data-variant", "horizontal-menu"); + const albumFilters = page.locator(".nebula-album-filters"); + await albumFilters.getByRole("button", { name: "Collection", exact: true }).click(); + await albumFilters.getByRole("checkbox", { name: "Genèse Astrale" }).check(); + await page.keyboard.press("Escape"); + // Le menu passe au-dessus des cartes : sa dernière option reste cliquable, et un badge permet de la retirer. + await albumFilters.getByRole("button", { name: "Rareté", exact: true }).click(); + await albumFilters.getByRole("checkbox", { name: "Mythique" }).check(); + await page.keyboard.press("Escape"); + await albumFilters.getByRole("button", { name: "Retirer le filtre Rareté : Mythique" }).click(); + await expect(page.locator(".nebula-album-group > h3")).toHaveText([/^Genèse Astrale \d+ \/ \d+$/]); + // Le bouton de réinitialisation vide la recherche et remet tous les filtres à zéro. + await expect(albumFilters.getByRole("button", { name: "Retirer le filtre Collection : Genèse Astrale" })).toBeVisible(); + await page.getByPlaceholder("Rechercher...").first().fill("aucune carte ne porte ce nom"); + await expect(page.getByText("Aucune édition ne correspond à ces filtres.")).toBeVisible(); + await page.getByRole("button", { name: "Réinitialiser les filtres" }).click(); + await expect(page.getByPlaceholder("Rechercher...").first()).toHaveValue(""); + await expect(albumFilters.locator(".nds-active-filter")).toHaveCount(0); + await expect(page.locator(".nebula-album-group > h3")).toHaveCount(3); + // Au défilement, le menu collant reste sous le header au lieu de passer derrière. + await page.evaluate(() => globalThis.scrollTo(0, 900)); + await expect.poll(() => page.evaluate(() => globalThis.scrollY)).toBeGreaterThan(0); + const [topbarBottom, stickyNavTop] = await page.evaluate(() => [globalThis.document.querySelector(".topbar").getBoundingClientRect().bottom, globalThis.document.querySelector(".nebula-dashboard-nav").getBoundingClientRect().top]); + expect(stickyNavTop).toBeGreaterThanOrEqual(topbarBottom); + await page.evaluate(() => globalThis.scrollTo(0, 0)); + await expect(page.locator(".nebula-album-entry:not([data-missing])").first()).toBeVisible(); + await expect(page.locator(".nebula-card-concealed").first()).toBeVisible(); + await expect(page.locator('.nebula-card-concealed[data-card-size="md"]').first()).toBeVisible(); + await expect(page.locator(".nebula-card-concealed .nebula-card-face")).toHaveCount(0); + const undiscoveredCard = page.locator(".nebula-album-entry[data-undiscovered] .nebula-card-concealed").first(); + await expect(undiscoveredCard).toBeVisible(); + await expect(undiscoveredCard.locator(".nebula-card-tilt-surface")).toHaveCSS("filter", "grayscale(0.6) brightness(0.72)"); + await expect(undiscoveredCard.locator(".nebula-card-tilt-surface")).toHaveCSS("opacity", "0.7"); + expect((await undiscoveredCard.boundingBox()).width).toBeLessThanOrEqual(181); + const holographicCard = page.locator('.nebula-card[data-holo-effect="spectral-prism"][data-holo-palette="aurora"]').first(); + const cosmicCard = page.locator('.nebula-card[data-holo-effect="spectral-prism"][data-holo-palette="cosmic"]').first(); + await expect(holographicCard.locator(".nebula-card-holo-primary")).toBeAttached(); + await expect(holographicCard.locator(".nebula-card-holo-secondary")).toBeAttached(); + await expect(holographicCard).toHaveAttribute("data-card-size", "md"); + await expect(holographicCard.locator("h3")).toBeVisible(); + await expect(holographicCard.locator(".nebula-card-rarity-symbol")).toBeVisible(); + await expect(holographicCard.locator(".nebula-card-quantity")).toBeVisible(); + await expect(holographicCard.locator(".nebula-card-copy")).toHaveCount(0); + await expect(cosmicCard).toBeAttached(); + expect(await holographicCard.evaluate((element) => element.ownerDocument.defaultView.getComputedStyle(element).getPropertyValue("--holo-1").trim())).toBe("#0b5e4a"); + expect(await cosmicCard.evaluate((element) => element.ownerDocument.defaultView.getComputedStyle(element).getPropertyValue("--holo-1").trim())).toBe("#1e1b6b"); + const holographicGradient = await holographicCard.evaluate((element) => element.ownerDocument.defaultView.getComputedStyle(element).getPropertyValue("--holo-gradient").trim()); + const renderedSpectrum = await holographicCard.locator(".nebula-card-holo-primary").evaluate((element) => element.ownerDocument.defaultView.getComputedStyle(element).backgroundImage); + expect(holographicGradient).not.toMatch(/\d+%/); + expect(holographicGradient.match(/#[0-9a-f]{6}/gi)).toHaveLength(21); + expect(renderedSpectrum.match(/linear-gradient/g)).toHaveLength(1); + await expectArtworkFramed(holographicCard); + await expectFixedTitleBand(holographicCard, "bottom"); + await expectStandardCardFrame(holographicCard, "md"); + await expect.poll(() => holographicCard.locator(".nebula-card-art img").evaluate((image) => ({ width: image.naturalWidth, height: image.naturalHeight }))).toEqual({ width: 800, height: 800 }); + await expect(holographicCard.locator(".nebula-card-holo-primary")).toHaveCSS("background-repeat", "no-repeat"); + await holographicCard.scrollIntoViewIfNeeded(); + const bounds = await holographicCard.boundingBox(); + await page.mouse.move(bounds.x + bounds.width * 0.82, bounds.y + bounds.height * 0.24); + await expect.poll(() => holographicCard.evaluate((element) => Number.parseFloat(element.ownerDocument.defaultView.getComputedStyle(element).getPropertyValue("--card-tilt-y")))).toBeGreaterThan(1); + await expect(holographicCard.locator(".nebula-card-holo-primary")).toHaveCSS("opacity", "0.46"); + await expect(holographicCard.locator(".nebula-card-holo-primary")).toHaveCSS("animation-name", "nebula-spectral-prism"); + await expect(holographicCard.locator(".nebula-card-holo-secondary")).toHaveCSS("opacity", "0.28"); + await page.mouse.move(bounds.x + bounds.width + 5, bounds.y + bounds.height * 0.5); + await expect.poll(() => holographicCard.evaluate((element) => element.matches(":hover"))).toBe(true); + await expect(holographicCard.locator(".nebula-card-holo-primary")).toHaveCSS("opacity", "0.46"); + const tiltedHitbox = await holographicCard.boundingBox(); + expect(Math.abs(tiltedHitbox.x - bounds.x)).toBeLessThan(0.1); + expect(Math.abs(tiltedHitbox.y - bounds.y)).toBeLessThan(0.1); + await page.mouse.move(0, 0); + const tiltAfterLeave = await holographicCard.evaluate((element) => Math.abs(Number.parseFloat(element.ownerDocument.defaultView.getComputedStyle(element).getPropertyValue("--card-tilt-y")))); + expect(tiltAfterLeave).toBeGreaterThan(0.2); + await expect.poll(() => holographicCard.evaluate((element) => Math.abs(Number.parseFloat(element.ownerDocument.defaultView.getComputedStyle(element).getPropertyValue("--card-tilt-y"))))).toBeLessThan(0.1); + await holographicCard.click(); + const detailDialog = page.getByRole("dialog"); + const largeCard = detailDialog.locator('.nebula-card[data-card-size="lg"][data-holo-palette="aurora"]'); + await expect(detailDialog).toHaveCSS("overflow-x", "hidden"); + expect((await detailDialog.boundingBox()).width).toBeGreaterThan(900); + await expectArtworkFramed(largeCard); + await expectFixedTitleBand(largeCard, "top"); + await expectStandardCardFrame(largeCard, "lg"); + await expect(largeCard.locator(".nebula-card-copy p")).toBeVisible(); + await expect(largeCard.locator(".nebula-card-quantity")).toHaveCount(0); + const ownedCopiesLabel = detailDialog.getByText("Exemplaires possédés", { exact: true }); + await expect(ownedCopiesLabel).toBeVisible(); + await expect(ownedCopiesLabel).toHaveCSS("white-space", "nowrap"); + await expect(detailDialog.locator("dl > div").filter({ hasText: "Exemplaires possédés" }).locator("dd")).toHaveText(/^[1-9]\d*$/); + expect(await largeCard.evaluate((element) => ({ + holographicLayer: Number(element.ownerDocument.defaultView.getComputedStyle(element.querySelector(".nebula-card-holo-primary")).zIndex), + copy: Number(element.ownerDocument.defaultView.getComputedStyle(element.querySelector(".nebula-card-copy")).zIndex) + }))).toEqual({ holographicLayer: 2, copy: 3 }); + expect(await detailDialog.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(false); + await page.setViewportSize({ width: 768, height: 900 }); + expect(await detailDialog.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(false); + expect(await ownedCopiesLabel.evaluate((element) => { + const styles = element.ownerDocument.defaultView.getComputedStyle(element); + return element.getBoundingClientRect().height <= Number.parseFloat(styles.lineHeight) * 1.1; + })).toBe(true); + await detailDialog.getByRole("button", { name: "Fermer" }).click(); + await page.emulateMedia({ reducedMotion: "reduce" }); + await holographicCard.hover(); + await expect(holographicCard.locator(".nebula-card-tilt-surface")).toHaveCSS("transform", "none"); + await expect(holographicCard.locator(".nebula-card-holo-primary")).toHaveCSS("animation-name", "none"); + + await page.setViewportSize({ width: 768, height: 900 }); + const overflow = await page + .locator("html") + .evaluate((element) => element.scrollWidth > element.clientWidth); + expect(overflow).toBe(false); + + // Boutique : barème, recyclage et achat d'une ouverture (pas assez de poussière au départ). + await page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Boutique", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Boutique", exact: true })).toBeVisible(); + const shopItem = page.locator('.nebula-shop-item:not([data-item="pack"])'); + // Le paquet de la boutique se présente avec son dos et son prix, et reste hors de portée sans assez de poussière. + const shopPackItem = page.locator('.nebula-shop-item[data-item="pack"]'); + await expect(shopPackItem.getByRole("heading", { name: "Poussières d'étoiles" })).toBeVisible(); + await expect(shopPackItem.locator('img[src="/static/img/cards/stardust/back.webp"]')).toBeVisible(); + await expect(shopPackItem.getByRole("button", { name: "Acheter et ouvrir" })).toBeDisabled(); + await expect(shopPackItem).toContainText("Il vous manque 60 poussières."); + // Le solde ne met plus en avant les ouvertures achetées : la boutique est une grille d'articles illustrés. + await expect(page.locator(".nebula-shop-wallet")).not.toContainText("Ouvertures achetées"); + // Le solde est sous le menu, et la page se limite à son en-tête et à ses articles. + await expect(page.locator(".nebula-dashboard-aside-slot .nebula-shop-wallet")).toBeVisible(); + await expect(page.getByRole("heading", { name: "À échanger", exact: true })).toHaveCount(0); + await expect(shopItem.getByRole("button", { name: /Utiliser/ })).toHaveCount(0); + await expect(page.locator(".nebula-shop")).not.toContainText("doublon"); + const shopItemImage = shopItem.locator('.nds-card-cover img[src="/static/img/cards/shop/pack.webp"]'); + await expect(shopItemImage).toBeVisible(); + await expect.poll(() => shopItemImage.evaluate((image) => image.complete && image.naturalWidth)).toBeGreaterThan(0); + await expect(shopItem.getByRole("heading", { name: "Ouverture de paquet" })).toBeVisible(); + await expect(shopItem.getByRole("button", { name: "Acheter" })).toBeDisabled(); + await expect(shopItem).toContainText("Il vous manque 30 poussières."); + expect(await page.locator("html").evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(false); + await expect(page).toHaveURL(/#\/cards\/shop$/); + + // Le recyclage vit dans la Collection : plus d'entrée de menu, et l'ancienne adresse y mène. + await expect(page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Recyclage", exact: true })).toHaveCount(0); + await page.goto("/#/cards/recycling"); + await expect(page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Collection", exact: true })).toHaveAttribute("aria-current", "page"); + await expect(page.locator(".nebula-album-group").first()).toBeVisible(); + await expect(page.locator(".nebula-recycle-box")).toHaveCount(0); + expect(await page.locator("html").evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(false); + + // En demi-écran, le hero empile le texte et le compte au lieu d'écraser le titre. + await page.setViewportSize({ width: 768, height: 900 }); + expect(await page.locator(".nebula-player-hero > div").first().evaluate((element) => element.getBoundingClientRect().width)).toBeGreaterThan(400); + expect(await page.locator("html").evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(false); + await page.setViewportSize({ width: 1280, height: 720 }); + + // Échanges et dons : le type se choisit avec le groupe NDS et l'adresse de la section se recharge. + await page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Échanges et dons", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Échanges et dons", exact: true })).toBeVisible(); + await page.reload(); + await expect(page.getByRole("heading", { name: "Échanges et dons", exact: true })).toBeVisible(); + await expect(page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Échanges et dons", exact: true })).toHaveAttribute("aria-current", "page"); +}); + +test("administrator navigates sections, manages mythic content and previews visuals", async ({ page }) => { + test.setTimeout(90_000); + const noOverflow = async () => expect(await page.locator("html").evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(false); + await page.goto("/#/cards/admin"); + await page.getByRole("button", { name: "Version développement", exact: true }).click(); + await expect(page).toHaveURL(/#\/cards\/admin$/); + const backToGame = page.getByRole("link", { name: "Retour au jeu", exact: true }); + await expect(backToGame).toHaveAttribute("href", "#/cards"); + expect(await backToGame.evaluate((element) => element.nextElementSibling?.getAttribute("aria-label"))).toBe("Sections de l’administration"); + await expect(page.getByRole("navigation", { name: "Sections de Sokko TCG" })).toHaveCount(0); + await expect(page.getByRole("heading", { name: "Tableau de bord Sokko TCG", exact: true })).toBeVisible(); + const playersStat = page.locator(".nebula-dashboard-stat").filter({ has: page.getByText("Joueurs", { exact: true }) }); + await expect(playersStat.locator("strong")).toHaveText("2"); + await expect(playersStat.locator("small")).toHaveText(/^[0-9]+ actifs? sur 7 jours$/); + await expect(page.locator(".nebula-admin-alerts")).toContainText("Rien à signaler."); + await expect(page.locator(".nebula-dashboard-stat .nebula-dashboard-stat-label")).toHaveText(["Joueurs", "Collections actives", "Cartes différentes"]); + const collectionsStat = page.locator(".nebula-dashboard-stat").filter({ has: page.getByText("Collections actives", { exact: true }) }); + await expect(collectionsStat.locator("strong")).toHaveText("3"); + await expect(collectionsStat.locator("small")).toHaveText("sur 3 collections au total"); + await expect(page.locator(".nebula-dashboard-stat").filter({ has: page.getByText("Cartes différentes", { exact: true }) }).locator("small")).toHaveText(/^dont [0-9]+ variantes? mythiques?$/); + // Les joueurs sont dans la vue d'ensemble : l'ancienne adresse y redirige. + const players = page.locator(".nebula-admin-player-list"); + await expect(players.getByRole("columnheader")).toHaveText(["Joueur", "Paquets", "Dernier", "Cartes", "Échanges", "Réserve", "Poussière"]); + const devRow = players.getByRole("row", { name: /Version développement/ }); + await expect(devRow).toContainText(/[0-5] \/ 5/); + await expect(devRow.locator(".nebula-stardust")).toHaveText("✦0"); + + const navigation = page.getByRole("navigation", { name: "Sections de l’administration" }); + await expect(navigation.getByRole("link")).toHaveText(["Vue d’ensemble", "Collections", "Codes cadeaux", "Boutique", "Atelier visuel", "Historique"]); + await expect(navigation.getByRole("link", { name: "Vue d’ensemble" })).toHaveAttribute("aria-current", "page"); + await page.setViewportSize({ width: 1440, height: 900 }); + expect(await page.locator(".nebula-dashboard-aside").evaluate((element) => globalThis.getComputedStyle(element).position)).toBe("sticky"); + await page.setViewportSize({ width: 768, height: 720 }); + expect(await navigation.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true); + expect(await navigation.getByRole("link").evaluateAll((links) => new Set(links.map((link) => Math.round(link.getBoundingClientRect().top))).size)).toBe(1); + for (const link of await navigation.getByRole("link").all()) await expect(link).toBeInViewport(); + await noOverflow(); + + await page.goto("/#/cards/admin/players"); + await expect(navigation.getByRole("link", { name: "Vue d’ensemble" })).toHaveAttribute("aria-current", "page"); + await expect(players).toBeVisible(); + + await page.goto("/#/cards/admin/collections"); + await expect(navigation.getByRole("link", { name: "Collections" })).toHaveAttribute("aria-current", "page"); + const collectionTiles = page.locator(".nebula-admin-collection-tile"); + await expect(collectionTiles).toHaveCount(3); + const genesisTile = page.getByRole("link", { name: "Ouvrir la collection Genèse Astrale" }); + await expect(genesisTile).toContainText("Événement"); + await expect(genesisTile.locator(".nebula-admin-collection-counts > span")).toHaveText(["10cartes", "11variations", "1mythique tirable"]); + await expect(genesisTile.locator(".nebula-admin-rarity-counts b")).toHaveText(["4", "3", "2", "1", "1"]); + await expect(genesisTile).not.toContainText("Ouverture mythique"); + await expect(genesisTile.locator(".nebula-collection-back")).toBeVisible(); + const tileBackWidth = async () => Math.round((await genesisTile.locator(".nebula-admin-collection-back").boundingBox()).width); + expect(await tileBackWidth()).toBe(140); + await page.setViewportSize({ width: 1440, height: 900 }); + expect(await tileBackWidth()).toBe(180); + await page.setViewportSize({ width: 768, height: 720 }); + await expect(page.locator(".nebula-admin-catalog-card")).toHaveCount(0); + await noOverflow(); + + await page.getByRole("link", { name: "Ouvrir la collection La Nébuleuse Originelle" }).click(); + await expect(page).toHaveURL(/#\/cards\/admin\/collections\/primordial-nebula$/); + await expect(navigation.getByRole("link", { name: "Collections" })).toHaveAttribute("aria-current", "page"); + await expect(page.locator(".nebula-admin-collection-card")).toContainText("Primordial Nebula"); + const dragonCatalogCard = page.locator(".nebula-admin-catalog-card").filter({ hasText: "Dragon du Néant Étoilé" }).filter({ hasText: "Prisme spectral — Aurore" }); + await expect(dragonCatalogCard.locator('.nebula-card[data-card-size="sm"]')).toBeVisible(); + await dragonCatalogCard.getByRole("button", { name: "Voir Dragon du Néant Étoilé" }).click(); + const dragonDialog = page.getByRole("dialog", { name: "Dragon du Néant Étoilé" }); + await expect(dragonDialog.locator('.nebula-card[data-card-size="lg"]')).toBeVisible(); + await expect(dragonDialog).toContainText("Prisme spectral — Aurore"); + await dragonDialog.getByRole("button", { name: "Configurer la version mythique" }).click(); + await expect(dragonDialog).toHaveCount(0); + const dragonMythic = page.locator("#nebula-admin-mythic-starvoid-dragon"); + const mythicEditorPanel = page.locator("#nebula-admin-mythic-editor-panel"); + await expect(page.locator(".nebula-admin-mythic-tile")).toHaveCount(6); + await expect(dragonMythic.locator('.nebula-card[data-card-size="md"]')).toHaveCount(1); + await expect(dragonMythic.locator(".nebula-admin-mythic-hint")).toHaveText("2 mythiques"); + await expect(page.locator(".nebula-admin-catalog-card code")).toHaveCount(0); + const dragonTileButton = dragonMythic.getByRole("button", { name: "Configurer la version mythique de Dragon du Néant Étoilé" }); + await expect(dragonTileButton).toHaveAttribute("aria-pressed", "true"); + await expect(mythicEditorPanel.getByRole("heading", { name: "Version mythique · Dragon du Néant Étoilé" })).toBeVisible(); + await expect(mythicEditorPanel.getByRole("heading", { name: "Ouverture mythique de la carte" })).toBeVisible(); + await expect(mythicEditorPanel.locator(".nebula-admin-card-opening-block .nebula-card")).toHaveAttribute("data-card-size", "md"); + const trashButton = mythicEditorPanel.getByRole("button", { name: "Supprimer la variation Prisme spectral — Cosmique" }); + await expect(trashButton).toHaveAttribute("data-variant", "danger"); + await expect(trashButton).toHaveClass(/nds-icon-button/); + await expect(trashButton).not.toHaveText(/./); + await expect(mythicEditorPanel.getByRole("button", { name: "Retirer Prisme spectral — Aurore des tirages" })).toHaveClass(/ui-tooltip-anchor/); + const dragonVariations = mythicEditorPanel.locator(".nebula-admin-mythic-variation"); + await expect(dragonVariations).toHaveCount(2); + await expect(dragonVariations.locator("strong")).toHaveText(["Aurore", "Cosmique"]); + await expect(dragonVariations.locator('.nebula-card[data-card-size="sm"]')).toHaveCount(2); + await expect(mythicEditorPanel.getByRole("button", { name: "Ajouter une variation" })).toBeVisible(); + await dragonVariations.nth(1).getByRole("button", { name: "Prévisualiser Prisme spectral — Cosmique" }).click(); + await expect(dragonVariations.nth(1)).toHaveAttribute("data-selected", "true"); + await expect(mythicEditorPanel.locator(".nebula-admin-card-opening-block")).toContainText("Prisme spectral — Cosmique"); + await mythicEditorPanel.getByRole("button", { name: "Fermer" }).click(); + await expect(mythicEditorPanel).toHaveCount(0); + await expect(dragonTileButton).toHaveAttribute("aria-pressed", "false"); + await noOverflow(); + + await page.getByRole("navigation", { name: "Fil d’Ariane" }).getByRole("link", { name: "Collections" }).click(); + await expect(page).toHaveURL(/#\/cards\/admin\/collections$/); + await genesisTile.click(); + await expect(page).toHaveURL(/#\/cards\/admin\/collections\/astral-genesis$/); + const genesisOpening = page.getByRole("region", { name: "Ouverture mythique de la collection" }); + await expectOptions(page, genesisOpening, "Forme de particules", ["Étincelles (défaut)", "Flocons de neige"]); + await expectOptions(page, genesisOpening, "Palette de particules", ["Violet épique", "Or légendaire", "Arc-en-ciel (défaut)", "Comme la palette holo"]); + await page.setViewportSize({ width: 1440, height: 900 }); + // En grand, taux de tirage et ouverture mythique côte à côte (50:50), de même hauteur, sans défilement du tableau. + const openingBox = await genesisOpening.boundingBox(); + const ratesBox = await page.getByRole("region", { name: "Taux de tirage" }).boundingBox(); + expect(Math.abs(openingBox.width - ratesBox.width)).toBeLessThanOrEqual(1); + expect(Math.abs(openingBox.height - ratesBox.height)).toBeLessThanOrEqual(1); + expect(await page.locator(".nebula-admin-drop-scroll").evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true); + expect(openingBox.x).toBeGreaterThan(ratesBox.x + ratesBox.width); + expect(Math.abs(openingBox.y - ratesBox.y)).toBeLessThanOrEqual(1); + await page.setViewportSize({ width: 900, height: 900 }); + const [stackedOpening, stackedRates] = await Promise.all([genesisOpening.boundingBox(), page.getByRole("region", { name: "Taux de tirage" }).boundingBox()]); + expect(stackedOpening.y).toBeGreaterThan(stackedRates.y + stackedRates.height); + expect(Math.abs(stackedOpening.width - stackedRates.width)).toBeLessThanOrEqual(1); + await page.setViewportSize({ width: 1440, height: 900 }); + await chooseOption(genesisOpening, "Forme de particules", "Flocons de neige"); + await expect(selectTrigger(genesisOpening, "Forme de particules")).toHaveText("Flocons de neige"); + await expect(genesisOpening).toHaveCSS("overflow", "visible"); + // Les deux menus côte à côte, à la même hauteur. + const [shapeBox, paletteBox] = await Promise.all([selectTrigger(genesisOpening, "Forme de particules").boundingBox(), selectTrigger(genesisOpening, "Palette de particules").boundingBox()]); + expect(Math.abs(shapeBox.y - paletteBox.y)).toBeLessThanOrEqual(1); + expect(shapeBox.x + shapeBox.width).toBeLessThan(paletteBox.x); + await genesisOpening.getByRole("button", { name: "Révéler la carte mythique de la collection" }).click(); + await expect(genesisOpening.locator(".nebula-card-reveal")).toHaveAttribute("data-particle-shape", "snowflakes"); + await expect(genesisOpening.locator(".nebula-card-particles i").first()).toBeAttached(); + await noOverflow(); + + const mythicPullEditions = page.locator(".nebula-admin-catalog-card").filter({ hasText: "La Pioche Mythique" }); + await expect(mythicPullEditions).toHaveCount(2); + const pullItem = page.locator("#nebula-admin-mythic-mythic-card-pull"); + await pullItem.getByRole("button", { name: "Configurer la version mythique de La Pioche Mythique" }).click(); + const editor = page.locator("#nebula-admin-mythic-editor-panel .nebula-admin-mythic-editor"); + const variations = editor.locator(".nebula-admin-mythic-variation"); + await expect(variations).toHaveCount(1); + await expect(variations.first().locator("strong")).toHaveText("Solaire"); + await expect(variations.first().locator(".nebula-admin-mythic-variation-specs dd")).toHaveText(["Standard", "Prisme spectral", "À venir"]); + await expect(editor.getByRole("button", { name: "Enregistrer" })).toHaveCount(0); + const cardOpening = editor.getByRole("group", { name: "Ouverture mythique de la carte" }); + await expectOptions(page, cardOpening, "Forme de particules", ["Étincelles", "Flocons de neige (hérité de la collection)"]); + await expect(selectTrigger(cardOpening, "Forme de particules")).toHaveText("Flocons de neige (hérité de la collection)"); + await selectTrigger(cardOpening, "Palette de particules").click(); + await expect(cardOpening.getByRole("option", { name: /Arc-en-ciel/ })).toHaveText(["Arc-en-ciel (défaut)"]); + await page.keyboard.press("Escape"); + await editor.getByRole("button", { name: "Ajouter une variation" }).click(); + await expect(variations).toHaveCount(2); + await expect(variations.nth(1).getByRole("button", { name: "Palette holographique : Arc-en-ciel" })).toBeVisible(); + await expect(selectTrigger(variations.nth(1), "Particules")).toBeDisabled(); + await expect(variations.nth(1)).toHaveAttribute("data-selected", "true"); + await expect(editor.getByRole("button", { name: "Ajouter une variation" })).toHaveCount(0); + const draftActions = variations.nth(1).locator(".nebula-admin-mythic-variation-actions .nds-icon-button"); + await expect(draftActions).toHaveCount(2); + await expect(draftActions.first()).toHaveAccessibleName("Valider la nouvelle variation"); + await expect(draftActions.first()).toHaveAttribute("data-variant", "primary"); + await expect(draftActions.nth(1)).toHaveAccessibleName("Annuler la nouvelle variation"); + await variations.nth(1).getByLabel("Palette holographique").click(); + await variations.nth(1).getByRole("button", { name: "Solaire", exact: true }).click(); + await expect(variations.nth(1).getByRole("status")).toHaveText("Cette combinaison existe déjà."); + await expect(draftActions.first()).toBeDisabled(); + await draftActions.nth(1).click(); + await expect(variations).toHaveCount(1); + await editor.getByRole("button", { name: "Ajouter une variation" }).click(); + await expect(variations).toHaveCount(2); + const variationColumns = () => editor.locator(".nebula-admin-mythic-variations").evaluate((element) => globalThis.getComputedStyle(element).gridTemplateColumns.trim().split(/\s+/).length); + await page.setViewportSize({ width: 2560, height: 1080 }); + expect(await variationColumns()).toBe(3); + const copyBesideCard = async () => { + const [cardBox, copyBox] = await Promise.all([variations.first().locator(".nebula-card").boundingBox(), variations.first().locator(".nebula-admin-mythic-variation-copy").boundingBox()]); + return copyBox.x >= cardBox.x + cardBox.width - 1; + }; + expect(await copyBesideCard()).toBe(true); + await page.setViewportSize({ width: 1440, height: 900 }); + expect(await variationColumns()).toBe(3); + expect(await copyBesideCard()).toBe(false); + await page.setViewportSize({ width: 768, height: 720 }); + expect(await variationColumns()).toBe(3); + // En demi-écran comme en grand, le menu de palette de la dernière colonne se recale au lieu d'être coupé. + await page.setViewportSize({ width: 1440, height: 900 }); + await variations.nth(1).scrollIntoViewIfNeeded(); + await variations.nth(1).getByRole("button", { name: "Palette holographique : Arc-en-ciel" }).click(); + await expectOpenMenuVisible(page, ".nebula-admin-palette-menu.is-open"); + await page.keyboard.press("Escape"); + await page.evaluate(() => globalThis.scrollTo(0, globalThis.document.documentElement.scrollHeight)); + await variations.nth(1).getByRole("button", { name: "Palette holographique : Arc-en-ciel" }).click(); + await expectOpenMenuVisible(page, ".nebula-admin-palette-menu.is-open"); + await page.keyboard.press("Escape"); + await page.setViewportSize({ width: 768, height: 720 }); + await variations.nth(1).getByRole("button", { name: "Palette holographique : Arc-en-ciel" }).click(); + const lastPaletteOption = variations.nth(1).getByRole("button", { name: "Ténèbres", exact: true }); + await expect(lastPaletteOption).toBeVisible(); + await lastPaletteOption.scrollIntoViewIfNeeded(); + // L'événement de défilement part à la frame suivante : le menu doit rester défilé après son traitement. + await page.evaluate(() => new Promise((done) => globalThis.requestAnimationFrame(() => globalThis.requestAnimationFrame(done)))); + expect(await lastPaletteOption.evaluate((element) => { + const box = element.getBoundingClientRect(); + return element.contains(element.ownerDocument.elementFromPoint(box.left + box.width / 2, box.bottom - 4)); + })).toBe(true); + await page.keyboard.press("Escape"); + await chooseOption(cardOpening, "Palette de particules", "Comme la palette holo"); + await expect(selectTrigger(cardOpening, "Palette de particules")).toHaveText("Comme la palette holo"); + await expect(variations).toHaveCount(2); + await editor.getByRole("button", { name: "Révéler la variation mythique" }).click(); + const editorSurface = editor.locator(".nebula-card-reveal"); + await expect(editorSurface).toHaveAttribute("data-particle-shape", "snowflakes"); + await expect(editorSurface).toHaveAttribute("data-particle-palette", "match-holo"); + await expect(editorSurface).toHaveCSS("--opening-aura", "#ff0000"); + await editor.getByRole("button", { name: "Valider la nouvelle variation" }).click(); + await expect(editor.locator(".nebula-admin-mythic-variation[data-new]")).toHaveCount(0); + await expect(editor.locator(".nebula-admin-mythic-variation")).toHaveCount(2); + await expect(editor.locator(".nebula-admin-mythic-variation strong")).toHaveText(["Arc-en-ciel", "Solaire"]); + await expect(editor.getByRole("button", { name: "Ajouter une variation" })).toBeVisible(); + await expect(selectTrigger(editor.getByRole("group", { name: "Ouverture mythique de la carte" }), "Palette de particules")).toHaveText("Comme la palette holo"); + await expect(mythicPullEditions).toHaveCount(3); + await noOverflow(); + + const config = await page.evaluate(() => globalThis.fetch("/api/cards/config").then((response) => response.json())); + expect(config.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-rainbow")).toBe(true); + expect(config.catalog.mythicOpeningSettings).toEqual(expect.arrayContaining([ + { scope: "card", targetId: "mythic-card-pull", particleShapeId: null, particlePaletteId: "match-holo" }, + { scope: "collection", targetId: "astral-genesis", particleShapeId: "snowflakes", particlePaletteId: null } + ])); + await editor.getByRole("button", { name: "Supprimer la variation Prisme spectral — Arc-en-ciel" }).click(); + const removalDialog = page.getByRole("dialog", { name: "Supprimer Prisme spectral — Arc-en-ciel ?" }); + await removalDialog.getByRole("button", { name: "Annuler" }).click(); + await expect(editor.locator(".nebula-admin-mythic-variation")).toHaveCount(2); + await editor.getByRole("button", { name: "Supprimer la variation Prisme spectral — Arc-en-ciel" }).click(); + await removalDialog.getByRole("button", { name: "Supprimer" }).click(); + await expect(editor.locator(".nebula-admin-mythic-variation")).toHaveCount(1); + await chooseOption(editor.getByRole("group", { name: "Ouverture mythique de la carte" }), "Palette de particules", INHERITED); + await expect(selectTrigger(editor.getByRole("group", { name: "Ouverture mythique de la carte" }), "Palette de particules")).toHaveText(INHERITED); + await chooseOption(genesisOpening, "Forme de particules", INHERITED); + await expect(selectTrigger(genesisOpening, "Forme de particules")).toHaveText(INHERITED); + await expect(mythicPullEditions).toHaveCount(2); + + await page.goto("/#/cards/admin/catalog/inconnue"); + await expect(page.getByText("Cette collection n’existe pas.", { exact: true })).toBeVisible(); + + await navigation.getByRole("link", { name: "Atelier visuel" }).click(); + await expect(page).toHaveURL(/#\/cards\/admin\/visual-lab$/); + const openingEffects = page.locator(".nebula-admin-opening-effect-card"); + await expect(openingEffects).toHaveCount(4); + await expect(openingEffects.locator(".eyebrow")).toHaveText(["Effet de rareté", "Effet de rareté", "Effet de rareté", "Effet de rareté"]); + await expect(openingEffects.locator("h4")).toHaveText(["Mythique", "Rare", "Épique", "Légendaire"]); + await expect(openingEffects.first().locator(".nebula-admin-style-preview > span")).toHaveText(/^Aperçu · .+ — Prisme spectral — /); + const holoSectionBox = await page.getByRole("heading", { name: /Effets holographiques mythiques/ }).boundingBox(); + const openingSectionBox = await page.getByRole("heading", { name: /Effets d’ouverture/ }).boundingBox(); + expect(holoSectionBox.y).toBeLessThan(openingSectionBox.y); + const openingColumns = () => page.locator('[data-opening-group="rarities"]').evaluate((element) => element.ownerDocument.defaultView.getComputedStyle(element).gridTemplateColumns.trim().split(/\s+/).length); + expect(await openingColumns()).toBe(2); + await noOverflow(); + await page.setViewportSize({ width: 1440, height: 900 }); + expect(await openingColumns()).toBe(3); + const mythicOpeningCard = openingEffects.filter({ has: page.getByRole("heading", { name: "Mythique", exact: true }) }); + const legendaryOpeningCard = openingEffects.filter({ has: page.getByRole("heading", { name: "Légendaire", exact: true }) }); + const [mythicBox, legendaryBox, gridBox] = await Promise.all([mythicOpeningCard.boundingBox(), legendaryOpeningCard.boundingBox(), page.locator('[data-opening-group="rarities"]').boundingBox()]); + expect(mythicBox.y + mythicBox.height).toBeLessThan(legendaryBox.y + 1); + expect(Math.round(mythicBox.width)).toBe(760); + expect(Math.abs((mythicBox.x - gridBox.x) - (gridBox.x + gridBox.width - mythicBox.x - mythicBox.width))).toBeLessThanOrEqual(1); + + const effectStyles = page.locator(".nebula-admin-effect-grid .nebula-admin-style-card"); + await expect(effectStyles.locator("h4")).toHaveText(["Prisme spectral", "Reflet diffractif"]); + const spectralStyle = effectStyles.filter({ has: page.getByRole("heading", { name: "Prisme spectral", exact: true }) }); + // Les aperçus holographiques gardent le vrai format `lg`, 300 x 420 px. + const holoPreviewBox = await spectralStyle.locator(".nebula-admin-style-preview > .nebula-card").boundingBox(); + expect([Math.round(holoPreviewBox.width), Math.round(holoPreviewBox.height)]).toEqual([300, 420]); + // Pleine illustration : l'image remplit la carte, la description disparaît et le nom reste, avec son effet métallique. + await chooseOption(spectralStyle, "Format", "Pleine illustration"); + const fullArtCard = spectralStyle.locator('.nebula-card[data-card-layout="full-art"][data-holo-effect="spectral-prism"]'); + await expect(fullArtCard.locator('.nebula-card-art img[src$="/astral-genesis/legendary/mythic_card_pull__full.webp"]')).toBeVisible(); + await expect(fullArtCard.locator(".nebula-card-copy")).toHaveCount(0); + await expect(fullArtCard.locator("h3")).toBeVisible(); + await expect(fullArtCard.locator("h3 > span")).toHaveCSS("color", "rgba(0, 0, 0, 0)"); + // Une ombre de texte se peindrait par-dessus le dégradé et ternirait le nom. + await expect(fullArtCard.locator("h3 > span")).toHaveCSS("text-shadow", "none"); + const fullArtBounds = await fullArtCard.evaluate((element) => { + const face = element.querySelector(".nebula-card-face").getBoundingClientRect(); + const art = element.querySelector(".nebula-card-art").getBoundingClientRect(); + return { widthGap: face.width - art.width, heightGap: face.height - art.height }; + }); + expect(fullArtBounds.widthGap).toBeLessThanOrEqual(5); + expect(fullArtBounds.heightGap).toBeLessThanOrEqual(5); + await chooseOption(spectralStyle, "Format", "Standard"); + await expect(spectralStyle).toHaveCount(1); + await expect(spectralStyle.locator('.nebula-card[data-card-size="lg"]')).toHaveCount(1); + await expect(spectralStyle.locator('.nebula-card-art img[src$="/astral-genesis/legendary/mythic_card_pull.webp"]')).toHaveCount(1); + await expect(spectralStyle.getByRole("heading", { name: "Prisme spectral", exact: true })).toBeVisible(); + await expect(selectTrigger(spectralStyle, "Particules au survol")).toBeDisabled(); + await expect(selectTrigger(spectralStyle, "Particules au survol")).toHaveText("À venir"); + const paletteTrigger = spectralStyle.getByRole("button", { name: "Palette de couleurs : Arc-en-ciel" }); + const paletteTriggerLabel = paletteTrigger.getByText("Arc-en-ciel", { exact: true }); + await expect(paletteTriggerLabel).toBeVisible(); + expect(await paletteTriggerLabel.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true); + await expect(paletteTrigger.locator('.nebula-admin-palette[data-compact="true"] i').first()).toHaveCSS("width", "12px"); + await paletteTrigger.click(); + await expect(spectralStyle).toHaveCSS("overflow", "visible"); + const solarPaletteOption = spectralStyle.getByRole("button", { name: "Solaire", exact: true }); + await expect(solarPaletteOption.locator('.nebula-admin-palette[data-compact="true"] i')).toHaveCount(7); + await solarPaletteOption.click(); + await expect(spectralStyle.getByRole("button", { name: "Palette de couleurs : Solaire" })).toBeVisible(); + await expect(spectralStyle.locator('.nebula-card[data-holo-palette="solar"], .nebula-card-face[data-holo-palette="solar"]').first()).toBeVisible(); + + // Reflet diffractif : mêmes réglages que le prisme, mais tout découle du tilt, sans animation automatique. + const diffractionStyle = effectStyles.filter({ has: page.getByRole("heading", { name: "Reflet diffractif", exact: true }) }); + const diffractionCard = diffractionStyle.locator(".nebula-admin-style-preview > .nebula-card"); + const diffractionLayer = diffractionCard.locator(".nebula-card-holo-primary"); + await chooseOption(diffractionStyle, "Format", "Pleine illustration"); + await expect(diffractionCard).toHaveAttribute("data-card-layout", "full-art"); + await chooseOption(diffractionStyle, "Format", "Standard"); + await diffractionStyle.getByRole("button", { name: "Palette de couleurs : Arc-en-ciel" }).click(); + await diffractionStyle.getByRole("button", { name: "Solaire", exact: true }).click(); + await expect(diffractionCard).toHaveAttribute("data-holo-palette", "solar"); + await expect(selectTrigger(diffractionStyle, "Particules au survol")).toHaveText("À venir"); + await diffractionCard.scrollIntoViewIfNeeded(); + await expect(diffractionLayer).toHaveCSS("opacity", "0.05"); + const diffractionBox = await diffractionCard.boundingBox(); + const tiltTo = async (ratioX, ratioY) => { + await page.mouse.move(diffractionBox.x + diffractionBox.width * ratioX, diffractionBox.y + diffractionBox.height * ratioY); + await expect.poll(() => diffractionCard.evaluate((element, expected) => Math.abs(Number.parseFloat(element.style.getPropertyValue("--card-pointer-x")) - expected), ratioX * 100)).toBeLessThan(1); + return diffractionLayer.evaluate((element) => { + const style = element.ownerDocument.defaultView.getComputedStyle(element); + return { opacity: Number(style.opacity), position: style.backgroundPosition, animation: style.animationName }; + }); + }; + const flat = await tiltTo(0.5, 0.5); + const tilted = await tiltTo(0.95, 0.9); + expect(flat.animation).toBe("none"); + expect(tilted.animation).toBe("none"); + expect(tilted.opacity).toBeGreaterThan(flat.opacity + 0.2); + expect(tilted.position).not.toBe(flat.position); + await page.mouse.move(0, 0); + await expect.poll(() => diffractionLayer.evaluate((element) => Number(element.ownerDocument.defaultView.getComputedStyle(element).opacity))).toBeLessThan(0.07); + + const rarePreview = openingEffects.filter({ has: page.locator('[data-opening-effect="rare-opening"]') }); + const rareCard = rarePreview.getByRole("button", { name: "Révéler la carte Rare", exact: true }); + const rareSurface = rarePreview.locator(".nebula-card-reveal"); + await rareCard.focus(); + await rareCard.press("Enter"); + await expect(rareSurface).toHaveAttribute("data-reveal-phase", "aura"); + await expect(rareSurface).not.toHaveAttribute("disabled", ""); + await expect(rareSurface).toHaveCSS("opacity", "1"); + await expect(rareSurface).toHaveCSS("--card-rarity", "#3b82f6"); + await expect(rareSurface).toHaveCSS("--opening-aura", "#3b82f6"); + expect(await rareSurface.evaluate((element) => element.ownerDocument.defaultView.getComputedStyle(element, "::after").animationName)).toBe("nebula-opening-aura"); + await expect(rareSurface.locator(".nebula-card-particles i")).toHaveCount(0); + await expect(rarePreview.getByRole("button", { name: "Remettre la carte Rare face cachée", exact: true })).toHaveAttribute("data-reveal-phase", "revealed"); + await rarePreview.getByRole("button", { name: "Remettre la carte Rare face cachée", exact: true }).click(); + await expect(rarePreview.getByRole("button", { name: "Révéler la carte Rare", exact: true })).toHaveAttribute("data-reveal-phase", "concealed"); + + const epicPreview = openingEffects.filter({ has: page.locator('[data-opening-effect="epic-opening"]') }); + const epicCard = epicPreview.getByRole("button", { name: "Révéler la carte Épique", exact: true }); + const epicSurface = epicPreview.locator(".nebula-card-reveal"); + await epicCard.click(); + await expect(epicSurface).toHaveAttribute("data-reveal-phase", "aura"); + await expect(epicSurface).toHaveCSS("--card-rarity", "#d946ef"); + await expect(epicSurface).toHaveCSS("--opening-aura", "#d946ef"); + await expect(epicSurface.locator(".nebula-card-particles i")).toHaveCount(18); + await expect(epicSurface.locator(".nebula-card-particles i").first()).toHaveCSS("animation-name", "nebula-particle"); + await expect(epicPreview.getByRole("button", { name: "Remettre la carte Épique face cachée", exact: true })).toHaveAttribute("data-reveal-phase", "revealed"); + + const legendaryPreview = openingEffects.filter({ has: page.locator('[data-opening-effect="legendary-opening"]') }); + const legendaryCard = legendaryPreview.getByRole("button", { name: "Révéler la carte Légendaire", exact: true }); + const legendarySurface = legendaryPreview.locator(".nebula-card-reveal"); + await legendaryCard.click(); + await expect(legendarySurface).toHaveAttribute("data-reveal-phase", "aura"); + await expect(legendarySurface).toHaveCSS("--opening-aura", "#f6c453"); + await expect(legendarySurface.locator(".nebula-card-particles i")).toHaveCount(32); + await expect(legendaryPreview.getByRole("button", { name: "Remettre la carte Légendaire face cachée", exact: true })).toHaveAttribute("data-reveal-phase", "revealed"); + + await legendaryPreview.getByRole("button", { name: "Remettre la carte Légendaire face cachée", exact: true }).click(); + await expect(legendaryPreview.getByRole("button", { name: "Révéler la carte Légendaire", exact: true })).toHaveAttribute("data-reveal-phase", "concealed"); + await page.emulateMedia({ reducedMotion: "reduce" }); + await legendaryPreview.getByRole("button", { name: "Révéler la carte Légendaire", exact: true }).click(); + await expect(legendaryPreview.getByRole("button", { name: "Remettre la carte Légendaire face cachée", exact: true })).toHaveAttribute("data-reveal-phase", "revealed"); + await expect(legendarySurface.locator(".nebula-card-particles")).toHaveCSS("display", "none"); + await page.emulateMedia({ reducedMotion: "no-preference" }); + const legendaryBurstVisual = await legendarySurface.locator(".nebula-card-particles").evaluate((element) => { + const styles = element.ownerDocument.defaultView; + const normalizeColors = (value) => value.replace(/(?:rgba?|color)\([^)]*\)/g, ""); + const before = styles.getComputedStyle(element, "::before"); + const after = styles.getComputedStyle(element, "::after"); + const particle = styles.getComputedStyle(element.querySelector("i")); + return { + geometry: { + ring: { width: before.width, height: before.height, border: before.borderWidth, radius: before.borderRadius, shadow: normalizeColors(before.boxShadow), animation: before.animationName, duration: before.animationDuration, easing: before.animationTimingFunction }, + rays: { width: after.width, height: after.height, radius: after.borderRadius, filter: normalizeColors(after.filter), animation: after.animationName, duration: after.animationDuration, easing: after.animationTimingFunction }, + particle: { width: particle.width, height: particle.height, radius: particle.borderRadius, clipPath: particle.clipPath, animation: particle.animationName, duration: particle.animationDuration, easing: particle.animationTimingFunction, x: particle.getPropertyValue("--x"), y: particle.getPropertyValue("--y") }, + particleSizes: [...element.querySelectorAll("i")].map((item) => `${styles.getComputedStyle(item).width}x${styles.getComputedStyle(item).height}`).join(" ") + }, + paint: { ringBackground: before.backgroundImage, ringMask: before.maskImage || before.webkitMaskImage, rayBackground: after.backgroundImage, rayMask: after.maskImage || after.webkitMaskImage } + }; + }); + expect(legendaryBurstVisual.geometry.ring.width).toBe("92px"); + expect(legendaryBurstVisual.geometry.ring.height).toBe("92px"); + expect(legendaryBurstVisual.geometry.ring.border).toBe("6px"); + expect(legendaryBurstVisual.paint.ringBackground).toBe("none"); + expect(legendaryBurstVisual.paint.ringMask).toBe("none"); + expect(legendaryBurstVisual.geometry.rays.width).toBe("260px"); + expect(legendaryBurstVisual.geometry.rays.height).toBe("260px"); + expect(legendaryBurstVisual.paint.rayBackground).toContain("repeating-conic-gradient"); + expect(legendaryBurstVisual.paint.rayMask).toContain("radial-gradient"); + expect(legendaryBurstVisual.paint.rayMask).not.toContain("repeating-conic-gradient"); + expect(legendaryBurstVisual.geometry.rays.filter).toContain("drop-shadow"); + expect(legendaryBurstVisual.geometry.rays.animation).toBe("nebula-particle-flash"); + expect(legendaryBurstVisual.geometry.rays.duration).toBe("0.68s"); + await expect(legendarySurface.locator(".nebula-card-particle-ring-glow")).toHaveCount(0); + const legendaryAuraBase = await legendarySurface.evaluate((element) => { + const style = globalThis.getComputedStyle(element, "::after"); + const normalizeColors = (value) => value.replace(/(?:rgba?|color)\([^)]*\)/g, ""); + return { inset: style.inset, border: style.borderWidth, radius: style.borderRadius, background: normalizeColors(style.backgroundImage), shadow: normalizeColors(style.boxShadow), filter: normalizeColors(style.filter), mask: style.maskImage || style.webkitMaskImage }; + }); + + await expect(legendarySurface).not.toHaveAttribute("data-aura-palette"); + await expect(legendarySurface.locator(".nebula-card-glow-palette, .nebula-card-opening-glow-palette")).toHaveCount(0); + const mythicPreview = openingEffects.filter({ has: page.locator('[data-opening-effect="mythic-default-opening"]') }); + const mythicSurface = mythicPreview.locator(".nebula-card-reveal"); + await expect(mythicPreview).not.toContainText("Effet personnalisé"); + await expect(mythicSurface).toHaveCSS("--card-rarity", "#67e8f9"); + await expect(mythicSurface).toHaveAttribute("data-particle-shape", "sparks"); + await expect(mythicSurface).toHaveAttribute("data-particle-palette", "rainbow"); + await expect(mythicPreview.getByRole("button", { name: "Forme de particules : Étincelles" })).toBeVisible(); + const particlePaletteTrigger = mythicPreview.getByRole("button", { name: "Palette de particules : Arc-en-ciel" }); + await expect(particlePaletteTrigger.locator('.nebula-admin-palette[data-compact="true"] i')).toHaveCount(7); + await particlePaletteTrigger.click(); + await mythicPreview.getByRole("button", { name: "Violet épique", exact: true }).click(); + await expect(mythicSurface).toHaveAttribute("data-particle-palette", "epic-violet"); + await expect(mythicSurface).toHaveCSS("--opening-aura-secondary", "#f0abfc"); + expect(await mythicSurface.evaluate((element) => element.style.getPropertyValue("--opening-aura-gradient"))).toBe("conic-gradient(from 15deg, #ffffff, #f0abfc, #d946ef, #a21caf, #ffffff)"); + const violetRayVisual = await mythicSurface.evaluate((element) => { + const particles = element.ownerDocument.createElement("span"); + particles.className = "nebula-card-particles"; + element.append(particles); + const style = globalThis.getComputedStyle(particles, "::after"); + const visual = { background: style.backgroundImage, mask: style.maskImage || style.webkitMaskImage }; + particles.remove(); + return visual; + }); + await mythicPreview.getByRole("button", { name: "Palette de particules : Violet épique" }).click(); + await mythicPreview.getByRole("button", { name: "Arc-en-ciel", exact: true }).click(); + const rainbowRayVisual = await mythicSurface.evaluate((element) => { + const particles = element.ownerDocument.createElement("span"); + particles.className = "nebula-card-particles"; + element.append(particles); + const style = globalThis.getComputedStyle(particles, "::after"); + const visual = { background: style.backgroundImage, mask: style.maskImage || style.webkitMaskImage }; + particles.remove(); + return visual; + }); + expect(violetRayVisual.mask).toBe(rainbowRayVisual.mask); + expect(rainbowRayVisual.mask).toContain("repeating-conic-gradient"); + expect(rainbowRayVisual.mask).toContain("18deg"); + expect(violetRayVisual.background).toContain("rgb(217, 70, 239)"); + expect(rainbowRayVisual.background).toContain("rgb(52, 199, 89)"); + const mythicCard = mythicPreview.getByRole("button", { name: "Révéler la carte Mythique", exact: true }); + await mythicPreview.getByRole("button", { name: "Forme de particules : Étincelles" }).click(); + await expect(mythicPreview.getByRole("button", { name: "Flocons de neige", exact: true })).toBeVisible(); + await mythicPreview.getByRole("button", { name: "Flocons de neige", exact: true }).click(); + await expect(mythicSurface).toHaveAttribute("data-particle-shape", "snowflakes"); + await mythicCard.click(); + await expect(mythicSurface.locator(".nebula-card-particles i")).toHaveCount(48); + const snowflakeVisual = await mythicSurface.locator(".nebula-card-particles").evaluate((element) => { + const styles = element.ownerDocument.defaultView; + const before = styles.getComputedStyle(element, "::before"); + const after = styles.getComputedStyle(element, "::after"); + const particle = element.querySelectorAll("i"); + const flake = styles.getComputedStyle(particle[0], "::before"); + return { + ring: { width: before.width, border: before.borderWidth, mask: before.maskImage || before.webkitMaskImage }, + rays: { width: after.width, animation: after.animationName }, + sizes: [particle[0], particle[2]].map((item) => styles.getComputedStyle(item).width), + particleAnimation: styles.getComputedStyle(particle[0]).animationName, + flakeMask: flake.maskImage || flake.webkitMaskImage, + clipPath: styles.getComputedStyle(particle[0]).clipPath + }; + }); + expect(snowflakeVisual.ring).toEqual({ width: "92px", border: "6px", mask: expect.stringContaining("radial-gradient") }); + expect(snowflakeVisual.rays).toEqual({ width: "260px", animation: "nebula-particle-flash" }); + expect(snowflakeVisual.sizes).toEqual(["24px", "14px"]); + expect(snowflakeVisual.particleAnimation).toBe("nebula-particle-snowflake"); + expect(snowflakeVisual.flakeMask).toContain("svg"); + expect(snowflakeVisual.clipPath).toBe("none"); + await expect(mythicPreview.getByRole("button", { name: "Remettre la carte Mythique face cachée", exact: true })).toHaveAttribute("data-reveal-phase", "revealed"); + await mythicPreview.getByRole("button", { name: "Remettre la carte Mythique face cachée", exact: true }).click(); + await expect(mythicCard).toHaveAttribute("data-reveal-phase", "concealed"); + await mythicPreview.getByRole("button", { name: "Forme de particules : Flocons de neige" }).click(); + await mythicPreview.getByRole("button", { name: "Étincelles", exact: true }).click(); + await expect(mythicSurface).toHaveAttribute("data-particle-shape", "sparks"); + await mythicCard.click(); + await expect(mythicSurface).toHaveAttribute("data-reveal-phase", "aura"); + await expect(mythicSurface).toHaveCSS("--opening-aura", "#ff3b30"); + await expect(mythicSurface).toHaveCSS("--opening-aura-duration", "450ms"); + await expect(mythicSurface).toHaveCSS("--opening-particle-duration", "1200ms"); + await expect(mythicSurface).toHaveCSS("--opening-aura-secondary", "#ff9500"); + await expect(mythicSurface).toHaveCSS("--opening-aura-tertiary", "#ffcc00"); + expect(await mythicSurface.evaluate((element) => element.style.getPropertyValue("--opening-aura-gradient"))).toBe("conic-gradient(from 15deg, #ff3b30, #ff9500, #ffcc00, #34c759, #00c7be, #3b82f6, #d946ef, #ff3b30)"); + const mythicAuraBase = await mythicSurface.evaluate((element) => { + const style = globalThis.getComputedStyle(element, "::after"); + const normalizeColors = (value) => value.replace(/(?:rgba?|color)\([^)]*\)/g, ""); + return { inset: style.inset, border: style.borderWidth, radius: style.borderRadius, background: normalizeColors(style.backgroundImage), shadow: normalizeColors(style.boxShadow), filter: normalizeColors(style.filter), mask: style.maskImage || style.webkitMaskImage }; + }); + const { shadow: mythicAuraShadow, ...mythicAuraBaseShape } = mythicAuraBase; + const { shadow: legendaryAuraShadow, ...legendaryAuraBaseShape } = legendaryAuraBase; + expect(mythicAuraBaseShape).toEqual(legendaryAuraBaseShape); + expect(legendaryAuraShadow).toContain("28px"); + expect(mythicAuraShadow).toBe("none"); + await expect(mythicSurface).toHaveAttribute("data-aura-palette", "true"); + await expect(mythicSurface.locator(".nebula-card-tilt-surface")).toHaveCSS("filter", "none"); + const crownGlowVisual = await mythicSurface.locator(":scope > .nebula-card-opening-glow-palette").evaluate((element) => { + const style = globalThis.getComputedStyle(element); + const inner = element.firstElementChild; + const near = globalThis.getComputedStyle(inner, "::before"); + const far = globalThis.getComputedStyle(inner, "::after"); + return { display: style.display, animation: style.animationName, duration: style.animationDuration, mask: style.maskImage || style.webkitMaskImage, nearBackground: near.backgroundImage, nearFilter: near.filter, nearOpacity: near.opacity, farFilter: far.filter, farOpacity: far.opacity }; + }); + expect(crownGlowVisual).toMatchObject({ display: "block", animation: "nebula-opening-aura", duration: "0.45s", nearOpacity: "0.78", farOpacity: "0.48" }); + expect(crownGlowVisual.mask).toContain("svg"); + expect(crownGlowVisual.nearBackground).toContain("conic-gradient"); + expect(crownGlowVisual.nearFilter).toContain("blur(14px)"); + expect(crownGlowVisual.farFilter).toContain("blur(32px)"); + const cardGlowVisual = await mythicSurface.locator(".nebula-card-glow-palette").evaluateAll((elements) => elements.map((element) => { + const style = globalThis.getComputedStyle(element); + return { side: element.dataset.side, display: style.display, backface: style.backfaceVisibility, background: globalThis.getComputedStyle(element, "::before").backgroundImage, animation: style.animationName }; + })); + expect(cardGlowVisual.map(({ side }) => side)).toEqual(["back", "face"]); + for (const glow of cardGlowVisual) expect(glow).toMatchObject({ display: "block", backface: "hidden", animation: "nebula-opening-card-glow-palette-in" }); + for (const glow of cardGlowVisual) expect(glow.background).toContain("conic-gradient"); + const mythicAuraPalettes = mythicSurface.locator(":scope > .nebula-card-opening-aura-palette, :scope > .nebula-card-opening-crown-palette"); + await expect(mythicAuraPalettes).toHaveCount(2); + const auraPaletteVisual = await mythicSurface.locator(":scope > .nebula-card-opening-aura-palette").evaluate((element) => { + const style = globalThis.getComputedStyle(element); + return { background: style.backgroundImage, mask: style.maskImage || style.webkitMaskImage, animation: style.animationName, duration: style.animationDuration, filter: style.filter, zIndex: style.zIndex }; + }); + const crownPaletteVisual = await mythicSurface.locator(":scope > .nebula-card-opening-crown-palette").evaluate((element) => { + const style = globalThis.getComputedStyle(element); + return { background: style.backgroundImage, mask: style.maskImage || style.webkitMaskImage, animation: style.animationName, duration: style.animationDuration, filter: style.filter, zIndex: style.zIndex }; + }); + expect(auraPaletteVisual.background).toContain("conic-gradient"); + expect(auraPaletteVisual.mask).toContain("radial-gradient"); + expect(crownPaletteVisual.background).toContain("conic-gradient"); + expect(crownPaletteVisual.mask).toContain("linear-gradient"); + expect(auraPaletteVisual.animation).toBe("nebula-opening-aura"); + expect(crownPaletteVisual.animation).toBe("nebula-opening-aura"); + expect(auraPaletteVisual.duration).toBe("0.45s"); + expect(crownPaletteVisual.duration).toBe("0.45s"); + expect(auraPaletteVisual.filter).toBe(crownPaletteVisual.filter); + expect(auraPaletteVisual.zIndex).toBe("1"); + expect(crownPaletteVisual.zIndex).toBe("1"); + await expect(mythicSurface.locator(".nebula-card-tilt-surface")).toHaveCSS("z-index", "2"); + await expect(mythicSurface.locator(".nebula-card-particles i")).toHaveCount(48); + const mythicBurstGeometry = await mythicSurface.locator(".nebula-card-particles").evaluate((element) => { + const styles = element.ownerDocument.defaultView; + const normalizeColors = (value) => value.replace(/rgba?\([^)]*\)/g, ""); + const before = styles.getComputedStyle(element, "::before"); + const after = styles.getComputedStyle(element, "::after"); + const particle = styles.getComputedStyle(element.querySelector("i")); + return { + ring: { width: before.width, height: before.height, border: before.borderWidth, radius: before.borderRadius, shadow: normalizeColors(before.boxShadow), animation: before.animationName, duration: before.animationDuration, easing: before.animationTimingFunction }, + rays: { width: after.width, height: after.height, radius: after.borderRadius, filter: normalizeColors(after.filter), animation: after.animationName, duration: after.animationDuration, easing: after.animationTimingFunction }, + particle: { width: particle.width, height: particle.height, radius: particle.borderRadius, clipPath: particle.clipPath, animation: particle.animationName, duration: particle.animationDuration, easing: particle.animationTimingFunction, x: particle.getPropertyValue("--x"), y: particle.getPropertyValue("--y") }, + particleSizes: [...element.querySelectorAll("i")].map((item) => `${styles.getComputedStyle(item).width}x${styles.getComputedStyle(item).height}`).join(" ") + }; + }); + const { shadow: mythicRingShadow, ...mythicRingGeometry } = mythicBurstGeometry.ring; + const { shadow: legendaryRingShadow, ...legendaryRingGeometry } = legendaryBurstVisual.geometry.ring; + expect(legendaryRingShadow).not.toBe("none"); + expect(mythicRingShadow).toBe("none"); + const { width: mythicParticleWidth, height: mythicParticleHeight, ...mythicParticleMotion } = mythicBurstGeometry.particle; + const { width: legendaryParticleWidth, height: legendaryParticleHeight, ...legendaryParticleMotion } = legendaryBurstVisual.geometry.particle; + const { particleSizes: mythicParticleSizes, ...mythicBurstShared } = mythicBurstGeometry; + const { particleSizes: legendaryParticleSizes, ...legendaryBurstShared } = legendaryBurstVisual.geometry; + expect({ ...mythicBurstShared, ring: mythicRingGeometry, particle: mythicParticleMotion }).toEqual({ ...legendaryBurstShared, ring: legendaryRingGeometry, particle: legendaryParticleMotion }); + expect([legendaryParticleWidth, legendaryParticleHeight]).toEqual(["12px", "12px"]); + expect([mythicParticleWidth, mythicParticleHeight]).toEqual(["16px", "16px"]); + expect(legendaryParticleSizes.split(" ").slice(0, 3)).toEqual(["12pxx12px", "12pxx12px", "7pxx18px"]); + expect(mythicParticleSizes.split(" ").slice(0, 3)).toEqual(["16pxx16px", "16pxx16px", "9pxx24px"]); + expect(mythicParticleSizes.split(" ")).toHaveLength(48); + const mythicRingBackground = await mythicSurface.locator(".nebula-card-particles").evaluate((element) => globalThis.getComputedStyle(element, "::before").backgroundImage); + expect(mythicRingBackground).toContain("conic-gradient"); + expect(mythicRingBackground).toContain("rgb(255, 59, 48)"); + const mythicRingGlow = await mythicSurface.locator(".nebula-card-particle-ring-glow").evaluateAll((elements) => elements.map((element) => { + const style = globalThis.getComputedStyle(element); + return { glow: element.dataset.glow, background: globalThis.getComputedStyle(element.firstElementChild.firstElementChild).backgroundImage, filter: globalThis.getComputedStyle(element.firstElementChild).filter, animation: style.animationName, duration: style.animationDuration }; + })); + expect(mythicRingGlow.map(({ glow }) => glow)).toEqual(["outer", "inner"]); + for (const glow of mythicRingGlow) { + expect(glow.background).toContain("conic-gradient"); + expect(glow.filter).toBe("blur(9px)"); + expect(glow.animation).toBe("nebula-particle-ring"); + expect(glow.duration).toBe("1.2s"); + } + await expectMythicRingSilhouetteToMatchLegendary(page); + const mythicRayBackground = await mythicSurface.locator(".nebula-card-particles").evaluate((element) => globalThis.getComputedStyle(element, "::after").backgroundImage); + expect(mythicRayBackground).toContain("conic-gradient"); + expect(mythicRayBackground).toContain("rgb(255, 59, 48)"); + expect(mythicRayBackground).toContain("rgb(52, 199, 89)"); + const mythicParticleColors = await mythicSurface.locator(".nebula-card-particles i").evaluateAll((particles) => [...new Set(particles.map((particle) => globalThis.getComputedStyle(particle).color))]); + expect(mythicParticleColors.length).toBe(7); + await expect(mythicPreview.getByRole("button", { name: "Remettre la carte Mythique face cachée", exact: true })).toHaveAttribute("data-reveal-phase", "revealed"); + + await page.setViewportSize({ width: 768, height: 900 }); + await noOverflow(); + + await navigation.getByRole("link", { name: "Collections" }).click(); + await expect(page).toHaveURL(/#\/cards\/admin\/collections$/); + const recharge = page.getByRole("complementary", { name: "Recharge des ouvertures" }); + await expect(recharge.locator(".nebula-admin-recharge-current")).toHaveText("1 ouverture toutes les heures · réserve de 5"); + await expect(recharge.getByLabel("Délai en minutes")).toHaveValue("60"); + await expect(recharge.getByRole("status")).toHaveText("1 h · 24 ouvertures par jour · réserve vide remplie en 5 h"); + await expect(recharge.getByRole("combobox")).toHaveCount(0); + const applyRecharge = recharge.getByRole("button", { name: "Appliquer", exact: true }); + await expect(applyRecharge).toBeDisabled(); + await recharge.getByLabel("Délai en minutes").fill("30"); + await expect(recharge.getByRole("status")).toHaveText("30 min · 48 ouvertures par jour · réserve vide remplie en 2 h 30 min"); + await applyRecharge.click(); + await page.getByRole("dialog", { name: "Passer à 1 ouverture toutes les 30 min ?" }).getByRole("button", { name: "Appliquer le délai" }).click(); + await expect(recharge.locator(".nebula-admin-recharge-current")).toHaveText("1 ouverture toutes les 30 min · réserve de 5"); + await expect(recharge.getByRole("button", { name: "Appliquer", exact: true })).toBeDisabled(); + + // L'historique d'administration garde cette modification, lisible et attribuée, et s'actualise sans recharger la page. + await page.getByRole("navigation", { name: "Sections de l’administration" }).getByRole("link", { name: "Historique", exact: true }).click(); + await expect(page).toHaveURL(/#\/cards\/admin\/history$/); + const latestAdminAction = page.locator(".nebula-history-list > li").first(); + await expect(latestAdminAction).toContainText("Recharge modifiée"); + await expect(latestAdminAction).toContainText(/1\s*h → 30\s*min/); + await expect(latestAdminAction).toContainText("par Version développement"); + await page.goBack(); + + // Ouverture aux joueurs et taux de tirage se règlent sur la page de la collection. + await page.getByRole("link", { name: "Ouvrir la collection Genèse Astrale" }).click(); + await expect(page).toHaveURL(/#\/cards\/admin\/collections\/astral-genesis$/); + const genesisCard = page.locator(".nebula-admin-collection-card"); + const packSwitch = genesisCard.getByRole("button", { name: "Ouvrir Genèse Astrale aux joueurs" }); + await expect(packSwitch).toHaveAttribute("aria-pressed", "true"); + const genesisPack = page.locator(".nebula-admin-drop-rates"); + await expect(genesisPack.getByRole("heading", { name: "Taux de tirage" })).toBeVisible(); + await expect(genesisPack.locator("tbody tr td strong")).toHaveText(["64 %", "24 %", "8 %", "3 %", "1 %"]); + await expect(genesisPack.locator('tbody tr[data-rarity="mythic"] td').nth(2)).toHaveText("1"); + await expect(genesisPack.locator('tbody tr[data-rarity="mythic"] td').nth(3)).toHaveText("1 %"); + const applyButton = genesisPack.getByRole("button", { name: "Appliquer", exact: true }); + const recommendedButton = genesisPack.getByRole("button", { name: "Taux recommandés" }); + await expect(recommendedButton).toBeDisabled(); + await expect(applyButton).toBeDisabled(); + await genesisPack.getByLabel("Poids Commun").fill("63"); + await genesisPack.getByLabel("Poids Mythique").fill("2"); + await expect(genesisPack.locator('tbody tr[data-rarity="mythic"] td strong')).toHaveText("2 %"); + await expect(genesisPack.locator('tbody tr[data-rarity="mythic"] td small')).toHaveText("avant 1 %"); + await genesisPack.getByLabel("Poids Rare").fill("-1"); + await expect(genesisPack.getByRole("alert")).toContainText("entier positif ou nul"); + await expect(applyButton).toBeDisabled(); + await genesisPack.getByLabel("Poids Rare").fill("24"); + await applyButton.click(); + await page.getByRole("dialog", { name: "Appliquer les nouveaux taux de Genèse Astrale ?" }).getByRole("button", { name: "Appliquer les taux" }).click(); + await expect(applyButton).toBeDisabled(); + await expect(genesisPack.locator('tbody tr[data-rarity="mythic"] td strong')).toHaveText("2 %"); + // « Taux recommandés » préremplit le tableau sans rien enregistrer. + await recommendedButton.click(); + await expect(genesisPack.getByLabel("Poids Mythique")).toHaveValue("1"); + await expect(genesisPack.getByLabel("Poids Commun")).toHaveValue("64"); + await expect(recommendedButton).toBeDisabled(); + await expect(applyButton).toBeEnabled(); + await genesisPack.getByRole("button", { name: "Annuler les modifications" }).click(); + await expect(genesisPack.getByLabel("Poids Mythique")).toHaveValue("2"); + await packSwitch.click(); + await page.getByRole("dialog", { name: "Fermer Genèse Astrale ?" }).getByRole("button", { name: "Fermer le paquet" }).click(); + await expect(packSwitch).toHaveAttribute("aria-pressed", "false"); + await expect(genesisCard).toContainText("Fermé aux joueurs"); + // Une collection temporaire fermée sans carte possédée disparaît de la page Collection du joueur. + const closedCollectionAdminUrl = page.url(); + await page.goto("/#/cards/collection"); + await expect(page.locator(".nebula-album-group").first()).toBeVisible(); + await expect(page.locator(".nebula-album-group", { hasText: "Genèse Astrale" })).toHaveCount(0); + await page.locator(".nebula-album-filters").getByRole("button", { name: "Collection", exact: true }).click(); + await expect(page.locator(".nebula-album-filters").getByRole("checkbox", { name: "Genèse Astrale" })).toHaveCount(0); + await page.keyboard.press("Escape"); + await page.goto(closedCollectionAdminUrl); + await expect(genesisCard).toContainText("Fermé aux joueurs"); + await expect(genesisCard.locator(".nebula-admin-collection-badges .nds-badge").nth(1)).toHaveText("Fermée"); + await packSwitch.click(); + await expect(packSwitch).toHaveAttribute("aria-pressed", "true"); + await noOverflow(); + await page.goto("/#/cards/admin/packs"); + await expect(navigation.getByRole("link", { name: "Collections" })).toHaveAttribute("aria-current", "page"); + + await navigation.getByRole("link", { name: "Boutique" }).click(); + await expect(page).toHaveURL(/#\/cards\/admin\/shop$/); + const recyclingForm = page.getByRole("region", { name: "Recyclage des doublons" }); + const articlesForm = page.getByRole("region", { name: "Articles de la boutique" }); + await expect(recyclingForm.getByLabel("Mythique", { exact: true })).toHaveValue("150"); + await expect(recyclingForm.getByRole("button", { name: "Appliquer" })).toBeDisabled(); + await expect(articlesForm.getByRole("button", { name: "Appliquer" })).toBeDisabled(); + // Mêmes illustrations que la boutique des joueurs. + await expect(articlesForm.locator('.nebula-shop-item[data-item="pack"] .nebula-collection-back')).toBeVisible(); + await expect(articlesForm.locator('.nebula-shop-item[data-item="opening"] img')).toHaveAttribute("src", "/static/img/cards/shop/pack.webp"); + // Appliquer les prix conserve le brouillon du barème, et ne l'envoie pas. + await recyclingForm.getByLabel("Commun", { exact: true }).fill("2"); + await articlesForm.getByLabel("Prix d’une ouverture de paquet").fill("45"); + await expect(articlesForm.getByRole("status")).toHaveText("Une ouverture = 45 doublons communs recyclés."); + await articlesForm.getByRole("button", { name: "Appliquer" }).click(); + await page.getByRole("dialog").getByRole("button", { name: "Appliquer" }).click(); + await expect(articlesForm.getByLabel("Prix d’une ouverture de paquet")).toHaveValue("45"); + await expect(articlesForm.getByRole("button", { name: "Appliquer" })).toBeDisabled(); + await expect(recyclingForm.getByLabel("Commun", { exact: true })).toHaveValue("2"); + await recyclingForm.getByRole("button", { name: "Annuler les modifications" }).click(); + await expect(recyclingForm.getByLabel("Commun", { exact: true })).toHaveValue("1"); + await noOverflow(); + + await navigation.getByRole("link", { name: "Codes cadeaux" }).click(); + // La liste d'abord : le formulaire s'ouvre à la demande. + await expect(page.getByText("Aucune campagne pour l’instant.", { exact: true })).toBeVisible(); + const campaignForm = page.locator(".nebula-admin-campaign-form"); + await expect(campaignForm).toHaveCount(0); + const newCampaign = page.getByRole("button", { name: "+ Nouvelle campagne" }); + await newCampaign.click(); + await campaignForm.getByRole("button", { name: "Annuler" }).click(); + await expect(campaignForm).toHaveCount(0); + await newCampaign.click(); + await expect(page.getByRole("heading", { name: "Nouvelle campagne" })).toBeVisible(); + const createButton = campaignForm.getByRole("button", { name: "Créer la campagne" }); + await expect(createButton).toBeDisabled(); + await expect(campaignForm.locator(".nebula-admin-reward-item")).toHaveCount(0); + await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toHaveText("Ajoutez des cartes ou un paquet pour voir le récapitulatif."); + await expect(campaignForm.getByRole("group", { name: "Cartes à offrir" })).toHaveCount(0); + await expect(campaignForm.locator(".nebula-admin-campaign-missing")).toHaveText("Pour créer la campagne, il manque : le nom de la campagne ; au moins une carte ou un paquet ; un code de 4 à 24 caractères (lettres, chiffres, tirets)."); + + // Carte offerte, codes uniques. + await campaignForm.getByLabel("Nom de la campagne, visible par les joueurs").fill("Cadeau dragon"); + await campaignForm.getByRole("button", { name: "+ Ajouter des cartes" }).click(); + const cardPicker = campaignForm.getByRole("group", { name: "Cartes à offrir" }); + await expect(cardPicker.getByRole("status")).toHaveText("Aucune carte cochée."); + await expect(cardPicker.locator('.nebula-card[data-card-size="sm"]').first()).toBeVisible(); + await cardPicker.getByRole("radio", { name: "Mythique" }).click(); + await cardPicker.getByRole("searchbox").fill("dragon"); + await expect(cardPicker.locator(".nebula-admin-card-picker-item")).toHaveCount(2); + const auroraDragon = cardPicker.getByRole("button", { name: "Sélectionner Dragon du Néant Étoilé — Mythique · Prisme spectral — Aurore" }); + const otherDragon = cardPicker.locator(".nebula-admin-card-picker-item button").nth(1); + await auroraDragon.click(); + await otherDragon.click(); + await expect(auroraDragon).toHaveAttribute("aria-pressed", "true"); + await expect(cardPicker.getByRole("status")).toHaveText("2 cartes cochées"); + // Un second clic décoche la carte. + await otherDragon.click(); + await expect(otherDragon).toHaveAttribute("aria-pressed", "false"); + const checkedCards = campaignForm.getByRole("list", { name: "Cartes cochées" }); + await expect(checkedCards.getByRole("listitem")).toHaveCount(1); + await expect(checkedCards).toContainText("Dragon du Néant Étoilé — Mythique · Prisme spectral — Aurore"); + // Par défaut : sans limite d'utilisations, sans date d'expiration. + await expect(campaignForm.getByLabel("Sans limite d’utilisations")).toBeChecked(); + await expect(campaignForm.getByLabel("Utilisations maximum")).toHaveCount(0); + await expect(campaignForm.getByLabel("Sans date d’expiration")).toBeChecked(); + await expect(campaignForm.getByLabel("Valable jusqu’au")).toHaveCount(0); + await campaignForm.getByRole("button", { name: "Générer" }).click(); + await expect(campaignForm.getByLabel("Code à annoncer (4 à 24 caractères)")).toHaveValue(/^[2-9A-HJKMNP-Z]{4}-[2-9A-HJKMNP-Z]{4}$/); + await campaignForm.getByLabel("Code à annoncer (4 à 24 caractères)").fill("dragon"); + await campaignForm.getByLabel("Sans limite d’utilisations").uncheck(); + await campaignForm.getByLabel("Utilisations maximum").fill("1"); + await campaignForm.getByLabel("Sans date d’expiration").uncheck(); + await expect(campaignForm.getByLabel("Valable jusqu’au")).toBeVisible(); + await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("Carte Dragon du Néant Étoilé (Mythique · Prisme spectral — Aurore)"); + await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("Le code DRAGON, utilisable 1 fois, jusqu’au"); + await createButton.click(); + const generated = page.locator(".nebula-admin-generated"); + await expect(generated.getByRole("heading", { name: "Campagne « Cadeau dragon » créée" })).toBeVisible(); + await expect(generated).toContainText("Code à annoncer : DRAGON"); + await expect(campaignForm).toHaveCount(0); + await generated.getByRole("button", { name: "Fermer" }).click(); + await newCampaign.click(); + + // Récompense composée : une carte et deux paquets avec garantie, code partagé sans limite. + await campaignForm.getByLabel("Nom de la campagne, visible par les joueurs").fill("Live de lancement"); + await expect(campaignForm.locator(".nebula-admin-reward-item")).toHaveCount(0); + await expect(cardPicker).toHaveCount(0); + await campaignForm.getByRole("button", { name: "+ Ajouter des cartes" }).click(); + await chooseOption(campaignForm, "Collection affichée", "Genèse Astrale"); + await cardPicker.getByRole("button", { name: "Sélectionner Booster Astral — Commun" }).click(); + await campaignForm.getByRole("button", { name: "+ Ajouter un paquet" }).click(); + const packItem = campaignForm.getByRole("group", { name: "Paquet 1" }); + await chooseOption(packItem, "Collection", "Genèse Astrale"); + await packItem.getByLabel("Quantité").fill("2"); + await packItem.getByRole("radio", { name: "Une rareté minimum" }).click(); + await chooseOption(packItem, "Rareté garantie", "Légendaire"); + await campaignForm.getByLabel("Code à annoncer (4 à 24 caractères)").fill("e2e live"); + await expect(campaignForm.getByLabel("Code à annoncer (4 à 24 caractères)")).toHaveValue("E2E-LIVE"); + await expect(campaignForm.locator(".nebula-admin-campaign-missing")).toHaveCount(0); + await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("+ 2 × Paquet Genèse Astrale · au moins 1 carte légendaire ou mieux garantie"); + await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("Le code E2E-LIVE, utilisable sans limite, sans date d’expiration."); + await createButton.click(); + await expect(generated).toContainText("E2E-LIVE"); + + const campaigns = page.locator(".nebula-campaign-card"); + await expect(campaigns).toHaveCount(2); + const dragonCampaign = page.getByRole("article", { name: "Cadeau dragon" }); + await dragonCampaign.getByRole("button", { name: "Détails" }).click(); + await expect(dragonCampaign).toContainText("Code DRAGON"); + await expect(dragonCampaign).toContainText("0 / 1 utilisés"); + await expect(dragonCampaign).toContainText("Personne n’a encore utilisé ce code."); + await noOverflow(); + + // Le joueur utilise le code partagé dans l'onglet Paquets et ouvre le paquet offert. + await page.goto("/#/cards"); + await page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Paquets", exact: true }).click(); + await page.getByRole("textbox", { name: "Utiliser un code" }).fill("e2e-live"); + await page.getByRole("button", { name: "Utiliser le code" }).click(); + await expect(page.locator(".nebula-redeem [role=\"status\"]")).toContainText("Code utilisé, vous recevez : Carte Booster Astral"); + await expect(page.locator(".nebula-redeem [role=\"status\"]")).toContainText("2 × Paquet Genèse Astrale · au moins 1 carte légendaire ou mieux garantie"); + const giftPack = page.locator(".nebula-gift-pack"); + await expect(giftPack).toHaveCount(2); + await expect(giftPack.first()).toContainText("Live de lancement"); + await giftPack.first().click(); + await expect(page.getByRole("heading", { name: "Révélez vos trois cartes" })).toBeVisible(); + await expect(page.locator(".nebula-opening-odds")).toContainText("au moins 1 carte légendaire ou mieux garantie"); + await page.getByRole("button", { name: "Tout révéler" }).click(); + await expect(page.locator(".nebula-opening-cards .nebula-card[data-rarity=\"legendary\"], .nebula-opening-cards .nebula-card[data-rarity=\"mythic\"]").first()).toBeAttached(); +}); + +test("administration stays within a phone screen", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto("/#/cards/admin/history"); + await page.getByRole("button", { name: "Version développement", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Historique", exact: true })).toBeVisible(); + // Un ancêtre masque ce qui dépasse : scrollWidth ne le voit pas, seule la position des éléments le révèle. + const clipped = await page.locator(".nebula-dashboard :is(a, button, h1)").evaluateAll((elements) => elements + .filter((element) => element.getBoundingClientRect().right > element.ownerDocument.defaultView.innerWidth + 0.5) + .map((element) => element.textContent)); + expect(clipped).toEqual([]); +}); + +test("players give cards and answer trade proposals from two accounts", async ({ browser, page }) => { + test.setTimeout(90_000); + const nav = (scope) => scope.getByRole("navigation", { name: "Sections de Sokko TCG" }); + const noOverflow = async (scope) => expect(await scope.locator("html").evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(false); + await page.goto("/#/cards/transfers"); + await page.getByRole("button", { name: "Version développement", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Échanges et dons", exact: true })).toBeVisible(); + + 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" }); + await partnerContext.addCookies([{ name: "sokkog_cards_session", value: token, url: "http://127.0.0.1:4180" }]); + const partner = await partnerContext.newPage(); + await partner.goto("/#/cards/transfers"); + + // Don : deux envois du même doublon, sans code ni confirmation du destinataire. + async function give() { + await partner.getByRole("button", { name: "Faire un don", exact: true }).click(); + const dialog = partner.getByRole("dialog"); + await chooseOption(dialog, "Joueur", /Version développement/); + await dialog.getByRole("button", { name: /Vous donnez : Loup des Aurores/ }).click(); + await dialog.getByRole("button", { name: /^Donner Loup des Aurores à Version développement/ }).click(); + await expect(partner.getByRole("status")).toContainText("Loup des Aurores a été donnée à Version développement."); + } + await give(); + await give(); + await page.reload(); + await nav(page).getByRole("link", { name: "Collection", exact: true }).waitFor(); + await expect(nav(page).getByRole("link", { name: "Échanges et dons", exact: true })).toBeVisible(); + await page.getByRole("button", { name: /Terminées \(\d+\)/ }).click(); + await expect(page.locator(".nebula-transfers-finished .nebula-transfer-card").first()).toContainText("Don de Partenaire E2E"); + await expect(page.locator(".nebula-transfers-finished .nebula-transfer-card").first()).toContainText("Loup des Aurores"); + + // Échange : le partenaire voit le doublon de l'autre joueur et demande une carte précise. + async function propose() { + await partner.reload(); + await partner.getByRole("button", { name: "Proposer un échange", exact: true }).click(); + const dialog = partner.getByRole("dialog"); + await expect(dialog.getByRole("button", { name: "Envoyer la proposition" })).toBeDisabled(); + await chooseOption(dialog, "Joueur", /Version développement/); + await dialog.getByRole("button", { name: /Vous donnez : Dragon du Néant Étoilé/ }).click(); + await dialog.getByRole("button", { name: /Vous recevez : Loup des Aurores/ }).click(); + await noOverflow(partner); + // Dans le groupe Échange / Don, le texte ne touche pas les bords de son option. + expect(await dialog.locator(".nds-radio-button-group button").evaluateAll((buttons) => buttons.every((button) => { + const range = button.ownerDocument.createRange(); + range.selectNodeContents(button); + const text = range.getBoundingClientRect(); + const box = button.getBoundingClientRect(); + return text.left - box.left >= 6 && box.right - text.right >= 6; + }))).toBe(true); + await dialog.getByRole("button", { name: "Envoyer la proposition" }).click(); + await expect(partner.getByRole("status")).toContainText("Proposition envoyée à Version développement."); + } + await propose(); + await expect(partner.getByRole("heading", { name: /Envoyées/ })).toBeVisible(); + await expect(partner.locator(".nebula-transfer-card").first()).toContainText(/Expire dans/); + + // Le compteur du menu apparaît au retour sur la page, sans recharger. + await page.evaluate(() => globalThis.dispatchEvent(new globalThis.Event("focus"))); + await expect(nav(page).getByRole("link", { name: /Échanges et dons/ }).locator(".nds-badge")).toHaveText("1"); + const inbox = page.locator(".nebula-transfer-card", { hasText: "Échange avec Partenaire E2E" }).first(); + await expect(inbox.locator(".nebula-card")).toHaveCount(2); + await inbox.getByRole("button", { name: "Refuser" }).click(); + await expect(page.getByRole("status")).toContainText("Proposition refusée."); + await expect(nav(page).getByRole("link", { name: "Échanges et dons", exact: true })).toBeVisible(); + + // Le partenaire propose de nouveau, annule, puis propose encore : l'autre joueur accepte. + await propose(); + await partner.getByRole("button", { name: "Annuler", exact: true }).click(); + await expect(partner.getByRole("status")).toContainText("Proposition annulée"); + await propose(); + await page.evaluate(() => globalThis.dispatchEvent(new globalThis.Event("focus"))); + await page.locator(".nebula-transfer-card", { hasText: "Échange avec Partenaire E2E" }).first().getByRole("button", { name: "Accepter" }).click(); + await expect(page.getByRole("status")).toContainText("Échange terminé"); + await page.goto("/#/cards/history"); + await expect(page.locator(".nebula-history-list")).toContainText("Reçue : Dragon du Néant Étoilé"); + + // La fiche d'une carte en double ouvre directement le formulaire. + await partner.goto("/#/cards/collection"); + await partner.locator(".nebula-album-entry:not([data-missing]) button").first().click(); + await partner.getByRole("dialog").getByRole("button", { name: "Donner", exact: true }).click(); + await expect(partner.getByRole("dialog").getByRole("heading", { name: "Faire un don" })).toBeVisible(); + await expect(partner.getByRole("dialog").locator('[data-selected]')).toHaveCount(1); + await partner.getByRole("dialog").getByRole("button", { name: "Fermer", exact: true }).click(); + + // Le paquet de la boutique s'achète en poussière, s'ouvre aussitôt et n'est jamais proposé dans Paquets. + await partner.goto("/#/cards/packs"); + await expect(partner.locator(".nebula-pack")).toHaveCount(2); + await partner.goto("/#/cards/shop"); + const packItem = partner.locator('.nebula-shop-item[data-item="pack"]'); + await packItem.getByRole("button", { name: "Acheter et ouvrir" }).click(); + await expect(partner).toHaveURL(/#\/cards\/packs$/); + await expect(partner.getByRole("heading", { name: "Révélez vos trois cartes" })).toBeVisible(); + await expect(partner.locator(".nebula-card-back img").first()).toHaveAttribute("src", "/static/img/cards/stardust/back.webp"); + await expect(partner.locator(".nebula-opening-odds")).toContainText("50 % des légendaires et mythiques tirées viennent de Poussières d'étoiles"); + await partner.getByRole("button", { name: "Tout révéler" }).click(); + await partner.getByRole("button", { name: "Retour", exact: true }).click({ timeout: 30_000 }); + await partner.goto("/#/cards/shop"); + await expect(partner.locator(".nebula-shop-wallet")).toContainText("440"); + await partnerContext.close(); +}); + +test("administrator previews the mythic opening from a base without any mythic variation", async ({ page }) => { + await page.route("**/api/cards/config*", async (route) => { + const response = await route.fetch(); + const json = await response.json(); + json.catalog.editions = json.catalog.editions.filter((edition) => edition.rarity !== "mythic"); + await route.fulfill({ response, json }); + }); + await page.goto("/#/cards/admin"); + await page.getByRole("button", { name: "Version développement", exact: true }).click(); + await page.getByRole("link", { name: "Atelier visuel" }).click(); + const mythicPreview = page.locator(".nebula-admin-opening-effect-card").filter({ has: page.getByRole("heading", { name: "Mythique", exact: true }) }); + await expect(mythicPreview.locator(".nebula-admin-style-preview > span")).toHaveText(/^Aperçu · .+ — Prisme spectral — /); + await mythicPreview.getByRole("button", { name: "Révéler la carte Mythique", exact: true }).click(); + await expect(mythicPreview.locator(".nebula-card-particles i").first()).toBeAttached(); +}); diff --git a/e2e/style-layouts.spec.js b/e2e/style-layouts.spec.js index 47b0df0..a064f07 100644 --- a/e2e/style-layouts.spec.js +++ b/e2e/style-layouts.spec.js @@ -90,7 +90,8 @@ for (const width of [1920, 1280, 1025, 1024, 960, 768]) { await expect(page.locator(".sidebar-note")).toHaveCSS("display", "block"); await expect(page.locator(".sidebar-storage-actions")).toHaveCSS("flex-direction", responsiveCompact ? "column" : "row"); await expect(page.locator(".sidebar-action-button")).toHaveCount(2); - await expect(page.locator(".nav-item")).toHaveCount(3); + await expect(page.locator(".nav-item")).toHaveCount(4); + await expect(page.getByRole("link", { name: /Sokko TCG/ })).toBeVisible(); await expect(page.locator(".nav-item strong").first()).toHaveCSS("display", responsiveCompact ? "none" : "block"); const brand = page.locator(".brand"); const brandMark = page.locator(".brand-mark"); diff --git a/eslint.config.js b/eslint.config.js index 805a312..b271048 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -46,7 +46,7 @@ export default [ } }, { - files: ["*.js", "*.mjs", "scripts/**/*.mjs", "tests/**/*.mjs"], + files: ["*.js", "*.mjs", "scripts/**/*.mjs", "services/**/*.js", "tests/**/*.mjs"], languageOptions: { ecmaVersion: "latest", sourceType: "module", diff --git a/ops/systemd/sokko-g.service b/ops/systemd/sokko-g.service index 54b9a9f..87d45fe 100644 --- a/ops/systemd/sokko-g.service +++ b/ops/systemd/sokko-g.service @@ -9,6 +9,7 @@ User=shinuwa WorkingDirectory=/data/webapps/sites/sokko-g Environment=NODE_ENV=production Environment=PATH=/home/shinuwa/.nvm/versions/node/v24.11.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +EnvironmentFile=-/etc/sokko-g/cards.env ExecStart=/home/shinuwa/.nvm/versions/node/v24.11.1/bin/npm start Restart=always RestartSec=5 diff --git a/package.json b/package.json index 04373f8..cdc1bdc 100644 --- a/package.json +++ b/package.json @@ -15,11 +15,15 @@ "preview": "vite preview", "lists:index": "node scripts/generate-list-indexes.mjs", "lint": "eslint .", + "lint:cards": "eslint server.mjs vite.config.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 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:full": "npm run check && npm run test:e2e && npm run test:e2e:production", + "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", "test": "node --test", + "test:cards": "node --test tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs && node --test --test-name-pattern=\"site content json is complete\" tests/data-validation.test.mjs", "test:e2e": "playwright test", "test:e2e:production": "npm run build && playwright test --config playwright.production.config.js", + "test:e2e:cards": "playwright test --config playwright.cards.config.js", "images:convert": "node scripts/convert-public-images.mjs", "profile:assets": "npm run build && node scripts/measure-public-assets.mjs", "profile:toolboxes": "npm run build && node scripts/profile-toolbox-loading.mjs" diff --git a/playwright.cards.config.js b/playwright.cards.config.js new file mode 100644 index 0000000..a414205 --- /dev/null +++ b/playwright.cards.config.js @@ -0,0 +1,18 @@ +// Rôle : exécute les parcours Sokko TCG contre le vrai serveur Node et une base temporaire. +import { defineConfig, devices } from "@playwright/test"; + +export default defineConfig({ + testDir: "./e2e", + testMatch: "nebula-cards.spec.js", + workers: 1, + outputDir: "test-results/cards", + reporter: [["list"], ["html", { open: "never", outputFolder: "playwright-report/cards" }]], + use: { baseURL: "http://127.0.0.1:4180", trace: "retain-on-failure", screenshot: "only-on-failure" }, + webServer: { + command: "npm run build && node scripts/start-cards-e2e-server.mjs", + url: "http://127.0.0.1:4180/api/cards/config", + reuseExistingServer: false, + timeout: 120000 + }, + projects: [{ name: "chromium-cards", use: { ...devices["Desktop Chrome"] } }] +}); diff --git a/playwright.config.js b/playwright.config.js index 9629172..49d6bcb 100644 --- a/playwright.config.js +++ b/playwright.config.js @@ -1,22 +1,26 @@ // Rôle : configure les diagnostics navigateur Playwright sans les intégrer au check de prod. import { defineConfig, devices } from "@playwright/test"; +const port = Number(process.env.E2E_PORT || 5173); +const baseURL = `http://localhost:${port}`; +const isolatedCardsEnvironment = process.env.E2E_PORT ? "CARDS_DB_PATH=:memory: CARDS_DEV_AUTH=true " : ""; + export default defineConfig({ testDir: "./e2e", - testIgnore: "**/production/**", + testIgnore: ["**/production/**", "**/nebula-cards.spec.js"], fullyParallel: true, // Le serveur Vite partagé compile les outils lazy à la première visite. workers: 2, reporter: [["list"], ["html", { open: "never" }]], use: { - baseURL: "http://localhost:5173", + baseURL, trace: "retain-on-failure", screenshot: "only-on-failure" }, webServer: { - command: "npm run dev", - url: "http://localhost:5173", - reuseExistingServer: true, + command: `${isolatedCardsEnvironment}npm run dev -- --port ${port}`, + url: baseURL, + reuseExistingServer: !process.env.E2E_PORT, timeout: 120000 }, projects: [ diff --git a/scripts/backup-nebula-cards.mjs b/scripts/backup-nebula-cards.mjs new file mode 100644 index 0000000..bcf1a8a --- /dev/null +++ b/scripts/backup-nebula-cards.mjs @@ -0,0 +1,18 @@ +// Rôle : sauvegarde ou vérifie la base Sokko TCG depuis les tâches d'exploitation. +import { resolve } from "node:path"; +import { backupCardsDatabase, restoreCardsDatabase, verifyCardsDatabase } from "../services/cards/backup.js"; + +const [mode, source, destination] = process.argv.slice(2); +if (mode === "backup" && source && destination) { + await backupCardsDatabase(resolve(source), resolve(destination)); + console.log(`Sokko TCG backup written to ${resolve(destination)}`); +} else if (mode === "verify" && source) { + verifyCardsDatabase(resolve(source)); + console.log(`Sokko TCG backup verified: ${resolve(source)}`); +} else if (mode === "restore" && source && destination) { + restoreCardsDatabase(resolve(source), resolve(destination)); + console.log(`Sokko TCG database restored to ${resolve(destination)}`); +} else { + console.error("Usage: node scripts/backup-nebula-cards.mjs backup | verify | restore "); + process.exitCode = 1; +} diff --git a/scripts/start-cards-e2e-server.mjs b/scripts/start-cards-e2e-server.mjs new file mode 100644 index 0000000..f866059 --- /dev/null +++ b/scripts/start-cards-e2e-server.mjs @@ -0,0 +1,50 @@ +// Rôle : démarre le build avec une base Sokko TCG temporaire pour les parcours Playwright. +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const directory = mkdtempSync(join(tmpdir(), "sokkog-cards-e2e-")); +process.env.NODE_ENV = "production"; +process.env.PORT = process.env.PORT || "4180"; +process.env.CARDS_ENABLED = "true"; +process.env.CARDS_DEV_AUTH = "true"; +process.env.CARDS_DB_PATH = join(directory, "cards.sqlite"); +process.env.CARDS_PUBLIC_ORIGIN = `http://127.0.0.1:${process.env.PORT}`; +// Rend le bouton Discord visible ; les parcours ne le suivent jamais jusqu'à Discord. +process.env.DISCORD_CLIENT_ID = "e2e-client"; +process.env.DISCORD_CLIENT_SECRET = "e2e-secret"; + +// Un second joueur, avec des doublons et une session, pour les parcours d'échange et de don à deux comptes. +const [{ CardsDatabase }, { CardsService }, { loadCardsCatalog }] = await Promise.all([import("../services/cards/database.js"), import("../services/cards/service.js"), import("../services/cards/catalog.js")]); +const seedDatabase = new CardsDatabase(process.env.CARDS_DB_PATH); +const seedService = new CardsService({ database: seedDatabase, catalog: loadCardsCatalog(join(import.meta.dirname, "..", "website", "public", "data", "cards", "catalog.json")) }); +const partner = seedService.upsertPlayer({ discordId: "e2e-partner", displayName: "Partenaire E2E" }); +for (const editionId of ["aurora-wolf-standard", "aurora-wolf-standard", "aurora-wolf-standard", "aurora-wolf-standard", "starvoid-dragon-standard", "starvoid-dragon-standard", "starvoid-dragon-standard"]) seedService.addCard(partner.id, editionId); +seedDatabase.db.prepare("UPDATE players SET stardust = 500 WHERE id = ?").run(partner.id); +writeFileSync(join(tmpdir(), "sokkog-cards-e2e-partner.json"), JSON.stringify({ token: seedService.createSession(partner.id).token })); +// Une base neuve n'a aucune variation mythique : les parcours de jeu et d'administration en ont besoin. +const insertVariation = seedDatabase.db.prepare("INSERT INTO mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by) VALUES (?, ?, ?, 'active', 0, NULL)"); +for (const cardId of ["starvoid-dragon", "crimson-moon-kitsune", "milky-way-panda", "constellation-magpie", "solar-dawn-capybara", "aurora-wolf"]) { + for (const finishId of ["spectral-prism-aurora", "spectral-prism-cosmic"]) insertVariation.run(`${cardId}-${finishId}`, cardId, finishId); +} +insertVariation.run("mythic-card-pull-spectral-prism-solar", "mythic-card-pull", "spectral-prism-solar"); +seedDatabase.close(); + +const { startServer } = await import("../server.mjs"); +const draws = [0.999, 0, 0.999, 0.999, 0.999, 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. +const server = startServer({ cardsApiOptions: { apiRateLimit: 100_000, random: (max) => Math.min(max - 1, Math.floor(draws[drawIndex++ % draws.length] * max)) } }); +let stopping = false; + +function stop() { + if (stopping) return; + stopping = true; + server.close(() => { + rmSync(directory, { recursive: true, force: true }); + process.exit(0); + }); +} + +process.on("SIGTERM", stop); +process.on("SIGINT", stop); diff --git a/server.mjs b/server.mjs index f3135b9..c3bdf3b 100644 --- a/server.mjs +++ b/server.mjs @@ -1,6 +1,7 @@ // Rôle : sert l'application Vite construite ou les sources publiques avec leur politique de cache. import { createReadStream, existsSync, statSync } from "node:fs"; import { loadProjectEnv } from "./scripts/load-project-env.mjs"; +import { createCardsApiHandler } from "./services/cards/api.js"; import { createServer } from "node:http"; import { extname, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -65,8 +66,9 @@ function getCacheControl(root, file) { return "no-cache"; } -export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot } = {}) { - return createServer((req, res) => { +export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null } = {}) { + const server = createServer(async (req, res) => { + if (cardsApi && await cardsApi(req, res)) return; const file = resolvePath(req.url || "/", root, publicRoot); if (!file || !existsSync(file)) { res.writeHead(404, { @@ -83,12 +85,15 @@ export function createStaticServer({ root = defaultRoot, publicRoot = defaultPub }); createReadStream(file).pipe(res); }); + if (cardsApi?.close) server.once("close", cardsApi.close); + return server; } -export function startServer() { +export function startServer({ cardsApiOptions = {} } = {}) { loadProjectEnv(); const port = Number(process.env.PORT || 5173); - const server = createStaticServer(); + const cardsApi = createCardsApiHandler({ projectRoot, ...cardsApiOptions }); + const server = createStaticServer({ cardsApi }); server.on("error", (error) => { if (error.code === "EADDRINUSE") { diff --git a/services/cards/admin-seed.js b/services/cards/admin-seed.js new file mode 100644 index 0000000..e13b83e --- /dev/null +++ b/services/cards/admin-seed.js @@ -0,0 +1,21 @@ +// Rôle : contenu de départ des tables gérées depuis l'administration, inséré par la migration 2. +// Listes figées : elles décrivent l'état initial de la base ; la suite se gère depuis l'administration. + +// Paquets ouvrables au départ. +export const INITIAL_COLLECTION_STATES = Object.freeze([ + Object.freeze({ collectionId: "primordial-nebula", active: true }), + Object.freeze({ collectionId: "astral-genesis", active: true }) +]); + +// Taux de tirage de départ, égaux aux poids recommandés des raretés (catalog.json). +const LAUNCH_WEIGHTS = Object.freeze({ common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 }); +export const INITIAL_DROP_RATES = Object.freeze(["primordial-nebula", "astral-genesis"].map((collectionId) => Object.freeze({ collectionId, rarityWeights: LAUNCH_WEIGHTS }))); + +// Recharge de départ : une ouverture toutes les heures, réserve plafonnée à 5. +export const INITIAL_RECHARGE_SETTING = Object.freeze({ intervalMs: 60 * 60 * 1000, maxOpenings: 5 }); + +// Boutique de départ : poussière d'étoiles gagnée par doublon recyclé, selon sa rareté, et prix d'une ouverture achetée. +export const INITIAL_SHOP_SETTING = Object.freeze({ + stardustValues: Object.freeze({ common: 1, rare: 3, epic: 10, legendary: 40, mythic: 150 }), + openingPrice: 30 +}); diff --git a/services/cards/api.js b/services/cards/api.js new file mode 100644 index 0000000..c6b9dfe --- /dev/null +++ b/services/cards/api.js @@ -0,0 +1,362 @@ +// Rôle : expose l'API HTTP, l'authentification Discord et les protections de session Sokko TCG. +import { randomBytes } from "node:crypto"; +import { join, resolve } from "node:path"; +import { CardsDatabase } from "./database.js"; +import { loadCardsCatalog, publicCatalog } from "./catalog.js"; +import { CardsService, DEV_DISCORD_ID } from "./service.js"; + +const JSON_LIMIT = 64 * 1024; +const DISCORD_TIMEOUT_MS = 10_000; + +function bool(value, fallback = false) { + if (value == null || value === "") return fallback; + return /^(1|true|yes|on)$/i.test(String(value)); +} + +function json(res, status, body) { + const payload = JSON.stringify(body); + res.writeHead(status, { + "Content-Type": "application/json; charset=utf-8", + "Content-Length": Buffer.byteLength(payload), + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff" + }); + res.end(payload); +} + +function redirect(res, location, cookies = []) { + const headers = { Location: location, "Cache-Control": "no-store" }; + if (cookies.length) headers["Set-Cookie"] = cookies; + res.writeHead(302, headers); + res.end(); +} + +function parseCookies(req) { + return Object.fromEntries(String(req.headers.cookie || "").split(";").map((entry) => entry.trim()).filter(Boolean).map((entry) => { + const separator = entry.indexOf("="); + return [decodeURIComponent(entry.slice(0, separator)), decodeURIComponent(entry.slice(separator + 1))]; + })); +} + +function sessionCookie(value, secure, maxAge = 30 * 24 * 60 * 60) { + return `sokkog_cards_session=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`; +} + +function stateCookie(value, secure, maxAge = 600) { + return `sokkog_cards_oauth_state=${encodeURIComponent(value)}; Path=/api/cards/auth; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`; +} + +function oauthReturnCookie(value, secure, maxAge = 600) { + return `sokkog_cards_oauth_return=${encodeURIComponent(value)}; Path=/api/cards/auth; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`; +} + +function cardsReturnPath(value) { + return /^\/cards(?:\/admin(?:\/[a-z0-9-]{1,40}){0,2}|\/[a-z0-9-]{1,40})?$/.test(String(value || "")) ? value : "/cards"; +} + +async function readBody(req) { + let size = 0; + const chunks = []; + for await (const chunk of req) { + size += chunk.length; + if (size > JSON_LIMIT) throw Object.assign(new Error("Requête trop volumineuse."), { status: 413, code: "BODY_TOO_LARGE" }); + chunks.push(chunk); + } + if (!chunks.length) return {}; + try { + return JSON.parse(Buffer.concat(chunks).toString("utf8")); + } catch { + throw Object.assign(new Error("Corps JSON invalide."), { status: 400, code: "INVALID_JSON" }); + } +} + +function requestOrigin(req) { + const protocol = String(req.headers["x-forwarded-proto"] || "http").split(",")[0].trim(); + return `${protocol}://${req.headers.host}`; +} + +function routeMatch(pathname, pattern) { + const match = pathname.match(pattern); + return match ? match.slice(1).map(decodeURIComponent) : null; +} + +function createRateLimiter(now) { + const buckets = new Map(); + return (req, scope, limit = 60) => { + const key = `${String(req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "unknown").split(",")[0]}:${scope}`; + const minute = Math.floor(now() / 60_000); + const current = buckets.get(key); + if (!current || current.minute !== minute) { + buckets.set(key, { minute, count: 1 }); + return; + } + current.count += 1; + if (current.count > limit) throw Object.assign(new Error("Trop de tentatives. Réessayez dans quelques instants."), { status: 429, code: "RATE_LIMITED" }); + }; +} + +export function createCardsApiHandler({ + projectRoot = resolve("."), + env = process.env, + enabled = bool(env.CARDS_ENABLED, env.NODE_ENV !== "production"), + devAuth = bool(env.CARDS_DEV_AUTH, env.NODE_ENV !== "production"), + databasePath = env.CARDS_DB_PATH || join(projectRoot, ".local", "nebula-cards.sqlite"), + catalogPath = join(projectRoot, "website", "public", "data", "cards", "catalog.json"), + now = Date.now, + random, + fetchImpl = fetch, + devPerks = false, + apiRateLimit = 60 +} = {}) { + let database = null; + let service = null; + if (enabled) { + if (env.NODE_ENV === "production" && !env.CARDS_DB_PATH) throw new TypeError("CARDS_DB_PATH is required when Sokko TCG is enabled in production."); + // Sans origine fixe, le retour OAuth et le contrôle CSRF dépendraient de l'en-tête Host envoyé par le client. + if (env.NODE_ENV === "production" && !env.CARDS_PUBLIC_ORIGIN) throw new TypeError("CARDS_PUBLIC_ORIGIN is required when Sokko TCG is enabled in production."); + const catalog = loadCardsCatalog(catalogPath); + database = new CardsDatabase(databasePath); + service = new CardsService({ database, catalog, now, random, devPerks }); + } + const secureCookies = env.NODE_ENV === "production"; + const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean)); + const rateLimit = createRateLimiter(now); + const publicOrigin = (req) => env.CARDS_PUBLIC_ORIGIN || requestOrigin(req); + const discordCallbackUrl = (req) => env.DISCORD_REDIRECT_URI || `${publicOrigin(req)}/api/cards/auth/callback`; + + // Échange le code contre le profil Discord ; toute erreur reste côté serveur et devient un retour lisible pour le joueur. + async function fetchDiscordUser(req, code) { + const signal = AbortSignal.timeout(DISCORD_TIMEOUT_MS); + const tokenResponse = await fetchImpl("https://discord.com/api/oauth2/token", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ client_id: env.DISCORD_CLIENT_ID, client_secret: env.DISCORD_CLIENT_SECRET, grant_type: "authorization_code", code, redirect_uri: discordCallbackUrl(req) }), + signal + }); + if (!tokenResponse.ok) throw new Error(`Discord token exchange failed with status ${tokenResponse.status}.`); + const { access_token: accessToken } = await tokenResponse.json(); + const userResponse = await fetchImpl("https://discord.com/api/users/@me", { headers: { Authorization: `Bearer ${accessToken}` }, signal }); + if (!userResponse.ok) throw new Error(`Discord profile request failed with status ${userResponse.status}.`); + return userResponse.json(); + } + + async function handler(req, res) { + const url = new URL(req.url || "/", requestOrigin(req)); + if (!url.pathname.startsWith("/api/cards")) return false; + try { + if (req.method === "GET" && url.pathname === "/api/cards/config") { + json(res, 200, { + enabled, + devAuth: enabled && devAuth, + discordConfigured: enabled && Boolean(env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET), + catalog: enabled ? publicCatalog(service.catalog) : null + }); + return true; + } + rateLimit(req, "api", apiRateLimit); + if (!enabled) { + json(res, 503, { error: { code: "CARDS_DISABLED", message: "Sokko TCG est désactivé." } }); + return true; + } + + const cookies = parseCookies(req); + const session = service.getSession(cookies.sokkog_cards_session); + + if (req.method === "GET" && url.pathname === "/api/cards/auth/discord") { + if (!env.DISCORD_CLIENT_ID || !env.DISCORD_CLIENT_SECRET) throw Object.assign(new Error("Connexion Discord non configurée."), { status: 503, code: "DISCORD_NOT_CONFIGURED" }); + const state = randomBytes(24).toString("base64url"); + const returnTo = cardsReturnPath(url.searchParams.get("returnTo")); + const target = new URL("https://discord.com/oauth2/authorize"); + target.search = new URLSearchParams({ client_id: env.DISCORD_CLIENT_ID, response_type: "code", redirect_uri: discordCallbackUrl(req), scope: "identify", state }).toString(); + redirect(res, target.toString(), [stateCookie(state, secureCookies), oauthReturnCookie(returnTo, secureCookies)]); + return true; + } + + if (req.method === "GET" && url.pathname === "/api/cards/auth/callback") { + const state = url.searchParams.get("state"); + const code = url.searchParams.get("code"); + const returnTo = cardsReturnPath(cookies.sokkog_cards_oauth_return); + const clearedCookies = [stateCookie("", secureCookies, 0), oauthReturnCookie("", secureCookies, 0)]; + // Cette route est une navigation : le joueur revient toujours sur le site, jamais sur une réponse JSON. + const fail = (reason) => redirect(res, `${publicOrigin(req)}/?cardsAuth=${reason}#${returnTo}`, clearedCookies); + if (!state || state !== cookies.sokkog_cards_oauth_state) { + fail("expired"); + return true; + } + if (url.searchParams.get("error") === "access_denied") { + fail("denied"); + return true; + } + try { + if (!code) throw new Error("Discord callback has no authorization code."); + const user = await fetchDiscordUser(req, code); + const avatarUrl = user.avatar ? `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=128` : ""; + const player = service.upsertPlayer({ discordId: String(user.id), displayName: user.global_name || user.username, avatarUrl, isAdmin: adminIds.has(String(user.id)) }); + const created = service.createSession(player.id); + redirect(res, `${publicOrigin(req)}/#${returnTo}`, [sessionCookie(created.token, secureCookies), ...clearedCookies]); + } catch (error) { + console.error(error); + fail("failed"); + } + return true; + } + + if (req.method === "POST" && url.pathname === "/api/cards/auth/dev") { + if (!devAuth) throw Object.assign(new Error("Connexion de développement indisponible."), { status: 404, code: "NOT_FOUND" }); + rateLimit(req, "dev-auth", 10); + const player = service.upsertPlayer({ discordId: DEV_DISCORD_ID, displayName: "Version développement", isAdmin: true }); + const created = service.createSession(player.id); + res.setHeader("Set-Cookie", sessionCookie(created.token, secureCookies)); + json(res, 200, { player, csrfToken: created.csrfToken }); + return true; + } + + if (req.method === "GET" && url.pathname === "/api/cards/session") { + json(res, 200, session ? { authenticated: true, ...session } : { authenticated: false }); + return true; + } + + if (!session) throw Object.assign(new Error("Connectez-vous pour accéder à votre collection."), { status: 401, code: "AUTH_REQUIRED" }); + if (req.method !== "GET") { + const origin = req.headers.origin; + if (origin && origin !== publicOrigin(req)) throw Object.assign(new Error("Origine de requête refusée."), { status: 403, code: "ORIGIN" }); + if (req.headers["x-csrf-token"] !== session.csrfToken) throw Object.assign(new Error("Session expirée ou requête invalide."), { status: 403, code: "CSRF" }); + } + + if (req.method === "POST" && url.pathname === "/api/cards/auth/logout") { + service.deleteSession(cookies.sokkog_cards_session); + res.setHeader("Set-Cookie", sessionCookie("", secureCookies, 0)); + json(res, 200, { ok: true }); + return true; + } + if (req.method === "GET" && url.pathname === "/api/cards/state") { + json(res, 200, service.getState(session.player.id)); + return true; + } + if (req.method === "GET" && url.pathname === "/api/cards/admin/dashboard") { + json(res, 200, service.getAdminDashboard(session.player.id)); + return true; + } + if (req.method === "GET" && url.pathname === "/api/cards/admin/history") { + const before = url.searchParams.get("before"); + if (before != null && !/^[1-9]\d{0,15}$/.test(before)) throw Object.assign(new Error("Curseur d'historique invalide."), { status: 400, code: "INVALID_CURSOR" }); + json(res, 200, service.getAdminHistory(session.player.id, { before: before == null ? null : Number(before) })); + return true; + } + if (req.method === "POST" && url.pathname === "/api/cards/openings") { + const body = await readBody(req); + json(res, 201, service.openPack(session.player.id, body.collectionId, req.headers["idempotency-key"], { purchased: body.purchased === true })); + return true; + } + const giftOpen = routeMatch(url.pathname, /^\/api\/cards\/gift-packs\/([^/]+)\/open$/); + if (req.method === "POST" && giftOpen) { + json(res, 201, service.openGiftPack(session.player.id, giftOpen[0], req.headers["idempotency-key"])); + return true; + } + const openingComplete = routeMatch(url.pathname, /^\/api\/cards\/openings\/([^/]+)\/complete$/); + if (req.method === "POST" && openingComplete) { + json(res, 200, service.completeOpening(session.player.id, openingComplete[0])); + return true; + } + if (req.method === "PUT" && url.pathname === "/api/cards/favorites") { + const body = await readBody(req); + json(res, 200, service.setFavorite(session.player.id, body.editionId, Boolean(body.favorite))); + return true; + } + if (req.method === "GET" && url.pathname === "/api/cards/traders") { + json(res, 200, service.listTraders(session.player.id)); + return true; + } + if (req.method === "POST" && url.pathname === "/api/cards/transfers") { + rateLimit(req, "transfer", 30); + json(res, 201, service.createTransfer(session.player.id, await readBody(req))); + return true; + } + for (const [action, method] of [["accept", "acceptTransfer"], ["decline", "declineTransfer"], ["cancel", "cancelTransfer"]]) { + const match = routeMatch(url.pathname, new RegExp(`^/api/cards/transfers/([^/]+)/${action}$`)); + if (req.method === "POST" && match) { + json(res, 200, service[method](session.player.id, match[0])); + return true; + } + } + if (req.method === "POST" && url.pathname === "/api/cards/rewards/claim") { + rateLimit(req, "reward-code", 20); + json(res, 200, service.claimCampaign(session.player.id, (await readBody(req)).code)); + return true; + } + if (req.method === "POST" && url.pathname === "/api/cards/admin/campaigns") { + json(res, 201, service.createCampaign(session.player.id, await readBody(req))); + return true; + } + const cardMythic = routeMatch(url.pathname, /^\/api\/cards\/admin\/catalog\/cards\/([^/]+)\/mythic$/); + if (req.method === "PUT" && cardMythic) { + const body = await readBody(req); + json(res, 200, service.setCardMythicConfig(session.player.id, cardMythic[0], { finishIds: body.finishIds, opening: { particleShapeId: body.opening?.particleShapeId ?? null, particlePaletteId: body.opening?.particlePaletteId ?? null } })); + return true; + } + if (req.method === "POST" && url.pathname === "/api/cards/recycle") { + json(res, 200, service.recycleDuplicates(session.player.id, { editionId: (await readBody(req)).editionId ?? null })); + return true; + } + if (req.method === "POST" && url.pathname === "/api/cards/shop/pack") { + json(res, 201, service.buyShopPack(session.player.id, req.headers["idempotency-key"])); + return true; + } + if (req.method === "POST" && url.pathname === "/api/cards/shop/openings") { + json(res, 200, service.buyOpening(session.player.id)); + return true; + } + if (req.method === "PUT" && url.pathname === "/api/cards/admin/shop") { + const body = await readBody(req); + json(res, 200, service.updateShopSetting(session.player.id, { stardustValues: body.stardustValues, openingPrice: body.openingPrice, shopPackPrice: body.shopPackPrice, shopPackShare: body.shopPackShare })); + return true; + } + if (req.method === "PUT" && url.pathname === "/api/cards/admin/recharge") { + json(res, 200, service.updateRechargeSetting(session.player.id, { intervalMs: (await readBody(req)).intervalMs })); + return true; + } + const collectionState = routeMatch(url.pathname, /^\/api\/cards\/admin\/collections\/([^/]+)\/state$/); + if (req.method === "PUT" && collectionState) { + json(res, 200, service.setCollectionActive(session.player.id, collectionState[0], (await readBody(req)).active)); + return true; + } + const dropRates = routeMatch(url.pathname, /^\/api\/cards\/admin\/collections\/([^/]+)\/drop-rates$/); + if (req.method === "PUT" && dropRates) { + json(res, 200, service.setDropRates(session.player.id, dropRates[0], (await readBody(req)).rarityWeights)); + return true; + } + const collectionOpening = routeMatch(url.pathname, /^\/api\/cards\/admin\/catalog\/collections\/([^/]+)\/mythic-opening$/); + if (req.method === "PUT" && collectionOpening) { + const body = await readBody(req); + json(res, 200, service.setCollectionMythicOpening(session.player.id, collectionOpening[0], { particleShapeId: body.particleShapeId ?? null, particlePaletteId: body.particlePaletteId ?? null })); + return true; + } + const campaignDetail = routeMatch(url.pathname, /^\/api\/cards\/admin\/campaigns\/([^/]+)$/); + if (req.method === "GET" && campaignDetail) { + json(res, 200, service.campaignDetail(session.player.id, campaignDetail[0])); + return true; + } + const campaignExpiry = routeMatch(url.pathname, /^\/api\/cards\/admin\/campaigns\/([^/]+)\/expiry$/); + if (req.method === "PUT" && campaignExpiry) { + json(res, 200, service.extendCampaign(session.player.id, campaignExpiry[0], (await readBody(req)).expiresAt)); + return true; + } + const revokeCampaign = routeMatch(url.pathname, /^\/api\/cards\/admin\/campaigns\/([^/]+)\/revoke$/); + if (req.method === "POST" && revokeCampaign) { + json(res, 200, service.revokeCampaign(session.player.id, revokeCampaign[0])); + return true; + } + + json(res, 404, { error: { code: "NOT_FOUND", message: "Route Sokko TCG introuvable." } }); + return true; + } catch (error) { + json(res, error.status || 500, { error: { code: error.code || "INTERNAL_ERROR", message: error.status ? error.message : "Une erreur serveur est survenue." } }); + if (!error.status) console.error(error); + return true; + } + } + + handler.close = () => database?.close(); + handler.service = service; + return handler; +} diff --git a/services/cards/backup.js b/services/cards/backup.js new file mode 100644 index 0000000..c57d4c7 --- /dev/null +++ b/services/cards/backup.js @@ -0,0 +1,42 @@ +// Rôle : crée, vérifie et restaure des sauvegardes cohérentes de la base Sokko TCG. +import { copyFileSync, mkdirSync, renameSync, rmSync } from "node:fs"; +import { dirname } from "node:path"; +import { backup, DatabaseSync } from "node:sqlite"; + +export async function backupCardsDatabase(sourcePath, destinationPath) { + mkdirSync(dirname(destinationPath), { recursive: true }); + const temporaryPath = `${destinationPath}.tmp`; + rmSync(temporaryPath, { force: true }); + const source = new DatabaseSync(sourcePath, { readOnly: true }); + try { + await backup(source, temporaryPath); + } finally { + source.close(); + } + verifyCardsDatabase(temporaryPath); + renameSync(temporaryPath, destinationPath); + return destinationPath; +} + +export function verifyCardsDatabase(path) { + const database = new DatabaseSync(path, { readOnly: true }); + try { + const result = database.prepare("PRAGMA integrity_check").get(); + if (result.integrity_check !== "ok") throw new Error(`SQLite integrity check failed: ${result.integrity_check}`); + database.prepare("SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1").get(); + return true; + } finally { + database.close(); + } +} + +export function restoreCardsDatabase(backupPath, destinationPath) { + verifyCardsDatabase(backupPath); + mkdirSync(dirname(destinationPath), { recursive: true }); + const temporaryPath = `${destinationPath}.restore`; + rmSync(temporaryPath, { force: true }); + copyFileSync(backupPath, temporaryPath); + verifyCardsDatabase(temporaryPath); + renameSync(temporaryPath, destinationPath); + return destinationPath; +} diff --git a/services/cards/catalog.js b/services/cards/catalog.js new file mode 100644 index 0000000..f60dcaf --- /dev/null +++ b/services/cards/catalog.js @@ -0,0 +1,301 @@ +// Rôle : charge et valide le catalogue public, ses finitions et effets Sokko TCG. +import { readFileSync } from "node:fs"; + +const RARITY_IDS = new Set(["common", "rare", "epic", "legendary", "mythic"]); +const PARTICLE_SHAPE_KINDS = new Set(["sparks", "snowflakes"]); +const PACK_CATEGORIES = new Set(["permanent", "event", "shop"]); +const PACK_BACK_SYMBOLS = new Set(["star", "rift", "orbit"]); +const COLOR_PATTERN = /^#[0-9a-f]{6}$/i; +// Formats d'une variation mythique : le premier est le format de référence ; `full-art` utilise `card.fullImage` sur toute la carte. +const STANDARD_FORMAT = "standard"; +export const FULL_ART_FORMAT = "full-art"; +// Palette d'ouverture spéciale : reprend les couleurs de la palette holographique de la variation. +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 PACK_BACK_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/; + +function requireUnique(items, label) { + const ids = new Set(); + for (const item of items) { + if (!item?.id || typeof item.id !== "string") throw new TypeError(`${label}: every item needs a string id.`); + if (ids.has(item.id)) throw new TypeError(`${label}: duplicate id ${item.id}.`); + ids.add(item.id); + } + return ids; +} + +export function validateCardsCatalog(catalog) { + 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"]) { + if (!Array.isArray(catalog[key]) || !catalog[key].length) throw new TypeError(`Cards catalog ${key} must be a non-empty array.`); + } + const rarityIds = requireUnique(catalog.rarities, "rarities"); + const effectPresetIds = requireUnique(catalog.effectPresets, "effectPresets"); + const effectPaletteIds = requireUnique(catalog.effectPalettes, "effectPalettes"); + const particleShapeIds = requireUnique(catalog.particleShapes, "particleShapes"); + const particlePaletteIds = requireUnique(catalog.particlePalettes, "particlePalettes"); + const particlePresetIds = requireUnique(catalog.particlePresets, "particlePresets"); + requireUnique(catalog.openingEffects, "openingEffects"); + const finishIds = requireUnique(catalog.finishes, "finishes"); + const collectionIds = requireUnique(catalog.collections, "collections"); + const cardIds = requireUnique(catalog.cards, "cards"); + requireUnique(catalog.editions, "editions"); + 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. + validateRarityWeights(Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, rarity.recommendedWeight])), rarityIds, "recommended weights"); + + for (const preset of catalog.effectPresets) { + if (!preset.label || preset.kind !== "holographic") throw new TypeError(`Invalid holographic effect preset ${preset.id}.`); + } + if (catalog.cardFormats?.[0]?.id !== STANDARD_FORMAT || catalog.cardFormats.some((format) => !format.label) || !catalog.cardFormats.some((format) => format.id === FULL_ART_FORMAT)) { + throw new TypeError("Cards catalog must declare the standard and full-art formats."); + } + for (const palette of catalog.effectPalettes) { + if (!palette.label || !Array.isArray(palette.colors) || palette.colors.length !== 7 + || new Set(palette.colors).size !== 7 + || palette.colors.some((color) => !COLOR_PATTERN.test(color)) || !COLOR_PATTERN.test(palette.highlight)) { + throw new TypeError(`Invalid effect palette ${palette.id}.`); + } + } + for (const shape of catalog.particleShapes) { + if (!shape.label || !PARTICLE_SHAPE_KINDS.has(shape.kind)) throw new TypeError(`Invalid particle shape ${shape.id}.`); + } + for (const palette of catalog.particlePalettes) { + if (!palette.label || !Array.isArray(palette.colors) || palette.colors.length < 1 || palette.colors.length > 7 + || palette.colors.some((color) => !COLOR_PATTERN.test(color))) { + throw new TypeError(`Invalid particle palette ${palette.id}.`); + } + } + for (const preset of catalog.particlePresets) { + if (!preset.label || !particleShapeIds.has(preset.shapeId) || !particlePaletteIds.has(preset.paletteId) + || !Number.isInteger(preset.count) || preset.count < 1 || preset.count > 64) { + throw new TypeError(`Invalid particle preset ${preset.id}.`); + } + } + // Un seul effet d'ouverture par rareté ; les variantes mythiques passent par les réglages d'ouverture. + const openingEffectRarities = new Set(); + for (const effect of catalog.openingEffects) { + if (!effect.label || !RARITY_IDS.has(effect.rarity) || effect.rarity === "common" + || !Array.isArray(effect.auraColors) || effect.auraColors.length < 1 || effect.auraColors.length > 7 + || effect.auraColors.some((color) => !COLOR_PATTERN.test(color)) + || Object.hasOwn(effect, "collectionId") + || !Number.isInteger(effect.auraDurationMs) || effect.auraDurationMs < 0 || effect.auraDurationMs > 2_000 + || !Number.isInteger(effect.particleDurationMs) || effect.particleDurationMs < 0 || effect.particleDurationMs > 2_000) { + throw new TypeError(`Invalid opening effect ${effect.id}.`); + } + if (effect.particlePresetId != null && !particlePresetIds.has(effect.particlePresetId)) throw new TypeError(`Opening effect ${effect.id} needs a known particle preset.`); + if (effect.particlePresetId == null && effect.particleDurationMs !== 0) throw new TypeError(`Opening effect ${effect.id} cannot animate missing particles.`); + if (openingEffectRarities.has(effect.rarity)) throw new TypeError(`Duplicate opening effect for rarity ${effect.rarity}.`); + openingEffectRarities.add(effect.rarity); + } + for (const rarity of ["rare", "epic", "legendary", "mythic"]) { + if (!openingEffectRarities.has(rarity)) throw new TypeError(`Cards catalog needs an opening effect for rarity ${rarity}.`); + } + const defaultMythicOpening = catalog.openingEffects.find((effect) => effect.rarity === "mythic"); + if (!particlePresetIds.has(defaultMythicOpening.particlePresetId)) throw new TypeError("The default mythic opening effect needs particles."); + for (const finish of catalog.finishes) { + if (!finish.label + || !Object.hasOwn(finish, "effectPresetId") + || !Object.hasOwn(finish, "paletteId")) { + throw new TypeError(`Invalid finish ${finish.id}.`); + } + const hasEffect = finish.effectPresetId != null; + if (hasEffect && !effectPresetIds.has(finish.effectPresetId)) throw new TypeError(`Finish ${finish.id} needs a known holographic effect.`); + if (hasEffect && !effectPaletteIds.has(finish.paletteId)) throw new TypeError(`Holographic finish ${finish.id} needs a known palette.`); + if (!hasEffect && finish.paletteId != null) throw new TypeError(`Finish ${finish.id} cannot use a palette without a holographic effect.`); + } + + for (const collection of catalog.collections) { + if (!collection.name || !collection.systemName || !collection.description || (collection.active != null && typeof collection.active !== "boolean") || typeof collection.promotional !== "boolean") { + throw new TypeError(`Invalid collection ${collection.id}.`); + } + if (!PACK_CATEGORIES.has(collection.packCategory) + || !PACK_BACK_SYMBOLS.has(collection.back?.symbol) + || !PACK_BACK_IMAGE_PATTERN.test(collection.back?.image) + || !COLOR_PATTERN.test(collection.back?.primary) + || !COLOR_PATTERN.test(collection.back?.secondary)) { + throw new TypeError(`Invalid pack presentation for collection ${collection.id}.`); + } + } + + for (const card of catalog.cards) { + if (!collectionIds.has(card.collectionId)) throw new TypeError(`Unknown collection for card ${card.id}.`); + if (!card.name || card.name.length > 40) throw new TypeError(`Card ${card.id} name must contain 1 to 40 characters.`); + if (!card.description || card.description.length > 200) throw new TypeError(`Card ${card.id} description must contain 1 to 200 characters.`); + if (card.image != null && !CARD_IMAGE_PATTERN.test(card.image)) throw new TypeError(`Card ${card.id} image must use a canonical WebP path.`); + if (card.fullImage != null && !CARD_IMAGE_PATTERN.test(card.fullImage)) throw new TypeError(`Card ${card.id} full image must use a canonical WebP path.`); + } + + for (const edition of catalog.editions) { + if (!cardIds.has(edition.cardId)) throw new TypeError(`Unknown card for edition ${edition.id}.`); + if (!RARITY_IDS.has(edition.rarity)) throw new TypeError(`Unknown rarity for edition ${edition.id}.`); + if (!Array.isArray(edition.finishIds) || edition.finishIds.some((id) => !finishIds.has(id))) throw new TypeError(`Unknown finish for edition ${edition.id}.`); + if (edition.retired != null && typeof edition.retired !== "boolean") throw new TypeError(`Edition ${edition.id} retired flag must be a boolean.`); + if (edition.promotional && edition.legendaryEditionId) throw new TypeError(`Promotional edition ${edition.id} cannot require a legendary parent.`); + if (edition.rarity === "mythic" && !edition.promotional) { + const parent = catalog.editions.find((candidate) => candidate.id === edition.legendaryEditionId); + if (!parent || parent.cardId !== edition.cardId || parent.rarity !== "legendary") throw new TypeError(`Mythic edition ${edition.id} needs a legendary edition of the same card.`); + } + } + if (catalog.mythicOpeningSettings != null) { + if (!Array.isArray(catalog.mythicOpeningSettings)) throw new TypeError("Cards catalog mythicOpeningSettings must be an array."); + const settingKeys = new Set(); + for (const setting of catalog.mythicOpeningSettings) { + const targets = setting?.scope === "collection" ? collectionIds : setting?.scope === "card" ? cardIds : null; + if (!targets?.has(setting.targetId) + || (setting.particleShapeId != null && !particleShapeIds.has(setting.particleShapeId)) + || (setting.particlePaletteId != null && setting.particlePaletteId !== MATCH_HOLO_PALETTE_ID && !particlePaletteIds.has(setting.particlePaletteId))) { + throw new TypeError(`Invalid mythic opening setting ${setting?.scope}:${setting?.targetId}.`); + } + const key = `${setting.scope}:${setting.targetId}`; + if (settingKeys.has(key)) throw new TypeError(`Duplicate mythic opening setting ${key}.`); + settingKeys.add(key); + } + } + + // Les taux de tirage n'existent que dans le catalogue publié (ils viennent de la base). + for (const collection of catalog.collections) { + if (collection.dropWeights != null) validateRarityWeights(collection.dropWeights, rarityIds, collection.id); + } + return catalog; +} + +export const MAX_RARITY_WEIGHT = 1_000_000; + +// Poids entiers, positifs ou nuls, une entrée par rareté connue, total strictement positif. +export function validateRarityWeights(weights, rarityIds, label = "drop weights") { + if (!weights || typeof weights !== "object" || Array.isArray(weights)) throw new TypeError(`Invalid drop weights in ${label}.`); + const entries = Object.entries(weights); + if (entries.length !== rarityIds.size || entries.some(([rarity, weight]) => !rarityIds.has(rarity) || !Number.isInteger(weight) || weight < 0 || weight > MAX_RARITY_WEIGHT)) { + throw new TypeError(`Invalid drop weight in ${label}.`); + } + if (entries.reduce((sum, [, weight]) => sum + weight, 0) <= 0) throw new TypeError(`Drop weights in ${label} must have a positive total.`); + return weights; +} + +export const STANDARD_FINISH_ID = "standard"; + +// Les finitions ne sont pas déclarées : « standard » plus une finition par combinaison effet holographique × palette. +export function withGeneratedFinishes(catalog) { + const finishes = [{ id: STANDARD_FINISH_ID, label: "Standard", effectPresetId: null, paletteId: null, formatId: STANDARD_FORMAT }]; + for (const format of catalog.cardFormats || []) { + for (const effect of catalog.effectPresets || []) { + for (const palette of catalog.effectPalettes || []) { + // Le format de référence garde des identifiants courts ; les autres sont préfixés par leur format. + const standard = format.id === STANDARD_FORMAT; + finishes.push({ + id: `${standard ? "" : `${format.id}-`}${effect.id}-${palette.id}`, + label: `${standard ? "" : `${format.label} · `}${effect.label} — ${palette.label}`, + effectPresetId: effect.id, + paletteId: palette.id, + formatId: format.id + }); + } + } + } + return { ...catalog, finishes }; +} + +// catalog.json ne déclare ni finitions (générées) ni contenu géré en base depuis l'administration : +// variations mythiques, activation des paquets et taux de tirage. +export function assertVersionedCatalogScope(catalog) { + if (catalog.finishes) throw new TypeError("Finishes are generated from effect presets and palettes: remove finishes from catalog.json."); + if (catalog.dropTables) throw new TypeError("Drop rates are managed from the admin database: remove dropTables from catalog.json."); + const withRates = catalog.collections?.find((collection) => Object.hasOwn(collection, "dropWeights")); + if (withRates) throw new TypeError(`Collection ${withRates.id} drop rates are managed from the admin database: remove dropWeights from catalog.json.`); + const withState = catalog.collections?.find((collection) => Object.hasOwn(collection, "active")); + if (withState) throw new TypeError(`Collection ${withState.id} availability is managed from the admin database: remove active from catalog.json.`); + const mythic = catalog.editions?.find((edition) => edition.rarity === "mythic" && !edition.promotional); + if (mythic) throw new TypeError(`Mythic edition ${mythic.id} must be managed from the admin database, not catalog.json.`); + return catalog; +} + +// Prépare le catalogue versionné tel qu'il est lu depuis catalog.json. +export function prepareVersionedCatalog(raw) { + return validateCardsCatalog(withGeneratedFinishes(assertVersionedCatalogScope(raw))); +} + +export function loadCardsCatalog(path) { + return prepareVersionedCatalog(JSON.parse(readFileSync(path, "utf8"))); +} + +export function createCatalogIndex(catalog) { + return { + collections: new Map(catalog.collections.map((item) => [item.id, item])), + cards: new Map(catalog.cards.map((item) => [item.id, item])), + editions: new Map(catalog.editions.map((item) => [item.id, item])), + finishes: new Map(catalog.finishes.map((item) => [item.id, item])), + effectPresets: new Map(catalog.effectPresets.map((item) => [item.id, item])), + effectPalettes: new Map(catalog.effectPalettes.map((item) => [item.id, item])), + particleShapes: new Map(catalog.particleShapes.map((item) => [item.id, item])), + particlePalettes: new Map(catalog.particlePalettes.map((item) => [item.id, item])), + particlePresets: new Map(catalog.particlePresets.map((item) => [item.id, item])), + openingEffects: new Map(catalog.openingEffects.map((item) => [item.id, item])) + }; +} + +export function isDrawableEdition(edition) { + return !edition.promotional && !edition.retired; +} + +export function holographicFinishIds(catalog) { + return new Set(catalog.finishes.filter((finish) => finish.effectPresetId != null).map((finish) => finish.id)); +} + +export function legendaryParentEdition(catalog, cardId) { + return catalog.editions.find((edition) => edition.cardId === cardId && edition.rarity === "legendary" && !edition.promotional) || null; +} + +export function mythicEditionId(cardId, finishId) { + return `${cardId}-${finishId}`; +} + +// Construit le catalogue publié : catalogue versionné + variations mythiques et réglages d'ouverture enregistrés en base. +// `variations` : [{ editionId, cardId, finishId, status: "active" | "retired" }] +// `openingSettings` : [{ scope: "collection" | "card", targetId, particleShapeId | null, particlePaletteId | null }] +// `collectionStates` : [{ collectionId, active }] ; une collection sans état est inactive. +// `dropRates` : [{ collectionId, rarityWeights }] ; publiés sur chaque collection dans `dropWeights`. +export function buildPublishedCatalog(versionedCatalog, { variations = [], openingSettings = [], collectionStates = [], dropRates = [] } = {}) { + const catalog = structuredClone(versionedCatalog); + const states = new Map(collectionStates.map((state) => [state.collectionId, Boolean(state.active)])); + const rates = new Map(dropRates.map((rate) => [rate.collectionId, rate.rarityWeights])); + catalog.collections = catalog.collections.map((collection) => { + const dropWeights = rates.get(collection.id); + return { ...collection, active: states.get(collection.id) ?? false, ...(dropWeights ? { dropWeights: { ...dropWeights } } : {}) }; + }); + for (const collection of catalog.collections.filter((item) => item.active)) { + if (!collection.dropWeights) throw new TypeError(`Active collection ${collection.id} needs drop rates.`); + } + const holographic = holographicFinishIds(catalog); + const knownIds = new Set(catalog.editions.map((edition) => edition.id)); + const mythics = variations.map((variation) => { + const parent = legendaryParentEdition(catalog, variation.cardId); + if (!parent || !holographic.has(variation.finishId) || variation.editionId !== mythicEditionId(variation.cardId, variation.finishId) || knownIds.has(variation.editionId)) { + throw new TypeError(`Mythic variation ${variation.editionId} needs a legendary card and a holographic finish.`); + } + knownIds.add(variation.editionId); + return { + id: variation.editionId, + cardId: variation.cardId, + rarity: "mythic", + finishIds: [variation.finishId], + promotional: false, + legendaryEditionId: parent.id, + ...(variation.status === "retired" ? { retired: true } : {}) + }; + }); + // Chaque variation suit sa carte légendaire, dans l'ordre des finitions. + const finishOrder = new Map(catalog.finishes.map((finish, index) => [finish.id, index])); + mythics.sort((left, right) => finishOrder.get(left.finishIds[0]) - finishOrder.get(right.finishIds[0])); + catalog.editions = catalog.editions.flatMap((edition) => edition.rarity === "legendary" && !edition.promotional + ? [edition, ...mythics.filter((mythic) => mythic.legendaryEditionId === edition.id)] + : [edition]); + catalog.mythicOpeningSettings = openingSettings + .map(({ scope, targetId, particleShapeId = null, particlePaletteId = null }) => ({ scope, targetId, particleShapeId, particlePaletteId })) + .filter((setting) => setting.particleShapeId || setting.particlePaletteId); + return validateCardsCatalog(catalog); +} + +export function publicCatalog(catalog) { + return JSON.parse(JSON.stringify(catalog)); +} diff --git a/services/cards/database.js b/services/cards/database.js new file mode 100644 index 0000000..c54004e --- /dev/null +++ b/services/cards/database.js @@ -0,0 +1,229 @@ +// Rôle : encapsule la base SQLite et les migrations du mini-jeu Sokko TCG. +import { mkdirSync } from "node:fs"; +import { dirname } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "./admin-seed.js"; + +const MIGRATIONS = [ + ` + CREATE TABLE players ( + id TEXT PRIMARY KEY, + discord_id TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + avatar_url TEXT NOT NULL DEFAULT '', + is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)), + created_at INTEGER NOT NULL, + openings_balance INTEGER NOT NULL DEFAULT 1 CHECK (openings_balance BETWEEN 0 AND 5), + recharge_anchor INTEGER, + stardust INTEGER NOT NULL DEFAULT 0 CHECK (stardust >= 0), + purchased_openings INTEGER NOT NULL DEFAULT 0 CHECK (purchased_openings >= 0) + ) STRICT; + CREATE TABLE sessions ( + token_hash TEXT PRIMARY KEY, + player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, + csrf_token TEXT NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL + ) STRICT; + CREATE INDEX sessions_player_idx ON sessions(player_id); + CREATE TABLE openings ( + id TEXT PRIMARY KEY, + player_id TEXT NOT NULL REFERENCES players(id), + collection_id TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('pending', 'completed')), + created_at INTEGER NOT NULL, + completed_at INTEGER + ) STRICT; + CREATE INDEX openings_player_idx ON openings(player_id, created_at DESC); + -- Collection : une ligne par carte possédée, avec sa quantité. Un joueur garde toujours au moins un exemplaire de + -- chaque carte obtenue (seuls les doublons s'échangent, se donnent ou se recyclent) : une ligne n'est jamais supprimée. + CREATE TABLE collection_cards ( + player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, + edition_id TEXT NOT NULL, + quantity INTEGER NOT NULL CHECK (quantity >= 1), + acquired_at INTEGER NOT NULL, + PRIMARY KEY (player_id, edition_id) + ) STRICT; + CREATE TABLE opening_cards ( + opening_id TEXT NOT NULL REFERENCES openings(id) ON DELETE CASCADE, + position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 2), + edition_id TEXT NOT NULL, + was_new_card INTEGER NOT NULL CHECK (was_new_card IN (0, 1)), + was_new_edition INTEGER NOT NULL CHECK (was_new_edition IN (0, 1)), + quantity_before INTEGER NOT NULL, + PRIMARY KEY (opening_id, position) + ) STRICT; + CREATE TABLE favorites ( + player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, + edition_id TEXT NOT NULL, + PRIMARY KEY (player_id, edition_id) + ) STRICT; + CREATE TABLE transfers ( + id TEXT PRIMARY KEY, + code TEXT NOT NULL UNIQUE, + type TEXT NOT NULL CHECK (type IN ('trade', 'gift')), + initiator_id TEXT NOT NULL REFERENCES players(id), + recipient_id TEXT REFERENCES players(id), + offered_edition_id TEXT NOT NULL, + requested_edition_id TEXT, + initiator_confirmed INTEGER NOT NULL DEFAULT 0 CHECK (initiator_confirmed IN (0, 1)), + recipient_confirmed INTEGER NOT NULL DEFAULT 0 CHECK (recipient_confirmed IN (0, 1)), + status TEXT NOT NULL CHECK (status IN ('open', 'joined', 'completed', 'cancelled', 'expired')), + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + completed_at INTEGER + ) STRICT; + CREATE INDEX transfers_participants_idx ON transfers(initiator_id, recipient_id, status); + -- Un transfert en cours (open, joined) réserve un doublon de chaque carte engagée. + CREATE TABLE campaigns ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + code TEXT NOT NULL UNIQUE, + reward_json TEXT NOT NULL, + max_claims INTEGER CHECK (max_claims IS NULL OR max_claims > 0), + created_by TEXT NOT NULL REFERENCES players(id), + created_at INTEGER NOT NULL, + expires_at INTEGER, + revoked_at INTEGER + ) STRICT; + CREATE TABLE campaign_claims ( + id TEXT PRIMARY KEY, + campaign_id TEXT NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, + player_id TEXT NOT NULL REFERENCES players(id), + claimed_at INTEGER NOT NULL, + UNIQUE (campaign_id, player_id) + ) STRICT; + CREATE TABLE gift_packs ( + id TEXT PRIMARY KEY, + player_id TEXT NOT NULL REFERENCES players(id), + campaign_id TEXT NOT NULL REFERENCES campaigns(id), + collection_id TEXT NOT NULL, + options_json TEXT NOT NULL, + created_at INTEGER NOT NULL, + opening_id TEXT REFERENCES openings(id), + opened_at INTEGER + ) STRICT; + CREATE INDEX gift_packs_player_idx ON gift_packs(player_id, opened_at); + CREATE TABLE idempotency ( + player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, + scope TEXT NOT NULL, + request_key TEXT NOT NULL, + response_json TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (player_id, scope, request_key) + ) STRICT; + CREATE TABLE audit_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + player_id TEXT REFERENCES players(id), + event_type TEXT NOT NULL, + entity_id TEXT NOT NULL, + details_json TEXT NOT NULL, + created_at INTEGER NOT NULL + ) STRICT; + CREATE INDEX audit_player_idx ON audit_log(player_id, created_at DESC); + `, + // Contenu géré depuis l'administration : variations mythiques, réglages d'ouverture, état des paquets, + // tables de tirage, recharge des ouvertures et boutique (barème de poussière d'étoiles, prix d'une ouverture). Ces données n'existent qu'ici ; la migration insère le contenu de départ (admin-seed.js). + ` + CREATE INDEX collection_cards_edition_idx ON collection_cards(edition_id); + CREATE INDEX opening_cards_edition_idx ON opening_cards(edition_id); + CREATE TABLE mythic_variations ( + edition_id TEXT PRIMARY KEY, + card_id TEXT NOT NULL, + finish_id TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('active', 'retired')), + updated_at INTEGER NOT NULL, + updated_by TEXT REFERENCES players(id) + ) STRICT; + CREATE TABLE mythic_opening_settings ( + scope TEXT NOT NULL CHECK (scope IN ('collection', 'card')), + target_id TEXT NOT NULL, + particle_shape_id TEXT, + particle_palette_id TEXT, + updated_at INTEGER NOT NULL, + updated_by TEXT REFERENCES players(id), + PRIMARY KEY (scope, target_id) + ) STRICT; + CREATE TABLE collection_states ( + collection_id TEXT PRIMARY KEY, + active INTEGER NOT NULL CHECK (active IN (0, 1)), + updated_at INTEGER NOT NULL, + updated_by TEXT REFERENCES players(id) + ) STRICT; + CREATE TABLE drop_rates ( + collection_id TEXT PRIMARY KEY, + rarity_weights_json TEXT NOT NULL, + updated_at INTEGER NOT NULL, + updated_by TEXT REFERENCES players(id) + ) STRICT; + CREATE TABLE recharge_settings ( + id INTEGER PRIMARY KEY CHECK (id = 1), + interval_ms INTEGER NOT NULL CHECK (interval_ms >= 60000), + max_openings INTEGER NOT NULL CHECK (max_openings BETWEEN 1 AND 5), + updated_at INTEGER NOT NULL, + updated_by TEXT REFERENCES players(id) + ) STRICT; + CREATE TABLE shop_settings ( + id INTEGER PRIMARY KEY CHECK (id = 1), + stardust_values_json TEXT NOT NULL, + opening_price INTEGER NOT NULL CHECK (opening_price > 0), + updated_at INTEGER NOT NULL, + updated_by TEXT REFERENCES players(id) + ) STRICT; + INSERT INTO shop_settings(id, stardust_values_json, opening_price, updated_at, updated_by) VALUES (1, '${JSON.stringify(INITIAL_SHOP_SETTING.stardustValues)}', ${INITIAL_SHOP_SETTING.openingPrice}, 0, NULL); + INSERT INTO recharge_settings(id, interval_ms, max_openings, updated_at, updated_by) VALUES (1, ${INITIAL_RECHARGE_SETTING.intervalMs}, ${INITIAL_RECHARGE_SETTING.maxOpenings}, 0, NULL); + ${INITIAL_COLLECTION_STATES.map(({ collectionId, active }) => `INSERT INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('${collectionId}', ${active ? 1 : 0}, 0, NULL);`).join("\n ")} + ${INITIAL_DROP_RATES.map(({ collectionId, rarityWeights }) => `INSERT INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('${collectionId}', '${JSON.stringify(rarityWeights)}', 0, NULL);`).join("\n ")} + `, + // Propositions directes : plus de code à rejoindre. Les transferts en cours de l'ancien système sont annulés, + // ce qui libère leurs doublons réservés. Les anciens statuts et colonnes restent pour relire l'historique. + ` + ALTER TABLE transfers ADD COLUMN declined INTEGER NOT NULL DEFAULT 0 CHECK (declined IN (0, 1)); + UPDATE transfers SET status = 'cancelled' WHERE status IN ('open', 'joined'); + `, + // Paquet de la Boutique : la collection stardust s'ouvre avec les poids recommandés ; prix et part de ses cartes se règlent dans l'administration. + ` + ALTER TABLE shop_settings ADD COLUMN shop_pack_price INTEGER NOT NULL DEFAULT 60 CHECK (shop_pack_price >= 1); + ALTER TABLE shop_settings ADD COLUMN shop_pack_share INTEGER NOT NULL DEFAULT 50 CHECK (shop_pack_share BETWEEN 0 AND 100); + INSERT OR IGNORE INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('stardust', 1, 0, NULL); + INSERT OR IGNORE INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('stardust', '{"common":64,"rare":24,"epic":8,"legendary":3,"mythic":1}', 0, NULL); + ` +]; + +export class CardsDatabase { + constructor(path) { + if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true }); + this.db = new DatabaseSync(path); + this.db.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"); + this.migrate(); + } + + migrate() { + this.db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at INTEGER NOT NULL) STRICT;"); + const applied = new Set(this.db.prepare("SELECT version FROM schema_migrations").all().map((row) => row.version)); + MIGRATIONS.forEach((sql, index) => { + const version = index + 1; + if (applied.has(version)) return; + this.transaction(() => { + this.db.exec(sql); + this.db.prepare("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)").run(version, Date.now()); + }); + }); + } + + transaction(callback) { + this.db.exec("BEGIN IMMEDIATE"); + try { + const result = callback(); + this.db.exec("COMMIT"); + return result; + } catch (error) { + this.db.exec("ROLLBACK"); + throw error; + } + } + + close() { + this.db.close(); + } +} diff --git a/services/cards/game-rules.js b/services/cards/game-rules.js new file mode 100644 index 0000000..432936c --- /dev/null +++ b/services/cards/game-rules.js @@ -0,0 +1,125 @@ +// Rôle : calcule la recharge des ouvertures et sélectionne les éditions d'un paquet. +import { randomInt } from "node:crypto"; +import { isDrawableEdition } from "./catalog.js"; + +// Réglage de recharge unique (table recharge_settings) : un délai entre deux ouvertures et une réserve maximale. +// Un changement de délai s'applique aussi au temps déjà écoulé depuis la dernière recharge du joueur. +export const MIN_RECHARGE_INTERVAL_MS = 60_000; +export const MAX_RECHARGE_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; + +function checkedSetting({ intervalMs, maxOpenings }) { + if (!Number.isInteger(intervalMs) || intervalMs < 1 || !Number.isInteger(maxOpenings) || maxOpenings < 1) throw new TypeError("Recharge setting is invalid."); + return { intervalMs, maxOpenings }; +} + +export function calculateRecharge(player, now, setting) { + const { intervalMs, maxOpenings } = checkedSetting(setting); + const balance = Math.max(0, Number(player.openingsBalance) || 0); + if (balance >= maxOpenings) return { openingsBalance: maxOpenings, rechargeAnchor: null, nextOpeningAt: null }; + const anchor = player.rechargeAnchor == null ? now : Number(player.rechargeAnchor); + const earned = Math.max(0, Math.floor((now - anchor) / intervalMs)); + const openingsBalance = Math.min(maxOpenings, balance + earned); + if (openingsBalance >= maxOpenings) return { openingsBalance: maxOpenings, rechargeAnchor: null, nextOpeningAt: null }; + const rechargeAnchor = anchor + earned * intervalMs; + return { openingsBalance, rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs }; +} + +// Réserve figée juste sous le maximum, pour le compte de développement : le minuteur continue de tourner et repart à chaque échéance. +export function pinnedRecharge(player, now, setting) { + const { intervalMs, maxOpenings } = checkedSetting(setting); + const anchor = player.rechargeAnchor == null ? now : Number(player.rechargeAnchor); + const rechargeAnchor = anchor + Math.max(0, Math.floor((now - anchor) / intervalMs)) * intervalMs; + return { openingsBalance: Math.max(1, maxOpenings - 1), rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs }; +} + +export function spendOpening(recharge, now, setting) { + const { intervalMs, maxOpenings } = checkedSetting(setting); + if (recharge.openingsBalance < 1) throw Object.assign(new Error("Aucune ouverture disponible."), { status: 409, code: "NO_OPENING" }); + const wasFull = recharge.openingsBalance >= maxOpenings || recharge.rechargeAnchor == null; + const rechargeAnchor = wasFull ? now : recharge.rechargeAnchor; + return { openingsBalance: recharge.openingsBalance - 1, rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs }; +} + +function weightedChoice(entries, random = (max) => randomInt(max)) { + const total = entries.reduce((sum, [, weight]) => sum + weight, 0); + if (total <= 0) throw new TypeError("A weighted choice needs a positive total."); + let cursor = random(total); + for (const [value, weight] of entries) { + cursor -= weight; + if (cursor < 0) return value; + } + return entries.at(-1)[0]; +} + +const pick = (random, max) => (random || ((limit) => randomInt(limit)))(max); + +// Paquet de la Boutique : les cartes de toutes les autres collections actives, plus les légendaires et mythiques de sa propre collection. +// Quand une de ces deux raretés sort, `share` % des tirages reviennent aux cartes de sa collection, quel que soit leur nombre. +const FEATURED_RARITIES = new Set(["legendary", "mythic"]); +export function drawShopPack(catalog, collectionId, random, share) { + const collection = catalog.collections.find((item) => item.id === collectionId && item.active); + if (!collection) throw Object.assign(new Error("Ce paquet n'est pas disponible."), { status: 404, code: "COLLECTION_UNAVAILABLE" }); + if (!collection.dropWeights) throw new TypeError(`No drop rates for ${collectionId}.`); + const sourceOf = new Map(catalog.cards.map((card) => [card.id, card.collectionId])); + const activeIds = new Set(catalog.collections.filter((item) => item.active && item.packCategory !== "shop").map((item) => item.id)); + const drawableEditions = catalog.editions.filter(isDrawableEdition); + const others = drawableEditions.filter((edition) => activeIds.has(sourceOf.get(edition.cardId))); + const featured = drawableEditions.filter((edition) => sourceOf.get(edition.cardId) === collectionId && FEATURED_RARITIES.has(edition.rarity)); + const ofRarity = (editions, rarity) => editions.filter((edition) => edition.rarity === rarity); + const rarityEntries = Object.entries(collection.dropWeights).filter(([rarity, weight]) => weight > 0 && (ofRarity(others, rarity).length || ofRarity(featured, rarity).length)); + if (!rarityEntries.length) throw Object.assign(new Error("Aucune carte ne peut être tirée avec ces taux."), { status: 409, code: "NOTHING_DRAWABLE" }); + return Array.from({ length: 3 }, () => { + const rarity = weightedChoice(rarityEntries, random); + const featuredCandidates = ofRarity(featured, rarity); + const otherCandidates = ofRarity(others, rarity); + const useFeatured = featuredCandidates.length > 0 && (!otherCandidates.length || pick(random, 100) < share); + const candidates = useFeatured ? featuredCandidates : otherCandidates; + return candidates[pick(random, candidates.length)].id; + }); +} + +// Tire les trois cartes d'un paquet. Options des paquets offerts : +// - `weights` : poids personnalisés (sinon ceux de la collection) ; +// - `guarantee` : { type: "rarity", rarity, count } (au moins `count` cartes de cette rareté ou mieux) +// ou { type: "edition", editionId } (cette variation figure dans le paquet) ; +// - `requireActive` : un paquet offert s'ouvre même si la collection est fermée. +export function drawPack(catalog, collectionId, random, { weights = null, guarantee = null, requireActive = true } = {}) { + const collection = catalog.collections.find((item) => item.id === collectionId && (item.active || !requireActive)); + if (!collection) throw Object.assign(new Error("Cette collection n'est pas disponible."), { status: 404, code: "COLLECTION_UNAVAILABLE" }); + const rarityWeights = weights || collection.dropWeights; + if (!rarityWeights) throw new TypeError(`No drop rates for ${collectionId}.`); + const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collectionId).map((card) => card.id)); + const editions = catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition)); + const drawable = (rarity) => editions.some((edition) => edition.rarity === rarity); + const rarityEntries = Object.entries(rarityWeights).filter(([rarity, weight]) => weight > 0 && drawable(rarity)); + if (!rarityEntries.length) throw Object.assign(new Error("Aucune carte ne peut être tirée avec ces taux."), { status: 409, code: "NOTHING_DRAWABLE" }); + const rank = new Map(catalog.rarities.map((rarity, index) => [rarity.id, index])); + const slots = Array.from({ length: 3 }, () => weightedChoice(rarityEntries, random)); + + if (guarantee?.type === "rarity") { + const eligible = catalog.rarities.filter((rarity) => rank.get(rarity.id) >= rank.get(guarantee.rarity) && drawable(rarity.id)).map((rarity) => rarity.id); + if (!eligible.length) throw Object.assign(new Error("Aucune carte de cette rareté ou mieux ne peut être tirée."), { status: 409, code: "GUARANTEE_UNAVAILABLE" }); + const weighted = eligible.map((rarity) => [rarity, rarityWeights[rarity] || 0]).filter(([, weight]) => weight > 0); + let missing = guarantee.count - slots.filter((rarity) => rank.get(rarity) >= rank.get(guarantee.rarity)).length; + // On améliore d'abord les cartes les plus communes. + const order = slots.map((rarity, index) => index).sort((left, right) => rank.get(slots[left]) - rank.get(slots[right])); + for (const index of order) { + if (missing <= 0) break; + if (rank.get(slots[index]) >= rank.get(guarantee.rarity)) continue; + slots[index] = weighted.length ? weightedChoice(weighted, random) : eligible[0]; + missing -= 1; + } + } + + const picked = slots.map((rarity) => { + const candidates = editions.filter((edition) => edition.rarity === rarity); + return candidates[pick(random, candidates.length)]; + }); + if (guarantee?.type === "edition" && !picked.some((edition) => edition.id === guarantee.editionId)) { + const guaranteed = catalog.editions.find((edition) => edition.id === guarantee.editionId && cardIds.has(edition.cardId)); + if (!guaranteed) throw Object.assign(new Error("La carte garantie n'appartient pas à cette collection."), { status: 409, code: "GUARANTEE_UNAVAILABLE" }); + const lowest = picked.reduce((best, edition, index) => (rank.get(edition.rarity) < rank.get(picked[best].rarity) ? index : best), 0); + picked[lowest] = guaranteed; + } + return picked.map((edition) => edition.id); +} diff --git a/services/cards/rewards.js b/services/cards/rewards.js new file mode 100644 index 0000000..10aa919 --- /dev/null +++ b/services/cards/rewards.js @@ -0,0 +1,69 @@ +// Rôle : valide et normalise les récompenses distribuées par codes (des cartes et des paquets avec leurs options). +import { isDrawableEdition, validateRarityWeights } from "./catalog.js"; + +function invalid(message) { + throw Object.assign(new Error(message), { status: 400, code: "REWARD_INVALID" }); +} + +export const MAX_REWARD_ITEMS = 50; +export const MAX_ITEM_QUANTITY = 10; + +// Une récompense est une liste d'éléments : { items: [élément, …] }, au plus 50 éléments. +// Élément « carte » : { type: "card", editionId, quantity: 1 }, chaque carte au plus une fois +// Élément « paquet » : { type: "pack", collectionId, rarityWeights | null, guarantee | null, quantity } +// guarantee : { type: "rarity", rarity, count (1 à 3) } ou { type: "edition", editionId } +export function normalizeReward(reward, catalog) { + const items = reward?.items; + if (!Array.isArray(items) || !items.length) invalid("Ajoutez au moins une carte ou un paquet à offrir."); + if (items.length > MAX_REWARD_ITEMS) invalid(`Au plus ${MAX_REWARD_ITEMS} éléments par récompense.`); + const cardIds = items.filter((item) => item?.type === "card").map((item) => item.editionId); + if (new Set(cardIds).size !== cardIds.length) invalid("Chaque carte ne peut être offerte qu’une fois par récompense."); + return { items: items.map((item) => { + const quantity = item?.quantity ?? 1; + if (item?.type === "card" && quantity !== 1) invalid("Une carte s’offre en un seul exemplaire."); + if (!Number.isInteger(quantity) || quantity < 1 || quantity > MAX_ITEM_QUANTITY) invalid(`Quantité invalide : de 1 à ${MAX_ITEM_QUANTITY} par élément.`); + return { ...normalizeItem(item, catalog), quantity }; + }) }; +} + +function normalizeItem(reward, catalog) { + if (reward?.type === "card") { + if (!catalog.editions.some((edition) => edition.id === reward.editionId)) invalid("Choisissez une carte du catalogue."); + return { type: "card", editionId: reward.editionId }; + } + if (reward?.type !== "pack") invalid("Choisissez une carte ou un paquet à offrir."); + const collection = catalog.collections.find((item) => item.id === reward.collectionId); + if (!collection) invalid("Choisissez une collection."); + const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collection.id).map((card) => card.id)); + if (collection.packCategory === "shop") invalid("Ce paquet ne s’obtient que dans la boutique."); + const drawable = catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition)); + const rarityIds = new Set(catalog.rarities.map((rarity) => rarity.id)); + + let rarityWeights = null; + if (reward.rarityWeights != null) { + try { + validateRarityWeights(reward.rarityWeights, rarityIds, collection.id); + } catch { + invalid("Taux personnalisés invalides : un entier positif ou nul par rareté, pour un total strictement positif."); + } + if (!drawable.some((edition) => reward.rarityWeights[edition.rarity] > 0)) invalid("Ces taux ne permettent de tirer aucune carte de la collection."); + rarityWeights = Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, reward.rarityWeights[rarity.id]])); + } + + let guarantee = null; + if (reward.guarantee?.type === "rarity") { + const { rarity, count } = reward.guarantee; + const rank = catalog.rarities.findIndex((item) => item.id === rarity); + if (rank < 0 || !Number.isInteger(count) || count < 1 || count > 3) invalid("Garantie invalide : de 1 à 3 cartes d’une rareté connue."); + if (!drawable.some((edition) => catalog.rarities.findIndex((item) => item.id === edition.rarity) >= rank)) invalid("Cette collection n’a aucune carte tirable de cette rareté ou mieux."); + guarantee = { type: "rarity", rarity, count }; + } else if (reward.guarantee?.type === "edition") { + const edition = catalog.editions.find((item) => item.id === reward.guarantee.editionId); + if (!edition || !cardIds.has(edition.cardId)) invalid("La carte garantie doit appartenir à la collection du paquet."); + guarantee = { type: "edition", editionId: edition.id }; + } else if (reward.guarantee != null) { + invalid("Garantie inconnue."); + } + if (!rarityWeights && !collection.dropWeights) invalid("Cette collection n’a pas de taux de tirage : définissez des taux personnalisés."); + return { type: "pack", collectionId: collection.id, rarityWeights, guarantee }; +} diff --git a/services/cards/service.js b/services/cards/service.js new file mode 100644 index 0000000..b166467 --- /dev/null +++ b/services/cards/service.js @@ -0,0 +1,854 @@ +// Rôle : applique les règles serveur de propriété, paquets, transferts et distributions Sokko TCG. +import { createHash, randomBytes, randomUUID } from "node:crypto"; +import { normalizeReward } from "./rewards.js"; +import { planRecycling, spareQuantity, validateShopSetting } from "./stardust.js"; +import { FULL_ART_FORMAT, buildPublishedCatalog, createCatalogIndex, holographicFinishIds, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js"; +import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js"; + +const TRANSFER_TTL_MS = 7 * 24 * 60 * 60 * 1000; +const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; +const RARITY_RANK = new Map(["common", "rare", "epic", "legendary", "mythic"].map((rarity, index) => [rarity, index])); + +function fail(status, code, message) { + throw Object.assign(new Error(message), { status, code }); +} + +function token(bytes = 24) { + return randomBytes(bytes).toString("base64url"); +} + +function tokenHash(value) { + return createHash("sha256").update(value).digest("hex"); +} + +function publicPlayer(row) { + return { id: row.id, displayName: row.display_name, avatarUrl: row.avatar_url, isAdmin: Boolean(row.is_admin) }; +} + +// Compte de la connexion « Version développement » et son solde de poussière figé par `devPerks`. +export const DEV_DISCORD_ID = "dev-admin"; +const WELCOME_OPENINGS = 3; +const ADMIN_HISTORY_PAGE_SIZE = 50; +// Liste blanche : audit_log garde aussi les actions d'administration, qui n'ont pas leur place dans le journal d'un joueur. +// Les types gift_created, gift_joined, gift_cancelled et trade_joined ne sont plus écrits, mais restent lisibles dans les anciens comptes. +const PLAYER_HISTORY_EVENTS = Object.freeze([ + "welcome_opening", "pack_opened", "gift_pack_opened", "cards_recycled", "opening_purchased", "campaign_claimed", + "trade_created", "trade_received", "trade_declined", "trade_joined", "trade_completed", "trade_cancelled", + "gift_created", "gift_joined", "gift_completed", "gift_cancelled" +]); +const DEV_STARDUST = 1000; + +export class CardsService { + constructor({ database, catalog, now = Date.now, random, devPerks = false } = {}) { + // Serveur Vite local uniquement : ressources permanentes du compte de développement pour tester le jeu sans attendre. + this.devPerks = devPerks; + this.database = database; + this.db = database.db; + // Catalogue versionné préparé par loadCardsCatalog / prepareVersionedCatalog (finitions générées, sans mythiques). + this.versionedCatalog = catalog; + this.now = now; + this.random = random; + this.reloadCatalog(); + } + + get rechargeSetting() { + const row = this.db.prepare("SELECT interval_ms, max_openings, updated_at FROM recharge_settings WHERE id = 1").get(); + return { intervalMs: row.interval_ms, maxOpenings: row.max_openings, updatedAt: row.updated_at }; + } + + // Le délai s'applique immédiatement à tous les joueurs, y compris au temps écoulé depuis leur dernière recharge. + updateRechargeSetting(playerId, { intervalMs } = {}) { + this.requireAdmin(playerId); + if (!Number.isInteger(intervalMs) || intervalMs < MIN_RECHARGE_INTERVAL_MS || intervalMs > MAX_RECHARGE_INTERVAL_MS || intervalMs % MIN_RECHARGE_INTERVAL_MS !== 0) { + fail(400, "RECHARGE_INTERVAL_INVALID", "Délai invalide : un nombre entier de minutes, entre 1 minute et 7 jours."); + } + const current = this.rechargeSetting; + if (current.intervalMs === intervalMs) fail(409, "RECHARGE_UNCHANGED", "Ce délai est déjà en vigueur."); + this.database.transaction(() => { + this.db.prepare("UPDATE recharge_settings SET interval_ms = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(intervalMs, this.now(), playerId); + this.audit(playerId, "recharge_updated", "recharge", { previousIntervalMs: current.intervalMs, intervalMs }); + }); + return { rechargeSetting: this.rechargeSetting }; + } + + get shopSetting() { + const row = this.db.prepare("SELECT stardust_values_json, opening_price, shop_pack_price, shop_pack_share, updated_at FROM shop_settings WHERE id = 1").get(); + return { stardustValues: JSON.parse(row.stardust_values_json), openingPrice: row.opening_price, shopPackPrice: row.shop_pack_price, shopPackShare: row.shop_pack_share, updatedAt: row.updated_at }; + } + + updateShopSetting(playerId, { stardustValues, openingPrice, shopPackPrice, shopPackShare } = {}) { + this.requireAdmin(playerId); + const previous = this.shopSetting; + const next = { stardustValues, openingPrice, shopPackPrice: shopPackPrice ?? previous.shopPackPrice, shopPackShare: shopPackShare ?? previous.shopPackShare }; + const error = validateShopSetting(next, this.catalog.rarities.map((rarity) => rarity.id)); + if (error) fail(400, "SHOP_SETTING_INVALID", error); + this.database.transaction(() => { + this.db.prepare("UPDATE shop_settings SET stardust_values_json = ?, opening_price = ?, shop_pack_price = ?, shop_pack_share = ?, updated_at = ?, updated_by = ? WHERE id = 1") + .run(JSON.stringify(next.stardustValues), next.openingPrice, next.shopPackPrice, next.shopPackShare, this.now(), playerId); + this.audit(playerId, "shop_updated", "shop", { previous: { stardustValues: previous.stardustValues, openingPrice: previous.openingPrice, shopPackPrice: previous.shopPackPrice, shopPackShare: previous.shopPackShare }, ...next }); + }); + return { shopSetting: this.shopSetting }; + } + + // Ignore les lignes devenues incohérentes avec le catalogue versionné (carte, finition, forme ou palette supprimées) + // pour que le serveur démarre toujours ; elles restent en base et réapparaissent si la cible revient. + adminContent() { + const versioned = this.versionedCatalog; + const holographic = holographicFinishIds(versioned); + const cardIds = new Set(versioned.cards.map((card) => card.id)); + const collectionIds = new Set(versioned.collections.map((collection) => collection.id)); + const shapeIds = new Set(versioned.particleShapes.map((shape) => shape.id)); + const paletteIds = new Set([...versioned.particlePalettes.map((palette) => palette.id), MATCH_HOLO_PALETTE_ID]); + const variations = this.db.prepare("SELECT edition_id, card_id, finish_id, status FROM mythic_variations").all() + .map((row) => ({ editionId: row.edition_id, cardId: row.card_id, finishId: row.finish_id, status: row.status })) + .filter((row) => holographic.has(row.finishId) && legendaryParentEdition(versioned, row.cardId) && row.editionId === mythicEditionId(row.cardId, row.finishId)); + const openingSettings = this.db.prepare("SELECT scope, target_id, particle_shape_id, particle_palette_id FROM mythic_opening_settings ORDER BY scope, target_id").all() + .map((row) => ({ + scope: row.scope, + targetId: row.target_id, + particleShapeId: shapeIds.has(row.particle_shape_id) ? row.particle_shape_id : null, + particlePaletteId: paletteIds.has(row.particle_palette_id) ? row.particle_palette_id : null + })) + .filter((row) => (row.scope === "card" ? cardIds : collectionIds).has(row.targetId)); + const collectionStates = this.db.prepare("SELECT collection_id, active FROM collection_states").all() + .filter((row) => collectionIds.has(row.collection_id)) + .map((row) => ({ collectionId: row.collection_id, active: Boolean(row.active) })); + const rarityIds = new Set(versioned.rarities.map((rarity) => rarity.id)); + const dropRates = this.db.prepare("SELECT collection_id, rarity_weights_json FROM drop_rates").all() + .map((row) => ({ collectionId: row.collection_id, rarityWeights: JSON.parse(row.rarity_weights_json) })) + .filter((rate) => { + if (!collectionIds.has(rate.collectionId)) return false; + try { + validateRarityWeights(rate.rarityWeights, rarityIds, rate.collectionId); + return true; + } catch { + return false; + } + }); + return { variations, openingSettings, collectionStates, dropRates }; + } + + reloadCatalog() { + const catalog = buildPublishedCatalog(this.versionedCatalog, this.adminContent()); + this.catalog = catalog; + this.index = createCatalogIndex(catalog); + return catalog; + } + + requireAdmin(playerId) { + const player = this.db.prepare("SELECT is_admin FROM players WHERE id = ?").get(playerId); + if (!player?.is_admin) fail(403, "ADMIN_REQUIRED", "Accès administrateur requis."); + } + + validateOpeningStyle({ particleShapeId = null, particlePaletteId = null } = {}) { + if (particleShapeId != null && !this.versionedCatalog.particleShapes.some((shape) => shape.id === particleShapeId)) fail(400, "PARTICLE_SHAPE_INVALID", "Forme de particules inconnue."); + if (particlePaletteId != null && particlePaletteId !== MATCH_HOLO_PALETTE_ID && !this.versionedCatalog.particlePalettes.some((palette) => palette.id === particlePaletteId)) fail(400, "PARTICLE_PALETTE_INVALID", "Palette de particules inconnue."); + return { particleShapeId, particlePaletteId }; + } + + writeOpeningSetting(playerId, scope, targetId, { particleShapeId, particlePaletteId }) { + if (!particleShapeId && !particlePaletteId) { + this.db.prepare("DELETE FROM mythic_opening_settings WHERE scope = ? AND target_id = ?").run(scope, targetId); + return; + } + this.db.prepare(`INSERT INTO mythic_opening_settings(scope, target_id, particle_shape_id, particle_palette_id, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(scope, target_id) DO UPDATE SET particle_shape_id = excluded.particle_shape_id, particle_palette_id = excluded.particle_palette_id, updated_at = excluded.updated_at, updated_by = excluded.updated_by`) + .run(scope, targetId, particleShapeId, particlePaletteId, this.now(), playerId); + } + + // Édition encore possédée, ou citée par une ouverture ou un transfert passés (même si l'exemplaire a été recyclé). + editionReferenced(editionId) { + return Boolean(this.db.prepare(`SELECT 1 FROM collection_cards WHERE edition_id = ?1 + UNION ALL SELECT 1 FROM opening_cards WHERE edition_id = ?1 + UNION ALL SELECT 1 FROM transfers WHERE offered_edition_id = ?1 OR requested_edition_id = ?1 LIMIT 1`).get(editionId)); + } + + // Nombre de campagnes qui citent chaque édition, comme carte offerte ou carte garantie d'un paquet. + // Les paquets offerts reprennent la récompense de leur campagne : ils sont couverts aussi. + editionCampaignCounts() { + const counts = {}; + for (const row of this.db.prepare("SELECT reward_json FROM campaigns").all()) { + const ids = new Set(JSON.parse(row.reward_json).items.map((item) => (item.type === "card" ? item.editionId : item.guarantee?.editionId)).filter(Boolean)); + for (const id of ids) counts[id] = (counts[id] || 0) + 1; + } + return counts; + } + + setCardMythicConfig(playerId, cardId, { finishIds, opening = {} } = {}) { + this.requireAdmin(playerId); + const versioned = this.versionedCatalog; + const card = versioned.cards.find((item) => item.id === cardId); + if (!card) fail(404, "CARD_NOT_FOUND", "Carte introuvable."); + if (!legendaryParentEdition(versioned, cardId)) fail(400, "LEGENDARY_REQUIRED", "Seule une carte légendaire peut recevoir une version mythique."); + const holographic = holographicFinishIds(versioned); + if (!Array.isArray(finishIds) || finishIds.some((id) => typeof id !== "string" || !holographic.has(id))) fail(400, "FINISH_INVALID", "Choisissez uniquement des finitions holographiques."); + const needsFullImage = (id) => versioned.finishes.find((item) => item.id === id)?.formatId === FULL_ART_FORMAT; + if (!card.fullImage && finishIds.some(needsFullImage)) fail(400, "FULL_IMAGE_REQUIRED", "Cette carte n’a pas d’illustration pleine."); + const openingStyle = this.validateOpeningStyle(opening); + const wanted = new Set(finishIds); + const now = this.now(); + this.database.transaction(() => { + // Une seule règle pour toutes les variations : retirée des tirages si un joueur la possède ou si une campagne + // la cite (sinon ses codes et paquets offerts ne fonctionneraient plus), supprimée sinon. + const campaignCounts = this.editionCampaignCounts(); + for (const finishId of holographic) { + const editionId = mythicEditionId(cardId, finishId); + const row = this.db.prepare("SELECT status FROM mythic_variations WHERE edition_id = ?").get(editionId); + if (wanted.has(finishId)) { + if (row?.status !== "active") { + this.db.prepare(`INSERT INTO mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by) VALUES (?, ?, ?, 'active', ?, ?) + ON CONFLICT(edition_id) DO UPDATE SET status = 'active', updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(editionId, cardId, finishId, now, playerId); + } + } else if (row && (this.editionReferenced(editionId) || campaignCounts[editionId] > 0)) { + if (row.status !== "retired") this.db.prepare("UPDATE mythic_variations SET status = 'retired', updated_at = ?, updated_by = ? WHERE edition_id = ?").run(now, playerId, editionId); + } else if (row) { + this.db.prepare("DELETE FROM mythic_variations WHERE edition_id = ?").run(editionId); + } + } + this.writeOpeningSetting(playerId, "card", cardId, openingStyle); + this.audit(playerId, "catalog_card_mythic_updated", cardId, { finishIds: [...wanted], opening: openingStyle }); + this.reloadCatalog(); + }); + return { catalog: publicCatalog(this.catalog) }; + } + + requireCollection(collectionId) { + if (!this.versionedCatalog.collections.some((collection) => collection.id === collectionId)) fail(404, "COLLECTION_NOT_FOUND", "Collection introuvable."); + } + + setCollectionActive(playerId, collectionId, active) { + this.requireAdmin(playerId); + this.requireCollection(collectionId); + if (typeof active !== "boolean") fail(400, "COLLECTION_STATE_INVALID", "État du paquet invalide."); + if (active && !this.index.collections.get(collectionId)?.dropWeights) fail(409, "DROP_RATES_REQUIRED", "Définissez d’abord les taux de tirage de ce paquet."); + this.database.transaction(() => { + this.db.prepare(`INSERT INTO collection_states(collection_id, active, updated_at, updated_by) VALUES (?, ?, ?, ?) + ON CONFLICT(collection_id) DO UPDATE SET active = excluded.active, updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(collectionId, active ? 1 : 0, this.now(), playerId); + this.audit(playerId, active ? "collection_opened" : "collection_closed", collectionId, {}); + this.reloadCatalog(); + }); + return { catalog: publicCatalog(this.catalog) }; + } + + // Les taux de tirage se modifient directement ; le journal d'audit garde les anciens et les nouveaux poids. + setDropRates(playerId, collectionId, rarityWeights) { + this.requireAdmin(playerId); + this.requireCollection(collectionId); + const rarityIds = new Set(this.versionedCatalog.rarities.map((rarity) => rarity.id)); + try { + validateRarityWeights(rarityWeights, rarityIds, collectionId); + } catch { + fail(400, "DROP_WEIGHTS_INVALID", "Poids invalides : un entier positif ou nul par rareté, pour un total strictement positif."); + } + const previous = this.index.collections.get(collectionId)?.dropWeights || null; + if (previous && [...rarityIds].every((rarity) => previous[rarity] === rarityWeights[rarity])) fail(409, "DROP_RATES_UNCHANGED", "Ces taux sont déjà en vigueur."); + const weights = Object.fromEntries([...rarityIds].map((rarity) => [rarity, rarityWeights[rarity]])); + this.database.transaction(() => { + this.db.prepare(`INSERT INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES (?, ?, ?, ?) + ON CONFLICT(collection_id) DO UPDATE SET rarity_weights_json = excluded.rarity_weights_json, updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(collectionId, JSON.stringify(weights), this.now(), playerId); + this.audit(playerId, "drop_rates_updated", collectionId, { previous, rarityWeights: weights }); + this.reloadCatalog(); + }); + return { catalog: publicCatalog(this.catalog) }; + } + + setCollectionMythicOpening(playerId, collectionId, opening = {}) { + this.requireAdmin(playerId); + if (!this.versionedCatalog.collections.some((collection) => collection.id === collectionId)) fail(404, "COLLECTION_NOT_FOUND", "Collection introuvable."); + const openingStyle = this.validateOpeningStyle(opening); + this.database.transaction(() => { + this.writeOpeningSetting(playerId, "collection", collectionId, openingStyle); + this.audit(playerId, "catalog_collection_opening_updated", collectionId, { opening: openingStyle }); + this.reloadCatalog(); + }); + return { catalog: publicCatalog(this.catalog) }; + } + + upsertPlayer({ discordId, displayName, avatarUrl = "", isAdmin = false }) { + const now = this.now(); + let row = this.db.prepare("SELECT * FROM players WHERE discord_id = ?").get(discordId); + if (!row) { + const id = randomUUID(); + this.db.prepare(`INSERT INTO players(id, discord_id, display_name, avatar_url, is_admin, created_at, openings_balance, recharge_anchor) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(id, discordId, displayName, avatarUrl, isAdmin ? 1 : 0, now, WELCOME_OPENINGS, now); + row = this.db.prepare("SELECT * FROM players WHERE id = ?").get(id); + this.audit(id, "welcome_opening", id, { amount: WELCOME_OPENINGS }); + } else { + this.db.prepare("UPDATE players SET display_name = ?, avatar_url = ?, is_admin = ? WHERE id = ?").run(displayName, avatarUrl, isAdmin ? 1 : 0, row.id); + row = this.db.prepare("SELECT * FROM players WHERE id = ?").get(row.id); + } + return publicPlayer(row); + } + + createSession(playerId) { + const rawToken = token(32); + const csrfToken = token(24); + const now = this.now(); + this.db.prepare("INSERT INTO sessions(token_hash, player_id, csrf_token, created_at, expires_at) VALUES (?, ?, ?, ?, ?)") + .run(tokenHash(rawToken), playerId, csrfToken, now, now + SESSION_TTL_MS); + return { token: rawToken, csrfToken, expiresAt: now + SESSION_TTL_MS }; + } + + getSession(rawToken) { + if (!rawToken) return null; + const row = this.db.prepare(`SELECT s.*, p.discord_id, p.display_name, p.avatar_url, p.is_admin + FROM sessions s JOIN players p ON p.id = s.player_id WHERE s.token_hash = ?`).get(tokenHash(rawToken)); + if (!row || row.expires_at <= this.now()) { + if (row) this.db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(tokenHash(rawToken)); + return null; + } + return { player: publicPlayer({ id: row.player_id, ...row }), csrfToken: row.csrf_token, expiresAt: row.expires_at }; + } + + deleteSession(rawToken) { + if (rawToken) this.db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(tokenHash(rawToken)); + } + + refreshRecharge(playerId) { + const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId); + if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable."); + const pinned = this.devPerks && player.discord_id === DEV_DISCORD_ID; + const recharge = (pinned ? pinnedRecharge : calculateRecharge)({ + openingsBalance: player.openings_balance, + rechargeAnchor: player.recharge_anchor + }, this.now(), this.rechargeSetting); + this.db.prepare("UPDATE players SET openings_balance = ?, recharge_anchor = ? WHERE id = ?") + .run(recharge.openingsBalance, recharge.rechargeAnchor, playerId); + if (pinned) this.db.prepare("UPDATE players SET stardust = ? WHERE id = ?").run(DEV_STARDUST, playerId); + return recharge; + } + + // Carte affichable à partir d'une édition (catalogue publié). + cardEntry(editionId, extra = {}) { + const edition = this.index.editions.get(editionId); + const card = edition ? this.index.cards.get(edition.cardId) : null; + return { editionId, edition, card, ...extra }; + } + + quantityOf(playerId, editionId) { + return this.db.prepare("SELECT quantity FROM collection_cards WHERE player_id = ? AND edition_id = ?").get(playerId, editionId)?.quantity ?? 0; + } + + addCard(playerId, editionId) { + this.db.prepare(`INSERT INTO collection_cards(player_id, edition_id, quantity, acquired_at) VALUES (?, ?, 1, ?) + ON CONFLICT(player_id, edition_id) DO UPDATE SET quantity = quantity + 1`).run(playerId, editionId, this.now()); + } + + // Retire des doublons : l'exemplaire conservé ne peut jamais partir. + removeDuplicates(playerId, editionId, count) { + const removed = this.db.prepare("UPDATE collection_cards SET quantity = quantity - ?1 WHERE player_id = ?2 AND edition_id = ?3 AND quantity - ?1 >= 1").run(count, playerId, editionId); + if (!removed.changes) fail(409, "COLLECTION_CHANGED", "Votre collection a changé, réessayez."); + } + + // Doublons réservés par les transferts en cours du joueur, par carte. + reservedCounts(playerId) { + const rows = this.db.prepare(`SELECT edition_id, COUNT(*) AS count FROM ( + SELECT offered_edition_id AS edition_id FROM transfers WHERE initiator_id = ?1 AND status = 'open' + ) GROUP BY edition_id`).all(playerId); + return new Map(rows.map((row) => [row.edition_id, row.count])); + } + + // Collection du joueur : quantité, doublons réservés et doublons disponibles (échange, don, recyclage) par carte. + collectionOf(playerId) { + const reserved = this.reservedCounts(playerId); + return this.db.prepare("SELECT edition_id, quantity, acquired_at FROM collection_cards WHERE player_id = ? ORDER BY acquired_at DESC, edition_id").all(playerId) + .map((row) => { + const entry = { editionId: row.edition_id, quantity: row.quantity, reserved: reserved.get(row.edition_id) || 0, acquiredAt: row.acquired_at }; + return { ...entry, spare: spareQuantity(entry) }; + }); + } + + requireSpare(playerId, editionId) { + const entry = this.collectionOf(playerId).find((item) => item.editionId === editionId); + if (!entry) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte."); + if (!entry.spare) fail(409, "NOT_A_DUPLICATE", "Seuls les doublons peuvent être échangés ou donnés : gardez au moins un exemplaire."); + } + + openingById(openingId, playerId) { + const opening = this.db.prepare("SELECT * FROM openings WHERE id = ? AND player_id = ?").get(openingId, playerId); + if (!opening) return null; + const cards = this.db.prepare("SELECT * FROM opening_cards WHERE opening_id = ? ORDER BY position").all(opening.id); + const gift = this.db.prepare("SELECT options_json FROM gift_packs WHERE opening_id = ?").get(opening.id); + return { + id: opening.id, + collectionId: opening.collection_id, + options: gift ? JSON.parse(gift.options_json) : null, + status: opening.status, + createdAt: opening.created_at, + cards: cards.map((row) => this.cardEntry(row.edition_id, { id: `${opening.id}:${row.position}`, position: row.position, isNewCard: Boolean(row.was_new_card), isNewEdition: Boolean(row.was_new_edition), quantityBefore: row.quantity_before })) + }; + } + + rarestPull(playerId) { + const pulls = this.db.prepare(`SELECT oc.edition_id, oc.position, o.id AS opening_id, o.created_at AS opened_at + FROM opening_cards oc + JOIN openings o ON o.id = oc.opening_id + WHERE o.player_id = ? + ORDER BY o.created_at DESC, oc.position DESC`).all(playerId); + let rarest = null; + for (const pull of pulls) { + const entry = this.cardEntry(pull.edition_id, { id: `${pull.opening_id}:${pull.position}`, openedAt: pull.opened_at }); + if (!rarest || (RARITY_RANK.get(entry.edition?.rarity) ?? -1) > (RARITY_RANK.get(rarest.edition?.rarity) ?? -1)) rarest = entry; + } + return rarest; + } + + // Un transfert expiré ou annulé libère simplement ses doublons réservés (la réservation découle du statut). + expireTransfers() { + this.db.prepare("UPDATE transfers SET status = 'expired' WHERE status = 'open' AND expires_at <= ?").run(this.now()); + } + + transferView(row, playerId) { + const initiator = this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id = ?").get(row.initiator_id); + const recipient = row.recipient_id ? this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id = ?").get(row.recipient_id) : null; + return { + id: row.id, type: row.type, status: row.status, declined: Boolean(row.declined), createdAt: row.created_at, expiresAt: row.expires_at, completedAt: row.completed_at, + direction: row.initiator_id === playerId ? "sent" : "received", + initiator: initiator && { id: initiator.id, displayName: initiator.display_name, avatarUrl: initiator.avatar_url }, + recipient: recipient && { id: recipient.id, displayName: recipient.display_name, avatarUrl: recipient.avatar_url }, + offered: this.cardEntry(row.offered_edition_id), + requested: row.requested_edition_id ? this.cardEntry(row.requested_edition_id) : null + }; + } + + getState(playerId) { + const recharge = this.database.transaction(() => this.refreshRecharge(playerId)); + this.expireTransfers(); + const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId); + if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable."); + const owned = this.collectionOf(playerId); + const collection = owned.map((entry) => this.cardEntry(entry.editionId, entry)); + const favorites = this.db.prepare("SELECT edition_id FROM favorites WHERE player_id = ?").all(playerId).map((row) => row.edition_id); + const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(playerId); + const history = this.db.prepare("SELECT event_type, entity_id, details_json, created_at FROM audit_log WHERE player_id = ? AND event_type IN (" + PLAYER_HISTORY_EVENTS.map(() => "?").join(", ") + ") ORDER BY created_at DESC LIMIT 100").all(playerId, ...PLAYER_HISTORY_EVENTS) + .map((row) => ({ type: row.event_type, entityId: row.entity_id, details: JSON.parse(row.details_json), createdAt: row.created_at })); + const transferRows = this.db.prepare("SELECT * FROM transfers WHERE initiator_id = ? OR recipient_id = ? ORDER BY created_at DESC LIMIT 50").all(playerId, playerId); + const giftPacks = this.db.prepare(`SELECT g.id, g.collection_id, g.options_json, g.created_at, c.name AS campaign_name + 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) + .map((row) => ({ id: row.id, collectionId: row.collection_id, campaignName: row.campaign_name, receivedAt: row.created_at, options: JSON.parse(row.options_json) })); + const openingsCount = this.db.prepare("SELECT COUNT(*) AS count FROM openings WHERE player_id = ?").get(playerId).count; + const shop = this.shopSetting; + const recycling = this.recyclingPlan(owned); + return { + player: publicPlayer(player), recharge, collection, favorites, + wallet: { stardust: player.stardust, purchasedOpenings: player.purchased_openings }, + shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare }, + recycling: { count: recycling.count, stardust: recycling.stardust }, + pendingOpening: pending ? this.openingById(pending.id, playerId) : null, + rarestPull: this.rarestPull(playerId), stats: { openingsCount }, + history, transfers: transferRows.map((row) => this.transferView(row, playerId)), giftPacks + }; + } + + // Tout ce qui n'est pas un événement de jeu : une nouvelle action d'administration apparaît ici sans autre déclaration. + getAdminHistory(playerId, { before = null } = {}) { + this.requireAdmin(playerId); + const rows = this.db.prepare(`SELECT a.id, a.event_type, a.entity_id, a.details_json, a.created_at, p.display_name AS admin_name, c.name AS campaign_name + FROM audit_log a + LEFT JOIN players p ON p.id = a.player_id + LEFT JOIN campaigns c ON c.id = a.entity_id AND a.event_type LIKE 'campaign_%' + WHERE a.event_type NOT IN (${PLAYER_HISTORY_EVENTS.map(() => "?").join(", ")}) AND (? IS NULL OR a.id < ?) + ORDER BY a.id DESC LIMIT ?`).all(...PLAYER_HISTORY_EVENTS, before, before, ADMIN_HISTORY_PAGE_SIZE + 1); + const page = rows.slice(0, ADMIN_HISTORY_PAGE_SIZE); + return { + entries: page.map((row) => ({ id: row.id, type: row.event_type, entityId: row.entity_id, details: JSON.parse(row.details_json), createdAt: row.created_at, adminName: row.admin_name, campaignName: row.campaign_name })), + nextBefore: rows.length > ADMIN_HISTORY_PAGE_SIZE ? page.at(-1).id : null + }; + } + + getAdminDashboard(playerId) { + this.requireAdmin(playerId); + // Cartes possédées par joueur et par rareté (la rareté vient du catalogue publié). + const rarityCounts = new Map(); + for (const row of this.db.prepare("SELECT player_id, edition_id, quantity FROM collection_cards").all()) { + const rarity = this.index.editions.get(row.edition_id)?.rarity; + if (!rarity) continue; + const counts = rarityCounts.get(row.player_id) || {}; + counts[rarity] = (counts[rarity] || 0) + row.quantity; + rarityCounts.set(row.player_id, counts); + } + const players = this.database.transaction(() => this.db.prepare(`SELECT p.*, + (SELECT MAX(o.created_at) FROM openings o WHERE o.player_id = p.id) AS last_opening_at, + (SELECT COUNT(*) FROM openings o WHERE o.player_id = p.id) AS openings_count, + (SELECT COALESCE(SUM(c.quantity), 0) FROM collection_cards c WHERE c.player_id = p.id) AS total_cards, + (SELECT COUNT(*) FROM gift_packs g WHERE g.player_id = p.id AND g.opening_id IS NULL) AS gift_packs, + (SELECT COUNT(*) FROM transfers t WHERE t.status = 'completed' AND (t.initiator_id = p.id OR t.recipient_id = p.id)) AS transfers_count + FROM players p ORDER BY p.display_name COLLATE NOCASE`).all().map((row) => { + const recharge = this.refreshRecharge(row.id); + return { + id: row.id, + displayName: row.display_name, + avatarUrl: row.avatar_url, + isAdmin: Boolean(row.is_admin), + createdAt: row.created_at, + lastOpeningAt: row.last_opening_at ?? null, + openingsCount: row.openings_count, + openingsBalance: recharge.openingsBalance, + nextOpeningAt: recharge.nextOpeningAt, + totalCards: row.total_cards, + rarityCounts: rarityCounts.get(row.id) || {}, + giftPacks: row.gift_packs, + transfersCount: row.transfers_count, + stardust: row.stardust, + purchasedOpenings: row.purchased_openings + }; + })); + const now = this.now(); + return { + generatedAt: now, + stats: { + totalPlayers: players.length, + activePlayers7d: this.db.prepare("SELECT COUNT(DISTINCT player_id) AS count FROM openings WHERE created_at >= ?").get(now - 7 * 24 * 3_600_000).count + }, + players, + rechargeSetting: this.rechargeSetting, + shopSetting: this.shopSetting, + campaigns: this.campaignSummaries(), + editionCampaigns: this.editionCampaignCounts(), + // Variations possédées ou citées par une ouverture ou un transfert passés : elles ne peuvent qu'être retirées. + recordedEditions: this.db.prepare(`SELECT edition_id FROM collection_cards UNION SELECT edition_id FROM opening_cards + UNION SELECT offered_edition_id FROM transfers UNION SELECT requested_edition_id FROM transfers WHERE requested_edition_id IS NOT NULL`).all().map((row) => row.edition_id), + editionOwners: Object.fromEntries(this.db.prepare("SELECT edition_id, COUNT(*) AS owners FROM collection_cards GROUP BY edition_id").all().map((row) => [row.edition_id, row.owners])) + }; + } + + // Crée une ouverture en attente de révélation avec les éditions tirées ; utilisé par les paquets normaux, achetés et offerts. + // Une carte ou une édition est « nouvelle » si le joueur ne la possédait pas : une carte obtenue n'est jamais perdue. + insertOpening(playerId, collectionId, editionIds) { + const openingId = randomUUID(); + this.db.prepare("INSERT INTO openings(id, player_id, collection_id, status, created_at) VALUES (?, ?, ?, 'pending', ?)") + .run(openingId, playerId, collectionId, this.now()); + const ownsCard = this.db.prepare("SELECT 1 FROM collection_cards WHERE player_id = ? AND edition_id IN (SELECT value FROM json_each(?)) LIMIT 1"); + editionIds.forEach((editionId, position) => { + const edition = this.index.editions.get(editionId); + const quantity = this.quantityOf(playerId, editionId); + const cardEditions = this.catalog.editions.filter((item) => item.cardId === edition.cardId).map((item) => item.id); + const knownCard = ownsCard.get(playerId, JSON.stringify(cardEditions)); + this.db.prepare("INSERT INTO opening_cards(opening_id, position, edition_id, was_new_card, was_new_edition, quantity_before) VALUES (?, ?, ?, ?, ?, ?)") + .run(openingId, position, editionId, knownCard ? 0 : 1, quantity ? 0 : 1, quantity); + this.addCard(playerId, editionId); + }); + return openingId; + } + + // Rejoue une requête déjà traitée (même clé d'idempotence) ou exécute `create` qui renvoie l'identifiant d'ouverture. + idempotentOpening(playerId, scope, requestKey, create) { + if (!requestKey || requestKey.length > 100) fail(400, "IDEMPOTENCY_REQUIRED", "Une clé d'idempotence est requise."); + let openingId; + this.database.transaction(() => { + const previous = this.db.prepare("SELECT response_json FROM idempotency WHERE player_id = ? AND scope = ? AND request_key = ?").get(playerId, scope, requestKey); + if (previous) { + openingId = JSON.parse(previous.response_json).openingId; + return; + } + const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId); + if (pending) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours."); + openingId = create(); + this.db.prepare("INSERT INTO idempotency(player_id, scope, request_key, response_json, created_at) VALUES (?, ?, ?, ?, ?)") + .run(playerId, scope, requestKey, JSON.stringify({ openingId }), this.now()); + }); + return { opening: this.openingById(openingId, playerId), state: this.getState(playerId) }; + } + + // `purchased` : consomme une ouverture achetée en boutique au lieu de la réserve rechargeable. + openPack(playerId, collectionId, requestKey, { purchased = false } = {}) { + return this.idempotentOpening(playerId, purchased ? "open-purchased" : "open-pack", requestKey, () => { + if (this.catalog.collections.find((item) => item.id === collectionId)?.packCategory === "shop") fail(409, "SHOP_PACK_ONLY", "Ce paquet ne s’obtient que dans la boutique."); + if (purchased) { + const spent = this.db.prepare("UPDATE players SET purchased_openings = purchased_openings - 1 WHERE id = ? AND purchased_openings > 0").run(playerId); + if (!spent.changes) fail(409, "NO_PURCHASED_OPENING", "Vous n’avez aucune ouverture achetée."); + } else { + const spent = spendOpening(this.refreshRecharge(playerId), this.now(), this.rechargeSetting); + this.db.prepare("UPDATE players SET openings_balance = ?, recharge_anchor = ? WHERE id = ?").run(spent.openingsBalance, spent.rechargeAnchor, playerId); + } + const editionIds = drawPack(this.catalog, collectionId, this.random); + const openingId = this.insertOpening(playerId, collectionId, editionIds); + this.audit(playerId, "pack_opened", openingId, { collectionId, cards: editionIds, ...(purchased ? { purchased: true } : {}) }); + return openingId; + }); + } + + recyclingPlan(collection, editionId = null) { + return planRecycling(collection, { editionId, rarityOf: (id) => this.index.editions.get(id)?.rarity, stardustValues: this.shopSetting.stardustValues }); + } + + // Recycle tous les doublons disponibles, ou un seul doublon de `editionId` ; un exemplaire de chaque carte reste toujours. + recycleDuplicates(playerId, { editionId = null } = {}) { + if (editionId != null && !this.index.editions.has(editionId)) fail(404, "EDITION_NOT_FOUND", "Édition introuvable."); + let plan; + this.database.transaction(() => { + this.expireTransfers(); + if (this.db.prepare("SELECT 1 FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId)) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours."); + plan = this.recyclingPlan(this.collectionOf(playerId), editionId); + if (!plan.count) fail(409, "NO_DUPLICATE", editionId ? "Aucun doublon disponible pour cette carte." : "Aucun doublon à recycler."); + for (const item of plan.items) this.removeDuplicates(playerId, item.editionId, item.count); + this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(plan.stardust, playerId); + this.audit(playerId, "cards_recycled", editionId || "duplicates", { count: plan.count, stardust: plan.stardust, editions: plan.items.map((item) => item.editionId) }); + }); + return { recycled: { count: plan.count, stardust: plan.stardust }, state: this.getState(playerId) }; + } + + buyOpening(playerId) { + const { openingPrice } = this.shopSetting; + this.database.transaction(() => { + const bought = this.db.prepare("UPDATE players SET stardust = stardust - ?, purchased_openings = purchased_openings + 1 WHERE id = ? AND stardust >= ?").run(openingPrice, playerId, openingPrice); + if (!bought.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles."); + this.audit(playerId, "opening_purchased", "shop", { price: openingPrice }); + }); + return this.getState(playerId); + } + + // Le paquet de la Boutique se paie en poussière et s'ouvre aussitôt ; il ne consomme aucune ouverture. + buyShopPack(playerId, requestKey) { + return this.idempotentOpening(playerId, "buy-shop-pack", requestKey, () => { + const collection = this.catalog.collections.find((item) => item.packCategory === "shop" && item.active); + if (!collection) fail(404, "COLLECTION_UNAVAILABLE", "Ce paquet n’est pas disponible."); + const { shopPackPrice, shopPackShare } = this.shopSetting; + // Compte de développement : son solde figé doit être appliqué avant de vérifier le prix. + this.refreshRecharge(playerId); + const paid = this.db.prepare("UPDATE players SET stardust = stardust - ? WHERE id = ? AND stardust >= ?").run(shopPackPrice, playerId, shopPackPrice); + if (!paid.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles."); + const editionIds = drawShopPack(this.catalog, collection.id, this.random, shopPackShare); + const openingId = this.insertOpening(playerId, collection.id, editionIds); + this.audit(playerId, "pack_opened", openingId, { collectionId: collection.id, cards: editionIds, price: shopPackPrice }); + return openingId; + }); + } + + // Un paquet offert ne consomme pas d'ouverture rechargeable et s'ouvre même si la collection est fermée. + openGiftPack(playerId, giftPackId, requestKey) { + return this.idempotentOpening(playerId, "open-gift", requestKey, () => { + const gift = this.db.prepare("SELECT * FROM gift_packs WHERE id = ? AND player_id = ? AND opening_id IS NULL").get(giftPackId, playerId); + if (!gift) fail(404, "GIFT_PACK_NOT_FOUND", "Ce paquet offert n'est plus disponible."); + const options = JSON.parse(gift.options_json); + const editionIds = drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights, guarantee: options.guarantee, requireActive: false }); + const openingId = this.insertOpening(playerId, gift.collection_id, editionIds); + this.db.prepare("UPDATE gift_packs SET opening_id = ?, opened_at = ? WHERE id = ?").run(openingId, this.now(), gift.id); + this.audit(playerId, "gift_pack_opened", openingId, { collectionId: gift.collection_id, campaignId: gift.campaign_id, cards: editionIds }); + return openingId; + }); + } + + completeOpening(playerId, openingId) { + const result = this.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE id = ? AND player_id = ? AND status = 'pending'").run(this.now(), openingId, playerId); + if (!result.changes && !this.openingById(openingId, playerId)) fail(404, "OPENING_NOT_FOUND", "Ouverture introuvable."); + return this.getState(playerId); + } + + setFavorite(playerId, editionId, favorite) { + if (!this.index.editions.has(editionId)) fail(404, "EDITION_NOT_FOUND", "Édition introuvable."); + if (favorite) this.db.prepare("INSERT OR IGNORE INTO favorites(player_id, edition_id) VALUES (?, ?)").run(playerId, editionId); + else this.db.prepare("DELETE FROM favorites WHERE player_id = ? AND edition_id = ?").run(playerId, editionId); + return this.getState(playerId); + } + + // Joueurs à qui donner ou proposer un échange : seuls leur identité publique et leurs doublons disponibles sont exposés, jamais leur collection. + listTraders(playerId) { + this.expireTransfers(); + const rows = this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id != ? ORDER BY display_name COLLATE NOCASE").all(playerId); + return { + traders: rows.map((row) => ({ + id: row.id, + displayName: row.display_name, + avatarUrl: row.avatar_url, + duplicates: this.collectionOf(row.id).filter((entry) => entry.spare > 0).map(({ editionId, spare }) => ({ editionId, spare })) + })) + }; + } + + // Déplace un doublon d'un joueur à l'autre ; l'exemplaire conservé reste toujours. + moveDuplicate(fromId, toId, editionId) { + this.removeDuplicates(fromId, editionId, 1); + this.addCard(toId, editionId); + } + + requireRecipient(playerId, recipientId) { + if (recipientId === playerId) fail(409, "SELF_TRANSFER", "Vous ne pouvez pas vous envoyer une carte."); + if (!recipientId || !this.db.prepare("SELECT 1 FROM players WHERE id = ?").get(recipientId)) fail(404, "PLAYER_NOT_FOUND", "Ce joueur est introuvable."); + } + + // Un don arrive immédiatement. Un échange réserve le doublon proposé jusqu'à la réponse, l'annulation ou l'expiration. + createTransfer(playerId, { type, recipientId, editionId, requestedEditionId = null } = {}) { + if (!["trade", "gift"].includes(type)) fail(400, "TRANSFER_TYPE", "Type de transfert invalide."); + const transferId = randomUUID(); + this.database.transaction(() => { + this.expireTransfers(); + this.requireRecipient(playerId, recipientId); + this.requireSpare(playerId, editionId); + const now = this.now(); + const insert = this.db.prepare(`INSERT INTO transfers(id, code, type, initiator_id, recipient_id, offered_edition_id, requested_edition_id, status, created_at, expires_at, completed_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`); + if (type === "gift") { + insert.run(transferId, token(9).toUpperCase(), type, playerId, recipientId, editionId, null, "completed", now, now, now); + this.moveDuplicate(playerId, recipientId, editionId); + this.audit(playerId, "gift_completed", transferId, { sent: editionId, received: null }); + this.audit(recipientId, "gift_completed", transferId, { sent: null, received: editionId }); + return; + } + if (requestedEditionId === editionId) fail(400, "TRADE_SAME_CARD", "Choisissez deux cartes différentes."); + if (!this.collectionOf(recipientId).some((entry) => entry.editionId === requestedEditionId && entry.spare > 0)) fail(409, "TRADE_CARD_UNAVAILABLE", "Ce joueur n’a plus ce doublon disponible."); + insert.run(transferId, token(9).toUpperCase(), type, playerId, recipientId, editionId, requestedEditionId, "open", now, now + TRANSFER_TTL_MS, null); + this.audit(playerId, "trade_created", transferId, { sent: editionId, received: requestedEditionId }); + this.audit(recipientId, "trade_received", transferId, { sent: requestedEditionId, received: editionId }); + }); + return { transfer: this.transferView(this.db.prepare("SELECT * FROM transfers WHERE id = ?").get(transferId), playerId), state: this.getState(playerId) }; + } + + openTrade(transferId) { + const transfer = this.db.prepare("SELECT * FROM transfers WHERE id = ? AND status = 'open'").get(transferId); + if (!transfer) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible."); + return transfer; + } + + acceptTransfer(playerId, transferId) { + this.database.transaction(() => { + this.expireTransfers(); + const transfer = this.openTrade(transferId); + if (transfer.recipient_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible."); + // Le doublon demandé n'est pas réservé tant que la proposition n'est pas acceptée : il a pu partir entre-temps. + this.requireSpare(playerId, transfer.requested_edition_id); + this.moveDuplicate(transfer.initiator_id, playerId, transfer.offered_edition_id); + this.moveDuplicate(playerId, transfer.initiator_id, transfer.requested_edition_id); + this.db.prepare("UPDATE transfers SET status = 'completed', completed_at = ? WHERE id = ?").run(this.now(), transferId); + this.audit(transfer.initiator_id, "trade_completed", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id }); + this.audit(playerId, "trade_completed", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id }); + }); + return this.getState(playerId); + } + + declineTransfer(playerId, transferId) { + this.database.transaction(() => { + this.expireTransfers(); + const transfer = this.openTrade(transferId); + if (transfer.recipient_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible."); + this.db.prepare("UPDATE transfers SET status = 'cancelled', declined = 1 WHERE id = ?").run(transferId); + this.audit(transfer.initiator_id, "trade_declined", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id }); + this.audit(playerId, "trade_declined", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id }); + }); + return this.getState(playerId); + } + + cancelTransfer(playerId, transferId) { + this.database.transaction(() => { + this.expireTransfers(); + const transfer = this.openTrade(transferId); + if (transfer.initiator_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible."); + this.db.prepare("UPDATE transfers SET status = 'cancelled' WHERE id = ?").run(transferId); + this.audit(playerId, "trade_cancelled", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id }); + this.audit(transfer.recipient_id, "trade_cancelled", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id }); + }); + return this.getState(playerId); + } + + // Toutes les campagnes, ou une seule si `campaignId` est donné. + campaignSummaries(campaignId = null) { + return this.db.prepare(`SELECT c.*, (SELECT COUNT(*) FROM campaign_claims cl WHERE cl.campaign_id = c.id) AS claimed_count + FROM campaigns c WHERE ? IS NULL OR c.id = ? ORDER BY c.created_at DESC`).all(campaignId, campaignId).map((row) => ({ + id: row.id, + name: row.name, + code: row.code, + reward: JSON.parse(row.reward_json), + maxClaims: row.max_claims, + claimedCount: row.claimed_count, + createdAt: row.created_at, + expiresAt: row.expires_at, + revokedAt: row.revoked_at + })); + } + + // Une campagne = un code lisible, partagé entre les joueurs, chacun ne l'utilisant qu'une fois. + // `maxClaims` null = utilisations illimitées ; `expiresAt` null = sans date d'expiration. + createCampaign(playerId, { name, reward, code: rawCode, maxClaims, expiresAt } = {}) { + this.requireAdmin(playerId); + const normalized = normalizeReward(reward, this.catalog); + if (!name?.trim() || name.trim().length > 80) fail(400, "CAMPAIGN_INVALID", "Donnez un nom de 1 à 80 caractères à la campagne."); + const code = String(rawCode || "").trim().toUpperCase(); + if (!/^[A-Z0-9][A-Z0-9-]{3,23}$/.test(code)) fail(400, "CAMPAIGN_INVALID", "Code : 4 à 24 caractères, lettres, chiffres et tirets."); + const limit = maxClaims == null ? null : Number(maxClaims); + if (limit !== null && (!Number.isInteger(limit) || limit < 1 || limit > 100_000)) fail(400, "CAMPAIGN_INVALID", "Entre 1 et 100 000 utilisations, ou illimité."); + const expiry = this.campaignExpiry(expiresAt); + if (this.db.prepare("SELECT 1 FROM campaigns WHERE code = ?").get(code)) fail(409, "CODE_TAKEN", "Ce code est déjà utilisé par une autre campagne."); + const campaignId = randomUUID(); + this.database.transaction(() => { + this.db.prepare(`INSERT INTO campaigns(id, name, code, reward_json, max_claims, created_by, created_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(campaignId, name.trim(), code, JSON.stringify(normalized), limit, playerId, this.now(), expiry); + this.audit(playerId, "campaign_created", campaignId, { code, reward: normalized, maxClaims: limit }); + }); + return { campaign: this.campaignSummary(campaignId) }; + } + + campaignSummary(campaignId) { + const [campaign] = this.campaignSummaries(campaignId); + if (!campaign) fail(404, "CAMPAIGN_NOT_FOUND", "Campagne introuvable."); + return campaign; + } + + campaignDetail(playerId, campaignId) { + this.requireAdmin(playerId); + const campaign = this.campaignSummary(campaignId); + const claims = this.db.prepare(`SELECT cl.claimed_at, p.display_name FROM campaign_claims cl JOIN players p ON p.id = cl.player_id + WHERE cl.campaign_id = ? ORDER BY cl.claimed_at, cl.rowid`).all(campaignId).map((row) => ({ playerName: row.display_name, claimedAt: row.claimed_at })); + return { campaign, claims }; + } + + revokeCampaign(playerId, campaignId) { + this.requireAdmin(playerId); + this.database.transaction(() => { + this.campaignSummary(campaignId); + this.db.prepare("UPDATE campaigns SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").run(this.now(), campaignId); + this.audit(playerId, "campaign_revoked", campaignId, {}); + }); + return { campaign: this.campaignSummary(campaignId) }; + } + + // Date d'expiration d'une campagne : null (sans expiration) ou un instant futur. + campaignExpiry(expiresAt) { + if (expiresAt == null) return null; + const expiry = Number(expiresAt); + if (!Number.isFinite(expiry) || expiry <= this.now()) fail(400, "CAMPAIGN_INVALID", "La date d’expiration doit être dans le futur."); + return expiry; + } + + extendCampaign(playerId, campaignId, expiresAt) { + this.requireAdmin(playerId); + const expiry = this.campaignExpiry(expiresAt); + const result = this.db.prepare("UPDATE campaigns SET expires_at = ? WHERE id = ? AND revoked_at IS NULL").run(expiry, campaignId); + if (!result.changes) fail(404, "CAMPAIGN_NOT_FOUND", "Campagne introuvable ou révoquée."); + this.audit(playerId, "campaign_extended", campaignId, { expiresAt: expiry }); + return { campaign: this.campaignSummary(campaignId) }; + } + + claimCampaign(playerId, rawCode) { + const code = String(rawCode || "").trim().toUpperCase(); + let reward; + this.database.transaction(() => { + const row = this.db.prepare("SELECT * FROM campaigns WHERE code = ?").get(code); + if (!row || row.revoked_at || (row.expires_at != null && row.expires_at <= this.now())) fail(404, "CODE_INVALID", "Code invalide, expiré ou révoqué."); + if (this.db.prepare("SELECT 1 FROM campaign_claims WHERE campaign_id = ? AND player_id = ?").get(row.id, playerId)) fail(409, "CAMPAIGN_ALREADY_CLAIMED", "Vous avez déjà reçu cette récompense."); + const used = row.max_claims != null && this.db.prepare("SELECT COUNT(*) AS count FROM campaign_claims WHERE campaign_id = ?").get(row.id).count >= row.max_claims; + if (used) fail(409, "CODE_EXHAUSTED", "Ce code a atteint son nombre maximal d’utilisations."); + reward = JSON.parse(row.reward_json); + for (const item of reward.items) { + for (let copy = 0; copy < item.quantity; copy += 1) { + if (item.type === "card") { + const edition = this.index.editions.get(item.editionId); + if (!edition) fail(409, "REWARD_UNAVAILABLE", "Une carte de cette récompense n’existe plus dans le catalogue."); + this.addCard(playerId, edition.id); + } else { + const options = { rarityWeights: item.rarityWeights, guarantee: item.guarantee }; + this.db.prepare("INSERT INTO gift_packs(id, player_id, campaign_id, collection_id, options_json, created_at) VALUES (?, ?, ?, ?, ?, ?)") + .run(randomUUID(), playerId, row.id, item.collectionId, JSON.stringify(options), this.now()); + } + } + } + this.db.prepare("INSERT INTO campaign_claims(id, campaign_id, player_id, claimed_at) VALUES (?, ?, ?, ?)").run(randomUUID(), row.id, playerId, this.now()); + this.audit(playerId, "campaign_claimed", row.id, { campaignName: row.name, reward }); + }); + return { reward, state: this.getState(playerId) }; + } + + audit(playerId, eventType, entityId, details) { + this.db.prepare("INSERT INTO audit_log(player_id, event_type, entity_id, details_json, created_at) VALUES (?, ?, ?, ?, ?)") + .run(playerId, eventType, entityId, JSON.stringify(details), this.now()); + } +} diff --git a/services/cards/stardust.js b/services/cards/stardust.js new file mode 100644 index 0000000..d319529 --- /dev/null +++ b/services/cards/stardust.js @@ -0,0 +1,35 @@ +// Rôle : règles pures de la poussière d'étoiles (recyclage des doublons, barème de la boutique). +// Le serveur s'en sert aussi pour l'aperçu envoyé au client, qui correspond donc exactement au recyclage appliqué. + +export const MAX_STARDUST_VALUE = 100_000; +export const MAX_OPENING_PRICE = 100_000; + +// Doublons disponibles d'une carte : la quantité possédée moins l'exemplaire toujours conservé et les doublons réservés par un +// transfert en cours. Seuls ces doublons s'échangent, se donnent ou se recyclent. +export const spareQuantity = ({ quantity, reserved = 0 }) => Math.max(0, quantity - 1 - reserved); + +// `collection` : [{ editionId, quantity, reserved }] ; `rarityOf(editionId)` renvoie la rareté de la carte. +// Sans `editionId`, prépare le recyclage de tous les doublons disponibles ; avec, d'un seul doublon de cette carte. +export function planRecycling(collection, { rarityOf, stardustValues, editionId = null }) { + const items = collection + .filter((entry) => !editionId || entry.editionId === editionId) + .map((entry) => { + const count = editionId ? Math.min(1, spareQuantity(entry)) : spareQuantity(entry); + return { editionId: entry.editionId, count, stardust: count * (stardustValues[rarityOf(entry.editionId)] ?? 0) }; + }) + .filter((item) => item.count > 0); + return { items, count: items.reduce((total, item) => total + item.count, 0), stardust: items.reduce((total, item) => total + item.stardust, 0) }; +} + +export function validateShopSetting({ stardustValues, openingPrice, shopPackPrice, shopPackShare } = {}, rarityIds) { + const valid = (value, max) => Number.isInteger(value) && value >= 0 && value <= max; + if (!stardustValues || typeof stardustValues !== "object" || Array.isArray(stardustValues)) return "Barème de poussière invalide."; + for (const rarityId of rarityIds) { + if (!valid(stardustValues[rarityId], MAX_STARDUST_VALUE)) return `Valeur invalide pour la rareté ${rarityId} : un entier entre 0 et ${MAX_STARDUST_VALUE.toLocaleString("fr-FR")}.`; + } + if (Object.keys(stardustValues).some((rarityId) => !rarityIds.includes(rarityId))) return "Rareté inconnue dans le barème."; + if (!valid(openingPrice, MAX_OPENING_PRICE) || openingPrice < 1) return `Prix d’une ouverture invalide : un entier entre 1 et ${MAX_OPENING_PRICE.toLocaleString("fr-FR")}.`; + if (!valid(shopPackPrice, MAX_OPENING_PRICE) || shopPackPrice < 1) return `Prix du paquet de la boutique invalide : un entier entre 1 et ${MAX_OPENING_PRICE.toLocaleString("fr-FR")}.`; + if (!valid(shopPackShare, 100)) return "Part des cartes de la boutique invalide : un entier entre 0 et 100."; + return null; +} diff --git a/tests/helpers/data-validation.mjs b/tests/helpers/data-validation.mjs index 4d92492..b501618 100644 --- a/tests/helpers/data-validation.mjs +++ b/tests/helpers/data-validation.mjs @@ -87,6 +87,7 @@ export function validateSiteContent(site) { "navigation.home", "navigation.toolboxes", "navigation.games", + "navigation.cards", "navigation.library", "navigation.about", "sidebar.badge", @@ -95,6 +96,7 @@ export function validateSiteContent(site) { "topbar.toolbox", "topbar.library", "topbar.games", + "topbar.cards", "topbar.gameViewLabel", "topbar.guideView", "topbar.toolboxView", @@ -106,6 +108,129 @@ export function validateSiteContent(site) { "gamesPage.emptyTitle", "gamesPage.emptyText", "gamesPage.retryLabel", + "cards.eyebrow", + "cards.title", + "cards.description", + "cards.loadingTitle", + "cards.loadingText", + "cards.disabledTitle", + "cards.disabled", + "cards.errorTitle", + "cards.loginDescription", + "cards.discordLogin", + "cards.discordUnavailable", + "cards.discordErrors.denied", + "cards.discordErrors.expired", + "cards.discordErrors.failed", + "cards.devLogin", + "cards.admin.backToGame", + "cards.admin.restrictedTitle", + "cards.admin.restrictedText", + "cards.home.eyebrow", + "cards.home.title", + "cards.home.available", + "cards.home.next", + "cards.home.full", + "cards.home.rarestEyebrow", + "cards.home.rarestTitle", + "cards.home.noPull", + "cards.home.browsePacks", + "cards.home.resume", + "cards.home.resumeAction", + "cards.home.cardsDiscovered", + "cards.home.editionsDiscovered", + "cards.home.ownedCopies", + "cards.home.packsOpened", + "cards.navigation.home", + "cards.navigation.packs", + "cards.navigation.collection", + "cards.navigation.shop", + "cards.navigation.transfers", + "cards.navigation.history", + "cards.transfers.eyebrow", + "cards.transfers.title", + "cards.transfers.newGift", + "cards.transfers.newTrade", + "cards.transfers.inboxTitle", + "cards.transfers.sentTitle", + "cards.transfers.finishedTitle", + "cards.transfers.empty", + "cards.transfers.giftFrom", + "cards.transfers.giftTo", + "cards.transfers.tradeWith", + "cards.transfers.expires", + "cards.transfers.youGive", + "cards.transfers.youReceive", + "cards.transfers.accept", + "cards.transfers.decline", + "cards.transfers.cancel", + "cards.transfers.close", + "cards.transfers.statusCompleted", + "cards.transfers.statusCancelled", + "cards.transfers.statusDeclined", + "cards.transfers.statusExpired", + "cards.transfers.acceptedNotice", + "cards.transfers.declinedNotice", + "cards.transfers.cancelledNotice", + "cards.transfers.typeLabel", + "cards.transfers.typeTrade", + "cards.transfers.typeGift", + "cards.transfers.playerLabel", + "cards.transfers.playerPlaceholder", + "cards.transfers.playerLoading", + "cards.transfers.noPlayers", + "cards.transfers.duplicatesShort", + "cards.transfers.noDuplicates", + "cards.transfers.playerNoDuplicates", + "cards.transfers.choosePlayerFirst", + "cards.transfers.missingBadge", + "cards.transfers.giftHelp", + "cards.transfers.tradeHelp", + "cards.transfers.sameCard", + "cards.transfers.giveAction", + "cards.transfers.toPlayer", + "cards.transfers.sendTrade", + "cards.transfers.giftSentNotice", + "cards.transfers.tradeSentNotice", + "cards.collection.eyebrow", + "cards.collection.title", + "cards.collection.resetFilters", + "cards.history.pendingCards", + "cards.recycling.barLabel", + "cards.recycling.viewDuplicates", + "cards.recycling.viewAll", + "cards.recycling.allButton", + "cards.recycling.ratesLabel", + "cards.recycling.pending", + "cards.recycling.pendingAction", + "cards.home.stardust", + "cards.home.recyclable", + "cards.packs.eyebrow", + "cards.packs.title", + "cards.packs.permanent", + "cards.packs.permanentDescription", + "cards.packs.event", + "cards.packs.eventDescription", + "cards.packs.open", + "cards.packs.probabilities", + "cards.packs.back", + "cards.packs.shopShare", + "cards.shop.packDescription", + "cards.shop.packAction", + "cards.shop.packPending", + "cards.packs.purchasedLabel", + "cards.packs.purchasedHelp", + "cards.packs.empty", + "cards.packs.redeemTitle", + "cards.packs.redeemHelp", + "cards.packs.redeemPlaceholder", + "cards.packs.redeemButton", + "cards.packs.redeemReceived", + "cards.packs.redeemWhere", + "cards.packs.giftTitle", + "cards.packs.giftDescription", + "cards.packs.giftOpen", + "cards.packs.noOpening", "guideChecklist.label", "guideChecklist.selectLabel", "guideChecklist.selectPlaceholder", diff --git a/tests/nebula-cards-api.test.mjs b/tests/nebula-cards-api.test.mjs new file mode 100644 index 0000000..30939b6 --- /dev/null +++ b/tests/nebula-cards-api.test.mjs @@ -0,0 +1,229 @@ +// Rôle : vérifie le contrat HTTP, la session, le CSRF et l'idempotence de l'API Sokko TCG. +import assert from "node:assert/strict"; +import { Readable } from "node:stream"; +import { test } from "node:test"; +import { resolve } from "node:path"; +import { createCardsApiHandler } from "../services/cards/api.js"; + +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: {}, body: "" }; + 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.body += value; } + }; + await handler(mockRequest(options), res); + response.json = response.body ? JSON.parse(response.body) : null; + return response; +} + +test("Discord OAuth preserves the dedicated admin route", async (t) => { + const handler = createCardsApiHandler({ + projectRoot: resolve("."), + enabled: true, + devAuth: false, + databasePath: ":memory:", + env: { + NODE_ENV: "test", + DISCORD_CLIENT_ID: "discord-client", + DISCORD_CLIENT_SECRET: "discord-secret", + CARDS_ADMIN_DISCORD_IDS: "discord-admin" + }, + fetchImpl: async (url) => { + if (String(url).includes("/oauth2/token")) return { ok: true, json: async () => ({ access_token: "discord-token" }) }; + return { ok: true, json: async () => ({ id: "discord-admin", username: "Admin", global_name: "TCG Admin", avatar: null }) }; + } + }); + t.after(() => handler.close()); + + const authorization = await call(handler, { path: "/api/cards/auth/discord?returnTo=%2Fcards%2Fadmin" }); + assert.equal(authorization.status, 302); + const authorizationUrl = new URL(authorization.headers.location); + const state = authorizationUrl.searchParams.get("state"); + const oauthCookies = authorization.headers["set-cookie"]; + assert.ok(oauthCookies.some((cookie) => cookie.startsWith("sokkog_cards_oauth_return=%2Fcards%2Fadmin;"))); + // Le retour après connexion accepte les sections joueur, jamais une adresse hors de Sokko TCG. + for (const [returnTo, expected] of [["/cards/shop", "%2Fcards%2Fshop"], ["/cards/admin/collections/nebula", "%2Fcards%2Fadmin%2Fcollections%2Fnebula"], ["/cards/shop/extra", "%2Fcards"], ["//evil.example/cards", "%2Fcards"], ["/cards/../toolboxes", "%2Fcards"]]) { + const response = await call(handler, { path: `/api/cards/auth/discord?returnTo=${encodeURIComponent(returnTo)}` }); + assert.ok(response.headers["set-cookie"].some((cookie) => cookie.startsWith(`sokkog_cards_oauth_return=${expected};`)), returnTo); + } + + const callback = await call(handler, { + path: `/api/cards/auth/callback?state=${encodeURIComponent(state)}&code=discord-code`, + headers: { cookie: oauthCookies.map((cookie) => cookie.split(";")[0]).join("; ") } + }); + assert.equal(callback.status, 302); + assert.equal(callback.headers.location, "http://localhost:5173/#/cards/admin"); + assert.ok(callback.headers["set-cookie"].some((cookie) => cookie.startsWith("sokkog_cards_oauth_return=;"))); +}); + +test("Discord OAuth failures return to the login screen without opening a session", async (t) => { + const env = { NODE_ENV: "test", DISCORD_CLIENT_ID: "discord-client", DISCORD_CLIENT_SECRET: "discord-secret" }; + let discordResponse = { ok: false, status: 400 }; + const logged = []; + t.mock.method(console, "error", (error) => logged.push(error)); + const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: false, databasePath: ":memory:", env, fetchImpl: async () => discordResponse }); + t.after(() => handler.close()); + const authorization = await call(handler, { path: "/api/cards/auth/discord?returnTo=%2Fcards%2Fshop" }); + const state = new URL(authorization.headers.location).searchParams.get("state"); + const cookie = authorization.headers["set-cookie"].map((value) => value.split(";")[0]).join("; "); + const callback = (query, headers = { cookie }) => call(handler, { path: `/api/cards/auth/callback?${query}`, headers }); + + for (const [query, headers, reason] of [ + [`state=${state}&error=access_denied`, { cookie }, "denied"], + [`state=${state}&code=abc`, {}, "expired"], + [`state=other&code=abc`, { cookie }, "expired"], + [`state=${state}&code=abc`, { cookie }, "failed"], + [`state=${state}`, { cookie }, "failed"] + ]) { + const response = await callback(query, headers); + assert.equal(response.status, 302, query); + assert.equal(response.headers.location, `http://localhost:5173/?cardsAuth=${reason}#${reason === "expired" && !headers.cookie ? "/cards" : "/cards/shop"}`, query); + assert.equal(response.headers["set-cookie"].some((value) => value.startsWith("sokkog_cards_session=")), false, query); + assert.ok(response.headers["set-cookie"].some((value) => value.startsWith("sokkog_cards_oauth_state=;")), query); + } + assert.equal(logged.length, 2); + assert.equal(logged.some((error) => String(error.message).includes("discord-secret")), false); + + discordResponse = { ok: true, status: 200, json: async () => { throw new Error("invalid body"); } }; + assert.equal((await callback(`state=${state}&code=abc`)).headers.location, "http://localhost:5173/?cardsAuth=failed#/cards/shop"); +}); + +test("production refuses to start Sokko TCG without a public origin", () => { + assert.throws(() => createCardsApiHandler({ projectRoot: resolve("."), enabled: true, databasePath: ":memory:", env: { NODE_ENV: "production", CARDS_DB_PATH: ":memory:" } }), /CARDS_PUBLIC_ORIGIN/); +}); + +test("cards API authenticates dev sessions and protects mutations", async (t) => { + const handler = createCardsApiHandler({ + projectRoot: resolve("."), + enabled: true, + devAuth: true, + databasePath: ":memory:", + env: { NODE_ENV: "test" }, + random: () => 0 + }); + t.after(() => handler.close()); + + const config = await call(handler, { path: "/api/cards/config" }); + assert.equal(config.status, 200); + assert.equal(config.json.enabled, true); + assert.equal(config.json.catalog.collections.length, 3); + + const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} }); + assert.equal(login.status, 200); + assert.equal(login.json.player.isAdmin, true); + const sessionCookie = login.headers["set-cookie"].split(";")[0]; + const csrfToken = login.json.csrfToken; + + const rejected = await call(handler, { method: "POST", path: "/api/cards/openings", headers: { cookie: sessionCookie, "idempotency-key": "one" }, body: { collectionId: "primordial-nebula" } }); + assert.equal(rejected.status, 403); + assert.equal(rejected.json.error.code, "CSRF"); + + const opened = await call(handler, { method: "POST", path: "/api/cards/openings", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken, "idempotency-key": "one" }, body: { collectionId: "primordial-nebula" } }); + assert.equal(opened.status, 201); + assert.equal(opened.json.opening.cards.length, 3); + const repeated = await call(handler, { method: "POST", path: "/api/cards/openings", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken, "idempotency-key": "one" }, body: { collectionId: "primordial-nebula" } }); + assert.equal(repeated.json.opening.id, opened.json.opening.id); + + const state = await call(handler, { path: "/api/cards/state", headers: { cookie: sessionCookie } }); + assert.equal(state.status, 200); + assert.equal(state.json.collection.reduce((total, entry) => total + entry.quantity, 0), 3); + + const dashboard = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: sessionCookie } }); + assert.equal(dashboard.status, 200); + assert.equal(dashboard.json.stats.totalPlayers, 1); + assert.equal(dashboard.json.players[0].totalCards, 3); + assert.equal(dashboard.json.shopSetting.openingPrice, 30); + + const recycled = await call(handler, { method: "POST", path: "/api/cards/recycle", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: {} }); + assert.ok([200, 409].includes(recycled.status)); + const shopUpdate = await call(handler, { method: "PUT", path: "/api/cards/admin/shop", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { stardustValues: dashboard.json.shopSetting.stardustValues, openingPrice: 1 } }); + assert.equal(shopUpdate.status, 200); + assert.equal(shopUpdate.json.shopSetting.openingPrice, 1); + const noCsrf = await call(handler, { method: "POST", path: "/api/cards/shop/openings", headers: { cookie: sessionCookie }, body: {} }); + assert.equal(noCsrf.status, 403); + assert.equal("discordId" in dashboard.json.players[0], false); + + const regularPlayer = handler.service.upsertPlayer({ discordId: "regular-player", displayName: "Regular" }); + const regularSession = handler.service.createSession(regularPlayer.id); + const forbidden = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: `sokkog_cards_session=${regularSession.token}` } }); + assert.equal(forbidden.status, 403); + assert.equal(forbidden.json.error.code, "ADMIN_REQUIRED"); + const forbiddenHistory = await call(handler, { path: "/api/cards/admin/history", headers: { cookie: `sokkog_cards_session=${regularSession.token}` } }); + assert.equal(forbiddenHistory.status, 403); + assert.equal((await call(handler, { path: "/api/cards/admin/history?before=abc", headers: { cookie: sessionCookie } })).status, 400); + assert.equal((await call(handler, { path: "/api/cards/admin/history", headers: { cookie: sessionCookie } })).status, 200); + + const mythicPath = "/api/cards/admin/catalog/cards/mythic-card-pull/mythic"; + const mythicBody = { finishIds: ["spectral-prism-solar", "spectral-prism-cosmic"], opening: { particleShapeId: "snowflakes", particlePaletteId: null } }; + const missingCsrf = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: sessionCookie }, body: mythicBody }); + assert.equal(missingCsrf.status, 403); + assert.equal(missingCsrf.json.error.code, "CSRF"); + const regularCsrf = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: mythicBody }); + assert.equal(regularCsrf.status, 403); + assert.equal(regularCsrf.json.error.code, "ADMIN_REQUIRED"); + const updated = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: mythicBody }); + assert.equal(updated.status, 200); + assert.ok(updated.json.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-cosmic")); + const collectionOpening = await call(handler, { method: "PUT", path: "/api/cards/admin/catalog/collections/astral-genesis/mythic-opening", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { particleShapeId: null, particlePaletteId: "match-holo" } }); + assert.equal(collectionOpening.status, 200); + const refreshedConfig = await call(handler, { path: "/api/cards/config" }); + assert.ok(refreshedConfig.json.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-cosmic")); + assert.deepEqual(refreshedConfig.json.catalog.mythicOpeningSettings.map((item) => item.scope).sort(), ["card", "collection"]); + + const dropPath = "/api/cards/admin/collections/astral-genesis/drop-rates"; + const weights = { common: 60, rare: 25, epic: 10, legendary: 4, mythic: 1 }; + const dropForbidden = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: { rarityWeights: weights } }); + assert.equal(dropForbidden.status, 403); + const dropUpdated = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { rarityWeights: weights } }); + assert.equal(dropUpdated.status, 200); + assert.deepEqual(dropUpdated.json.catalog.collections.find((collection) => collection.id === "astral-genesis").dropWeights, weights); + const dropUnchanged = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { rarityWeights: weights } }); + assert.equal(dropUnchanged.status, 409); + const closed = await call(handler, { method: "PUT", path: "/api/cards/admin/collections/astral-genesis/state", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { active: false } }); + assert.equal(closed.status, 200); + const afterClose = await call(handler, { path: "/api/cards/config" }); + assert.equal(afterClose.json.catalog.collections.find((collection) => collection.id === "astral-genesis").active, false); + assert.equal("dropTables" in afterClose.json.catalog, false); + + const rechargeForbidden = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: { intervalMs: 7_200_000 } }); + assert.equal(rechargeForbidden.status, 403); + const rechargeUpdated = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { intervalMs: 7_200_000 } }); + assert.equal(rechargeUpdated.status, 200); + assert.equal(rechargeUpdated.json.rechargeSetting.intervalMs, 7_200_000); + const rechargeInvalid = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { intervalMs: "1h" } }); + assert.equal(rechargeInvalid.status, 400); + const dashboardAfterRecharge = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: sessionCookie } }); + assert.equal(dashboardAfterRecharge.json.rechargeSetting.intervalMs, 7_200_000); +}); + +test("gift pack codes are claimed and opened through the API", async (t) => { + const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 }); + t.after(() => handler.close()); + const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} }); + const headers = { cookie: login.headers["set-cookie"].split(";")[0], "x-csrf-token": login.json.csrfToken }; + const created = await call(handler, { method: "POST", path: "/api/cards/admin/campaigns", headers, body: { name: "Live", reward: { items: [{ type: "pack", collectionId: "astral-genesis", guarantee: { type: "rarity", rarity: "epic", count: 1 } }] }, code: "API-LIVE", maxClaims: null, expiresAt: Date.now() + 60_000 } }); + assert.equal(created.status, 201); + const detail = await call(handler, { path: `/api/cards/admin/campaigns/${created.json.campaign.id}`, headers }); + assert.equal(detail.json.campaign.code, "API-LIVE"); + const claimed = await call(handler, { method: "POST", path: "/api/cards/rewards/claim", headers, body: { code: "api-live" } }); + assert.equal(claimed.status, 200); + assert.equal(claimed.json.state.giftPacks.length, 1); + const opened = await call(handler, { method: "POST", path: `/api/cards/gift-packs/${claimed.json.state.giftPacks[0].id}/open`, headers: { ...headers, "idempotency-key": "gift" } }); + assert.equal(opened.status, 201); + assert.equal(opened.json.opening.cards.length, 3); + const extended = await call(handler, { method: "PUT", path: `/api/cards/admin/campaigns/${created.json.campaign.id}/expiry`, headers, body: { expiresAt: Date.now() + 120_000 } }); + assert.equal(extended.status, 200); +}); diff --git a/tests/nebula-cards.test.mjs b/tests/nebula-cards.test.mjs new file mode 100644 index 0000000..5814525 --- /dev/null +++ b/tests/nebula-cards.test.mjs @@ -0,0 +1,934 @@ +// Rôle : vérifie les règles, la persistance et les mutations protégées de Sokko TCG. +import assert from "node:assert/strict"; +import { access, readdir, readFile } from "node:fs/promises"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { assertVersionedCatalogScope, buildPublishedCatalog, prepareVersionedCatalog, validateCardsCatalog, withGeneratedFinishes } from "../services/cards/catalog.js"; +import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "../services/cards/admin-seed.js"; +import { planRecycling } from "../services/cards/stardust.js"; +import { resolveMythicOpeningStyle, resolveOpeningEffect } from "../website/src/features/cards/openingEffects.js"; +import { summarizeReward } from "../website/src/features/cards/rewardText.js"; +import { CardsDatabase } from "../services/cards/database.js"; +import { calculateRecharge, drawPack, drawShopPack } from "../services/cards/game-rules.js"; +import { CardsService, DEV_DISCORD_ID } from "../services/cards/service.js"; +import { visibleCollections } from "../website/src/features/cards/collectionState.js"; +import { backupCardsDatabase, restoreCardsDatabase, verifyCardsDatabase } from "../services/cards/backup.js"; + +// Catalogue versionné (finitions générées, sans variation mythique) et catalogue publié avec une variation de test. +const rawCatalog = JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")); +const baseCatalog = prepareVersionedCatalog(rawCatalog); +const TEST_MYTHIC_VARIATIONS = [{ editionId: "mythic-card-pull-spectral-prism-solar", cardId: "mythic-card-pull", finishId: "spectral-prism-solar", status: "active" }]; +const catalog = buildPublishedCatalog(baseCatalog, { variations: TEST_MYTHIC_VARIATIONS, collectionStates: INITIAL_COLLECTION_STATES, dropRates: INITIAL_DROP_RATES }); + +test("Sokko TCG uses design system dropdowns instead of native selects", async () => { + const entries = await readdir("website/src/features/cards", { recursive: true }); + const sources = entries.filter((entry) => entry.endsWith(".jsx")); + assert.ok(sources.length > 10); + for (const source of sources) { + assert.doesNotMatch(await readFile(join("website/src/features/cards", source), "utf8"), /