From c2f162d8231110f129491d6db9be4f65376cc1f2 Mon Sep 17 00:00:00 2001 From: "IETM_FIXE\\ietm6" Date: Sat, 17 Oct 2026 11:58:26 +0200 Subject: [PATCH] =?UTF-8?q?Mentor=20d'=C3=A9criture=20(M1-M3)=20:=20coach?= =?UTF-8?q?=20dans=20les=20champs,=20relecture=20d'=C3=A9diteur,=20m=C3=A9?= =?UTF-8?q?thode=20guid=C3=A9e=20=C2=AB=20Donjon=20en=205=20salles=20?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - M1 coach : bouton ampoule sur 17 champs narratifs (scène, chapitre, arc), panneau de conseils (à quoi ça sert, questions, exemple, piège classique). Contenu statique i18n fr/en, sans IA ; ampoule aussi dans l'en-tête des sections repliables (input coachTopic d'expandable-section). - M2 relecture d'éditeur : WritingReviewService + GET /api/campaigns/{id}/writing-review, 10 règles déterministes WRITE-001 à 010 (couloir, faux choix, révélation à chemin unique, rythme monotone, enjeux absents, narration trop longue ou qui décide à la place des PJ, combat sans but, fin unique, scènes non typées). Le back renvoie ruleId + params, les textes fr/en sont dans l'i18n. Panneau sur le hub, encart dans les éditeurs, liens « Voir » avec ?focus= (nouveaux focus : narration, choices, stakes). - M3 méthode guidée : POST /api/campaigns/{id}/guided-skeleton (arc existant ou nouveau, chapitre, scènes typées, chaînage optionnel, transactionnel) + assistant pas à pas générique /campaigns/:id/guided/:method, première méthode « Donjon en 5 salles ». Entrées sur le hub de campagne. - Garde-fous vitest : complétude des textes fr/en du coach, de la relecture (règles lues dans le Java) et des méthodes guidées. Vérifié : core clean verify (1182 tests), web build + 299 tests vitest, lint sans erreur, parcours testés dans l'appli (back Postgres de dev). À redéployer : core (2 endpoints, aucune migration) + web. --- .../campaigncontext/GuidedSkeleton.java | 44 ++ .../GuidedSkeletonService.java | 157 ++++++ .../campaigncontext/WritingRemark.java | 35 ++ .../campaigncontext/WritingReviewReport.java | 12 + .../campaigncontext/WritingReviewService.java | 333 ++++++++++++ .../writingreview/WritingRemarkCategory.java | 17 + .../controller/GuidedSkeletonController.java | 43 ++ .../controller/WritingReviewController.java | 39 ++ .../GuidedSkeletonServiceTest.java | 199 +++++++ .../WritingReviewServiceTest.java | 322 +++++++++++ installers/install.ps1 | 27 +- web/src/app/app.component.html | 1 + web/src/app/app.component.ts | 2 + web/src/app/app.routes.ts | 1 + .../arc/arc-edit/arc-edit.component.html | 30 +- .../arc/arc-edit/arc-edit.component.ts | 8 +- .../campaign-detail.component.html | 11 + .../campaign-detail.component.scss | 12 + .../campaign-detail.component.ts | 3 +- .../chapter-edit/chapter-edit.component.html | 20 +- .../chapter-edit/chapter-edit.component.ts | 9 +- .../campaigns/guided/guided-method.model.ts | 58 ++ .../campaigns/guided/guided-methods.spec.ts | 104 ++++ .../app/campaigns/guided/guided-methods.ts | 9 + .../guided-wizard.component.html | 171 ++++++ .../guided-wizard.component.scss | 352 ++++++++++++ .../guided-wizard/guided-wizard.component.ts | 255 +++++++++ .../guided/methods/five-room.method.ts | 101 ++++ .../scene-edit/scene-edit.component.html | 33 +- .../scene/scene-edit/scene-edit.component.ts | 6 +- .../campaigns/writing-remark-action.helper.ts | 38 ++ web/src/app/services/guided-skeleton.model.ts | 39 ++ .../app/services/guided-skeleton.service.ts | 15 + web/src/app/services/writing-review.model.ts | 29 + .../app/services/writing-review.service.ts | 18 + .../expandable-section.component.html | 29 +- .../expandable-section.component.scss | 15 +- .../expandable-section.component.ts | 8 +- .../writing-coach-content.spec.ts | 65 +++ .../writing-coach-panel.component.html | 57 ++ .../writing-coach-panel.component.scss | 154 ++++++ .../writing-coach-panel.component.ts | 80 +++ .../writing-coach-trigger.component.ts | 69 +++ .../writing-coach/writing-coach.service.ts | 30 ++ .../writing-remark-card.component.ts | 87 +++ .../writing-review-content.spec.ts | 74 +++ .../writing-review-hints.component.ts | 98 ++++ .../writing-review-panel.component.html | 37 ++ .../writing-review-panel.component.scss | 92 ++++ .../writing-review-panel.component.ts | 86 +++ web/src/assets/i18n/en.json | 504 ++++++++++++++++++ web/src/assets/i18n/fr.json | 504 ++++++++++++++++++ web/src/assets/i18n/fragments/guided.en.json | 236 ++++++++ web/src/assets/i18n/fragments/guided.fr.json | 236 ++++++++ .../i18n/fragments/writing-coach.en.json | 204 +++++++ .../i18n/fragments/writing-coach.fr.json | 204 +++++++ .../i18n/fragments/writing-review.en.json | 70 +++ .../i18n/fragments/writing-review.fr.json | 70 +++ web/src/styles/_forms.scss | 11 + 59 files changed, 5533 insertions(+), 40 deletions(-) create mode 100644 core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeleton.java create mode 100644 core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeletonService.java create mode 100644 core/src/main/java/com/loremind/application/campaigncontext/WritingRemark.java create mode 100644 core/src/main/java/com/loremind/application/campaigncontext/WritingReviewReport.java create mode 100644 core/src/main/java/com/loremind/application/campaigncontext/WritingReviewService.java create mode 100644 core/src/main/java/com/loremind/domain/campaigncontext/writingreview/WritingRemarkCategory.java create mode 100644 core/src/main/java/com/loremind/infrastructure/web/controller/GuidedSkeletonController.java create mode 100644 core/src/main/java/com/loremind/infrastructure/web/controller/WritingReviewController.java create mode 100644 core/src/test/java/com/loremind/application/campaigncontext/GuidedSkeletonServiceTest.java create mode 100644 core/src/test/java/com/loremind/application/campaigncontext/WritingReviewServiceTest.java create mode 100644 web/src/app/campaigns/guided/guided-method.model.ts create mode 100644 web/src/app/campaigns/guided/guided-methods.spec.ts create mode 100644 web/src/app/campaigns/guided/guided-methods.ts create mode 100644 web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.html create mode 100644 web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.scss create mode 100644 web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.ts create mode 100644 web/src/app/campaigns/guided/methods/five-room.method.ts create mode 100644 web/src/app/campaigns/writing-remark-action.helper.ts create mode 100644 web/src/app/services/guided-skeleton.model.ts create mode 100644 web/src/app/services/guided-skeleton.service.ts create mode 100644 web/src/app/services/writing-review.model.ts create mode 100644 web/src/app/services/writing-review.service.ts create mode 100644 web/src/app/shared/writing-coach/writing-coach-content.spec.ts create mode 100644 web/src/app/shared/writing-coach/writing-coach-panel.component.html create mode 100644 web/src/app/shared/writing-coach/writing-coach-panel.component.scss create mode 100644 web/src/app/shared/writing-coach/writing-coach-panel.component.ts create mode 100644 web/src/app/shared/writing-coach/writing-coach-trigger.component.ts create mode 100644 web/src/app/shared/writing-coach/writing-coach.service.ts create mode 100644 web/src/app/shared/writing-review/writing-remark-card.component.ts create mode 100644 web/src/app/shared/writing-review/writing-review-content.spec.ts create mode 100644 web/src/app/shared/writing-review/writing-review-hints.component.ts create mode 100644 web/src/app/shared/writing-review/writing-review-panel.component.html create mode 100644 web/src/app/shared/writing-review/writing-review-panel.component.scss create mode 100644 web/src/app/shared/writing-review/writing-review-panel.component.ts create mode 100644 web/src/assets/i18n/fragments/guided.en.json create mode 100644 web/src/assets/i18n/fragments/guided.fr.json create mode 100644 web/src/assets/i18n/fragments/writing-coach.en.json create mode 100644 web/src/assets/i18n/fragments/writing-coach.fr.json create mode 100644 web/src/assets/i18n/fragments/writing-review.en.json create mode 100644 web/src/assets/i18n/fragments/writing-review.fr.json diff --git a/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeleton.java b/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeleton.java new file mode 100644 index 0000000..b256439 --- /dev/null +++ b/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeleton.java @@ -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. + * + *

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.

