Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2f162d823 | ||
|
|
ad3ea0e9e6 | ||
|
|
0c44e42a22 | ||
|
|
1c8b24c5dd | ||
|
|
177967af55 | ||
|
|
42c4b53ced | ||
|
|
3e9e828225 |
@@ -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/
|
||||
|
||||
@@ -6,7 +6,9 @@ name: Qualité & Sécurité
|
||||
# assainie, on pourra l'ajouter aux checks requis de la branch protection.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# 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]
|
||||
|
||||
@@ -27,11 +29,14 @@ jobs:
|
||||
- name: MegaLinter
|
||||
uses: oxsecurity/megalinter/flavors/cupcake@v9
|
||||
env:
|
||||
# push sur main → tout le dépôt ; PR → seulement les fichiers modifiés.
|
||||
VALIDATE_ALL_CODEBASE: ${{ github.event_name == 'push' }}
|
||||
# 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@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: megalinter-reports
|
||||
path: megalinter-reports/
|
||||
@@ -61,17 +66,39 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -129,3 +129,5 @@ web/coverage/
|
||||
brain/htmlcov/
|
||||
brain/.coverage
|
||||
foundry-module/
|
||||
plan-promotion-loremind.md
|
||||
post-reddit-foundryvtt.md
|
||||
|
||||
@@ -35,3 +35,9 @@ 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
@@ -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.2-beta",
|
||||
version="1.0.3",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
+14
-1
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>1.0.2-beta</version>
|
||||
<version>1.0.3</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>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
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)
|
||||
*/
|
||||
public record GuidedSkeleton(
|
||||
String arcId,
|
||||
String newArcName,
|
||||
ChapterSpec chapter,
|
||||
List<SceneSpec> scenes,
|
||||
boolean linkSequentially,
|
||||
String linkLabel
|
||||
) {
|
||||
|
||||
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||
}
|
||||
|
||||
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. */
|
||||
public record Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
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 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;
|
||||
|
||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
ArcService arcService,
|
||||
ChapterService chapterService,
|
||||
SceneService sceneService) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.arcService = arcService;
|
||||
this.chapterService = chapterService;
|
||||
this.sceneService = sceneService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
List<GuidedSkeleton.SceneSpec> specs = skeleton.scenes().stream()
|
||||
.filter(s -> s != null && !isBlank(s.name()))
|
||||
.toList();
|
||||
|
||||
String arcId = resolveArc(campaignId, skeleton);
|
||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
||||
|
||||
List<Scene> scenes = new ArrayList<>();
|
||||
int order = 0;
|
||||
for (GuidedSkeleton.SceneSpec spec : specs) {
|
||||
scenes.add(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()));
|
||||
}
|
||||
|
||||
if (skeleton.linkSequentially()) {
|
||||
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
||||
}
|
||||
|
||||
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList());
|
||||
}
|
||||
|
||||
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()))
|
||||
.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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -156,6 +161,18 @@ public class QuestService {
|
||||
/**
|
||||
* Supprime la quête et, en cascade, ses {@code QuestProgression} dans toutes les Parties.
|
||||
*
|
||||
* <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
|
||||
@@ -167,28 +184,47 @@ 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();
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
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.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.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.ArrayList;
|
||||
import java.util.Comparator;
|
||||
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 chemins menant à une révélation (en deçà : un seul chemin). */
|
||||
static final int REVELATION_MIN_INCOMING = 2;
|
||||
/** 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;
|
||||
|
||||
public WritingReviewService(CampaignRepository campaignRepository,
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
QuestRepository questRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.questRepository = questRepository;
|
||||
}
|
||||
|
||||
/** 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-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);
|
||||
}
|
||||
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);
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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;
|
||||
long incoming = chapterScenes.stream()
|
||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||
.flatMap(s -> s.getBranches().stream().map(SceneBranch::targetSceneId).distinct())
|
||||
.filter(scene.getId()::equals)
|
||||
.count();
|
||||
if (incoming < REVELATION_MIN_INCOMING) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||
Map.of("incoming", String.valueOf(incoming))));
|
||||
}
|
||||
}
|
||||
|
||||
/** 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())) {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers ----------------------------------------------------------------------------
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.loremind.domain.campaigncontext.writingreview;
|
||||
|
||||
/**
|
||||
* Famille d'une remarque de relecture (Mentor d'écriture, phase M2). Sert à
|
||||
* regrouper les conseils côté front ; n'implique aucune gravité : une remarque de
|
||||
* relecture est un conseil d'auteur, jamais un blocage.
|
||||
*/
|
||||
public enum WritingRemarkCategory {
|
||||
/** Pouvoir des joueurs : vrais choix, chemins multiples, issues alternatives. */
|
||||
AGENCY,
|
||||
/** Rythme : variété des scènes, lisibilité de la structure. */
|
||||
PACING,
|
||||
/** Enjeux : ce que les joueurs risquent, pourquoi l'adversité agit. */
|
||||
STAKES,
|
||||
/** Narration : textes lus aux joueurs. */
|
||||
NARRATION
|
||||
}
|
||||
+31
-1
@@ -3,6 +3,9 @@ package com.loremind.infrastructure.transfer.foundry;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Room;
|
||||
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||
@@ -40,6 +43,7 @@ public class FoundryExportService {
|
||||
private final CampaignJpaRepository campaignRepo;
|
||||
private final ArcJpaRepository arcRepo;
|
||||
private final ChapterJpaRepository chapterRepo;
|
||||
private final QuestJpaRepository questRepo;
|
||||
private final SceneJpaRepository sceneRepo;
|
||||
private final NpcJpaRepository npcRepo;
|
||||
private final EnemyJpaRepository enemyRepo;
|
||||
@@ -55,6 +59,7 @@ public class FoundryExportService {
|
||||
public FoundryExportService(CampaignJpaRepository campaignRepo,
|
||||
ArcJpaRepository arcRepo,
|
||||
ChapterJpaRepository chapterRepo,
|
||||
QuestJpaRepository questRepo,
|
||||
SceneJpaRepository sceneRepo,
|
||||
NpcJpaRepository npcRepo,
|
||||
EnemyJpaRepository enemyRepo,
|
||||
@@ -69,6 +74,7 @@ public class FoundryExportService {
|
||||
this.campaignRepo = campaignRepo;
|
||||
this.arcRepo = arcRepo;
|
||||
this.chapterRepo = chapterRepo;
|
||||
this.questRepo = questRepo;
|
||||
this.sceneRepo = sceneRepo;
|
||||
this.npcRepo = npcRepo;
|
||||
this.enemyRepo = enemyRepo;
|
||||
@@ -154,7 +160,20 @@ public class FoundryExportService {
|
||||
List<FoundryBundle.Quest> quests = new ArrayList<>();
|
||||
List<FoundryBundle.Scene> scenes = new ArrayList<>();
|
||||
|
||||
Set<String> liveContainerIds = liveQuestContainerIds(campaign);
|
||||
for (ArcJpaEntity arc : sortByOrder(arcRepo.findByCampaignId(campaign.getId()), ArcJpaEntity::getOrder)) {
|
||||
List<ChapterJpaEntity> chapters = sortByOrder(chapterRepo.findByArcId(arc.getId()), ChapterJpaEntity::getOrder);
|
||||
// L'arc technique SYSTEM (« Quetes libres ») est masque dans l'appli : seuls
|
||||
// les conteneurs des quetes VIVANTES partent dans l'export. Un conteneur
|
||||
// orphelin (quete supprimee, chapitre garde par deleteQuest car il contenait
|
||||
// des scenes) est invisible cote LoreMind -> il ne doit pas reapparaitre
|
||||
// cote Foundry. Arc omis entierement s'il ne reste rien.
|
||||
if (arc.getType() == ArcType.SYSTEM) {
|
||||
chapters = chapters.stream()
|
||||
.filter(ch -> liveContainerIds.contains(str(ch.getId())))
|
||||
.toList();
|
||||
if (chapters.isEmpty()) continue;
|
||||
}
|
||||
// Sans journaux, arcs/quetes ne servent que d'ossature (dossiers des Scenes) :
|
||||
// leurs illustrations ne sont pas embarquees.
|
||||
arcs.add(new FoundryBundle.Arc(
|
||||
@@ -163,7 +182,7 @@ public class FoundryExportService {
|
||||
arc.getThemes(), arc.getStakes(), arc.getGmNotes(), arc.getRewards(), arc.getResolution(),
|
||||
opts.journals() ? assets.images(arc.getIllustrationImageIds()) : List.of()));
|
||||
|
||||
for (ChapterJpaEntity ch : sortByOrder(chapterRepo.findByArcId(arc.getId()), ChapterJpaEntity::getOrder)) {
|
||||
for (ChapterJpaEntity ch : chapters) {
|
||||
quests.add(new FoundryBundle.Quest(
|
||||
str(ch.getId()), str(arc.getId()), ch.getName(), ch.getDescription(), ch.getOrder(),
|
||||
ch.getIcon(), ch.getPlayerObjectives(), ch.getNarrativeStakes(), ch.getGmNotes(),
|
||||
@@ -177,6 +196,17 @@ public class FoundryExportService {
|
||||
return new ArcsQuestsScenes(arcs, quests, scenes);
|
||||
}
|
||||
|
||||
/** Ids des chapitres-conteneurs references par les quetes vivantes de la campagne. */
|
||||
private Set<String> liveQuestContainerIds(CampaignJpaEntity campaign) {
|
||||
Set<String> ids = new HashSet<>();
|
||||
for (QuestJpaEntity q : questRepo.findByCampaignId(campaign.getId())) {
|
||||
for (QuestNodeRef n : q.getNodes() != null ? q.getNodes() : List.<QuestNodeRef>of()) {
|
||||
if (n.nodeType() == NodeType.CHAPTER) ids.add(n.nodeId());
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** PNJ : purement journal — hors perimetre sans les journaux. */
|
||||
private List<FoundryBundle.Persona> buildNpcs(CampaignJpaEntity campaign, ExportOptions opts,
|
||||
List<TemplateField> npcTemplate, AssetRegistry assets) {
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.GuidedSkeleton;
|
||||
import com.loremind.application.campaigncontext.GuidedSkeletonService;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Controller des méthodes guidées (Mentor d'écriture, phase M3) : persiste le
|
||||
* squelette (arc → chapitre → scènes) construit question par question par le MJ.
|
||||
*
|
||||
* <p>201 + ids créés ; 400 si le squelette est invalide ({@code GlobalExceptionHandler}) ;
|
||||
* 404 si la campagne est inconnue.</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/guided-skeleton")
|
||||
public class GuidedSkeletonController {
|
||||
|
||||
private final GuidedSkeletonService guidedSkeletonService;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public GuidedSkeletonController(GuidedSkeletonService guidedSkeletonService,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.guidedSkeletonService = guidedSkeletonService;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<GuidedSkeleton.Result> create(@PathVariable String campaignId,
|
||||
@RequestBody GuidedSkeleton skeleton) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
// Squelette invalide : IllegalArgumentException → 400 via GlobalExceptionHandler.
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(guidedSkeletonService.create(campaignId, skeleton));
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,16 @@ public class QuestController {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/** Impact d'une suppression : scènes du conteneur (quête libre) qui partiront avec. */
|
||||
@GetMapping("/{questId}/deletion-impact")
|
||||
public ResponseEntity<QuestService.DeletionImpact> getDeletionImpact(@PathVariable String campaignId,
|
||||
@PathVariable String questId) {
|
||||
if (questService.getQuestById(questId).isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(questService.getDeletionImpact(questId));
|
||||
}
|
||||
|
||||
/** Réordonne les quêtes de la campagne : order = position. */
|
||||
@PutMapping("/reorder")
|
||||
public ResponseEntity<Void> reorder(@PathVariable String campaignId, @RequestBody ReorderRequest req) {
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.WritingReviewReport;
|
||||
import com.loremind.application.campaigncontext.WritingReviewService;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Controller de la relecture d'éditeur (Mentor d'écriture, phase M2) : conseils
|
||||
* d'auteur sur la qualité de l'écriture d'une campagne.
|
||||
*
|
||||
* <p>Read-model pur, toujours 200 quand la campagne existe (les remarques conseillent,
|
||||
* elles ne bloquent rien). 404 si la campagne est inconnue.</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/writing-review")
|
||||
public class WritingReviewController {
|
||||
|
||||
private final WritingReviewService writingReviewService;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public WritingReviewController(WritingReviewService writingReviewService,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.writingReviewService = writingReviewService;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<WritingReviewReport> getWritingReview(@PathVariable String campaignId) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(writingReviewService.review(campaignId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package db.migration;
|
||||
|
||||
import org.flywaydb.core.api.migration.BaseJavaMigration;
|
||||
import org.flywaydb.core.api.migration.Context;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Nettoyage des CONTENEURS ORPHELINS des quêtes libres (arc technique SYSTEM).
|
||||
*
|
||||
* <p>Jusqu'à la 1.0.2, supprimer une quête libre GARDAIT son chapitre-conteneur
|
||||
* s'il contenait des scènes (garde anti-perte de contenu) — mais l'arc SYSTEM
|
||||
* étant masqué partout dans l'appli, ce contenu devenait INVISIBLE et
|
||||
* irrécupérable, tout en ressortant dans l'export Foundry (« quêtes fantômes »).
|
||||
* {@code QuestService.deleteQuest} cascade désormais ces conteneurs ; cette
|
||||
* migration répare l'existant SANS perte :</p>
|
||||
* <ul>
|
||||
* <li>conteneur orphelin AVEC scènes → une quête libre est RECRÉÉE dessus (même
|
||||
* nom que le chapitre) : le contenu redevient visible sous « Quêtes », et
|
||||
* l'utilisateur le garde ou le supprime via le flux normal (qui annonce
|
||||
* l'impact) ;</li>
|
||||
* <li>conteneur orphelin VIDE → supprimé (fantôme sans contenu).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>« Orphelin » = chapitre d'un arc SYSTEM dont l'id n'apparaît dans les
|
||||
* {@code nodes} d'AUCUNE quête de la campagne. Détection prudente par motif
|
||||
* {@code "nodeId":"<id>"} : une collision d'id avec un nœud SCENE fait considérer
|
||||
* le chapitre comme référencé → il est laissé en place (aucun risque de perte).</p>
|
||||
*
|
||||
* <p>Migration en Java (et non SQL) : la corrélation chapitre ↔ nodes JSON des
|
||||
* quêtes demande une itération par candidat, illisible en SQL portable H2/PG.</p>
|
||||
*/
|
||||
@SuppressWarnings("java:S101") // Nommage V24__... IMPOSE par la convention Flyway des migrations Java.
|
||||
public class V24__Reattach_orphan_free_quest_containers extends BaseJavaMigration {
|
||||
|
||||
private record Candidate(long chapterId, String name, long campaignId) {}
|
||||
|
||||
@Override
|
||||
public void migrate(Context context) throws Exception {
|
||||
Connection conn = context.getConnection();
|
||||
|
||||
List<Candidate> candidates = new ArrayList<>();
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT c.id, c.name, a.campaign_id FROM chapters c "
|
||||
+ "JOIN arcs a ON c.arc_id = a.id WHERE a.type = 'SYSTEM'");
|
||||
ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
candidates.add(new Candidate(rs.getLong(1), rs.getString(2), rs.getLong(3)));
|
||||
}
|
||||
}
|
||||
|
||||
for (Candidate ch : candidates) {
|
||||
if (isReferencedByAQuest(conn, ch)) continue; // conteneur d'une quête vivante
|
||||
if (countScenes(conn, ch.chapterId()) == 0) {
|
||||
deleteEmptyChapter(conn, ch.chapterId());
|
||||
} else {
|
||||
recreateFreeQuest(conn, ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isReferencedByAQuest(Connection conn, Candidate ch) throws Exception {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT COUNT(*) FROM quests WHERE campaign_id = ? AND nodes LIKE ?")) {
|
||||
ps.setLong(1, ch.campaignId());
|
||||
ps.setString(2, "%\"nodeId\":\"" + ch.chapterId() + "\"%");
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
return rs.getLong(1) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int countScenes(Connection conn, long chapterId) throws Exception {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT COUNT(*) FROM scenes WHERE chapter_id = ?")) {
|
||||
ps.setLong(1, chapterId);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
return rs.getInt(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteEmptyChapter(Connection conn, long chapterId) throws Exception {
|
||||
try (PreparedStatement ps = conn.prepareStatement("DELETE FROM chapters WHERE id = ?")) {
|
||||
ps.setLong(1, chapterId);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/** Recrée une quête LIBRE (arc_id NULL) pointant le conteneur, à la suite de l'ordre. */
|
||||
private void recreateFreeQuest(Connection conn, Candidate ch) throws Exception {
|
||||
int order;
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT COALESCE(MAX(\"order\"), -1) + 1 FROM quests WHERE campaign_id = ?")) {
|
||||
ps.setLong(1, ch.campaignId());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
order = rs.getInt(1);
|
||||
}
|
||||
}
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"INSERT INTO quests (campaign_id, \"order\", name, description, prerequisites, "
|
||||
+ "nodes, related_page_ids, illustration_image_ids, created_at, updated_at) "
|
||||
+ "VALUES (?, ?, ?, '', '[]', ?, '[]', '[]', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)")) {
|
||||
ps.setLong(1, ch.campaignId());
|
||||
ps.setInt(2, order);
|
||||
ps.setString(3, ch.name());
|
||||
ps.setString(4, "[{\"nodeType\":\"CHAPTER\",\"nodeId\":\"" + ch.chapterId() + "\",\"order\":0}]");
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
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.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire pour {@link GuidedSkeletonService} (Mentor d'écriture, phase M3) :
|
||||
* placement (nouvel arc / arc existant), champs reportés, chaînage des scènes, validations.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class GuidedSkeletonServiceTest {
|
||||
|
||||
private static final String CAMP = "camp";
|
||||
|
||||
@Mock private ArcRepository arcRepository;
|
||||
@Mock private ChapterRepository chapterRepository;
|
||||
@Mock private SceneRepository sceneRepository;
|
||||
@Mock private ArcService arcService;
|
||||
@Mock private ChapterService chapterService;
|
||||
@Mock private SceneService sceneService;
|
||||
|
||||
@InjectMocks private GuidedSkeletonService service;
|
||||
|
||||
private final List<Scene> createdScenes = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void stubCreations() {
|
||||
AtomicInteger ids = new AtomicInteger();
|
||||
when(arcService.createArc(any(Arc.class))).thenAnswer(inv -> {
|
||||
Arc a = inv.getArgument(0);
|
||||
a.setId("new-arc");
|
||||
return a;
|
||||
});
|
||||
when(chapterService.createChapter(any(Chapter.class))).thenAnswer(inv -> {
|
||||
Chapter c = inv.getArgument(0);
|
||||
c.setId("new-chap");
|
||||
return c;
|
||||
});
|
||||
when(sceneService.createScene(any(Scene.class))).thenAnswer(inv -> {
|
||||
Scene s = inv.getArgument(0);
|
||||
s.setId("scene-" + ids.incrementAndGet());
|
||||
createdScenes.add(s);
|
||||
return s;
|
||||
});
|
||||
}
|
||||
|
||||
private static GuidedSkeleton.SceneSpec room(String name, SceneType type) {
|
||||
return new GuidedSkeleton.SceneSpec(name, "Ce qui s'y passe", type, "La crypte",
|
||||
"Combattre ou négocier", "Le gardien protège son frère", null);
|
||||
}
|
||||
|
||||
private static GuidedSkeleton skeleton(String arcId, String newArcName, boolean link) {
|
||||
return new GuidedSkeleton(arcId, newArcName,
|
||||
new GuidedSkeleton.ChapterSpec("La crypte oubliée", "Une accroche", "Retrouver le reliquaire", "Le village sera maudit"),
|
||||
List.of(room("Salle 1", SceneType.ENCOUNTER), room("Salle 2", SceneType.LOCATION), room("Salle 3", SceneType.REVELATION)),
|
||||
link, "Vers la salle suivante");
|
||||
}
|
||||
|
||||
@Test
|
||||
void newArc_isLinear_andPlacedAfterVisibleArcs_beforeSystemArc() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("a1").type(ArcType.LINEAR).order(0).build(),
|
||||
Arc.builder().id("a2").type(ArcType.HUB).order(1).build(),
|
||||
Arc.builder().id("sys").type(ArcType.SYSTEM).order(9999).build()));
|
||||
|
||||
GuidedSkeleton.Result result = service.create(CAMP, skeleton(null, "Les terres brûlées", false));
|
||||
|
||||
ArgumentCaptor<Arc> arc = ArgumentCaptor.forClass(Arc.class);
|
||||
verify(arcService).createArc(arc.capture());
|
||||
assertEquals(ArcType.LINEAR, arc.getValue().getType());
|
||||
assertEquals(2, arc.getValue().getOrder());
|
||||
assertEquals(CAMP, arc.getValue().getCampaignId());
|
||||
assertEquals("new-arc", result.arcId());
|
||||
assertEquals("new-chap", result.chapterId());
|
||||
assertEquals(List.of("scene-1", "scene-2", "scene-3"), result.sceneIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingArc_chapterAppendedAfterExistingChapters_withItsFields() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("a1").type(ArcType.LINEAR).order(0).build()));
|
||||
when(chapterRepository.findByArcId("a1")).thenReturn(List.of(
|
||||
Chapter.builder().id("c1").arcId("a1").order(0).build(),
|
||||
Chapter.builder().id("c2").arcId("a1").order(3).build()));
|
||||
|
||||
service.create(CAMP, skeleton("a1", null, false));
|
||||
|
||||
verify(arcService, never()).createArc(any(Arc.class));
|
||||
ArgumentCaptor<Chapter> chapter = ArgumentCaptor.forClass(Chapter.class);
|
||||
verify(chapterService).createChapter(chapter.capture());
|
||||
assertEquals("a1", chapter.getValue().getArcId());
|
||||
assertEquals(4, chapter.getValue().getOrder());
|
||||
assertEquals("Retrouver le reliquaire", chapter.getValue().getPlayerObjectives());
|
||||
assertEquals("Le village sera maudit", chapter.getValue().getNarrativeStakes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scenes_keepOrderTypeAndFields() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
|
||||
service.create(CAMP, skeleton(null, "Arc", false));
|
||||
|
||||
assertEquals(3, createdScenes.size());
|
||||
Scene first = createdScenes.get(0);
|
||||
assertEquals(0, first.getOrder());
|
||||
assertEquals("new-chap", first.getChapterId());
|
||||
assertEquals(SceneType.ENCOUNTER, first.getType());
|
||||
assertEquals("La crypte", first.getLocation());
|
||||
assertEquals("Combattre ou négocier", first.getChoicesConsequences());
|
||||
assertEquals("Le gardien protège son frère", first.getGmSecretNotes());
|
||||
assertEquals(SceneType.REVELATION, createdScenes.get(2).getType());
|
||||
assertEquals(2, createdScenes.get(2).getOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkSequentially_chainsEachSceneToTheNext_lastHasNoExit() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
|
||||
service.create(CAMP, skeleton(null, "Arc", true));
|
||||
|
||||
verify(sceneRepository, times(2)).save(any(Scene.class));
|
||||
assertEquals("scene-2", createdScenes.get(0).getBranches().get(0).targetSceneId());
|
||||
assertEquals("Vers la salle suivante", createdScenes.get(0).getBranches().get(0).label());
|
||||
assertEquals("scene-3", createdScenes.get(1).getBranches().get(0).targetSceneId());
|
||||
assertTrue(createdScenes.get(2).getBranches() == null || createdScenes.get(2).getBranches().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unnamedScenes_areSkipped_andBlankFieldsStoredAsNull() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
GuidedSkeleton s = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Chap", " ", null, null),
|
||||
List.of(new GuidedSkeleton.SceneSpec("Salle", " ", null, "", null, null, null),
|
||||
new GuidedSkeleton.SceneSpec(" ", "ignorée", SceneType.EVENT, null, null, null, null)),
|
||||
false, null);
|
||||
|
||||
service.create(CAMP, s);
|
||||
|
||||
assertEquals(1, createdScenes.size());
|
||||
assertNull(createdScenes.get(0).getDescription());
|
||||
assertNull(createdScenes.get(0).getLocation());
|
||||
assertEquals(SceneType.GENERIC, createdScenes.get(0).getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_ambiguousPlacement() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("a1", "Arc", false)));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton(null, " ", false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_arcOfAnotherCampaign_orNonLinearArc() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("hub").type(ArcType.HUB).order(0).build()));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("ailleurs", null, false)));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("hub", null, false)));
|
||||
verify(chapterService, never()).createChapter(any(Chapter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_missingChapterName_orNoNamedScene() {
|
||||
GuidedSkeleton noChapterName = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec(" ", null, null, null), List.of(room("S", null)), false, null);
|
||||
GuidedSkeleton noScene = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Chap", null, null, null),
|
||||
List.of(new GuidedSkeleton.SceneSpec("", null, null, null, null, null, null)), false, null);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noChapterName));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noScene));
|
||||
}
|
||||
}
|
||||
@@ -230,13 +230,112 @@ class QuestServiceTest {
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-real").arcId("arc-lin").name("Réel").build()));
|
||||
when(arcRepository.findById("arc-lin"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-lin").type(ArcType.LINEAR).build()));
|
||||
when(sceneRepository.findByChapterId("chap-real")).thenReturn(List.of());
|
||||
// NB : pas de stub sceneRepository — un chapitre non-conteneur est écarté avant toute lecture des scènes.
|
||||
|
||||
service.deleteQuest("q-1");
|
||||
|
||||
verify(chapterRepository, never()).deleteById(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteQuest_freeQuest_cascadesScenesOfSystemContainer() {
|
||||
// Conteneur d'arc SYSTEM : INVISIBLE une fois la quête supprimée -> il part avec
|
||||
// ses scènes (sinon il pourrit en fantôme inaccessible qui ressort dans les exports).
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").name("Libre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of());
|
||||
when(chapterRepository.findById("chap-free"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-free").arcId("arc-sys").name("Libre").build()));
|
||||
when(arcRepository.findById("arc-sys"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-sys").type(ArcType.SYSTEM).build()));
|
||||
when(sceneRepository.findByChapterId("chap-free")).thenReturn(List.of(
|
||||
Scene.builder().id("s-1").chapterId("chap-free").name("S1").build(),
|
||||
Scene.builder().id("s-2").chapterId("chap-free").name("S2").build()));
|
||||
|
||||
service.deleteQuest("q-1");
|
||||
|
||||
verify(sceneRepository).deleteById("s-1");
|
||||
verify(sceneRepository).deleteById("s-2");
|
||||
verify(chapterRepository).deleteById("chap-free");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_freeQuestWithScenes_countsThem() {
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").name("Libre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(quest)); // filtrée par id
|
||||
when(chapterRepository.findById("chap-free"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-free").arcId("arc-sys").name("Libre").build()));
|
||||
when(arcRepository.findById("arc-sys"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-sys").type(ArcType.SYSTEM).build()));
|
||||
when(sceneRepository.findByChapterId("chap-free")).thenReturn(List.of(
|
||||
Scene.builder().id("s-1").chapterId("chap-free").name("S1").build(),
|
||||
Scene.builder().id("s-2").chapterId("chap-free").name("S2").build()));
|
||||
|
||||
assertEquals(2, service.getDeletionImpact("q-1").scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_unknownQuest_returnsZero() {
|
||||
when(questRepository.findById("inconnue")).thenReturn(Optional.empty());
|
||||
|
||||
assertEquals(0, service.getDeletionImpact("inconnue").scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_systemContainerReferencedByAnotherQuest_reportsZero() {
|
||||
// Conteneur PARTAGÉ (autre quête le référence) : il survivra -> impact 0.
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").name("Libre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
Quest other = Quest.builder().id("q-2").campaignId("camp").name("Autre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(quest, other));
|
||||
when(chapterRepository.findById("chap-free"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-free").arcId("arc-sys").name("Libre").build()));
|
||||
when(arcRepository.findById("arc-sys"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-sys").type(ArcType.SYSTEM).build()));
|
||||
|
||||
assertEquals(0, service.getDeletionImpact("q-1").scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteQuest_freeQuest_systemContainerReferencedElsewhere_keptWithScenes() {
|
||||
// Même partagé en arc SYSTEM, un conteneur encore référencé n'est JAMAIS cascadé.
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").name("Libre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
Quest other = Quest.builder().id("q-2").campaignId("camp").name("Autre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(other));
|
||||
when(chapterRepository.findById("chap-free"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-free").arcId("arc-sys").name("Libre").build()));
|
||||
when(arcRepository.findById("arc-sys"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-sys").type(ArcType.SYSTEM).build()));
|
||||
|
||||
service.deleteQuest("q-1");
|
||||
|
||||
verify(chapterRepository, never()).deleteById(anyString());
|
||||
verify(sceneRepository, never()).deleteById(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_hubQuest_reportsZero() {
|
||||
// Jumeau de hub : GARDÉ à la suppression (il reste visible dans l'arc) -> impact 0.
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").arcId("arc-h").name("Q")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-1", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(quest));
|
||||
when(chapterRepository.findById("chap-1"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-1").arcId("arc-h").name("Q").build()));
|
||||
when(arcRepository.findById("arc-h"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-h").type(ArcType.HUB).build()));
|
||||
|
||||
assertEquals(0, service.getDeletionImpact("q-1").scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteQuest_keepsContainerReferencedByAnotherQuest() {
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").arcId("arc-h").name("Q")
|
||||
@@ -247,7 +346,7 @@ class QuestServiceTest {
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(other));
|
||||
when(chapterRepository.findById("chap-1"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-1").arcId("arc-h").name("Q").build()));
|
||||
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of());
|
||||
// NB : pas de stub sceneRepository — un conteneur encore référencé est écarté avant toute lecture.
|
||||
|
||||
service.deleteQuest("q-1");
|
||||
|
||||
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
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.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.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire pour {@link WritingReviewService} (Mentor d'écriture, phase M2).
|
||||
* Chaque règle WRITE-xxx a son cas positif ET un cas qui ne doit PAS la déclencher
|
||||
* (le mentor doit rester sobre : un faux positif décourage le débutant).
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WritingReviewServiceTest {
|
||||
|
||||
private static final String CAMP = "camp";
|
||||
|
||||
@Mock private CampaignRepository campaignRepository;
|
||||
@Mock private ArcRepository arcRepository;
|
||||
@Mock private ChapterRepository chapterRepository;
|
||||
@Mock private SceneRepository sceneRepository;
|
||||
@Mock private QuestRepository questRepository;
|
||||
|
||||
@InjectMocks private WritingReviewService service;
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
private static Arc arc(String id, ArcType type) {
|
||||
return Arc.builder().id(id).name(id).campaignId(CAMP).type(type).order(0).stakes("Le village brûle").build();
|
||||
}
|
||||
|
||||
private static Chapter chapter(String id, String arcId) {
|
||||
return Chapter.builder().id(id).name(id).arcId(arcId).order(0).narrativeStakes("Un allié en danger").build();
|
||||
}
|
||||
|
||||
/** Scène « propre » : typée, avec un choix décrit (ne déclenche aucune règle seule). */
|
||||
private static Scene.SceneBuilder scene(String id, int order) {
|
||||
return Scene.builder().id(id).name(id).chapterId("chap").order(order)
|
||||
.type(SceneType.NPC).choicesConsequences("Convaincre ou menacer");
|
||||
}
|
||||
|
||||
private void tree(Arc arc, Chapter chapter, List<Scene> scenes) {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(arc));
|
||||
when(chapterRepository.findByArcId(arc.getId())).thenReturn(List.of(chapter));
|
||||
when(sceneRepository.findByChapterId(chapter.getId())).thenReturn(scenes);
|
||||
}
|
||||
|
||||
private void tree(List<Scene> scenes) {
|
||||
tree(arc("arc", ArcType.HUB), chapter("chap", "arc"), scenes);
|
||||
}
|
||||
|
||||
private Set<String> ruleIds() {
|
||||
return service.review(CAMP).remarks().stream().map(WritingRemark::ruleId).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private WritingRemark remark(String ruleId) {
|
||||
return service.review(CAMP).remarks().stream().filter(r -> r.ruleId().equals(ruleId))
|
||||
.findFirst().orElseThrow(() -> new AssertionError("Règle absente : " + ruleId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyCampaign_hasNoRemark() {
|
||||
assertTrue(service.review(CAMP).remarks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wellWrittenChapter_hasNoRemark() {
|
||||
tree(List.of(scene("s1", 0).build(), scene("s2", 1).type(SceneType.LOCATION).build()));
|
||||
assertTrue(service.review(CAMP).remarks().isEmpty());
|
||||
}
|
||||
|
||||
// --- WRITE-001 : couloir ---
|
||||
|
||||
@Test
|
||||
void corridor_threeScenesWithoutChoiceNorBranch() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).choicesConsequences(null).build(),
|
||||
scene("s2", 1).choicesConsequences(null).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).choicesConsequences(null).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-001-CORRIDOR");
|
||||
assertEquals(ReadinessEntityType.CHAPTER, r.entityType());
|
||||
assertEquals("3", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void corridor_notRaised_whenOneSceneOffersAChoice() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).choicesConsequences(null).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).choicesConsequences(null).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-001-CORRIDOR"));
|
||||
}
|
||||
|
||||
// --- WRITE-002 : faux carrefour ---
|
||||
|
||||
@Test
|
||||
void fakeChoice_allBranchesLeadToSameScene() {
|
||||
Scene target = scene("s2", 1).name("La crypte").type(SceneType.LOCATION).build();
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "s2"), SceneBranch.of("B", "s2"))).build(),
|
||||
target));
|
||||
|
||||
WritingRemark r = remark("WRITE-002-FAKE-CHOICE");
|
||||
assertEquals("s1", r.entityId());
|
||||
assertEquals("La crypte", r.params().get("target"));
|
||||
assertEquals("2", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fakeChoice_notRaised_whenBranchesDiverge() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "s2"), SceneBranch.of("B", "s3"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-002-FAKE-CHOICE"));
|
||||
}
|
||||
|
||||
// --- WRITE-003 : révélation à chemin unique ---
|
||||
|
||||
@Test
|
||||
void singleClue_revelationReachableByOnePath() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
||||
scene("rev", 1).type(SceneType.REVELATION).build()));
|
||||
|
||||
assertEquals("1", remark("WRITE-003-SINGLE-CLUE").params().get("incoming"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_withTwoPaths_orInChapterWithoutLinks() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).branches(List.of(SceneBranch.of("B", "rev"))).build(),
|
||||
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_inChapterWithoutAnyLink() {
|
||||
tree(List.of(scene("s1", 0).build(), scene("rev", 1).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
// --- WRITE-004 : rythme monotone ---
|
||||
|
||||
@Test
|
||||
void monotonousPacing_threeFightsInARow() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s2", 1).enemies("Deux gobelins").build(),
|
||||
scene("s3", 2).combatDifficulty("Difficile").build(),
|
||||
scene("s4", 3).type(SceneType.LOCATION).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-004-MONOTONOUS-PACING");
|
||||
assertEquals("COMBAT", r.params().get("kind"));
|
||||
assertEquals("3", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void monotonousPacing_notRaised_whenVaried_orUntyped() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s2", 1).type(SceneType.NPC).build(),
|
||||
scene("s3", 2).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s4", 3).type(SceneType.GENERIC).build(),
|
||||
scene("s5", 4).type(SceneType.GENERIC).build(),
|
||||
scene("s6", 5).type(SceneType.GENERIC).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-004-MONOTONOUS-PACING"));
|
||||
}
|
||||
|
||||
// --- WRITE-005 : sans enjeu ---
|
||||
|
||||
@Test
|
||||
void noStakes_onChapterAndArc() {
|
||||
Arc a = Arc.builder().id("arc").name("Arc").campaignId(CAMP).type(ArcType.LINEAR).order(0).build();
|
||||
Chapter c = Chapter.builder().id("chap").name("Chap").arcId("arc").order(0).build();
|
||||
tree(a, c, List.of(scene("s1", 0).branches(List.of(SceneBranch.of("A", "s1"))).build()));
|
||||
|
||||
List<WritingRemark> remarks = service.review(CAMP).remarks().stream()
|
||||
.filter(r -> r.ruleId().equals("WRITE-005-NO-STAKES")).toList();
|
||||
assertEquals(Set.of(ReadinessEntityType.ARC, ReadinessEntityType.CHAPTER),
|
||||
remarks.stream().map(WritingRemark::entityType).collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noStakes_notRaised_onEmptyArc_norOnSystemArc() {
|
||||
Arc empty = Arc.builder().id("empty").name("Vide").campaignId(CAMP).type(ArcType.LINEAR).order(0).build();
|
||||
Arc system = Arc.builder().id("sys").name("Quêtes libres").campaignId(CAMP).type(ArcType.SYSTEM).order(9999).build();
|
||||
Chapter container = Chapter.builder().id("box").name("Q").arcId("sys").order(0).build();
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(empty, system));
|
||||
when(chapterRepository.findByArcId("empty")).thenReturn(List.of());
|
||||
when(chapterRepository.findByArcId("sys")).thenReturn(List.of(container));
|
||||
when(sceneRepository.findByChapterId("box")).thenReturn(List.of(scene("s1", 0).build()));
|
||||
|
||||
assertFalse(ruleIds().contains("WRITE-005-NO-STAKES"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noStakes_raisedOnHubArcCarriedByQuests() {
|
||||
Arc hub = Arc.builder().id("hub").name("Hub").campaignId(CAMP).type(ArcType.HUB).order(0).build();
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(hub));
|
||||
when(questRepository.findByCampaignId(CAMP))
|
||||
.thenReturn(List.of(Quest.builder().id("q").campaignId(CAMP).arcId("hub").build()));
|
||||
|
||||
assertEquals(ReadinessEntityType.ARC, remark("WRITE-005-NO-STAKES").entityType());
|
||||
}
|
||||
|
||||
// --- WRITE-006 / WRITE-007 : narration ---
|
||||
|
||||
@Test
|
||||
void longNarration_overThreshold() {
|
||||
String text = "a".repeat(WritingReviewService.LONG_NARRATION_CHARS + 1);
|
||||
tree(List.of(scene("s1", 0).playerNarration(text).build()));
|
||||
|
||||
assertEquals(String.valueOf(text.length()), remark("WRITE-006-LONG-NARRATION").params().get("chars"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narrationDecides_capturesThePhrase_inFrenchAndEnglish() {
|
||||
tree(List.of(scene("s1", 0).playerNarration("La porte grince. Vous avez peur et reculez.").build()));
|
||||
assertEquals("Vous avez peur", remark("WRITE-007-NARRATION-DECIDES").params().get("phrase"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narrationDecides_english() {
|
||||
tree(List.of(scene("s1", 0).playerNarration("The door creaks open. You enter the hall.").build()));
|
||||
assertEquals("You enter", remark("WRITE-007-NARRATION-DECIDES").params().get("phrase"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narration_notRaised_whenDescriptiveAndShort() {
|
||||
tree(List.of(scene("s1", 0)
|
||||
.playerNarration("La porte grince. Une odeur de cire flotte dans l'air. Que faites-vous ?").build()));
|
||||
Set<String> ids = ruleIds();
|
||||
assertFalse(ids.contains("WRITE-006-LONG-NARRATION"));
|
||||
assertFalse(ids.contains("WRITE-007-NARRATION-DECIDES"));
|
||||
}
|
||||
|
||||
// --- WRITE-008 : combat sans but ---
|
||||
|
||||
@Test
|
||||
void combatWithoutPurpose() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.ENCOUNTER).choicesConsequences(null).build()));
|
||||
assertEquals("s1", remark("WRITE-008-COMBAT-NO-PURPOSE").entityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void combatWithoutPurpose_notRaised_whenGmNotesExplainMotives() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.ENCOUNTER).choicesConsequences(null)
|
||||
.gmSecretNotes("Ils veulent couler la barque").build()));
|
||||
assertFalse(ruleIds().contains("WRITE-008-COMBAT-NO-PURPOSE"));
|
||||
}
|
||||
|
||||
// --- WRITE-009 : fin unique ---
|
||||
|
||||
@Test
|
||||
void singleEnding_onLastSceneOfLinearArc() {
|
||||
tree(arc("arc", ArcType.LINEAR), chapter("chap", "arc"), List.of(
|
||||
scene("s1", 0).build(),
|
||||
scene("final", 1).type(SceneType.LOCATION).choicesConsequences(null).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-009-SINGLE-ENDING");
|
||||
assertEquals("final", r.entityId());
|
||||
assertEquals("arc", r.params().get("arc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleEnding_notRaised_onHubArc_orWhenFinaleHasChoices() {
|
||||
tree(arc("arc", ArcType.HUB), chapter("chap", "arc"),
|
||||
List.of(scene("final", 0).choicesConsequences(null).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-009-SINGLE-ENDING"));
|
||||
}
|
||||
|
||||
// --- WRITE-010 : scènes non typées ---
|
||||
|
||||
@Test
|
||||
void untypedScenes_whenMostScenesAreGeneric() {
|
||||
List<Scene> scenes = new ArrayList<>(IntStream.range(0, 5)
|
||||
.mapToObj(i -> scene("s" + i, i).type(SceneType.GENERIC).build()).toList());
|
||||
tree(scenes);
|
||||
when(campaignRepository.findById(CAMP))
|
||||
.thenReturn(Optional.of(Campaign.builder().id(CAMP).name("Ma campagne").build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-010-UNTYPED-SCENES");
|
||||
assertEquals(ReadinessEntityType.CAMPAIGN, r.entityType());
|
||||
assertEquals("100", r.params().get("percent"));
|
||||
// Remarque de campagne en tête de liste.
|
||||
assertEquals("WRITE-010-UNTYPED-SCENES", service.review(CAMP).remarks().get(0).ruleId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void untypedScenes_notRaised_belowMinimumSceneCount() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.GENERIC).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-010-UNTYPED-SCENES"));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -119,4 +121,77 @@ class FlywayMigrationTest {
|
||||
assertEquals("[]", rs.getString(2));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* V24 : les conteneurs ORPHELINS de l'arc SYSTEM (quête libre supprimée avant que
|
||||
* la suppression ne cascade) sont réparés — rattachés à une quête recréée s'ils
|
||||
* ont des scènes (contenu redevenu visible), supprimés s'ils sont vides. Le
|
||||
* conteneur d'une quête vivante n'est pas touché.
|
||||
*/
|
||||
@Test
|
||||
void v24_reattachesOrphanSystemContainers_andDropsEmptyOnes() throws SQLException {
|
||||
String url = "jdbc:h2:mem:flyway_v24_test;MODE=PostgreSQL;NON_KEYWORDS=VALUE;DB_CLOSE_DELAY=-1";
|
||||
|
||||
// 1) Schéma arrêté AVANT V24…
|
||||
Flyway.configure()
|
||||
.dataSource(url, "sa", "")
|
||||
.locations("classpath:db/migration")
|
||||
.target(MigrationVersion.fromVersion("23"))
|
||||
.load()
|
||||
.migrate();
|
||||
|
||||
// 2) …peuplé : un arc SYSTEM avec un orphelin PLEIN (1 scène), un orphelin
|
||||
// VIDE, et le conteneur d'une quête VIVANTE.
|
||||
try (Connection conn = DriverManager.getConnection(url, "sa", "");
|
||||
Statement st = conn.createStatement()) {
|
||||
st.executeUpdate("insert into campaigns (id, name, arcs_count, created_at, updated_at) "
|
||||
+ "values (1, 'C', 0, now(), now())");
|
||||
st.executeUpdate("insert into arcs (id, name, campaign_id, \"order\", type, created_at, updated_at) "
|
||||
+ "values (9, 'Quêtes libres', 1, 9999, 'SYSTEM', now(), now())");
|
||||
st.executeUpdate("insert into chapters (id, name, arc_id, \"order\", created_at, updated_at) "
|
||||
+ "values (41, 'Orphelin plein', 9, 0, now(), now())");
|
||||
st.executeUpdate("insert into chapters (id, name, arc_id, \"order\", created_at, updated_at) "
|
||||
+ "values (42, 'Orphelin vide', 9, 1, now(), now())");
|
||||
st.executeUpdate("insert into chapters (id, name, arc_id, \"order\", created_at, updated_at) "
|
||||
+ "values (43, 'Vivant', 9, 2, now(), now())");
|
||||
st.executeUpdate("insert into scenes (id, name, chapter_id, \"order\", created_at, updated_at) "
|
||||
+ "values (1, 'S', 41, 0, now(), now())");
|
||||
st.executeUpdate("insert into quests (campaign_id, \"order\", name, nodes, created_at, updated_at) "
|
||||
+ "values (1, 0, 'Vivant', '[{\"nodeType\":\"CHAPTER\",\"nodeId\":\"43\",\"order\":0}]', now(), now())");
|
||||
}
|
||||
|
||||
// 3) Fin de la chaîne : V24 répare.
|
||||
Flyway.configure()
|
||||
.dataSource(url, "sa", "")
|
||||
.locations("classpath:db/migration")
|
||||
.load()
|
||||
.migrate();
|
||||
|
||||
try (Connection conn = DriverManager.getConnection(url, "sa", "");
|
||||
Statement st = conn.createStatement()) {
|
||||
|
||||
// L'orphelin PLEIN est rattaché : quête LIBRE (arc_id NULL) recréée dessus.
|
||||
try (ResultSet rs = st.executeQuery(
|
||||
"select arc_id, nodes from quests where name = 'Orphelin plein'")) {
|
||||
assertTrue(rs.next(), "une quête aurait dû être recréée sur le conteneur orphelin");
|
||||
assertNull(rs.getObject(1));
|
||||
assertEquals("[{\"nodeType\":\"CHAPTER\",\"nodeId\":\"41\",\"order\":0}]", rs.getString(2));
|
||||
}
|
||||
|
||||
// L'orphelin VIDE a disparu ; l'orphelin plein et le conteneur vivant restent.
|
||||
try (ResultSet rs = st.executeQuery("select id from chapters where arc_id = 9 order by id")) {
|
||||
assertTrue(rs.next());
|
||||
assertEquals(41, rs.getInt(1));
|
||||
assertTrue(rs.next());
|
||||
assertEquals(43, rs.getInt(1));
|
||||
assertFalse(rs.next(), "l'orphelin vide (42) aurait dû être supprimé");
|
||||
}
|
||||
|
||||
// Pas de doublon : la quête vivante n'a pas été re-rattachée.
|
||||
try (ResultSet rs = st.executeQuery("select count(*) from quests")) {
|
||||
rs.next();
|
||||
assertEquals(2, rs.getInt(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+60
@@ -1,5 +1,8 @@
|
||||
package com.loremind.infrastructure.transfer.foundry;
|
||||
|
||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.persistence.entity.*;
|
||||
@@ -30,6 +33,7 @@ class FoundryExportServiceTest {
|
||||
@Autowired private CampaignJpaRepository campaignRepo;
|
||||
@Autowired private ArcJpaRepository arcRepo;
|
||||
@Autowired private ChapterJpaRepository chapterRepo;
|
||||
@Autowired private QuestJpaRepository questRepo;
|
||||
@Autowired private SceneJpaRepository sceneRepo;
|
||||
@Autowired private NpcJpaRepository npcRepo;
|
||||
@Autowired private GameSystemJpaRepository gameSystemRepo;
|
||||
@@ -251,4 +255,60 @@ class FoundryExportServiceTest {
|
||||
assertThrows(java.util.NoSuchElementException.class,
|
||||
() -> service.buildBundle("999999999", "2026-06-25T00:00:00Z"));
|
||||
}
|
||||
|
||||
/**
|
||||
* L'arc technique SYSTEM heberge les conteneurs des quetes libres. Un conteneur
|
||||
* ORPHELIN (quete supprimee, chapitre garde par deleteQuest car il contenait des
|
||||
* scenes) est invisible dans l'appli : il ne doit pas partir dans le bundle.
|
||||
*/
|
||||
@Test
|
||||
void buildBundle_systemArc_exportsOnlyLiveQuestContainers() {
|
||||
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder()
|
||||
.name("Quetes libres").description("d").arcsCount(1).build());
|
||||
ArcJpaEntity system = arcRepo.save(ArcJpaEntity.builder()
|
||||
.campaignId(camp.getId()).name("Quêtes libres").order(9999)
|
||||
.type(ArcType.SYSTEM).build());
|
||||
ChapterJpaEntity live = chapterRepo.save(ChapterJpaEntity.builder()
|
||||
.arcId(system.getId()).name("Quete vivante").order(0).build());
|
||||
ChapterJpaEntity orphan = chapterRepo.save(ChapterJpaEntity.builder()
|
||||
.arcId(system.getId()).name("test de quete").order(1).build());
|
||||
sceneRepo.save(SceneJpaEntity.builder()
|
||||
.chapterId(live.getId()).name("Scene vivante").order(0).build());
|
||||
sceneRepo.save(SceneJpaEntity.builder()
|
||||
.chapterId(orphan.getId()).name("Scene fantome").order(0).build());
|
||||
questRepo.save(QuestJpaEntity.builder()
|
||||
.campaignId(camp.getId()).name("Quete vivante").order(0)
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, String.valueOf(live.getId()), 0)))
|
||||
.build());
|
||||
|
||||
FoundryBundle.Data data = service.buildBundle(
|
||||
String.valueOf(camp.getId()), "2026-07-09T00:00:00Z").data();
|
||||
|
||||
assertEquals(1, data.arcs().size());
|
||||
assertEquals(1, data.quests().size());
|
||||
assertEquals("Quete vivante", data.quests().get(0).name());
|
||||
assertEquals(1, data.scenes().size());
|
||||
assertEquals("Scene vivante", data.scenes().get(0).name());
|
||||
}
|
||||
|
||||
/** Sans quete vivante, l'arc SYSTEM disparait entierement du bundle. */
|
||||
@Test
|
||||
void buildBundle_systemArcWithoutLiveQuest_isDroppedEntirely() {
|
||||
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder()
|
||||
.name("Fantomes").description("d").arcsCount(1).build());
|
||||
ArcJpaEntity system = arcRepo.save(ArcJpaEntity.builder()
|
||||
.campaignId(camp.getId()).name("Quêtes libres").order(9999)
|
||||
.type(ArcType.SYSTEM).build());
|
||||
ChapterJpaEntity orphan = chapterRepo.save(ChapterJpaEntity.builder()
|
||||
.arcId(system.getId()).name("test").order(0).build());
|
||||
sceneRepo.save(SceneJpaEntity.builder()
|
||||
.chapterId(orphan.getId()).name("test").order(0).build());
|
||||
|
||||
FoundryBundle.Data data = service.buildBundle(
|
||||
String.valueOf(camp.getId()), "2026-07-09T00:00:00Z").data();
|
||||
|
||||
assertTrue(data.arcs().isEmpty());
|
||||
assertTrue(data.quests().isEmpty());
|
||||
assertTrue(data.scenes().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
+25
-2
@@ -18,7 +18,9 @@
|
||||
Le code source de ce script est public et auditable a l'adresse indiquee dans .LINK.
|
||||
|
||||
.PARAMETER InstallDir
|
||||
Dossier d'installation. Defaut : %LOCALAPPDATA%\DM Loremind
|
||||
Dossier d'installation. Defaut : %LOCALAPPDATA%\DM Loremind Docker
|
||||
(PAS "%LOCALAPPDATA%\DM Loremind" : ce dossier est celui de l'application
|
||||
bureau .msi — les deux produits ne doivent jamais partager un dossier).
|
||||
|
||||
.PARAMETER ComposeUrl
|
||||
URL du fichier docker-compose.yml a recuperer. Defaut : version officielle du depot.
|
||||
@@ -48,7 +50,7 @@
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$InstallDir = "$env:LOCALAPPDATA\DM Loremind",
|
||||
[string]$InstallDir = "$env:LOCALAPPDATA\DM Loremind Docker",
|
||||
[string]$ComposeUrl = "https://raw.githubusercontent.com/IGMLcreation/LoreMind/main/docker-compose.yml",
|
||||
[int]$WebPort = 8081,
|
||||
[switch]$NonInteractive
|
||||
@@ -204,6 +206,27 @@ if (Test-Docker) {
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Dossier d'installation + docker-compose.yml
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compat : les stacks historiques vivaient dans "%LOCALAPPDATA%\DM Loremind",
|
||||
# desormais reserve a l'application bureau (.msi jpackage, meme nom produit —
|
||||
# une maj du .msi pouvait ecraser compose/.env). Si un stack y est deja
|
||||
# installe (compose present, pas d'exe bureau), on le reutilise plutot que
|
||||
# d'en creer un second qui entrerait en conflit (memes noms de conteneurs).
|
||||
$legacyDir = "$env:LOCALAPPDATA\DM Loremind"
|
||||
if ($InstallDir -eq "$env:LOCALAPPDATA\DM Loremind Docker" -and
|
||||
(Test-Path (Join-Path $legacyDir 'docker-compose.yml')) -and
|
||||
-not (Test-Path (Join-Path $legacyDir 'DM Loremind.exe'))) {
|
||||
Write-Warn2 "Stack Docker existant detecte dans $legacyDir - reutilise (pas de duplication)."
|
||||
$InstallDir = $legacyDir
|
||||
}
|
||||
|
||||
# Garde-fou : jamais d'installation du stack Docker dans le dossier de
|
||||
# l'application bureau (le .msi et le stack s'ecraseraient mutuellement).
|
||||
if (Test-Path (Join-Path $InstallDir 'DM Loremind.exe')) {
|
||||
Write-Err "Le dossier $InstallDir contient l'application bureau DM Loremind (.msi)."
|
||||
Write-Err "La version Docker doit vivre ailleurs : relancez avec -InstallDir <autre dossier>."
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Step "Preparation du dossier $InstallDir"
|
||||
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
|
||||
Set-Location $InstallDir
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ruleset xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
name="LoreMind"
|
||||
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
||||
|
||||
<description>
|
||||
Ruleset PMD LoreMind — détecté automatiquement par MegaLinter (JAVA_PMD).
|
||||
Philosophie : bugs et pièges réels uniquement. Les catégories de STYLE
|
||||
(codestyle/design/documentation) sont exclues : le défaut MegaLinter y
|
||||
générait ~11 000 violations hors sujet (conventions incompatibles avec
|
||||
l'idiome Lombok/slf4j/Spring du projet : champ `log`, DI constructeur…).
|
||||
</description>
|
||||
|
||||
<!-- Bugs probables : null, equals/hashCode, ressources, casts douteux… -->
|
||||
<rule ref="category/java/errorprone.xml">
|
||||
<!-- Chaque littéral dupliqué = une violation : du bruit, pas un bug. -->
|
||||
<exclude name="AvoidDuplicateLiterals"/>
|
||||
<exclude name="AvoidLiteralsInIfCondition"/>
|
||||
<!-- Entités JPA/DTO : pas de sérialisation Java native ici. -->
|
||||
<exclude name="MissingSerialVersionUID"/>
|
||||
<!-- `this.name = name` en DI/setters : idiome standard. -->
|
||||
<exclude name="AvoidFieldNameMatchingMethodName"/>
|
||||
<exclude name="AvoidFieldNameMatchingTypeName"/>
|
||||
<!-- `while ((x = read()) != null)` : idiome de lecture standard. -->
|
||||
<exclude name="AssignmentInOperand"/>
|
||||
<!-- catch(Exception) best-effort : choix assumé du projet (imports,
|
||||
exports, best-effort serveur) — pas un gate. -->
|
||||
<exclude name="AvoidCatchingGenericException"/>
|
||||
<!-- TODO backlog : réactiver et passer les toLowerCase/UpperCase en
|
||||
Locale.ROOT (27 sites) — bug potentiel (locale turque) mais
|
||||
changement de comportement à valider posément. -->
|
||||
<exclude name="UseLocaleWithCaseConversions"/>
|
||||
</rule>
|
||||
|
||||
<!-- Concurrence -->
|
||||
<rule ref="category/java/multithreading.xml">
|
||||
<!-- Règle d'époque J2EE : les threads sont légitimes (sidecar, SSE…). -->
|
||||
<exclude name="DoNotUseThreads"/>
|
||||
<!-- Flaguerait CHAQUE HashMap, y compris locales à une méthode (×135). -->
|
||||
<exclude name="UseConcurrentHashMap"/>
|
||||
</rule>
|
||||
|
||||
<!-- Performance (sans les micro-optimisations StringBuilder : le rendu
|
||||
PDF/HTML fait des milliers d'appends, aucun n'est un point chaud). -->
|
||||
<rule ref="category/java/performance.xml">
|
||||
<exclude name="AvoidInstantiatingObjectsInLoops"/>
|
||||
<exclude name="AppendCharacterWithChar"/>
|
||||
<exclude name="ConsecutiveLiteralAppends"/>
|
||||
<exclude name="ConsecutiveAppendsShouldReuse"/>
|
||||
<exclude name="InsufficientStringBufferDeclaration"/>
|
||||
</rule>
|
||||
|
||||
<!-- Sécurité -->
|
||||
<rule ref="category/java/security.xml"/>
|
||||
|
||||
<!-- Bonnes pratiques (sous-ensemble non-style) -->
|
||||
<rule ref="category/java/bestpractices.xml">
|
||||
<!-- slf4j paramétré ({} + args) rend le guard inutile. -->
|
||||
<exclude name="GuardLogStatement"/>
|
||||
<!-- Les ports hexagonaux à méthode unique ne sont pas des lambdas. -->
|
||||
<exclude name="ImplicitFunctionalInterface"/>
|
||||
<!-- Déclarer List vs ArrayList : style, pas un bug. -->
|
||||
<exclude name="LooseCoupling"/>
|
||||
<!-- StringBuilder en champ : pattern builder assumé (export PDF). -->
|
||||
<exclude name="AvoidStringBufferField"/>
|
||||
<!-- Style de tests : à l'appréciation du projet, pas un gate. -->
|
||||
<exclude name="UnitTestAssertionsShouldIncludeMessage"/>
|
||||
<exclude name="UnitTestContainsTooManyAsserts"/>
|
||||
<exclude name="UnitTestShouldIncludeAssert"/>
|
||||
</rule>
|
||||
|
||||
</ruleset>
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
FROM node:20-bookworm-slim AS build
|
||||
WORKDIR /build
|
||||
RUN npm install -g npm@latest
|
||||
# PAS de mise à jour de npm ici : « npm@latest » est une cible mouvante qui finit
|
||||
# par exiger un Node plus récent que l'image (npm 12 -> Node >= 22) et casse le
|
||||
# build. Le npm livré avec l'image suffit (npm ci supporte lockfileVersion 3).
|
||||
COPY package*.json ./
|
||||
RUN npm ci --include=dev --ignore-scripts --no-audit --no-fund --no-progress
|
||||
COPY . .
|
||||
|
||||
@@ -42,6 +42,23 @@ module.exports = defineConfig([
|
||||
// Math.random() est légitime ici : tables aléatoires / jets de dés = le
|
||||
// domaine métier. Aucun usage cryptographique côté front.
|
||||
"sonarjs/pseudo-random": "off",
|
||||
// 9 fonctions historiques dépassent le seuil de 15 (jusqu'à 39 sur les
|
||||
// graphes campagne/chapitre). Les refactorer "pour le lint" sans filet de
|
||||
// tests serait plus risqué qu'utile → warn (visible, non bloquant).
|
||||
// Backlog : campaign-graph (×3), chapter-graph (×2), campaign-import,
|
||||
// settings, persona-view, sse.util. Repasser en "error" une fois résorbé.
|
||||
"sonarjs/cognitive-complexity": "warn",
|
||||
// Convention TS standard : un préfixe `_` marque un paramètre/variable
|
||||
// volontairement inutilisé (ex. paramètres conservés pour ne pas casser
|
||||
// les appelants — cf. campaign-tree.helper.ts).
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
caughtErrorsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
Generated
+855
-842
File diff suppressed because it is too large
Load Diff
+10
-10
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "loremind-web",
|
||||
"version": "1.0.2-beta",
|
||||
"version": "1.0.3",
|
||||
"description": "LoreMind Frontend - Angular",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
@@ -20,15 +20,15 @@
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^21.2.16",
|
||||
"@angular/animations": "^21.2.17",
|
||||
"@angular/cdk": "^21.2.14",
|
||||
"@angular/common": "^21.2.16",
|
||||
"@angular/compiler": "^21.2.16",
|
||||
"@angular/core": "^21.2.16",
|
||||
"@angular/forms": "^21.2.16",
|
||||
"@angular/platform-browser": "^21.2.16",
|
||||
"@angular/platform-browser-dynamic": "^21.2.16",
|
||||
"@angular/router": "^21.2.16",
|
||||
"@angular/common": "^21.2.17",
|
||||
"@angular/compiler": "^21.2.17",
|
||||
"@angular/core": "^21.2.17",
|
||||
"@angular/forms": "^21.2.17",
|
||||
"@angular/platform-browser": "^21.2.17",
|
||||
"@angular/platform-browser-dynamic": "^21.2.17",
|
||||
"@angular/router": "^21.2.17",
|
||||
"@ngx-translate/core": "^18.0.0",
|
||||
"@ngx-translate/http-loader": "^18.0.0",
|
||||
"dompurify": "^3.4.1",
|
||||
@@ -41,7 +41,7 @@
|
||||
"devDependencies": {
|
||||
"@angular-devkit/build-angular": "^21.2.14",
|
||||
"@angular/cli": "^21.2.14",
|
||||
"@angular/compiler-cli": "^21.2.16",
|
||||
"@angular/compiler-cli": "^21.2.17",
|
||||
"@emnapi/core": "^1.11.0",
|
||||
"@emnapi/runtime": "^1.11.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
|
||||
@@ -23,3 +23,4 @@
|
||||
|
||||
<app-global-search></app-global-search>
|
||||
<app-confirm-dialog-host></app-confirm-dialog-host>
|
||||
<app-writing-coach-panel></app-writing-coach-panel>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { SecondarySidebarComponent } from './shared/secondary-sidebar/secondary-
|
||||
import { GlobalSearchComponent } from './shared/global-search/global-search.component';
|
||||
import { UpdateBannerComponent } from './shared/update-banner/update-banner.component';
|
||||
import { ConfirmDialogHostComponent } from './shared/confirm-dialog/confirm-dialog-host.component';
|
||||
import { WritingCoachPanelComponent } from './shared/writing-coach/writing-coach-panel.component';
|
||||
import { LayoutService } from './services/layout.service';
|
||||
import { GlobalSearchService } from './services/global-search.service';
|
||||
import { VersionCheckerService } from './services/version-checker.service';
|
||||
@@ -19,6 +20,7 @@ import { VersionCheckerService } from './services/version-checker.service';
|
||||
GlobalSearchComponent,
|
||||
UpdateBannerComponent,
|
||||
ConfirmDialogHostComponent,
|
||||
WritingCoachPanelComponent,
|
||||
AsyncPipe
|
||||
],
|
||||
templateUrl: './app.component.html',
|
||||
|
||||
@@ -45,6 +45,7 @@ export const routes: Routes = [
|
||||
{ path: 'campaigns/:campaignId/random-tables/:tableId/edit', loadComponent: () => import('./campaigns/random-table/random-table-edit/random-table-edit.component').then(m => m.RandomTableEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/random-tables/:tableId', loadComponent: () => import('./campaigns/random-table/random-table-view/random-table-view.component').then(m => m.RandomTableViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/create', loadComponent: () => import('./campaigns/arc/arc-create/arc-create.component').then(m => m.ArcCreateComponent) },
|
||||
{ path: 'campaigns/:campaignId/guided/:method', loadComponent: () => import('./campaigns/guided/guided-wizard/guided-wizard.component').then(m => m.GuidedWizardComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId', loadComponent: () => import('./campaigns/arc/arc-view/arc-view.component').then(m => m.ArcViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId/edit', loadComponent: () => import('./campaigns/arc/arc-edit/arc-edit.component').then(m => m.ArcEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/create', loadComponent: () => import('./campaigns/chapter/chapter-create/chapter-create.component').then(m => m.ChapterCreateComponent) },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
@@ -25,7 +25,7 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
templateUrl: './arc-create.component.html',
|
||||
styleUrls: ['./arc-create.component.scss']
|
||||
})
|
||||
export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
export class ArcCreateComponent implements OnInit {
|
||||
readonly BookOpen = BookOpen;
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
|
||||
@@ -88,11 +88,4 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
cancel(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,9 @@
|
||||
<!-- Tout est optionnel sauf le titre : identité visible, le reste replié. -->
|
||||
<p class="optional-hint">{{ 'arcEdit.optionalHint' | translate }}</p>
|
||||
|
||||
<!-- Mentor d'écriture (M2) : conseils de relecture qui concernent cette entité. -->
|
||||
<app-writing-review-hints [campaignId]="campaignId" entityType="ARC" [entityId]="arcId"></app-writing-review-hints>
|
||||
|
||||
<!-- Co-création (Pilier A) : le co-MJ propose, validation champ par champ → remplit le formulaire. -->
|
||||
<app-entity-assist-panel
|
||||
[entityType]="'arc'" [entityId]="arcId" [campaignId]="campaignId"
|
||||
@@ -47,7 +50,10 @@
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-edit-description">{{ 'arcEdit.synopsisLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-description">{{ 'arcEdit.synopsisLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.synopsis"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-description"
|
||||
formControlName="description"
|
||||
@@ -89,10 +95,13 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Thèmes et enjeux -->
|
||||
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [filled]="themesStakesFilled">
|
||||
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [initiallyOpen]="focusSection === 'stakes'" [filled]="themesStakesFilled">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="arc-edit-themes">{{ 'arcEdit.themesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-themes">{{ 'arcEdit.themesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.themes"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-themes"
|
||||
formControlName="themes"
|
||||
@@ -101,7 +110,10 @@
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="arc-edit-stakes">{{ 'arcEdit.stakesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-stakes">{{ 'arcEdit.stakesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.stakes"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-stakes"
|
||||
formControlName="stakes"
|
||||
@@ -129,7 +141,10 @@
|
||||
<!-- Récompenses et dénouement -->
|
||||
<app-expandable-section [title]="'arcEdit.rewardsResolutionSectionTitle' | translate" icon="🎁" [filled]="rewardsResolutionFilled">
|
||||
<div class="field">
|
||||
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.rewards"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-rewards"
|
||||
formControlName="rewards"
|
||||
@@ -138,7 +153,10 @@
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.resolution"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-resolution"
|
||||
formControlName="resolution"
|
||||
@@ -183,5 +201,5 @@
|
||||
[isOpen]="chatOpen"
|
||||
[welcomeMessage]="'arcEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
(closed)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
@@ -26,6 +26,8 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { EntityAssistPanelComponent } from '../../../shared/entity-assist-panel/entity-assist-panel.component';
|
||||
import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { WritingReviewHintsComponent } from '../../../shared/writing-review/writing-review-hints.component';
|
||||
|
||||
/**
|
||||
* Écran de détail/modification d'un Arc.
|
||||
@@ -38,11 +40,11 @@ import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-edit',
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, ExpandableSectionComponent, EntityAssistPanelComponent, TranslatePipe],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, ExpandableSectionComponent, EntityAssistPanelComponent, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent],
|
||||
templateUrl: './arc-edit.component.html',
|
||||
styleUrls: ['./arc-edit.component.scss']
|
||||
})
|
||||
export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
export class ArcEditComponent implements OnInit {
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Sparkles = Sparkles;
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
@@ -74,6 +76,9 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
arcId = '';
|
||||
arc: Arc | null = null;
|
||||
|
||||
/** `?focus=stakes` (lien « Voir » de la relecture d'éditeur) → section dépliée d'office. */
|
||||
focusSection: string | null = null;
|
||||
|
||||
/** Pages disponibles pour le picker (vide si la campagne n'a pas de loreId). */
|
||||
availablePages: Page[] = [];
|
||||
/** ID du Lore associé à la campagne (null si campagne sans univers). */
|
||||
@@ -135,6 +140,7 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
if (newArcId !== this.arcId || newCampaignId !== this.campaignId) {
|
||||
this.campaignId = newCampaignId;
|
||||
this.arcId = newArcId;
|
||||
this.focusSection = this.route.snapshot.queryParamMap.get('focus');
|
||||
this.loadAll();
|
||||
}
|
||||
});
|
||||
@@ -221,11 +227,4 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
cancel(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'arcs', this.arcId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
@@ -35,7 +35,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
templateUrl: './arc-view.component.html',
|
||||
styleUrls: ['./arc-view.component.scss']
|
||||
})
|
||||
export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
export class ArcViewComponent implements OnInit {
|
||||
readonly Pencil = Pencil;
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Plus = Plus;
|
||||
@@ -162,8 +162,4 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
error: () => console.error('Impossible de récupérer les dépendances de l\'arc')
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant suivant.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
private readonly DRAG_THRESHOLD = 4;
|
||||
|
||||
// Adjacence (ids de nœuds) — sert à recalculer les arêtes après un drag.
|
||||
private adjacency: Array<{ key: string; kind: NodeKind; a: string; b: string }> = [];
|
||||
private adjacency: { key: string; kind: NodeKind; a: string; b: string }[] = [];
|
||||
|
||||
// Disposition personnalisée : positions sauvegardées sur la campagne, sauvegarde
|
||||
// différée après un drag (évite un PUT par pixel déplacé).
|
||||
@@ -174,7 +174,10 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
if (this.draggingId) return; // pas de changement de focus en plein drag
|
||||
this.hoveredId = node.id;
|
||||
this.hoverNeighbors = new Set(
|
||||
this.adjacency.flatMap(e => e.a === node.id ? [e.b] : e.b === node.id ? [e.a] : []));
|
||||
this.adjacency.flatMap(e => {
|
||||
if (e.a === node.id) return [e.b];
|
||||
return e.b === node.id ? [e.a] : [];
|
||||
}));
|
||||
}
|
||||
|
||||
onNodeLeave(): void {
|
||||
@@ -230,7 +233,7 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
for (const [arcId, chapters] of Object.entries(treeData.chaptersByArc)) {
|
||||
for (const ch of chapters) arcOfChapter.set(ch.id!, arcId);
|
||||
}
|
||||
const linkedScenes: Array<{ scene: Scene; chapterId: string }> = [];
|
||||
const linkedScenes: { scene: Scene; chapterId: string }[] = [];
|
||||
if (!this.hiddenKinds.has('scene')) {
|
||||
for (const [chapterId, scenes] of Object.entries(treeData.scenesByChapter)) {
|
||||
if (!arcOfChapter.has(chapterId)) continue;
|
||||
@@ -268,7 +271,7 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
|
||||
// Arêtes. Les liens page↔page sont dé-dupliqués par paire non-orientée
|
||||
// (A→B et B→A = un seul trait) ; les liens entité→page portent le type de l'entité.
|
||||
const adjacency: Array<{ key: string; kind: NodeKind; a: string; b: string }> = [];
|
||||
const adjacency: { key: string; kind: NodeKind; a: string; b: string }[] = [];
|
||||
const seenPairs = new Set<string>();
|
||||
for (const p of pages) {
|
||||
for (const targetId of p.relatedPageIds ?? []) {
|
||||
@@ -530,14 +533,16 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
if (Math.abs(dx) >= needX || Math.abs(dy) >= needY) continue;
|
||||
const overlapX = needX - Math.abs(dx);
|
||||
const overlapY = needY - Math.abs(dy);
|
||||
// Départage déterministe quand les centres coïncident (dx/dy = 0).
|
||||
const tieBreak = i % 2 === 0 ? 1 : -1;
|
||||
if (overlapX / needX < overlapY / needY) {
|
||||
const shift = overlapX / 2 + 0.5;
|
||||
const sign = dx !== 0 ? Math.sign(dx) : (i % 2 === 0 ? 1 : -1);
|
||||
const sign = dx !== 0 ? Math.sign(dx) : tieBreak;
|
||||
a.x -= sign * shift;
|
||||
b.x += sign * shift;
|
||||
} else {
|
||||
const shift = overlapY / 2 + 0.5;
|
||||
const sign = dy !== 0 ? Math.sign(dy) : (i % 2 === 0 ? 1 : -1);
|
||||
const sign = dy !== 0 ? Math.sign(dy) : tieBreak;
|
||||
a.y -= sign * shift;
|
||||
b.y += sign * shift;
|
||||
}
|
||||
|
||||
@@ -82,7 +82,10 @@ export function buildCampaignTree(
|
||||
// Clé TYPE|ID obligatoire : chaque table a sa propre séquence IDENTITY (une quête
|
||||
// id 6 et une scène id 6 coexistent) — sans le type, un manque de quête allumerait
|
||||
// à tort la pastille d'une scène/PNJ portant le même numéro.
|
||||
const sevRank = (s: ReadinessSeverity): number => (s === 'BLOCKING' ? 2 : s === 'RECOMMENDED' ? 1 : 0);
|
||||
const sevRank = (s: ReadinessSeverity): number => {
|
||||
if (s === 'BLOCKING') return 2;
|
||||
return s === 'RECOMMENDED' ? 1 : 0;
|
||||
};
|
||||
const gapsByKey = new Map<string, ReadinessGap[]>();
|
||||
for (const g of readinessGaps) {
|
||||
const key = `${g.entityType}|${g.entityId}`;
|
||||
|
||||
@@ -69,7 +69,7 @@
|
||||
[placeholder]="'campaignCreate.gameSystemNamePlaceholder' | translate"
|
||||
(keydown.enter)="$event.preventDefault(); submitCreateGameSystem()"
|
||||
(keydown.escape)="cancelCreateGameSystem()"
|
||||
autofocus
|
||||
|
||||
/>
|
||||
<div class="inline-create-actions">
|
||||
<button type="button" class="btn-inline-primary"
|
||||
|
||||
@@ -29,7 +29,7 @@ export interface CampaignCreatePayload {
|
||||
styleUrls: ['./campaign-create.component.scss']
|
||||
})
|
||||
export class CampaignCreateComponent implements OnInit {
|
||||
@Output() close = new EventEmitter<void>();
|
||||
@Output() closed = new EventEmitter<void>();
|
||||
@Output() created = new EventEmitter<CampaignCreatePayload>();
|
||||
|
||||
readonly BookCopy = BookCopy;
|
||||
@@ -131,6 +131,6 @@ export class CampaignCreateComponent implements OnInit {
|
||||
}
|
||||
|
||||
onCancel(): void {
|
||||
this.close.emit();
|
||||
this.closed.emit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,8 @@
|
||||
<!-- ============ Guidage co-MJ : « Prochaines étapes » (Pilier B) ============ -->
|
||||
@if (!editing && campaign.id) {
|
||||
<app-readiness-panel [campaignId]="campaign.id" [assessment]="readiness"></app-readiness-panel>
|
||||
<!-- Mentor d'écriture (M2) : conseils d'auteur sur la qualité, à côté de la complétude. -->
|
||||
<app-writing-review-panel [campaignId]="campaign.id"></app-writing-review-panel>
|
||||
}
|
||||
<!-- ============ Header : mode édition inline ============ -->
|
||||
@if (editing) {
|
||||
@@ -106,7 +108,7 @@
|
||||
[placeholder]="'campaignDetail.gameSystemNamePlaceholder' | translate"
|
||||
(keydown.enter)="$event.preventDefault(); submitCreateGameSystem()"
|
||||
(keydown.escape)="cancelCreateGameSystem()"
|
||||
autofocus
|
||||
|
||||
/>
|
||||
<div class="inline-create-actions">
|
||||
<button type="button" class="btn-inline-primary"
|
||||
@@ -206,6 +208,11 @@
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
{{ 'campaignDetail.newArc' | translate }}
|
||||
</button>
|
||||
<!-- Mentor d'écriture (M3) : écrire une aventure question par question. -->
|
||||
<a class="btn-add btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided', 'five-room']">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ 'guided.entry' | translate }}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
@if (arcs.length > 0 && !showQuickAddScene) {
|
||||
@@ -235,6 +242,10 @@
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
{{ 'campaignDetail.quickSceneFirst' | translate }}
|
||||
</button>
|
||||
<a class="btn-add-first btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided', 'five-room']">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ 'guided.entryFirst' | translate }}
|
||||
</a>
|
||||
<button type="button" class="empty-alt-action" (click)="createArc()">
|
||||
{{ 'campaignDetail.organizeInArcs' | translate }}
|
||||
</button>
|
||||
|
||||
@@ -486,6 +486,18 @@
|
||||
&:hover { background: #5b52e0; }
|
||||
}
|
||||
|
||||
// Entrée « Méthode guidée » (Mentor d'écriture, M3) : un lien stylé en bouton,
|
||||
// accent ambré du mentor pour le distinguer des créations « à la main ».
|
||||
.btn-guided {
|
||||
text-decoration: none;
|
||||
background: rgba(251, 191, 36, 0.12);
|
||||
color: #fde68a;
|
||||
border: 1px solid rgba(251, 191, 36, 0.35);
|
||||
|
||||
&:hover { background: rgba(251, 191, 36, 0.2); }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
|
||||
}
|
||||
|
||||
// Action secondaire de l'état vide (« ou créer un arc ») — bouton texte discret.
|
||||
.empty-alt-action {
|
||||
background: none;
|
||||
|
||||
@@ -32,11 +32,12 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
import { FolderGroup, groupByFolder, byOrder } from '../../../shared/folder-grouping.util';
|
||||
import { CampaignReadinessAssessment } from '../../../services/readiness.model';
|
||||
import { ReadinessPanelComponent } from '../../../shared/readiness-panel/readiness-panel.component';
|
||||
import { WritingReviewPanelComponent } from '../../../shared/writing-review/writing-review-panel.component';
|
||||
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-detail',
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, FoundryExportDialogComponent],
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, WritingReviewPanelComponent, FoundryExportDialogComponent],
|
||||
templateUrl: './campaign-detail.component.html',
|
||||
styleUrls: ['./campaign-detail.component.scss']
|
||||
})
|
||||
|
||||
@@ -52,6 +52,19 @@ interface NpcNode { name: string; description: string; selected: boolean; existi
|
||||
* Flux : upload → progression streamée → arbre éditable (revue) → création.
|
||||
* Rien n'est créé tant que l'utilisateur n'a pas validé « Créer dans la campagne ».
|
||||
*/
|
||||
|
||||
/** Nettoie les pièces (rooms) d'une scène pour le payload de création. */
|
||||
function cleanRooms(rooms: { name: string; description: string; enemies: string; loot: string }[]) {
|
||||
return rooms
|
||||
.filter(r => r.name.trim())
|
||||
.map(r => ({
|
||||
name: r.name.trim(),
|
||||
description: r.description.trim(),
|
||||
enemies: r.enemies.trim(),
|
||||
loot: r.loot.trim()
|
||||
}));
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-import',
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe, FileDropDirective],
|
||||
@@ -401,14 +414,7 @@ export class CampaignImportComponent implements OnInit {
|
||||
playerNarration: s.playerNarration.trim(),
|
||||
gmNotes: s.gmNotes.trim(),
|
||||
existingId: s.existingId ?? null,
|
||||
rooms: s.rooms
|
||||
.filter(r => r.name.trim())
|
||||
.map(r => ({
|
||||
name: r.name.trim(),
|
||||
description: r.description.trim(),
|
||||
enemies: r.enemies.trim(),
|
||||
loot: r.loot.trim()
|
||||
}))
|
||||
rooms: cleanRooms(s.rooms)
|
||||
}))
|
||||
}))
|
||||
})),
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
|
||||
@if (showCreateModal) {
|
||||
<app-campaign-create
|
||||
(close)="onModalClose()"
|
||||
(closed)="onModalClose()"
|
||||
(created)="onCampaignCreated($event)">
|
||||
</app-campaign-create>
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
@@ -24,7 +24,7 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
templateUrl: './chapter-create.component.html',
|
||||
styleUrls: ['./chapter-create.component.scss']
|
||||
})
|
||||
export class ChapterCreateComponent implements OnInit, OnDestroy {
|
||||
export class ChapterCreateComponent implements OnInit {
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
selectedIcon: string | null = null;
|
||||
|
||||
@@ -88,11 +88,4 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
|
||||
cancel(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,9 @@
|
||||
<!-- Tout est optionnel sauf le titre : identité visible, le reste replié. -->
|
||||
<p class="optional-hint">{{ 'chapterEdit.optionalHint' | translate }}</p>
|
||||
|
||||
<!-- Mentor d'écriture (M2) : conseils de relecture qui concernent cette entité. -->
|
||||
<app-writing-review-hints [campaignId]="campaignId" entityType="CHAPTER" [entityId]="chapterId"></app-writing-review-hints>
|
||||
|
||||
<!-- Co-création (Pilier A) : le co-MJ propose, validation champ par champ → remplit le formulaire. -->
|
||||
<app-entity-assist-panel
|
||||
[entityType]="'chapter'" [entityId]="chapterId" [campaignId]="campaignId"
|
||||
@@ -53,7 +56,10 @@
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="chapter-edit-description">{{ 'chapterEdit.synopsisLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="chapter-edit-description">{{ 'chapterEdit.synopsisLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="chapter.synopsis"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="chapter-edit-description"
|
||||
formControlName="description"
|
||||
@@ -93,10 +99,13 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Objectifs et enjeux -->
|
||||
<app-expandable-section [title]="'chapterEdit.objectivesStakesSectionTitle' | translate" icon="🎯" [filled]="objectivesStakesFilled">
|
||||
<app-expandable-section [title]="'chapterEdit.objectivesStakesSectionTitle' | translate" icon="🎯" [initiallyOpen]="focusSection === 'stakes'" [filled]="objectivesStakesFilled">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="chapter-edit-player-objectives">{{ 'chapterEdit.playerObjectivesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="chapter-edit-player-objectives">{{ 'chapterEdit.playerObjectivesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="chapter.objectives"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="chapter-edit-player-objectives"
|
||||
formControlName="playerObjectives"
|
||||
@@ -105,7 +114,10 @@
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="chapter-edit-narrative-stakes">{{ 'chapterEdit.narrativeStakesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="chapter-edit-narrative-stakes">{{ 'chapterEdit.narrativeStakesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="chapter.stakes"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="chapter-edit-narrative-stakes"
|
||||
formControlName="narrativeStakes"
|
||||
@@ -151,5 +163,5 @@
|
||||
[isOpen]="chatOpen"
|
||||
[welcomeMessage]="'chapterEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
(closed)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
@@ -27,6 +27,8 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
import { EntityAssistPanelComponent } from '../../../shared/entity-assist-panel/entity-assist-panel.component';
|
||||
import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
import { SceneDraftPanelComponent } from '../../../shared/scene-draft-panel/scene-draft-panel.component';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { WritingReviewHintsComponent } from '../../../shared/writing-review/writing-review-hints.component';
|
||||
|
||||
/**
|
||||
* Écran d'édition d'un Chapitre. Donnée de SCÉNARIO uniquement.
|
||||
@@ -47,12 +49,13 @@ import { SceneDraftPanelComponent } from '../../../shared/scene-draft-panel/scen
|
||||
ExpandableSectionComponent,
|
||||
EntityAssistPanelComponent,
|
||||
SceneDraftPanelComponent,
|
||||
TranslatePipe
|
||||
TranslatePipe,
|
||||
WritingCoachTriggerComponent, WritingReviewHintsComponent
|
||||
],
|
||||
templateUrl: './chapter-edit.component.html',
|
||||
styleUrls: ['./chapter-edit.component.scss']
|
||||
})
|
||||
export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
export class ChapterEditComponent implements OnInit {
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Sparkles = Sparkles;
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
@@ -88,6 +91,9 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
/** `?assist=draft-scenes` (bouton « Corriger » du guidage) → panneau IA déployé d'office. */
|
||||
assistParam: string | null = null;
|
||||
|
||||
/** `?focus=stakes` (lien « Voir » de la relecture d'éditeur) → section dépliée d'office. */
|
||||
focusSection: string | null = null;
|
||||
|
||||
availablePages: Page[] = [];
|
||||
loreId: string | null = null;
|
||||
relatedPageIds: string[] = [];
|
||||
@@ -144,6 +150,7 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
this.arcId = newArcId;
|
||||
this.chapterId = newChapterId;
|
||||
this.assistParam = this.route.snapshot.queryParamMap.get('assist');
|
||||
this.focusSection = this.route.snapshot.queryParamMap.get('focus');
|
||||
this.loadAll();
|
||||
}
|
||||
});
|
||||
@@ -220,6 +227,4 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
cancel(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'arcs', this.arcId, 'chapters', this.chapterId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, ElementRef, ViewChild, HostListener, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, ElementRef, ViewChild, HostListener, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { FormsModule } from '@angular/forms';
|
||||
@@ -29,7 +29,7 @@ interface GraphEdge { key: string; label: string; kind: LinkType; x1: number; y1
|
||||
templateUrl: './chapter-graph.component.html',
|
||||
styleUrls: ['./chapter-graph.component.scss']
|
||||
})
|
||||
export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
export class ChapterGraphComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly Plus = Plus;
|
||||
readonly ZoomIn = ZoomIn;
|
||||
@@ -507,7 +507,7 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
scene.graphX = node.x;
|
||||
scene.graphY = node.y;
|
||||
this.campaignService.updateScene(nodeId, { ...scene, order: scene.order ?? 0 })
|
||||
.subscribe({ error: () => {} });
|
||||
.subscribe({ error: () => { /* best-effort : erreur ignorée volontairement */ } });
|
||||
}
|
||||
|
||||
private truncate(text: string): string {
|
||||
@@ -548,7 +548,7 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
};
|
||||
this.campaignService.createScene(payload).subscribe({
|
||||
next: () => this.load(),
|
||||
error: () => {}
|
||||
error: () => { /* best-effort : erreur ignorée volontairement */ }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -592,7 +592,7 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
node.name = name;
|
||||
node.displayName = this.truncate(name);
|
||||
scene.name = name;
|
||||
this.campaignService.updateScene(id, { ...scene, order: scene.order ?? 0 }).subscribe({ error: () => {} });
|
||||
this.campaignService.updateScene(id, { ...scene, order: scene.order ?? 0 }).subscribe({ error: () => { /* best-effort : erreur ignorée volontairement */ } });
|
||||
}
|
||||
|
||||
cancelRename(): void {
|
||||
@@ -635,7 +635,7 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
if (existing.some(b => b.targetSceneId === toId)) return;
|
||||
const next: SceneBranch[] = [...existing, { label: '', targetSceneId: toId, condition: '', kind: 'EXIT' }];
|
||||
this.campaignService.updateScene(fromId, { ...scene, order: scene.order ?? 0, branches: next })
|
||||
.subscribe({ next: () => this.load(), error: () => {} });
|
||||
.subscribe({ next: () => this.load(), error: () => { /* best-effort : erreur ignorée volontairement */ } });
|
||||
}
|
||||
|
||||
// ─────────────── Sélection / édition / suppression d'un lien ───────────────
|
||||
@@ -698,7 +698,7 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
? { ...b, label: this.editEdgeLabel.trim(), condition: this.editEdgeCondition.trim(), kind: this.editEdgeKind }
|
||||
: b);
|
||||
this.campaignService.updateScene(scene.id!, { ...scene, order: scene.order ?? 0, branches })
|
||||
.subscribe({ next: () => { this.selectedEdgeKey = null; this.load(); }, error: () => {} });
|
||||
.subscribe({ next: () => { this.selectedEdgeKey = null; this.load(); }, error: () => { /* best-effort : erreur ignorée volontairement */ } });
|
||||
}
|
||||
|
||||
/** Supprime (sépare) le lien sélectionné. */
|
||||
@@ -709,10 +709,6 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
const { scene, branchIndex } = found;
|
||||
const branches = (scene.branches ?? []).filter((_, i) => i !== branchIndex);
|
||||
this.campaignService.updateScene(scene.id!, { ...scene, order: scene.order ?? 0, branches })
|
||||
.subscribe({ next: () => { this.selectedEdgeKey = null; this.load(); }, error: () => {} });
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant suivant.
|
||||
.subscribe({ next: () => { this.selectedEdgeKey = null; this.load(); }, error: () => { /* best-effort : erreur ignorée volontairement */ } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
@@ -30,7 +30,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
templateUrl: './chapter-view.component.html',
|
||||
styleUrls: ['./chapter-view.component.scss']
|
||||
})
|
||||
export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
export class ChapterViewComponent implements OnInit {
|
||||
readonly Pencil = Pencil;
|
||||
readonly Network = Network;
|
||||
readonly Trash2 = Trash2;
|
||||
@@ -147,11 +147,4 @@ export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
error: () => console.error('Impossible de récupérer les dépendances du chapitre')
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +100,6 @@
|
||||
[isOpen]="chatOpen"
|
||||
[welcomeMessage]="'characterEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
(closed)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
}
|
||||
|
||||
@@ -26,6 +26,6 @@
|
||||
entityType="character"
|
||||
[entityId]="characterId"
|
||||
[isOpen]="chatOpen"
|
||||
(close)="chatOpen = false">
|
||||
(closed)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { GuidedChapterSpec, GuidedSceneSpec } from '../../services/guided-skeleton.model';
|
||||
|
||||
/**
|
||||
* Définition d'une méthode guidée (Mentor d'écriture, phases M3/M5). L'assistant
|
||||
* `guided-wizard` est générique : il affiche les étapes d'une méthode et lui délègue
|
||||
* la construction du squelette. Ajouter une méthode = un fichier de définition + ses
|
||||
* textes i18n (`guided.<i18nKey>.*`) + son entrée dans `GUIDED_METHODS`.
|
||||
*
|
||||
* Conventions i18n (préfixe `guided.<i18nKey>.`) :
|
||||
* - `name`, `tagline` : présentation de la méthode ;
|
||||
* - `steps.<stepId>.title|why|example` : chaque étape (pourquoi + exemple, posture mentor) ;
|
||||
* - `fields.<fieldKey>.label|placeholder` : chaque champ (`fieldKey` peut contenir des points) ;
|
||||
* - `options.<fieldKey>.<option>` : libellés des choix ;
|
||||
* - `defaults.<fieldKey>` : valeur proposée d'office (ex. nom d'une salle).
|
||||
*/
|
||||
|
||||
/** Réponses du MJ, par clé de champ. */
|
||||
export type GuidedAnswers = Record<string, string>;
|
||||
|
||||
export interface GuidedField {
|
||||
key: string;
|
||||
kind: 'text' | 'textarea' | 'choice';
|
||||
required?: boolean;
|
||||
/** Valeurs possibles d'un champ `choice` (la 1re est sélectionnée par défaut). */
|
||||
options?: string[];
|
||||
/** Pré-remplir avec `defaults.<key>` (traduit) à la première visite. */
|
||||
prefilled?: boolean;
|
||||
/** Sujet du coach d'écriture (💡) associé, ex. `scene.choices`. */
|
||||
coachTopic?: string;
|
||||
}
|
||||
|
||||
export interface GuidedStep {
|
||||
id: string;
|
||||
/** `placement` : où ranger l'aventure ; `form` : questions ; `review` : récapitulatif. */
|
||||
kind: 'placement' | 'form' | 'review';
|
||||
fields?: GuidedField[];
|
||||
}
|
||||
|
||||
/** Ce que la méthode produit à partir des réponses (le placement est ajouté par l'assistant). */
|
||||
export interface GuidedDraft {
|
||||
chapter: GuidedChapterSpec;
|
||||
scenes: GuidedSceneSpec[];
|
||||
}
|
||||
|
||||
export interface GuidedMethod {
|
||||
/** Identifiant d'URL (`/campaigns/:id/guided/:method`). */
|
||||
id: string;
|
||||
/** Préfixe i18n sous `guided.`. */
|
||||
i18nKey: string;
|
||||
steps: GuidedStep[];
|
||||
toDraft(answers: GuidedAnswers): GuidedDraft;
|
||||
}
|
||||
|
||||
/** Valeur nettoyée d'une réponse (chaîne vide → null). */
|
||||
export function answer(answers: GuidedAnswers, key: string): string | null {
|
||||
const value = answers[key]?.trim();
|
||||
return value ? value : null;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { GuidedField, GuidedStep } from './guided-method.model';
|
||||
import { GUIDED_METHODS } from './guided-methods';
|
||||
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
|
||||
|
||||
/**
|
||||
* Garde-fous des méthodes guidées : chaque étape / champ / option / valeur par défaut
|
||||
* a son texte en fr ET en en (sinon l'assistant afficherait des clés brutes), et la
|
||||
* méthode « 5 salles » produit le bon squelette.
|
||||
*/
|
||||
const FRAGMENTS_DIR = join(process.cwd(), 'src/assets/i18n/fragments');
|
||||
|
||||
function i18n(lang: 'fr' | 'en'): Record<string, unknown> {
|
||||
return JSON.parse(readFileSync(join(FRAGMENTS_DIR, `guided.${lang}.json`), 'utf-8')).guided;
|
||||
}
|
||||
|
||||
function lookup(root: Record<string, unknown>, path: string): unknown {
|
||||
return path.split('.').reduce<unknown>((node, part) =>
|
||||
node && typeof node === 'object' ? (node as Record<string, unknown>)[part] : undefined, root);
|
||||
}
|
||||
|
||||
function fieldKeys(p: string, f: GuidedField): string[] {
|
||||
return [
|
||||
`${p}.fields.${f.key}.label`,
|
||||
...(f.kind === 'choice' ? [] : [`${p}.fields.${f.key}.placeholder`]),
|
||||
...(f.options ?? []).map(o => `${p}.options.${f.key}.${o}`),
|
||||
...(f.prefilled ? [`${p}.defaults.${f.key}`] : [])
|
||||
];
|
||||
}
|
||||
|
||||
function stepKeys(p: string, step: GuidedStep): string[] {
|
||||
return [
|
||||
`${p}.steps.${step.id}.title`,
|
||||
`${p}.steps.${step.id}.why`,
|
||||
...(step.kind === 'review' ? [] : [`${p}.steps.${step.id}.example`]),
|
||||
...(step.fields ?? []).flatMap(f => fieldKeys(p, f))
|
||||
];
|
||||
}
|
||||
|
||||
function requiredKeys(): string[] {
|
||||
return GUIDED_METHODS.flatMap(m => [`${m.i18nKey}.name`, ...m.steps.flatMap(s => stepKeys(m.i18nKey, s))]);
|
||||
}
|
||||
|
||||
describe('guided methods content', () => {
|
||||
const keys = requiredKeys();
|
||||
|
||||
for (const lang of ['fr', 'en'] as const) {
|
||||
it.each(keys)(`${lang}: guided.%s is a non-empty text`, key => {
|
||||
const value = lookup(i18n(lang), key);
|
||||
expect(typeof value === 'string' && value.trim().length > 0, `guided.${key} (${lang})`).toBe(true);
|
||||
});
|
||||
}
|
||||
|
||||
it('has unique method ids and step ids', () => {
|
||||
expect(new Set(GUIDED_METHODS.map(m => m.id)).size).toBe(GUIDED_METHODS.length);
|
||||
for (const m of GUIDED_METHODS) {
|
||||
expect(new Set(m.steps.map(s => s.id)).size).toBe(m.steps.length);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('five-room method', () => {
|
||||
const answers = {
|
||||
title: ' Le reliquaire volé ',
|
||||
location: 'La crypte',
|
||||
hook: 'Le prêtre a disparu',
|
||||
objectives: 'Ramener la relique',
|
||||
stakes: '',
|
||||
'room1.name': "L'entrée gardée",
|
||||
'room1.nature': 'social',
|
||||
'room1.choices': 'Convaincre ou ruser',
|
||||
'room2.name': "L'épreuve",
|
||||
'room2.nature': 'puzzle',
|
||||
'room3.name': 'Le revers',
|
||||
'room4.name': 'Le climax',
|
||||
'room4.enemies': "L'envoûteuse",
|
||||
'room5.name': 'La récompense',
|
||||
'room5.secret': 'Le symbole de la confrérie'
|
||||
};
|
||||
|
||||
it('builds the chapter from the frame and stakes answers', () => {
|
||||
expect(FIVE_ROOM_METHOD.toDraft(answers).chapter).toEqual({
|
||||
name: 'Le reliquaire volé',
|
||||
description: 'Le prêtre a disparu',
|
||||
playerObjectives: 'Ramener la relique',
|
||||
narrativeStakes: null
|
||||
});
|
||||
});
|
||||
|
||||
it('builds five typed scenes in the same place', () => {
|
||||
const scenes = FIVE_ROOM_METHOD.toDraft(answers).scenes;
|
||||
expect(scenes.map(s => s.type)).toEqual(['NPC', 'LOCATION', 'EVENT', 'ENCOUNTER', 'REVELATION']);
|
||||
expect(scenes.every(s => s.location === 'La crypte')).toBe(true);
|
||||
expect(scenes[0].choicesConsequences).toBe('Convaincre ou ruser');
|
||||
expect(scenes[3].enemies).toBe("L'envoûteuse");
|
||||
expect(scenes[4].gmSecretNotes).toBe('Le symbole de la confrérie');
|
||||
});
|
||||
|
||||
it('defaults room 1 to a fight when no nature was chosen', () => {
|
||||
expect(FIVE_ROOM_METHOD.toDraft({}).scenes[0].type).toBe('ENCOUNTER');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { GuidedMethod } from './guided-method.model';
|
||||
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
|
||||
|
||||
/** Méthodes guidées disponibles (M5 : préparation minimale, enquête, casse, bac à sable…). */
|
||||
export const GUIDED_METHODS: GuidedMethod[] = [FIVE_ROOM_METHOD];
|
||||
|
||||
export function findGuidedMethod(id: string | null): GuidedMethod | undefined {
|
||||
return GUIDED_METHODS.find(m => m.id === id);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
@if (method && step) {
|
||||
<div class="wizard">
|
||||
|
||||
<header class="wizard-top">
|
||||
<a class="wizard-back" [routerLink]="['/campaigns', campaignId]">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
{{ 'guided.backToCampaign' | translate }}
|
||||
</a>
|
||||
<div class="wizard-method">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ k('name') | translate }}
|
||||
</div>
|
||||
<div class="wizard-progress" role="progressbar"
|
||||
[attr.aria-valuenow]="stepIndex + 1" aria-valuemin="1" [attr.aria-valuemax]="total"
|
||||
[attr.aria-label]="'guided.progress' | translate: { n: stepIndex + 1, total: total }">
|
||||
<span class="progress-text">{{ 'guided.progress' | translate: { n: stepIndex + 1, total: total } }}</span>
|
||||
<span class="progress-track"><span class="progress-fill" [style.width.%]="progress"></span></span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="wizard-step">
|
||||
<h1 #stepTitle tabindex="-1">{{ k('steps.' + step.id + '.title') | translate }}</h1>
|
||||
<p class="step-why">{{ k('steps.' + step.id + '.why') | translate }}</p>
|
||||
|
||||
@if (step.kind !== 'review') {
|
||||
<aside class="step-example">
|
||||
<span class="example-label">{{ 'guided.exampleLabel' | translate }}</span>
|
||||
<p>{{ k('steps.' + step.id + '.example') | translate }}</p>
|
||||
</aside>
|
||||
}
|
||||
|
||||
<!-- Où ranger l'aventure -->
|
||||
@if (step.kind === 'placement') {
|
||||
<fieldset class="placement">
|
||||
<legend class="sr-only">{{ k('steps.placement.title') | translate }}</legend>
|
||||
@if (linearArcs.length > 0) {
|
||||
<label class="option-card" [class.selected]="answers['placement.mode'] === 'existing'">
|
||||
<input type="radio" name="placement-mode" value="existing"
|
||||
[ngModel]="answers['placement.mode']" (ngModelChange)="setAnswer('placement.mode', $event)" />
|
||||
<span>{{ 'guided.placementExisting' | translate }}</span>
|
||||
</label>
|
||||
@if (answers['placement.mode'] === 'existing') {
|
||||
<div class="field nested">
|
||||
<label for="guided-arc">{{ 'guided.placementArcLabel' | translate }}</label>
|
||||
<select id="guided-arc" [ngModel]="answers['placement.arcId']"
|
||||
(ngModelChange)="setAnswer('placement.arcId', $event)">
|
||||
@for (arc of linearArcs; track arc.id) {
|
||||
<option [value]="arc.id">{{ arc.name }}</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
<label class="option-card" [class.selected]="answers['placement.mode'] === 'new'">
|
||||
<input type="radio" name="placement-mode" value="new"
|
||||
[ngModel]="answers['placement.mode']" (ngModelChange)="setAnswer('placement.mode', $event)" />
|
||||
<span>{{ 'guided.placementNew' | translate }}</span>
|
||||
</label>
|
||||
@if (answers['placement.mode'] === 'new') {
|
||||
<div class="field nested">
|
||||
<label for="guided-new-arc">{{ 'guided.placementNewArcLabel' | translate }} *</label>
|
||||
<input id="guided-new-arc" type="text" [ngModel]="answers['placement.newArcName']"
|
||||
(ngModelChange)="setAnswer('placement.newArcName', $event)"
|
||||
[placeholder]="'guided.placementNewArcPlaceholder' | translate" />
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
}
|
||||
|
||||
<!-- Questions de l'étape -->
|
||||
@if (step.kind === 'form') {
|
||||
<div class="step-fields">
|
||||
@for (field of step.fields; track field.key) {
|
||||
@if (field.kind === 'choice') {
|
||||
<fieldset class="field choice-field">
|
||||
<legend>{{ k('fields.' + field.key + '.label') | translate }}</legend>
|
||||
<div class="choice-row">
|
||||
@for (option of field.options; track option) {
|
||||
<label class="choice-chip" [class.selected]="answers[field.key] === option">
|
||||
<!-- attr.* : name/value doivent exister dans le DOM (groupe radio natif,
|
||||
navigation clavier) ; [value] seul est consommé par le ControlValueAccessor. -->
|
||||
<input type="radio" [attr.name]="fieldId(field)" [attr.value]="option" [value]="option"
|
||||
[ngModel]="answers[field.key]" (ngModelChange)="setAnswer(field.key, $event)" />
|
||||
{{ k('options.' + field.key + '.' + option) | translate }}
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
</fieldset>
|
||||
} @else {
|
||||
<div class="field">
|
||||
<div class="field-label-row">
|
||||
<label [for]="fieldId(field)">
|
||||
{{ k('fields.' + field.key + '.label') | translate }}@if (field.required) { * }
|
||||
</label>
|
||||
@if (field.coachTopic) {
|
||||
<app-writing-coach-trigger [topic]="field.coachTopic"></app-writing-coach-trigger>
|
||||
}
|
||||
</div>
|
||||
@if (field.kind === 'textarea') {
|
||||
<textarea [id]="fieldId(field)" rows="3"
|
||||
[ngModel]="answers[field.key]" (ngModelChange)="setAnswer(field.key, $event)"
|
||||
[placeholder]="k('fields.' + field.key + '.placeholder') | translate"></textarea>
|
||||
} @else {
|
||||
<input [id]="fieldId(field)" type="text"
|
||||
[ngModel]="answers[field.key]" (ngModelChange)="setAnswer(field.key, $event)"
|
||||
[placeholder]="k('fields.' + field.key + '.placeholder') | translate" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Récapitulatif -->
|
||||
@if (step.kind === 'review' && draft; as d) {
|
||||
<div class="review">
|
||||
<dl class="review-meta">
|
||||
<dt>{{ 'guided.reviewArc' | translate }}</dt>
|
||||
<dd>{{ placementLabel }}</dd>
|
||||
<dt>{{ 'guided.reviewChapter' | translate }}</dt>
|
||||
<dd>{{ d.chapter.name }}</dd>
|
||||
</dl>
|
||||
<ol class="review-scenes">
|
||||
@for (scene of d.scenes; track $index) {
|
||||
<li>
|
||||
<span class="scene-name">{{ scene.name }}</span>
|
||||
<span class="scene-type">{{ ('sceneType.' + scene.type) | translate }}</span>
|
||||
</li>
|
||||
}
|
||||
</ol>
|
||||
<label class="link-toggle">
|
||||
<input type="checkbox" [(ngModel)]="linkScenes" />
|
||||
{{ 'guided.linkScenes' | translate }}
|
||||
</label>
|
||||
<p class="review-after">{{ 'guided.reviewAfter' | translate }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (error) {
|
||||
<p class="wizard-error" role="alert">{{ error }}</p>
|
||||
}
|
||||
</main>
|
||||
|
||||
<footer class="wizard-nav">
|
||||
<button type="button" class="btn-secondary" (click)="previous()" [disabled]="stepIndex === 0">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
{{ 'guided.previous' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-ghost" (click)="restart()">
|
||||
<lucide-icon [img]="RotateCcw" [size]="14"></lucide-icon>
|
||||
{{ 'guided.restart' | translate }}
|
||||
</button>
|
||||
@if (isLast) {
|
||||
<button type="button" class="btn-primary" (click)="create()" [disabled]="submitting">
|
||||
<lucide-icon [img]="Check" [size]="14"></lucide-icon>
|
||||
{{ (submitting ? 'guided.creating' : 'guided.create') | translate }}
|
||||
</button>
|
||||
} @else {
|
||||
<button type="button" class="btn-primary" (click)="next()" [disabled]="!canProceed()">
|
||||
{{ 'guided.next' | translate }}
|
||||
<lucide-icon [img]="ArrowRight" [size]="14"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
</footer>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="wizard">
|
||||
<p class="wizard-error">{{ 'guided.unknownMethod' | translate }}</p>
|
||||
<a [routerLink]="['/campaigns', campaignId]">{{ 'guided.backToCampaign' | translate }}</a>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// Une étape par écran, colonne unique et étroite : lisible sur ordinateur comme
|
||||
// sur téléphone (la barre de navigation reste collée en bas de l'écran).
|
||||
.wizard {
|
||||
max-width: 680px;
|
||||
margin: 0 auto;
|
||||
padding: 1.5rem 0 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.wizard-top {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.6rem 1rem;
|
||||
}
|
||||
|
||||
.wizard-back {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover { color: #e5e7eb; }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; border-radius: 4px; }
|
||||
}
|
||||
|
||||
.wizard-method {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
color: #fbbf24;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.wizard-progress {
|
||||
flex-basis: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
flex-shrink: 0;
|
||||
font-size: 0.8rem;
|
||||
color: #9ca3af;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.progress-track {
|
||||
flex: 1;
|
||||
height: 6px;
|
||||
border-radius: 999px;
|
||||
background: #1f2937;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: #6c63ff;
|
||||
border-radius: 999px;
|
||||
transition: width 0.25s ease;
|
||||
}
|
||||
|
||||
.wizard-step {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.1rem;
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
color: white;
|
||||
text-wrap: balance;
|
||||
|
||||
&:focus { outline: none; }
|
||||
}
|
||||
}
|
||||
|
||||
.step-why {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.6;
|
||||
color: #d1d5db;
|
||||
}
|
||||
|
||||
.step-example {
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 8px;
|
||||
background: rgba(108, 99, 255, 0.08);
|
||||
border: 1px solid rgba(108, 99, 255, 0.25);
|
||||
|
||||
p {
|
||||
margin: 0.3rem 0 0;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.55;
|
||||
font-style: italic;
|
||||
color: #d1d5db;
|
||||
}
|
||||
}
|
||||
|
||||
.example-label {
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: #a5b4fc;
|
||||
}
|
||||
|
||||
.step-fields {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.1rem;
|
||||
}
|
||||
|
||||
// --- Placement & choix ---------------------------------------------------------------
|
||||
|
||||
.placement {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.option-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
padding: 0.9rem 1rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #374151;
|
||||
background: #111827;
|
||||
color: #e5e7eb;
|
||||
font-size: 0.92rem;
|
||||
cursor: pointer;
|
||||
|
||||
&.selected { border-color: #6c63ff; background: rgba(108, 99, 255, 0.1); }
|
||||
input { accent-color: #6c63ff; width: 18px; height: 18px; margin: 0; }
|
||||
}
|
||||
|
||||
.nested {
|
||||
margin: 0 0 0.4rem 1.6rem;
|
||||
}
|
||||
|
||||
.choice-field {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
|
||||
legend {
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: #d1d5db;
|
||||
}
|
||||
}
|
||||
|
||||
.choice-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.choice-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
min-height: 44px;
|
||||
padding: 0 1rem;
|
||||
border-radius: 999px;
|
||||
border: 1px solid #374151;
|
||||
background: #111827;
|
||||
color: #d1d5db;
|
||||
font-size: 0.88rem;
|
||||
cursor: pointer;
|
||||
|
||||
&.selected { border-color: #6c63ff; color: white; background: rgba(108, 99, 255, 0.15); }
|
||||
input { accent-color: #6c63ff; margin: 0; }
|
||||
&:focus-within { outline: 2px solid #6c63ff; outline-offset: 2px; }
|
||||
}
|
||||
|
||||
// --- Récapitulatif --------------------------------------------------------------------
|
||||
|
||||
.review {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.review-meta {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0.4rem 1rem;
|
||||
margin: 0;
|
||||
|
||||
dt { color: #9ca3af; font-size: 0.85rem; }
|
||||
dd { margin: 0; color: #f3f4f6; font-weight: 600; font-size: 0.9rem; overflow-wrap: anywhere; }
|
||||
}
|
||||
|
||||
.review-scenes {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
counter-reset: scene;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.45rem;
|
||||
|
||||
li {
|
||||
counter-increment: scene;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.7rem 0.9rem;
|
||||
border-radius: 8px;
|
||||
background: #111827;
|
||||
border: 1px solid #1f2937;
|
||||
|
||||
&::before {
|
||||
content: counter(scene);
|
||||
flex-shrink: 0;
|
||||
width: 1.6rem;
|
||||
height: 1.6rem;
|
||||
border-radius: 50%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #1f2937;
|
||||
color: #a5b4fc;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.scene-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
color: #f3f4f6;
|
||||
font-size: 0.9rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.scene-type {
|
||||
flex-shrink: 0;
|
||||
padding: 0.1rem 0.55rem;
|
||||
border-radius: 999px;
|
||||
background: #1f2937;
|
||||
color: #9ca3af;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.link-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
color: #d1d5db;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
|
||||
input { accent-color: #6c63ff; width: 18px; height: 18px; margin: 0; }
|
||||
}
|
||||
|
||||
.review-after {
|
||||
margin: 0;
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.wizard-error {
|
||||
margin: 0;
|
||||
color: #fca5a5;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
// --- Navigation -------------------------------------------------------------------------
|
||||
|
||||
.wizard-nav {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
margin-top: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem 0;
|
||||
background: #0a0a14;
|
||||
border-top: 1px solid #1f2937;
|
||||
|
||||
.btn-primary { margin-left: auto; }
|
||||
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
min-height: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
padding: 0.6rem 0.8rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover { color: #e5e7eb; background: #111827; }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; }
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.wizard { padding-top: 1rem; }
|
||||
.wizard-step h1 { font-size: 1.3rem; }
|
||||
.wizard-nav {
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
|
||||
.btn-secondary,
|
||||
.btn-primary { flex: 1; padding-left: 0.75rem; padding-right: 0.75rem; }
|
||||
.btn-ghost { order: -1; flex-basis: 100%; justify-content: flex-start; padding-left: 0; }
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.progress-fill { transition: none; }
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { Component, DestroyRef, ElementRef, OnInit, ViewChild, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { LucideAngularModule, ArrowLeft, ArrowRight, Check, RotateCcw, Sparkles } from 'lucide-angular';
|
||||
|
||||
import { Arc } from '../../../services/campaign.model';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GuidedSkeletonService } from '../../../services/guided-skeleton.service';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { GuidedAnswers, GuidedDraft, GuidedField, GuidedMethod, GuidedStep, answer } from '../guided-method.model';
|
||||
import { findGuidedMethod } from '../guided-methods';
|
||||
|
||||
/** Clés de réponse réservées à l'assistant (placement + chaînage), communes à toutes les méthodes. */
|
||||
const PLACEMENT_MODE = 'placement.mode';
|
||||
const PLACEMENT_ARC = 'placement.arcId';
|
||||
const PLACEMENT_NEW_ARC = 'placement.newArcName';
|
||||
const LINK_SCENES = 'link';
|
||||
|
||||
/**
|
||||
* Assistant pas à pas d'une méthode guidée (Mentor d'écriture, phase M3) :
|
||||
* une étape par écran (lisible sur téléphone), chacune expliquée (pourquoi + exemple),
|
||||
* avec le coach 💡 sur les champs. Les réponses sont celles du MJ : rien n'est généré.
|
||||
* Le brouillon est gardé dans le navigateur pour pouvoir quitter et revenir.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-guided-wizard',
|
||||
imports: [FormsModule, RouterLink, TranslatePipe, LucideAngularModule, WritingCoachTriggerComponent],
|
||||
templateUrl: './guided-wizard.component.html',
|
||||
styleUrls: ['./guided-wizard.component.scss']
|
||||
})
|
||||
export class GuidedWizardComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly ArrowRight = ArrowRight;
|
||||
readonly Check = Check;
|
||||
readonly RotateCcw = RotateCcw;
|
||||
readonly Sparkles = Sparkles;
|
||||
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly router = inject(Router);
|
||||
private readonly translate = inject(TranslateService);
|
||||
private readonly campaignService = inject(CampaignService);
|
||||
private readonly skeletonService = inject(GuidedSkeletonService);
|
||||
private readonly confirmDialog = inject(ConfirmDialogService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
@ViewChild('stepTitle') stepTitle?: ElementRef<HTMLHeadingElement>;
|
||||
|
||||
campaignId = '';
|
||||
method: GuidedMethod | null = null;
|
||||
answers: GuidedAnswers = {};
|
||||
stepIndex = 0;
|
||||
/** Arcs linéaires de la campagne : seuls candidats pour y ranger l'aventure. */
|
||||
linearArcs: Arc[] = [];
|
||||
/** Le placement par défaut dépend des arcs : on attend leur chargement pour le choisir. */
|
||||
private arcsLoaded = false;
|
||||
submitting = false;
|
||||
error: string | null = null;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(pm => {
|
||||
this.campaignId = pm.get('campaignId') ?? '';
|
||||
this.method = findGuidedMethod(pm.get('method')) ?? null;
|
||||
if (!this.method) return;
|
||||
this.restoreDraft();
|
||||
this.arcsLoaded = false;
|
||||
this.campaignService.getArcs(this.campaignId).subscribe(arcs => {
|
||||
this.linearArcs = arcs
|
||||
.filter(a => (a.type ?? 'LINEAR') === 'LINEAR')
|
||||
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
||||
this.arcsLoaded = true;
|
||||
this.applyDefaults();
|
||||
});
|
||||
this.applyDefaults();
|
||||
});
|
||||
}
|
||||
|
||||
// --- Navigation ------------------------------------------------------------------
|
||||
|
||||
get step(): GuidedStep | null {
|
||||
return this.method?.steps[this.stepIndex] ?? null;
|
||||
}
|
||||
|
||||
get total(): number {
|
||||
return this.method?.steps.length ?? 0;
|
||||
}
|
||||
|
||||
get progress(): number {
|
||||
return this.total ? Math.round(((this.stepIndex + 1) / this.total) * 100) : 0;
|
||||
}
|
||||
|
||||
get isLast(): boolean {
|
||||
return this.stepIndex === this.total - 1;
|
||||
}
|
||||
|
||||
next(): void {
|
||||
if (!this.canProceed() || this.isLast) return;
|
||||
this.goTo(this.stepIndex + 1);
|
||||
}
|
||||
|
||||
previous(): void {
|
||||
if (this.stepIndex > 0) this.goTo(this.stepIndex - 1);
|
||||
}
|
||||
|
||||
private goTo(index: number): void {
|
||||
this.stepIndex = index;
|
||||
this.error = null;
|
||||
this.applyDefaults();
|
||||
this.saveDraft();
|
||||
// Nouvelle étape = nouvel écran : on remonte et on place le focus sur son titre.
|
||||
setTimeout(() => {
|
||||
this.stepTitle?.nativeElement.focus();
|
||||
this.stepTitle?.nativeElement.scrollIntoView({ block: 'start' });
|
||||
});
|
||||
}
|
||||
|
||||
canProceed(): boolean {
|
||||
const step = this.step;
|
||||
if (!step) return false;
|
||||
if (step.kind === 'placement') {
|
||||
return this.answers[PLACEMENT_MODE] === 'existing'
|
||||
? !!this.answers[PLACEMENT_ARC]
|
||||
: !!answer(this.answers, PLACEMENT_NEW_ARC);
|
||||
}
|
||||
return (step.fields ?? []).every(f => !f.required || !!answer(this.answers, f.key));
|
||||
}
|
||||
|
||||
// --- Réponses ----------------------------------------------------------------------
|
||||
|
||||
/** Clé i18n de la méthode courante. */
|
||||
k(path: string): string {
|
||||
return `guided.${this.method?.i18nKey}.${path}`;
|
||||
}
|
||||
|
||||
fieldId(field: GuidedField): string {
|
||||
return `guided-${field.key.replace(/\./g, '-')}`;
|
||||
}
|
||||
|
||||
setAnswer(key: string, value: string): void {
|
||||
this.answers = { ...this.answers, [key]: value };
|
||||
this.saveDraft();
|
||||
}
|
||||
|
||||
/** Placement par défaut + valeurs pré-remplies + premier choix des champs `choice`. */
|
||||
private applyDefaults(): void {
|
||||
const a = { ...this.answers };
|
||||
if (this.arcsLoaded) this.applyPlacementDefaults(a);
|
||||
a[LINK_SCENES] ??= 'true';
|
||||
for (const field of this.step?.fields ?? []) {
|
||||
if (a[field.key] !== undefined) continue;
|
||||
if (field.kind === 'choice' && field.options?.length) a[field.key] = field.options[0];
|
||||
else if (field.prefilled) a[field.key] = this.translate.instant(this.k(`defaults.${field.key}`));
|
||||
}
|
||||
this.answers = a;
|
||||
}
|
||||
|
||||
/** Arc existant par défaut s'il y en a ; sinon (ou arc disparu) nouvel arc. */
|
||||
private applyPlacementDefaults(a: GuidedAnswers): void {
|
||||
a[PLACEMENT_MODE] ??= this.linearArcs.length > 0 ? 'existing' : 'new';
|
||||
if (a[PLACEMENT_MODE] === 'existing' && !this.linearArcs.some(arc => arc.id === a[PLACEMENT_ARC])) {
|
||||
a[PLACEMENT_ARC] = this.linearArcs[0]?.id ?? '';
|
||||
if (!a[PLACEMENT_ARC]) a[PLACEMENT_MODE] = 'new';
|
||||
}
|
||||
}
|
||||
|
||||
// --- Récapitulatif & création --------------------------------------------------------
|
||||
|
||||
get draft(): GuidedDraft | null {
|
||||
return this.method ? this.method.toDraft(this.answers) : null;
|
||||
}
|
||||
|
||||
get placementLabel(): string {
|
||||
if (this.answers[PLACEMENT_MODE] === 'existing') {
|
||||
return this.linearArcs.find(a => a.id === this.answers[PLACEMENT_ARC])?.name ?? '';
|
||||
}
|
||||
return answer(this.answers, PLACEMENT_NEW_ARC) ?? '';
|
||||
}
|
||||
|
||||
get linkScenes(): boolean {
|
||||
return this.answers[LINK_SCENES] !== 'false';
|
||||
}
|
||||
|
||||
set linkScenes(value: boolean) {
|
||||
this.setAnswer(LINK_SCENES, String(value));
|
||||
}
|
||||
|
||||
create(): void {
|
||||
const draft = this.draft;
|
||||
if (!draft || this.submitting) return;
|
||||
const existing = this.answers[PLACEMENT_MODE] === 'existing';
|
||||
this.submitting = true;
|
||||
this.error = null;
|
||||
this.skeletonService.create(this.campaignId, {
|
||||
arcId: existing ? this.answers[PLACEMENT_ARC] : null,
|
||||
newArcName: existing ? null : answer(this.answers, PLACEMENT_NEW_ARC),
|
||||
chapter: draft.chapter,
|
||||
scenes: draft.scenes,
|
||||
linkSequentially: this.linkScenes,
|
||||
linkLabel: this.translate.instant('guided.linkLabel')
|
||||
}).subscribe({
|
||||
next: result => {
|
||||
this.clearDraft();
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'arcs', result.arcId, 'chapters', result.chapterId]);
|
||||
},
|
||||
error: () => {
|
||||
this.submitting = false;
|
||||
this.error = this.translate.instant('guided.createError');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async restart(): Promise<void> {
|
||||
const ok = await this.confirmDialog.confirm({
|
||||
title: this.translate.instant('guided.restartTitle'),
|
||||
message: this.translate.instant('guided.restartMessage'),
|
||||
confirmLabel: this.translate.instant('guided.restart')
|
||||
});
|
||||
if (!ok) return;
|
||||
this.clearDraft();
|
||||
this.answers = {};
|
||||
this.goTo(0);
|
||||
}
|
||||
|
||||
// --- Brouillon (confort par navigateur : jamais indispensable) -------------------------
|
||||
|
||||
private get storageKey(): string {
|
||||
return `loremind.guided.${this.campaignId}.${this.method?.id}`;
|
||||
}
|
||||
|
||||
private restoreDraft(): void {
|
||||
this.answers = {};
|
||||
this.stepIndex = 0;
|
||||
try {
|
||||
const raw = localStorage.getItem(this.storageKey);
|
||||
if (!raw) return;
|
||||
const saved = JSON.parse(raw) as { answers?: GuidedAnswers; step?: number };
|
||||
this.answers = saved.answers ?? {};
|
||||
this.stepIndex = Math.min(Math.max(saved.step ?? 0, 0), this.total - 1);
|
||||
} catch { /* brouillon illisible ou stockage bloqué : on repart de zéro */ }
|
||||
}
|
||||
|
||||
private saveDraft(): void {
|
||||
try {
|
||||
localStorage.setItem(this.storageKey, JSON.stringify({ answers: this.answers, step: this.stepIndex }));
|
||||
} catch { /* stockage indisponible : le brouillon n'est simplement pas gardé */ }
|
||||
}
|
||||
|
||||
private clearDraft(): void {
|
||||
try {
|
||||
localStorage.removeItem(this.storageKey);
|
||||
} catch { /* rien à nettoyer */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { SceneType } from '../../../services/campaign.model';
|
||||
import { GuidedSceneSpec } from '../../../services/guided-skeleton.model';
|
||||
import { GuidedAnswers, GuidedField, GuidedMethod, answer } from '../guided-method.model';
|
||||
|
||||
/**
|
||||
* « Donjon en 5 salles » (méthode popularisée par Johnn Four ; textes écrits pour
|
||||
* LoreMind). Une aventure courte en cinq temps : un gardien à l'entrée, une épreuve
|
||||
* qui ne se règle pas à l'épée, un revers, le climax, puis la récompense ou la
|
||||
* révélation. Le « donjon » peut être n'importe quel lieu : manoir, navire, forêt…
|
||||
*
|
||||
* Produit 1 chapitre (accroche, objectifs, enjeux) + 5 scènes typées dans le même lieu.
|
||||
*/
|
||||
|
||||
/** Champs communs à chaque salle : nom (pré-rempli), ce qui s'y passe, choix, secret du MJ. */
|
||||
function roomFields(room: number, extra: GuidedField[] = []): GuidedField[] {
|
||||
return [
|
||||
{ key: `room${room}.name`, kind: 'text', required: true, prefilled: true },
|
||||
...extra.filter(f => f.kind === 'choice'),
|
||||
{ key: `room${room}.description`, kind: 'textarea', coachTopic: 'scene.description' },
|
||||
...extra.filter(f => f.kind !== 'choice'),
|
||||
{ key: `room${room}.choices`, kind: 'textarea', coachTopic: 'scene.choices' },
|
||||
{ key: `room${room}.secret`, kind: 'textarea', coachTopic: 'scene.gmNotes' }
|
||||
];
|
||||
}
|
||||
|
||||
/** Nature de la salle (choix du MJ) → type de scène, pour que la relecture juge le rythme. */
|
||||
const NATURE_TO_TYPE: Record<string, SceneType> = {
|
||||
combat: 'ENCOUNTER',
|
||||
social: 'NPC',
|
||||
obstacle: 'LOCATION',
|
||||
puzzle: 'LOCATION',
|
||||
exploration: 'LOCATION'
|
||||
};
|
||||
|
||||
export const FIVE_ROOM_METHOD: GuidedMethod = {
|
||||
id: 'five-room',
|
||||
i18nKey: 'fiveRoom',
|
||||
steps: [
|
||||
{ id: 'placement', kind: 'placement' },
|
||||
{
|
||||
id: 'frame', kind: 'form', fields: [
|
||||
{ key: 'title', kind: 'text', required: true },
|
||||
{ key: 'location', kind: 'text', coachTopic: 'scene.setting' },
|
||||
{ key: 'hook', kind: 'textarea', coachTopic: 'chapter.synopsis' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'stakes', kind: 'form', fields: [
|
||||
{ key: 'objectives', kind: 'textarea', coachTopic: 'chapter.objectives' },
|
||||
{ key: 'stakes', kind: 'textarea', coachTopic: 'chapter.stakes' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'room1', kind: 'form', fields: roomFields(1, [
|
||||
{ key: 'room1.nature', kind: 'choice', options: ['combat', 'social', 'obstacle'] },
|
||||
{ key: 'room1.enemies', kind: 'text' }
|
||||
])
|
||||
},
|
||||
{
|
||||
id: 'room2', kind: 'form', fields: roomFields(2, [
|
||||
{ key: 'room2.nature', kind: 'choice', options: ['puzzle', 'social', 'exploration'] }
|
||||
])
|
||||
},
|
||||
{ id: 'room3', kind: 'form', fields: roomFields(3) },
|
||||
{
|
||||
id: 'room4', kind: 'form', fields: roomFields(4, [
|
||||
{ key: 'room4.enemies', kind: 'text', coachTopic: 'scene.combat' }
|
||||
])
|
||||
},
|
||||
{ id: 'room5', kind: 'form', fields: roomFields(5) },
|
||||
{ id: 'review', kind: 'review' }
|
||||
],
|
||||
|
||||
toDraft(answers: GuidedAnswers) {
|
||||
const location = answer(answers, 'location');
|
||||
const room = (n: number, type: SceneType): GuidedSceneSpec => ({
|
||||
name: answer(answers, `room${n}.name`) ?? '',
|
||||
description: answer(answers, `room${n}.description`),
|
||||
type,
|
||||
location,
|
||||
choicesConsequences: answer(answers, `room${n}.choices`),
|
||||
gmSecretNotes: answer(answers, `room${n}.secret`),
|
||||
enemies: answer(answers, `room${n}.enemies`)
|
||||
});
|
||||
return {
|
||||
chapter: {
|
||||
name: answer(answers, 'title') ?? '',
|
||||
description: answer(answers, 'hook'),
|
||||
playerObjectives: answer(answers, 'objectives'),
|
||||
narrativeStakes: answer(answers, 'stakes')
|
||||
},
|
||||
scenes: [
|
||||
room(1, NATURE_TO_TYPE[answers['room1.nature']] ?? 'ENCOUNTER'),
|
||||
room(2, NATURE_TO_TYPE[answers['room2.nature']] ?? 'LOCATION'),
|
||||
room(3, 'EVENT'),
|
||||
room(4, 'ENCOUNTER'),
|
||||
room(5, 'REVELATION')
|
||||
]
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -57,7 +57,11 @@ export class ItemCatalogViewComponent implements OnInit {
|
||||
map.get(cat)!.push(it);
|
||||
}
|
||||
return [...map.entries()]
|
||||
.sort(([a], [b]) => (a === '—' ? 1 : b === '—' ? -1 : a.localeCompare(b, 'fr')))
|
||||
.sort(([a], [b]) => {
|
||||
if (a === '—') return 1; // catégorie "sans catégorie" toujours en dernier
|
||||
if (b === '—') return -1;
|
||||
return a.localeCompare(b, 'fr');
|
||||
})
|
||||
.map(([category, items]) => ({ category, items }));
|
||||
}
|
||||
|
||||
|
||||
@@ -131,6 +131,6 @@
|
||||
[isOpen]="chatOpen"
|
||||
[welcomeMessage]="'npcEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
(closed)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
}
|
||||
|
||||
@@ -43,6 +43,6 @@
|
||||
entityType="npc"
|
||||
[entityId]="npcId"
|
||||
[isOpen]="chatOpen"
|
||||
(close)="chatOpen = false">
|
||||
(closed)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
}
|
||||
|
||||
@@ -15,6 +15,11 @@ import { Page } from '../../../services/page.model';
|
||||
import { PersonaViewComponent } from '../../../shared/persona-view/persona-view.component';
|
||||
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
||||
|
||||
/** Indexe des pages par id (les pages venant du serveur ont toujours un id). */
|
||||
function indexPagesById(pages: Page[]): Map<string, Page> {
|
||||
return new Map(pages.map(p => [p.id!, p]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Vue lecture seule "WorldAnvil" d'une fiche PNJ.
|
||||
* Route : /campaigns/:campaignId/npcs/:npcId
|
||||
@@ -89,7 +94,7 @@ export class NpcViewComponent implements OnInit, OnDestroy {
|
||||
if (camp.loreId) {
|
||||
this.loreId = camp.loreId;
|
||||
this.pageService.getByLoreId(camp.loreId).subscribe(pages => {
|
||||
this.lorePagesById = new Map(pages.map(p => [p.id!, p]));
|
||||
this.lorePagesById = indexPagesById(pages);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
+2
-4
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
@@ -34,7 +34,7 @@ import { SessionPrepPanelComponent } from '../../../shared/session-prep-panel/se
|
||||
templateUrl: './playthrough-detail.component.html',
|
||||
styleUrls: ['./playthrough-detail.component.scss']
|
||||
})
|
||||
export class PlaythroughDetailComponent implements OnInit, OnDestroy {
|
||||
export class PlaythroughDetailComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly Play = Play;
|
||||
readonly Flag = Flag;
|
||||
@@ -155,6 +155,4 @@ export class PlaythroughDetailComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {}
|
||||
}
|
||||
|
||||
+2
-4
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
@@ -26,7 +26,7 @@ import { PlaythroughFlagsManagerComponent } from '../../../shared/playthrough-fl
|
||||
templateUrl: './playthrough-flags-page.component.html',
|
||||
styleUrls: ['./playthrough-flags-page.component.scss']
|
||||
})
|
||||
export class PlaythroughFlagsPageComponent implements OnInit, OnDestroy {
|
||||
export class PlaythroughFlagsPageComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
|
||||
campaignId = '';
|
||||
@@ -75,6 +75,4 @@ export class PlaythroughFlagsPageComponent implements OnInit, OnDestroy {
|
||||
back(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
@@ -41,7 +41,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
templateUrl: './quest-edit.component.html',
|
||||
styleUrls: ['./quest-edit.component.scss']
|
||||
})
|
||||
export class QuestEditComponent implements OnInit, OnDestroy {
|
||||
export class QuestEditComponent implements OnInit {
|
||||
readonly Trash2 = Trash2;
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
selectedIcon: string | null = null;
|
||||
@@ -232,6 +232,4 @@ export class QuestEditComponent implements OnInit, OnDestroy {
|
||||
cancel(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'quests']);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
@@ -33,7 +33,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
templateUrl: './quest-view.component.html',
|
||||
styleUrls: ['./quest-view.component.scss']
|
||||
})
|
||||
export class QuestViewComponent implements OnInit, OnDestroy {
|
||||
export class QuestViewComponent implements OnInit {
|
||||
readonly Pencil = Pencil;
|
||||
readonly Trash2 = Trash2;
|
||||
readonly BookOpen = BookOpen;
|
||||
@@ -181,14 +181,32 @@ export class QuestViewComponent implements OnInit, OnDestroy {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'quests', this.questId, 'edit']);
|
||||
}
|
||||
|
||||
/** Suppression simple : une quête n'a pas d'enfants (les nœuds sont des références faibles). */
|
||||
/**
|
||||
* Suppression avec annonce de l'impact réel : le conteneur de scènes d'une quête
|
||||
* LIBRE (arc SYSTEM, invisible dans l'arbre) part en cascade avec ses scènes —
|
||||
* le nombre est affiché dans la confirmation. Les nœuds simplement liés et les
|
||||
* jumeaux de hub (qui restent visibles dans leur arc) ne sont pas concernés.
|
||||
*/
|
||||
deleteQuest(): void {
|
||||
if (!this.quest) return;
|
||||
const quest = this.quest;
|
||||
if (!quest?.id) return;
|
||||
this.questService.deletionImpact(this.campaignId, quest.id).subscribe({
|
||||
next: impact => this.confirmDeleteQuest(quest, impact.scenes),
|
||||
error: () => this.confirmDeleteQuest(quest, 0) // impact indisponible : confirmation simple
|
||||
});
|
||||
}
|
||||
|
||||
private confirmDeleteQuest(quest: Quest, scenes: number): void {
|
||||
const details = [
|
||||
...(scenes > 0
|
||||
? [this.translate.instant('questView.deleteImpactScenes', { count: scenes })]
|
||||
: []),
|
||||
this.translate.instant('questView.irreversible')
|
||||
];
|
||||
this.confirmDialog.confirm({
|
||||
title: this.translate.instant('questView.deleteTitle'),
|
||||
message: this.translate.instant('questView.deleteMessage', { name: quest.name }),
|
||||
details: [this.translate.instant('questView.irreversible')],
|
||||
details,
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
@@ -199,8 +217,4 @@ export class QuestViewComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant suivant.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
@@ -24,7 +24,7 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
templateUrl: './scene-create.component.html',
|
||||
styleUrls: ['./scene-create.component.scss']
|
||||
})
|
||||
export class SceneCreateComponent implements OnInit, OnDestroy {
|
||||
export class SceneCreateComponent implements OnInit {
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
selectedIcon: string | null = null;
|
||||
|
||||
@@ -90,11 +90,4 @@ export class SceneCreateComponent implements OnInit, OnDestroy {
|
||||
cancel(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@
|
||||
est dans des sections repliables avec pastille « rempli ». -->
|
||||
<p class="optional-hint">{{ 'sceneEdit.optionalHint' | translate }}</p>
|
||||
|
||||
<!-- Mentor d'écriture (M2) : conseils de relecture qui concernent cette entité. -->
|
||||
<app-writing-review-hints [campaignId]="campaignId" entityType="SCENE" [entityId]="sceneId"></app-writing-review-hints>
|
||||
|
||||
<!-- Co-création (Pilier A) : le co-MJ propose, l'utilisateur valide champ par champ.
|
||||
Les champs retenus remplissent le formulaire ; rien n'est enregistré avant la sauvegarde. -->
|
||||
<app-entity-assist-panel
|
||||
@@ -49,7 +52,10 @@
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="scene-edit-description">{{ 'sceneEdit.descriptionLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="scene-edit-description">{{ 'sceneEdit.descriptionLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="scene.description"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="scene-edit-description"
|
||||
formControlName="description"
|
||||
@@ -65,7 +71,10 @@
|
||||
|
||||
<!-- Type narratif du nœud (Niveau 2 — graphe de nœuds typés) -->
|
||||
<div class="field">
|
||||
<label for="scene-edit-type">{{ 'sceneEdit.nodeTypeLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="scene-edit-type">{{ 'sceneEdit.nodeTypeLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="scene.nodeType"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<select id="scene-edit-type" formControlName="type">
|
||||
@for (opt of sceneTypeOptions; track opt) {
|
||||
<option [value]="opt">{{ 'sceneType.' + opt | translate }}</option>
|
||||
@@ -181,7 +190,10 @@
|
||||
<app-expandable-section [title]="'sceneEdit.contextSectionTitle' | translate" icon="📍" [initiallyOpen]="true" [filled]="contextFilled">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="scene-edit-location">{{ 'sceneEdit.locationLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="scene-edit-location">{{ 'sceneEdit.locationLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="scene.setting"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<input id="scene-edit-location" type="text" formControlName="location" [placeholder]="'sceneEdit.locationPlaceholder' | translate" />
|
||||
</div>
|
||||
<div class="field">
|
||||
@@ -190,7 +202,10 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="scene-edit-atmosphere">{{ 'sceneEdit.atmosphereLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="scene-edit-atmosphere">{{ 'sceneEdit.atmosphereLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="scene.atmosphere"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="scene-edit-atmosphere"
|
||||
formControlName="atmosphere"
|
||||
@@ -201,7 +216,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Narration pour les joueurs -->
|
||||
<app-expandable-section [title]="'sceneEdit.narrationSectionTitle' | translate" icon="📖" [filled]="narrationFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.narrationSectionTitle' | translate" coachTopic="scene.narration" icon="📖" [initiallyOpen]="focusSection === 'narration'" [filled]="narrationFilled">
|
||||
<div class="field">
|
||||
<textarea
|
||||
formControlName="playerNarration"
|
||||
@@ -213,7 +228,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Notes et secrets du MJ (privé) -->
|
||||
<app-expandable-section [title]="'sceneEdit.gmNotesSectionTitle' | translate" icon="🔒" variant="private" [filled]="gmNotesFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.gmNotesSectionTitle' | translate" coachTopic="scene.gmNotes" icon="🔒" variant="private" [filled]="gmNotesFilled">
|
||||
<div class="field">
|
||||
<textarea
|
||||
formControlName="gmSecretNotes"
|
||||
@@ -225,7 +240,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Choix et conséquences -->
|
||||
<app-expandable-section [title]="'sceneEdit.choicesSectionTitle' | translate" icon="🔀" [filled]="choicesFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.choicesSectionTitle' | translate" coachTopic="scene.choices" icon="🔀" [initiallyOpen]="focusSection === 'choices'" [filled]="choicesFilled">
|
||||
<div class="field">
|
||||
<textarea
|
||||
formControlName="choicesConsequences"
|
||||
@@ -236,7 +251,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Branches narratives (graphe intra-chapitre) -->
|
||||
<app-expandable-section [title]="'sceneEdit.branchesSectionTitle' | translate" icon="🌿" [initiallyOpen]="focusSection === 'branches'" [filled]="branchesFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.branchesSectionTitle' | translate" coachTopic="scene.branches" icon="🌿" [initiallyOpen]="focusSection === 'branches'" [filled]="branchesFilled">
|
||||
@if (siblingScenes.length === 0) {
|
||||
<div class="branches-hint">
|
||||
<small class="field-hint">
|
||||
@@ -307,7 +322,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Combat ou rencontre -->
|
||||
<app-expandable-section [title]="'sceneEdit.combatSectionTitle' | translate" icon="⚔️" [initiallyOpen]="focusSection === 'combat'" [filled]="combatFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.combatSectionTitle' | translate" coachTopic="scene.combat" icon="⚔️" [initiallyOpen]="focusSection === 'combat'" [filled]="combatFilled">
|
||||
<div class="field">
|
||||
<label for="scene-edit-combat-difficulty">{{ 'sceneEdit.combatDifficultyLabel' | translate }}</label>
|
||||
<input id="scene-edit-combat-difficulty" type="text" formControlName="combatDifficulty" [placeholder]="'sceneEdit.combatDifficultyPlaceholder' | translate" />
|
||||
@@ -385,5 +400,5 @@
|
||||
[isOpen]="chatOpen"
|
||||
[welcomeMessage]="'sceneEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
(closed)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
@@ -31,6 +31,8 @@ import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
import { FileDropDirective } from '../../../shared/file-drop.directive';
|
||||
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { WritingReviewHintsComponent } from '../../../shared/writing-review/writing-review-hints.component';
|
||||
|
||||
/**
|
||||
* État d'édition d'UNE battlemap de la scène (une carte par variante : Jour, Nuit,
|
||||
@@ -63,11 +65,11 @@ interface BattlemapEdit {
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-scene-edit',
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, ExpandableSectionComponent, LoreLinkPickerComponent, EnemyLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, RoomsEditorComponent, EntityAssistPanelComponent, FileDropDirective, TranslatePipe],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, ExpandableSectionComponent, LoreLinkPickerComponent, EnemyLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, RoomsEditorComponent, EntityAssistPanelComponent, FileDropDirective, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent],
|
||||
templateUrl: './scene-edit.component.html',
|
||||
styleUrls: ['./scene-edit.component.scss']
|
||||
})
|
||||
export class SceneEditComponent implements OnInit, OnDestroy {
|
||||
export class SceneEditComponent implements OnInit {
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Sparkles = Sparkles;
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
@@ -95,7 +97,7 @@ export class SceneEditComponent implements OnInit, OnDestroy {
|
||||
scene: Scene | null = null;
|
||||
|
||||
/**
|
||||
* Section à déplier d'office (query param `?focus=combat|branches|rooms`) — posé par
|
||||
* Section à déplier d'office (query param `?focus=combat|branches|rooms|narration|choices`) — posé par
|
||||
* le bouton « Corriger » du guidage pour atterrir directement sur l'outil fautif.
|
||||
*/
|
||||
focusSection: string | null = null;
|
||||
@@ -251,7 +253,7 @@ export class SceneEditComponent implements OnInit, OnDestroy {
|
||||
};
|
||||
if (entry.mediaFileId) {
|
||||
this.storedFileService.getById(entry.mediaFileId)
|
||||
.subscribe({ next: f => entry.mediaName = f.filename, error: () => {} });
|
||||
.subscribe({ next: f => entry.mediaName = f.filename, error: () => { /* best-effort : erreur ignorée volontairement */ } });
|
||||
}
|
||||
if (entry.dataFileId) {
|
||||
this.storedFileService.getById(entry.dataFileId).subscribe({
|
||||
@@ -260,7 +262,7 @@ export class SceneEditComponent implements OnInit, OnDestroy {
|
||||
// Deduit la source : un .dd2vtt/.uvtt => DungeonDraft.
|
||||
if (/\.(dd2vtt|uvtt)$/i.test(f.filename)) entry.source = 'DUNGEONDRAFT';
|
||||
},
|
||||
error: () => {}
|
||||
error: () => { /* best-effort : erreur ignorée volontairement */ }
|
||||
});
|
||||
}
|
||||
return entry;
|
||||
@@ -480,12 +482,14 @@ export class SceneEditComponent implements OnInit, OnDestroy {
|
||||
onDd2vttSelected(bm: BattlemapEdit, event: Event): void {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (file) void this.uploadDd2vtt(bm, file);
|
||||
// Fire-and-forget : uploadDd2vtt gère lui-même ses erreurs.
|
||||
if (file) this.uploadDd2vtt(bm, file);
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
onDd2vttDropped(bm: BattlemapEdit, files: File[]): void {
|
||||
if (files[0]) void this.uploadDd2vtt(bm, files[0]);
|
||||
// Fire-and-forget : uploadDd2vtt gère lui-même ses erreurs.
|
||||
if (files[0]) this.uploadDd2vtt(bm, files[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -552,13 +556,7 @@ export class SceneEditComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private extForType(type: string): string {
|
||||
return type === 'image/jpeg' ? '.jpg' : type === 'image/webp' ? '.webp' : '.png';
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
if (type === 'image/jpeg') return '.jpg';
|
||||
return type === 'image/webp' ? '.webp' : '.png';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
@@ -31,7 +31,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
templateUrl: './scene-view.component.html',
|
||||
styleUrls: ['./scene-view.component.scss']
|
||||
})
|
||||
export class SceneViewComponent implements OnInit, OnDestroy {
|
||||
export class SceneViewComponent implements OnInit {
|
||||
readonly Pencil = Pencil;
|
||||
readonly Trash2 = Trash2;
|
||||
readonly resolveCampaignIcon = resolveCampaignIcon;
|
||||
@@ -160,11 +160,4 @@ export class SceneViewComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { WritingRemark } from '../services/writing-review.model';
|
||||
import { GapAction } from './gap-action.helper';
|
||||
|
||||
/**
|
||||
* Lien « Voir » d'une remarque de relecture : ouvre l'éditeur concerné avec la
|
||||
* section en cause dépliée (`?focus=…`), comme le « Corriger » du readiness.
|
||||
*/
|
||||
export function remarkAction(remark: WritingRemark, campaignId: string): GapAction {
|
||||
const base = ['/campaigns', campaignId];
|
||||
const focus = FOCUS_BY_RULE[remark.ruleId];
|
||||
const queryParams = focus ? { focus } : undefined;
|
||||
switch (remark.entityType) {
|
||||
case 'SCENE':
|
||||
return {
|
||||
link: [...base, 'arcs', remark.arcId ?? '', 'chapters', remark.chapterId ?? '', 'scenes', remark.entityId, 'edit'],
|
||||
queryParams
|
||||
};
|
||||
case 'CHAPTER':
|
||||
// Couloir / rythme : c'est l'enchaînement des scènes qu'il faut voir (vue du chapitre).
|
||||
if (!focus) return { link: [...base, 'arcs', remark.arcId ?? '', 'chapters', remark.entityId] };
|
||||
return { link: [...base, 'arcs', remark.arcId ?? '', 'chapters', remark.entityId, 'edit'], queryParams };
|
||||
case 'ARC':
|
||||
return { link: [...base, 'arcs', remark.entityId, 'edit'], queryParams };
|
||||
default:
|
||||
return { link: base };
|
||||
}
|
||||
}
|
||||
|
||||
/** Section de l'éditeur à déplier selon la règle (clé = ruleId complet). */
|
||||
const FOCUS_BY_RULE: Record<string, string> = {
|
||||
'WRITE-002-FAKE-CHOICE': 'branches',
|
||||
'WRITE-003-SINGLE-CLUE': 'branches',
|
||||
'WRITE-005-NO-STAKES': 'stakes',
|
||||
'WRITE-006-LONG-NARRATION': 'narration',
|
||||
'WRITE-007-NARRATION-DECIDES': 'narration',
|
||||
'WRITE-008-COMBAT-NO-PURPOSE': 'combat',
|
||||
'WRITE-009-SINGLE-ENDING': 'choices'
|
||||
};
|
||||
@@ -361,7 +361,10 @@ export class GameSystemEditComponent implements OnInit {
|
||||
};
|
||||
|
||||
for (const line of lines) {
|
||||
const match = line.match(/^##\s+(.+?)\s*$/);
|
||||
// `\S` force un début de titre non-blanc : frontière déterministe entre
|
||||
// `\s+` et la capture (l'ancien `.+?`+`\s*$` backtrackait). Le trim()
|
||||
// en aval retire les espaces de fin.
|
||||
const match = line.match(/^##\s+(\S.*)$/);
|
||||
if (match) {
|
||||
flush();
|
||||
current = { title: match[1].trim(), content: '', collapsed: false };
|
||||
|
||||
@@ -154,10 +154,14 @@ export class BlockGridBuilderComponent implements OnDestroy {
|
||||
|
||||
addLabel(block: TemplateField): void { block.labels = [...(block.labels ?? []), '']; this.emit(); }
|
||||
updateLabel(block: TemplateField, i: number, value: string): void {
|
||||
if (!block.labels) return; block.labels[i] = value; this.emit();
|
||||
if (!block.labels) return;
|
||||
block.labels[i] = value;
|
||||
this.emit();
|
||||
}
|
||||
removeLabel(block: TemplateField, i: number): void {
|
||||
if (!block.labels) return; block.labels = block.labels.filter((_, k) => k !== i); this.emit();
|
||||
if (!block.labels) return;
|
||||
block.labels = block.labels.filter((_, k) => k !== i);
|
||||
this.emit();
|
||||
}
|
||||
|
||||
// --- Glisser : création / déplacement / redimensionnement ---------------
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnDestroy, OnInit, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin } from 'rxjs';
|
||||
@@ -33,7 +33,7 @@ import { ConfirmDialogService } from '../../shared/confirm-dialog/confirm-dialog
|
||||
templateUrl: './folder-view.component.html',
|
||||
styleUrls: ['./folder-view.component.scss']
|
||||
})
|
||||
export class FolderViewComponent implements OnInit, OnDestroy {
|
||||
export class FolderViewComponent implements OnInit {
|
||||
readonly Folder = Folder;
|
||||
readonly FileText = FileText;
|
||||
readonly Pencil = Pencil;
|
||||
@@ -237,11 +237,4 @@ export class FolderViewComponent implements OnInit, OnDestroy {
|
||||
error: () => console.error('Impossible de récupérer les dépendances du dossier')
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { TranslatePipe } from '@ngx-translate/core';
|
||||
styleUrls: ['./lore-create.component.scss']
|
||||
})
|
||||
export class LoreCreateComponent {
|
||||
@Output() close = new EventEmitter<void>();
|
||||
@Output() closed = new EventEmitter<void>();
|
||||
@Output() created = new EventEmitter<{ name: string; description: string }>();
|
||||
|
||||
readonly BookCopy = BookCopy;
|
||||
@@ -32,6 +32,6 @@ export class LoreCreateComponent {
|
||||
}
|
||||
|
||||
onCancel(): void {
|
||||
this.close.emit();
|
||||
this.closed.emit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
@@ -11,7 +11,7 @@ import { LayoutService } from '../../services/layout.service';
|
||||
import { LoreNode } from '../../services/lore.model';
|
||||
import { loadLoreSidebarData, buildLoreSidebarConfig } from '../lore-sidebar.helper';
|
||||
import { popReturnTo } from '../return-stack.helper';
|
||||
import { LORE_ICON_OPTIONS, IconOption, resolveIcon } from '../lore-icons';
|
||||
import { LORE_ICON_OPTIONS, IconOption } from '../lore-icons';
|
||||
|
||||
@Component({
|
||||
selector: 'app-lore-node-create',
|
||||
@@ -19,7 +19,7 @@ import { LORE_ICON_OPTIONS, IconOption, resolveIcon } from '../lore-icons';
|
||||
templateUrl: './lore-node-create.component.html',
|
||||
styleUrls: ['./lore-node-create.component.scss']
|
||||
})
|
||||
export class LoreNodeCreateComponent implements OnInit, OnDestroy {
|
||||
export class LoreNodeCreateComponent implements OnInit {
|
||||
|
||||
readonly iconOptions: IconOption[] = LORE_ICON_OPTIONS;
|
||||
|
||||
@@ -109,11 +109,4 @@ export class LoreNodeCreateComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
this.router.navigate(['/lore', this.loreId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
@@ -38,7 +38,7 @@ import { LORE_ICON_OPTIONS, IconOption } from '../lore-icons';
|
||||
templateUrl: './lore-node-edit.component.html',
|
||||
styleUrls: ['./lore-node-edit.component.scss']
|
||||
})
|
||||
export class LoreNodeEditComponent implements OnInit, OnDestroy {
|
||||
export class LoreNodeEditComponent implements OnInit {
|
||||
|
||||
readonly iconOptions: IconOption[] = LORE_ICON_OPTIONS;
|
||||
|
||||
@@ -147,11 +147,4 @@ export class LoreNodeEditComponent implements OnInit, OnDestroy {
|
||||
if (!key) return null;
|
||||
return this.iconOptions.find(o => o.key === key)?.icon ?? null;
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
|
||||
@if (showCreateModal) {
|
||||
<app-lore-create
|
||||
(close)="onModalClose()"
|
||||
(closed)="onModalClose()"
|
||||
(created)="onLoreCreated($event)">
|
||||
</app-lore-create>
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@
|
||||
[systemPromptAddon]="wizardSystemPrompt"
|
||||
[quickSuggestions]="wizardSuggestions"
|
||||
[primaryAction]="wizardPrimaryAction"
|
||||
(close)="closeWizard()"
|
||||
(closed)="closeWizard()"
|
||||
(assistantReply)="onWizardReply($event)"
|
||||
(primaryActionClick)="applyWizardAndCreate()">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
@@ -32,7 +32,7 @@ import { AiChatDrawerComponent, ChatPrimaryAction } from '../../shared/ai-chat-d
|
||||
templateUrl: './page-create.component.html',
|
||||
styleUrls: ['./page-create.component.scss']
|
||||
})
|
||||
export class PageCreateComponent implements OnInit, OnDestroy {
|
||||
export class PageCreateComponent implements OnInit {
|
||||
readonly FileText = FileText;
|
||||
readonly Sparkles = Sparkles;
|
||||
readonly Plus = Plus;
|
||||
@@ -165,7 +165,7 @@ export class PageCreateComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private restoreDraft(): void {
|
||||
let raw: string | null = null;
|
||||
let raw: string | null;
|
||||
try { raw = sessionStorage.getItem(this.draftKey); } catch { return; }
|
||||
if (!raw) return;
|
||||
sessionStorage.removeItem(this.draftKey);
|
||||
@@ -328,7 +328,9 @@ Les clés du JSON doivent correspondre EXACTEMENT aux noms de champs indiqués.
|
||||
* Retourne null si absent ou JSON invalide.
|
||||
*/
|
||||
private extractValuesBlock(reply: string): Record<string, string> | null {
|
||||
const match = reply.match(/<values>\s*([\s\S]*?)\s*<\/values>/i);
|
||||
// Pas de \s* autour de la capture (backtracking quadratique) :
|
||||
// JSON.parse tolère nativement les blancs en tête/queue.
|
||||
const match = reply.match(/<values>([\s\S]*?)<\/values>/i);
|
||||
if (!match) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]) as Record<string, unknown>;
|
||||
@@ -342,11 +344,4 @@ Les clés du JSON doivent correspondre EXACTEMENT aux noms de champs indiqués.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,6 +195,6 @@
|
||||
[isOpen]="chatOpen"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
[primaryAction]="chatPrimaryAction"
|
||||
(close)="chatOpen = false"
|
||||
(closed)="chatOpen = false"
|
||||
(primaryActionClick)="onChatFillRequested()">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { FormsModule } from '@angular/forms';
|
||||
@@ -44,7 +44,7 @@ import { ConfirmDialogService } from '../../shared/confirm-dialog/confirm-dialog
|
||||
templateUrl: './page-edit.component.html',
|
||||
styleUrls: ['./page-edit.component.scss']
|
||||
})
|
||||
export class PageEditComponent implements OnInit, OnDestroy {
|
||||
export class PageEditComponent implements OnInit {
|
||||
readonly Sparkles = Sparkles;
|
||||
readonly Plus = Plus;
|
||||
readonly Trash2 = Trash2;
|
||||
@@ -84,7 +84,7 @@ export class PageEditComponent implements OnInit, OnDestroy {
|
||||
/** Valeurs des champs KEY_VALUE_LIST (liste clé/valeur) : fieldName → (label → valeur). */
|
||||
keyValueValues: Record<string, Record<string, string>> = {};
|
||||
/** Valeurs des champs TABLE : fieldName → lignes (colonne → cellule). */
|
||||
tableValues: Record<string, Array<Record<string, string>>> = {};
|
||||
tableValues: Record<string, Record<string, string>[]> = {};
|
||||
/** Étiquettes libres (Phase 5B). */
|
||||
tags: string[] = [];
|
||||
/** IDs des pages liées (Phase 5B). */
|
||||
@@ -200,7 +200,7 @@ export class PageEditComponent implements OnInit, OnDestroy {
|
||||
const imageBase: Record<string, string[]> = {};
|
||||
const framingBase: Record<string, Record<string, ImageFraming>> = {};
|
||||
const kvBase: Record<string, Record<string, string>> = {};
|
||||
const tableBase: Record<string, Array<Record<string, string>>> = {};
|
||||
const tableBase: Record<string, Record<string, string>[]> = {};
|
||||
// Les valeurs sont rangées par clé STABLE (id) ; on relit d'abord par clé,
|
||||
// puis par nom (pages dont les valeurs étaient encore rangées par nom — elles
|
||||
// sont ainsi migrées vers la clé id à la prochaine sauvegarde).
|
||||
@@ -259,7 +259,9 @@ export class PageEditComponent implements OnInit, OnDestroy {
|
||||
addTableRow(fieldName: string, columns: string[] | null | undefined): void {
|
||||
const row: Record<string, string> = {};
|
||||
for (const col of columns ?? []) row[col] = '';
|
||||
(this.tableValues[fieldName] ??= []).push(row);
|
||||
const rows = this.tableValues[fieldName] ?? [];
|
||||
rows.push(row);
|
||||
this.tableValues[fieldName] = rows;
|
||||
}
|
||||
|
||||
removeTableRow(fieldName: string, rowIndex: number): void {
|
||||
@@ -267,7 +269,7 @@ export class PageEditComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
/** Lignes du tableau d'un champ — toujours un tableau (jamais undefined) pour le `@for`. */
|
||||
tableRows(fieldName: string): Array<Record<string, string>> {
|
||||
tableRows(fieldName: string): Record<string, string>[] {
|
||||
return this.tableValues[fieldName] ?? [];
|
||||
}
|
||||
|
||||
@@ -343,11 +345,4 @@ export class PageEditComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
@@ -36,7 +36,7 @@ import { ConfirmDialogService } from '../../shared/confirm-dialog/confirm-dialog
|
||||
templateUrl: './page-view.component.html',
|
||||
styleUrls: ['./page-view.component.scss']
|
||||
})
|
||||
export class PageViewComponent implements OnInit, OnDestroy {
|
||||
export class PageViewComponent implements OnInit {
|
||||
readonly Pencil = Pencil;
|
||||
readonly Trash2 = Trash2;
|
||||
|
||||
@@ -155,7 +155,7 @@ export class PageViewComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
/** Lignes d'un champ TABLE (liste vide si jamais rempli). */
|
||||
tableRowsOf(field: TemplateField): Array<Record<string, string>> {
|
||||
tableRowsOf(field: TemplateField): Record<string, string>[] {
|
||||
const v = this.page?.tableValues;
|
||||
return v?.[blockKey(field)] ?? v?.[field.name] ?? [];
|
||||
}
|
||||
@@ -196,11 +196,4 @@ export class PageViewComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
@@ -24,7 +24,7 @@ import { popReturnTo } from '../return-stack.helper';
|
||||
templateUrl: './template-create.component.html',
|
||||
styleUrls: ['./template-create.component.scss']
|
||||
})
|
||||
export class TemplateCreateComponent implements OnInit, OnDestroy {
|
||||
export class TemplateCreateComponent implements OnInit {
|
||||
form: FormGroup;
|
||||
loreId = '';
|
||||
nodes: LoreNode[] = [];
|
||||
@@ -85,7 +85,7 @@ export class TemplateCreateComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private restoreDraft(): void {
|
||||
let raw: string | null = null;
|
||||
let raw: string | null;
|
||||
try { raw = sessionStorage.getItem(this.draftKey); } catch { return; }
|
||||
if (!raw) return;
|
||||
sessionStorage.removeItem(this.draftKey);
|
||||
@@ -146,11 +146,4 @@ export class TemplateCreateComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
this.router.navigate(['/lore', this.loreId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { SceneType } from './campaign.model';
|
||||
|
||||
/**
|
||||
* Squelette d'aventure produit par une méthode guidée (Mentor d'écriture, phase M3),
|
||||
* envoyé à POST /api/campaigns/{id}/guided-skeleton. Miroir du record Java `GuidedSkeleton`.
|
||||
*/
|
||||
export interface GuidedChapterSpec {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
playerObjectives?: string | null;
|
||||
narrativeStakes?: string | null;
|
||||
}
|
||||
|
||||
export interface GuidedSceneSpec {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
type: SceneType;
|
||||
location?: string | null;
|
||||
choicesConsequences?: string | null;
|
||||
gmSecretNotes?: string | null;
|
||||
enemies?: string | null;
|
||||
}
|
||||
|
||||
export interface GuidedSkeleton {
|
||||
/** Arc linéaire existant… */
|
||||
arcId?: string | null;
|
||||
/** …ou nom du nouvel arc (exactement l'un des deux). */
|
||||
newArcName?: string | null;
|
||||
chapter: GuidedChapterSpec;
|
||||
scenes: GuidedSceneSpec[];
|
||||
linkSequentially: boolean;
|
||||
linkLabel?: string | null;
|
||||
}
|
||||
|
||||
export interface GuidedSkeletonResult {
|
||||
arcId: string;
|
||||
chapterId: string;
|
||||
sceneIds: string[];
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { GuidedSkeleton, GuidedSkeletonResult } from './guided-skeleton.model';
|
||||
|
||||
/** Service HTTP des méthodes guidées (Mentor d'écriture, phase M3). */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class GuidedSkeletonService {
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
create(campaignId: string, skeleton: GuidedSkeleton): Observable<GuidedSkeletonResult> {
|
||||
return this.http.post<GuidedSkeletonResult>(`/api/campaigns/${campaignId}/guided-skeleton`, skeleton);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, catchError, of } from 'rxjs';
|
||||
import { Observable, catchError, map, of } from 'rxjs';
|
||||
|
||||
/**
|
||||
* Reflet de LicenseStatus (enum cote backend).
|
||||
@@ -44,13 +44,13 @@ export interface BetaStatusDTO {
|
||||
enabled: boolean;
|
||||
updateAvailable: boolean;
|
||||
anyUnknown: boolean;
|
||||
images: Array<{
|
||||
images: {
|
||||
image: string;
|
||||
localVersion: string | null;
|
||||
remoteVersion: string | null;
|
||||
status: 'UP_TO_DATE' | 'UPDATE_AVAILABLE' | 'UNKNOWN';
|
||||
updateAvailable: boolean;
|
||||
}>;
|
||||
}[];
|
||||
checkedAt: string;
|
||||
disabledReason: string | null;
|
||||
}
|
||||
@@ -86,10 +86,13 @@ export class LicenseService {
|
||||
|
||||
disconnect(): Observable<boolean> {
|
||||
return this.http.delete<void>(this.apiUrl, this.authOptions).pipe(
|
||||
// Convertit en boolean : true = succes, false = erreur
|
||||
// (catchError plus bas masque les detail HTTP)
|
||||
catchError(() => of(false as any))
|
||||
) as unknown as Observable<boolean>;
|
||||
// Convertit en boolean : true = succes, false = erreur.
|
||||
// (Avant : le cast `as unknown as` masquait l'absence de map() — le
|
||||
// succes emettait `undefined`, donc falsy. Consommateur actuel ignore
|
||||
// la valeur, mais le type est desormais honnete.)
|
||||
map(() => true),
|
||||
catchError(() => of(false))
|
||||
);
|
||||
}
|
||||
|
||||
refresh(): Observable<LicenseStatusDTO | null> {
|
||||
|
||||
@@ -48,7 +48,9 @@ export interface NotebookAction {
|
||||
resolution?: string;
|
||||
}
|
||||
|
||||
const ACTION_RE = /```loremind-action\s*([\s\S]*?)```/g;
|
||||
// Pas de \s* avant la capture (backtracking quadratique) : la capture est
|
||||
// trim()ée avant JSON.parse de toute façon.
|
||||
const ACTION_RE = /```loremind-action([\s\S]*?)```/g;
|
||||
const VALID_TYPES = new Set(['npc', 'scene', 'chapter', 'arc', 'table']);
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,6 +6,13 @@ import { Notebook, NotebookArchive, NotebookDetail, NotebookSource, NotebookChat
|
||||
import { LanguageService } from './language.service';
|
||||
import { parseSseStream } from '../shared/sse.util';
|
||||
|
||||
/** Normalise les sources renvoyées par le Brain (événement SSE `sources`). */
|
||||
function mapSseSources(sources: { source_id?: string; page?: number | null; score?: number }[] | undefined) {
|
||||
return (sources ?? []).map(s => ({
|
||||
sourceId: s.source_id ?? '', page: s.page ?? null, score: s.score ?? 0
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Service des notebooks (atelier RAG) : CRUD, upload/indexation de sources,
|
||||
* et chat ancré STREAMÉ (SSE via fetch, comme ai-chat.service).
|
||||
@@ -96,12 +103,7 @@ export class NotebookService {
|
||||
} else if (event === 'sources') {
|
||||
try {
|
||||
const o = JSON.parse(data) as { sources?: { source_id?: string; page?: number | null; score?: number }[] };
|
||||
emit({
|
||||
type: 'sources',
|
||||
sources: (o.sources ?? []).map(s => ({
|
||||
sourceId: s.source_id ?? '', page: s.page ?? null, score: s.score ?? 0
|
||||
}))
|
||||
});
|
||||
emit({ type: 'sources', sources: mapSseSources(o.sources) });
|
||||
} catch { /* ignore */ }
|
||||
} else if (event === 'progress') {
|
||||
try {
|
||||
|
||||
@@ -40,7 +40,7 @@ export interface Page {
|
||||
* Pour chaque champ TABLE (colonnes figees au template, lignes libres) :
|
||||
* fieldName → lignes ordonnees, chaque ligne = colonne → cellule.
|
||||
*/
|
||||
tableValues?: Record<string, Array<Record<string, string>>>;
|
||||
tableValues?: Record<string, Record<string, string>[]>;
|
||||
notes?: string | null;
|
||||
tags?: string[];
|
||||
relatedPageIds?: string[];
|
||||
|
||||
@@ -3,6 +3,11 @@ import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Quest, QuestCreate } from './campaign.model';
|
||||
|
||||
/** Impact d'une suppression : scènes du conteneur (quête libre) qui partiront avec. */
|
||||
export interface QuestDeletionImpact {
|
||||
scenes: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service HTTP pour les Quêtes (Niveau 1). API nestée sous la campagne :
|
||||
* /api/campaigns/{campaignId}/quests. Si {@code playthroughId} est fourni, les
|
||||
@@ -39,6 +44,10 @@ export class QuestService {
|
||||
return this.http.delete<void>(`${this.base(campaignId)}/${questId}`);
|
||||
}
|
||||
|
||||
deletionImpact(campaignId: string, questId: string): Observable<QuestDeletionImpact> {
|
||||
return this.http.get<QuestDeletionImpact>(`${this.base(campaignId)}/${questId}/deletion-impact`);
|
||||
}
|
||||
|
||||
reorder(campaignId: string, orderedIds: string[]): Observable<void> {
|
||||
return this.http.put<void>(`${this.base(campaignId)}/reorder`, { orderedIds });
|
||||
}
|
||||
|
||||
@@ -46,9 +46,10 @@ export class VersionCheckerService {
|
||||
*/
|
||||
start(): void {
|
||||
if (this.timer !== null) return;
|
||||
void this.fetchInitial();
|
||||
// Fire-and-forget : fetchInitial/poll gèrent leurs erreurs en interne.
|
||||
this.fetchInitial();
|
||||
this.timer = setInterval(
|
||||
() => void this.poll(),
|
||||
() => { this.poll(); },
|
||||
VersionCheckerService.POLL_INTERVAL_MS,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { ReadinessEntityType } from './readiness.model';
|
||||
|
||||
/**
|
||||
* Modèles de la relecture d'éditeur (Mentor d'écriture, phase M2) renvoyés par
|
||||
* GET /api/campaigns/{id}/writing-review. Le back renvoie la règle et ses paramètres ;
|
||||
* le texte (observation / pourquoi / question) vient de l'i18n `writingReview.rules.<ruleId>`.
|
||||
*/
|
||||
|
||||
export type WritingRemarkCategory = 'AGENCY' | 'PACING' | 'STAKES' | 'NARRATION';
|
||||
|
||||
export interface WritingRemark {
|
||||
entityType: ReadinessEntityType;
|
||||
entityId: string;
|
||||
entityName?: string | null;
|
||||
ruleId: string;
|
||||
category: WritingRemarkCategory;
|
||||
/** Valeurs injectées dans le texte i18n (count, phrase, target…). */
|
||||
params: Record<string, string>;
|
||||
arcId?: string | null;
|
||||
chapterId?: string | null;
|
||||
}
|
||||
|
||||
export interface WritingReviewReport {
|
||||
campaignId: string;
|
||||
remarks: WritingRemark[];
|
||||
}
|
||||
|
||||
/** Ordre d'affichage des familles de remarques. */
|
||||
export const WRITING_REMARK_CATEGORIES: WritingRemarkCategory[] = ['AGENCY', 'STAKES', 'PACING', 'NARRATION'];
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { WritingReviewReport } from './writing-review.model';
|
||||
|
||||
/**
|
||||
* Service HTTP de la relecture d'éditeur (Mentor d'écriture, phase M2).
|
||||
* Read-model pur, déterministe, sans effet de bord.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class WritingReviewService {
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
getReview(campaignId: string): Observable<WritingReviewReport> {
|
||||
return this.http.get<WritingReviewReport>(`/api/campaigns/${campaignId}/writing-review`);
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
name="editName"
|
||||
(keydown.enter)="saveRename()"
|
||||
(keydown.escape)="cancelRename()"
|
||||
autofocus />
|
||||
/>
|
||||
<button type="button" class="btn-icon" (click)="saveRename()" [disabled]="!editName.trim()" [title]="'common.validate' | translate">
|
||||
<lucide-icon [img]="Check" [size]="14"></lucide-icon>
|
||||
</button>
|
||||
|
||||
@@ -281,11 +281,14 @@ export class SessionDetailComponent implements OnInit, OnDestroy {
|
||||
if (!this.session) return;
|
||||
const session = this.session;
|
||||
const entryCount = this.entries.length;
|
||||
const entriesDetail = entryCount === 0
|
||||
? this.translate.instant('sessionDetail.deleteConfirm.noEntries')
|
||||
: entryCount === 1
|
||||
? this.translate.instant('sessionDetail.deleteConfirm.entriesOne')
|
||||
: this.translate.instant('sessionDetail.deleteConfirm.entriesMany', { n: entryCount });
|
||||
let entriesDetail: string;
|
||||
if (entryCount === 0) {
|
||||
entriesDetail = this.translate.instant('sessionDetail.deleteConfirm.noEntries');
|
||||
} else if (entryCount === 1) {
|
||||
entriesDetail = this.translate.instant('sessionDetail.deleteConfirm.entriesOne');
|
||||
} else {
|
||||
entriesDetail = this.translate.instant('sessionDetail.deleteConfirm.entriesMany', { n: entryCount });
|
||||
}
|
||||
const details = [
|
||||
entriesDetail,
|
||||
this.translate.instant('sessionDetail.deleteConfirm.irreversible')
|
||||
|
||||
@@ -58,7 +58,9 @@ export class SessionDicePanelComponent {
|
||||
}
|
||||
const sumRolls = rolls.reduce((s, n) => s + n, 0);
|
||||
const total = sumRolls + this.modifier;
|
||||
const modPart = this.modifier === 0 ? '' : (this.modifier > 0 ? `+${this.modifier}` : `${this.modifier}`);
|
||||
let modPart = '';
|
||||
if (this.modifier > 0) modPart = `+${this.modifier}`;
|
||||
else if (this.modifier < 0) modPart = `${this.modifier}`;
|
||||
const notation = `${safeCount}d${this.selectedFace}${modPart}`;
|
||||
const detailsPart = rolls.length > 1 ? ` [${rolls.join(', ')}]` : '';
|
||||
const summary = `🎲 ${notation}${detailsPart} = ${total}`;
|
||||
|
||||
+5
-1
@@ -52,7 +52,11 @@ export class SessionItemCatalogsPanelComponent implements OnInit {
|
||||
map.get(cat)!.push(it);
|
||||
}
|
||||
return [...map.entries()]
|
||||
.sort(([a], [b]) => (a === '—' ? 1 : b === '—' ? -1 : a.localeCompare(b, 'fr')))
|
||||
.sort(([a], [b]) => {
|
||||
if (a === '—') return 1; // catégorie "sans catégorie" toujours en dernier
|
||||
if (b === '—') return -1;
|
||||
return a.localeCompare(b, 'fr');
|
||||
})
|
||||
.map(([category, items]) => ({ category, items }));
|
||||
}
|
||||
|
||||
|
||||
@@ -209,9 +209,10 @@ export class OllamaModelManagerComponent implements OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private extractError(err: any, fallback: string): string {
|
||||
if (err?.error?.detail) return String(err.error.detail);
|
||||
if (err?.message) return err.message;
|
||||
private extractError(err: unknown, fallback: string): string {
|
||||
const e = err as { error?: { detail?: unknown }; message?: string } | null;
|
||||
if (e?.error?.detail) return String(e.error.detail);
|
||||
if (e?.message) return e.message;
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user