Compare commits

...
31 Commits
Author SHA1 Message Date
ietm64 cccf2b85db Correction test PDF
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 37s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m25s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 58s
Build & Push Images / build (brain) (push) Successful in 1m51s
Build & Push Images / build (web) (push) Successful in 2m21s
Build & Push Images / build (core) (push) Successful in 4m16s
Build & Push Images / build-switcher (push) Successful in 16s
2026-10-17 19:17:37 +02:00
ietm64 6ae9238fee passage v1.5.0-beta
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 49s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 52s
Build & Push Images / build (brain) (push) Successful in 1m24s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m6s
Build & Push Images / build (web) (push) Successful in 2m36s
Build & Push Images / build (core) (push) Successful in 4m19s
Build & Push Images / build-switcher (push) Successful in 22s
2026-10-17 19:05:52 +02:00
ietm64 0ef1380265 Améliore la navigation et la mise en page des exports PDF
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 37s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m37s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m1s
- Ajoute les fils d’Ariane, les favoris et l’historique de navigation
- Étend la recherche aux arcs, chapitres, scènes et quêtes
- Regroupe les actions de campagne dans le menu Gérer
- Améliore la navigation au clavier et sur mobile
- Refonte de l’export A4 : deux colonnes, couverture illustrée et encadrés
- Ajoute des motifs décoratifs en pied de page et une variante pour l’impression
- Vérifie la pagination, les renvois et la confidentialité de l’édition joueurs
2026-10-17 19:05:15 +02:00
ietm64 9a7e93b162 Passage v1.4.0-beta
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 55s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 53s
Build & Push Images / build (brain) (push) Successful in 1m26s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m24s
Build & Push Images / build (web) (push) Successful in 2m11s
Build & Push Images / build (core) (push) Successful in 4m30s
Build & Push Images / build-switcher (push) Successful in 23s
2026-10-17 17:09:13 +02:00
ietm64 106754fd77 Mentor d'écriture : champs d'histoire pour scènes, arcs et PNJ
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 52s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 54s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 54s
- Scène : « Utilité » (ce que l'histoire perd si on la coupe) et « Tactique
  et moral des adversaires » (comment ils se battent, quand ils fuient ou se
  rendent), dans l'éditeur, la vue et le PDF (réservés au MJ).
- Arc : « Histoire cachée » (la vérité que les joueurs reconstituent) et
  « Accroches » (une par ligne), nouvelle section de l'éditeur ; dans le PDF,
  histoire cachée en encadré secret et accroches, version MJ uniquement.
- PNJ : bloc « Rôle dans l'histoire », indépendant du système de jeu : rôle
  (opposant, allié, ressource, figurant), motivation, ce qu'il sait,
  signe distinctif. Dans le PDF, le signe distinctif se voit aussi en
  version joueurs ; rôle, motivation et savoir restent réservés au MJ.
- Huit fiches du coach pour ces champs, rédigées pour LoreMind.
- Relecture d'éditeur : WRITE-016 (opposant ou allié sans motivation, lien
  vers la fiche du PNJ), WRITE-017 (arc avec une seule accroche) ; un combat
  dont la tactique est écrite n'est plus signalé « sans but » (WRITE-008).
- Migration V27 (colonnes scènes/arcs, fiche PNJ en JSON) ; champs
  conservés à l'export/import de campagne.

Vérifié : core clean verify (1277 tests, dont règles, rendu MJ/joueurs,
aller-retour export/import), web build + 844 vitest, lint sans erreur,
migration V27 appliquée sur une base existante et fiche PNJ enregistrée
puis signalée par la relecture dans le navigateur.
À redéployer : core + web (migration V27).
2026-10-17 17:07:10 +02:00
ietm64 0c0581e894 Méthodes guidées : « Enquête en nœuds » et « Plan du méchant »
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 39s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 59s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 48s
- Page de choix de méthode (/campaigns/:id/guided) : les boutons « Méthode
  guidée » de la campagne y mènent ; une carte par méthode avec son
  principe et le nombre de scènes créées.
- Enquête en nœuds : vérité cachée (notes MJ du chapitre), accroche, trois
  pistes de natures variées, conclusion, scène de relance. Les 6 scènes sont
  reliées en réseau (12 liens) : l'accroche ouvre les trois pistes, chaque
  piste renvoie à une autre et donne un indice vers la conclusion, la relance
  ramène aux trois pistes. Ni chemin unique ni passage obligé : la relecture
  d'éditeur ne signale rien sur la structure générée.
- Plan du méchant : l'adversaire, ce qu'il veut et ce qui arrive s'il
  réussit, puis six étapes (trois discrètes, trois visibles) avec ce que les
  joueurs peuvent remarquer. Plan complet en notes MJ, scènes non chaînées
  (c'est l'adversaire qui avance), et au choix une horloge de 6 segments
  créée dans chaque partie de la campagne.
- Squelette guidé : notes MJ du chapitre, liens explicites typés (piste,
  indice) et horloge ; le Donjon en 5 salles est inchangé.

Vérifié : core clean verify (1268 tests, dont liens, index décalés par une
scène ignorée, horloge par partie), web build + vitest (textes fr/en de
chaque étape, structure des deux méthodes), lint sans erreur, parcours
complet des deux assistants dans le navigateur.
À redéployer : core + web (aucune migration).
2026-10-17 16:52:41 +02:00
ietm64 dae0508c93 Export PDF : mise en page module (renvois, annexes MJ, cartes pleine page)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 46s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 54s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 54s
- Renvois internes : les sorties d'une scène, les adversaires d'un combat et
  les nœuds d'une quête renvoient à leur cible avec son numéro de page
  (« La crypte (p. 12) », « Goule (p. 24) »). Un renvoi vers une partie non
  exportée devient du texte simple (pas de numéro faux ou vide).
- Annexes MJ (nouvelle partie, jamais en version joueurs) :
  - Révélations et indices : pour chaque révélation, les scènes qui y mènent,
    leur page et la nature du lien (indice, piste) ; signalée si rien n'y mène.
  - Index des PNJ et index des adversaires (dossier, niveau, scènes où chaque
    adversaire apparaît, page de la fiche).
- Cartes en pleine page : chaque battlemap et chaque plan de pièce sur sa
  propre page paysage, en plus haute résolution, prête à imprimer ; la scène
  y renvoie au lieu de l'afficher en petit.
- Fenêtre d'export : cases « Annexes MJ » et « Cartes en pleine page »
  (version joueurs : cartes cochées, annexes non).

Vérifié : core clean verify (1264 tests, dont renvois, renvois morts
neutralisés, annexes, version joueurs sans annexe, pages paysage dans le
PDF réel), web build + 367 vitest, lint sans erreur, rendu visuel du livret
de démonstration en A4 et A5.
À redéployer : core + web (aucune migration).
2026-10-17 16:40:20 +02:00
ietm64 cbd59a5bd9 Relecture d'éditeur : règles sur la forme du graphe (ne jamais bloquer les joueurs)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 42s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m8s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m4s
- WRITE-003 : une révélation doit être atteinte par au moins 3 scènes
  (règle des 3 indices, seuil relevé de 2 à 3).
- WRITE-011 Scène isolée : dans un chapitre qui utilise des liens, scène
  sans lien entrant ni sortant (hors ouverture ; une scène qui ne fait que
  partir vers d'autres reste valable, c'est une scène que le MJ déclenche).
- WRITE-012 Passage obligé : tous les chemins de l'ouverture vers les fins
  du chapitre traversent une même scène (une remarque par chapitre).
- WRITE-013 Donjon en couloir : 4 pièces ou plus reliées sans aucune boucle.
- WRITE-014 Enquête sans relance : révélations mais aucune scène
  d'événement à déclencher quand les joueurs piétinent.
- WRITE-015 Indices d'un seul genre : 3 chemins ou plus vers une révélation,
  tous depuis le même type de scène.
- Textes fr/en des cinq règles, lien « Voir » vers la bonne section de
  l'éditeur de scène (liens, choix, pièces).

Vérifié : core clean verify (1258 tests, cas positif et négatif par règle),
web build + 367 vitest, lint sans erreur, relecture d'une vraie campagne de
test (un seul passage obligé signalé, sur un chapitre en ligne droite).
À redéployer : core + web (aucune migration).
2026-10-17 16:30:22 +02:00
ietm64 d759bc8131 Export PDF : fiche Publication et options d'export (module à partager ou vendre)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 44s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 57s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m41s
- Correctifs du livret : le résumé des scènes est enfin exporté, libellés
  accentués (Thèmes, Récompenses, Résolution, Choix et conséquences), stats
  Foundry en français (PV, CA, FOR, FP…), encadrés et longues pages de lore
  coupables entre deux pages (fini les grands blancs), plus de date d'export
  en couverture, titre/auteur/sujet/langue dans les propriétés du PDF.
- Fiche Publication de la campagne (écran /campaigns/:id/publication) :
  sous-titre, auteur, version, illustration de couverture, page technique
  (système, niveaux, joueurs, durée), argument, avertissements de contenu,
  contexte caché et accroches pour le MJ, crédits et licence. Stockée en JSON
  (migration V26), API GET/PUT /api/campaigns/{id}/publication, conservée à
  l'export/import de campagne (couverture remappée).