+ * + * @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 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 sceneIds) { + } +} diff --git a/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeletonService.java b/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeletonService.java new file mode 100644 index 0000000..6f310b3 --- /dev/null +++ b/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeletonService.java @@ -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. + * + *

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.

+ */ +@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 specs = skeleton.scenes().stream() + .filter(s -> s != null && !isBlank(s.name())) + .toList(); + + String arcId = resolveArc(campaignId, skeleton); + Chapter chapter = createChapter(arcId, skeleton.chapter()); + + List 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 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 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(); + } +} diff --git a/core/src/main/java/com/loremind/application/campaigncontext/WritingRemark.java b/core/src/main/java/com/loremind/application/campaigncontext/WritingRemark.java new file mode 100644 index 0000000..b49a179 --- /dev/null +++ b/core/src/main/java/com/loremind/application/campaigncontext/WritingRemark.java @@ -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). + * + *

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.}), en fr comme en en.

+ * + * @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 params, + String arcId, + String chapterId +) { +} diff --git a/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewReport.java b/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewReport.java new file mode 100644 index 0000000..8336d71 --- /dev/null +++ b/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewReport.java @@ -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 remarks) { +} diff --git a/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewService.java b/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewService.java new file mode 100644 index 0000000..4842c77 --- /dev/null +++ b/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewService.java @@ -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. + * + *

Déterministe, sans IA, sans persistance ; 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}.

+ * + *

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.

+ */ +@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 campaignRemarks = new ArrayList<>(); + List treeRemarks = new ArrayList<>(); + + Set arcsWithQuests = questRepository.findByCampaignId(campaignId).stream() + .map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet()); + + List arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId)); + arcs.sort(Comparator.comparingInt(Arc::getOrder)); + + int totalScenes = 0; + int genericScenes = 0; + for (Arc arc : arcs) { + List 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 lastChapterScenes = List.of(); + for (Chapter chapter : chapters) { + List 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 remarks = new ArrayList<>(campaignRemarks); + remarks.addAll(treeRemarks); + return new WritingReviewReport(campaignId, remarks); + } + + // --- Niveau chapitre --------------------------------------------------------------- + + private void reviewChapter(Arc arc, Chapter chapter, List scenes, List 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 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 chapterScenes, + List 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 chapterScenes, + List out) { + List branches = scene.getBranches(); + if (branches == null || branches.size() < 2) return; + Set 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 chapterScenes, + List 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 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 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 lastChapterScenes, List 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 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 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 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; + } +} diff --git a/core/src/main/java/com/loremind/domain/campaigncontext/writingreview/WritingRemarkCategory.java b/core/src/main/java/com/loremind/domain/campaigncontext/writingreview/WritingRemarkCategory.java new file mode 100644 index 0000000..a8b14f6 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/campaigncontext/writingreview/WritingRemarkCategory.java @@ -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 +} diff --git a/core/src/main/java/com/loremind/infrastructure/web/controller/GuidedSkeletonController.java b/core/src/main/java/com/loremind/infrastructure/web/controller/GuidedSkeletonController.java new file mode 100644 index 0000000..6fad3b3 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/web/controller/GuidedSkeletonController.java @@ -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. + * + *

201 + ids créés ; 400 si le squelette est invalide ({@code GlobalExceptionHandler}) ; + * 404 si la campagne est inconnue.

+ */ +@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 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)); + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/web/controller/WritingReviewController.java b/core/src/main/java/com/loremind/infrastructure/web/controller/WritingReviewController.java new file mode 100644 index 0000000..cdb8ac3 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/web/controller/WritingReviewController.java @@ -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. + * + *

Read-model pur, toujours 200 quand la campagne existe (les remarques conseillent, + * elles ne bloquent rien). 404 si la campagne est inconnue.