- Dans le PDF : couverture illustrée, page de crédits, introduction (page
  technique, l'aventure en bref, contexte MJ, accroches, structure). Fiche
  vide : livret de campagne inchangé.
- Options d'export (modale au clic sur « Exporter en PDF ») : version MJ ou
  joueurs (aucun secret : notes MJ, conséquences, sorties, combats, contexte),
  format A4 / A5 / US Letter, mode impression sans aplats, choix des parties,
  lore complet ou seulement les pages liées à la campagne.
- Cinq nouvelles fiches du coach d'écriture sur l'écran Publication
  (argument, avertissements, contexte caché, accroches, crédits).

Vérifié : core clean verify (1247 tests, dont contenu du PDF par option,
version joueurs sans secret, propriétés du fichier, format Letter, remap de
la couverture à l'import), web build + 357 vitest, lint sans erreur, essai
dans le navigateur (migration V26 sur une base existante, enregistrement de
la fiche, export joueurs A5).
À redéployer : core + web (migration V26).
2026-10-17 16:22:24 +02:00
ietm64 ac7648f9fe Passage v1.3.0-beta
Build & Push Images / build (web) (push) Successful in 2m14s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 44s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m0s
Build & Push Images / build (brain) (push) Successful in 1m37s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m15s
Build & Push Images / build-switcher (push) Successful in 23s
Build & Push Images / build (core) (push) Successful in 4m22s
2026-10-17 15:47:14 +02:00
ietm64 d9a90f8412 Accès tablette : vérification du pare-feu sous Linux (ufw, firewalld)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 43s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 48s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 51s
- Choix de l'accès au pare-feu selon le système (HostNetworkAccessConfig) :
  Windows (PowerShell, UAC), Linux, sinon pas de diagnostic.
- Linux, sans droits root : ufw détecté via /etc/ufw/ufw.conf, firewalld via
  systemctl ; firewalld dit si le port est ouvert (firewall-cmd
  --query-port). Règles ufw illisibles sans root : port « inconnu », jamais
  de faux « prêt ».
- Vérification du réseau : état du pare-feu Linux et commande exacte à lancer
  sur la machine (sudo ufw allow <port>/tcp, ou firewall-cmd), avec bouton
  « Copier ». Pas d'autorisation en un clic (serveur sans écran).
- Le diagnostic reçoit le port réglé de l'accès distant.

Vérifié : core clean verify (1228 tests, dont lecture de ufw.conf,
interprétation de firewall-cmd et verdicts Linux), web build + 342 vitest,
lint sans erreur.
À redéployer : core + web (mode bureau ; aucune migration).
2026-10-17 15:41:50 +02:00
ietm64 2e9632de49 Mobile et tablette : arborescence en navigation par niveaux
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 41s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 47s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 49s
Avant : sur téléphone, toucher un arc ouvrait sa page et refermait le volet ;
pour voir chapitres et scènes il fallait viser une flèche de 12 px.

- En mode tiroir (< 1024 px), un niveau à la fois : toucher un nœud qui a
  des enfants entre dedans sans quitter le volet, bouton « retour » vers le
  niveau parent ; seule une feuille (scène, page…) navigue et ferme le volet.
- En-tête de niveau : titre, « Ouvrir la fiche » et actions de création du
  nœud (« Nouveau chapitre », « Nouvelle scène », « Nouvelle page »…).
- Lignes de 48 px minimum, titres sur deux lignes au plus, compteur
  d'éléments, pastilles de readiness conservées ; glisser-déposer réservé à
  l'ordinateur ; volet de 400 px sur tablette.
- Le volet rouvert montre le niveau de la page courante (élément surligné) ;
  l'accueil de la section n'est pas pris pour la page courante.
- Campagnes et Lore (panneau Templates gardé à la racine). Ordinateur
  inchangé : arbre classique.

Vérifié : web build + 342 vitest (logique de navigation testée), lint sans
erreur, e2e 80/80 dont le parcours mobile hub → scène réécrit pour les
niveaux, essais au doigt à 375 et 768 px (campagne et Lore).
À redéployer : web.
2026-10-17 15:34:41 +02:00
ietm64 fbb1956e17 Accès tablette : détection des pare-feu tiers (Bitdefender, Norton…)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 46s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 59s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m4s
Constat terrain : avec Bitdefender, la règle Windows était en place et la
vérification affichait « prêt » alors que le pare-feu de l'antivirus
filtrait encore les connexions de la tablette.

- Lecture du Centre de sécurité Windows (SecurityCenter2/FirewallProduct) :
  les pare-feu tiers déclarés sont remontés avec le diagnostic.
- Vérification du réseau : plus de « tout est prêt » trompeur quand un pare-feu
  tiers est présent — avertissement nommant le logiciel, consigne (réseau
  domestique, mode furtif désactivé, règle entrante pour DM Loremind) et lien
  vers la doc.

Vérifié : core clean verify (1221 tests, dont la lecture réelle sur Windows
qui remonte bien « Bitdefender Pare-feu »), web build + 337 vitest, lint sans
erreur.
À redéployer : core + web (mode bureau ; aucune migration).
2026-10-17 15:08:12 +02:00
ietm64 8c6b642975 Accès tablette : vérification du réseau et autorisation pare-feu en un clic
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 42s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 51s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m33s
Build & Push Images / build (brain) (push) Successful in 1m39s
Build & Push Images / build (web) (push) Successful in 2m3s
Build & Push Images / build-switcher (push) Successful in 25s
Build & Push Images / build (core) (push) Successful in 4m13s
Constat terrain : le téléphone chargeait sans fin — le pare-feu Windows
n'avait aucune règle pour DM Loremind (la fenêtre d'autorisation n'apparaît
pas toujours) et le Wi-Fi était classé « Public » par défaut.

- Bloc « Vérification du réseau » dans Paramètres > Accès depuis une
  tablette : lit le type des réseaux connectés et les règles entrantes du
  pare-feu visant l'appli (PowerShell, lecture seule, sans droits admin).
- Bouton « Autoriser dans le pare-feu » : confirmation administrateur
  Windows (UAC), règle limitée aux réseaux privés, blocages éventuels de
  l'appli retirés ; résultat affiché (appliqué / annulé / échec).
- Réseau classé « Public » : explication + bouton « Ouvrir les réglages
  réseau » (le profil réseau reste un choix de l'utilisateur).
- Textes et doc corrigés (fin de la consigne trompeuse « réseaux privés
  uniquement ») ; section « La tablette charge sans fin » avec la commande
  manuelle de secours.

Vérifié : core clean verify (1219 tests, dont une vraie lecture du système
sur Windows), web build + 337 vitest, lint sans erreur, bloc vérifié en mode
bureau isolé.
À redéployer : core + web (mode bureau ; aucune migration).
2026-10-17 14:41:54 +02:00
ietm64 d926545e3d Mobile : raccourci « Séance en cours » dans la barre haute + hub sans débordement à 375 px
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 1m43s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 2m3s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m3s
Build & Push Images / build (brain) (push) Successful in 2m40s
Build & Push Images / build (core) (push) Successful in 4m24s
Build & Push Images / build (web) (push) Successful in 2m35s
Build & Push Images / build-switcher (push) Successful in 24s
- Barre haute mobile : pastille « Séance en cours » (mode compact du
  raccourci, 44 px) — un tap ramène à la séance, liste déroulante s'il y en a
  plusieurs (fermée par Échap ou un tap à côté).
- Hub campagne : l'en-tête de section « Arcs narratifs » passe à la ligne au
  lieu de déborder (3 boutons depuis l'ajout de « Méthode guidée »).

Vérifié : core clean verify (1206 tests), web build + 337 vitest, lint sans
erreur, e2e Playwright 80/80 (desktop + mobile 375 px) sur la branche
fusionnée.
À redéployer : web.
2026-10-17 14:07:20 +02:00
ietm64 b323c681f8 Fusion : séances accessibles et règles sous la main en séance
# Conflicts:
#	web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.ts
#	web/src/assets/i18n/en.json
#	web/src/assets/i18n/fr.json
2026-10-17 14:01:36 +02:00
ietm64 e7063b31e3 Fusion : front utilisable sur téléphone et tablette
# Conflicts:
#	web/src/assets/i18n/en.json
#	web/src/assets/i18n/fr.json
2026-10-17 14:01:11 +02:00
ietm64 ab658f27b0 Appli de bureau : accès depuis une tablette sur le réseau local (appairage par code, migration V25)
- Activation dans Paramètres > « Accès depuis une tablette » (raccourci tray
  « Connecter une tablette… ») : un second connecteur Tomcat s'ouvre à chaud
  sur le réseau local (port 8765 par défaut, modifiable) ; le connecteur
  habituel reste sur 127.0.0.1, rien ne change pour qui n'active rien.
- Appairage : QR code + code à 6 chiffres (5 min, usage unique, 5 essais,
  20 échecs/min au total) échangé contre un jeton d'appareil posé en cookie
  HttpOnly + SameSite=Strict ; seule son empreinte SHA-256 est stockée
  (tables remote_access_config et remote_devices, migration V25).
- RemoteAccessFilter (avant le HTTP Basic) : depuis le réseau, API réservée
  aux appareils appairés (sinon 401 → écran /pair côté front) ; Paramètres,
  données, mises à jour et licence toujours refusés (403), même appairé.
- Front : section Paramètres (adresse, QR code, compte à rebours, appareils
  autorisés avec « Retirer l'accès »), écran d'appairage plein écran,
  intercepteur de redirection ; dépendance qrcode.
- Mode bureau uniquement (profil local) : Docker inchangé.

Vérifié : core clean verify (1205 tests, dont un test d'intégration sur un
vrai Tomcat : ouverture/fermeture du port, filtre, appairage + cookie),
migration V25 sur H2, web build + 303 vitest, lint sans erreur, parcours PC
et tablette testés en mode bureau isolé ; doc à jour (accès tablette +
Tailscale).
À redéployer : core (migration V25) + web.
2026-10-17 14:00:43 +02:00
ietm64 c2947cfef8 Séances accessibles en un clic + règles du système sous la main en séance
- Raccourci « Séance en cours » dans le menu principal : visible dès qu'une
  séance tourne (liste dépliable s'il y en a plusieurs, la plus récente en
  tête), rafraîchi à la navigation et au démarrage/fin d'une séance.
- Hub campagne : bloc « Jouer » sous l'en-tête — reprendre la séance en
  cours, sinon démarrer une séance sur la partie la plus récente (menu pour
  en choisir une autre), ou créer une partie s'il n'y en a aucune.
- Arbre de campagne : section « Jeu > Parties » avant la narration.
- Onglet « Règles » en séance : sommaire des sections, sections repliables,
  recherche instantanée hors ligne (insensible aux accents, à la casse et aux
  ligatures, ne garde et ne surligne que les lignes concernées), sections
  épinglables (mémorisées par système), « Demander à l'IA » qui bascule sur
  l'onglet IA avec la question préremplie ; liens utiles si la campagne n'a
  pas de système ou si le système n'a pas de règles.
- Core : GET /api/sessions?active=true (séances en cours sans tout
  l'historique) ; l'arbre /campaigns/{id}/tree inclut les parties.

Vérifié : core test-compile + tests, web build + vitest (recherche dans les
règles, bloc « Jouer »), lint sans nouvelle erreur, testé desktop et 375 px.
À redéployer : core (aucune migration) + web.
2026-10-17 14:00:32 +02:00
ietm64 67ac4cc68f Front utilisable sur téléphone et tablette + suite e2e réparée
- Sous 1024 px : barre haute (menu, arborescence titrée par la campagne ou
  le lore, recherche), menu principal et arborescence en tiroirs (fermeture
  au changement de page, au tap extérieur et avec Échap ; focus gardé dans le
  tiroir puis rendu au bouton). Desktop inchangé, le repli de l'arborescence
  à 44 px fonctionne toujours.
- Règles globales (styles/_responsive.scss) : formulaires sur une colonne
  sous 600 px, boutons d'en-tête qui passent à la ligne, marges de page
  réduites sur téléphone, cibles tactiles agrandies, actions révélées au
  survol visibles en permanence sur écran tactile.
- Écrans corrigés : hub campagne, Lore, dossiers et séance (titres lisibles,
  horloges en 2 colonnes), assistant IA plein écran sur téléphone, listes de
  campagnes et de lores sur une colonne.
- e2e : projet Playwright « mobile » (375 px, tactile) avec 3 tests de
  navigation ; 3 tests desktop périmés corrigés (suite complète 80/80).

Vérifié : aucun scroll horizontal sur 18 écrans à 375/768/1024 px, build web,
vitest, lint sans nouvelle erreur.
À redéployer : web.
2026-10-17 14:00:19 +02:00
ietm64 c2f162d823 Mentor d'écriture (M1-M3) : coach dans les champs, relecture d'éditeur, méthode guidée « Donjon en 5 salles »
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 13m48s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 13m16s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m3s
Build & Push Images / build (core) (push) Successful in 4m50s
Build & Push Images / build (web) (push) Successful in 3m26s
Build & Push Images / build-switcher (push) Successful in 26s
Build & Push Images / build (brain) (push) Canceled after 1m5s
- M1 coach : bouton ampoule sur 17 champs narratifs (scène, chapitre, arc),
  panneau de conseils (à quoi ça sert, questions, exemple, piège classique).
  Contenu statique i18n fr/en, sans IA ; ampoule aussi dans l'en-tête des
  sections repliables (input coachTopic d'expandable-section).
- M2 relecture d'éditeur : WritingReviewService + GET
  /api/campaigns/{id}/writing-review, 10 règles déterministes WRITE-001 à 010
  (couloir, faux choix, révélation à chemin unique, rythme monotone, enjeux
  absents, narration trop longue ou qui décide à la place des PJ, combat sans
  but, fin unique, scènes non typées). Le back renvoie ruleId + params, les
  textes fr/en sont dans l'i18n. Panneau sur le hub, encart dans les éditeurs,
  liens « Voir » avec ?focus= (nouveaux focus : narration, choices, stakes).
- M3 méthode guidée : POST /api/campaigns/{id}/guided-skeleton (arc existant
  ou nouveau, chapitre, scènes typées, chaînage optionnel, transactionnel)
  + assistant pas à pas générique /campaigns/:id/guided/:method, première
  méthode « Donjon en 5 salles ». Entrées sur le hub de campagne.
- Garde-fous vitest : complétude des textes fr/en du coach, de la relecture
  (règles lues dans le Java) et des méthodes guidées.

Vérifié : core clean verify (1182 tests), web build + 299 tests vitest, lint
sans erreur, parcours testés dans l'appli (back Postgres de dev).
À redéployer : core (2 endpoints, aucune migration) + web.
2026-10-17 11:58:26 +02:00
ietm64 ad3ea0e9e6 CI : build web cassé par la sortie de npm 12 (npm@latest exige Node >= 22)
Tests unitaires / Brain (Python · pytest + couverture) (push) Successful in 24s
Tests unitaires / Web (Angular · vitest + couverture) (push) Successful in 29s
Tests unitaires / Core (Java · mvn test + JaCoCo) (push) Successful in 3m14s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m1s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 45s
E2E Tests / e2e (push) Failing after 4m6s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Successful in 1m12s
Build & Push Images / build (brain) (push) Successful in 2m14s
Build & Push Images / build (web) (push) Successful in 1m54s
Build & Push Images / build (core) (push) Successful in 3m41s
Build & Push Images / build-switcher (push) Successful in 48s
Suppression du « npm install -g npm@latest » du Dockerfile web : cible
mouvante inutile — le npm embarqué dans node:20 suffit pour npm ci
(lockfileVersion 3) et le build Angular.
2026-07-10 09:31:58 +02:00
ietm64 0c44e42a22 Quêtes libres : fin des conteneurs fantômes (cascade, impact annoncé, export filtré, migration V24)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 52s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Successful in 2m36s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m11s
Build & Push Images / build (web) (push) Failing after 35s
Build & Push Images / build (brain) (push) Successful in 1m18s
Build & Push Images / build-switcher (push) Successful in 42s
Build & Push Images / build (core) (push) Successful in 3m8s
Sidebar Lore : le panneau Templates ne peut plus écraser l'arbre

Plafonné à 45 % de la sidebar avec ascenseur interne sur la liste —
l'en-tête, le repli et le bouton + restent toujours visibles, l'arbre
garde son propre scroll (remonté par un utilisateur avec ~30 templates)

Passage v1.0.3
2026-07-10 09:19:26 +02:00
ietm64 1c8b24c5dd CI : Trivy en résolution 100 % hors-ligne (--offline-scan)
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Successful in 32s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 42s
Build & Push Images / build (brain) (push) Successful in 1m26s
Build & Push Images / build (web) (push) Successful in 1m59s
Build & Push Images / build (core) (push) Successful in 3m16s
Build & Push Images / build-switcher (push) Successful in 16s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 55s
Le préchargement du cache Maven ne suffisait pas : Trivy va chercher les
POMs parents (ex. netty-parent) sur Maven Central même quand ~/.m2 est
rempli, et l'IP du runner finit rate-limitée (429, blocage 30 min).
--offline-scan supprime toute requête réseau pendant la résolution — sans
perte : dependency:go-offline garantit juste avant que tout est en cache.
2026-07-07 12:09:04 +02:00
ietm64 177967af55 Sécurité : purge des 22 CVE remontées par Trivy (premier run du gate)
Build & Push Images / build (web) (push) Successful in 1m58s
Build & Push Images / build (core) (push) Successful in 3m13s
Build & Push Images / build-switcher (push) Successful in 22s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 43s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m0s
Build & Push Images / build (brain) (push) Successful in 1m12s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 2m35s
- core : overrides BOM Spring Boot — tomcat-embed 10.1.55 (3 CRITICAL dont
  bypass d'auth digest), jackson-databind 2.21.4 (exécution de code arbitraire),
  netty 4.1.135.Final (lot DoS/bypass hostname/DNS), postgresql 42.7.11
- web : Angular 21.2.16 → 21.2.17 (HttpTransferCache, DoS formatDate,
  DOM clobbering hydration) — package-lock régénéré (peer-deps exactes
  entre paquets @angular : montée impossible paquet par paquet)

Vérifié : test-compile core, build + tests web, re-scan Trivy local propr
2026-07-07 01:22:54 +02:00
ietm64 42c4b53ced Stack qualité CI (MegaLinter, Trivy, ESLint) et purge du backlog lint web
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m9s
Build & Push Images / build (brain) (push) Successful in 1m10s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 2m36s
Build & Push Images / build (web) (push) Successful in 1m48s
Build & Push Images / build-switcher (push) Successful in 20s
Build & Push Images / build (core) (push) Successful in 3m9s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 38s
CI (Gitea Actions) :
- Nouveau workflow quality.yml (séparé de ci.yml, non bloquant pour la release) :
  MegaLinter v9 (PMD, Ruff, Bandit, gitleaks, hadolint), ng lint (web) et
  Trivy (CVE des dépendances Maven/pip/npm), sur main + beta + PR
- Trivy : préchargement du cache Maven avant le scan — sans ça Maven Central
  rate-limite l'IP du runner (429) en résolvant les BOMs du parent Spring Boot
- upload-artifact v4 → v3 : l'API artifacts v4 n'est pas supportée par Gitea
  (corrige aussi l'upload du rapport Playwright de e2e.yml, cassé depuis toujours)
- Ruleset PMD projet (java-pmd-ruleset.xml, auto-détecté par MegaLinter) orienté
  bugs réels, sans le style Lombok-hostile du défaut : 11 337 → 65 findings ;
  PMD en mode rapport (JAVA_PMD_DISABLE_ERRORS) le temps de purger ce backlog

Web :
- angular-eslint 21 + eslint-plugin-sonarjs : les règles Sonar vivent désormais
  dans ESLint (config web/eslint.config.js, réglages justifiés en commentaire)
- tsconfig : skipLibCheck + types:[] + node_modules ré-exclu — répare les builds
  desktop Windows/Linux cassés par le conflit @types/eslint-scope vs ESLint 9
- Purge du backlog lint : 114 erreurs → 0 sur 66 fichiers (ngOnDestroy vides
  supprimés, any typés avec les vrais DTOs, outputs (close) → (closed), regex
  super-linéaires désamorcées, ternaires/fonctions imbriqués dépliés, intention
  documentée sur les catch/error volontairement vides)
- Bug latent corrigé au passage : license.service.disconnect() émettait
  undefined au lieu de true en cas de succès (masqué par un double cast)
2026-07-07 01:05:00 +02:00
ietm64 3e9e828225 Mise en place de la qualité sur la branche beta également
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m5s
Build & Push Images / build (brain) (push) Successful in 2m5s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 14m12s
Build & Push Images / build (web) (push) Failing after 2m7s
Build & Push Images / build-switcher (push) Successful in 18s
Build & Push Images / build (core) (push) Successful in 3m27s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Failing after 8m26s
2026-07-07 00:16:23 +02:00
ietm64 51eb907078 Mise en place de la version 1.0.2-bêta
Build & Push Images / build (core) (push) Waiting to run
Build & Push Images / build (brain) (push) Successful in 1m28s
Build & Push Images / build-switcher (push) Has been cancelled
Build & Push Images / build (web) (push) Has been cancelled
2026-07-07 00:12:40 +02:00
ietm64 9f0359d8c0 Dernière fournée de corrections Sonar
Mise en place de MegaLinter ; web-lint pour la partie code quality sur la CI, Trivy pour la partie CVE
2026-07-07 00:11:52 +02:00
ietm64 587e0fe097 passage 1.0.1-beta
Build & Push Images / build (brain) (push) Successful in 1m29s
Build & Push Images / build (web) (push) Successful in 1m58s
Build & Push Images / build (core) (push) Successful in 3m39s
Build & Push Images / build-switcher (push) Successful in 20s
2026-07-06 15:25:48 +02:00
ietm64 5c3c58265f Première fournée correction dette technique.
Refactoring du code pour améliorer la lisibilité de ce dernier coté core
Correction sur l'export / import : les images n'étaient pas bien liées à la campagne lors de l'export / import et provoquait un bug d'affichage des images
lorsqu'on voulait ouvrir une campagne importée.
2026-07-06 14:39:55 +02:00
684 changed files with 31271 additions and 4940 deletions
+3 -1
View File
@@ -82,9 +82,11 @@ jobs:
if: failure()
run: docker compose -f docker-compose.yml -f docker-compose.e2e.yml logs --no-color
# v3 obligatoire : l'API artifacts v4 n'est pas supportée par Gitea
# (GHESNotSupportedError — constaté sur le job MegaLinter).
- name: Upload Playwright report
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v3
with:
name: playwright-report
path: web/playwright-report/
+104
View File
@@ -0,0 +1,104 @@
name: Qualité & Sécurité
# Analyse statique (MegaLinter, config racine .mega-linter.yml) + CVE des
# dépendances (Trivy). Workflow SÉPARÉ de ci.yml : un rouge qualité ne bloque
# pas la chaîne tests → release pendant la phase de rodage. Une fois la base
# assainie, on pourra l'ajouter aux checks requis de la branch protection.
on:
push:
# beta inclus : c'est la branche de dev, le feedback qualité doit y vivre
# (ci.yml/e2e.yml, eux, restent volontairement sur main + PR).
branches: [main, beta]
pull_request:
branches: [main]
jobs:
megalinter:
name: MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
# Historique complet : requis par gitleaks (scan de l'historique)
# et par le mode "fichiers modifiés seulement" en PR.
fetch-depth: 0
# Flavor "cupcake" : image allégée couvrant les langages courants
# (Java/Python/TS inclus). Si un linter activé manquait à la flavor,
# MegaLinter échoue en l'indiquant → remplacer par oxsecurity/megalinter@v9
# (image complète, plus lourde).
- name: MegaLinter
uses: oxsecurity/megalinter/flavors/cupcake@v9
env:
# main → scan complet du dépôt ; beta et PR → seulement les fichiers
# modifiés par rapport à main (rapide, feedback ciblé).
VALIDATE_ALL_CODEBASE: ${{ github.ref == 'refs/heads/main' }}
# v3 obligatoire : l'API artifacts v4 (@actions/artifact 2.x) n'est pas
# supportée par Gitea (GHESNotSupportedError constaté avec v4).
- name: Publier les rapports
if: always()
uses: actions/upload-artifact@v3
with:
name: megalinter-reports
path: megalinter-reports/
web-lint:
name: Web (ESLint · angular-eslint + sonarjs)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: npm
cache-dependency-path: web/package-lock.json
- name: npm ci
working-directory: web
run: npm ci --no-audit --no-fund
# Lint via la toolchain du projet (et non via MegaLinter : ESLint a
# besoin des plugins de web/node_modules et du contexte Angular).
# Config + règles : web/eslint.config.js (sonarjs = règles "à la Sonar").
- name: ng lint
working-directory: web
run: npm run lint
trivy:
name: Trivy (CVE dépendances Maven / pip / npm)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# Pour résoudre pom.xml (versions héritées du parent Spring Boot), Trivy
# télécharge les BOMs depuis Maven Central — qui finit par rate-limiter
# l'IP du runner (429). Parade officielle : peupler ~/.m2 AVANT le scan,
# Trivy lit le cache local en priorité. Le cache setup-java (clé pom.xml)
# rend l'étape quasi gratuite d'un run à l'autre.
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
cache: maven
- name: Précharger le cache Maven (~/.m2)
working-directory: core
run: |
chmod +x ./mvnw
./mvnw -B -q dependency:go-offline
- name: Installer Trivy
run: curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# Scanne les manifestes du dépôt (pom.xml, requirements*.txt,
# package-lock.json) contre les bases CVE. --ignore-unfixed : on ne
# bloque que sur les vulnérabilités qui ONT un correctif publié.
# --offline-scan : AUCUNE requête vers Maven Central pendant la
# résolution — Trivy allait y chercher les POMs parents même avec le
# cache rempli, et l'IP du runner finissait rate-limitée (429, 30 min).
# Tout est déjà dans ~/.m2 grâce au dependency:go-offline ci-dessus ;
# contrepartie : une dépendance absente du cache serait ignorée en
# silence (impossible ici, go-offline échouerait d'abord).
- name: Scan des dépendances (HIGH/CRITICAL bloquants)
run: |
trivy fs . \
--scanners vuln \
--severity HIGH,CRITICAL \
--ignore-unfixed \
--offline-scan \
--skip-dirs node_modules \
--skip-dirs docusaurus \
--exit-code 1
+2
View File
@@ -129,3 +129,5 @@ web/coverage/
brain/htmlcov/
brain/.coverage
foundry-module/
plan-promotion-loremind.md
post-reddit-foundryvtt.md
+43
View File
@@ -0,0 +1,43 @@
# Configuration MegaLinter — https://megalinter.io/latest/config-file/
#
# Périmètre volontairement resserré (liste ENABLE_LINTERS exclusive) : on
# active les linters au fil de l'eau plutôt que de subir les ~100 par défaut.
# Le scan CVE des dépendances n'est PAS ici : il est porté par le job Trivy
# (cf. .gitea/workflows/quality.yml).
APPLY_FIXES: none
DEFAULT_BRANCH: main
SHOW_ELAPSED_TIME: true
PRINT_ALPACA: false
# Liste EXCLUSIVE : tout linter absent d'ici est désactivé.
ENABLE_LINTERS:
# --- core (Java) : bugs + code smells "à la Sonar" sur les sources.
# (Sonar for IDE reste pertinent en local pour l'analyse de flux fine.)
- JAVA_PMD
# --- brain (Python) ---
- PYTHON_RUFF # remplace flake8/pylint/isort, très rapide
- PYTHON_BANDIT # sécurité du code Python
# - PYTHON_MYPY # à activer quand le brain aura des annotations de types
# --- repo entier ---
- REPOSITORY_GITLEAKS # secrets committés (tokens, mots de passe…)
- DOCKERFILE_HADOLINT # bonnes pratiques Dockerfile
# --- web (TypeScript) : PAS via MegaLinter. Le lint tourne avec la
# toolchain du projet (job "web-lint" de quality.yml → ng lint,
# config web/eslint.config.js avec angular-eslint + sonarjs).
# Jamais d'analyse des artefacts de build, dépendances et sites docs.
FILTER_REGEX_EXCLUDE: '(^|/)(node_modules|target|dist|coverage|\.angular|\.mvn|docusaurus)/'
# Rapports déposés là où le workflow les publie en artefact CI.
REPORT_OUTPUT_FOLDER: megalinter-reports
# Phase de rodage : passer temporairement à true pour rendre le job
# informatif (rapport sans échec CI) le temps de purger l'existant.
DISABLE_ERRORS: false
# PMD : ruleset projet à la racine (java-pmd-ruleset.xml, détecté
# automatiquement) — orienté bugs réels, sans style. Non-bloquant le temps
# de purger le backlog (~65 findings : PreserveStackTrace, EmptyCatchBlock,
# CheckResultSet, RelianceOnDefaultCharset…). Repasser à false ensuite.
JAVA_PMD_DISABLE_ERRORS: true
+1 -1
View File
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
app = FastAPI(
title="LoreMind Brain",
description="Backend IA pour la génération de contenu narratif.",
version="1.0.0",
version="1.5.0-beta",
)
logger = logging.getLogger(__name__)
+14 -1
View File
@@ -14,7 +14,7 @@
<groupId>com.loremind</groupId>
<artifactId>loremind-core</artifactId>
<version>1.0.0</version>
<version>1.5.0-beta</version>
<name>LoreMind Core</name>
<description>Backend Core - Architecture Hexagonale</description>
@@ -24,6 +24,19 @@
>= 3.18 : corrige CVE-2025-48924 (recursion infinie ClassUtils.getClass).
Propriete reconnue par le BOM Spring Boot → s'applique partout. -->
<commons-lang3.version>3.20.0</commons-lang3.version>
<!-- Overrides CVE (detectes par Trivy en CI — job quality.yml) :
proprietes reconnues par le BOM Spring Boot, comme ci-dessus. -->
<!-- >= 2.21.4 : CVE-2026-54512 / CVE-2026-54513 (execution de code
arbitraire via contournement du PolymorphicTypeValidator). -->
<jackson-bom.version>2.21.4</jackson-bom.version>
<!-- >= 4.1.135 : lot de CVE netty (DoS codec/handler, bypass de
verification hostname CVE-2026-50010, DNS CVE-2026-45674/47691). -->
<netty.version>4.1.135.Final</netty.version>
<!-- >= 10.1.55 : 3 CRITICAL Tomcat (CVE-2026-41293 headers HTTP/2 non
valides, CVE-2026-43512 bypass auth digest, CVE-2026-43515). -->
<tomcat.version>10.1.55</tomcat.version>
<!-- >= 42.7.11 : CVE-2026-42198 (DoS client via SCRAM-SHA-256). -->
<postgresql.version>42.7.11</postgresql.version>
</properties>
<dependencies>
@@ -1,9 +1,9 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.FieldProposal;
import com.loremind.domain.campaigncontext.Quest;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.generation.FieldProposal;
import com.loremind.domain.campaigncontext.quest.Quest;
import com.loremind.domain.shared.ReorderSupport;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
@@ -169,8 +169,8 @@ public class ArcService {
@Transactional
public void reorderArcs(List<String> orderedIds) {
ReorderSupport.reorder(orderedIds,
id -> arcRepository.findById(id).orElse(null),
(arc, i) -> arc.setOrder(i),
arcRepository::findById,
Arc::setOrder,
arcRepository::save);
}
}
@@ -41,6 +41,16 @@ public class CampaignBriefBuilder {
sb.append("# Campagne : ").append(cc.campaignName()).append("\n");
if (notBlank(cc.campaignDescription())) sb.append(cc.campaignDescription()).append("\n");
appendStructure(sb, cc);
appendNpcs(sb, cc);
if (campaign.isLinkedToLore()) {
loreContextBuilder.buildOptional(campaign.getLoreId()).ifPresent(lore -> appendLore(sb, lore));
}
return sb.toString();
}
private void appendStructure(StringBuilder sb, CampaignStructuralContext cc) {
sb.append("\n## Structure (arcs → chapitres → scènes)\n");
sb.append("_Un arc HUB contient des chapitres parallèles appelés « quêtes » ; ")
.append("un arc LINEAR contient des chapitres en séquence._\n");
@@ -48,34 +58,38 @@ public class CampaignBriefBuilder {
sb.append("_(aucun arc pour le moment)_\n");
}
for (ArcSummary arc : cc.arcs()) {
sb.append(arc.hub() ? "### Arc HUB (à quêtes) : " : "### Arc : ").append(arc.name());
if (notBlank(arc.description())) sb.append(" — ").append(arc.description());
appendArc(sb, arc);
}
}
private void appendArc(StringBuilder sb, ArcSummary arc) {
sb.append(arc.hub() ? "### Arc HUB (à quêtes) : " : "### Arc : ").append(arc.name());
if (notBlank(arc.description())) sb.append(" — ").append(arc.description());
sb.append("\n");
for (ChapterSummary ch : arc.chapters()) {
appendChapter(sb, arc.hub(), ch);
}
}
private void appendChapter(StringBuilder sb, boolean hub, ChapterSummary ch) {
sb.append(hub ? "- Quête : " : "- Chapitre : ").append(ch.name());
if (notBlank(ch.description())) sb.append(" — ").append(ch.description());
sb.append("\n");
for (SceneSummary sc : ch.scenes()) {
sb.append(" - Scène : ").append(sc.name());
if (notBlank(sc.description())) sb.append(" — ").append(sc.description());
sb.append("\n");
for (ChapterSummary ch : arc.chapters()) {
sb.append(arc.hub() ? "- Quête : " : "- Chapitre : ").append(ch.name());
if (notBlank(ch.description())) sb.append(" — ").append(ch.description());
sb.append("\n");
for (SceneSummary sc : ch.scenes()) {
sb.append(" - Scène : ").append(sc.name());
if (notBlank(sc.description())) sb.append(" — ").append(sc.description());
sb.append("\n");
}
}
}
}
if (!cc.npcs().isEmpty()) {
sb.append("\n## PNJ existants\n");
for (NpcSummary n : cc.npcs()) {
sb.append("- ").append(n.name());
if (notBlank(n.snippet())) sb.append(" : ").append(n.snippet());
sb.append("\n");
}
private void appendNpcs(StringBuilder sb, CampaignStructuralContext cc) {
if (cc.npcs().isEmpty()) return;
sb.append("\n## PNJ existants\n");
for (NpcSummary n : cc.npcs()) {
sb.append("- ").append(n.name());
if (notBlank(n.snippet())) sb.append(" : ").append(n.snippet());
sb.append("\n");
}
if (campaign.isLinkedToLore()) {
loreContextBuilder.buildOptional(campaign.getLoreId()).ifPresent(lore -> appendLore(sb, lore));
}
return sb.toString();
}
private void appendLore(StringBuilder sb, LoreStructuralContext lore) {
@@ -0,0 +1,20 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CampaignContentSearchService {
private final CampaignContentSearchRepository repository;
public CampaignContentSearchService(CampaignContentSearchRepository repository) {
this.repository = repository;
}
public List<CampaignContentHit> search(String query) {
String value = query == null ? "" : query.strip();
return value.length() < 2 ? List.of() : repository.searchByName(value);
}
}
@@ -0,0 +1,40 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
import org.springframework.stereotype.Component;
/**
* Formateur de contexte campagne pour les prompts IA.
* Centralise la construction du bloc "nom + description + système de jeu".
*/
@Component
public class CampaignContextFormatter {
private final CampaignRepository campaignRepository;
private final GameSystemRepository gameSystemRepository;
public CampaignContextFormatter(CampaignRepository campaignRepository,
GameSystemRepository gameSystemRepository) {
this.campaignRepository = campaignRepository;
this.gameSystemRepository = gameSystemRepository;
}
/** Contexte compact : nom de campagne + description + système de jeu. */
public String format(String campaignId) {
if (campaignId == null) return "";
Campaign campaign = campaignRepository.findById(campaignId).orElse(null);
if (campaign == null) return "";
StringBuilder sb = new StringBuilder();
sb.append("Campagne : ").append(campaign.getName());
if (campaign.getDescription() != null && !campaign.getDescription().isBlank()) {
sb.append(" — ").append(campaign.getDescription().trim());
}
if (campaign.getGameSystemId() != null && !campaign.getGameSystemId().isBlank()) {
gameSystemRepository.findById(campaign.getGameSystemId())
.ifPresent(gs -> sb.append("\nSystème de jeu : ").append(gs.getName()));
}
return sb.toString();
}
}
@@ -1,17 +1,17 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.ArcType;
import com.loremind.domain.campaigncontext.CampaignImportProgress;
import com.loremind.domain.campaigncontext.CampaignImportProposal;
import com.loremind.domain.campaigncontext.CampaignImportProposal.ArcProposal;
import com.loremind.domain.campaigncontext.CampaignImportProposal.ChapterProposal;
import com.loremind.domain.campaigncontext.CampaignImportProposal.NpcProposal;
import com.loremind.domain.campaigncontext.CampaignImportProposal.RoomProposal;
import com.loremind.domain.campaigncontext.CampaignImportProposal.SceneProposal;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.Room;
import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.ArcType;
import com.loremind.domain.campaigncontext.generation.CampaignImportProgress;
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal;
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.ArcProposal;
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.ChapterProposal;
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.NpcProposal;
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.RoomProposal;
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.SceneProposal;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.structure.Room;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.ports.CampaignPdfImporter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -83,66 +83,95 @@ public class CampaignImportService {
throw new IllegalArgumentException("Campagne introuvable : " + campaignId);
}
int arcsCreated = 0, chaptersCreated = 0, scenesCreated = 0;
int arcsCreated = 0;
int chaptersCreated = 0;
int scenesCreated = 0;
// Les nouveaux nœuds sont ordonnés APRÈS les frères existants (déjà comptés
// via leur existingId dans l'arbre fusionné venu de la revue).
int arcOrder = countExisting(proposal.arcs(), ArcProposal::existingId);
for (ArcProposal arcP : proposal.arcs()) {
if (isBlank(arcP.name())) continue;
String arcId;
if (!isBlank(arcP.existingId())) {
arcId = arcP.existingId(); // arc déjà présent → on s'y rattache
} else {
arcOrder++;
Arc arc = arcService.createArc(Arc.builder()
.name(arcP.name().trim())
.description(nullIfBlank(arcP.description()))
.campaignId(campaignId)
.order(arcOrder)
.type(parseArcType(arcP.type()))
.build());
arcId = arc.getId();
arcsCreated++;
}
int chapterOrder = countExisting(arcP.chapters(), ChapterProposal::existingId);
for (ChapterProposal chapP : safe(arcP.chapters())) {
if (isBlank(chapP.name())) continue;
String chapId;
if (!isBlank(chapP.existingId())) {
chapId = chapP.existingId();
} else {
chapterOrder++;
Chapter chapter = chapterService.createChapter(
chapP.name().trim(), nullIfBlank(chapP.description()), arcId, chapterOrder);
chapId = chapter.getId();
chaptersCreated++;
}
int sceneOrder = countExisting(chapP.scenes(), SceneProposal::existingId);
for (SceneProposal sceneP : safe(chapP.scenes())) {
if (isBlank(sceneP.name())) continue;
if (!isBlank(sceneP.existingId())) continue; // scène déjà présente
sceneOrder++;
sceneService.createScene(Scene.builder()
.name(sceneP.name().trim())
.description(nullIfBlank(sceneP.description()))
.playerNarration(nullIfBlank(sceneP.playerNarration()))
.gmSecretNotes(nullIfBlank(sceneP.gmNotes()))
.chapterId(chapId)
.order(sceneOrder)
.rooms(toRooms(sceneP.rooms()))
.build());
scenesCreated++;
}
}
ArcOutcome outcome = applyArc(campaignId, arcP, arcOrder);
arcOrder = outcome.nextOrder();
arcsCreated += outcome.arcsCreated();
chaptersCreated += outcome.chaptersCreated();
scenesCreated += outcome.scenesCreated();
}
int npcsCreated = createNpcs(campaignId, proposal.npcs());
return new ApplyResult(arcsCreated, chaptersCreated, scenesCreated, npcsCreated);
}
/** Ordre d'arc suivant + compteurs créés (arc et, en cascade, ses chapitres/scènes). */
private record ArcOutcome(int nextOrder, int arcsCreated, int chaptersCreated, int scenesCreated) {}
private ArcOutcome applyArc(String campaignId, ArcProposal arcP, int arcOrder) {
String arcId;
int arcsCreated = 0;
if (!isBlank(arcP.existingId())) {
arcId = arcP.existingId(); // arc déjà présent → on s'y rattache
} else {
arcOrder++;
Arc arc = arcService.createArc(Arc.builder()
.name(arcP.name().trim())
.description(nullIfBlank(arcP.description()))
.campaignId(campaignId)
.order(arcOrder)
.type(parseArcType(arcP.type()))
.build());
arcId = arc.getId();
arcsCreated = 1;
}
int chapterOrder = countExisting(arcP.chapters(), ChapterProposal::existingId);
int chaptersCreated = 0;
int scenesCreated = 0;
for (ChapterProposal chapP : safe(arcP.chapters())) {
if (isBlank(chapP.name())) continue;
ChapterOutcome outcome = applyChapter(arcId, chapP, chapterOrder);
chapterOrder = outcome.nextOrder();
chaptersCreated += outcome.chaptersCreated();
scenesCreated += outcome.scenesCreated();
}
return new ArcOutcome(arcOrder, arcsCreated, chaptersCreated, scenesCreated);
}
/** Ordre de chapitre suivant + compteurs créés (chapitre et, en cascade, ses scènes). */
private record ChapterOutcome(int nextOrder, int chaptersCreated, int scenesCreated) {}
private ChapterOutcome applyChapter(String arcId, ChapterProposal chapP, int chapterOrder) {
String chapId;
int chaptersCreated = 0;
if (!isBlank(chapP.existingId())) {
chapId = chapP.existingId();
} else {
chapterOrder++;
Chapter chapter = chapterService.createChapter(
chapP.name().trim(), nullIfBlank(chapP.description()), arcId, chapterOrder);
chapId = chapter.getId();
chaptersCreated = 1;
}
int sceneOrder = countExisting(chapP.scenes(), SceneProposal::existingId);
int scenesCreated = 0;
for (SceneProposal sceneP : safe(chapP.scenes())) {
if (isBlank(sceneP.name()) || !isBlank(sceneP.existingId())) continue; // vide ou déjà présente
sceneOrder++;
sceneService.createScene(Scene.builder()
.name(sceneP.name().trim())
.description(nullIfBlank(sceneP.description()))
.playerNarration(nullIfBlank(sceneP.playerNarration()))
.gmSecretNotes(nullIfBlank(sceneP.gmNotes()))
.chapterId(chapId)
.order(sceneOrder)
.rooms(toRooms(sceneP.rooms()))
.build());
scenesCreated++;
}
return new ChapterOutcome(chapterOrder, chaptersCreated, scenesCreated);
}
/**
* Crée les PNJ proposés (description → values["Description"], même convention
* que les cartes d'action des ateliers). Les PNJ portant un nom déjà présent
@@ -182,7 +211,8 @@ public class CampaignImportService {
/** "HUB" (insensible à la casse) → {@link ArcType#HUB} ; tout le reste → LINEAR. */
private static ArcType parseArcType(String type) {
return "HUB".equalsIgnoreCase(type == null ? "" : type.trim()) ? ArcType.HUB : ArcType.LINEAR;
String normalized = type == null ? "" : type.trim();
return "HUB".equalsIgnoreCase(normalized) ? ArcType.HUB : ArcType.LINEAR;
}
/** Convertit les pièces proposées en {@link Room} (ID généré, ordre = index). */
@@ -1,6 +1,6 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.ReadinessStatus;
import com.loremind.domain.campaigncontext.readiness.ReadinessStatus;
import java.util.List;
import java.util.Map;
@@ -1,20 +1,19 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.ArcType;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.ArcType;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.Enemy;
import com.loremind.domain.campaigncontext.NodeType;
import com.loremind.domain.campaigncontext.Prerequisite;
import com.loremind.domain.campaigncontext.Quest;
import com.loremind.domain.campaigncontext.ReadinessEntityType;
import com.loremind.domain.campaigncontext.ReadinessSeverity;
import com.loremind.domain.campaigncontext.ReadinessStatus;
import com.loremind.domain.campaigncontext.Room;
import com.loremind.domain.campaigncontext.RoomBranch;
import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.SceneBranch;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.bestiary.Enemy;
import com.loremind.domain.campaigncontext.quest.NodeType;
import com.loremind.domain.campaigncontext.quest.Prerequisite;
import com.loremind.domain.campaigncontext.quest.Quest;
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
import com.loremind.domain.campaigncontext.readiness.ReadinessSeverity;
import com.loremind.domain.campaigncontext.readiness.ReadinessStatus;
import com.loremind.domain.campaigncontext.structure.Room;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.structure.SceneBranch;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
@@ -55,6 +54,8 @@ import java.util.stream.Collectors;
@Service
public class CampaignReadinessService {
private static final String SCENE_FALLBACK_NAME = "Scène";
private final CampaignRepository campaignRepository;
private final ArcRepository arcRepository;
private final ChapterRepository chapterRepository;
@@ -88,11 +89,6 @@ public class CampaignReadinessService {
Set<String> enemyIds = enemyRepository.findByCampaignId(campaignId).stream()
.map(Enemy::getId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
// Index global chapitres / scènes (cibles possibles des nœuds de quête).
Set<String> allChapterIds = new HashSet<>();
Set<String> allSceneIds = new HashSet<>();
int totalScenes = 0;
List<Quest> quests = questRepository.findByCampaignId(campaignId);
// Arcs HUB « portés » par ≥1 quête rattachée : ne comptent PAS comme vides
// (un arc HUB contient des quêtes, un arc LINÉAIRE des chapitres).
@@ -102,50 +98,28 @@ public class CampaignReadinessService {
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
arcs.sort(Comparator.comparingInt(Arc::getOrder));
// Index global chapitres / scènes (cibles possibles des nœuds de quête).
Set<String> allChapterIds = new HashSet<>();
Set<String> allSceneIds = new HashSet<>();
int totalScenes = 0;
for (Arc arc : arcs) {
List<Chapter> chapters = chapterRepository.findByArcId(arc.getId());
// Arc SYSTEM (conteneurs des quêtes libres) : jamais « vide » — c'est de la
// plomberie invisible. Ses chapitres restent analysés (CHAP-001 des conteneurs).
boolean hubCoveredByQuest = arc.getType() == ArcType.HUB && arcsWithQuests.contains(arc.getId());
if (chapters.isEmpty() && !hubCoveredByQuest && arc.getType() != ArcType.SYSTEM) {
String msg = arc.getType() == ArcType.HUB
? "Arc vide : ajoutez une quête (ou un chapitre), ou supprimez-le."
: "Arc vide : ajoutez un chapitre, ou supprimez-le.";
gaps.add(new ReadinessGap(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
"ARC-001-EMPTY", msg, ReadinessSeverity.BLOCKING, arc.getId(), null));
}
for (Chapter chapter : chapters) {
allChapterIds.add(chapter.getId());
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId());
if (scenes.isEmpty()) {
gaps.add(new ReadinessGap(ReadinessEntityType.CHAPTER, chapter.getId(),
labelOr(chapter.getName(), "Chapitre"), "CHAP-001-NO-SCENE",
"Chapitre vide : ajoutez au moins une scène pour pouvoir le jouer.",
ReadinessSeverity.BLOCKING, arc.getId(), chapter.getId()));
}
Set<String> chapterSceneIds = scenes.stream()
.map(Scene::getId).filter(Objects::nonNull).collect(Collectors.toSet());
totalScenes += scenes.size();
for (Scene scene : scenes) {
allSceneIds.add(scene.getId());
checkScene(scene, arc.getId(), chapter.getId(), chapterSceneIds, enemyIds, gaps);
}
}
ArcScan scan = checkArc(arc, arcsWithQuests, enemyIds, gaps);
allChapterIds.addAll(scan.chapterIds());
allSceneIds.addAll(scan.sceneIds());
totalScenes += scan.sceneCount();
}
Set<String> questIds = quests.stream()
.map(Quest::getId).filter(Objects::nonNull).collect(Collectors.toSet());
// Campagne vide : ni scène jouable, ni quête porteuse de contenu (couvre le mode plat).
boolean anyQuestWithNodes = quests.stream()
.anyMatch(q -> q.getNodes() != null && !q.getNodes().isEmpty());
if (totalScenes == 0 && !anyQuestWithNodes) {
if (totalScenes == 0 && !anyQuestHasNodes(quests)) {
gaps.add(new ReadinessGap(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
"CAMP-001-NO-CONTENT",
"Campagne vide : ajoutez un arc avec une scène, ou créez une quête, pour commencer à jouer.",
ReadinessSeverity.BLOCKING, null, null));
}
Set<String> questIds = quests.stream()
.map(Quest::getId).filter(Objects::nonNull).collect(Collectors.toSet());
for (Quest quest : quests) {
checkQuest(quest, allChapterIds, allSceneIds, questIds, gaps);
}
@@ -153,88 +127,149 @@ public class CampaignReadinessService {
return aggregate(campaignId, gaps);
}
/** Résultat du scan d'un arc : chapitres/scènes indexés (cibles des nœuds de quête) + total scènes. */
private record ArcScan(Set<String> chapterIds, Set<String> sceneIds, int sceneCount) {}
private ArcScan checkArc(Arc arc, Set<String> arcsWithQuests, Set<String> enemyIds, List<ReadinessGap> gaps) {
List<Chapter> chapters = chapterRepository.findByArcId(arc.getId());
// Arc SYSTEM (conteneurs des quêtes libres) : jamais « vide » — c'est de la
// plomberie invisible. Ses chapitres restent analysés (CHAP-001 des conteneurs).
boolean hubCoveredByQuest = arc.getType() == ArcType.HUB && arcsWithQuests.contains(arc.getId());
if (chapters.isEmpty() && !hubCoveredByQuest && arc.getType() != ArcType.SYSTEM) {
gaps.add(emptyArcGap(arc));
}
Set<String> chapterIds = new HashSet<>();
Set<String> sceneIds = new HashSet<>();
int sceneCount = 0;
for (Chapter chapter : chapters) {
chapterIds.add(chapter.getId());
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId());
if (scenes.isEmpty()) {
gaps.add(new ReadinessGap(ReadinessEntityType.CHAPTER, chapter.getId(),
labelOr(chapter.getName(), "Chapitre"), "CHAP-001-NO-SCENE",
"Chapitre vide : ajoutez au moins une scène pour pouvoir le jouer.",
ReadinessSeverity.BLOCKING, arc.getId(), chapter.getId()));
}
Set<String> chapterSceneIds = scenes.stream()
.map(Scene::getId).filter(Objects::nonNull).collect(Collectors.toSet());
sceneCount += scenes.size();
for (Scene scene : scenes) {
sceneIds.add(scene.getId());
checkScene(scene, arc.getId(), chapter.getId(), chapterSceneIds, enemyIds, gaps);
}
}
return new ArcScan(chapterIds, sceneIds, sceneCount);
}
private ReadinessGap emptyArcGap(Arc arc) {
String msg = arc.getType() == ArcType.HUB
? "Arc vide : ajoutez une quête (ou un chapitre), ou supprimez-le."
: "Arc vide : ajoutez un chapitre, ou supprimez-le.";
return new ReadinessGap(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
"ARC-001-EMPTY", msg, ReadinessSeverity.BLOCKING, arc.getId(), null);
}
private static boolean anyQuestHasNodes(List<Quest> quests) {
return quests.stream().anyMatch(q -> q.getNodes() != null && !q.getNodes().isEmpty());
}
private void checkScene(Scene scene, String arcId, String chapterId,
Set<String> chapterSceneIds, Set<String> enemyIds, List<ReadinessGap> gaps) {
String name = labelOr(scene.getName(), "Scène");
checkSceneName(scene, arcId, chapterId, gaps);
checkSceneBranches(scene, arcId, chapterId, chapterSceneIds, gaps);
checkSceneCombat(scene, arcId, chapterId, enemyIds, gaps);
checkSceneEnemyRefs(scene, arcId, chapterId, enemyIds, gaps);
checkSceneRooms(scene, arcId, chapterId, enemyIds, gaps);
}
// SCENE-001 — scène sans titre.
/** SCENE-001 — scène sans titre. */
private void checkSceneName(Scene scene, String arcId, String chapterId, List<ReadinessGap> gaps) {
if (isBlank(scene.getName())) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-001-NO-NAME",
"Scène sans titre : donnez-lui un nom pour l'identifier et la jouer.",
ReadinessSeverity.BLOCKING));
}
}
// SCENE-010 — branche de sortie cassée (vide / hors chapitre / auto-référence).
/** SCENE-010 — branche de sortie cassée (vide / hors chapitre / auto-référence). */
private void checkSceneBranches(Scene scene, String arcId, String chapterId,
Set<String> chapterSceneIds, List<ReadinessGap> gaps) {
List<SceneBranch> branches = scene.getBranches();
if (branches != null && branches.stream().anyMatch(b ->
if (branches == null) return;
boolean invalid = branches.stream().anyMatch(b ->
isBlank(b.targetSceneId())
|| b.targetSceneId().equals(scene.getId())
|| !chapterSceneIds.contains(b.targetSceneId()))) {
|| !chapterSceneIds.contains(b.targetSceneId()));
if (invalid) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-010-BRANCH-INVALID",
"Branche cassée : une sortie de « " + name
"Branche cassée : une sortie de « " + labelOr(scene.getName(), SCENE_FALLBACK_NAME)
+ " » pointe dans le vide, hors du chapitre, ou sur elle-même.",
ReadinessSeverity.BLOCKING));
}
}
// SCENE-011 — combat annoncé sans adversaire (règle produit clé).
if (!isBlank(scene.getCombatDifficulty())) {
boolean hasEnemyText = !isBlank(scene.getEnemies());
boolean hasResolvedEnemy = scene.getEnemyIds() != null
&& scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id) && enemyIds.contains(id));
if (!hasEnemyText && !hasResolvedEnemy) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-011-COMBAT-NO-ENEMY",
"Combat annoncé sans adversaire : ajoutez une fiche du bestiaire ou décrivez les ennemis.",
ReadinessSeverity.RECOMMENDED));
}
/** SCENE-011 — combat annoncé sans adversaire (règle produit clé). */
private void checkSceneCombat(Scene scene, String arcId, String chapterId,
Set<String> enemyIds, List<ReadinessGap> gaps) {
if (isBlank(scene.getCombatDifficulty())) return;
boolean hasEnemyText = !isBlank(scene.getEnemies());
boolean hasResolvedEnemy = scene.getEnemyIds() != null
&& scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id) && enemyIds.contains(id));
if (!hasEnemyText && !hasResolvedEnemy) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-011-COMBAT-NO-ENEMY",
"Combat annoncé sans adversaire : ajoutez une fiche du bestiaire ou décrivez les ennemis.",
ReadinessSeverity.RECOMMENDED));
}
}
// SCENE-012 — référence d'ennemi cassée (fiche supprimée).
if (scene.getEnemyIds() != null
&& scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id) && !enemyIds.contains(id))) {
/** SCENE-012 — référence d'ennemi cassée (fiche supprimée). */
private void checkSceneEnemyRefs(Scene scene, String arcId, String chapterId,
Set<String> enemyIds, List<ReadinessGap> gaps) {
if (scene.getEnemyIds() == null) return;
boolean broken = scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id) && !enemyIds.contains(id));
if (broken) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-012-ENEMY-REF-BROKEN",
"Ennemi introuvable : « " + name
"Ennemi introuvable : « " + labelOr(scene.getName(), SCENE_FALLBACK_NAME)
+ " » référence une fiche du bestiaire supprimée. Retirez la référence ou recréez la fiche.",
ReadinessSeverity.RECOMMENDED));
}
}
// SCENE-041 / SCENE-042 — pièces explorables : portes cassées + ennemis fantômes.
/** SCENE-041 / SCENE-042 — pièces explorables : portes cassées + ennemis fantômes. */
private void checkSceneRooms(Scene scene, String arcId, String chapterId,
Set<String> enemyIds, List<ReadinessGap> gaps) {
List<Room> rooms = scene.getRooms();
if (rooms != null && !rooms.isEmpty()) {
Set<String> roomIds = rooms.stream()
.map(Room::getId).filter(Objects::nonNull).collect(Collectors.toSet());
boolean roomBranchInvalid = false;
boolean roomEnemyBroken = false;
for (Room room : rooms) {
if (room.getBranches() != null) {
for (RoomBranch rb : room.getBranches()) {
if (isBlank(rb.targetRoomId())
|| rb.targetRoomId().equals(room.getId())
|| !roomIds.contains(rb.targetRoomId())) {
roomBranchInvalid = true;
}
}
}
if (room.getEnemyIds() != null) {
for (String id : room.getEnemyIds()) {
if (!isBlank(id) && !enemyIds.contains(id)) {
roomEnemyBroken = true;
}
}
}
}
if (roomBranchInvalid) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-041-ROOMBRANCH-INVALID",
"Porte cassée : dans « " + name
+ " », une sortie de pièce pointe hors de la scène ou dans le vide.",
ReadinessSeverity.BLOCKING));
}
if (roomEnemyBroken) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-042-ROOM-ENEMY-BROKEN",
"Ennemi introuvable dans une pièce de « " + name
+ " » : la référence pointe vers une fiche supprimée.",
ReadinessSeverity.RECOMMENDED));
}
if (rooms == null || rooms.isEmpty()) return;
String name = labelOr(scene.getName(), SCENE_FALLBACK_NAME);
Set<String> roomIds = rooms.stream()
.map(Room::getId).filter(Objects::nonNull).collect(Collectors.toSet());
if (rooms.stream().anyMatch(room -> hasInvalidBranch(room, roomIds))) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-041-ROOMBRANCH-INVALID",
"Porte cassée : dans « " + name
+ " », une sortie de pièce pointe hors de la scène ou dans le vide.",
ReadinessSeverity.BLOCKING));
}
if (rooms.stream().anyMatch(room -> hasBrokenEnemyRef(room, enemyIds))) {
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-042-ROOM-ENEMY-BROKEN",
"Ennemi introuvable dans une pièce de « " + name
+ " » : la référence pointe vers une fiche supprimée.",
ReadinessSeverity.RECOMMENDED));
}
}
private static boolean hasInvalidBranch(Room room, Set<String> roomIds) {
if (room.getBranches() == null) return false;
return room.getBranches().stream().anyMatch(rb ->
isBlank(rb.targetRoomId())
|| rb.targetRoomId().equals(room.getId())
|| !roomIds.contains(rb.targetRoomId()));
}
private static boolean hasBrokenEnemyRef(Room room, Set<String> enemyIds) {
if (room.getEnemyIds() == null) return false;
return room.getEnemyIds().stream().anyMatch(id -> !isBlank(id) && !enemyIds.contains(id));
}
private void checkQuest(Quest quest, Set<String> allChapterIds, Set<String> allSceneIds,
@@ -244,8 +279,7 @@ public class CampaignReadinessService {
// QUEST-001 — quête sans nœud ; sinon QUEST-010 — nœud pointant dans le vide.
if (quest.getNodes() == null || quest.getNodes().isEmpty()) {
gaps.add(questGap(quest, "QUEST-001-NO-NODES",
"Quête sans contenu : ajoutez au moins un chapitre ou une scène à « " + name + " ».",
ReadinessSeverity.BLOCKING));
"Quête sans contenu : ajoutez au moins un chapitre ou une scène à « " + name + " »."));
} else if (quest.getNodes().stream().anyMatch(n ->
n.nodeType() == null
|| isBlank(n.nodeId())
@@ -253,8 +287,7 @@ public class CampaignReadinessService {
|| (n.nodeType() == NodeType.SCENE && !allSceneIds.contains(n.nodeId())))) {
gaps.add(questGap(quest, "QUEST-010-NODE-REF-BROKEN",
"Nœud de quête cassé : dans « " + name
+ " », un chapitre ou une scène référencé n'existe plus.",
ReadinessSeverity.BLOCKING));
+ " », un chapitre ou une scène référencé n'existe plus."));
}
// CAMP-010 — prérequis QuestCompleted pointant une quête disparue.
@@ -264,8 +297,7 @@ public class CampaignReadinessService {
.anyMatch(qid -> isBlank(qid) || !questIds.contains(qid))) {
gaps.add(questGap(quest, "CAMP-010-DANGLING-QUEST-PREREQ",
"Prérequis cassé : « " + name
+ " » dépend d'une quête qui n'existe plus. Corrigez la condition de déblocage.",
ReadinessSeverity.BLOCKING));
+ " » dépend d'une quête qui n'existe plus. Corrigez la condition de déblocage."));
}
}
@@ -294,12 +326,12 @@ public class CampaignReadinessService {
private ReadinessGap sceneGap(Scene scene, String arcId, String chapterId,
String ruleId, String message, ReadinessSeverity severity) {
return new ReadinessGap(ReadinessEntityType.SCENE, scene.getId(),
labelOr(scene.getName(), "Scène"), ruleId, message, severity, arcId, chapterId);
labelOr(scene.getName(), SCENE_FALLBACK_NAME), ruleId, message, severity, arcId, chapterId);
}
private ReadinessGap questGap(Quest quest, String ruleId, String message, ReadinessSeverity severity) {
private ReadinessGap questGap(Quest quest, String ruleId, String message) {
return new ReadinessGap(ReadinessEntityType.QUEST, quest.getId(),
labelOr(quest.getName(), "Quête"), ruleId, message, severity, null, null);
labelOr(quest.getName(), "Quête"), ruleId, message, ReadinessSeverity.BLOCKING, null, null);
}
private static int severityRank(ReadinessSeverity severity) {
@@ -1,7 +1,7 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Prerequisite;
import com.loremind.domain.campaigncontext.Quest;
import com.loremind.domain.campaigncontext.quest.Prerequisite;
import com.loremind.domain.campaigncontext.quest.Quest;
import com.loremind.domain.campaigncontext.ports.QuestRepository;
import org.springframework.stereotype.Service;
@@ -1,9 +1,10 @@
package com.loremind.application.campaigncontext;
import com.loremind.application.playcontext.PlaythroughService;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.CampaignPublication;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
@@ -108,6 +109,23 @@ public class CampaignService {
campaignRepository.save(campaign);
}
/** Fiche « Publication » de la campagne (vide si jamais renseignée). */
public CampaignPublication getPublication(String id) {
Campaign campaign = campaignRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
return campaign.getPublication() != null ? campaign.getPublication() : CampaignPublication.empty();
}
/** Remplace la fiche « Publication » (nettoyée : blancs → vide, longueurs bornées). */
public CampaignPublication updatePublication(String id, CampaignPublication publication) {
Campaign campaign = campaignRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
CampaignPublication clean = publication != null ? publication.normalized() : CampaignPublication.empty();
campaign.setPublication(clean.hasContent() ? clean : null);
campaignRepository.save(campaign);
return clean;
}
private String normalizeId(String id) {
return (id == null || id.isBlank()) ? null : id;
}
@@ -1,7 +1,7 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.FieldProposal;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.generation.FieldProposal;
import com.loremind.domain.shared.ReorderSupport;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
import com.loremind.domain.campaigncontext.ports.SceneRepository;
@@ -136,7 +136,7 @@ public class ChapterService {
@Transactional
public void reorderChapters(String arcId, List<String> orderedIds) {
ReorderSupport.reorder(orderedIds,
id -> chapterRepository.findById(id).orElse(null),
chapterRepository::findById,
(chapter, i) -> {
if (arcId != null && !arcId.isBlank()) chapter.setArcId(arcId);
chapter.setOrder(i);
@@ -1,6 +1,6 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Character;
import com.loremind.domain.campaigncontext.bestiary.Character;
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
import org.springframework.stereotype.Service;
@@ -41,9 +41,9 @@ public class CharacterService {
.name(data.name())
.portraitImageId(data.portraitImageId())
.headerImageId(data.headerImageId())
.values(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>())
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
.values(copyStringMap(data.values()))
.imageValues(copyStringListMap(data.imageValues()))
.keyValueValues(copyStringMapMap(data.keyValueValues()))
.playthroughId(data.playthroughId())
.order(order)
.build();
@@ -64,9 +64,9 @@ public class CharacterService {
existing.setName(data.name());
existing.setPortraitImageId(data.portraitImageId());
existing.setHeaderImageId(data.headerImageId());
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
existing.setValues(copyStringMap(data.values()));
existing.setImageValues(copyStringListMap(data.imageValues()));
existing.setKeyValueValues(copyStringMapMap(data.keyValueValues()));
if (data.order() != null) {
existing.setOrder(data.order());
}
@@ -89,4 +89,16 @@ public class CharacterService {
.max()
.orElse(-1) + 1;
}
private static Map<String, String> copyStringMap(Map<String, String> map) {
return map != null ? new HashMap<>(map) : new HashMap<>();
}
private static Map<String, List<String>> copyStringListMap(Map<String, List<String>> map) {
return map != null ? new HashMap<>(map) : new HashMap<>();
}
private static Map<String, Map<String, String>> copyStringMapMap(Map<String, Map<String, String>> map) {
return map != null ? new HashMap<>(map) : new HashMap<>();
}
}
@@ -1,6 +1,6 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Enemy;
import com.loremind.domain.campaigncontext.bestiary.Enemy;
import com.loremind.domain.shared.ReorderSupport;
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
import com.loremind.domain.images.Image;
@@ -10,11 +10,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.*;
/**
* Service d'application pour les fiches d'ennemis (bestiaire de campagne).
@@ -48,18 +44,10 @@ public class EnemyService {
public Enemy createEnemy(EnemyData data) {
int order = data.order() != null ? data.order() : nextOrderFor(data.campaignId());
Enemy enemy = Enemy.builder()
.name(data.name())
.level(normalize(data.level()))
.folder(normalize(data.folder()))
.portraitImageId(data.portraitImageId())
.headerImageId(data.headerImageId())
.values(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>())
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
.campaignId(data.campaignId())
.order(order)
.build();
Enemy enemy = Enemy.builder().build();
applyCommonEnemyFields(enemy, data);
enemy.setCampaignId(data.campaignId());
enemy.setOrder(order);
return enemyRepository.save(enemy);
}
@@ -74,17 +62,11 @@ public class EnemyService {
public Enemy updateEnemy(String id, EnemyData data) {
Enemy existing = enemyRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Enemy non trouvé avec l'ID: " + id));
existing.setName(data.name());
existing.setLevel(normalize(data.level()));
existing.setFolder(normalize(data.folder()));
existing.setPortraitImageId(data.portraitImageId());
existing.setHeaderImageId(data.headerImageId());
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
applyCommonEnemyFields(existing, data);
if (data.order() != null) {
existing.setOrder(data.order());
}
// campaignId immuable après création.
return enemyRepository.save(existing);
}
@@ -100,7 +82,7 @@ public class EnemyService {
public void reorderEnemies(String folder, List<String> orderedIds) {
String f = normalize(folder);
ReorderSupport.reorder(orderedIds,
id -> enemyRepository.findById(id).orElse(null),
enemyRepository::findById,
(enemy, i) -> { enemy.setFolder(f); enemy.setOrder(i); },
enemyRepository::save);
}
@@ -141,9 +123,7 @@ public class EnemyService {
return null;
}
if (bytes.length == 0) return null;
String ext = contentType.contains("png") ? "png"
: contentType.contains("jpeg") || contentType.contains("jpg") ? "jpg"
: contentType.contains("gif") ? "gif" : "webp";
String ext = pickExtension(contentType);
// Type MIME canonique dérivé de l'extension : un data URL "image/jpg" (non
// standard) serait rejeté par ImageService (qui n'accepte que "image/jpeg").
String mimeType = "jpg".equals(ext) ? "image/jpeg" : "image/" + ext;
@@ -158,6 +138,14 @@ public class EnemyService {
}
}
/** Extension déduite du content-type ; "webp" par défaut si non reconnu. */
private static String pickExtension(String contentType) {
if (contentType.contains("png")) return "png";
if (contentType.contains("jpeg") || contentType.contains("jpg")) return "jpg";
if (contentType.contains("gif")) return "gif";
return "webp";
}
public record MonsterImportResult(int created, int updated) {}
/**
@@ -174,46 +162,51 @@ public class EnemyService {
}
int order = existing.stream().mapToInt(Enemy::getOrder).max().orElse(-1) + 1;
int created = 0, updated = 0;
int created = 0;
int updated = 0;
for (MonsterImport m : monsters) {
if (m.foundryRef() == null || m.foundryRef().isBlank()
|| m.name() == null || m.name().isBlank()) {
continue;
}
if (isBlank(m.foundryRef()) || isBlank(m.name())) continue;
Map<String, String> stats = m.stats() != null ? new HashMap<>(m.stats()) : new HashMap<>();
String folder = foundryFolder(m.folder());
Enemy ex = byRef.get(m.foundryRef());
if (ex != null) {
ex.setName(m.name());
ex.setFoundryStats(stats); // rafraîchit le snapshot
ex.setFolder(folder); // ré-aligne sur l'arborescence Foundry
// Portrait : seulement s'il manque (pas de ré-upload à chaque import).
if (ex.getPortraitImageId() == null) {
String portrait = storePortrait(m.imgData(), m.name());
if (portrait != null) ex.setPortraitImageId(portrait);
}
enemyRepository.save(ex);
updateMonster(ex, m, stats);
updated++;
} else {
Enemy saved = enemyRepository.save(Enemy.builder()
.name(m.name())
.foundryRef(m.foundryRef())
.foundryStats(stats)
.folder(folder)
.portraitImageId(storePortrait(m.imgData(), m.name()))
.campaignId(campaignId)
.order(order++)
.values(new HashMap<>())
.imageValues(new HashMap<>())
.keyValueValues(new HashMap<>())
.build());
byRef.put(m.foundryRef(), saved);
byRef.put(m.foundryRef(), createMonster(campaignId, m, stats, order++));
created++;
}
}
return new MonsterImportResult(created, updated);
}
/** Met à jour un monstre déjà importé : nom, snapshot de stats, dossier, portrait manquant. */
private void updateMonster(Enemy ex, MonsterImport m, Map<String, String> stats) {
ex.setName(m.name());
ex.setFoundryStats(stats); // rafraîchit le snapshot
ex.setFolder(foundryFolder(m.folder())); // ré-aligne sur l'arborescence Foundry
// Portrait : seulement s'il manque (pas de ré-upload à chaque import).
if (ex.getPortraitImageId() == null) {
String portrait = storePortrait(m.imgData(), m.name());
if (portrait != null) ex.setPortraitImageId(portrait);
}
enemyRepository.save(ex);
}
private Enemy createMonster(String campaignId, MonsterImport m, Map<String, String> stats, int order) {
return enemyRepository.save(Enemy.builder()
.name(m.name())
.foundryRef(m.foundryRef())
.foundryStats(stats)
.folder(foundryFolder(m.folder()))
.portraitImageId(storePortrait(m.imgData(), m.name()))
.campaignId(campaignId)
.order(order)
.values(new HashMap<>())
.imageValues(new HashMap<>())
.keyValueValues(new HashMap<>())
.build());
}
public List<Enemy> searchEnemies(String query) {
if (query == null || query.isBlank()) return List.of();
return enemyRepository.searchByName(query.trim());
@@ -226,10 +219,37 @@ public class EnemyService {
return trimmed.isEmpty() ? null : trimmed;
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
private int nextOrderFor(String campaignId) {
return enemyRepository.findByCampaignId(campaignId).stream()
.mapToInt(Enemy::getOrder)
.max()
.orElse(-1) + 1;
}
private static Map<String, String> copyStringMap(Map<String, String> map) {
return map != null ? new HashMap<>(map) : new HashMap<>();
}
private static Map<String, List<String>> copyStringListMap(Map<String, List<String>> map) {
return map != null ? new HashMap<>(map) : new HashMap<>();
}
private static Map<String, Map<String, String>> copyStringMapMap(Map<String, Map<String, String>> map) {
return map != null ? new HashMap<>(map) : new HashMap<>();
}
private static void applyCommonEnemyFields(Enemy enemy, EnemyData data) {
enemy.setName(data.name());
enemy.setLevel(normalize(data.level()));
enemy.setFolder(normalize(data.folder()));
enemy.setPortraitImageId(data.portraitImageId());
enemy.setHeaderImageId(data.headerImageId());
enemy.setValues(copyStringMap(data.values()));
enemy.setImageValues(copyStringListMap(data.imageValues()));
enemy.setKeyValueValues(copyStringMapMap(data.keyValueValues()));
}
}
@@ -0,0 +1,89 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.structure.LinkType;
import com.loremind.domain.campaigncontext.structure.SceneType;
import java.util.List;
/**
* Squelette d'aventure produit par une méthode guidée (Mentor d'écriture, phase M3 —
* voir docs/conception-mentor-ecriture.md) : un chapitre et ses scènes, rédigés par le MJ
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
*
* <p>Placement : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le chapitre
* est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la suite).
* Exactement l'un des deux.</p>
*
* @param arcId arc existant où ajouter le chapitre, ou {@code null}
* @param newArcName nom du nouvel arc à créer, ou {@code null}
* @param chapter le chapitre (nom obligatoire)
* @param scenes les scènes, dans l'ordre (au moins une avec un nom)
* @param linkSequentially relier chaque scène à la suivante par une sortie
* @param linkLabel libellé de ces sorties (rédigé dans la langue du MJ par le front)
* @param links liens explicites entre scènes (indices dans {@code scenes}), ou {@code null} :
* une enquête en nœuds relie ses pistes en réseau, pas en chaîne
* @param clock horloge à créer dans chaque partie de la campagne (plan du méchant), ou {@code null}
*/
public record GuidedSkeleton(
String arcId,
String newArcName,
ChapterSpec chapter,
List<SceneSpec> scenes,
boolean linkSequentially,
String linkLabel,
List<LinkSpec> links,
ClockSpec clock
) {
/** Squelette sans liens explicites ni horloge (Donjon en 5 salles). */
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
boolean linkSequentially, String linkLabel) {
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, null, null);
}
/** @param gmNotes notes réservées au MJ (vérité cachée d'une enquête, plan complet du méchant) */
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes,
String gmNotes) {
public ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
this(name, description, playerObjectives, narrativeStakes, null);
}
}
/**
* Lien d'une scène vers une autre, par position dans {@code scenes}.
*
* @param from index de la scène de départ
* @param to index de la scène d'arrivée
* @param label libellé du lien (langue du MJ)
* @param kind nature du lien (sortie, piste, indice) ; {@code null} = sortie
*/
public record LinkSpec(int from, int to, String label, LinkType kind) {
}
/**
* Horloge de progression à créer dans chaque partie (Playthrough) de la campagne.
*
* @param name nom de l'horloge
* @param description ce qui arrive quand elle est pleine
* @param segments nombre de segments (une étape du plan = un segment)
*/
public record ClockSpec(String name, String description, int segments) {
}
public record SceneSpec(
String name, String description, SceneType type, String location,
String choicesConsequences, String gmSecretNotes, String enemies) {
}
/**
* Ce qui a été créé, pour que le front ouvre directement le chapitre.
*
* @param clocks nombre d'horloges créées (une par partie de la campagne)
*/
public record Result(String arcId, String chapterId, List<String> sceneIds, int clocks) {
public Result(String arcId, String chapterId, List<String> sceneIds) {
this(arcId, chapterId, sceneIds, 0);
}
}
}
@@ -0,0 +1,217 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
import com.loremind.domain.campaigncontext.ports.SceneRepository;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.ArcType;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.structure.LinkType;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.structure.SceneBranch;
import com.loremind.domain.campaigncontext.structure.SceneType;
import com.loremind.application.playcontext.ClockService;
import com.loremind.domain.playcontext.ClockTrigger;
import com.loremind.domain.playcontext.Playthrough;
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Persiste d'un bloc le squelette d'une méthode guidée (Mentor d'écriture, phase M3) :
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
*
* <p>Ne fait qu'ajouter : rien d'existant n'est modifié, à part l'ordre naturel (le nouvel
* arc et le nouveau chapitre se placent à la suite). Transactionnel : tout ou rien.</p>
*/
@Service
public class GuidedSkeletonService {
private final ArcRepository arcRepository;
private final ChapterRepository chapterRepository;
private final SceneRepository sceneRepository;
private final ArcService arcService;
private final ChapterService chapterService;
private final SceneService sceneService;
private final PlaythroughRepository playthroughRepository;
private final ClockService clockService;
public GuidedSkeletonService(ArcRepository arcRepository,
ChapterRepository chapterRepository,
SceneRepository sceneRepository,
ArcService arcService,
ChapterService chapterService,
SceneService sceneService,
PlaythroughRepository playthroughRepository,
ClockService clockService) {
this.arcRepository = arcRepository;
this.chapterRepository = chapterRepository;
this.sceneRepository = sceneRepository;
this.arcService = arcService;
this.chapterService = chapterService;
this.sceneService = sceneService;
this.playthroughRepository = playthroughRepository;
this.clockService = clockService;
}
/**
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
* arc d'une autre campagne ou non linéaire)
*/
@Transactional
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
validate(skeleton);
String arcId = resolveArc(campaignId, skeleton);
Chapter chapter = createChapter(arcId, skeleton.chapter());
// Une scène sans nom est ignorée ; byIndex garde la position d'origine pour les liens.
List<Scene> scenes = new ArrayList<>();
List<Scene> byIndex = new ArrayList<>();
int order = 0;
for (GuidedSkeleton.SceneSpec spec : skeleton.scenes()) {
if (spec == null || isBlank(spec.name())) {
byIndex.add(null);
continue;
}
Scene created = sceneService.createScene(Scene.builder()
.name(spec.name().trim())
.description(blankToNull(spec.description()))
.type(Objects.requireNonNullElse(spec.type(), SceneType.GENERIC))
.location(blankToNull(spec.location()))
.choicesConsequences(blankToNull(spec.choicesConsequences()))
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
.enemies(blankToNull(spec.enemies()))
.chapterId(chapter.getId())
.order(order++)
.build());
scenes.add(created);
byIndex.add(created);
}
if (skeleton.linkSequentially()) {
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
}
if (skeleton.links() != null && !skeleton.links().isEmpty()) {
linkExplicitly(byIndex, skeleton.links());
}
int clocks = createClocks(campaignId, skeleton.clock());
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList(), clocks);
}
/**
* Liens explicites (réseau d'une enquête) : ajoutés aux sorties existantes. Un lien vers
* ou depuis une scène ignorée (sans nom), hors limites ou en boucle sur soi est écarté.
*/
private void linkExplicitly(List<Scene> byIndex, List<GuidedSkeleton.LinkSpec> links) {
java.util.Map<String, Scene> touched = new java.util.LinkedHashMap<>();
for (GuidedSkeleton.LinkSpec link : links) {
if (link == null || link.from() == link.to()) continue;
Scene from = at(byIndex, link.from());
Scene to = at(byIndex, link.to());
if (from == null || to == null) continue;
List<SceneBranch> branches = from.getBranches() == null ? new ArrayList<>() : new ArrayList<>(from.getBranches());
String label = isBlank(link.label()) ? to.getName() : link.label().trim();
branches.add(new SceneBranch(label, to.getId(), null,
Objects.requireNonNullElse(link.kind(), LinkType.EXIT)));
from.setBranches(branches);
touched.put(from.getId(), from);
}
touched.values().forEach(sceneRepository::save);
}
private static Scene at(List<Scene> byIndex, int index) {
return index >= 0 && index < byIndex.size() ? byIndex.get(index) : null;
}
/**
* Horloge du plan (méthode « Plan du méchant ») : créée dans chaque partie de la campagne,
* car une horloge est de l'état de partie. Aucune partie : rien n'est créé (le MJ la
* créera quand il lancera une partie).
*/
private int createClocks(String campaignId, GuidedSkeleton.ClockSpec clock) {
if (clock == null || isBlank(clock.name())) return 0;
int count = 0;
for (Playthrough p : playthroughRepository.findByCampaignId(campaignId)) {
clockService.create(p.getId(), clock.name().trim(), blankToNull(clock.description()),
clock.segments(), ClockTrigger.NONE, null, null);
count++;
}
return count;
}
private static void validate(GuidedSkeleton skeleton) {
if (skeleton == null) {
throw new IllegalArgumentException("Squelette manquant.");
}
boolean hasArc = !isBlank(skeleton.arcId());
boolean hasNewArc = !isBlank(skeleton.newArcName());
if (hasArc == hasNewArc) {
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
}
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
throw new IllegalArgumentException("Le chapitre doit avoir un nom.");
}
if (skeleton.scenes() == null || skeleton.scenes().stream().noneMatch(s -> s != null && !isBlank(s.name()))) {
throw new IllegalArgumentException("Il faut au moins une scène nommée.");
}
}
/** Arc existant (vérifié : même campagne, linéaire) ou nouvel arc linéaire placé à la suite. */
private String resolveArc(String campaignId, GuidedSkeleton skeleton) {
List<Arc> arcs = arcRepository.findByCampaignId(campaignId);
if (!isBlank(skeleton.arcId())) {
Arc arc = arcs.stream().filter(a -> skeleton.arcId().equals(a.getId())).findFirst()
.orElseThrow(() -> new IllegalArgumentException("Arc introuvable dans cette campagne."));
if (arc.getType() != ArcType.LINEAR) {
throw new IllegalArgumentException("Une méthode guidée s'ajoute à un arc linéaire.");
}
return arc.getId();
}
// L'arc SYSTEM (« Quêtes libres », ordre 9999) reste en dernier : on ne le compte pas.
int nextOrder = arcs.stream().filter(a -> a.getType() != ArcType.SYSTEM)
.mapToInt(Arc::getOrder).max().orElse(-1) + 1;
return arcService.createArc(Arc.builder()
.name(skeleton.newArcName().trim())
.campaignId(campaignId)
.type(ArcType.LINEAR)
.order(nextOrder)
.build()).getId();
}
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec) {
int nextOrder = chapterRepository.findByArcId(arcId).stream()
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
return chapterService.createChapter(Chapter.builder()
.name(spec.name().trim())
.description(blankToNull(spec.description()))
.playerObjectives(blankToNull(spec.playerObjectives()))
.narrativeStakes(blankToNull(spec.narrativeStakes()))
.gmNotes(blankToNull(spec.gmNotes()))
.arcId(arcId)
.order(nextOrder)
.build());
}
/** Chaque scène reçoit une sortie vers la suivante (la dernière n'en a pas). */
private void linkInChain(List<Scene> scenes, String label) {
for (int i = 0; i < scenes.size() - 1; i++) {
Scene scene = scenes.get(i);
scene.setBranches(new ArrayList<>(List.of(
new SceneBranch(label, scenes.get(i + 1).getId(), null, LinkType.EXIT))));
sceneRepository.save(scene);
}
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
private static String blankToNull(String s) {
return isBlank(s) ? null : s.trim();
}
}
@@ -1,12 +1,9 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.CatalogItem;
import com.loremind.domain.campaigncontext.ItemCatalog;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.itemcatalog.CatalogItem;
import com.loremind.domain.campaigncontext.itemcatalog.ItemCatalog;
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerator;
import com.loremind.domain.campaigncontext.ports.ItemCatalogRepository;
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@@ -21,18 +18,15 @@ public class ItemCatalogService {
private final ItemCatalogRepository repository;
private final ItemCatalogGenerator generator;
private final CampaignRepository campaignRepository;
private final GameSystemRepository gameSystemRepository;
private final CampaignContextFormatter campaignContextFormatter;
public ItemCatalogService(
ItemCatalogRepository repository,
ItemCatalogGenerator generator,
CampaignRepository campaignRepository,
GameSystemRepository gameSystemRepository) {
CampaignContextFormatter campaignContextFormatter) {
this.repository = repository;
this.generator = generator;
this.campaignRepository = campaignRepository;
this.gameSystemRepository = gameSystemRepository;
this.campaignContextFormatter = campaignContextFormatter;
}
public record CatalogData(
@@ -89,7 +83,8 @@ public class ItemCatalogService {
/** Génère une PROPOSITION de catalogue (non persistée) via l'IA, contextualisée campagne. */
public ItemCatalog generateProposal(String campaignId, String description) {
ItemCatalogGenerator.GeneratedCatalog g = generator.generate(description, buildContext(campaignId));
ItemCatalogGenerator.GeneratedCatalog g = generator.generate(
description, campaignContextFormatter.format(campaignId));
return ItemCatalog.builder()
.name(g.name())
.description(g.description())
@@ -102,22 +97,6 @@ public class ItemCatalogService {
return items != null ? new ArrayList<>(items) : new ArrayList<>();
}
private String buildContext(String campaignId) {
if (campaignId == null) return "";
Campaign campaign = campaignRepository.findById(campaignId).orElse(null);
if (campaign == null) return "";
StringBuilder sb = new StringBuilder();
sb.append("Campagne : ").append(campaign.getName());
if (campaign.getDescription() != null && !campaign.getDescription().isBlank()) {
sb.append(" — ").append(campaign.getDescription().trim());
}
if (campaign.getGameSystemId() != null && !campaign.getGameSystemId().isBlank()) {
gameSystemRepository.findById(campaign.getGameSystemId())
.ifPresent(gs -> sb.append("\nSystème de jeu : ").append(gs.getName()));
}
return sb.toString();
}
private int nextOrderFor(String campaignId) {
return repository.findByCampaignId(campaignId).stream()
.mapToInt(ItemCatalog::getOrder)
@@ -1,9 +1,9 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.Notebook;
import com.loremind.domain.campaigncontext.NotebookMessage;
import com.loremind.domain.campaigncontext.NotebookSource;
import com.loremind.domain.campaigncontext.notebook.Notebook;
import com.loremind.domain.campaigncontext.notebook.NotebookMessage;
import com.loremind.domain.campaigncontext.notebook.NotebookSource;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.ports.NotebookIndexer;
import com.loremind.domain.campaigncontext.ports.NotebookRepository;
@@ -1,15 +1,12 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Npc;
import com.loremind.domain.campaigncontext.bestiary.Npc;
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
import com.loremind.domain.shared.ReorderSupport;
import com.loremind.domain.campaigncontext.ports.NpcRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.*;
/**
* Service d'application pour les fiches de PNJ (campagne).
@@ -33,8 +30,17 @@ public class NpcService {
String campaignId,
List<String> relatedPageIds,
String folder,
Integer order
) {}
Integer order,
/** Rôle dans l'histoire ; null = inchangé (mise à jour) / non renseigné (création). */
NpcStory story
) {
public NpcData(String name, String portraitImageId, String headerImageId, Map<String, String> values,
Map<String, List<String>> imageValues, Map<String, Map<String, String>> keyValueValues,
String campaignId, List<String> relatedPageIds, String folder, Integer order) {
this(name, portraitImageId, headerImageId, values, imageValues, keyValueValues, campaignId,
relatedPageIds, folder, order, null);
}
}
public Npc createNpc(NpcData data) {
int order = data.order() != null
@@ -51,6 +57,7 @@ public class NpcService {
.relatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>())
.folder(normalizeFolder(data.folder()))
.order(order)
.story(cleanStory(data.story()))
.build();
return npcRepository.save(npc);
}
@@ -74,12 +81,22 @@ public class NpcService {
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
existing.setRelatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>());
existing.setFolder(normalizeFolder(data.folder()));
if (data.story() != null) {
existing.setStory(cleanStory(data.story()));
}
if (data.order() != null) {
existing.setOrder(data.order());
}
return npcRepository.save(existing);
}
/** Fiche nettoyée, ou null si elle est vide (rien à stocker). */
private static NpcStory cleanStory(NpcStory story) {
if (story == null) return null;
NpcStory clean = story.normalized();
return clean.hasContent() ? clean : null;
}
public void deleteNpc(String id) {
npcRepository.deleteById(id);
}
@@ -92,7 +109,7 @@ public class NpcService {
public void reorderNpcs(String folder, List<String> orderedIds) {
String f = normalizeFolder(folder);
ReorderSupport.reorder(orderedIds,
id -> npcRepository.findById(id).orElse(null),
npcRepository::findById,
(npc, i) -> { npc.setFolder(f); npc.setOrder(i); },
npcRepository::save);
}
@@ -1,11 +1,11 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.ArcType;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.NodeType;
import com.loremind.domain.campaigncontext.Quest;
import com.loremind.domain.campaigncontext.QuestNodeRef;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.ArcType;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.quest.NodeType;
import com.loremind.domain.campaigncontext.quest.Quest;
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
import com.loremind.domain.campaigncontext.ports.QuestRepository;
@@ -106,6 +106,11 @@ public class QuestService {
/** Le chapitre est-il un CONTENEUR de cette quête (jumeau hub ou hébergé en arc SYSTEM) ? */
private boolean isContainerOf(Quest quest, Chapter chapter) {
if (Objects.equals(quest.getArcId(), chapter.getArcId())) return true;
return inSystemArc(chapter);
}
/** Le chapitre vit-il dans l'arc technique SYSTEM (masqué partout dans l'appli) ? */
private boolean inSystemArc(Chapter chapter) {
return chapter.getArcId() != null && arcRepository.findById(chapter.getArcId())
.map(a -> a.getType() == ArcType.SYSTEM)
.orElse(false);
@@ -119,15 +124,6 @@ public class QuestService {
return questRepository.findByCampaignId(campaignId);
}
/** Quêtes rattachées à un arc HUB. */
public List<Quest> getQuestsByArcId(String arcId) {
return questRepository.findByArcId(arcId);
}
public List<Quest> getAllQuests() {
return questRepository.findAll();
}
/** Met à jour une Quest (Parameter Object pattern, comme ChapterService). */
@Transactional
public Quest updateQuest(String id, Quest updated) {
@@ -165,9 +161,22 @@ public class QuestService {
/**
* Supprime la quête et, en cascade, ses {@code QuestProgression} dans toutes les Parties.
*
* <p>TODO (Phase 5) : signaler/nettoyer les {@code Prerequisite.QuestCompleted} pendants
* d'autres quêtes qui pointaient celle-ci. Échec sûr aujourd'hui : un prérequis vers une
* quête supprimée n'est jamais satisfait → la quête dépendante reste LOCKED (pas de corruption).</p>
* <p>Nettoyage du CONTENEUR (chapitre jumeau, jamais un chapitre simplement LIÉ —
* isContainerOf exclut les liens transversaux) :
* <ul>
* <li>jumeau de HUB non vide : GARDÉ — il redevient un chapitre visible de l'arc,
* aucune perte de contenu ;</li>
* <li>conteneur d'arc SYSTEM (quête libre) : supprimé AVEC ses scènes — une fois la
* quête partie il est invisible partout dans l'appli et pourrirait en fantôme
* (réapparitions dans les exports). L'impact est annoncé au préalable par
* {@link #getDeletionImpact} (dialogue de confirmation côté front) ;</li>
* <li>conteneur encore référencé par une autre quête : jamais touché.</li>
* </ul></p>
*
* <p>Limite connue (nettoyage prévu Phase 5) : les {@code Prerequisite.QuestCompleted}
* d'autres quêtes qui pointaient celle-ci restent pendants, sans être signalés ni
* nettoyés. Échec sûr aujourd'hui : un prérequis vers une quête supprimée n'est jamais
* satisfait → la quête dépendante reste LOCKED (pas de corruption).</p>
*/
@Transactional
public void deleteQuest(String id) {
@@ -175,41 +184,56 @@ public class QuestService {
progressionRepository.deleteByQuestId(id);
questRepository.deleteById(id);
if (quest == null) return;
// Nettoyage du CONTENEUR (jumeau hub ou hébergé en arc SYSTEM) : un chapitre VIDE
// (aucune scène), plus référencé par aucune autre quête, ne doit pas réapparaître
// comme « chapitre vide » fantôme. S'il contient des scènes, on le GARDE (aucune
// perte de contenu). Les chapitres simplement LIÉS (quête transversale pointant du
// contenu réel d'un autre arc) ne sont JAMAIS touchés — isContainerOf les exclut.
List<Quest> remaining = questRepository.findByCampaignId(quest.getCampaignId());
for (QuestNodeRef node : nullSafeNodes(quest.getNodes())) {
if (node.nodeType() != NodeType.CHAPTER) continue;
chapterRepository.findById(node.nodeId()).ifPresent(ch -> {
boolean container = isContainerOf(quest, ch);
boolean empty = sceneRepository.findByChapterId(ch.getId()).isEmpty();
boolean referencedElsewhere = remaining.stream()
.anyMatch(q -> nullSafeNodes(q.getNodes()).stream()
.anyMatch(n -> n.nodeType() == NodeType.CHAPTER
&& ch.getId().equals(n.nodeId())));
if (container && empty && !referencedElsewhere) {
chapterRepository.deleteById(ch.getId());
}
if (!container || referencedElsewhere) return;
var scenes = sceneRepository.findByChapterId(ch.getId());
if (!scenes.isEmpty() && !inSystemArc(ch)) return; // jumeau de hub : reste visible
for (var scene : scenes) sceneRepository.deleteById(scene.getId());
chapterRepository.deleteById(ch.getId());
});
}
}
/** Scènes qui tomberont avec la quête (conteneurs d'arc SYSTEM exclusifs à cette quête). */
public record DeletionImpact(int scenes) {}
public DeletionImpact getDeletionImpact(String questId) {
Quest quest = questRepository.findById(questId).orElse(null);
if (quest == null) return new DeletionImpact(0);
List<Quest> others = questRepository.findByCampaignId(quest.getCampaignId()).stream()
.filter(q -> !questId.equals(q.getId()))
.toList();
int scenes = 0;
for (QuestNodeRef node : nullSafeNodes(quest.getNodes())) {
if (node.nodeType() != NodeType.CHAPTER) continue;
Chapter ch = chapterRepository.findById(node.nodeId()).orElse(null);
if (ch == null || !isContainerOf(quest, ch) || !inSystemArc(ch)) continue;
boolean referencedElsewhere = others.stream()
.anyMatch(q -> nullSafeNodes(q.getNodes()).stream()
.anyMatch(n -> n.nodeType() == NodeType.CHAPTER
&& ch.getId().equals(n.nodeId())));
if (!referencedElsewhere) scenes += sceneRepository.findByChapterId(ch.getId()).size();
}
return new DeletionImpact(scenes);
}
private static List<QuestNodeRef> nullSafeNodes(List<QuestNodeRef> nodes) {
return nodes != null ? nodes : List.of();
}
public boolean questExists(String id) {
return questRepository.existsById(id);
}
/** Réordonne les quêtes d'une campagne : {@code order} = position. Transactionnel. */
@Transactional
public void reorderQuests(String campaignId, List<String> orderedIds) {
ReorderSupport.reorder(orderedIds,
id -> questRepository.findById(id).orElse(null),
questRepository::findById,
(quest, i) -> {
if (campaignId != null && !campaignId.isBlank()) quest.setCampaignId(campaignId);
quest.setOrder(i);
@@ -1,9 +1,9 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.PrerequisiteEvaluator;
import com.loremind.domain.campaigncontext.ProgressionStatus;
import com.loremind.domain.campaigncontext.Quest;
import com.loremind.domain.campaigncontext.QuestStatus;
import com.loremind.domain.campaigncontext.quest.PrerequisiteEvaluator;
import com.loremind.domain.campaigncontext.quest.ProgressionStatus;
import com.loremind.domain.campaigncontext.quest.Quest;
import com.loremind.domain.campaigncontext.quest.QuestStatus;
import com.loremind.domain.playcontext.QuestProgression;
import com.loremind.domain.playcontext.ports.PlaythroughFlagRepository;
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
@@ -1,13 +1,10 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.RandomTable;
import com.loremind.domain.campaigncontext.randomtable.RandomTable;
import com.loremind.domain.shared.ReorderSupport;
import com.loremind.domain.campaigncontext.RandomTableEntry;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.randomtable.RandomTableEntry;
import com.loremind.domain.campaigncontext.ports.RandomTableGenerator;
import com.loremind.domain.campaigncontext.ports.RandomTableRepository;
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@@ -22,18 +19,15 @@ public class RandomTableService {
private final RandomTableRepository repository;
private final RandomTableGenerator generator;
private final CampaignRepository campaignRepository;
private final GameSystemRepository gameSystemRepository;
private final CampaignContextFormatter campaignContextFormatter;
public RandomTableService(
RandomTableRepository repository,
RandomTableGenerator generator,
CampaignRepository campaignRepository,
GameSystemRepository gameSystemRepository) {
CampaignContextFormatter campaignContextFormatter) {
this.repository = repository;
this.generator = generator;
this.campaignRepository = campaignRepository;
this.gameSystemRepository = gameSystemRepository;
this.campaignContextFormatter = campaignContextFormatter;
}
public record TableData(
@@ -90,8 +84,8 @@ public class RandomTableService {
@org.springframework.transaction.annotation.Transactional
public void reorderTables(List<String> orderedIds) {
ReorderSupport.reorder(orderedIds,
id -> repository.findById(id).orElse(null),
(table, i) -> table.setOrder(i),
repository::findById,
RandomTable::setOrder,
repository::save);
}
@@ -103,7 +97,8 @@ public class RandomTableService {
/** Génère une PROPOSITION de table (non persistée) via l'IA, contextualisée campagne. */
public RandomTable generateProposal(String campaignId, String description, String diceFormula) {
String formula = (diceFormula == null || diceFormula.isBlank()) ? "1d20" : diceFormula;
RandomTableGenerator.GeneratedTable g = generator.generate(description, formula, buildContext(campaignId));
RandomTableGenerator.GeneratedTable g = generator.generate(
description, formula, campaignContextFormatter.format(campaignId));
return RandomTable.builder()
.name(g.name())
.description(g.description())
@@ -115,24 +110,7 @@ public class RandomTableService {
/** Brode un court récit IA sur un résultat tiré (pour la partie). */
public String improviseRoll(String campaignId, String tableName, String resultLabel, String resultDetail) {
return generator.improvise(tableName, resultLabel, resultDetail, buildContext(campaignId));
}
/** Contexte libre (nom de campagne + description + système) pour orienter l'IA. */
private String buildContext(String campaignId) {
if (campaignId == null) return "";
Campaign campaign = campaignRepository.findById(campaignId).orElse(null);
if (campaign == null) return "";
StringBuilder sb = new StringBuilder();
sb.append("Campagne : ").append(campaign.getName());
if (campaign.getDescription() != null && !campaign.getDescription().isBlank()) {
sb.append(" — ").append(campaign.getDescription().trim());
}
if (campaign.getGameSystemId() != null && !campaign.getGameSystemId().isBlank()) {
gameSystemRepository.findById(campaign.getGameSystemId())
.ifPresent(gs -> sb.append("\nSystème de jeu : ").append(gs.getName()));
}
return sb.toString();
return generator.improvise(tableName, resultLabel, resultDetail, campaignContextFormatter.format(campaignId));
}
private static List<RandomTableEntry> copyEntries(List<RandomTableEntry> entries) {
@@ -1,7 +1,7 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.ReadinessEntityType;
import com.loremind.domain.campaigncontext.ReadinessSeverity;
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
import com.loremind.domain.campaigncontext.readiness.ReadinessSeverity;
/**
* Un manque de préparation détecté sur une entité de scénario (read-model, Pilier B).
@@ -1,10 +1,10 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.FieldProposal;
import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.SceneDraft;
import com.loremind.domain.campaigncontext.generation.FieldProposal;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.generation.SceneDraft;
import com.loremind.domain.shared.ReorderSupport;
import com.loremind.domain.campaigncontext.SceneBranch;
import com.loremind.domain.campaigncontext.structure.SceneBranch;
import com.loremind.domain.campaigncontext.ports.SceneRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
@@ -125,6 +125,8 @@ public class SceneService {
case "playerNarration" -> scene.setPlayerNarration(value);
case "choicesConsequences" -> scene.setChoicesConsequences(value);
case "combatDifficulty" -> scene.setCombatDifficulty(value);
case "tactics" -> scene.setTactics(value);
case "purpose" -> scene.setPurpose(value);
case "enemies" -> scene.setEnemies(value);
case "gmSecretNotes" -> scene.setGmSecretNotes(value);
default -> { /* clé inconnue → ignorée (garde-fou anti-écrasement) */ }
@@ -171,7 +173,7 @@ public class SceneService {
if (id.equals(sibling.getId()) || branches == null || branches.isEmpty()) continue;
List<SceneBranch> kept = branches.stream()
.filter(b -> !id.equals(b.targetSceneId()))
.collect(Collectors.toList());
.toList();
if (kept.size() != branches.size()) {
sibling.setBranches(kept);
sceneRepository.save(sibling);
@@ -193,7 +195,7 @@ public class SceneService {
@Transactional
public void reorderScenes(String chapterId, List<String> orderedIds) {
ReorderSupport.reorder(orderedIds,
id -> sceneRepository.findById(id).orElse(null),
sceneRepository::findById,
(scene, i) -> {
if (chapterId != null && !chapterId.isBlank() && !chapterId.equals(scene.getChapterId())) {
scene.setChapterId(chapterId);
@@ -0,0 +1,35 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
import java.util.Map;
/**
* Une remarque de relecture d'éditeur (Mentor d'écriture, phase M2) : un conseil
* d'auteur sur la QUALITÉ de l'écriture, pas sur la complétude (ça, c'est le readiness).
*
* <p>Contrairement à {@link ReadinessGap}, le back ne rédige pas le texte : il
* renvoie la règle et ses paramètres, et le front compose observation / pourquoi /
* question depuis l'i18n ({@code writingReview.rules.<ruleId>}), en fr comme en en.</p>
*
* @param entityType type de l'entité concernée (réutilise celui du readiness pour les liens profonds)
* @param entityId id de l'entité concernée
* @param entityName libellé lisible de l'entité
* @param ruleId identifiant stable de la règle (ex. {@code WRITE-002-FAKE-CHOICE})
* @param category famille de la remarque (regroupement à l'affichage)
* @param params valeurs à injecter dans le texte i18n (ex. {@code count}, {@code phrase})
* @param arcId arc parent (navigation), ou {@code null}
* @param chapterId chapitre parent (navigation), ou {@code null}
*/
public record WritingRemark(
ReadinessEntityType entityType,
String entityId,
String entityName,
String ruleId,
WritingRemarkCategory category,
Map<String, String> params,
String arcId,
String chapterId
) {
}
@@ -0,0 +1,12 @@
package com.loremind.application.campaigncontext;
import java.util.List;
/**
* Relecture d'éditeur d'une campagne (Mentor d'écriture, phase M2).
*
* @param campaignId campagne relue
* @param remarks remarques dans l'ordre de l'arbre (campagne, puis arc par arc)
*/
public record WritingReviewReport(String campaignId, List<WritingRemark> remarks) {
}
@@ -0,0 +1,539 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
import com.loremind.domain.campaigncontext.bestiary.Npc;
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
import com.loremind.domain.campaigncontext.ports.NpcRepository;
import com.loremind.domain.campaigncontext.ports.QuestRepository;
import com.loremind.domain.campaigncontext.ports.SceneRepository;
import com.loremind.domain.campaigncontext.quest.Quest;
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.ArcType;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.structure.Room;
import com.loremind.domain.campaigncontext.structure.RoomBranch;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.structure.SceneBranch;
import com.loremind.domain.campaigncontext.structure.SceneType;
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
import org.springframework.stereotype.Service;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Relecture d'éditeur (Mentor d'écriture, phase M2 — voir docs/conception-mentor-ecriture.md) :
* conseils d'auteur sur la QUALITÉ de l'écriture (vrais choix, rythme, enjeux, narration),
* là où le readiness ({@link CampaignReadinessService}) ne juge que la complétude.
*
* <p><b>Déterministe, sans IA, sans persistance</b> ; même chargement en une passe que le
* readiness (arcs → chapitres → scènes). Purement indicatif : une remarque est un conseil,
* jamais un blocage. Le texte est composé côté front à partir de {@code ruleId} + {@code params}.</p>
*
* <p>L'arc SYSTEM (« Quêtes libres ») est de la plomberie invisible : ses chapitres-conteneurs
* ne reçoivent pas de remarque de niveau chapitre, mais leurs scènes sont relues comme les autres.</p>
*/
@Service
public class WritingReviewService {
/** WRITE-001 : à partir de combien de scènes un chapitre sans aucun choix devient un couloir. */
static final int CORRIDOR_MIN_SCENES = 3;
/** WRITE-003 : nombre minimal de scènes menant à une révélation (règle des 3 indices). */
static final int REVELATION_MIN_INCOMING = 3;
/** WRITE-011 / 012 / 014 : un chapitre « qui utilise le graphe » a au moins ce nombre de scènes reliées. */
static final int LINKED_MIN_SCENES = 2;
/** WRITE-012 : taille minimale d'un chapitre pour juger un passage obligé. */
static final int CHOKEPOINT_MIN_SCENES = 4;
/** WRITE-013 : nombre minimal de pièces pour juger la forme d'un donjon. */
static final int DUNGEON_MIN_ROOMS = 4;
/** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */
static final int PROACTIVE_MIN_SCENES = 3;
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
static final int MONOTONOUS_RUN = 3;
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
static final int LONG_NARRATION_CHARS = 1200;
/** WRITE-010 : nombre minimal de scènes pour juger la part de scènes non typées. */
static final int UNTYPED_MIN_SCENES = 5;
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
static final double UNTYPED_RATIO = 0.7;
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
static final String KIND_COMBAT = "COMBAT";
/**
* WRITE-007 : la narration décide à la place des personnages (action ou émotion imposée).
* Volontairement restreint aux tournures sans ambiguïté, pour éviter les faux positifs.
*/
private static final Pattern NARRATION_DECIDES = Pattern.compile(
"\\b(vous (?:décidez|choisissez|ressentez|avez (?:très |si )?peur"
+ "|êtes (?:terrifié|effrayé|terrorisé|paniqué|soulagé|ému)e?s?"
+ "|entrez|vous précipitez|dégainez|attaquez|fuyez)"
+ "|you (?:decide|choose|feel (?:afraid|scared|uneasy|relieved|guilty)"
+ "|are (?:afraid|scared|terrified|relieved|panicking)"
+ "|enter|rush|draw your|attack|flee))\\b",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.UNICODE_CHARACTER_CLASS);
private final CampaignRepository campaignRepository;
private final ArcRepository arcRepository;
private final ChapterRepository chapterRepository;
private final SceneRepository sceneRepository;
private final QuestRepository questRepository;
private final NpcRepository npcRepository;
public WritingReviewService(CampaignRepository campaignRepository,
ArcRepository arcRepository,
ChapterRepository chapterRepository,
SceneRepository sceneRepository,
QuestRepository questRepository,
NpcRepository npcRepository) {
this.campaignRepository = campaignRepository;
this.arcRepository = arcRepository;
this.chapterRepository = chapterRepository;
this.sceneRepository = sceneRepository;
this.questRepository = questRepository;
this.npcRepository = npcRepository;
}
/** Relit toute la campagne et renvoie les remarques dans l'ordre de l'arbre. */
public WritingReviewReport review(String campaignId) {
List<WritingRemark> campaignRemarks = new ArrayList<>();
List<WritingRemark> treeRemarks = new ArrayList<>();
Set<String> arcsWithQuests = questRepository.findByCampaignId(campaignId).stream()
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
arcs.sort(Comparator.comparingInt(Arc::getOrder));
int totalScenes = 0;
int genericScenes = 0;
for (Arc arc : arcs) {
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
// WRITE-017 — une seule accroche : les personnages n'ont qu'une raison de s'en mêler.
if (visibleArc && countLines(arc.getHooks()) == 1) {
treeRemarks.add(arcRemark(arc, "WRITE-017-SINGLE-HOOK", WritingRemarkCategory.AGENCY, Map.of()));
}
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
if (visibleArc && isBlank(arc.getStakes())
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
}
List<Scene> lastChapterScenes = List.of();
for (Chapter chapter : chapters) {
List<Scene> scenes = new ArrayList<>(sceneRepository.findByChapterId(chapter.getId()));
scenes.sort(Comparator.comparingInt(Scene::getOrder));
totalScenes += scenes.size();
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
if (visibleArc) {
reviewChapter(arc, chapter, scenes, treeRemarks);
}
for (Scene scene : scenes) {
reviewScene(arc, chapter, scene, scenes, treeRemarks);
}
reviewGraph(arc, chapter, scenes, treeRemarks);
if (!scenes.isEmpty()) {
lastChapterScenes = scenes;
}
}
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
checkSingleEnding(arc, lastChapterScenes, treeRemarks);
}
}
// WRITE-010 — trop de scènes non typées pour juger le rythme.
if (totalScenes >= UNTYPED_MIN_SCENES && (double) genericScenes / totalScenes > UNTYPED_RATIO) {
String campaignName = campaignRepository.findById(campaignId).map(Campaign::getName).orElse(null);
int pct = (int) Math.round(100.0 * genericScenes / totalScenes);
campaignRemarks.add(new WritingRemark(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
"WRITE-010-UNTYPED-SCENES", WritingRemarkCategory.PACING,
Map.of("percent", String.valueOf(pct), "count", String.valueOf(genericScenes)),
null, null));
}
List<WritingRemark> remarks = new ArrayList<>(campaignRemarks);
remarks.addAll(treeRemarks);
remarks.addAll(reviewNpcs(campaignId));
return new WritingReviewReport(campaignId, remarks);
}
// --- Niveau chapitre ---------------------------------------------------------------
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
boolean anyBranch = scenes.stream().anyMatch(WritingReviewService::hasBranches);
boolean anyChoice = scenes.stream().anyMatch(s -> !isBlank(s.getChoicesConsequences()));
if (scenes.size() >= CORRIDOR_MIN_SCENES && !anyBranch && !anyChoice) {
out.add(chapterRemark(arc, chapter, "WRITE-001-CORRIDOR", WritingRemarkCategory.AGENCY,
Map.of("count", String.valueOf(scenes.size()))));
}
// WRITE-004 — rythme monotone : N scènes d'affilée du même genre.
MonotonousRun run = findMonotonousRun(scenes);
if (run != null) {
out.add(chapterRemark(arc, chapter, "WRITE-004-MONOTONOUS-PACING", WritingRemarkCategory.PACING,
Map.of("count", String.valueOf(run.length()), "kind", run.kind())));
}
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
if (isBlank(chapter.getNarrativeStakes())) {
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
}
// WRITE-014 — enquête sans relance : des révélations, mais aucun événement que le MJ
// peut déclencher si les joueurs tournent en rond.
boolean investigation = scenes.stream().anyMatch(s -> typeOf(s) == SceneType.REVELATION);
boolean proactive = scenes.stream().anyMatch(s -> typeOf(s) == SceneType.EVENT);
if (investigation && !proactive && scenes.size() >= PROACTIVE_MIN_SCENES && usesLinks(scenes)) {
out.add(chapterRemark(arc, chapter, "WRITE-014-NO-PROACTIVE", WritingRemarkCategory.PACING, Map.of()));
}
}
private record MonotonousRun(String kind, int length) {}
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
private static MonotonousRun findMonotonousRun(List<Scene> scenes) {
String currentKind = null;
int length = 0;
MonotonousRun found = null;
for (Scene scene : scenes) {
String kind = pacingKind(scene);
if (kind != null && kind.equals(currentKind)) {
length++;
} else {
if (found != null) return found;
currentKind = kind;
length = kind == null ? 0 : 1;
}
if (length >= MONOTONOUS_RUN) {
found = new MonotonousRun(currentKind, length);
}
}
return found;
}
/** Genre d'une scène pour le rythme : COMBAT, sinon son type s'il est renseigné, sinon null. */
private static String pacingKind(Scene scene) {
if (isCombat(scene)) return KIND_COMBAT;
SceneType type = typeOf(scene);
return type == SceneType.GENERIC ? null : type.name();
}
// --- Niveau scène -------------------------------------------------------------------
private void reviewScene(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
List<WritingRemark> out) {
checkFakeChoice(arc, chapter, scene, chapterScenes, out);
checkSingleClue(arc, chapter, scene, chapterScenes, out);
checkNarration(arc, chapter, scene, out);
checkCombatPurpose(arc, chapter, scene, out);
checkLinearDungeon(arc, chapter, scene, out);
}
/**
* WRITE-013 — donjon en couloir : des pièces reliées entre elles, mais sans aucune boucle
* (graphe des liens = arbre). Les joueurs ne choisissent pas leur route et ne peuvent ni
* contourner un obstacle ni revenir par un autre chemin. Muet si les pièces ne sont pas reliées.
*/
private void checkLinearDungeon(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
List<Room> rooms = scene.getRooms();
if (rooms == null || rooms.size() < DUNGEON_MIN_ROOMS) return;
Set<String> ids = rooms.stream().map(Room::getId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
// Arêtes non orientées distinctes (A→B et B→A = un seul passage).
Set<String> edges = new HashSet<>();
for (Room r : rooms) {
if (r.getBranches() == null) continue;
for (RoomBranch b : r.getBranches()) {
String to = b.targetRoomId();
if (isBlank(r.getId()) || !ids.contains(to) || r.getId().equals(to)) continue;
edges.add(r.getId().compareTo(to) < 0 ? r.getId() + "|" + to : to + "|" + r.getId());
}
}
if (edges.isEmpty()) return;
int components = countComponents(ids, edges);
int loops = edges.size() - ids.size() + components;
if (loops == 0 && components == 1) {
out.add(sceneRemark(arc, chapter, scene, "WRITE-013-LINEAR-DUNGEON", WritingRemarkCategory.AGENCY,
Map.of("rooms", String.valueOf(ids.size()))));
}
}
private static int countComponents(Set<String> nodes, Set<String> edges) {
Map<String, Set<String>> adj = new HashMap<>();
for (String n : nodes) adj.put(n, new HashSet<>());
for (String e : edges) {
String[] ab = e.split("\\|", 2);
adj.get(ab[0]).add(ab[1]);
adj.get(ab[1]).add(ab[0]);
}
Set<String> seen = new HashSet<>();
int components = 0;
for (String start : nodes) {
if (!seen.add(start)) continue;
components++;
Deque<String> stack = new ArrayDeque<>(List.of(start));
while (!stack.isEmpty()) {
for (String next : adj.get(stack.pop())) {
if (seen.add(next)) stack.push(next);
}
}
}
return components;
}
// --- Graphe du chapitre -------------------------------------------------------------
/**
* Règles sur la forme du graphe des scènes d'un chapitre, seulement s'il utilise des liens
* (sans aucun lien, c'est WRITE-001 qui parle) : WRITE-011 scène isolée, WRITE-012 passage
* obligé. Les liens sont internes au chapitre (règle de SceneService).
*/
private void reviewGraph(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
if (!usesLinks(scenes)) return;
Map<String, Set<String>> next = successors(scenes);
Set<String> withIncoming = next.values().stream().flatMap(Set::stream).collect(Collectors.toSet());
// WRITE-011 — scène isolée : ni lien entrant ni lien sortant (hors scène d'ouverture).
for (int i = 1; i < scenes.size(); i++) {
Scene s = scenes.get(i);
if (next.get(s.getId()).isEmpty() && !withIncoming.contains(s.getId())) {
out.add(sceneRemark(arc, chapter, s, "WRITE-011-ISOLATED-SCENE", WritingRemarkCategory.PACING, Map.of()));
}
}
checkChokepoint(arc, chapter, scenes, next, out);
}
/**
* WRITE-012 — passage obligé : depuis la scène d'ouverture, tous les chemins vers les
* fins du chapitre traversent une même scène. Si les joueurs y échouent ou passent à côté,
* tout s'arrête. Une seule remarque par chapitre (le premier passage obligé).
*/
private void checkChokepoint(Arc arc, Chapter chapter, List<Scene> scenes, Map<String, Set<String>> next,
List<WritingRemark> out) {
if (scenes.size() < CHOKEPOINT_MIN_SCENES) return;
String entry = scenes.get(0).getId();
if (next.get(entry).isEmpty()) return;
Set<String> reachable = reach(entry, next, null);
Set<String> ends = reachable.stream().filter(id -> next.get(id).isEmpty()).collect(Collectors.toSet());
if (ends.isEmpty()) return; // Boucle sans fin : rien à juger.
List<Scene> chokepoints = new ArrayList<>();
for (Scene s : scenes) {
String id = s.getId();
if (id.equals(entry) || ends.contains(id) || !reachable.contains(id)) continue;
Set<String> without = reach(entry, next, id);
if (ends.stream().noneMatch(without::contains)) chokepoints.add(s);
}
if (chokepoints.isEmpty()) return;
out.add(sceneRemark(arc, chapter, chokepoints.get(0), "WRITE-012-CHOKEPOINT", WritingRemarkCategory.AGENCY,
Map.of("count", String.valueOf(chokepoints.size()))));
}
/** Successeurs de chaque scène du chapitre (liens vers des scènes du même chapitre seulement). */
private static Map<String, Set<String>> successors(List<Scene> scenes) {
Set<String> ids = scenes.stream().map(Scene::getId).collect(Collectors.toSet());
Map<String, Set<String>> next = new HashMap<>();
for (Scene s : scenes) {
Set<String> targets = new LinkedHashSet<>();
if (s.getBranches() != null) {
for (SceneBranch b : s.getBranches()) {
String to = b.targetSceneId();
if (ids.contains(to) && !to.equals(s.getId())) targets.add(to);
}
}
next.put(s.getId(), targets);
}
return next;
}
/** Scènes atteignables depuis {@code from} en suivant les liens, sans passer par {@code removed}. */
private static Set<String> reach(String from, Map<String, Set<String>> next, String removed) {
Set<String> seen = new HashSet<>();
Deque<String> stack = new ArrayDeque<>(List.of(from));
seen.add(from);
while (!stack.isEmpty()) {
for (String n : next.getOrDefault(stack.pop(), Set.of())) {
if (!n.equals(removed) && seen.add(n)) stack.push(n);
}
}
return seen;
}
/** Le chapitre utilise le graphe : au moins {@link #LINKED_MIN_SCENES} scènes portent des liens. */
private static boolean usesLinks(List<Scene> scenes) {
return scenes.stream().filter(WritingReviewService::hasBranches).count() >= LINKED_MIN_SCENES;
}
/** WRITE-002 — faux carrefour : plusieurs sorties qui mènent toutes au même endroit. */
private void checkFakeChoice(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
List<WritingRemark> out) {
List<SceneBranch> branches = scene.getBranches();
if (branches == null || branches.size() < 2) return;
Set<String> targets = branches.stream().map(SceneBranch::targetSceneId).collect(Collectors.toSet());
if (targets.size() != 1) return;
String target = targets.iterator().next();
if (isBlank(target)) return; // Branche cassée : c'est l'affaire du readiness (SCENE-010).
String targetName = chapterScenes.stream()
.filter(s -> target.equals(s.getId())).map(Scene::getName)
.filter(n -> !isBlank(n)).findFirst().orElse("?");
out.add(sceneRemark(arc, chapter, scene, "WRITE-002-FAKE-CHOICE", WritingRemarkCategory.AGENCY,
Map.of("count", String.valueOf(branches.size()), "target", targetName)));
}
/**
* WRITE-003 — révélation à chemin unique (règle des 3 indices). Seulement dans un
* chapitre qui utilise des liens : sans aucun lien, c'est WRITE-001 qui parle.
*/
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
List<WritingRemark> out) {
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
List<Scene> sources = chapterScenes.stream()
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
.filter(s -> s.getBranches().stream().anyMatch(b -> scene.getId().equals(b.targetSceneId())))
.toList();
if (sources.size() < REVELATION_MIN_INCOMING) {
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
Map.of("incoming", String.valueOf(sources.size()))));
return;
}
// WRITE-015 — assez de chemins, mais tous du même genre (que des interrogatoires…) :
// un groupe qui n'aime pas ce genre de scène passe à côté de tous les indices.
Set<SceneType> kinds = sources.stream().map(WritingReviewService::typeOf).collect(Collectors.toSet());
if (kinds.size() == 1 && !kinds.contains(SceneType.GENERIC)) {
out.add(sceneRemark(arc, chapter, scene, "WRITE-015-SAME-SOURCE-CLUES", WritingRemarkCategory.AGENCY,
Map.of("kind", kinds.iterator().next().name(), "count", String.valueOf(sources.size()))));
}
}
/** WRITE-006 — narration trop longue ; WRITE-007 — narration qui décide à la place des PJ. */
private void checkNarration(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
String narration = scene.getPlayerNarration();
if (isBlank(narration)) return;
int length = narration.strip().length();
if (length > LONG_NARRATION_CHARS) {
out.add(sceneRemark(arc, chapter, scene, "WRITE-006-LONG-NARRATION", WritingRemarkCategory.NARRATION,
Map.of("chars", String.valueOf(length))));
}
Matcher m = NARRATION_DECIDES.matcher(narration);
if (m.find()) {
out.add(sceneRemark(arc, chapter, scene, "WRITE-007-NARRATION-DECIDES", WritingRemarkCategory.NARRATION,
Map.of("phrase", m.group(1))));
}
}
/** WRITE-008 — combat sans but : ni choix décrits, ni notes sur les motivations des ennemis. */
private void checkCombatPurpose(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
if (isCombat(scene) && isBlank(scene.getChoicesConsequences()) && isBlank(scene.getGmSecretNotes())
&& isBlank(scene.getTactics())) {
out.add(sceneRemark(arc, chapter, scene, "WRITE-008-COMBAT-NO-PURPOSE", WritingRemarkCategory.STAKES,
Map.of()));
}
}
// --- Niveau arc -----------------------------------------------------------------------
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
private void checkSingleEnding(Arc arc, List<Scene> lastChapterScenes, List<WritingRemark> out) {
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
Map.of("arc", labelOr(arc.getName(), "Arc")), arc.getId(), finale.getChapterId()));
}
}
// --- PNJ ----------------------------------------------------------------------------------
/**
* WRITE-016 — opposant ou allié sans motivation : un PNJ qui pèse sur l'intrigue doit
* vouloir quelque chose, sinon le MJ ne sait pas comment le faire réagir. Les figurants
* et les PNJ sans rôle précisé ne sont pas jugés (pas de bruit sur les seconds rôles).
*/
private List<WritingRemark> reviewNpcs(String campaignId) {
List<WritingRemark> out = new ArrayList<>();
for (Npc npc : npcRepository.findByCampaignId(campaignId)) {
NpcStory story = npc.getStory();
if (story != null && story.drivesThePlot() && story.normalized().motivation() == null) {
out.add(new WritingRemark(ReadinessEntityType.NPC, npc.getId(), labelOr(npc.getName(), "PNJ"),
"WRITE-016-NPC-NO-MOTIVATION", WritingRemarkCategory.STAKES,
Map.of("role", story.normalized().role()), null, null));
}
}
return out;
}
// --- Helpers ----------------------------------------------------------------------------
/** Nombre de lignes non vides (une accroche par ligne, puces « - » comprises). */
private static int countLines(String text) {
if (isBlank(text)) return 0;
return (int) text.lines().filter(l -> !l.isBlank()).count();
}
private static boolean isCombat(Scene scene) {
return typeOf(scene) == SceneType.ENCOUNTER
|| !isBlank(scene.getCombatDifficulty())
|| !isBlank(scene.getEnemies())
|| (scene.getEnemyIds() != null && scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id)));
}
private static boolean hasBranches(Scene scene) {
return scene.getBranches() != null && !scene.getBranches().isEmpty();
}
private static SceneType typeOf(Scene scene) {
return Objects.requireNonNullElse(scene.getType(), SceneType.GENERIC);
}
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
WritingRemarkCategory category, Map<String, String> params) {
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
ruleId, category, params, arc.getId(), chapter.getId());
}
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
WritingRemarkCategory category, Map<String, String> params) {
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
ruleId, category, params, arc.getId(), chapter.getId());
}
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
Map<String, String> params) {
return new WritingRemark(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
ruleId, category, params, arc.getId(), null);
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
private static String labelOr(String value, String fallback) {
return isBlank(value) ? fallback : value;
}
}
@@ -7,6 +7,7 @@ import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Optional;
import java.util.Set;
@@ -24,18 +25,18 @@ import java.util.Set;
@Service
public class StoredFileService {
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
/** Types MIME explicitement autorises (en plus de tout {@code image/*} et {@code video/*}). */
private static final Set<String> ALLOWED_EXACT_MIME = Set.of(
"application/json",
"application/octet-stream",
DEFAULT_CONTENT_TYPE,
"text/plain"
);
/** Coherent avec spring.servlet.multipart.max-file-size (application.properties). */
private static final long MAX_SIZE_BYTES = 128L * 1024 * 1024; // 128 Mo
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
private final StoredFileRepository repository;
private final FileStorage storage;
@@ -60,7 +61,7 @@ public class StoredFileService {
.contentType(resolvedType)
.sizeBytes(sizeBytes)
.storageKey(storageKey)
.uploadedAt(LocalDateTime.now())
.uploadedAt(LocalDateTime.now(ZoneId.systemDefault()))
.build();
return repository.save(file);
} catch (RuntimeException ex) {
@@ -27,8 +27,13 @@ import java.util.regex.Pattern;
@Service
public class GameSystemContextBuilder {
/** Matche "## Titre" en début de ligne (multiline). Capture le titre en groupe 1. */
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(.+?)\\s*$");
/**
* Matche "## Titre" en début de ligne (multiline). Capture le titre en groupe 1.
* Le titre est forcé à commencer par un caractère non-blanc ({@code \S.*}) : la
* frontière entre les espaces de tête et le titre devient non ambiguë (classes de
* caractères disjointes), ce qui élimine tout risque de backtracking polynomial.
*/
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
private final GameSystemRepository gameSystemRepository;
@@ -119,27 +119,29 @@ public class GameSystemService {
List<TemplateField> template = new ArrayList<>();
Set<String> usedNames = new HashSet<>();
for (FoundryStructField f : fields == null ? List.<FoundryStructField>of() : fields) {
if (f.path() == null || f.path().isBlank()) continue;
String label = (f.label() != null && !f.label().isBlank()) ? f.label().trim() : f.path();
// Nom unique : libellé si libre, sinon le chemin (toujours unique).
String name = usedNames.contains(label.toLowerCase()) ? f.path() : label;
if (usedNames.contains(name.toLowerCase())) continue;
usedNames.add(name.toLowerCase());
FieldType type = "number".equalsIgnoreCase(f.type()) ? FieldType.NUMBER : FieldType.TEXT;
template.add(new TemplateField(name, type, null, null, f.path()));
for (FoundryStructField f : fields != null ? fields : List.<FoundryStructField>of()) {
TemplateField field = toTemplateField(f, usedNames);
if (field != null) template.add(field);
}
gs.replaceEnemyTemplate(template);
gs.setFoundryActorType(normalize(actorType));
return gameSystemRepository.save(gs);
}
public void deleteGameSystem(String id) {
gameSystemRepository.deleteById(id);
/** Convertit un champ Foundry en TemplateField, ou null si son chemin est vide ou son nom déjà pris. */
private static TemplateField toTemplateField(FoundryStructField f, Set<String> usedNames) {
if (f.path() == null || f.path().isBlank()) return null;
String label = (f.label() != null && !f.label().isBlank()) ? f.label().trim() : f.path();
// Nom unique : libellé si libre, sinon le chemin (toujours unique).
String name = usedNames.contains(label.toLowerCase()) ? f.path() : label;
if (usedNames.contains(name.toLowerCase())) return null;
usedNames.add(name.toLowerCase());
FieldType type = "number".equalsIgnoreCase(f.type()) ? FieldType.NUMBER : FieldType.TEXT;
return new TemplateField(name, type, null, null, f.path());
}
public boolean gameSystemExists(String id) {
return gameSystemRepository.existsById(id);
public void deleteGameSystem(String id) {
gameSystemRepository.deleteById(id);
}
public List<GameSystem> searchGameSystems(String query) {
@@ -1,12 +1,12 @@
package com.loremind.application.generationcontext;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.ArcType;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.ArcType;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.Character;
import com.loremind.domain.campaigncontext.Npc;
import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.bestiary.Character;
import com.loremind.domain.campaigncontext.bestiary.Npc;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
@@ -93,26 +93,26 @@ public class CampaignStructuralContextBuilder {
// les enemyIds des pièces sans N+1 sur le repo.
Map<String, String> enemyLabelById = enemyRepository.findByCampaignId(campaignId).stream()
.collect(Collectors.toMap(
com.loremind.domain.campaigncontext.Enemy::getId,
com.loremind.domain.campaigncontext.bestiary.Enemy::getId,
CampaignStructuralContextBuilder::enemyLabel,
(a, b) -> a));
List<ArcSummary> arcs = arcRepository.findByCampaignId(campaignId).stream()
.sorted(Comparator.comparingInt(Arc::getOrder))
.map(arc -> toArcSummary(arc, enemyLabelById))
.collect(Collectors.toList());
.toList();
List<CharacterSummary> characters = (playthroughId == null || playthroughId.isBlank())
? List.of()
: characterRepository.findByPlaythroughId(playthroughId).stream()
.sorted(Comparator.comparingInt(Character::getOrder))
.map(this::toCharacterSummary)
.collect(Collectors.toList());
.toList();
List<NpcSummary> npcs = npcRepository.findByCampaignId(campaignId).stream()
.sorted(Comparator.comparingInt(Npc::getOrder))
.map(this::toNpcSummary)
.collect(Collectors.toList());
.toList();
return new CampaignStructuralContext(
campaign.getName(),
@@ -140,27 +140,36 @@ public class CampaignStructuralContextBuilder {
* Snippet pour le resume IA : 1re ligne signifiante de la 1re valeur non vide
* du template (refonte 2026-04-30 — remplace l'ancien parsing markdown).
*/
private static String extractSnippet(java.util.Map<String, String> values) {
private static String extractSnippet(Map<String, String> values) {
if (values == null || values.isEmpty()) return "";
for (String value : values.values()) {
if (value == null || value.isBlank()) continue;
String firstLine = value.lines()
.map(String::strip)
.filter(l -> !l.isEmpty() && !l.startsWith("#"))
.findFirst()
.orElse("");
if (firstLine.isEmpty()) continue;
if (firstLine.length() <= CHARACTER_SNIPPET_MAX_LEN) return firstLine;
return firstLine.substring(0, CHARACTER_SNIPPET_MAX_LEN - 1).stripTrailing() + "…";
}
return "";
return values.values().stream()
.filter(v -> v != null && !v.isBlank())
.map(CampaignStructuralContextBuilder::firstMeaningfulLine)
.filter(l -> !l.isEmpty())
.findFirst()
.map(CampaignStructuralContextBuilder::truncateSnippet)
.orElse("");
}
/** 1re ligne non vide et non-titre ("# ...") d'une valeur de template, ou "" si aucune. */
private static String firstMeaningfulLine(String value) {
return value.lines()
.map(String::strip)
.filter(l -> !l.isEmpty() && !l.startsWith("#"))
.findFirst()
.orElse("");
}
private static String truncateSnippet(String firstLine) {
if (firstLine.length() <= CHARACTER_SNIPPET_MAX_LEN) return firstLine;
return firstLine.substring(0, CHARACTER_SNIPPET_MAX_LEN - 1).stripTrailing() + "…";
}
private ArcSummary toArcSummary(Arc arc, Map<String, String> enemyLabelById) {
List<ChapterSummary> chapters = chapterRepository.findByArcId(arc.getId()).stream()
.sorted(Comparator.comparingInt(Chapter::getOrder))
.map(chapter -> toChapterSummary(chapter, enemyLabelById))
.collect(Collectors.toList());
.toList();
return new ArcSummary(
arc.getName(),
arc.getDescription(),
@@ -181,7 +190,7 @@ public class CampaignStructuralContextBuilder {
List<SceneSummary> summaries = scenes.stream()
.map(s -> toSceneSummary(s, nameById, enemyLabelById))
.collect(Collectors.toList());
.toList();
return new ChapterSummary(
chapter.getName(),
@@ -199,7 +208,7 @@ public class CampaignStructuralContextBuilder {
b.label(),
nameById.getOrDefault(b.targetSceneId(), "(scène inconnue)"),
b.condition()))
.collect(Collectors.toList());
.toList();
List<RoomSummary> rooms = toRoomSummaries(scene, enemyLabelById);
@@ -221,8 +230,8 @@ public class CampaignStructuralContextBuilder {
if (scene.getRooms() == null || scene.getRooms().isEmpty()) return List.of();
Map<String, String> nameById = scene.getRooms().stream()
.collect(Collectors.toMap(
com.loremind.domain.campaigncontext.Room::getId,
com.loremind.domain.campaigncontext.Room::getName,
com.loremind.domain.campaigncontext.structure.Room::getId,
com.loremind.domain.campaigncontext.structure.Room::getName,
(a, b) -> a));
return scene.getRooms().stream()
.map(r -> {
@@ -233,12 +242,12 @@ public class CampaignStructuralContextBuilder {
b.label(),
nameById.getOrDefault(b.targetRoomId(), "(pièce inconnue)"),
b.condition()))
.collect(Collectors.toList());
.toList();
return new RoomSummary(
r.getName(), r.getFloor(), r.getDescription(),
roomEnemiesText(r, enemyLabelById), hints);
})
.collect(Collectors.toList());
.toList();
}
/**
@@ -247,7 +256,7 @@ public class CampaignStructuralContextBuilder {
* libre. L'un ou l'autre peut être vide.
*/
private static String roomEnemiesText(
com.loremind.domain.campaigncontext.Room room, Map<String, String> enemyLabelById) {
com.loremind.domain.campaigncontext.structure.Room room, Map<String, String> enemyLabelById) {
String linked = room.getEnemyIds() == null ? "" : room.getEnemyIds().stream()
.map(enemyLabelById::get)
.filter(l -> l != null && !l.isBlank())
@@ -259,7 +268,7 @@ public class CampaignStructuralContextBuilder {
}
/** Libellé court d'une fiche du bestiaire : « Nom (niveau) » ou « Nom ». */
private static String enemyLabel(com.loremind.domain.campaigncontext.Enemy enemy) {
private static String enemyLabel(com.loremind.domain.campaigncontext.bestiary.Enemy enemy) {
String level = enemy.getLevel() == null ? "" : enemy.getLevel().strip();
return level.isEmpty() ? enemy.getName() : enemy.getName() + " (" + level + ")";
}
@@ -1,14 +1,13 @@
package com.loremind.application.generationcontext;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.SceneDraft;
import com.loremind.domain.campaigncontext.SceneDraftProposal;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.application.campaigncontext.CampaignContextFormatter;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.generation.SceneDraft;
import com.loremind.domain.campaigncontext.generation.SceneDraftProposal;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
import com.loremind.domain.campaigncontext.ports.SceneDraftAssistant;
import com.loremind.domain.campaigncontext.ports.SceneRepository;
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -30,19 +29,16 @@ public class DraftScenesUseCase {
private final ChapterRepository chapterRepository;
private final SceneRepository sceneRepository;
private final CampaignRepository campaignRepository;
private final GameSystemRepository gameSystemRepository;
private final CampaignContextFormatter campaignContextFormatter;
private final SceneDraftAssistant assistant;
public DraftScenesUseCase(ChapterRepository chapterRepository,
SceneRepository sceneRepository,
CampaignRepository campaignRepository,
GameSystemRepository gameSystemRepository,
CampaignContextFormatter campaignContextFormatter,
SceneDraftAssistant assistant) {
this.chapterRepository = chapterRepository;
this.sceneRepository = sceneRepository;
this.campaignRepository = campaignRepository;
this.gameSystemRepository = gameSystemRepository;
this.campaignContextFormatter = campaignContextFormatter;
this.assistant = assistant;
}
@@ -55,13 +51,13 @@ public class DraftScenesUseCase {
List<SceneDraft> drafts = assistant.draftScenes(context, instruction, n).stream()
.filter(d -> d != null && d.name() != null && !d.name().isBlank())
.limit(n)
.collect(Collectors.toList());
.toList();
return new SceneDraftProposal(chapterId, drafts);
}
private String buildContext(Chapter chapter, String campaignId) {
StringBuilder sb = new StringBuilder();
sb.append("Chapitre : ").append(blankToLabel(chapter.getName(), "(sans titre)")).append("\n");
sb.append("Chapitre : ").append(blankToLabel(chapter.getName())).append("\n");
appendIf(sb, "Synopsis", chapter.getDescription());
appendIf(sb, "Objectifs des joueurs", chapter.getPlayerObjectives());
appendIf(sb, "Enjeux narratifs", chapter.getNarrativeStakes());
@@ -78,17 +74,10 @@ public class DraftScenesUseCase {
}
if (campaignId != null && !campaignId.isBlank()) {
campaignRepository.findById(campaignId).ifPresent(c -> {
sb.append("Campagne : ").append(c.getName());
if (c.getDescription() != null && !c.getDescription().isBlank()) {
sb.append(" — ").append(c.getDescription().trim());
}
sb.append("\n");
if (c.getGameSystemId() != null && !c.getGameSystemId().isBlank()) {
gameSystemRepository.findById(c.getGameSystemId())
.ifPresent(gs -> sb.append("Système de jeu : ").append(gs.getName()).append("\n"));
}
});
String campaignBlock = campaignContextFormatter.format(campaignId);
if (!campaignBlock.isBlank()) {
sb.append(campaignBlock).append("\n");
}
}
return sb.toString();
}
@@ -99,7 +88,7 @@ public class DraftScenesUseCase {
}
}
private static String blankToLabel(String value, String fallback) {
return value == null || value.isBlank() ? fallback : value;
private static String blankToLabel(String value) {
return value == null || value.isBlank() ? "(sans titre)" : value;
}
}
@@ -30,6 +30,8 @@ import java.util.Map;
@Service
public class GeneratePageValuesUseCase {
private static final String FOR_PAGE = ") pour la page ";
private final PageRepository pageRepository;
private final TemplateRepository templateRepository;
private final LoreRepository loreRepository;
@@ -96,22 +98,19 @@ public class GeneratePageValuesUseCase {
}
return templateRepository.findById(templateId)
.orElseThrow(() -> new IllegalStateException(
"Template introuvable (id=" + templateId
+ ") pour la page " + pageId));
"Template introuvable (id=" + templateId + FOR_PAGE + pageId));
}
private Lore loadLore(String loreId, String pageId) {
return loreRepository.findById(loreId)
.orElseThrow(() -> new IllegalStateException(
"Lore introuvable (id=" + loreId
+ ") pour la page " + pageId));
"Lore introuvable (id=" + loreId + FOR_PAGE + pageId));
}
private LoreNode loadFolder(String nodeId, String pageId) {
return loreNodeRepository.findById(nodeId)
.orElseThrow(() -> new IllegalStateException(
"Dossier parent introuvable (id=" + nodeId
+ ") pour la page " + pageId));
"Dossier parent introuvable (id=" + nodeId + FOR_PAGE + pageId));
}
private void requireNonEmptyFields(Template template) {
@@ -110,7 +110,7 @@ public class LoreStructuralContextBuilder {
return allPages.stream()
.filter(p -> nodeId.equals(p.getNodeId()))
.map(p -> toPageSummary(p, templateNameById, pageTitleById))
.collect(Collectors.toList());
.toList();
}
private PageSummary toPageSummary(
@@ -160,7 +160,7 @@ public class LoreStructuralContextBuilder {
return relatedIds.stream()
.map(pageTitleById::get)
.filter(title -> title != null && !title.isBlank())
.collect(Collectors.toList());
.toList();
}
private List<String> extractUniqueTags(List<Page> pages) {
@@ -168,6 +168,6 @@ public class LoreStructuralContextBuilder {
.filter(p -> p.getTags() != null)
.flatMap(p -> p.getTags().stream())
.distinct()
.collect(Collectors.toList());
.toList();
}
}
@@ -1,10 +1,9 @@
package com.loremind.application.generationcontext;
import com.loremind.domain.campaigncontext.EntityFieldPatchProposal;
import com.loremind.domain.campaigncontext.FieldProposal;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.application.campaigncontext.CampaignContextFormatter;
import com.loremind.domain.campaigncontext.generation.EntityFieldPatchProposal;
import com.loremind.domain.campaigncontext.generation.FieldProposal;
import com.loremind.domain.campaigncontext.ports.NarrativeFieldAssistant;
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@@ -26,18 +25,15 @@ import java.util.stream.Collectors;
public class NarrativeAssistFieldsUseCase {
private final NarrativeFieldCatalog catalog;
private final CampaignRepository campaignRepository;
private final GameSystemRepository gameSystemRepository;
private final CampaignContextFormatter campaignContextFormatter;
private final NarrativeFieldAssistant assistant;
public NarrativeAssistFieldsUseCase(
NarrativeFieldCatalog catalog,
CampaignRepository campaignRepository,
GameSystemRepository gameSystemRepository,
CampaignContextFormatter campaignContextFormatter,
NarrativeFieldAssistant assistant) {
this.catalog = catalog;
this.campaignRepository = campaignRepository;
this.gameSystemRepository = gameSystemRepository;
this.campaignContextFormatter = campaignContextFormatter;
this.assistant = assistant;
}
@@ -46,7 +42,7 @@ public class NarrativeAssistFieldsUseCase {
List<NarrativeFieldAssistant.FieldSpec> specs = snap.defs().stream()
.map(d -> new NarrativeFieldAssistant.FieldSpec(d.key(), d.label()))
.collect(Collectors.toList());
.toList();
Set<String> allowed = snap.defs().stream()
.map(NarrativeFieldCatalog.FieldDef::key).collect(Collectors.toSet());
@@ -56,19 +52,26 @@ public class NarrativeAssistFieldsUseCase {
List<FieldProposal> fields = new ArrayList<>();
for (NarrativeFieldAssistant.ProposedField pf : proposed) {
if (pf.key() == null || !allowed.contains(pf.key())) continue;
if (pf.value() == null || pf.value().isBlank()) continue;
String current = snap.current().getOrDefault(pf.key(), "");
fields.add(new FieldProposal(pf.key(), current, pf.value()));
FieldProposal proposal = toFieldProposal(pf, allowed, snap);
if (proposal != null) fields.add(proposal);
}
return new EntityFieldPatchProposal(snap.entityType(), entityId, "patch", fields);
}
/** Convertit un champ proposé par l'IA en FieldProposal, ou null si sa clé n'est pas autorisée ou sa valeur vide. */
private static FieldProposal toFieldProposal(
NarrativeFieldAssistant.ProposedField pf, Set<String> allowed, NarrativeFieldCatalog.Snapshot snap) {
if (pf.key() == null || !allowed.contains(pf.key())) return null;
if (pf.value() == null || pf.value().isBlank()) return null;
String current = snap.current().getOrDefault(pf.key(), "");
return new FieldProposal(pf.key(), current, pf.value());
}
/** Contexte compact : type + titre + valeurs actuelles non vides + méta campagne. */
private String buildContext(String campaignId, NarrativeFieldCatalog.Snapshot snap) {
StringBuilder sb = new StringBuilder();
sb.append(entityLabel(snap.entityType())).append(" : ")
.append(blankToLabel(snap.title(), "(sans titre)")).append("\n");
.append(blankToLabel(snap.title())).append("\n");
sb.append("État actuel des champs :\n");
boolean any = false;
for (Map.Entry<String, String> e : snap.current().entrySet()) {
@@ -82,17 +85,10 @@ public class NarrativeAssistFieldsUseCase {
sb.append("- (tous les champs sont vides — à créer de zéro)\n");
}
if (campaignId != null && !campaignId.isBlank()) {
campaignRepository.findById(campaignId).ifPresent(c -> {
sb.append("Campagne : ").append(c.getName());
if (c.getDescription() != null && !c.getDescription().isBlank()) {
sb.append(" — ").append(c.getDescription().trim());
}
sb.append("\n");
if (c.getGameSystemId() != null && !c.getGameSystemId().isBlank()) {
gameSystemRepository.findById(c.getGameSystemId())
.ifPresent(gs -> sb.append("Système de jeu : ").append(gs.getName()).append("\n"));
}
});
String campaignBlock = campaignContextFormatter.format(campaignId);
if (!campaignBlock.isBlank()) {
sb.append(campaignBlock).append("\n");
}
}
return sb.toString();
}
@@ -106,7 +102,7 @@ public class NarrativeAssistFieldsUseCase {
};
}
private static String blankToLabel(String value, String fallback) {
return value == null || value.isBlank() ? fallback : value;
private static String blankToLabel(String value) {
return value == null || value.isBlank() ? "(sans titre)" : value;
}
}
@@ -1,10 +1,10 @@
package com.loremind.application.generationcontext;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.Character;
import com.loremind.domain.campaigncontext.Npc;
import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.bestiary.Character;
import com.loremind.domain.campaigncontext.bestiary.Npc;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
@@ -28,6 +28,9 @@ import java.util.Map;
@Component
public class NarrativeEntityContextBuilder {
/** Longueur max d'une valeur de stat dans le résumé d'ennemi lié (contexte focus compact). */
private static final int STAT_VALUE_MAX_LEN = 100;
private final ArcRepository arcRepository;
private final ChapterRepository chapterRepository;
private final SceneRepository sceneRepository;
@@ -144,14 +147,14 @@ public class NarrativeEntityContextBuilder {
StringBuilder sb = new StringBuilder();
for (String enemyId : s.getEnemyIds()) {
enemyRepository.findById(enemyId).ifPresent(e -> {
if (sb.length() > 0) sb.append("\n");
if (!sb.isEmpty()) sb.append("\n");
sb.append("- ").append(e.getName());
if (e.getLevel() != null && !e.getLevel().isBlank()) {
sb.append(" (").append(e.getLevel().trim()).append(")");
}
String stats = e.getValues().entrySet().stream()
.filter(en -> en.getValue() != null && !en.getValue().isBlank())
.map(en -> en.getKey() + ": " + truncate(en.getValue().trim(), 100))
.map(en -> en.getKey() + ": " + truncate(en.getValue().trim()))
.collect(java.util.stream.Collectors.joining(" ; "));
if (!stats.isEmpty()) sb.append(" — ").append(stats);
});
@@ -159,8 +162,8 @@ public class NarrativeEntityContextBuilder {
return sb.toString();
}
private static String truncate(String value, int maxLen) {
return value.length() <= maxLen ? value : value.substring(0, maxLen - 1).stripTrailing() + "…";
private static String truncate(String value) {
return value.length() <= STAT_VALUE_MAX_LEN ? value : value.substring(0, STAT_VALUE_MAX_LEN - 1).stripTrailing() + "…";
}
private NarrativeEntityContext fromCharacter(Character c) {
@@ -1,8 +1,8 @@
package com.loremind.application.generationcontext;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.structure.Arc;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.structure.Scene;
import com.loremind.domain.campaigncontext.ports.ArcRepository;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
import com.loremind.domain.campaigncontext.ports.SceneRepository;
@@ -29,22 +29,25 @@ public class NarrativeFieldCatalog {
public record Snapshot(String entityType, String title,
LinkedHashMap<String, String> current, List<FieldDef> defs) {}
private static final String FIELD_DESCRIPTION = "description";
private static final String FIELD_GM_NOTES = "gmNotes";
private static final List<FieldDef> ARC_DEFS = List.of(
new FieldDef("description", "description / synopsis de l'arc"),
new FieldDef(FIELD_DESCRIPTION, "description / synopsis de l'arc"),
new FieldDef("themes", "thèmes explorés"),
new FieldDef("stakes", "enjeux globaux pour les personnages"),
new FieldDef("rewards", "récompenses et progression"),
new FieldDef("resolution", "dénouement prévu"),
new FieldDef("gmNotes", "notes privées du MJ"));
new FieldDef(FIELD_GM_NOTES, "notes privées du MJ"));
private static final List<FieldDef> CHAPTER_DEFS = List.of(
new FieldDef("description", "synopsis du chapitre"),
new FieldDef(FIELD_DESCRIPTION, "synopsis du chapitre"),
new FieldDef("playerObjectives", "objectifs des joueurs"),
new FieldDef("narrativeStakes", "enjeux narratifs dramatiques"),
new FieldDef("gmNotes", "notes privées du MJ"));
new FieldDef(FIELD_GM_NOTES, "notes privées du MJ"));
private static final List<FieldDef> SCENE_DEFS = List.of(
new FieldDef("description", "description courte de la scène"),
new FieldDef(FIELD_DESCRIPTION, "description courte de la scène"),
new FieldDef("location", "lieu où se déroule la scène"),
new FieldDef("timing", "moment / temporalité"),
new FieldDef("atmosphere", "ambiance (sons, odeurs, émotions, lumière)"),
@@ -80,12 +83,12 @@ public class NarrativeFieldCatalog {
Arc a = arcRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Arc non trouvé: " + id));
LinkedHashMap<String, String> cur = new LinkedHashMap<>();
cur.put("description", nz(a.getDescription()));
cur.put(FIELD_DESCRIPTION, nz(a.getDescription()));
cur.put("themes", nz(a.getThemes()));
cur.put("stakes", nz(a.getStakes()));
cur.put("rewards", nz(a.getRewards()));
cur.put("resolution", nz(a.getResolution()));
cur.put("gmNotes", nz(a.getGmNotes()));
cur.put(FIELD_GM_NOTES, nz(a.getGmNotes()));
return new Snapshot("arc", a.getName(), cur, ARC_DEFS);
}
@@ -93,10 +96,10 @@ public class NarrativeFieldCatalog {
Chapter c = chapterRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Chapitre non trouvé: " + id));
LinkedHashMap<String, String> cur = new LinkedHashMap<>();
cur.put("description", nz(c.getDescription()));
cur.put(FIELD_DESCRIPTION, nz(c.getDescription()));
cur.put("playerObjectives", nz(c.getPlayerObjectives()));
cur.put("narrativeStakes", nz(c.getNarrativeStakes()));
cur.put("gmNotes", nz(c.getGmNotes()));
cur.put(FIELD_GM_NOTES, nz(c.getGmNotes()));
return new Snapshot("chapter", c.getName(), cur, CHAPTER_DEFS);
}
@@ -104,7 +107,7 @@ public class NarrativeFieldCatalog {
Scene s = sceneRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Scène non trouvée: " + id));
LinkedHashMap<String, String> cur = new LinkedHashMap<>();
cur.put("description", nz(s.getDescription()));
cur.put(FIELD_DESCRIPTION, nz(s.getDescription()));
cur.put("location", nz(s.getLocation()));
cur.put("timing", nz(s.getTiming()));
cur.put("atmosphere", nz(s.getAtmosphere()));
@@ -1,9 +1,9 @@
package com.loremind.application.generationcontext;
import com.loremind.domain.campaigncontext.PrerequisiteEvaluator;
import com.loremind.domain.campaigncontext.ProgressionStatus;
import com.loremind.domain.campaigncontext.Quest;
import com.loremind.domain.campaigncontext.QuestStatus;
import com.loremind.domain.campaigncontext.quest.PrerequisiteEvaluator;
import com.loremind.domain.campaigncontext.quest.ProgressionStatus;
import com.loremind.domain.campaigncontext.quest.Quest;
import com.loremind.domain.campaigncontext.quest.QuestStatus;
import com.loremind.domain.campaigncontext.ports.QuestRepository;
import com.loremind.domain.generationcontext.SessionContext;
import com.loremind.domain.generationcontext.SessionContext.JournalEntrySummary;
@@ -26,7 +26,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Construit le SessionContext injecté dans le prompt IA pendant une partie.
@@ -62,10 +61,6 @@ public class SessionStructuralContextBuilder {
this.questProgressionRepository = questProgressionRepository;
}
public Optional<SessionContext> buildOptional(String sessionId) {
return sessionRepository.findById(sessionId).map(this::toContext);
}
public SessionContext build(String sessionId) {
Session session = sessionRepository.findById(sessionId)
.orElseThrow(() -> new IllegalArgumentException("Session introuvable : " + sessionId));
@@ -97,7 +92,7 @@ public class SessionStructuralContextBuilder {
return kept.stream()
.map(e -> toSummary(e, null))
.collect(Collectors.toList());
.toList();
}
/**
@@ -209,6 +204,6 @@ public class SessionStructuralContextBuilder {
.filter(Map.Entry::getValue)
.map(Map.Entry::getKey)
.sorted()
.collect(Collectors.toList());
.toList();
}
}
@@ -7,7 +7,7 @@ import com.loremind.domain.gamesystemcontext.GenerationIntent;
import com.loremind.domain.generationcontext.CampaignStructuralContext;
import com.loremind.domain.generationcontext.ChatMessage;
import com.loremind.domain.generationcontext.ChatRequest;
import com.loremind.domain.generationcontext.ChatUsage;
import com.loremind.domain.generationcontext.ChatStreamCallbacks;
import com.loremind.domain.generationcontext.GameSystemContext;
import com.loremind.domain.generationcontext.LoreStructuralContext;
import com.loremind.domain.generationcontext.NarrativeEntityContext;
@@ -15,7 +15,6 @@ import com.loremind.domain.generationcontext.ports.AiChatProvider;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.function.Consumer;
/**
* Use case applicatif : chat conversationnel pour une Campagne avec Structural Context.
@@ -72,10 +71,7 @@ public class StreamChatForCampaignUseCase {
String entityType,
String entityId,
List<ChatMessage> messages,
Consumer<ChatUsage> onUsage,
Consumer<String> onToken,
Runnable onComplete,
Consumer<Throwable> onError) {
ChatStreamCallbacks callbacks) {
Campaign campaign = campaignRepository.findById(campaignId)
.orElseThrow(() -> new IllegalArgumentException(
@@ -94,7 +90,7 @@ public class StreamChatForCampaignUseCase {
.gameSystemContext(gameSystemContext)
.build();
aiChatProvider.streamChat(request, onUsage, onToken, onComplete, onError);
aiChatProvider.streamChat(request, callbacks);
}
/**
@@ -2,7 +2,7 @@ package com.loremind.application.generationcontext;
import com.loremind.domain.generationcontext.ChatMessage;
import com.loremind.domain.generationcontext.ChatRequest;
import com.loremind.domain.generationcontext.ChatUsage;
import com.loremind.domain.generationcontext.ChatStreamCallbacks;
import com.loremind.domain.generationcontext.LoreStructuralContext;
import com.loremind.domain.generationcontext.PageContext;
import com.loremind.domain.generationcontext.ports.AiChatProvider;
@@ -15,7 +15,6 @@ import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* Use case applicatif : chat conversationnel avec Structural Context d'un Lore.
@@ -61,10 +60,7 @@ public class StreamChatForLoreUseCase {
String loreId,
String pageId,
List<ChatMessage> messages,
Consumer<ChatUsage> onUsage,
Consumer<String> onToken,
Runnable onComplete,
Consumer<Throwable> onError) {
ChatStreamCallbacks callbacks) {
LoreStructuralContext loreContext = loreContextBuilder.build(loreId);
PageContext pageContext = (pageId == null || pageId.isBlank())
@@ -77,7 +73,7 @@ public class StreamChatForLoreUseCase {
.pageContext(pageContext)
.build();
aiChatProvider.streamChat(request, onUsage, onToken, onComplete, onError);
aiChatProvider.streamChat(request, callbacks);
}
/**
@@ -7,7 +7,7 @@ import com.loremind.domain.gamesystemcontext.GenerationIntent;
import com.loremind.domain.generationcontext.CampaignStructuralContext;
import com.loremind.domain.generationcontext.ChatMessage;
import com.loremind.domain.generationcontext.ChatRequest;
import com.loremind.domain.generationcontext.ChatUsage;
import com.loremind.domain.generationcontext.ChatStreamCallbacks;
import com.loremind.domain.generationcontext.GameSystemContext;
import com.loremind.domain.generationcontext.LoreStructuralContext;
import com.loremind.domain.generationcontext.SessionContext;
@@ -19,7 +19,6 @@ import com.loremind.domain.playcontext.ports.SessionRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.function.Consumer;
/**
* Use case applicatif : chat IA pendant une Session de jeu.
@@ -71,10 +70,7 @@ public class StreamChatForSessionUseCase {
public void execute(
String sessionId,
List<ChatMessage> messages,
Consumer<ChatUsage> onUsage,
Consumer<String> onToken,
Runnable onComplete,
Consumer<Throwable> onError) {
ChatStreamCallbacks callbacks) {
Session session = sessionRepository.findById(sessionId)
.orElseThrow(() -> new IllegalArgumentException("Session introuvable : " + sessionId));
@@ -102,7 +98,7 @@ public class StreamChatForSessionUseCase {
.sessionContext(sessionContext)
.build();
aiChatProvider.streamChat(request, onUsage, onToken, onComplete, onError);
aiChatProvider.streamChat(request, callbacks);
}
private LoreStructuralContext loadLoreContextOrNull(Campaign campaign) {
@@ -7,6 +7,7 @@ import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -60,7 +61,7 @@ public class ImageService {
.contentType(contentType)
.sizeBytes(sizeBytes)
.storageKey(storageKey)
.uploadedAt(LocalDateTime.now())
.uploadedAt(LocalDateTime.now(ZoneId.systemDefault()))
.build();
return imageRepository.save(image);
} catch (RuntimeException ex) {
@@ -52,8 +52,8 @@ public class LicenseService {
this.repository = repository;
this.jwtVerifier = jwtVerifier;
this.relay = relay;
this.gracePeriodSeconds = (long) gracePeriodDays * 86_400L;
this.refreshBeforeExpirySeconds = (long) refreshBeforeExpiryDays * 86_400L;
this.gracePeriodSeconds = gracePeriodDays * 86_400L;
this.refreshBeforeExpirySeconds = refreshBeforeExpiryDays * 86_400L;
this.licensingEnabled = licensingEnabled;
}
@@ -134,9 +134,9 @@ public class LicenseService {
* Etat courant de la licence pour exposition UI / decision technique.
*/
public LicenseSnapshot getCurrentSnapshot() {
Optional<License> opt = repository.findCurrent();
if (opt.isEmpty()) return LicenseSnapshot.none();
return snapshotOf(opt.get(), Instant.now());
return repository.findCurrent()
.map(l -> snapshotOf(l, Instant.now()))
.orElseGet(LicenseSnapshot::none);
}
/**
@@ -161,31 +161,32 @@ public class LicenseService {
/**
* Tente un refresh si la licence est proche de l'expiration. Idempotent.
* Appele par le daemon planifie + manuellement via l'UI ("Reessayer").
*
* @return true si un refresh a ete tente (avec ou sans succes)
*/
public boolean refreshIfNeeded() {
public void refreshIfNeeded() {
Optional<License> opt = repository.findCurrent();
if (opt.isEmpty()) return false;
if (opt.isEmpty()) return;
License current = opt.get();
Instant now = Instant.now();
long secondsUntilExpiry = Duration.between(now, current.getExpiresAt()).getSeconds();
if (secondsUntilExpiry > refreshBeforeExpirySeconds) {
return false;
return;
}
return doRefresh(current, now);
doRefresh(current, now);
}
/**
* Force un refresh immediat (bouton UI "Reessayer maintenant").
*/
public boolean forceRefresh() {
return repository.findCurrent()
.map(license -> doRefresh(license, Instant.now()))
.orElse(false);
public void forceRefresh() {
repository.findCurrent().ifPresent(license -> doRefresh(license, Instant.now()));
}
private boolean doRefresh(License current, Instant now) {
/**
* Tente le refresh aupres du relais et persiste le resultat (succes ou echec) sur
* la licence. Le succes/echec est lu depuis {@code lastRefreshSucceeded}, pas
* depuis un retour de methode : le tentative est deja actee cote persistance.
*/
private void doRefresh(License current, Instant now) {
log.info("Refreshing Patreon license (current expires {})", current.getExpiresAt());
try {
String newJwt = relay.refreshToken(current.getRawJwt());
@@ -199,7 +200,6 @@ public class LicenseService {
current.setLastRefreshSucceeded(true);
repository.save(current);
log.info("License refreshed successfully (new expiry {})", claims.expiresAt());
return true;
} catch (LicenseRelay.RelayException e) {
current.setLastRefreshAttemptAt(now);
current.setLastRefreshSucceeded(false);
@@ -209,13 +209,11 @@ public class LicenseService {
} else {
log.warn("Relay refresh transient failure ({}): {}", e.getKind(), e.getMessage());
}
return true;
} catch (JwtVerifier.JwtVerificationException e) {
current.setLastRefreshAttemptAt(now);
current.setLastRefreshSucceeded(false);
repository.save(current);
log.error("Relay returned a JWT that fails verification: {}", e.getMessage());
return true;
}
}
@@ -77,7 +77,7 @@ public class LoreNodeService {
public void reorderNodes(String parentId, List<String> orderedIds) {
String parent = (parentId == null || parentId.isBlank()) ? null : parentId;
ReorderSupport.reorder(orderedIds,
id -> loreNodeRepository.findById(id).orElse(null),
loreNodeRepository::findById,
(node, i) -> {
if (parent == null || !isSelfOrDescendant(parent, node.getId())) {
node.setParentId(parent);
@@ -15,7 +15,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Service d'application pour le contexte Lore.
@@ -72,7 +71,7 @@ public class LoreService {
public List<Lore> getAllLores() {
return loreRepository.findAll().stream()
.map(this::withCounts)
.collect(Collectors.toList());
.toList();
}
/**
@@ -4,7 +4,6 @@ import com.loremind.domain.lorecontext.Page;
import com.loremind.domain.lorecontext.ports.PageRepository;
import org.springframework.stereotype.Service;
import com.loremind.domain.shared.CollectionUtils;
import com.loremind.domain.shared.ReorderSupport;
import java.util.ArrayList;
@@ -84,14 +83,7 @@ public class PageService {
existing.setTitle(changes.getTitle());
existing.setNodeId(changes.getNodeId());
existing.setValues(CollectionUtils.copyMap(changes.getValues()));
existing.setImageValues(CollectionUtils.copyMap(changes.getImageValues()));
existing.setImageFraming(CollectionUtils.copyMap(changes.getImageFraming()));
existing.setKeyValueValues(CollectionUtils.copyMap(changes.getKeyValueValues()));
existing.setTableValues(CollectionUtils.copyMap(changes.getTableValues()));
existing.setNotes(changes.getNotes());
existing.setTags(CollectionUtils.copyList(changes.getTags()));
existing.setRelatedPageIds(CollectionUtils.copyList(changes.getRelatedPageIds()));
existing.applyEditableContent(changes);
return pageRepository.save(existing);
}
@@ -106,7 +98,7 @@ public class PageService {
@org.springframework.transaction.annotation.Transactional
public void reorderPages(String nodeId, List<String> orderedIds) {
ReorderSupport.reorder(orderedIds,
id -> pageRepository.findById(id).orElse(null),
pageRepository::findById,
(page, i) -> {
if (nodeId != null && !nodeId.isBlank()) page.setNodeId(nodeId);
page.setOrder(i);
@@ -7,6 +7,7 @@ import com.loremind.domain.playcontext.ports.SessionRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Optional;
@@ -38,7 +39,7 @@ public class SessionEntryService {
}
validateContent(data.content());
LocalDateTime now = LocalDateTime.now();
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
SessionEntry entry = SessionEntry.builder()
.sessionId(sessionId)
.type(data.type() != null ? data.type() : EntryType.NOTE)
@@ -4,10 +4,10 @@ import com.loremind.application.campaigncontext.CampaignReadinessAssessment;
import com.loremind.application.campaigncontext.CampaignReadinessService;
import com.loremind.application.campaigncontext.QuestStatusEnricher;
import com.loremind.application.campaigncontext.ReadinessGap;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.Quest;
import com.loremind.domain.campaigncontext.QuestNodeRef;
import com.loremind.domain.campaigncontext.QuestStatus;
import com.loremind.domain.campaigncontext.structure.Chapter;
import com.loremind.domain.campaigncontext.quest.Quest;
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
import com.loremind.domain.campaigncontext.quest.QuestStatus;
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
import com.loremind.domain.campaigncontext.ports.QuestRepository;
import com.loremind.domain.campaigncontext.ports.SceneRepository;
@@ -20,7 +20,6 @@ import com.loremind.domain.playcontext.ports.PlaythroughRepository;
import com.loremind.domain.playcontext.ports.SessionRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
@@ -111,7 +110,7 @@ public class SessionPrepService {
} else {
focused = assessment.gaps().stream()
.filter(g -> isFocused(g, hotspotChapterIds, hotspotSceneIds, hotspotQuestIds))
.collect(Collectors.toList());
.toList();
}
int otherGapCount = assessment.gaps().size() - focused.size();
@@ -122,7 +121,7 @@ public class SessionPrepService {
.filter(c -> c.getFilled() > 0)
.map(c -> new SessionPrepReport.ClockInfo(c.getId(), c.getName(), c.getSegments(),
c.getFilled(), c.getFrontId() != null ? frontNames.get(c.getFrontId()) : null))
.collect(Collectors.toList());
.toList();
return new SessionPrepReport(
playthroughId,
@@ -173,7 +172,7 @@ public class SessionPrepService {
List<Session> sessions = sessionRepository.findByPlaythroughId(playthroughId);
return sessions.stream()
.max(Comparator.comparing(Session::getStartedAt,
Comparator.nullsFirst(Comparator.<LocalDateTime>naturalOrder())))
Comparator.nullsFirst(Comparator.naturalOrder())))
.map(s -> new SessionPrepReport.LastSessionInfo(
s.getId(), s.getName(), s.getStartedAt(), s.getEndedAt(), s.isActive()))
.orElse(null);
@@ -183,13 +182,13 @@ public class SessionPrepService {
return quests.stream()
.filter(q -> statusById.get(q.getId()) == wanted)
.sorted(Comparator.comparingInt(Quest::getOrder))
.collect(Collectors.toList());
.toList();
}
private static List<SessionPrepReport.QuestInfo> toQuestInfos(List<Quest> quests) {
return quests.stream()
.map(q -> new SessionPrepReport.QuestInfo(q.getId(), q.getName(), q.getIcon()))
.collect(Collectors.toList());
.toList();
}
private static List<Quest> concat(List<Quest> a, List<Quest> b) {
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
@@ -23,6 +24,7 @@ import java.util.Optional;
public class SessionService {
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final String SESSION_NOT_FOUND = "Session introuvable : ";
private final SessionRepository sessionRepository;
private final SessionEntryRepository entryRepository;
@@ -57,7 +59,7 @@ public class SessionService {
"). Termine-la avant d'en lancer une nouvelle.");
});
LocalDateTime now = LocalDateTime.now();
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
Session session = Session.builder()
.name(generateDefaultName(now))
.playthroughId(playthroughId)
@@ -68,11 +70,11 @@ public class SessionService {
public Session endSession(String id) {
Session session = sessionRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Session introuvable : " + id));
.orElseThrow(() -> new IllegalArgumentException(SESSION_NOT_FOUND + id));
if (!session.isActive()) {
throw new IllegalStateException("Cette session est déjà terminée.");
}
session.setEndedAt(LocalDateTime.now());
session.setEndedAt(LocalDateTime.now(ZoneId.systemDefault()));
Session saved = sessionRepository.save(session);
// Co-MJ : la séance se clôture -> avancer les horloges « fin de séance » de la Partie.
clockService.onSessionEnded(saved.getPlaythroughId());
@@ -86,7 +88,7 @@ public class SessionService {
*/
public Session setCurrentScene(String id, String sceneId) {
Session session = sessionRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Session introuvable : " + id));
.orElseThrow(() -> new IllegalArgumentException(SESSION_NOT_FOUND + id));
session.setCurrentSceneId(sceneId != null && !sceneId.isBlank() ? sceneId : null);
return sessionRepository.save(session);
}
@@ -96,7 +98,7 @@ public class SessionService {
throw new IllegalArgumentException("Le nom de la session ne peut pas être vide.");
}
Session session = sessionRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Session introuvable : " + id));
.orElseThrow(() -> new IllegalArgumentException(SESSION_NOT_FOUND + id));
session.setName(newName.trim());
return sessionRepository.save(session);
}
@@ -109,6 +111,11 @@ public class SessionService {
return sessionRepository.findActive();
}
/** Toutes les sessions en cours, la plus récente d'abord (raccourci « Séance en cours »). */
public List<Session> getAllActive() {
return sessionRepository.findAllActive();
}
public Optional<Session> getActiveByPlaythrough(String playthroughId) {
return sessionRepository.findActiveByPlaythroughId(playthroughId);
}
@@ -124,7 +131,7 @@ public class SessionService {
@Transactional
public void deleteSession(String id) {
if (!sessionRepository.existsById(id)) {
throw new IllegalArgumentException("Session introuvable : " + id);
throw new IllegalArgumentException(SESSION_NOT_FOUND + id);
}
entryRepository.deleteBySessionId(id);
sessionRepository.deleteById(id);
@@ -0,0 +1,104 @@
package com.loremind.application.remoteaccess;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Verdict « une tablette peut-elle joindre ce PC ? », calculé à partir des faits lus sur
* le système. Logique pure (testable sans Windows).
*
* @param supported vérification possible (Windows)
* @param ready rien ne bloque côté PC
* @param publicNetworks réseaux connectés classés « Public » que le pare-feu ne laisse pas passer
* @param firewallAllowed une règle active autorise l'application sur les réseaux privés
* @param firewallBlocked une règle active BLOQUE l'application (ex. « Annuler » dans la fenêtre Windows)
* @param thirdPartyFirewalls pare-feu tiers présents : leurs réglages ne sont pas lisibles, donc {@code ready}
* ne peut pas être garanti — le front avertit l'utilisateur de les régler lui-même
* @param program exécutable concerné
* @param platform {@code windows} ou {@code linux}
* @param linuxFirewall Linux : pare-feu actif ({@code ufw}, {@code firewalld}, {@code none})
* @param portOpen Linux : port autorisé ({@code null} = invérifiable sans droits administrateur)
* @param fixCommand Linux : commande à lancer pour ouvrir le port, ou {@code null}
*/
public record NetworkReadiness(
boolean supported,
boolean ready,
List<String> publicNetworks,
boolean firewallAllowed,
boolean firewallBlocked,
List<String> thirdPartyFirewalls,
String program,
String platform,
String linuxFirewall,
Boolean portOpen,
String fixCommand
) {
static final String PUBLIC = "Public";
static final String PRIVATE = "Private";
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
if (snapshot == null || !snapshot.supported()) {
return new NetworkReadiness(false, false, List.of(), false, false, List.of(), null, null, null, null, null);
}
if (NetworkSnapshot.LINUX.equals(snapshot.platform())) {
return evaluateLinux(snapshot);
}
List<NetworkSnapshot.FirewallRule> rules = snapshot.rules() == null ? List.of() : snapshot.rules();
boolean allowedPrivate = covers(rules, "Allow", PRIVATE);
boolean blockedPrivate = covers(rules, "Block", PRIVATE);
boolean publicOpen = covers(rules, "Allow", PUBLIC) && !covers(rules, "Block", PUBLIC);
List<String> publicNetworks = (snapshot.networks() == null ? List.<NetworkSnapshot.Network>of() : snapshot.networks())
.stream()
.filter(n -> PUBLIC.equalsIgnoreCase(n.category()))
.map(n -> n.name() != null && !n.name().isBlank() ? n.name() : n.alias())
.toList();
// Un réseau public n'est un obstacle que si le pare-feu ne l'ouvre pas explicitement.
List<String> blockingPublic = publicOpen ? List.of() : publicNetworks;
// « ready » ne porte que sur ce qui est lisible (Windows) ; un pare-feu tiers est signalé à part.
boolean ready = allowedPrivate && !blockedPrivate && blockingPublic.isEmpty();
List<String> thirdParty = snapshot.thirdPartyFirewalls() == null ? List.of() : snapshot.thirdPartyFirewalls();
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, thirdParty,
snapshot.program(), NetworkSnapshot.WINDOWS, null, null, null);
}
/**
* Linux : prêt si aucun pare-feu (ufw, firewalld) n'est actif, ou si le port est ouvert.
* Port invérifiable (ufw sans droits root) : pas prêt, mais pas en erreur — le front
* affiche la commande « au cas où ».
*/
private static NetworkReadiness evaluateLinux(NetworkSnapshot s) {
String fw = s.linuxFirewall() == null ? "none" : s.linuxFirewall();
boolean ready = "none".equals(fw) || Boolean.TRUE.equals(s.portOpen());
return new NetworkReadiness(true, ready, List.of(), false, false, List.of(), null,
NetworkSnapshot.LINUX, fw, s.portOpen(), ready ? null : linuxCommand(fw, s.port()));
}
static String linuxCommand(String firewall, int port) {
return switch (firewall) {
case "ufw" -> "sudo ufw allow " + port + "/tcp";
case "firewalld" -> "sudo firewall-cmd --permanent --add-port=" + port + "/tcp && sudo firewall-cmd --reload";
default -> null;
};
}
/** Une règle ACTIVE de cette action couvre-t-elle ce profil (« Any » couvre tout) ? */
private static boolean covers(List<NetworkSnapshot.FirewallRule> rules, String action, String profile) {
return rules.stream()
.filter(r -> action.equalsIgnoreCase(r.action()) && "True".equalsIgnoreCase(r.enabled()))
.anyMatch(r -> profiles(r.profile()).stream().anyMatch(p -> p.equals("any") || p.equals(profile.toLowerCase(Locale.ROOT))));
}
private static List<String> profiles(String raw) {
if (raw == null) return List.of();
return Arrays.stream(raw.split(","))
.map(s -> s.trim().toLowerCase(Locale.ROOT))
.filter(s -> !s.isEmpty())
.toList();
}
}
@@ -0,0 +1,13 @@
package com.loremind.application.remoteaccess;
import com.loremind.domain.remoteaccess.RemoteDevice;
import java.time.Instant;
/** Vue publique d'un appareil appairé (jamais l'empreinte du jeton). */
public record PairedDevice(String id, String name, String userAgent, Instant createdAt, Instant lastSeenAt) {
static PairedDevice of(RemoteDevice d) {
return new PairedDevice(d.getId(), d.getName(), d.getUserAgent(), d.getCreatedAt(), d.getLastSeenAt());
}
}
@@ -0,0 +1,7 @@
package com.loremind.application.remoteaccess;
import java.time.Instant;
/** Code d'appairage à 6 chiffres affiché sur le PC (usage unique). */
public record PairingCode(String code, Instant expiresAt) {
}
@@ -0,0 +1,9 @@
package com.loremind.application.remoteaccess;
/** Appairage refusé : code absent, faux, expiré, ou trop d'essais. Message prêt à afficher. */
public class PairingRejectedException extends RuntimeException {
public PairingRejectedException(String message) {
super(message);
}
}
@@ -0,0 +1,10 @@
package com.loremind.application.remoteaccess;
/**
* Résultat d'un appairage réussi.
*
* @param token jeton d'appareil en clair : à poser en cookie, jamais renvoyé dans le corps
* @param device l'appareil enregistré
*/
public record PairingResult(String token, PairedDevice device) {
}
@@ -0,0 +1,266 @@
package com.loremind.application.remoteaccess;
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
import com.loremind.domain.remoteaccess.RemoteDevice;
import com.loremind.domain.remoteaccess.ports.LanConnector;
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.Base64;
import java.util.Comparator;
import java.util.Deque;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
/**
* Accès distant à l'application de bureau (tablette / téléphone sur le réseau local).
* <p>
* Modèle de confiance : le connecteur habituel reste limité à la machine (127.0.0.1) et
* n'exige rien, comme avant. Quand le MJ active l'accès distant, un SECOND connecteur
* s'ouvre sur le réseau local ; tout ce qui y arrive doit présenter un jeton d'appareil,
* obtenu en saisissant un code à 6 chiffres affiché sur le PC (usage unique, 5 minutes,
* 5 essais). Les Paramètres restent réservés à la machine (filtre {@code RemoteAccessFilter}).
* <p>
* Uniquement en mode bureau (profil {@code local}) : en Docker, rien de tout ceci n'existe.
*/
@Service
@Profile("local")
public class RemoteAccessService {
private static final Logger log = LoggerFactory.getLogger(RemoteAccessService.class);
static final Duration CODE_TTL = Duration.ofMinutes(5);
static final int CODE_MAX_ATTEMPTS = 5;
/** Garde-fou anti force brute tous codes confondus : au-delà, plus aucun essai pendant 1 min. */
static final int GLOBAL_MAX_FAILURES_PER_MINUTE = 20;
/** On ne réécrit « vu pour la dernière fois » qu'au plus une fois par minute et par appareil. */
static final Duration TOUCH_INTERVAL = Duration.ofMinutes(1);
static final int DEVICE_NAME_MAX = 100;
static final int USER_AGENT_MAX = 300;
private final RemoteAccessConfigRepository configRepository;
private final RemoteDeviceRepository deviceRepository;
private final LanConnector lanConnector;
private final int localPort;
private final Clock clock;
private final SecureRandom random = new SecureRandom();
private PairingCode currentCode;
private int attemptsLeft;
private final Deque<Instant> recentFailures = new ArrayDeque<>();
private String lastError;
@Autowired
public RemoteAccessService(RemoteAccessConfigRepository configRepository,
RemoteDeviceRepository deviceRepository,
LanConnector lanConnector,
@Value("${server.port:8080}") int localPort) {
this(configRepository, deviceRepository, lanConnector, localPort, Clock.systemUTC());
}
RemoteAccessService(RemoteAccessConfigRepository configRepository,
RemoteDeviceRepository deviceRepository,
LanConnector lanConnector,
int localPort,
Clock clock) {
this.configRepository = configRepository;
this.deviceRepository = deviceRepository;
this.lanConnector = lanConnector;
this.localPort = localPort;
this.clock = clock;
}
// --- Réglage -----------------------------------------------------------------------
/** Au démarrage : rouvre le connecteur si l'accès distant était activé. Ne bloque jamais le lancement. */
public synchronized void applySavedConfig() {
RemoteAccessConfig config = currentConfig();
if (!config.enabled()) return;
try {
lanConnector.start(config.port());
lastError = null;
} catch (IllegalStateException e) {
lastError = e.getMessage();
log.warn("Accès distant activé mais connecteur impossible à ouvrir : {}", e.getMessage());
}
}
/**
* Active ou désactive l'accès distant. À l'activation, le connecteur est ouvert AVANT
* d'enregistrer le réglage : un port occupé laisse l'accès désactivé.
*
* @throws IllegalArgumentException port hors plage ou identique au port local
* @throws IllegalStateException port déjà occupé
*/
public synchronized RemoteAccessStatus configure(boolean enabled, int port) {
if (port < 1024 || port > 65535) {
throw new IllegalArgumentException("Le port doit être compris entre 1024 et 65535.");
}
if (port == localPort) {
throw new IllegalArgumentException("Choisissez un port différent de celui de l'application (" + localPort + ").");
}
if (enabled) {
lanConnector.start(port);
} else {
lanConnector.stop();
currentCode = null;
}
lastError = null;
configRepository.save(new RemoteAccessConfig(enabled, port));
return status();
}
public synchronized RemoteAccessStatus status() {
RemoteAccessConfig config = currentConfig();
int running = lanConnector.runningPort();
List<String> urls = running > 0
? lanConnector.lanAddresses().stream().map(ip -> "http://" + ip + ":" + running).toList()
: List.of();
List<PairedDevice> devices = deviceRepository.findAll().stream()
.sorted(Comparator.comparing(RemoteDevice::getCreatedAt, Comparator.nullsLast(Comparator.naturalOrder())))
.map(PairedDevice::of)
.toList();
return new RemoteAccessStatus(config.enabled(), config.port(), running > 0, urls, lastError, devices);
}
private RemoteAccessConfig currentConfig() {
return configRepository.find().orElseGet(RemoteAccessConfig::disabledByDefault);
}
// --- Appairage -----------------------------------------------------------------------
/**
* Nouveau code d'appairage (remplace le précédent).
*
* @throws IllegalStateException si l'accès distant n'est pas ouvert
*/
public synchronized PairingCode newPairingCode() {
if (lanConnector.runningPort() <= 0) {
throw new IllegalStateException("Activez d'abord l'accès depuis le réseau local.");
}
String code = String.format("%06d", random.nextInt(1_000_000));
currentCode = new PairingCode(code, clock.instant().plus(CODE_TTL));
attemptsLeft = CODE_MAX_ATTEMPTS;
return currentCode;
}
/**
* Échange un code valide contre un jeton d'appareil (à poser en cookie). Le code est
* consommé : un second appareil demande un nouveau code.
*
* @throws PairingRejectedException code absent, faux, expiré ou trop d'essais
*/
public synchronized PairingResult pair(String code, String deviceName, String userAgent) {
Instant now = clock.instant();
pruneFailures(now);
if (recentFailures.size() >= GLOBAL_MAX_FAILURES_PER_MINUTE) {
throw new PairingRejectedException("Trop d'essais. Patientez une minute.");
}
if (currentCode == null || now.isAfter(currentCode.expiresAt())) {
currentCode = null;
recordFailure(now);
throw new PairingRejectedException("Aucun code valide : affichez un nouveau code sur le PC.");
}
if (code == null || !constantTimeEquals(code.trim(), currentCode.code())) {
recordFailure(now);
if (--attemptsLeft <= 0) {
currentCode = null;
throw new PairingRejectedException("Trop d'essais : affichez un nouveau code sur le PC.");
}
throw new PairingRejectedException("Code incorrect.");
}
currentCode = null;
String token = newToken();
RemoteDevice device = deviceRepository.save(RemoteDevice.builder()
.name(clean(deviceName, DEVICE_NAME_MAX, "Appareil"))
.tokenHash(sha256(token))
.userAgent(clean(userAgent, USER_AGENT_MAX, null))
.createdAt(now)
.lastSeenAt(now)
.build());
log.info("Accès distant : appareil appairé « {} »", device.getName());
return new PairingResult(token, PairedDevice.of(device));
}
/** Appareil correspondant au jeton présenté, s'il est connu (sinon : appairage requis). */
public Optional<RemoteDevice> authenticate(String token) {
if (token == null || token.isBlank()) return Optional.empty();
Optional<RemoteDevice> device = deviceRepository.findByTokenHash(sha256(token));
device.ifPresent(d -> {
Instant now = clock.instant();
if (d.getLastSeenAt() == null || d.getLastSeenAt().plus(TOUCH_INTERVAL).isBefore(now)) {
deviceRepository.touch(d.getId(), now);
}
});
return device;
}
/** Coupe l'accès d'un appareil. */
public boolean revoke(String deviceId) {
return deviceRepository.deleteById(deviceId);
}
/** Port réseau réglé (ouvert ou non) : celui que le pare-feu doit laisser passer. */
public synchronized int configuredPort() {
return currentConfig().port();
}
/** Port du connecteur réseau ouvert, ou -1 (pour le filtre : qui vient « de l'extérieur » ?). */
public int lanPort() {
return lanConnector.runningPort();
}
// --- Outils -----------------------------------------------------------------------------
private void recordFailure(Instant now) {
recentFailures.addLast(now);
}
private void pruneFailures(Instant now) {
Instant limit = now.minus(Duration.ofMinutes(1));
while (!recentFailures.isEmpty() && recentFailures.peekFirst().isBefore(limit)) {
recentFailures.removeFirst();
}
}
private String newToken() {
byte[] bytes = new byte[32];
random.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
static String sha256(String value) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 indisponible", e);
}
}
private static boolean constantTimeEquals(String a, String b) {
return MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8), b.getBytes(StandardCharsets.UTF_8));
}
private static String clean(String value, int max, String fallback) {
if (value == null || value.isBlank()) return fallback;
String trimmed = value.strip();
return trimmed.length() > max ? trimmed.substring(0, max) : trimmed;
}
}
@@ -0,0 +1,23 @@
package com.loremind.application.remoteaccess;
import java.util.List;
/**
* État de l'accès distant, pour l'écran Paramètres du PC.
*
* @param enabled accès activé (réglage enregistré)
* @param port port réseau dédié
* @param running connecteur réseau effectivement ouvert
* @param urls adresses à taper sur la tablette (une par interface réseau locale)
* @param lastError dernière erreur d'ouverture (ex. port occupé au démarrage), ou null
* @param devices appareils appairés
*/
public record RemoteAccessStatus(
boolean enabled,
int port,
boolean running,
List<String> urls,
String lastError,
List<PairedDevice> devices
) {
}
@@ -44,6 +44,9 @@ public class Campaign {
*/
private String graphPositions;
/** Fiche « Publication » (couverture, page technique, crédits…). Null = jamais renseignée. */
private CampaignPublication publication;
public boolean isLinkedToLore() {
return this.loreId != null && !this.loreId.isBlank();
}
@@ -0,0 +1,6 @@
package com.loremind.domain.campaigncontext;
/** Lightweight search projection with the ancestors needed to open a result. */
public record CampaignContentHit(String kind, String id, String name,
String campaignId, String campaignName, String arcId, String arcName,
String chapterId, String chapterName) {}
@@ -0,0 +1,93 @@
package com.loremind.domain.campaigncontext;
import java.util.function.UnaryOperator;
/**
* Fiche « Publication » d'une campagne : ce qu'un module vendu ou partagé affiche en
* couverture, page technique, introduction pour le MJ et page de crédits.
* <p>
* Tout est en texte libre (« 1 à 3 », « 3-5 joueurs », « 2 séances de 4 h ») : chaque
* système de jeu a ses conventions, l'auteur écrit ce qu'il veut voir imprimé.
* Valeur immuable ; {@link #normalized()} nettoie une saisie (blancs → null, longueurs bornées).
*
* @param subtitle sous-titre de couverture
* @param author auteur(s) affichés en couverture
* @param system système de jeu tel qu'il doit apparaître (« D&amp;D 5e », « Chroniques Oubliées »)
* @param levels niveaux des personnages
* @param players nombre de joueurs
* @param duration durée de jeu estimée
* @param pitch argument : l'aventure en quelques lignes
* @param gmBackground contexte caché, réservé au MJ (ce qui s'est vraiment passé)
* @param hooks accroches pour impliquer les personnages (une par ligne « - … »)
* @param contentWarnings avertissements de contenu (thèmes sensibles)
* @param credits crédits : auteur, illustrations, relecture, testeurs…
* @param legal licence et mentions légales
* @param version version du document (« 1.0 »)
* @param coverImageId image de couverture (id d'image), nullable
*/
public record CampaignPublication(
String subtitle,
String author,
String system,
String levels,
String players,
String duration,
String pitch,
String gmBackground,
String hooks,
String contentWarnings,
String credits,
String legal,
String version,
String coverImageId
) {
private static final int SHORT_MAX = 200;
private static final int LONG_MAX = 20_000;
public static CampaignPublication empty() {
return new CampaignPublication(null, null, null, null, null, null, null,
null, null, null, null, null, null, null);
}
/** Copie nettoyée : textes rognés, blancs → null, longueurs bornées. */
public CampaignPublication normalized() {
UnaryOperator<String> shortText = s -> clean(s, SHORT_MAX);
UnaryOperator<String> longText = s -> clean(s, LONG_MAX);
return new CampaignPublication(
shortText.apply(subtitle), shortText.apply(author), shortText.apply(system),
shortText.apply(levels), shortText.apply(players), shortText.apply(duration),
longText.apply(pitch), longText.apply(gmBackground), longText.apply(hooks),
longText.apply(contentWarnings), longText.apply(credits), longText.apply(legal),
shortText.apply(version), shortText.apply(coverImageId));
}
/**
* Vrai si au moins un champ est renseigné. (Pas de getter {@code isEmpty()} : il serait
* sérialisé en JSON comme un champ de plus.)
*/
public boolean hasContent() {
return !normalized().equals(empty());
}
/** Au moins une information de la page technique (système, niveaux, joueurs, durée). */
public boolean hasTechnicalSheet() {
return present(system) || present(levels) || present(players) || present(duration);
}
/** Au moins une information de la page de crédits. */
public boolean hasCredits() {
return present(author) || present(credits) || present(legal) || present(version);
}
private static boolean present(String s) {
return s != null && !s.isBlank();
}
private static String clean(String s, int max) {
if (s == null) return null;
String t = s.trim();
if (t.isEmpty()) return null;
return t.length() > max ? t.substring(0, max) : t;
}
}
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.bestiary;
import lombok.Builder;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.bestiary;
import lombok.Builder;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.bestiary;
import lombok.Builder;
import lombok.Data;
@@ -60,6 +60,9 @@ public class Npc {
/** Ordre d'affichage dans la liste des PNJ de la campagne. */
private int order;
/** Rôle dans l'histoire (rôle, motivation, ce qu'il sait, signe distinctif). Null = non renseigné. */
private NpcStory story;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@@ -0,0 +1,49 @@
package com.loremind.domain.campaigncontext.bestiary;
import java.util.Locale;
import java.util.Set;
/**
* Fiche « rôle dans l'histoire » d'un PNJ, indépendante du système de jeu (le gabarit du
* système porte les caractéristiques) : ce qui rend le PNJ jouable et utile au récit.
*
* @param role place dans l'histoire : {@code OPPONENT} (s'oppose aux PJ), {@code ALLY}
* (les aide), {@code RESOURCE} (détient une information ou un service),
* {@code EXTRA} (figurant) ; null = non précisé
* @param motivation ce qu'il veut, et ce qu'il est prêt à faire pour l'obtenir
* @param knowledge ce qu'il sait (et peut révéler) — réservé au MJ
* @param mannerism signe distinctif à jouer (geste, phrasé, tic)
*/
public record NpcStory(String role, String motivation, String knowledge, String mannerism) {
public static final Set<String> ROLES = Set.of("OPPONENT", "ALLY", "RESOURCE", "EXTRA");
private static final int SHORT_MAX = 300;
private static final int LONG_MAX = 10_000;
/** Copie nettoyée : rôle inconnu → null, textes rognés (blancs → null) et bornés. */
public NpcStory normalized() {
String r = role == null ? null : role.trim().toUpperCase(Locale.ROOT);
// Set.of(...).contains(null) lève une NullPointerException : rôle absent testé à part.
return new NpcStory(r != null && ROLES.contains(r) ? r : null,
clean(motivation, LONG_MAX), clean(knowledge, LONG_MAX), clean(mannerism, SHORT_MAX));
}
/** Vrai si au moins un élément est renseigné. */
public boolean hasContent() {
NpcStory n = normalized();
return n.role() != null || n.motivation() != null || n.knowledge() != null || n.mannerism() != null;
}
/** Un PNJ qui pèse sur l'intrigue (opposant ou allié) : sa motivation est attendue. */
public boolean drivesThePlot() {
String r = normalized().role();
return "OPPONENT".equals(r) || "ALLY".equals(r);
}
private static String clean(String s, int max) {
if (s == null) return null;
String t = s.trim();
if (t.isEmpty()) return null;
return t.length() > max ? t.substring(0, max) : t;
}
}
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.generation;
/**
* Évènement d'avancement émis pendant l'import streamé d'un PDF de campagne.
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.generation;
import java.util.List;
@@ -11,12 +11,13 @@ import java.util.List;
public record CampaignImportProposal(List<ArcProposal> arcs, List<NpcProposal> npcs) {
/**
* {@code existingId} (nullable) : si présent, le nœud existe DÉJÀ dans la
* campagne (rempli côté UI lors de la revue pré-chargée) → l'apply ne le
* recrée pas, il l'utilise comme parent des nouveaux enfants. Null = à créer.
* {@code type} = "LINEAR" ou "HUB" (mappé sur {@link ArcType} à l'apply).
* <p>
* {@code existingId} (nullable, porté aussi par Chapter/SceneProposal) : si présent,
* le nœud existe DÉJÀ dans la campagne (rempli côté UI lors de la revue pré-chargée)
* → l'apply ne le recrée pas, il l'utilise comme parent des nouveaux enfants.
* Null = à créer.
*/
/** {@code type} = "LINEAR" ou "HUB" (mappé sur {@link ArcType} à l'apply). */
public record ArcProposal(
String name, String description, String type,
List<ChapterProposal> chapters, String existingId) {
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.generation;
import java.util.List;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.generation;
/**
* Proposition IA pour UN champ textuel d'une entité (Pilier A — co-création).
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.generation;
/**
* Ébauche de scène proposée par l'IA (Pilier A — capacité « create »). Value Object
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.generation;
import java.util.List;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.itemcatalog;
import lombok.Builder;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.itemcatalog;
import lombok.Builder;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.notebook;
import lombok.Builder;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.notebook;
import lombok.Builder;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.notebook;
import lombok.Builder;
import lombok.Data;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.Arc;
import com.loremind.domain.campaigncontext.structure.Arc;
import java.util.List;
import java.util.Optional;
@@ -0,0 +1,8 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import java.util.List;
public interface CampaignContentSearchRepository {
List<CampaignContentHit> searchByName(String query);
}
@@ -1,7 +1,7 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.CampaignImportProgress;
import com.loremind.domain.campaigncontext.CampaignImportProposal;
import com.loremind.domain.campaigncontext.generation.CampaignImportProgress;
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal;
import java.util.function.Consumer;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.Chapter;
import com.loremind.domain.campaigncontext.structure.Chapter;
import java.util.List;
import java.util.Optional;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.Character;
import com.loremind.domain.campaigncontext.bestiary.Character;
import java.util.List;
import java.util.Optional;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.Enemy;
import com.loremind.domain.campaigncontext.bestiary.Enemy;
import java.util.List;
import java.util.Optional;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.CatalogItem;
import com.loremind.domain.campaigncontext.itemcatalog.CatalogItem;
import java.util.List;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.ItemCatalog;
import com.loremind.domain.campaigncontext.itemcatalog.ItemCatalog;
import java.util.List;
import java.util.Optional;
@@ -16,11 +16,22 @@ public interface NotebookChatStreamer {
record Progress(int current, int total) {}
/**
* Streame la réponse ancrée sur les sources. Les callbacks sont invoqués au fil
* de l'eau : {@code onSourcesJson} UNE fois avant le premier token (JSON brut des
* passages utilisés — transparence UI), {@code onToken} par fragment,
* {@code onProgress} (mode approfondi uniquement) pendant la lecture du document,
* {@code onDone} à la fin, {@code onError} en cas d'échec.
* Callbacks du stream, invoqués au fil de l'eau : {@code onSourcesJson} UNE fois
* avant le premier token (JSON brut des passages utilisés — transparence UI),
* {@code onToken} par fragment, {@code onProgress} (mode approfondi uniquement)
* pendant la lecture du document, {@code onDone} à la fin, {@code onError} en
* cas d'échec. Regroupés en un seul objet (Argument Object) : ils voyagent
* toujours ensemble entre ce port, son adaptateur et le controller SSE.
*/
record Callbacks(
Consumer<String> onSourcesJson,
Consumer<String> onToken,
Consumer<Progress> onProgress,
Runnable onDone,
Consumer<Throwable> onError) {}
/**
* Streame la réponse ancrée sur les sources.
*
* @param deep true = analyse approfondie (map-reduce sur tout le document) ;
* false = chat RAG (top-k).
@@ -30,9 +41,5 @@ public interface NotebookChatStreamer {
List<Msg> messages,
String context,
boolean deep,
Consumer<String> onSourcesJson,
Consumer<String> onToken,
Consumer<Progress> onProgress,
Runnable onDone,
Consumer<Throwable> onError);
Callbacks callbacks);
}
@@ -1,8 +1,8 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.Notebook;
import com.loremind.domain.campaigncontext.NotebookMessage;
import com.loremind.domain.campaigncontext.NotebookSource;
import com.loremind.domain.campaigncontext.notebook.Notebook;
import com.loremind.domain.campaigncontext.notebook.NotebookMessage;
import com.loremind.domain.campaigncontext.notebook.NotebookSource;
import java.util.List;
import java.util.Optional;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.Npc;
import com.loremind.domain.campaigncontext.bestiary.Npc;
import java.util.List;
import java.util.Optional;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.Quest;
import com.loremind.domain.campaigncontext.quest.Quest;
import java.util.List;
import java.util.Optional;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.RandomTableEntry;
import com.loremind.domain.campaigncontext.randomtable.RandomTableEntry;
import java.util.List;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.RandomTable;
import com.loremind.domain.campaigncontext.randomtable.RandomTable;
import java.util.List;
import java.util.Optional;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.SceneDraft;
import com.loremind.domain.campaigncontext.generation.SceneDraft;
import java.util.List;
@@ -1,6 +1,6 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.structure.Scene;
import java.util.List;
import java.util.Optional;
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext.ports;
package com.loremind.domain.campaigncontext.ports.exceptions;
/**
* Erreur de domaine : l'import d'un PDF de campagne a échoué (PDF illisible,
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext.ports;
package com.loremind.domain.campaigncontext.ports.exceptions;
/**
* Échec de génération IA d'un catalogue d'objets (Brain injoignable, erreur du
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext.ports;
package com.loremind.domain.campaigncontext.ports.exceptions;
/**
* Erreur de génération lors de l'étoffage IA d'une entité narrative (Brain injoignable,
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext.ports;
package com.loremind.domain.campaigncontext.ports.exceptions;
/**
* Échec d'indexation/chat d'un notebook (Brain injoignable, erreur du modèle…).
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext.ports;
package com.loremind.domain.campaigncontext.ports.exceptions;
/**
* Échec de génération/improvisation IA d'une table (Brain injoignable, erreur du
@@ -1,4 +1,4 @@
package com.loremind.domain.campaigncontext;
package com.loremind.domain.campaigncontext.quest;
/**
* Type de nœud narratif référencé par une {@link Quest} via {@link QuestNodeRef}.

Some files were not shown because too many files have changed in this diff Show More