+ */ +@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 getWritingReview(@PathVariable String campaignId) { + if (!campaignRepository.existsById(campaignId)) { + return ResponseEntity.notFound().build(); + } + return ResponseEntity.ok(writingReviewService.review(campaignId)); + } +} diff --git a/core/src/test/java/com/loremind/application/campaigncontext/GuidedSkeletonServiceTest.java b/core/src/test/java/com/loremind/application/campaigncontext/GuidedSkeletonServiceTest.java new file mode 100644 index 0000000..dca31cf --- /dev/null +++ b/core/src/test/java/com/loremind/application/campaigncontext/GuidedSkeletonServiceTest.java @@ -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 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 = 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 = 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)); + } +} diff --git a/core/src/test/java/com/loremind/application/campaigncontext/WritingReviewServiceTest.java b/core/src/test/java/com/loremind/application/campaigncontext/WritingReviewServiceTest.java new file mode 100644 index 0000000..f4b45fc --- /dev/null +++ b/core/src/test/java/com/loremind/application/campaigncontext/WritingReviewServiceTest.java @@ -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 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 scenes) { + tree(arc("arc", ArcType.HUB), chapter("chap", "arc"), scenes); + } + + private Set 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 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 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 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")); + } +} diff --git a/installers/install.ps1 b/installers/install.ps1 index 64b7da1..a5f56c4 100644 --- a/installers/install.ps1 +++ b/installers/install.ps1 @@ -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 ." + exit 1 +} + Write-Step "Preparation du dossier $InstallDir" New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null Set-Location $InstallDir diff --git a/web/src/app/app.component.html b/web/src/app/app.component.html index cda78fd..3fd2153 100644 --- a/web/src/app/app.component.html +++ b/web/src/app/app.component.html @@ -23,3 +23,4 @@ + diff --git a/web/src/app/app.component.ts b/web/src/app/app.component.ts index d49295f..d3070d0 100644 --- a/web/src/app/app.component.ts +++ b/web/src/app/app.component.ts @@ -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', diff --git a/web/src/app/app.routes.ts b/web/src/app/app.routes.ts index 1b5abf0..f53d933 100644 --- a/web/src/app/app.routes.ts +++ b/web/src/app/app.routes.ts @@ -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) }, diff --git a/web/src/app/campaigns/arc/arc-edit/arc-edit.component.html b/web/src/app/campaigns/arc/arc-edit/arc-edit.component.html index a0f35fc..5ea57c0 100644 --- a/web/src/app/campaigns/arc/arc-edit/arc-edit.component.html +++ b/web/src/app/campaigns/arc/arc-edit/arc-edit.component.html @@ -29,6 +29,9 @@

{{ 'arcEdit.optionalHint' | translate }}

+ + +
- +
+ + +
- +
+ + +
- +
+ + +
- +
+ + +
+ } @else { + + } +
+ } + } + + } + + + @if (step.kind === 'review' && draft; as d) { +
+
+
{{ 'guided.reviewArc' | translate }}
+
{{ placementLabel }}
+
{{ 'guided.reviewChapter' | translate }}
+
{{ d.chapter.name }}
+
+
    + @for (scene of d.scenes; track $index) { +
  1. + {{ scene.name }} + {{ ('sceneType.' + scene.type) | translate }} +
  2. + } +
+ +

{{ 'guided.reviewAfter' | translate }}

+
+ } + + @if (error) { + + } + + +
+ + + @if (isLast) { + + } @else { + + } +
+ +} @else { +
+

{{ 'guided.unknownMethod' | translate }}

+ {{ 'guided.backToCampaign' | translate }} +
+} diff --git a/web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.scss b/web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.scss new file mode 100644 index 0000000..1278b47 --- /dev/null +++ b/web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.scss @@ -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; } +} diff --git a/web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.ts b/web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.ts new file mode 100644 index 0000000..053ebb0 --- /dev/null +++ b/web/src/app/campaigns/guided/guided-wizard/guided-wizard.component.ts @@ -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; + + 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 { + 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 */ } + } +} diff --git a/web/src/app/campaigns/guided/methods/five-room.method.ts b/web/src/app/campaigns/guided/methods/five-room.method.ts new file mode 100644 index 0000000..63a8083 --- /dev/null +++ b/web/src/app/campaigns/guided/methods/five-room.method.ts @@ -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 = { + 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') + ] + }; + } +}; diff --git a/web/src/app/campaigns/scene/scene-edit/scene-edit.component.html b/web/src/app/campaigns/scene/scene-edit/scene-edit.component.html index 9744d43..2e02cc6 100644 --- a/web/src/app/campaigns/scene/scene-edit/scene-edit.component.html +++ b/web/src/app/campaigns/scene/scene-edit/scene-edit.component.html @@ -30,6 +30,9 @@ est dans des sections repliables avec pastille « rempli ». -->

{{ 'sceneEdit.optionalHint' | translate }}

+ + +
- +
+ + +