Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a7e93b162 | ||
|
|
106754fd77 | ||
|
|
0c0581e894 | ||
|
|
dae0508c93 | ||
|
|
cbd59a5bd9 | ||
|
|
d759bc8131 | ||
|
|
ac7648f9fe | ||
|
|
d9a90f8412 | ||
|
|
2e9632de49 | ||
|
|
fbb1956e17 |
+1
-1
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LoreMind Brain",
|
title="LoreMind Brain",
|
||||||
description="Backend IA pour la génération de contenu narratif.",
|
description="Backend IA pour la génération de contenu narratif.",
|
||||||
version="1.0.3",
|
version="1.4.0-beta",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
<groupId>com.loremind</groupId>
|
<groupId>com.loremind</groupId>
|
||||||
<artifactId>loremind-core</artifactId>
|
<artifactId>loremind-core</artifactId>
|
||||||
<version>1.0.3</version>
|
<version>1.4.0-beta</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.loremind.application.campaigncontext;
|
|||||||
import com.loremind.application.playcontext.PlaythroughService;
|
import com.loremind.application.playcontext.PlaythroughService;
|
||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
@@ -108,6 +109,23 @@ public class CampaignService {
|
|||||||
campaignRepository.save(campaign);
|
campaignRepository.save(campaign);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fiche « Publication » de la campagne (vide si jamais renseignée). */
|
||||||
|
public CampaignPublication getPublication(String id) {
|
||||||
|
Campaign campaign = campaignRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||||
|
return campaign.getPublication() != null ? campaign.getPublication() : CampaignPublication.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remplace la fiche « Publication » (nettoyée : blancs → vide, longueurs bornées). */
|
||||||
|
public CampaignPublication updatePublication(String id, CampaignPublication publication) {
|
||||||
|
Campaign campaign = campaignRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||||
|
CampaignPublication clean = publication != null ? publication.normalized() : CampaignPublication.empty();
|
||||||
|
campaign.setPublication(clean.hasContent() ? clean : null);
|
||||||
|
campaignRepository.save(campaign);
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
|
||||||
private String normalizeId(String id) {
|
private String normalizeId(String id) {
|
||||||
return (id == null || id.isBlank()) ? null : id;
|
return (id == null || id.isBlank()) ? null : id;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -20,6 +21,9 @@ import java.util.List;
|
|||||||
* @param scenes les scènes, dans l'ordre (au moins une avec un nom)
|
* @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 linkSequentially relier chaque scène à la suivante par une sortie
|
||||||
* @param linkLabel libellé de ces sorties (rédigé dans la langue du MJ par le front)
|
* @param linkLabel libellé de ces sorties (rédigé dans la langue du MJ par le front)
|
||||||
|
* @param links liens explicites entre scènes (indices dans {@code scenes}), ou {@code null} :
|
||||||
|
* une enquête en nœuds relie ses pistes en réseau, pas en chaîne
|
||||||
|
* @param clock horloge à créer dans chaque partie de la campagne (plan du méchant), ou {@code null}
|
||||||
*/
|
*/
|
||||||
public record GuidedSkeleton(
|
public record GuidedSkeleton(
|
||||||
String arcId,
|
String arcId,
|
||||||
@@ -27,10 +31,44 @@ public record GuidedSkeleton(
|
|||||||
ChapterSpec chapter,
|
ChapterSpec chapter,
|
||||||
List<SceneSpec> scenes,
|
List<SceneSpec> scenes,
|
||||||
boolean linkSequentially,
|
boolean linkSequentially,
|
||||||
String linkLabel
|
String linkLabel,
|
||||||
|
List<LinkSpec> links,
|
||||||
|
ClockSpec clock
|
||||||
) {
|
) {
|
||||||
|
|
||||||
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
/** Squelette sans liens explicites ni horloge (Donjon en 5 salles). */
|
||||||
|
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||||
|
boolean linkSequentially, String linkLabel) {
|
||||||
|
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param gmNotes notes réservées au MJ (vérité cachée d'une enquête, plan complet du méchant) */
|
||||||
|
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes,
|
||||||
|
String gmNotes) {
|
||||||
|
public ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||||
|
this(name, description, playerObjectives, narrativeStakes, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lien d'une scène vers une autre, par position dans {@code scenes}.
|
||||||
|
*
|
||||||
|
* @param from index de la scène de départ
|
||||||
|
* @param to index de la scène d'arrivée
|
||||||
|
* @param label libellé du lien (langue du MJ)
|
||||||
|
* @param kind nature du lien (sortie, piste, indice) ; {@code null} = sortie
|
||||||
|
*/
|
||||||
|
public record LinkSpec(int from, int to, String label, LinkType kind) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Horloge de progression à créer dans chaque partie (Playthrough) de la campagne.
|
||||||
|
*
|
||||||
|
* @param name nom de l'horloge
|
||||||
|
* @param description ce qui arrive quand elle est pleine
|
||||||
|
* @param segments nombre de segments (une étape du plan = un segment)
|
||||||
|
*/
|
||||||
|
public record ClockSpec(String name, String description, int segments) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public record SceneSpec(
|
public record SceneSpec(
|
||||||
@@ -38,7 +76,14 @@ public record GuidedSkeleton(
|
|||||||
String choicesConsequences, String gmSecretNotes, String enemies) {
|
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) {
|
* Ce qui a été créé, pour que le front ouvre directement le chapitre.
|
||||||
|
*
|
||||||
|
* @param clocks nombre d'horloges créées (une par partie de la campagne)
|
||||||
|
*/
|
||||||
|
public record Result(String arcId, String chapterId, List<String> sceneIds, int clocks) {
|
||||||
|
public Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||||
|
this(arcId, chapterId, sceneIds, 0);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+69
-9
@@ -10,6 +10,10 @@ import com.loremind.domain.campaigncontext.structure.LinkType;
|
|||||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.application.playcontext.ClockService;
|
||||||
|
import com.loremind.domain.playcontext.ClockTrigger;
|
||||||
|
import com.loremind.domain.playcontext.Playthrough;
|
||||||
|
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -33,19 +37,25 @@ public class GuidedSkeletonService {
|
|||||||
private final ArcService arcService;
|
private final ArcService arcService;
|
||||||
private final ChapterService chapterService;
|
private final ChapterService chapterService;
|
||||||
private final SceneService sceneService;
|
private final SceneService sceneService;
|
||||||
|
private final PlaythroughRepository playthroughRepository;
|
||||||
|
private final ClockService clockService;
|
||||||
|
|
||||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
SceneRepository sceneRepository,
|
SceneRepository sceneRepository,
|
||||||
ArcService arcService,
|
ArcService arcService,
|
||||||
ChapterService chapterService,
|
ChapterService chapterService,
|
||||||
SceneService sceneService) {
|
SceneService sceneService,
|
||||||
|
PlaythroughRepository playthroughRepository,
|
||||||
|
ClockService clockService) {
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
this.arcService = arcService;
|
this.arcService = arcService;
|
||||||
this.chapterService = chapterService;
|
this.chapterService = chapterService;
|
||||||
this.sceneService = sceneService;
|
this.sceneService = sceneService;
|
||||||
|
this.playthroughRepository = playthroughRepository;
|
||||||
|
this.clockService = clockService;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -55,17 +65,19 @@ public class GuidedSkeletonService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||||
validate(skeleton);
|
validate(skeleton);
|
||||||
List<GuidedSkeleton.SceneSpec> specs = skeleton.scenes().stream()
|
|
||||||
.filter(s -> s != null && !isBlank(s.name()))
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
String arcId = resolveArc(campaignId, skeleton);
|
String arcId = resolveArc(campaignId, skeleton);
|
||||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
||||||
|
|
||||||
|
// Une scène sans nom est ignorée ; byIndex garde la position d'origine pour les liens.
|
||||||
List<Scene> scenes = new ArrayList<>();
|
List<Scene> scenes = new ArrayList<>();
|
||||||
|
List<Scene> byIndex = new ArrayList<>();
|
||||||
int order = 0;
|
int order = 0;
|
||||||
for (GuidedSkeleton.SceneSpec spec : specs) {
|
for (GuidedSkeleton.SceneSpec spec : skeleton.scenes()) {
|
||||||
scenes.add(sceneService.createScene(Scene.builder()
|
if (spec == null || isBlank(spec.name())) {
|
||||||
|
byIndex.add(null);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Scene created = sceneService.createScene(Scene.builder()
|
||||||
.name(spec.name().trim())
|
.name(spec.name().trim())
|
||||||
.description(blankToNull(spec.description()))
|
.description(blankToNull(spec.description()))
|
||||||
.type(Objects.requireNonNullElse(spec.type(), SceneType.GENERIC))
|
.type(Objects.requireNonNullElse(spec.type(), SceneType.GENERIC))
|
||||||
@@ -75,14 +87,61 @@ public class GuidedSkeletonService {
|
|||||||
.enemies(blankToNull(spec.enemies()))
|
.enemies(blankToNull(spec.enemies()))
|
||||||
.chapterId(chapter.getId())
|
.chapterId(chapter.getId())
|
||||||
.order(order++)
|
.order(order++)
|
||||||
.build()));
|
.build());
|
||||||
|
scenes.add(created);
|
||||||
|
byIndex.add(created);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (skeleton.linkSequentially()) {
|
if (skeleton.linkSequentially()) {
|
||||||
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
||||||
}
|
}
|
||||||
|
if (skeleton.links() != null && !skeleton.links().isEmpty()) {
|
||||||
|
linkExplicitly(byIndex, skeleton.links());
|
||||||
|
}
|
||||||
|
int clocks = createClocks(campaignId, skeleton.clock());
|
||||||
|
|
||||||
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList());
|
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList(), clocks);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liens explicites (réseau d'une enquête) : ajoutés aux sorties existantes. Un lien vers
|
||||||
|
* ou depuis une scène ignorée (sans nom), hors limites ou en boucle sur soi est écarté.
|
||||||
|
*/
|
||||||
|
private void linkExplicitly(List<Scene> byIndex, List<GuidedSkeleton.LinkSpec> links) {
|
||||||
|
java.util.Map<String, Scene> touched = new java.util.LinkedHashMap<>();
|
||||||
|
for (GuidedSkeleton.LinkSpec link : links) {
|
||||||
|
if (link == null || link.from() == link.to()) continue;
|
||||||
|
Scene from = at(byIndex, link.from());
|
||||||
|
Scene to = at(byIndex, link.to());
|
||||||
|
if (from == null || to == null) continue;
|
||||||
|
List<SceneBranch> branches = from.getBranches() == null ? new ArrayList<>() : new ArrayList<>(from.getBranches());
|
||||||
|
String label = isBlank(link.label()) ? to.getName() : link.label().trim();
|
||||||
|
branches.add(new SceneBranch(label, to.getId(), null,
|
||||||
|
Objects.requireNonNullElse(link.kind(), LinkType.EXIT)));
|
||||||
|
from.setBranches(branches);
|
||||||
|
touched.put(from.getId(), from);
|
||||||
|
}
|
||||||
|
touched.values().forEach(sceneRepository::save);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Scene at(List<Scene> byIndex, int index) {
|
||||||
|
return index >= 0 && index < byIndex.size() ? byIndex.get(index) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Horloge du plan (méthode « Plan du méchant ») : créée dans chaque partie de la campagne,
|
||||||
|
* car une horloge est de l'état de partie. Aucune partie : rien n'est créé (le MJ la
|
||||||
|
* créera quand il lancera une partie).
|
||||||
|
*/
|
||||||
|
private int createClocks(String campaignId, GuidedSkeleton.ClockSpec clock) {
|
||||||
|
if (clock == null || isBlank(clock.name())) return 0;
|
||||||
|
int count = 0;
|
||||||
|
for (Playthrough p : playthroughRepository.findByCampaignId(campaignId)) {
|
||||||
|
clockService.create(p.getId(), clock.name().trim(), blankToNull(clock.description()),
|
||||||
|
clock.segments(), ClockTrigger.NONE, null, null);
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void validate(GuidedSkeleton skeleton) {
|
private static void validate(GuidedSkeleton skeleton) {
|
||||||
@@ -132,6 +191,7 @@ public class GuidedSkeletonService {
|
|||||||
.description(blankToNull(spec.description()))
|
.description(blankToNull(spec.description()))
|
||||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||||
|
.gmNotes(blankToNull(spec.gmNotes()))
|
||||||
.arcId(arcId)
|
.arcId(arcId)
|
||||||
.order(nextOrder)
|
.order(nextOrder)
|
||||||
.build());
|
.build());
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||||
import com.loremind.domain.shared.ReorderSupport;
|
import com.loremind.domain.shared.ReorderSupport;
|
||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -29,8 +30,17 @@ public class NpcService {
|
|||||||
String campaignId,
|
String campaignId,
|
||||||
List<String> relatedPageIds,
|
List<String> relatedPageIds,
|
||||||
String folder,
|
String folder,
|
||||||
Integer order
|
Integer order,
|
||||||
) {}
|
/** Rôle dans l'histoire ; null = inchangé (mise à jour) / non renseigné (création). */
|
||||||
|
NpcStory story
|
||||||
|
) {
|
||||||
|
public NpcData(String name, String portraitImageId, String headerImageId, Map<String, String> values,
|
||||||
|
Map<String, List<String>> imageValues, Map<String, Map<String, String>> keyValueValues,
|
||||||
|
String campaignId, List<String> relatedPageIds, String folder, Integer order) {
|
||||||
|
this(name, portraitImageId, headerImageId, values, imageValues, keyValueValues, campaignId,
|
||||||
|
relatedPageIds, folder, order, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public Npc createNpc(NpcData data) {
|
public Npc createNpc(NpcData data) {
|
||||||
int order = data.order() != null
|
int order = data.order() != null
|
||||||
@@ -47,6 +57,7 @@ public class NpcService {
|
|||||||
.relatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>())
|
.relatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>())
|
||||||
.folder(normalizeFolder(data.folder()))
|
.folder(normalizeFolder(data.folder()))
|
||||||
.order(order)
|
.order(order)
|
||||||
|
.story(cleanStory(data.story()))
|
||||||
.build();
|
.build();
|
||||||
return npcRepository.save(npc);
|
return npcRepository.save(npc);
|
||||||
}
|
}
|
||||||
@@ -70,12 +81,22 @@ public class NpcService {
|
|||||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||||
existing.setRelatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>());
|
existing.setRelatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>());
|
||||||
existing.setFolder(normalizeFolder(data.folder()));
|
existing.setFolder(normalizeFolder(data.folder()));
|
||||||
|
if (data.story() != null) {
|
||||||
|
existing.setStory(cleanStory(data.story()));
|
||||||
|
}
|
||||||
if (data.order() != null) {
|
if (data.order() != null) {
|
||||||
existing.setOrder(data.order());
|
existing.setOrder(data.order());
|
||||||
}
|
}
|
||||||
return npcRepository.save(existing);
|
return npcRepository.save(existing);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fiche nettoyée, ou null si elle est vide (rien à stocker). */
|
||||||
|
private static NpcStory cleanStory(NpcStory story) {
|
||||||
|
if (story == null) return null;
|
||||||
|
NpcStory clean = story.normalized();
|
||||||
|
return clean.hasContent() ? clean : null;
|
||||||
|
}
|
||||||
|
|
||||||
public void deleteNpc(String id) {
|
public void deleteNpc(String id) {
|
||||||
npcRepository.deleteById(id);
|
npcRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -125,6 +125,8 @@ public class SceneService {
|
|||||||
case "playerNarration" -> scene.setPlayerNarration(value);
|
case "playerNarration" -> scene.setPlayerNarration(value);
|
||||||
case "choicesConsequences" -> scene.setChoicesConsequences(value);
|
case "choicesConsequences" -> scene.setChoicesConsequences(value);
|
||||||
case "combatDifficulty" -> scene.setCombatDifficulty(value);
|
case "combatDifficulty" -> scene.setCombatDifficulty(value);
|
||||||
|
case "tactics" -> scene.setTactics(value);
|
||||||
|
case "purpose" -> scene.setPurpose(value);
|
||||||
case "enemies" -> scene.setEnemies(value);
|
case "enemies" -> scene.setEnemies(value);
|
||||||
case "gmSecretNotes" -> scene.setGmSecretNotes(value);
|
case "gmSecretNotes" -> scene.setGmSecretNotes(value);
|
||||||
default -> { /* clé inconnue → ignorée (garde-fou anti-écrasement) */ }
|
default -> { /* clé inconnue → ignorée (garde-fou anti-écrasement) */ }
|
||||||
|
|||||||
+216
-10
@@ -4,6 +4,9 @@ import com.loremind.domain.campaigncontext.Campaign;
|
|||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||||
@@ -11,14 +14,21 @@ import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
|||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Room;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayDeque;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
|
import java.util.Deque;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
@@ -44,8 +54,16 @@ public class WritingReviewService {
|
|||||||
|
|
||||||
/** WRITE-001 : à partir de combien de scènes un chapitre sans aucun choix devient un couloir. */
|
/** WRITE-001 : à partir de combien de scènes un chapitre sans aucun choix devient un couloir. */
|
||||||
static final int CORRIDOR_MIN_SCENES = 3;
|
static final int CORRIDOR_MIN_SCENES = 3;
|
||||||
/** WRITE-003 : nombre minimal de chemins menant à une révélation (en deçà : un seul chemin). */
|
/** WRITE-003 : nombre minimal de scènes menant à une révélation (règle des 3 indices). */
|
||||||
static final int REVELATION_MIN_INCOMING = 2;
|
static final int REVELATION_MIN_INCOMING = 3;
|
||||||
|
/** WRITE-011 / 012 / 014 : un chapitre « qui utilise le graphe » a au moins ce nombre de scènes reliées. */
|
||||||
|
static final int LINKED_MIN_SCENES = 2;
|
||||||
|
/** WRITE-012 : taille minimale d'un chapitre pour juger un passage obligé. */
|
||||||
|
static final int CHOKEPOINT_MIN_SCENES = 4;
|
||||||
|
/** WRITE-013 : nombre minimal de pièces pour juger la forme d'un donjon. */
|
||||||
|
static final int DUNGEON_MIN_ROOMS = 4;
|
||||||
|
/** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */
|
||||||
|
static final int PROACTIVE_MIN_SCENES = 3;
|
||||||
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
||||||
static final int MONOTONOUS_RUN = 3;
|
static final int MONOTONOUS_RUN = 3;
|
||||||
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
||||||
@@ -76,17 +94,20 @@ public class WritingReviewService {
|
|||||||
private final ChapterRepository chapterRepository;
|
private final ChapterRepository chapterRepository;
|
||||||
private final SceneRepository sceneRepository;
|
private final SceneRepository sceneRepository;
|
||||||
private final QuestRepository questRepository;
|
private final QuestRepository questRepository;
|
||||||
|
private final NpcRepository npcRepository;
|
||||||
|
|
||||||
public WritingReviewService(CampaignRepository campaignRepository,
|
public WritingReviewService(CampaignRepository campaignRepository,
|
||||||
ArcRepository arcRepository,
|
ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
SceneRepository sceneRepository,
|
SceneRepository sceneRepository,
|
||||||
QuestRepository questRepository) {
|
QuestRepository questRepository,
|
||||||
|
NpcRepository npcRepository) {
|
||||||
this.campaignRepository = campaignRepository;
|
this.campaignRepository = campaignRepository;
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
this.questRepository = questRepository;
|
this.questRepository = questRepository;
|
||||||
|
this.npcRepository = npcRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Relit toute la campagne et renvoie les remarques dans l'ordre de l'arbre. */
|
/** Relit toute la campagne et renvoie les remarques dans l'ordre de l'arbre. */
|
||||||
@@ -107,6 +128,11 @@ public class WritingReviewService {
|
|||||||
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||||
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
||||||
|
|
||||||
|
// WRITE-017 — une seule accroche : les personnages n'ont qu'une raison de s'en mêler.
|
||||||
|
if (visibleArc && countLines(arc.getHooks()) == 1) {
|
||||||
|
treeRemarks.add(arcRemark(arc, "WRITE-017-SINGLE-HOOK", WritingRemarkCategory.AGENCY, Map.of()));
|
||||||
|
}
|
||||||
|
|
||||||
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
||||||
if (visibleArc && isBlank(arc.getStakes())
|
if (visibleArc && isBlank(arc.getStakes())
|
||||||
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
||||||
@@ -126,6 +152,7 @@ public class WritingReviewService {
|
|||||||
for (Scene scene : scenes) {
|
for (Scene scene : scenes) {
|
||||||
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
||||||
}
|
}
|
||||||
|
reviewGraph(arc, chapter, scenes, treeRemarks);
|
||||||
if (!scenes.isEmpty()) {
|
if (!scenes.isEmpty()) {
|
||||||
lastChapterScenes = scenes;
|
lastChapterScenes = scenes;
|
||||||
}
|
}
|
||||||
@@ -148,6 +175,7 @@ public class WritingReviewService {
|
|||||||
|
|
||||||
List<WritingRemark> remarks = new ArrayList<>(campaignRemarks);
|
List<WritingRemark> remarks = new ArrayList<>(campaignRemarks);
|
||||||
remarks.addAll(treeRemarks);
|
remarks.addAll(treeRemarks);
|
||||||
|
remarks.addAll(reviewNpcs(campaignId));
|
||||||
return new WritingReviewReport(campaignId, remarks);
|
return new WritingReviewReport(campaignId, remarks);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,6 +203,14 @@ public class WritingReviewService {
|
|||||||
if (isBlank(chapter.getNarrativeStakes())) {
|
if (isBlank(chapter.getNarrativeStakes())) {
|
||||||
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WRITE-014 — enquête sans relance : des révélations, mais aucun événement que le MJ
|
||||||
|
// peut déclencher si les joueurs tournent en rond.
|
||||||
|
boolean investigation = scenes.stream().anyMatch(s -> typeOf(s) == SceneType.REVELATION);
|
||||||
|
boolean proactive = scenes.stream().anyMatch(s -> typeOf(s) == SceneType.EVENT);
|
||||||
|
if (investigation && !proactive && scenes.size() >= PROACTIVE_MIN_SCENES && usesLinks(scenes)) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-014-NO-PROACTIVE", WritingRemarkCategory.PACING, Map.of()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private record MonotonousRun(String kind, int length) {}
|
private record MonotonousRun(String kind, int length) {}
|
||||||
@@ -215,6 +251,142 @@ public class WritingReviewService {
|
|||||||
checkSingleClue(arc, chapter, scene, chapterScenes, out);
|
checkSingleClue(arc, chapter, scene, chapterScenes, out);
|
||||||
checkNarration(arc, chapter, scene, out);
|
checkNarration(arc, chapter, scene, out);
|
||||||
checkCombatPurpose(arc, chapter, scene, out);
|
checkCombatPurpose(arc, chapter, scene, out);
|
||||||
|
checkLinearDungeon(arc, chapter, scene, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-013 — donjon en couloir : des pièces reliées entre elles, mais sans aucune boucle
|
||||||
|
* (graphe des liens = arbre). Les joueurs ne choisissent pas leur route et ne peuvent ni
|
||||||
|
* contourner un obstacle ni revenir par un autre chemin. Muet si les pièces ne sont pas reliées.
|
||||||
|
*/
|
||||||
|
private void checkLinearDungeon(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||||
|
List<Room> rooms = scene.getRooms();
|
||||||
|
if (rooms == null || rooms.size() < DUNGEON_MIN_ROOMS) return;
|
||||||
|
Set<String> ids = rooms.stream().map(Room::getId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||||
|
// Arêtes non orientées distinctes (A→B et B→A = un seul passage).
|
||||||
|
Set<String> edges = new HashSet<>();
|
||||||
|
for (Room r : rooms) {
|
||||||
|
if (r.getBranches() == null) continue;
|
||||||
|
for (RoomBranch b : r.getBranches()) {
|
||||||
|
String to = b.targetRoomId();
|
||||||
|
if (isBlank(r.getId()) || !ids.contains(to) || r.getId().equals(to)) continue;
|
||||||
|
edges.add(r.getId().compareTo(to) < 0 ? r.getId() + "|" + to : to + "|" + r.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (edges.isEmpty()) return;
|
||||||
|
int components = countComponents(ids, edges);
|
||||||
|
int loops = edges.size() - ids.size() + components;
|
||||||
|
if (loops == 0 && components == 1) {
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-013-LINEAR-DUNGEON", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("rooms", String.valueOf(ids.size()))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int countComponents(Set<String> nodes, Set<String> edges) {
|
||||||
|
Map<String, Set<String>> adj = new HashMap<>();
|
||||||
|
for (String n : nodes) adj.put(n, new HashSet<>());
|
||||||
|
for (String e : edges) {
|
||||||
|
String[] ab = e.split("\\|", 2);
|
||||||
|
adj.get(ab[0]).add(ab[1]);
|
||||||
|
adj.get(ab[1]).add(ab[0]);
|
||||||
|
}
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
int components = 0;
|
||||||
|
for (String start : nodes) {
|
||||||
|
if (!seen.add(start)) continue;
|
||||||
|
components++;
|
||||||
|
Deque<String> stack = new ArrayDeque<>(List.of(start));
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
for (String next : adj.get(stack.pop())) {
|
||||||
|
if (seen.add(next)) stack.push(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return components;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Graphe du chapitre -------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Règles sur la forme du graphe des scènes d'un chapitre, seulement s'il utilise des liens
|
||||||
|
* (sans aucun lien, c'est WRITE-001 qui parle) : WRITE-011 scène isolée, WRITE-012 passage
|
||||||
|
* obligé. Les liens sont internes au chapitre (règle de SceneService).
|
||||||
|
*/
|
||||||
|
private void reviewGraph(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||||
|
if (!usesLinks(scenes)) return;
|
||||||
|
Map<String, Set<String>> next = successors(scenes);
|
||||||
|
Set<String> withIncoming = next.values().stream().flatMap(Set::stream).collect(Collectors.toSet());
|
||||||
|
|
||||||
|
// WRITE-011 — scène isolée : ni lien entrant ni lien sortant (hors scène d'ouverture).
|
||||||
|
for (int i = 1; i < scenes.size(); i++) {
|
||||||
|
Scene s = scenes.get(i);
|
||||||
|
if (next.get(s.getId()).isEmpty() && !withIncoming.contains(s.getId())) {
|
||||||
|
out.add(sceneRemark(arc, chapter, s, "WRITE-011-ISOLATED-SCENE", WritingRemarkCategory.PACING, Map.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkChokepoint(arc, chapter, scenes, next, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-012 — passage obligé : depuis la scène d'ouverture, tous les chemins vers les
|
||||||
|
* fins du chapitre traversent une même scène. Si les joueurs y échouent ou passent à côté,
|
||||||
|
* tout s'arrête. Une seule remarque par chapitre (le premier passage obligé).
|
||||||
|
*/
|
||||||
|
private void checkChokepoint(Arc arc, Chapter chapter, List<Scene> scenes, Map<String, Set<String>> next,
|
||||||
|
List<WritingRemark> out) {
|
||||||
|
if (scenes.size() < CHOKEPOINT_MIN_SCENES) return;
|
||||||
|
String entry = scenes.get(0).getId();
|
||||||
|
if (next.get(entry).isEmpty()) return;
|
||||||
|
Set<String> reachable = reach(entry, next, null);
|
||||||
|
Set<String> ends = reachable.stream().filter(id -> next.get(id).isEmpty()).collect(Collectors.toSet());
|
||||||
|
if (ends.isEmpty()) return; // Boucle sans fin : rien à juger.
|
||||||
|
|
||||||
|
List<Scene> chokepoints = new ArrayList<>();
|
||||||
|
for (Scene s : scenes) {
|
||||||
|
String id = s.getId();
|
||||||
|
if (id.equals(entry) || ends.contains(id) || !reachable.contains(id)) continue;
|
||||||
|
Set<String> without = reach(entry, next, id);
|
||||||
|
if (ends.stream().noneMatch(without::contains)) chokepoints.add(s);
|
||||||
|
}
|
||||||
|
if (chokepoints.isEmpty()) return;
|
||||||
|
out.add(sceneRemark(arc, chapter, chokepoints.get(0), "WRITE-012-CHOKEPOINT", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("count", String.valueOf(chokepoints.size()))));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Successeurs de chaque scène du chapitre (liens vers des scènes du même chapitre seulement). */
|
||||||
|
private static Map<String, Set<String>> successors(List<Scene> scenes) {
|
||||||
|
Set<String> ids = scenes.stream().map(Scene::getId).collect(Collectors.toSet());
|
||||||
|
Map<String, Set<String>> next = new HashMap<>();
|
||||||
|
for (Scene s : scenes) {
|
||||||
|
Set<String> targets = new LinkedHashSet<>();
|
||||||
|
if (s.getBranches() != null) {
|
||||||
|
for (SceneBranch b : s.getBranches()) {
|
||||||
|
String to = b.targetSceneId();
|
||||||
|
if (ids.contains(to) && !to.equals(s.getId())) targets.add(to);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next.put(s.getId(), targets);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scènes atteignables depuis {@code from} en suivant les liens, sans passer par {@code removed}. */
|
||||||
|
private static Set<String> reach(String from, Map<String, Set<String>> next, String removed) {
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
Deque<String> stack = new ArrayDeque<>(List.of(from));
|
||||||
|
seen.add(from);
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
for (String n : next.getOrDefault(stack.pop(), Set.of())) {
|
||||||
|
if (!n.equals(removed) && seen.add(n)) stack.push(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return seen;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le chapitre utilise le graphe : au moins {@link #LINKED_MIN_SCENES} scènes portent des liens. */
|
||||||
|
private static boolean usesLinks(List<Scene> scenes) {
|
||||||
|
return scenes.stream().filter(WritingReviewService::hasBranches).count() >= LINKED_MIN_SCENES;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** WRITE-002 — faux carrefour : plusieurs sorties qui mènent toutes au même endroit. */
|
/** WRITE-002 — faux carrefour : plusieurs sorties qui mènent toutes au même endroit. */
|
||||||
@@ -241,14 +413,21 @@ public class WritingReviewService {
|
|||||||
List<WritingRemark> out) {
|
List<WritingRemark> out) {
|
||||||
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
||||||
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
||||||
long incoming = chapterScenes.stream()
|
List<Scene> sources = chapterScenes.stream()
|
||||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||||
.flatMap(s -> s.getBranches().stream().map(SceneBranch::targetSceneId).distinct())
|
.filter(s -> s.getBranches().stream().anyMatch(b -> scene.getId().equals(b.targetSceneId())))
|
||||||
.filter(scene.getId()::equals)
|
.toList();
|
||||||
.count();
|
if (sources.size() < REVELATION_MIN_INCOMING) {
|
||||||
if (incoming < REVELATION_MIN_INCOMING) {
|
|
||||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||||
Map.of("incoming", String.valueOf(incoming))));
|
Map.of("incoming", String.valueOf(sources.size()))));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// WRITE-015 — assez de chemins, mais tous du même genre (que des interrogatoires…) :
|
||||||
|
// un groupe qui n'aime pas ce genre de scène passe à côté de tous les indices.
|
||||||
|
Set<SceneType> kinds = sources.stream().map(WritingReviewService::typeOf).collect(Collectors.toSet());
|
||||||
|
if (kinds.size() == 1 && !kinds.contains(SceneType.GENERIC)) {
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-015-SAME-SOURCE-CLUES", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("kind", kinds.iterator().next().name(), "count", String.valueOf(sources.size()))));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,7 +449,8 @@ public class WritingReviewService {
|
|||||||
|
|
||||||
/** WRITE-008 — combat sans but : ni choix décrits, ni notes sur les motivations des ennemis. */
|
/** 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) {
|
private void checkCombatPurpose(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||||
if (isCombat(scene) && isBlank(scene.getChoicesConsequences()) && isBlank(scene.getGmSecretNotes())) {
|
if (isCombat(scene) && isBlank(scene.getChoicesConsequences()) && isBlank(scene.getGmSecretNotes())
|
||||||
|
&& isBlank(scene.getTactics())) {
|
||||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-008-COMBAT-NO-PURPOSE", WritingRemarkCategory.STAKES,
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-008-COMBAT-NO-PURPOSE", WritingRemarkCategory.STAKES,
|
||||||
Map.of()));
|
Map.of()));
|
||||||
}
|
}
|
||||||
@@ -288,8 +468,34 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- PNJ ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-016 — opposant ou allié sans motivation : un PNJ qui pèse sur l'intrigue doit
|
||||||
|
* vouloir quelque chose, sinon le MJ ne sait pas comment le faire réagir. Les figurants
|
||||||
|
* et les PNJ sans rôle précisé ne sont pas jugés (pas de bruit sur les seconds rôles).
|
||||||
|
*/
|
||||||
|
private List<WritingRemark> reviewNpcs(String campaignId) {
|
||||||
|
List<WritingRemark> out = new ArrayList<>();
|
||||||
|
for (Npc npc : npcRepository.findByCampaignId(campaignId)) {
|
||||||
|
NpcStory story = npc.getStory();
|
||||||
|
if (story != null && story.drivesThePlot() && story.normalized().motivation() == null) {
|
||||||
|
out.add(new WritingRemark(ReadinessEntityType.NPC, npc.getId(), labelOr(npc.getName(), "PNJ"),
|
||||||
|
"WRITE-016-NPC-NO-MOTIVATION", WritingRemarkCategory.STAKES,
|
||||||
|
Map.of("role", story.normalized().role()), null, null));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Helpers ----------------------------------------------------------------------------
|
// --- Helpers ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Nombre de lignes non vides (une accroche par ligne, puces « - » comprises). */
|
||||||
|
private static int countLines(String text) {
|
||||||
|
if (isBlank(text)) return 0;
|
||||||
|
return (int) text.lines().filter(l -> !l.isBlank()).count();
|
||||||
|
}
|
||||||
|
|
||||||
private static boolean isCombat(Scene scene) {
|
private static boolean isCombat(Scene scene) {
|
||||||
return typeOf(scene) == SceneType.ENCOUNTER
|
return typeOf(scene) == SceneType.ENCOUNTER
|
||||||
|| !isBlank(scene.getCombatDifficulty())
|
|| !isBlank(scene.getCombatDifficulty())
|
||||||
|
|||||||
@@ -15,7 +15,13 @@ import java.util.Locale;
|
|||||||
* @param publicNetworks réseaux connectés classés « Public » que le pare-feu ne laisse pas passer
|
* @param publicNetworks réseaux connectés classés « Public » que le pare-feu ne laisse pas passer
|
||||||
* @param firewallAllowed une règle active autorise l'application sur les réseaux privés
|
* @param firewallAllowed une règle active autorise l'application sur les réseaux privés
|
||||||
* @param firewallBlocked une règle active BLOQUE l'application (ex. « Annuler » dans la fenêtre Windows)
|
* @param firewallBlocked une règle active BLOQUE l'application (ex. « Annuler » dans la fenêtre Windows)
|
||||||
|
* @param thirdPartyFirewalls pare-feu tiers présents : leurs réglages ne sont pas lisibles, donc {@code ready}
|
||||||
|
* ne peut pas être garanti — le front avertit l'utilisateur de les régler lui-même
|
||||||
* @param program exécutable concerné
|
* @param program exécutable concerné
|
||||||
|
* @param platform {@code windows} ou {@code linux}
|
||||||
|
* @param linuxFirewall Linux : pare-feu actif ({@code ufw}, {@code firewalld}, {@code none})
|
||||||
|
* @param portOpen Linux : port autorisé ({@code null} = invérifiable sans droits administrateur)
|
||||||
|
* @param fixCommand Linux : commande à lancer pour ouvrir le port, ou {@code null}
|
||||||
*/
|
*/
|
||||||
public record NetworkReadiness(
|
public record NetworkReadiness(
|
||||||
boolean supported,
|
boolean supported,
|
||||||
@@ -23,7 +29,12 @@ public record NetworkReadiness(
|
|||||||
List<String> publicNetworks,
|
List<String> publicNetworks,
|
||||||
boolean firewallAllowed,
|
boolean firewallAllowed,
|
||||||
boolean firewallBlocked,
|
boolean firewallBlocked,
|
||||||
String program
|
List<String> thirdPartyFirewalls,
|
||||||
|
String program,
|
||||||
|
String platform,
|
||||||
|
String linuxFirewall,
|
||||||
|
Boolean portOpen,
|
||||||
|
String fixCommand
|
||||||
) {
|
) {
|
||||||
|
|
||||||
static final String PUBLIC = "Public";
|
static final String PUBLIC = "Public";
|
||||||
@@ -31,7 +42,10 @@ public record NetworkReadiness(
|
|||||||
|
|
||||||
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
|
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
|
||||||
if (snapshot == null || !snapshot.supported()) {
|
if (snapshot == null || !snapshot.supported()) {
|
||||||
return new NetworkReadiness(false, false, List.of(), false, false, null);
|
return new NetworkReadiness(false, false, List.of(), false, false, List.of(), null, null, null, null, null);
|
||||||
|
}
|
||||||
|
if (NetworkSnapshot.LINUX.equals(snapshot.platform())) {
|
||||||
|
return evaluateLinux(snapshot);
|
||||||
}
|
}
|
||||||
List<NetworkSnapshot.FirewallRule> rules = snapshot.rules() == null ? List.of() : snapshot.rules();
|
List<NetworkSnapshot.FirewallRule> rules = snapshot.rules() == null ? List.of() : snapshot.rules();
|
||||||
boolean allowedPrivate = covers(rules, "Allow", PRIVATE);
|
boolean allowedPrivate = covers(rules, "Allow", PRIVATE);
|
||||||
@@ -46,8 +60,31 @@ public record NetworkReadiness(
|
|||||||
// Un réseau public n'est un obstacle que si le pare-feu ne l'ouvre pas explicitement.
|
// Un réseau public n'est un obstacle que si le pare-feu ne l'ouvre pas explicitement.
|
||||||
List<String> blockingPublic = publicOpen ? List.of() : publicNetworks;
|
List<String> blockingPublic = publicOpen ? List.of() : publicNetworks;
|
||||||
|
|
||||||
|
// « ready » ne porte que sur ce qui est lisible (Windows) ; un pare-feu tiers est signalé à part.
|
||||||
boolean ready = allowedPrivate && !blockedPrivate && blockingPublic.isEmpty();
|
boolean ready = allowedPrivate && !blockedPrivate && blockingPublic.isEmpty();
|
||||||
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, snapshot.program());
|
List<String> thirdParty = snapshot.thirdPartyFirewalls() == null ? List.of() : snapshot.thirdPartyFirewalls();
|
||||||
|
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, thirdParty,
|
||||||
|
snapshot.program(), NetworkSnapshot.WINDOWS, null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Linux : prêt si aucun pare-feu (ufw, firewalld) n'est actif, ou si le port est ouvert.
|
||||||
|
* Port invérifiable (ufw sans droits root) : pas prêt, mais pas en erreur — le front
|
||||||
|
* affiche la commande « au cas où ».
|
||||||
|
*/
|
||||||
|
private static NetworkReadiness evaluateLinux(NetworkSnapshot s) {
|
||||||
|
String fw = s.linuxFirewall() == null ? "none" : s.linuxFirewall();
|
||||||
|
boolean ready = "none".equals(fw) || Boolean.TRUE.equals(s.portOpen());
|
||||||
|
return new NetworkReadiness(true, ready, List.of(), false, false, List.of(), null,
|
||||||
|
NetworkSnapshot.LINUX, fw, s.portOpen(), ready ? null : linuxCommand(fw, s.port()));
|
||||||
|
}
|
||||||
|
|
||||||
|
static String linuxCommand(String firewall, int port) {
|
||||||
|
return switch (firewall) {
|
||||||
|
case "ufw" -> "sudo ufw allow " + port + "/tcp";
|
||||||
|
case "firewalld" -> "sudo firewall-cmd --permanent --add-port=" + port + "/tcp && sudo firewall-cmd --reload";
|
||||||
|
default -> null;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Une règle ACTIVE de cette action couvre-t-elle ce profil (« Any » couvre tout) ? */
|
/** Une règle ACTIVE de cette action couvre-t-elle ce profil (« Any » couvre tout) ? */
|
||||||
|
|||||||
@@ -216,6 +216,11 @@ public class RemoteAccessService {
|
|||||||
return deviceRepository.deleteById(deviceId);
|
return deviceRepository.deleteById(deviceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Port réseau réglé (ouvert ou non) : celui que le pare-feu doit laisser passer. */
|
||||||
|
public synchronized int configuredPort() {
|
||||||
|
return currentConfig().port();
|
||||||
|
}
|
||||||
|
|
||||||
/** Port du connecteur réseau ouvert, ou -1 (pour le filtre : qui vient « de l'extérieur » ?). */
|
/** Port du connecteur réseau ouvert, ou -1 (pour le filtre : qui vient « de l'extérieur » ?). */
|
||||||
public int lanPort() {
|
public int lanPort() {
|
||||||
return lanConnector.runningPort();
|
return lanConnector.runningPort();
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ public class Campaign {
|
|||||||
*/
|
*/
|
||||||
private String graphPositions;
|
private String graphPositions;
|
||||||
|
|
||||||
|
/** Fiche « Publication » (couverture, page technique, crédits…). Null = jamais renseignée. */
|
||||||
|
private CampaignPublication publication;
|
||||||
|
|
||||||
public boolean isLinkedToLore() {
|
public boolean isLinkedToLore() {
|
||||||
return this.loreId != null && !this.loreId.isBlank();
|
return this.loreId != null && !this.loreId.isBlank();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import java.util.function.UnaryOperator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche « Publication » d'une campagne : ce qu'un module vendu ou partagé affiche en
|
||||||
|
* couverture, page technique, introduction pour le MJ et page de crédits.
|
||||||
|
* <p>
|
||||||
|
* Tout est en texte libre (« 1 à 3 », « 3-5 joueurs », « 2 séances de 4 h ») : chaque
|
||||||
|
* système de jeu a ses conventions, l'auteur écrit ce qu'il veut voir imprimé.
|
||||||
|
* Valeur immuable ; {@link #normalized()} nettoie une saisie (blancs → null, longueurs bornées).
|
||||||
|
*
|
||||||
|
* @param subtitle sous-titre de couverture
|
||||||
|
* @param author auteur(s) affichés en couverture
|
||||||
|
* @param system système de jeu tel qu'il doit apparaître (« D&D 5e », « Chroniques Oubliées »)
|
||||||
|
* @param levels niveaux des personnages
|
||||||
|
* @param players nombre de joueurs
|
||||||
|
* @param duration durée de jeu estimée
|
||||||
|
* @param pitch argument : l'aventure en quelques lignes
|
||||||
|
* @param gmBackground contexte caché, réservé au MJ (ce qui s'est vraiment passé)
|
||||||
|
* @param hooks accroches pour impliquer les personnages (une par ligne « - … »)
|
||||||
|
* @param contentWarnings avertissements de contenu (thèmes sensibles)
|
||||||
|
* @param credits crédits : auteur, illustrations, relecture, testeurs…
|
||||||
|
* @param legal licence et mentions légales
|
||||||
|
* @param version version du document (« 1.0 »)
|
||||||
|
* @param coverImageId image de couverture (id d'image), nullable
|
||||||
|
*/
|
||||||
|
public record CampaignPublication(
|
||||||
|
String subtitle,
|
||||||
|
String author,
|
||||||
|
String system,
|
||||||
|
String levels,
|
||||||
|
String players,
|
||||||
|
String duration,
|
||||||
|
String pitch,
|
||||||
|
String gmBackground,
|
||||||
|
String hooks,
|
||||||
|
String contentWarnings,
|
||||||
|
String credits,
|
||||||
|
String legal,
|
||||||
|
String version,
|
||||||
|
String coverImageId
|
||||||
|
) {
|
||||||
|
|
||||||
|
private static final int SHORT_MAX = 200;
|
||||||
|
private static final int LONG_MAX = 20_000;
|
||||||
|
|
||||||
|
public static CampaignPublication empty() {
|
||||||
|
return new CampaignPublication(null, null, null, null, null, null, null,
|
||||||
|
null, null, null, null, null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Copie nettoyée : textes rognés, blancs → null, longueurs bornées. */
|
||||||
|
public CampaignPublication normalized() {
|
||||||
|
UnaryOperator<String> shortText = s -> clean(s, SHORT_MAX);
|
||||||
|
UnaryOperator<String> longText = s -> clean(s, LONG_MAX);
|
||||||
|
return new CampaignPublication(
|
||||||
|
shortText.apply(subtitle), shortText.apply(author), shortText.apply(system),
|
||||||
|
shortText.apply(levels), shortText.apply(players), shortText.apply(duration),
|
||||||
|
longText.apply(pitch), longText.apply(gmBackground), longText.apply(hooks),
|
||||||
|
longText.apply(contentWarnings), longText.apply(credits), longText.apply(legal),
|
||||||
|
shortText.apply(version), shortText.apply(coverImageId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vrai si au moins un champ est renseigné. (Pas de getter {@code isEmpty()} : il serait
|
||||||
|
* sérialisé en JSON comme un champ de plus.)
|
||||||
|
*/
|
||||||
|
public boolean hasContent() {
|
||||||
|
return !normalized().equals(empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Au moins une information de la page technique (système, niveaux, joueurs, durée). */
|
||||||
|
public boolean hasTechnicalSheet() {
|
||||||
|
return present(system) || present(levels) || present(players) || present(duration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Au moins une information de la page de crédits. */
|
||||||
|
public boolean hasCredits() {
|
||||||
|
return present(author) || present(credits) || present(legal) || present(version);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean present(String s) {
|
||||||
|
return s != null && !s.isBlank();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String clean(String s, int max) {
|
||||||
|
if (s == null) return null;
|
||||||
|
String t = s.trim();
|
||||||
|
if (t.isEmpty()) return null;
|
||||||
|
return t.length() > max ? t.substring(0, max) : t;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,6 +60,9 @@ public class Npc {
|
|||||||
/** Ordre d'affichage dans la liste des PNJ de la campagne. */
|
/** Ordre d'affichage dans la liste des PNJ de la campagne. */
|
||||||
private int order;
|
private int order;
|
||||||
|
|
||||||
|
/** Rôle dans l'histoire (rôle, motivation, ce qu'il sait, signe distinctif). Null = non renseigné. */
|
||||||
|
private NpcStory story;
|
||||||
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.bestiary;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche « rôle dans l'histoire » d'un PNJ, indépendante du système de jeu (le gabarit du
|
||||||
|
* système porte les caractéristiques) : ce qui rend le PNJ jouable et utile au récit.
|
||||||
|
*
|
||||||
|
* @param role place dans l'histoire : {@code OPPONENT} (s'oppose aux PJ), {@code ALLY}
|
||||||
|
* (les aide), {@code RESOURCE} (détient une information ou un service),
|
||||||
|
* {@code EXTRA} (figurant) ; null = non précisé
|
||||||
|
* @param motivation ce qu'il veut, et ce qu'il est prêt à faire pour l'obtenir
|
||||||
|
* @param knowledge ce qu'il sait (et peut révéler) — réservé au MJ
|
||||||
|
* @param mannerism signe distinctif à jouer (geste, phrasé, tic)
|
||||||
|
*/
|
||||||
|
public record NpcStory(String role, String motivation, String knowledge, String mannerism) {
|
||||||
|
|
||||||
|
public static final Set<String> ROLES = Set.of("OPPONENT", "ALLY", "RESOURCE", "EXTRA");
|
||||||
|
private static final int SHORT_MAX = 300;
|
||||||
|
private static final int LONG_MAX = 10_000;
|
||||||
|
|
||||||
|
/** Copie nettoyée : rôle inconnu → null, textes rognés (blancs → null) et bornés. */
|
||||||
|
public NpcStory normalized() {
|
||||||
|
String r = role == null ? null : role.trim().toUpperCase(Locale.ROOT);
|
||||||
|
// Set.of(...).contains(null) lève une NullPointerException : rôle absent testé à part.
|
||||||
|
return new NpcStory(r != null && ROLES.contains(r) ? r : null,
|
||||||
|
clean(motivation, LONG_MAX), clean(knowledge, LONG_MAX), clean(mannerism, SHORT_MAX));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vrai si au moins un élément est renseigné. */
|
||||||
|
public boolean hasContent() {
|
||||||
|
NpcStory n = normalized();
|
||||||
|
return n.role() != null || n.motivation() != null || n.knowledge() != null || n.mannerism() != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un PNJ qui pèse sur l'intrigue (opposant ou allié) : sa motivation est attendue. */
|
||||||
|
public boolean drivesThePlot() {
|
||||||
|
String r = normalized().role();
|
||||||
|
return "OPPONENT".equals(r) || "ALLY".equals(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String clean(String s, int max) {
|
||||||
|
if (s == null) return null;
|
||||||
|
String t = s.trim();
|
||||||
|
if (t.isEmpty()) return null;
|
||||||
|
return t.length() > max ? t.substring(0, max) : t;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,6 +38,8 @@ public class Arc {
|
|||||||
private String gmNotes; // Notes privées du MJ (non exportées vers FoundryVTT)
|
private String gmNotes; // Notes privées du MJ (non exportées vers FoundryVTT)
|
||||||
private String rewards; // Récompenses et progression
|
private String rewards; // Récompenses et progression
|
||||||
private String resolution; // Dénouement prévu
|
private String resolution; // Dénouement prévu
|
||||||
|
private String hiddenTruth; // Histoire cachée : ce qui s'est vraiment passé (réservé au MJ)
|
||||||
|
private String hooks; // Accroches : pourquoi les personnages s'en mêlent (une par ligne)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IDs des pages du Lore associées à cet arc (weak cross-context references).
|
* IDs des pages du Lore associées à cet arc (weak cross-context references).
|
||||||
|
|||||||
@@ -48,6 +48,8 @@ public class Scene {
|
|||||||
|
|
||||||
// === Combat ou rencontre ===
|
// === Combat ou rencontre ===
|
||||||
private String combatDifficulty; // Difficulté estimée
|
private String combatDifficulty; // Difficulté estimée
|
||||||
|
private String tactics; // Tactique et moral des adversaires (quand fuient-ils, se rendent-ils ?)
|
||||||
|
private String purpose; // Utilité : ce que l'histoire perd si on coupe la scène
|
||||||
private String enemies; // Liste des ennemis et créatures (texte libre)
|
private String enemies; // Liste des ennemis et créatures (texte libre)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -11,8 +11,31 @@ import java.util.List;
|
|||||||
* @param program exécutable visé par les règles (DM Loremind.exe en bureau)
|
* @param program exécutable visé par les règles (DM Loremind.exe en bureau)
|
||||||
* @param networks réseaux connectés
|
* @param networks réseaux connectés
|
||||||
* @param rules règles entrantes du pare-feu pour ce programme
|
* @param rules règles entrantes du pare-feu pour ce programme
|
||||||
|
* @param thirdPartyFirewalls pare-feu tiers déclarés à Windows (Bitdefender, Norton…) : ils filtrent
|
||||||
|
* EN PLUS du pare-feu Windows, avec leurs propres règles, illisibles d'ici
|
||||||
|
* @param platform {@code windows} ou {@code linux}
|
||||||
|
* @param linuxFirewall Linux : pare-feu actif détecté ({@code ufw}, {@code firewalld}, {@code none})
|
||||||
|
* @param port port réseau de l'accès distant (Linux : port à ouvrir)
|
||||||
|
* @param portOpen Linux : port autorisé par le pare-feu ; {@code null} = impossible à savoir sans
|
||||||
|
* droits administrateur (ex. règles ufw illisibles)
|
||||||
*/
|
*/
|
||||||
public record NetworkSnapshot(boolean supported, String program, List<Network> networks, List<FirewallRule> rules) {
|
public record NetworkSnapshot(boolean supported, String program, List<Network> networks, List<FirewallRule> rules,
|
||||||
|
List<String> thirdPartyFirewalls, String platform, String linuxFirewall,
|
||||||
|
int port, Boolean portOpen) {
|
||||||
|
|
||||||
|
public static final String WINDOWS = "windows";
|
||||||
|
public static final String LINUX = "linux";
|
||||||
|
|
||||||
|
/** Instantané Windows (réseaux, règles du pare-feu, pare-feu tiers). */
|
||||||
|
public NetworkSnapshot(boolean supported, String program, List<Network> networks, List<FirewallRule> rules,
|
||||||
|
List<String> thirdPartyFirewalls) {
|
||||||
|
this(supported, program, networks, rules, thirdPartyFirewalls, WINDOWS, null, 0, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Instantané Linux : pare-feu actif et état du port quand il est lisible. */
|
||||||
|
public static NetworkSnapshot linux(String linuxFirewall, int port, Boolean portOpen) {
|
||||||
|
return new NetworkSnapshot(true, null, List.of(), List.of(), List.of(), LINUX, linuxFirewall, port, portOpen);
|
||||||
|
}
|
||||||
|
|
||||||
/** Catégorie Windows : {@code Public}, {@code Private} ou {@code DomainAuthenticated}. */
|
/** Catégorie Windows : {@code Public}, {@code Private} ou {@code DomainAuthenticated}. */
|
||||||
public record Network(String name, String alias, String category) {}
|
public record Network(String name, String alias, String category) {}
|
||||||
@@ -25,6 +48,6 @@ public record NetworkSnapshot(boolean supported, String program, List<Network> n
|
|||||||
public record FirewallRule(String action, String profile, String enabled) {}
|
public record FirewallRule(String action, String profile, String enabled) {}
|
||||||
|
|
||||||
public static NetworkSnapshot unsupported() {
|
public static NetworkSnapshot unsupported() {
|
||||||
return new NetworkSnapshot(false, null, List.of(), List.of());
|
return new NetworkSnapshot(false, null, List.of(), List.of(), List.of());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ public interface HostNetworkAccess {
|
|||||||
/** Résultat de la demande d'autorisation dans le pare-feu. */
|
/** Résultat de la demande d'autorisation dans le pare-feu. */
|
||||||
enum FirewallFixOutcome { APPLIED, CANCELLED, FAILED, UNSUPPORTED }
|
enum FirewallFixOutcome { APPLIED, CANCELLED, FAILED, UNSUPPORTED }
|
||||||
|
|
||||||
/** Lecture seule, sans droits administrateur. */
|
/** Lecture seule, sans droits administrateur. {@code port} : port réseau de l'accès distant. */
|
||||||
NetworkSnapshot inspect();
|
NetworkSnapshot inspect(int port);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Autorise l'application en entrée sur les réseaux privés. Passe par la confirmation
|
* Autorise l'application en entrée sur les réseaux privés. Passe par la confirmation
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||||
|
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mode bureau : choisit l'accès au pare-feu selon le système — Windows (PowerShell, UAC),
|
||||||
|
* Linux (ufw / firewalld, lecture sans root), sinon rien à vérifier (macOS…).
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
@Profile("local")
|
||||||
|
public class HostNetworkAccessConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public HostNetworkAccess hostNetworkAccess(ObjectMapper objectMapper) {
|
||||||
|
String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
|
||||||
|
if (os.startsWith("windows")) return new WindowsHostNetworkAccess(objectMapper);
|
||||||
|
if (os.contains("linux")) return new LinuxHostNetworkAccess();
|
||||||
|
return new UnsupportedHostNetworkAccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Système sans vérification prise en charge : le front n'affiche pas de diagnostic. */
|
||||||
|
static final class UnsupportedHostNetworkAccess implements HostNetworkAccess {
|
||||||
|
@Override public NetworkSnapshot inspect(int port) { return NetworkSnapshot.unsupported(); }
|
||||||
|
@Override public FirewallFixOutcome allowThroughFirewall() { return FirewallFixOutcome.UNSUPPORTED; }
|
||||||
|
@Override public void openNetworkSettings() { /* rien à ouvrir */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||||
|
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pare-feu sous Linux (Debian, Ubuntu, Fedora…) pour l'accès distant, SANS droits root.
|
||||||
|
* <p>
|
||||||
|
* Ce qu'on peut savoir sans root : quel pare-feu est actif — {@code ufw} via
|
||||||
|
* {@code /etc/ufw/ufw.conf} (lisible par tous), {@code firewalld} via {@code systemctl} — et,
|
||||||
|
* pour firewalld seulement, si le port est ouvert ({@code firewall-cmd --query-port}, autorisé
|
||||||
|
* aux utilisateurs). Les règles d'ufw ne se lisent qu'en root : l'état du port reste alors
|
||||||
|
* inconnu et le front affiche la commande à lancer. Pas d'autorisation en un clic : sur un
|
||||||
|
* serveur sans écran, aucune fenêtre ne peut demander le mot de passe administrateur.
|
||||||
|
* <p>
|
||||||
|
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Linux.
|
||||||
|
*/
|
||||||
|
public class LinuxHostNetworkAccess implements HostNetworkAccess {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(LinuxHostNetworkAccess.class);
|
||||||
|
private static final long COMMAND_TIMEOUT_S = 10;
|
||||||
|
|
||||||
|
static final String UFW = "ufw";
|
||||||
|
static final String FIREWALLD = "firewalld";
|
||||||
|
static final String NONE = "none";
|
||||||
|
|
||||||
|
private final Path ufwConf;
|
||||||
|
|
||||||
|
public LinuxHostNetworkAccess() {
|
||||||
|
this(Path.of("/etc/ufw/ufw.conf"));
|
||||||
|
}
|
||||||
|
|
||||||
|
LinuxHostNetworkAccess(Path ufwConf) {
|
||||||
|
this.ufwConf = ufwConf;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public NetworkSnapshot inspect(int port) {
|
||||||
|
if (ufwEnabled(readQuietly(ufwConf))) {
|
||||||
|
// Règles d'ufw illisibles sans root : état du port inconnu.
|
||||||
|
return NetworkSnapshot.linux(UFW, port, null);
|
||||||
|
}
|
||||||
|
if ("active".equals(run(List.of("systemctl", "is-active", FIREWALLD)).output().trim())) {
|
||||||
|
return NetworkSnapshot.linux(FIREWALLD, port, firewalldPortOpen(port));
|
||||||
|
}
|
||||||
|
return NetworkSnapshot.linux(NONE, port, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FirewallFixOutcome allowThroughFirewall() {
|
||||||
|
return FirewallFixOutcome.UNSUPPORTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void openNetworkSettings() {
|
||||||
|
// Pas de réglage réseau « Public / Privé » à basculer sous Linux.
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code firewall-cmd --query-port} : « yes » (0) / « no » (1) ; autre = inconnu. */
|
||||||
|
private Boolean firewalldPortOpen(int port) {
|
||||||
|
Result r = run(List.of("firewall-cmd", "--query-port=" + port + "/tcp"));
|
||||||
|
return interpretQuery(r.exitCode(), r.output());
|
||||||
|
}
|
||||||
|
|
||||||
|
static Boolean interpretQuery(int exitCode, String output) {
|
||||||
|
String out = output == null ? "" : output.trim().toLowerCase(Locale.ROOT);
|
||||||
|
if (exitCode == 0 && out.startsWith("yes")) return true;
|
||||||
|
if (exitCode == 1 && out.startsWith("no")) return false;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code ENABLED=yes} dans ufw.conf (guillemets et casse tolérés). */
|
||||||
|
static boolean ufwEnabled(String conf) {
|
||||||
|
if (conf == null) return false;
|
||||||
|
return conf.lines()
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(l -> !l.startsWith("#"))
|
||||||
|
.map(l -> l.replace("\"", "").replace("'", "").replace(" ", ""))
|
||||||
|
.anyMatch(l -> l.equalsIgnoreCase("ENABLED=yes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String readQuietly(Path file) {
|
||||||
|
try {
|
||||||
|
return Files.isReadable(file) ? Files.readString(file, StandardCharsets.UTF_8) : null;
|
||||||
|
} catch (IOException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Result(int exitCode, String output) {}
|
||||||
|
|
||||||
|
/** Commande système sans shell (pas d'interprétation), avec délai ; absente → code -1. */
|
||||||
|
private static Result run(List<String> command) {
|
||||||
|
try {
|
||||||
|
Process p = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||||
|
p.getOutputStream().close();
|
||||||
|
if (!p.waitFor(COMMAND_TIMEOUT_S, TimeUnit.SECONDS)) {
|
||||||
|
p.destroyForcibly();
|
||||||
|
return new Result(-1, "");
|
||||||
|
}
|
||||||
|
return new Result(p.exitValue(), new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.debug("Commande {} indisponible : {}", command.get(0), e.getMessage());
|
||||||
|
return new Result(-1, "");
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
return new Result(-1, "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
-7
@@ -6,8 +6,6 @@ import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
|||||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.context.annotation.Profile;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -31,9 +29,9 @@ import java.util.concurrent.TimeUnit;
|
|||||||
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de
|
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de
|
||||||
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable,
|
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable,
|
||||||
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell.
|
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell.
|
||||||
|
* <p>
|
||||||
|
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Windows.
|
||||||
*/
|
*/
|
||||||
@Component
|
|
||||||
@Profile("local")
|
|
||||||
public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(WindowsHostNetworkAccess.class);
|
private static final Logger log = LoggerFactory.getLogger(WindowsHostNetworkAccess.class);
|
||||||
@@ -52,7 +50,7 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public NetworkSnapshot inspect() {
|
public NetworkSnapshot inspect(int port) {
|
||||||
String program = currentProgram();
|
String program = currentProgram();
|
||||||
if (!isWindows() || program == null) return NetworkSnapshot.unsupported();
|
if (!isWindows() || program == null) return NetworkSnapshot.unsupported();
|
||||||
try {
|
try {
|
||||||
@@ -117,7 +115,12 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
||||||
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
|
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
|
||||||
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\n"
|
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\n"
|
||||||
+ "[pscustomobject]@{ networks = $nets; rules = $rules } | ConvertTo-Json -Depth 4 -Compress\n";
|
// Pare-feu TIERS déclarés au Centre de sécurité (le pare-feu Windows n'y figure pas) :
|
||||||
|
// ils filtrent en plus de Windows, avec des règles qu'on ne peut pas lire.
|
||||||
|
+ "$fw = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct | "
|
||||||
|
+ "ForEach-Object { $_.displayName } | Where-Object { $_ -and $_ -notmatch 'Windows' })\n"
|
||||||
|
+ "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | "
|
||||||
|
+ "ConvertTo-Json -Depth 4 -Compress\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -150,7 +153,11 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
for (JsonNode r : array(root.path("rules"))) {
|
for (JsonNode r : array(root.path("rules"))) {
|
||||||
rules.add(new NetworkSnapshot.FirewallRule(text(r, "action"), text(r, "profile"), text(r, "enabled")));
|
rules.add(new NetworkSnapshot.FirewallRule(text(r, "action"), text(r, "profile"), text(r, "enabled")));
|
||||||
}
|
}
|
||||||
return new NetworkSnapshot(true, program, networks, rules);
|
List<String> thirdParty = new ArrayList<>();
|
||||||
|
for (JsonNode f : array(root.path("thirdPartyFirewalls"))) {
|
||||||
|
if (f.isTextual() && !f.asText().isBlank()) thirdParty.add(f.asText());
|
||||||
|
}
|
||||||
|
return new NetworkSnapshot(true, program, networks, rules, thirdParty);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** ConvertTo-Json écrit un objet seul (pas un tableau) quand la liste n'a qu'un élément. */
|
/** ConvertTo-Json écrit un objet seul (pas un tableau) quand la liste n'a qu'un élément. */
|
||||||
|
|||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.converter;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
|
import jakarta.persistence.AttributeConverter;
|
||||||
|
import jakarta.persistence.Converter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convertit la fiche {@link CampaignPublication} en JSON stocké dans une colonne TEXT,
|
||||||
|
* et inversement. Fiche vide → NULL en base. Champs inconnus ignorés (fiche écrite par
|
||||||
|
* une version plus récente).
|
||||||
|
*/
|
||||||
|
@Converter
|
||||||
|
public class CampaignPublicationJsonConverter implements AttributeConverter<CampaignPublication, String> {
|
||||||
|
|
||||||
|
private static final ObjectMapper MAPPER = new ObjectMapper()
|
||||||
|
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String convertToDatabaseColumn(CampaignPublication attribute) {
|
||||||
|
if (attribute == null || !attribute.hasContent()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return MAPPER.writeValueAsString(attribute);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("Erreur sérialisation CampaignPublication → JSON", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CampaignPublication convertToEntityAttribute(String dbData) {
|
||||||
|
if (dbData == null || dbData.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return MAPPER.readValue(dbData, CampaignPublication.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("Erreur désérialisation JSON → CampaignPublication", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.converter;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||||
|
import jakarta.persistence.AttributeConverter;
|
||||||
|
import jakarta.persistence.Converter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convertit la fiche {@link NpcStory} (rôle dans l'histoire d'un PNJ) en JSON stocké dans une colonne TEXT,
|
||||||
|
* et inversement. Fiche vide → NULL en base. Champs inconnus ignorés (fiche écrite par
|
||||||
|
* une version plus récente).
|
||||||
|
*/
|
||||||
|
@Converter
|
||||||
|
public class NpcStoryJsonConverter implements AttributeConverter<NpcStory, String> {
|
||||||
|
|
||||||
|
private static final ObjectMapper MAPPER = new ObjectMapper()
|
||||||
|
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String convertToDatabaseColumn(NpcStory attribute) {
|
||||||
|
if (attribute == null || !attribute.hasContent()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return MAPPER.writeValueAsString(attribute);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("Erreur sérialisation NpcStory → JSON", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public NpcStory convertToEntityAttribute(String dbData) {
|
||||||
|
if (dbData == null || dbData.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return MAPPER.readValue(dbData, NpcStory.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("Erreur désérialisation JSON → NpcStory", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -72,6 +72,12 @@ public class ArcJpaEntity {
|
|||||||
@Column(columnDefinition = "TEXT")
|
@Column(columnDefinition = "TEXT")
|
||||||
private String resolution;
|
private String resolution;
|
||||||
|
|
||||||
|
@Column(name = "hidden_truth", columnDefinition = "TEXT")
|
||||||
|
private String hiddenTruth;
|
||||||
|
|
||||||
|
@Column(name = "hooks", columnDefinition = "TEXT")
|
||||||
|
private String hooks;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IDs des pages du Lore liées à cet arc, stockés en JSON dans une colonne TEXT.
|
* IDs des pages du Lore liées à cet arc, stockés en JSON dans une colonne TEXT.
|
||||||
* Pas de FK cross-context : respect des Bounded Contexts.
|
* Pas de FK cross-context : respect des Bounded Contexts.
|
||||||
|
|||||||
+7
@@ -1,5 +1,7 @@
|
|||||||
package com.loremind.infrastructure.persistence.entity;
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.CampaignPublicationJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -63,6 +65,11 @@ public class CampaignJpaEntity {
|
|||||||
@Column(name = "graph_positions", columnDefinition = "TEXT")
|
@Column(name = "graph_positions", columnDefinition = "TEXT")
|
||||||
private String graphPositions;
|
private String graphPositions;
|
||||||
|
|
||||||
|
/** Fiche « Publication » (JSON). NULL = jamais renseignée. */
|
||||||
|
@Column(name = "publication", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = CampaignPublicationJsonConverter.class)
|
||||||
|
private CampaignPublication publication;
|
||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||||
|
|||||||
@@ -67,6 +67,11 @@ public class NpcJpaEntity {
|
|||||||
@Column(name = "\"order\"", nullable = false)
|
@Column(name = "\"order\"", nullable = false)
|
||||||
private int order;
|
private int order;
|
||||||
|
|
||||||
|
/** Fiche « rôle dans l'histoire » (JSON). NULL = non renseignée. */
|
||||||
|
@Column(name = "story", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = com.loremind.infrastructure.persistence.converter.NpcStoryJsonConverter.class)
|
||||||
|
private com.loremind.domain.campaigncontext.bestiary.NpcStory story;
|
||||||
|
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
|||||||
@@ -78,6 +78,14 @@ public class SceneJpaEntity {
|
|||||||
@Column(name = "choices_consequences", columnDefinition = "TEXT")
|
@Column(name = "choices_consequences", columnDefinition = "TEXT")
|
||||||
private String choicesConsequences;
|
private String choicesConsequences;
|
||||||
|
|
||||||
|
// Tactique et moral des adversaires
|
||||||
|
@Column(name = "tactics", columnDefinition = "TEXT")
|
||||||
|
private String tactics;
|
||||||
|
|
||||||
|
// Utilité de la scène dans l'histoire
|
||||||
|
@Column(name = "purpose", columnDefinition = "TEXT")
|
||||||
|
private String purpose;
|
||||||
|
|
||||||
// Combat
|
// Combat
|
||||||
@Column(name = "combat_difficulty", columnDefinition = "TEXT")
|
@Column(name = "combat_difficulty", columnDefinition = "TEXT")
|
||||||
private String combatDifficulty;
|
private String combatDifficulty;
|
||||||
|
|||||||
+4
@@ -77,6 +77,8 @@ public class PostgresArcRepository implements ArcRepository {
|
|||||||
.gmNotes(jpaEntity.getGmNotes())
|
.gmNotes(jpaEntity.getGmNotes())
|
||||||
.rewards(jpaEntity.getRewards())
|
.rewards(jpaEntity.getRewards())
|
||||||
.resolution(jpaEntity.getResolution())
|
.resolution(jpaEntity.getResolution())
|
||||||
|
.hiddenTruth(jpaEntity.getHiddenTruth())
|
||||||
|
.hooks(jpaEntity.getHooks())
|
||||||
// Defensive copy : jamais de null en domaine pour simplifier les appelants.
|
// Defensive copy : jamais de null en domaine pour simplifier les appelants.
|
||||||
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
||||||
@@ -104,6 +106,8 @@ public class PostgresArcRepository implements ArcRepository {
|
|||||||
.gmNotes(arc.getGmNotes())
|
.gmNotes(arc.getGmNotes())
|
||||||
.rewards(arc.getRewards())
|
.rewards(arc.getRewards())
|
||||||
.resolution(arc.getResolution())
|
.resolution(arc.getResolution())
|
||||||
|
.hiddenTruth(arc.getHiddenTruth())
|
||||||
|
.hooks(arc.getHooks())
|
||||||
.relatedPageIds(arc.getRelatedPageIds() != null
|
.relatedPageIds(arc.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(arc.getRelatedPageIds())
|
? new ArrayList<>(arc.getRelatedPageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
|||||||
+2
@@ -76,6 +76,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
|||||||
.loreId(jpaEntity.getLoreId())
|
.loreId(jpaEntity.getLoreId())
|
||||||
.gameSystemId(jpaEntity.getGameSystemId())
|
.gameSystemId(jpaEntity.getGameSystemId())
|
||||||
.graphPositions(jpaEntity.getGraphPositions())
|
.graphPositions(jpaEntity.getGraphPositions())
|
||||||
|
.publication(jpaEntity.getPublication())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,6 +93,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
|||||||
.loreId(campaign.getLoreId())
|
.loreId(campaign.getLoreId())
|
||||||
.gameSystemId(campaign.getGameSystemId())
|
.gameSystemId(campaign.getGameSystemId())
|
||||||
.graphPositions(campaign.getGraphPositions())
|
.graphPositions(campaign.getGraphPositions())
|
||||||
|
.publication(campaign.getPublication())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
@@ -68,6 +68,7 @@ public class PostgresNpcRepository implements NpcRepository {
|
|||||||
.campaignId(e.getCampaignId().toString())
|
.campaignId(e.getCampaignId().toString())
|
||||||
.relatedPageIds(e.getRelatedPageIds() != null ? new ArrayList<>(e.getRelatedPageIds()) : new ArrayList<>())
|
.relatedPageIds(e.getRelatedPageIds() != null ? new ArrayList<>(e.getRelatedPageIds()) : new ArrayList<>())
|
||||||
.folder(e.getFolder())
|
.folder(e.getFolder())
|
||||||
|
.story(e.getStory())
|
||||||
.order(e.getOrder())
|
.order(e.getOrder())
|
||||||
.createdAt(e.getCreatedAt())
|
.createdAt(e.getCreatedAt())
|
||||||
.updatedAt(e.getUpdatedAt())
|
.updatedAt(e.getUpdatedAt())
|
||||||
@@ -87,6 +88,7 @@ public class PostgresNpcRepository implements NpcRepository {
|
|||||||
.campaignId(Long.parseLong(n.getCampaignId()))
|
.campaignId(Long.parseLong(n.getCampaignId()))
|
||||||
.relatedPageIds(n.getRelatedPageIds() != null ? new ArrayList<>(n.getRelatedPageIds()) : new ArrayList<>())
|
.relatedPageIds(n.getRelatedPageIds() != null ? new ArrayList<>(n.getRelatedPageIds()) : new ArrayList<>())
|
||||||
.folder(n.getFolder())
|
.folder(n.getFolder())
|
||||||
|
.story(n.getStory())
|
||||||
.order(n.getOrder())
|
.order(n.getOrder())
|
||||||
.createdAt(n.getCreatedAt())
|
.createdAt(n.getCreatedAt())
|
||||||
.updatedAt(n.getUpdatedAt())
|
.updatedAt(n.getUpdatedAt())
|
||||||
|
|||||||
+4
@@ -80,6 +80,8 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.gmSecretNotes(jpaEntity.getGmSecretNotes())
|
.gmSecretNotes(jpaEntity.getGmSecretNotes())
|
||||||
.choicesConsequences(jpaEntity.getChoicesConsequences())
|
.choicesConsequences(jpaEntity.getChoicesConsequences())
|
||||||
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
||||||
|
.tactics(jpaEntity.getTactics())
|
||||||
|
.purpose(jpaEntity.getPurpose())
|
||||||
.enemies(jpaEntity.getEnemies())
|
.enemies(jpaEntity.getEnemies())
|
||||||
.enemyIds(jpaEntity.getEnemyIds() != null
|
.enemyIds(jpaEntity.getEnemyIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getEnemyIds())
|
? new ArrayList<>(jpaEntity.getEnemyIds())
|
||||||
@@ -123,6 +125,8 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.gmSecretNotes(scene.getGmSecretNotes())
|
.gmSecretNotes(scene.getGmSecretNotes())
|
||||||
.choicesConsequences(scene.getChoicesConsequences())
|
.choicesConsequences(scene.getChoicesConsequences())
|
||||||
.combatDifficulty(scene.getCombatDifficulty())
|
.combatDifficulty(scene.getCombatDifficulty())
|
||||||
|
.tactics(scene.getTactics())
|
||||||
|
.purpose(scene.getPurpose())
|
||||||
.enemies(scene.getEnemies())
|
.enemies(scene.getEnemies())
|
||||||
.enemyIds(scene.getEnemyIds() != null
|
.enemyIds(scene.getEnemyIds() != null
|
||||||
? new ArrayList<>(scene.getEnemyIds())
|
? new ArrayList<>(scene.getEnemyIds())
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.infrastructure.transfer;
|
package com.loremind.infrastructure.transfer;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||||
@@ -99,11 +100,20 @@ class CampaignContentInserter {
|
|||||||
e.setPlayerCount(d.playerCount());
|
e.setPlayerCount(d.playerCount());
|
||||||
e.setLoreId(d.loreId()); // remappe en 2e passe
|
e.setLoreId(d.loreId()); // remappe en 2e passe
|
||||||
e.setGameSystemId(d.gameSystemId()); // remappe en 2e passe
|
e.setGameSystemId(d.gameSystemId()); // remappe en 2e passe
|
||||||
|
e.setPublication(remapCover(maps, d.publication()));
|
||||||
maps.campaignMap.put(d.id(), campaignRepo.save(e).getId());
|
maps.campaignMap.put(d.id(), campaignRepo.save(e).getId());
|
||||||
}
|
}
|
||||||
result.count("campaigns", maps.campaignMap.size());
|
result.count("campaigns", maps.campaignMap.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fiche « Publication » : l'image de couverture suit le remapping des images importées. */
|
||||||
|
private static CampaignPublication remapCover(ImportIdMaps maps, CampaignPublication p) {
|
||||||
|
if (p == null || p.coverImageId() == null) return p;
|
||||||
|
return new CampaignPublication(p.subtitle(), p.author(), p.system(), p.levels(), p.players(),
|
||||||
|
p.duration(), p.pitch(), p.gmBackground(), p.hooks(), p.contentWarnings(), p.credits(),
|
||||||
|
p.legal(), p.version(), IdRemapper.remapStringId(maps.imageMap, p.coverImageId()));
|
||||||
|
}
|
||||||
|
|
||||||
/** Arc (relatedPageIds remappe en 2e passe). */
|
/** Arc (relatedPageIds remappe en 2e passe). */
|
||||||
private void insertArcs(ContentExport export, ImportIdMaps maps, ImportResult.Builder result) {
|
private void insertArcs(ContentExport export, ImportIdMaps maps, ImportResult.Builder result) {
|
||||||
for (ContentExport.ArcDto d : nullSafe(export.arcs())) {
|
for (ContentExport.ArcDto d : nullSafe(export.arcs())) {
|
||||||
@@ -119,6 +129,8 @@ class CampaignContentInserter {
|
|||||||
e.setGmNotes(d.gmNotes());
|
e.setGmNotes(d.gmNotes());
|
||||||
e.setRewards(d.rewards());
|
e.setRewards(d.rewards());
|
||||||
e.setResolution(d.resolution());
|
e.setResolution(d.resolution());
|
||||||
|
e.setHiddenTruth(d.hiddenTruth());
|
||||||
|
e.setHooks(d.hooks());
|
||||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
||||||
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
||||||
maps.arcMap.put(d.id(), arcRepo.save(e).getId());
|
maps.arcMap.put(d.id(), arcRepo.save(e).getId());
|
||||||
@@ -257,6 +269,7 @@ class CampaignContentInserter {
|
|||||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
||||||
e.setFolder(d.folder());
|
e.setFolder(d.folder());
|
||||||
e.setOrder(d.order());
|
e.setOrder(d.order());
|
||||||
|
e.setStory(d.story());
|
||||||
maps.npcMap.put(d.id(), npcRepo.save(e).getId());
|
maps.npcMap.put(d.id(), npcRepo.save(e).getId());
|
||||||
}
|
}
|
||||||
result.count("npcs", maps.npcMap.size());
|
result.count("npcs", maps.npcMap.size());
|
||||||
@@ -307,6 +320,8 @@ class CampaignContentInserter {
|
|||||||
e.setBattlemaps(resolveBattlemaps(d, maps));
|
e.setBattlemaps(resolveBattlemaps(d, maps));
|
||||||
e.setGraphX(d.graphX());
|
e.setGraphX(d.graphX());
|
||||||
e.setGraphY(d.graphY());
|
e.setGraphY(d.graphY());
|
||||||
|
e.setTactics(d.tactics());
|
||||||
|
e.setPurpose(d.purpose());
|
||||||
e.setBranches(d.branches()); // remappe en 2e passe
|
e.setBranches(d.branches()); // remappe en 2e passe
|
||||||
// Rooms : l'id (UUID) et les branches restent tels quels ; seules leurs refs
|
// Rooms : l'id (UUID) et les branches restent tels quels ; seules leurs refs
|
||||||
// d'images (galerie + plan) sont remappees vers les images importees.
|
// d'images (galerie + plan) sont remappees vers les images importees.
|
||||||
|
|||||||
@@ -200,7 +200,7 @@ public class ExportService {
|
|||||||
List<QuestJpaEntity> campaignQuests = questRepo.findByCampaignId(cid);
|
List<QuestJpaEntity> campaignQuests = questRepo.findByCampaignId(cid);
|
||||||
// Images/fichiers : uniquement les binaires RÉFÉRENCÉS par la clôture (si option active).
|
// Images/fichiers : uniquement les binaires RÉFÉRENCÉS par la clôture (si option active).
|
||||||
BinaryClosure binaries = req.includeImages()
|
BinaryClosure binaries = req.includeImages()
|
||||||
? loadBinaryClosure(structure, lore, play, campaignQuests) : BinaryClosure.EMPTY;
|
? loadBinaryClosure(campaign, structure, lore, play, campaignQuests) : BinaryClosure.EMPTY;
|
||||||
|
|
||||||
ContentExport.CampaignDto campaignDto = campaignDto(campaign, req.includeLore());
|
ContentExport.CampaignDto campaignDto = campaignDto(campaign, req.includeLore());
|
||||||
|
|
||||||
@@ -304,9 +304,11 @@ public class ExportService {
|
|||||||
private static final BinaryClosure EMPTY = new BinaryClosure(List.of(), List.of());
|
private static final BinaryClosure EMPTY = new BinaryClosure(List.of(), List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
private BinaryClosure loadBinaryClosure(StructuralClosure structure, LoreClosure lore, PlayClosure play,
|
private BinaryClosure loadBinaryClosure(CampaignJpaEntity campaign, StructuralClosure structure,
|
||||||
|
LoreClosure lore, PlayClosure play,
|
||||||
List<QuestJpaEntity> campaignQuests) {
|
List<QuestJpaEntity> campaignQuests) {
|
||||||
Set<String> imageRefs = new LinkedHashSet<>();
|
Set<String> imageRefs = new LinkedHashSet<>();
|
||||||
|
if (campaign.getPublication() != null) add(imageRefs, campaign.getPublication().coverImageId());
|
||||||
structure.arcs().forEach(a -> addAll(imageRefs, a.getIllustrationImageIds()));
|
structure.arcs().forEach(a -> addAll(imageRefs, a.getIllustrationImageIds()));
|
||||||
structure.chapters().forEach(c -> addAll(imageRefs, c.getIllustrationImageIds()));
|
structure.chapters().forEach(c -> addAll(imageRefs, c.getIllustrationImageIds()));
|
||||||
campaignQuests.forEach(q -> addAll(imageRefs, q.getIllustrationImageIds()));
|
campaignQuests.forEach(q -> addAll(imageRefs, q.getIllustrationImageIds()));
|
||||||
@@ -340,7 +342,7 @@ public class ExportService {
|
|||||||
ContentExport.CampaignDto dto = toCampaignDto(campaign);
|
ContentExport.CampaignDto dto = toCampaignDto(campaign);
|
||||||
if (includeLore) return dto;
|
if (includeLore) return dto;
|
||||||
return new ContentExport.CampaignDto(dto.id(), dto.name(), dto.description(),
|
return new ContentExport.CampaignDto(dto.id(), dto.name(), dto.description(),
|
||||||
dto.arcsCount(), dto.playerCount(), null, dto.gameSystemId());
|
dto.arcsCount(), dto.playerCount(), null, dto.gameSystemId(), dto.publication());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ----- Helpers de chargement -----
|
// ----- Helpers de chargement -----
|
||||||
@@ -471,6 +473,9 @@ public class ExportService {
|
|||||||
/** Collecte les IDs d'images référencés par toutes les entités exportées (avant résolution en storageKey). */
|
/** Collecte les IDs d'images référencés par toutes les entités exportées (avant résolution en storageKey). */
|
||||||
private Set<String> collectImageIdRefs(ContentExport export) {
|
private Set<String> collectImageIdRefs(ContentExport export) {
|
||||||
Set<String> refs = new LinkedHashSet<>();
|
Set<String> refs = new LinkedHashSet<>();
|
||||||
|
for (ContentExport.CampaignDto c : export.campaigns()) {
|
||||||
|
if (c.publication() != null) add(refs, c.publication().coverImageId());
|
||||||
|
}
|
||||||
for (ContentExport.ArcDto a : export.arcs()) addAll(refs, a.illustrationImageIds());
|
for (ContentExport.ArcDto a : export.arcs()) addAll(refs, a.illustrationImageIds());
|
||||||
for (ContentExport.ChapterDto c : export.chapters()) addAll(refs, c.illustrationImageIds());
|
for (ContentExport.ChapterDto c : export.chapters()) addAll(refs, c.illustrationImageIds());
|
||||||
addQuestImageRefs(refs, export.quests());
|
addQuestImageRefs(refs, export.quests());
|
||||||
@@ -599,7 +604,8 @@ public class ExportService {
|
|||||||
|
|
||||||
private ContentExport.CampaignDto toCampaignDto(CampaignJpaEntity e) {
|
private ContentExport.CampaignDto toCampaignDto(CampaignJpaEntity e) {
|
||||||
return new ContentExport.CampaignDto(e.getId(), e.getName(), e.getDescription(),
|
return new ContentExport.CampaignDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
e.getArcsCount(), e.getPlayerCount(), e.getLoreId(), e.getGameSystemId());
|
e.getArcsCount(), e.getPlayerCount(), e.getLoreId(), e.getGameSystemId(),
|
||||||
|
e.getPublication());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.ArcDto toArcDto(ArcJpaEntity e) {
|
private ContentExport.ArcDto toArcDto(ArcJpaEntity e) {
|
||||||
@@ -608,7 +614,7 @@ public class ExportService {
|
|||||||
e.getType() != null ? e.getType().name() : null,
|
e.getType() != null ? e.getType().name() : null,
|
||||||
e.getIcon(), e.getThemes(), e.getStakes(), e.getGmNotes(),
|
e.getIcon(), e.getThemes(), e.getStakes(), e.getGmNotes(),
|
||||||
e.getRewards(), e.getResolution(), e.getRelatedPageIds(),
|
e.getRewards(), e.getResolution(), e.getRelatedPageIds(),
|
||||||
e.getIllustrationImageIds());
|
e.getIllustrationImageIds(), e.getHiddenTruth(), e.getHooks());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.ChapterDto toChapterDto(ChapterJpaEntity e) {
|
private ContentExport.ChapterDto toChapterDto(ChapterJpaEntity e) {
|
||||||
@@ -637,7 +643,7 @@ public class ExportService {
|
|||||||
e.getEnemies(), e.getEnemyIds(), e.getRelatedPageIds(),
|
e.getEnemies(), e.getEnemyIds(), e.getRelatedPageIds(),
|
||||||
e.getIllustrationImageIds(), null, null, // legacy battlemap : plus émis
|
e.getIllustrationImageIds(), null, null, // legacy battlemap : plus émis
|
||||||
e.getBattlemaps(), e.getBranches(), e.getRooms(), e.getType(),
|
e.getBattlemaps(), e.getBranches(), e.getRooms(), e.getType(),
|
||||||
e.getGraphX(), e.getGraphY());
|
e.getGraphX(), e.getGraphY(), e.getTactics(), e.getPurpose());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.CharacterDto toCharacterDto(CharacterJpaEntity e) {
|
private ContentExport.CharacterDto toCharacterDto(CharacterJpaEntity e) {
|
||||||
@@ -649,7 +655,7 @@ public class ExportService {
|
|||||||
private ContentExport.NpcDto toNpcDto(NpcJpaEntity e) {
|
private ContentExport.NpcDto toNpcDto(NpcJpaEntity e) {
|
||||||
return new ContentExport.NpcDto(e.getId(), e.getName(), e.getPortraitImageId(),
|
return new ContentExport.NpcDto(e.getId(), e.getName(), e.getPortraitImageId(),
|
||||||
e.getHeaderImageId(), e.getValues(), e.getImageValues(), e.getKeyValueValues(),
|
e.getHeaderImageId(), e.getValues(), e.getImageValues(), e.getKeyValueValues(),
|
||||||
e.getCampaignId(), e.getRelatedPageIds(), e.getFolder(), e.getOrder());
|
e.getCampaignId(), e.getRelatedPageIds(), e.getFolder(), e.getOrder(), e.getStory());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.EnemyDto toEnemyDto(EnemyJpaEntity e) {
|
private ContentExport.EnemyDto toEnemyDto(EnemyJpaEntity e) {
|
||||||
|
|||||||
@@ -128,7 +128,9 @@ public record ContentExport(
|
|||||||
int arcsCount,
|
int arcsCount,
|
||||||
int playerCount,
|
int playerCount,
|
||||||
String loreId,
|
String loreId,
|
||||||
String gameSystemId
|
String gameSystemId,
|
||||||
|
/** Fiche « Publication » ; absente des bundles antérieurs (null). */
|
||||||
|
com.loremind.domain.campaigncontext.CampaignPublication publication
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record ArcDto(
|
public record ArcDto(
|
||||||
@@ -145,7 +147,10 @@ public record ContentExport(
|
|||||||
String rewards,
|
String rewards,
|
||||||
String resolution,
|
String resolution,
|
||||||
List<String> relatedPageIds,
|
List<String> relatedPageIds,
|
||||||
List<String> illustrationImageIds
|
List<String> illustrationImageIds,
|
||||||
|
/** Histoire cachée et accroches ; absentes des bundles antérieurs (null). */
|
||||||
|
String hiddenTruth,
|
||||||
|
String hooks
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record ChapterDto(
|
public record ChapterDto(
|
||||||
@@ -195,7 +200,10 @@ public record ContentExport(
|
|||||||
List<Room> rooms,
|
List<Room> rooms,
|
||||||
SceneType type,
|
SceneType type,
|
||||||
Double graphX,
|
Double graphX,
|
||||||
Double graphY
|
Double graphY,
|
||||||
|
/** Tactique des adversaires et utilité ; absentes des bundles antérieurs (null). */
|
||||||
|
String tactics,
|
||||||
|
String purpose
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record CharacterDto(
|
public record CharacterDto(
|
||||||
@@ -222,7 +230,9 @@ public record ContentExport(
|
|||||||
Long campaignId,
|
Long campaignId,
|
||||||
List<String> relatedPageIds,
|
List<String> relatedPageIds,
|
||||||
String folder,
|
String folder,
|
||||||
int order
|
int order,
|
||||||
|
/** Rôle dans l'histoire ; absent des bundles antérieurs (null). */
|
||||||
|
com.loremind.domain.campaigncontext.bestiary.NpcStory story
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record EnemyDto(
|
public record EnemyDto(
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Room;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.ArcJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.ChapterJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SceneJpaEntity;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annexes d'un module publie : ce que le MJ consulte en jeu sans feuilleter tout le livret.
|
||||||
|
* <ul>
|
||||||
|
* <li>Revelations et indices : pour chaque revelation, les scenes qui y menent (et leur page) —
|
||||||
|
* le MJ voit d'un coup d'oeil ce que les joueurs peuvent encore decouvrir ;</li>
|
||||||
|
* <li>index des PNJ et des adversaires (avec les scenes ou ces derniers apparaissent) ;</li>
|
||||||
|
* <li>cartes : chaque battlemap et plan de piece sur sa propre page paysage, en grand,
|
||||||
|
* prete a imprimer ou a montrer aux joueurs.</li>
|
||||||
|
* </ul>
|
||||||
|
* Les renvois vers des parties absentes sont neutralises en fin de rendu ({@link PdfHtml#resolveRefs}).
|
||||||
|
*/
|
||||||
|
final class PdfAppendices {
|
||||||
|
|
||||||
|
/** Une carte rendue en pleine page paysage dans l'annexe. */
|
||||||
|
record MapPage(String anchor, String title, PdfImage image) {}
|
||||||
|
|
||||||
|
/** Ligne d'index (PNJ ou adversaire). */
|
||||||
|
record IndexRow(String anchor, String name, String folder, String level) {}
|
||||||
|
|
||||||
|
/** Resolution des cartes en annexe (plus fine que les illustrations : elles sont imprimees en grand). */
|
||||||
|
static final int MAP_MAX = 2400;
|
||||||
|
private static final String TD_OPEN = "<td>";
|
||||||
|
private static final String TD_CLOSE = "</td>";
|
||||||
|
|
||||||
|
private PdfAppendices() {}
|
||||||
|
|
||||||
|
// ====================================================================== Cartes
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cartes de chaque scene, dans l'ordre du livret : battlemaps (images uniquement) puis
|
||||||
|
* plans des pieces. Encodees UNE fois : la scene y renvoie, l'annexe les affiche.
|
||||||
|
*/
|
||||||
|
static Map<Long, List<MapPage>> collectMaps(Structure st, PdfImageEncoder encoder) {
|
||||||
|
Map<Long, List<MapPage>> maps = new LinkedHashMap<>();
|
||||||
|
for (SceneJpaEntity sc : scenesInOrder(st)) {
|
||||||
|
List<MapPage> pages = new ArrayList<>();
|
||||||
|
if (sc.getBattlemaps() != null) {
|
||||||
|
int i = 0;
|
||||||
|
for (var bm : sc.getBattlemaps()) {
|
||||||
|
PdfImage img = encoder.fileImage(bm.mediaFileId(), MAP_MAX);
|
||||||
|
if (img == null) continue;
|
||||||
|
String label = notBlank(bm.label()) ? sc.getName() + " — " + bm.label().trim() : sc.getName();
|
||||||
|
pages.add(new MapPage("map-" + sc.getId() + "-" + (i++), label, img));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sc.getRooms() != null) {
|
||||||
|
List<Room> rooms = new ArrayList<>(sc.getRooms());
|
||||||
|
rooms.sort(Comparator.comparingInt(Room::getOrder));
|
||||||
|
for (Room r : rooms) {
|
||||||
|
PdfImage img = encoder.image(r.getMapImageId(), MAP_MAX);
|
||||||
|
if (img != null) {
|
||||||
|
pages.add(new MapPage(roomMapAnchor(sc.getId(), r.getId()),
|
||||||
|
sc.getName() + " — Plan : " + r.getName(), img));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!pages.isEmpty()) maps.put(sc.getId(), pages);
|
||||||
|
}
|
||||||
|
return maps;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String roomMapAnchor(Long sceneId, String roomId) {
|
||||||
|
return "map-room-" + sceneId + "-" + (roomId == null ? "x" : roomId.replaceAll("[^A-Za-z0-9_-]", ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Partie « Cartes » : une carte par page paysage (page nommee {@code landscape}), titre
|
||||||
|
* en tete, image la plus grande possible sans deformation.
|
||||||
|
*/
|
||||||
|
static void mapsPart(PdfExportService.Ctx ctx, Map<Long, List<MapPage>> maps) {
|
||||||
|
if (maps.isEmpty()) return;
|
||||||
|
StringBuilder b = ctx.body;
|
||||||
|
PdfExportOptions.PageFormat format = ctx.opt.format();
|
||||||
|
// Page paysage : largeur = hauteur du format portrait. Marges 1 cm, ~1,6 cm pour le titre.
|
||||||
|
double pageW = format.landscapeWidthCm() - 2.0;
|
||||||
|
double pageH = format.widthCm - 2.0 - 1.6;
|
||||||
|
StringBuilder bms = new StringBuilder();
|
||||||
|
boolean first = true;
|
||||||
|
for (List<MapPage> pages : maps.values()) {
|
||||||
|
for (MapPage p : pages) {
|
||||||
|
b.append("<div class=\"map-page\"");
|
||||||
|
if (first) b.append(" id=\"part-maps\"");
|
||||||
|
b.append("><div class=\"map-title\" id=\"").append(p.anchor()).append("\">")
|
||||||
|
.append(esc(p.title())).append("</div>");
|
||||||
|
double w = Math.min(pageW, pageH * p.image().w() / p.image().h());
|
||||||
|
b.append("<img style=\"width:").append(cm(w)).append("\" src=\"").append(p.image().uri()).append("\"/>");
|
||||||
|
b.append(DIV_CLOSE);
|
||||||
|
bms.append(bookmark(p.title(), p.anchor(), ""));
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.addToc(0, "Cartes", "part-maps");
|
||||||
|
ctx.bookmarks.append(bookmark("Cartes", "part-maps", bms.toString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====================================================================== Annexes MJ
|
||||||
|
|
||||||
|
/** Revelations et indices : chaque scene REVELATION, et les scenes qui y menent. */
|
||||||
|
static void revelations(StringBuilder b, Structure st) {
|
||||||
|
List<SceneJpaEntity> scenes = scenesInOrder(st);
|
||||||
|
List<SceneJpaEntity> revelations = scenes.stream()
|
||||||
|
.filter(s -> s.getType() == SceneType.REVELATION).toList();
|
||||||
|
if (revelations.isEmpty()) return;
|
||||||
|
|
||||||
|
b.append("<h2 class=\"section-head\" id=\"annex-revelations\">Révélations et indices</h2>");
|
||||||
|
b.append("<p class=\"prose annex-intro\">Pour chaque révélation, les scènes qui permettent de la "
|
||||||
|
+ "découvrir. Visez au moins trois chemins : les joueurs en manqueront toujours un.</p>");
|
||||||
|
b.append("<table class=\"stats-table annex-table\"><thead><tr><th>Révélation</th>"
|
||||||
|
+ "<th>Y mènent</th></tr></thead><tbody>");
|
||||||
|
int row = 0;
|
||||||
|
for (SceneJpaEntity rev : revelations) {
|
||||||
|
String anchor = "scene-" + rev.getId();
|
||||||
|
b.append(trTag(row++)).append(TD_OPEN).append(xref(anchor, rev.getName())).append(' ')
|
||||||
|
.append(pageRef(anchor)).append(TD_CLOSE).append(TD_OPEN);
|
||||||
|
List<String> sources = incoming(rev, scenes);
|
||||||
|
if (sources.isEmpty()) {
|
||||||
|
b.append("<span class=\"annex-warn\">Aucune scène n'y mène.</span>");
|
||||||
|
} else {
|
||||||
|
b.append("<ul class=\"annex-list\">");
|
||||||
|
for (String s : sources) b.append("<li>").append(s).append("</li>");
|
||||||
|
b.append("</ul>");
|
||||||
|
}
|
||||||
|
b.append(TD_TR_CLOSE);
|
||||||
|
}
|
||||||
|
b.append(TBODY_TABLE_CLOSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scenes (du meme chapitre) qui ont un lien vers {@code target}, en HTML avec renvoi. */
|
||||||
|
private static List<String> incoming(SceneJpaEntity target, List<SceneJpaEntity> scenes) {
|
||||||
|
String targetId = String.valueOf(target.getId());
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
for (SceneJpaEntity s : scenes) {
|
||||||
|
if (s.getBranches() == null || Objects.equals(s.getId(), target.getId())) continue;
|
||||||
|
for (SceneBranch br : s.getBranches()) {
|
||||||
|
if (!targetId.equals(br.targetSceneId())) continue;
|
||||||
|
String anchor = "scene-" + s.getId();
|
||||||
|
StringBuilder line = new StringBuilder(xref(anchor, s.getName())).append(' ').append(pageRef(anchor));
|
||||||
|
if (br.kind() == LinkType.CLUE) line.append(" <span class=\"annex-kind\">indice</span>");
|
||||||
|
else if (br.kind() == LinkType.LEAD) line.append(" <span class=\"annex-kind\">piste</span>");
|
||||||
|
if (notBlank(br.label())) line.append(" — ").append(esc(br.label().trim()));
|
||||||
|
out.add(line.toString());
|
||||||
|
break; // une ligne par scene source
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Index alphabetique : nom (renvoi), dossier, niveau eventuel, apparitions eventuelles, page. */
|
||||||
|
static void index(StringBuilder b, String anchorId, String title, List<IndexRow> rows,
|
||||||
|
Map<String, List<String>> appearances) {
|
||||||
|
if (rows.isEmpty()) return;
|
||||||
|
List<IndexRow> sorted = new ArrayList<>(rows);
|
||||||
|
sorted.sort(Comparator.comparing(r -> r.name() == null ? "" : r.name().toLowerCase(Locale.ROOT)));
|
||||||
|
boolean withLevel = sorted.stream().anyMatch(r -> notBlank(r.level()));
|
||||||
|
boolean withAppearances = appearances != null && !appearances.isEmpty();
|
||||||
|
|
||||||
|
b.append("<h2 class=\"section-head\" id=\"").append(anchorId).append("\">").append(esc(title)).append("</h2>");
|
||||||
|
b.append("<table class=\"stats-table annex-table\"><thead><tr><th>Nom</th><th>Dossier</th>");
|
||||||
|
if (withLevel) b.append("<th>Niv.</th>");
|
||||||
|
if (withAppearances) b.append("<th>Apparaît dans</th>");
|
||||||
|
b.append("<th class=\"page-col\">Page</th></tr></thead><tbody>");
|
||||||
|
int row = 0;
|
||||||
|
for (IndexRow r : sorted) {
|
||||||
|
b.append(trTag(row++)).append(TD_OPEN).append(xref(r.anchor(), r.name())).append(TD_CLOSE)
|
||||||
|
.append(TD_OPEN).append(esc(notBlank(r.folder()) ? r.folder().replace("/", " / ") : "—")).append(TD_CLOSE);
|
||||||
|
if (withLevel) b.append(TD_OPEN).append(esc(notBlank(r.level()) ? r.level() : "—")).append(TD_CLOSE);
|
||||||
|
if (withAppearances) {
|
||||||
|
List<String> where = appearances.getOrDefault(r.anchor(), List.of());
|
||||||
|
b.append(TD_OPEN).append(where.isEmpty() ? "—" : String.join(", ", where)).append(TD_CLOSE);
|
||||||
|
}
|
||||||
|
b.append("<td class=\"page-col\">").append(pageRef(r.anchor())).append(TD_TR_CLOSE);
|
||||||
|
}
|
||||||
|
b.append(TBODY_TABLE_CLOSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ou apparait chaque adversaire : ancre de sa fiche ({@code enemy-<id>}) -> scenes
|
||||||
|
* (renvois) qui le citent, dans la scene elle-meme ou dans l'une de ses pieces.
|
||||||
|
*/
|
||||||
|
static Map<String, List<String>> enemyAppearances(Structure st) {
|
||||||
|
Map<String, Set<Long>> sceneIdsByEnemy = new LinkedHashMap<>();
|
||||||
|
Map<Long, SceneJpaEntity> byId = new LinkedHashMap<>();
|
||||||
|
for (SceneJpaEntity sc : scenesInOrder(st)) {
|
||||||
|
byId.put(sc.getId(), sc);
|
||||||
|
List<String> ids = new ArrayList<>();
|
||||||
|
if (sc.getEnemyIds() != null) ids.addAll(sc.getEnemyIds());
|
||||||
|
if (sc.getRooms() != null) {
|
||||||
|
for (Room r : sc.getRooms()) if (r.getEnemyIds() != null) ids.addAll(r.getEnemyIds());
|
||||||
|
}
|
||||||
|
for (String id : ids) {
|
||||||
|
if (notBlank(id)) sceneIdsByEnemy.computeIfAbsent("enemy-" + id.trim(), k -> new LinkedHashSet<>()).add(sc.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Map<String, List<String>> out = new LinkedHashMap<>();
|
||||||
|
sceneIdsByEnemy.forEach((enemyAnchor, sceneIds) -> {
|
||||||
|
List<String> refs = new ArrayList<>();
|
||||||
|
for (Long sid : sceneIds) {
|
||||||
|
String anchor = "scene-" + sid;
|
||||||
|
refs.add(xref(anchor, byId.get(sid).getName()) + " " + pageRef(anchor));
|
||||||
|
}
|
||||||
|
out.put(enemyAnchor, refs);
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Toutes les scenes dans l'ordre du livret (arcs, chapitres, scenes). */
|
||||||
|
private static List<SceneJpaEntity> scenesInOrder(Structure st) {
|
||||||
|
List<SceneJpaEntity> out = new ArrayList<>();
|
||||||
|
for (ArcJpaEntity arc : st.arcs) {
|
||||||
|
for (ChapterJpaEntity ch : st.chaptersByArc.getOrDefault(arc.getId(), List.of())) {
|
||||||
|
out.addAll(st.scenesByChapter.getOrDefault(ch.getId(), List.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Options de l'export PDF choisies par l'utilisateur.
|
||||||
|
*
|
||||||
|
* @param gmContent vrai = version MJ complète ; faux = version joueurs (aucun secret :
|
||||||
|
* notes MJ, conséquences, sorties, combats, contexte caché…)
|
||||||
|
* @param format format de page
|
||||||
|
* @param printFriendly vrai = sans aplats de couleur (économie d'encre)
|
||||||
|
* @param sections parties incluses
|
||||||
|
* @param loreScope pages de lore incluses (si la partie Lore est demandée)
|
||||||
|
*/
|
||||||
|
public record PdfExportOptions(boolean gmContent, PageFormat format, boolean printFriendly,
|
||||||
|
Set<Section> sections, LoreScope loreScope) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parties du livret qu'on peut inclure ou non. APPENDIX = annexes MJ (revelations et
|
||||||
|
* indices, index PNJ et adversaires ; jamais en version joueurs) ; MAPS = cartes en
|
||||||
|
* pleine page paysage (les scenes y renvoient au lieu de les afficher en petit).
|
||||||
|
*/
|
||||||
|
public enum Section { NARRATIVE, QUESTS, NPCS, ENEMIES, TABLES, LORE, APPENDIX, MAPS }
|
||||||
|
|
||||||
|
/** Pages de lore exportées : toutes, ou seulement celles liées au contenu de la campagne. */
|
||||||
|
public enum LoreScope { ALL, LINKED }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format de page : dimensions (cm), marges (haut, côtés, bas) et taille du texte courant.
|
||||||
|
* A5 : marges et corps réduits pour garder une ligne lisible sur une page étroite.
|
||||||
|
*/
|
||||||
|
public enum PageFormat {
|
||||||
|
A4("A4", 21.0, 29.7, 2.2, 1.7, 2.0, 10.0, 12.5),
|
||||||
|
A5("A5", 14.8, 21.0, 1.7, 1.3, 1.6, 9.0, 7.0),
|
||||||
|
LETTER("letter", 21.59, 27.94, 2.2, 1.8, 2.0, 10.0, 12.0);
|
||||||
|
|
||||||
|
final String cssSize;
|
||||||
|
final double widthCm;
|
||||||
|
final double heightCm;
|
||||||
|
final double marginTopCm;
|
||||||
|
final double marginSideCm;
|
||||||
|
final double marginBottomCm;
|
||||||
|
final double bodyPt;
|
||||||
|
/** Hauteur max de l'illustration de couverture : la couverture tient sur une page. */
|
||||||
|
final double coverArtMaxCm;
|
||||||
|
|
||||||
|
PageFormat(String cssSize, double widthCm, double heightCm, double marginTopCm, double marginSideCm,
|
||||||
|
double marginBottomCm, double bodyPt, double coverArtMaxCm) {
|
||||||
|
this.cssSize = cssSize;
|
||||||
|
this.widthCm = widthCm;
|
||||||
|
this.heightCm = heightCm;
|
||||||
|
this.marginTopCm = marginTopCm;
|
||||||
|
this.marginSideCm = marginSideCm;
|
||||||
|
this.marginBottomCm = marginBottomCm;
|
||||||
|
this.bodyPt = bodyPt;
|
||||||
|
this.coverArtMaxCm = coverArtMaxCm;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Largeur d'une page tournée en paysage (= hauteur en portrait). */
|
||||||
|
double landscapeWidthCm() {
|
||||||
|
return heightCm;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Largeur utile (page moins les deux marges latérales). */
|
||||||
|
double contentWidthCm() {
|
||||||
|
return widthCm - 2 * marginSideCm;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public PdfExportOptions {
|
||||||
|
format = format != null ? format : PageFormat.A4;
|
||||||
|
sections = sections == null || sections.isEmpty()
|
||||||
|
? EnumSet.allOf(Section.class) : EnumSet.copyOf(sections);
|
||||||
|
loreScope = loreScope != null ? loreScope : LoreScope.ALL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Livret MJ complet en A4 : le comportement historique de l'export. */
|
||||||
|
public static PdfExportOptions defaults() {
|
||||||
|
return new PdfExportOptions(true, PageFormat.A4, false, EnumSet.allOf(Section.class), LoreScope.ALL);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean includes(Section section) {
|
||||||
|
return sections.contains(section);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Construit les options depuis les paramètres de requête (valeurs inconnues ignorées,
|
||||||
|
* absentes = défaut). {@code sections} : liste séparée par des virgules.
|
||||||
|
*/
|
||||||
|
public static PdfExportOptions parse(String edition, String format, Boolean print,
|
||||||
|
String sections, String lore) {
|
||||||
|
boolean gm = !"player".equalsIgnoreCase(trim(edition));
|
||||||
|
PageFormat pf = enumOrNull(PageFormat.class, format);
|
||||||
|
LoreScope scope = enumOrNull(LoreScope.class, lore);
|
||||||
|
Set<Section> set = EnumSet.noneOf(Section.class);
|
||||||
|
if (sections != null) {
|
||||||
|
for (String s : sections.split(",")) {
|
||||||
|
Section sec = enumOrNull(Section.class, s);
|
||||||
|
if (sec != null) set.add(sec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new PdfExportOptions(gm, pf, Boolean.TRUE.equals(print), set, scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String trim(String s) {
|
||||||
|
return s == null ? "" : s.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <E extends Enum<E>> E enumOrNull(Class<E> type, String raw) {
|
||||||
|
String v = trim(raw).toUpperCase(Locale.ROOT);
|
||||||
|
if (v.isEmpty()) return null;
|
||||||
|
try {
|
||||||
|
return Enum.valueOf(type, v);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+524
-159
File diff suppressed because it is too large
Load Diff
@@ -139,6 +139,71 @@ final class PdfHtml {
|
|||||||
b.append(DIV_CLOSE);
|
b.append(DIV_CLOSE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ----- Renvois internes (« voir p. 12 ») -----
|
||||||
|
|
||||||
|
private static final java.util.regex.Pattern ID_ATTR = java.util.regex.Pattern.compile(" id=\"([^\"]+)\"");
|
||||||
|
private static final java.util.regex.Pattern XREF = java.util.regex.Pattern.compile(
|
||||||
|
"<a class=\"xref\" href=\"#([^\"]+)\">(.*?)</a>");
|
||||||
|
private static final java.util.regex.Pattern PREF = java.util.regex.Pattern.compile(
|
||||||
|
"<a class=\"pref\" href=\"#([^\"]+)\"></a>");
|
||||||
|
|
||||||
|
/** Nom cliquable vers une ancre du livret (retire par {@link #resolveRefs} si l'ancre manque). */
|
||||||
|
static String xref(String anchor, String text) {
|
||||||
|
return "<a class=\"xref\" href=\"#" + anchor + "\">" + esc(text) + "</a>";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Numero de page de l'ancre, rendu « (p. 12) » par target-counter (cf. export.css). */
|
||||||
|
static String pageRef(String anchor) {
|
||||||
|
return "<a class=\"pref\" href=\"#" + anchor + "\"></a>";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Neutralise les renvois vers des ancres absentes du document (partie non exportee,
|
||||||
|
* scene d'une quete exclue...) : le nom reste en texte simple, le numero de page disparait.
|
||||||
|
* openhtmltopdf ne sait pas resoudre target-counter vers une ancre inexistante.
|
||||||
|
*/
|
||||||
|
static String resolveRefs(String html) {
|
||||||
|
java.util.Set<String> ids = new java.util.HashSet<>();
|
||||||
|
java.util.regex.Matcher m = ID_ATTR.matcher(html);
|
||||||
|
while (m.find()) ids.add(m.group(1));
|
||||||
|
String out = XREF.matcher(html).replaceAll(r -> ids.contains(r.group(1))
|
||||||
|
? java.util.regex.Matcher.quoteReplacement(r.group())
|
||||||
|
: java.util.regex.Matcher.quoteReplacement(r.group(2)));
|
||||||
|
return PREF.matcher(out).replaceAll(r -> ids.contains(r.group(1))
|
||||||
|
? java.util.regex.Matcher.quoteReplacement(r.group()) : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Champ « libelle + elements » dont les elements sont DEJA du HTML (renvois, liens) :
|
||||||
|
* un seul element en ligne apres le libelle, plusieurs en liste a puces.
|
||||||
|
*/
|
||||||
|
static void blockHtml(StringBuilder b, String label, List<String> htmlItems) {
|
||||||
|
if (htmlItems == null || htmlItems.isEmpty()) return;
|
||||||
|
b.append("<div class=\"field\"><span class=\"field-label\">").append(esc(label)).append(SPAN_CLOSE);
|
||||||
|
if (htmlItems.size() == 1) {
|
||||||
|
b.append(htmlItems.get(0));
|
||||||
|
} else {
|
||||||
|
b.append("<ul>");
|
||||||
|
for (String item : htmlItems) b.append("<li>").append(item).append("</li>");
|
||||||
|
b.append("</ul>");
|
||||||
|
}
|
||||||
|
b.append(DIV_CLOSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Texte courant sans libelle : paragraphes et listes a puces (« - ... »). */
|
||||||
|
static void prose(StringBuilder b, String value) {
|
||||||
|
if (!notBlank(value)) return;
|
||||||
|
for (TextBlock t : parseBlocks(value)) {
|
||||||
|
if (t.list()) {
|
||||||
|
b.append("<ul class=\"prose-list\">");
|
||||||
|
for (String line : t.lines()) b.append("<li>").append(esc(line)).append("</li>");
|
||||||
|
b.append("</ul>");
|
||||||
|
} else {
|
||||||
|
b.append("<p class=\"prose\">").append(paragraphHtml(t)).append("</p>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static String paragraphHtml(TextBlock t) {
|
private static String paragraphHtml(TextBlock t) {
|
||||||
StringBuilder p = new StringBuilder();
|
StringBuilder p = new StringBuilder();
|
||||||
for (int i = 0; i < t.lines().size(); i++) {
|
for (int i = 0; i < t.lines().size(); i++) {
|
||||||
|
|||||||
@@ -65,6 +65,11 @@ class PdfImageEncoder {
|
|||||||
|
|
||||||
/** Battlemap (fichier stocke) re-encodee, seulement si c'est une image (pas une video). */
|
/** Battlemap (fichier stocke) re-encodee, seulement si c'est une image (pas une video). */
|
||||||
PdfImage fileImage(String fileId) {
|
PdfImage fileImage(String fileId) {
|
||||||
|
return fileImage(fileId, ILLUSTRATION_MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Idem, avec une cote max choisie (cartes pleine page de l'annexe : plus fines). */
|
||||||
|
PdfImage fileImage(String fileId, int maxDim) {
|
||||||
if (fileId == null || fileId.isBlank()) return null;
|
if (fileId == null || fileId.isBlank()) return null;
|
||||||
StoredFileJpaEntity e;
|
StoredFileJpaEntity e;
|
||||||
try {
|
try {
|
||||||
@@ -75,7 +80,7 @@ class PdfImageEncoder {
|
|||||||
if (e == null) return null;
|
if (e == null) return null;
|
||||||
String ct = e.getContentType();
|
String ct = e.getContentType();
|
||||||
if (ct == null || !ct.startsWith("image/")) return null; // mp4/webm -> ignore
|
if (ct == null || !ct.startsWith("image/")) return null; // mp4/webm -> ignore
|
||||||
return encode(fileStorage.download(e.getStorageKey()), ILLUSTRATION_MAX, fileId);
|
return encode(fileStorage.download(e.getStorageKey()), maxDim, fileId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Lit un flux image, le redimensionne (max maxDim) et le re-encode en data-URI JPEG. */
|
/** Lit un flux image, le redimensionne (max maxDim) et le re-encode en data-URI JPEG. */
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.loremind.infrastructure.web.controller;
|
|||||||
|
|
||||||
import com.loremind.application.campaigncontext.CampaignService;
|
import com.loremind.application.campaigncontext.CampaignService;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
import com.loremind.infrastructure.web.dto.campaigncontext.CampaignDTO;
|
import com.loremind.infrastructure.web.dto.campaigncontext.CampaignDTO;
|
||||||
import com.loremind.infrastructure.web.mapper.CampaignMapper;
|
import com.loremind.infrastructure.web.mapper.CampaignMapper;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -72,6 +73,18 @@ public class CampaignController {
|
|||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fiche « Publication » (couverture, page technique, crédits) utilisée par l'export PDF. */
|
||||||
|
@GetMapping("/{id}/publication")
|
||||||
|
public ResponseEntity<CampaignPublication> getPublication(@PathVariable String id) {
|
||||||
|
return ResponseEntity.ok(campaignService.getPublication(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}/publication")
|
||||||
|
public ResponseEntity<CampaignPublication> updatePublication(@PathVariable String id,
|
||||||
|
@RequestBody CampaignPublication body) {
|
||||||
|
return ResponseEntity.ok(campaignService.updatePublication(id, body));
|
||||||
|
}
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
@PutMapping("/{id}")
|
||||||
public ResponseEntity<CampaignDTO> updateCampaign(@PathVariable String id, @RequestBody CampaignDTO campaignDTO) {
|
public ResponseEntity<CampaignDTO> updateCampaign(@PathVariable String id, @RequestBody CampaignDTO campaignDTO) {
|
||||||
Campaign updatedCampaign = campaignService.updateCampaign(
|
Campaign updatedCampaign = campaignService.updateCampaign(
|
||||||
|
|||||||
@@ -83,7 +83,8 @@ public class NpcController {
|
|||||||
dto.getCampaignId(),
|
dto.getCampaignId(),
|
||||||
dto.getRelatedPageIds(),
|
dto.getRelatedPageIds(),
|
||||||
dto.getFolder(),
|
dto.getFolder(),
|
||||||
order
|
order,
|
||||||
|
dto.getStory()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-3
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.infrastructure.web.controller;
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions;
|
||||||
import com.loremind.infrastructure.transfer.pdf.PdfExportService;
|
import com.loremind.infrastructure.transfer.pdf.PdfExportService;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@@ -8,6 +9,7 @@ import org.springframework.http.ResponseEntity;
|
|||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
@@ -18,6 +20,10 @@ import java.util.NoSuchElementException;
|
|||||||
* <p>
|
* <p>
|
||||||
* {@code GET /api/campaigns/{campaignId}/pdf-export} -> application/pdf (structure
|
* {@code GET /api/campaigns/{campaignId}/pdf-export} -> application/pdf (structure
|
||||||
* narrative + PNJ/ennemis + lore + battlemaps).
|
* narrative + PNJ/ennemis + lore + battlemaps).
|
||||||
|
* <p>
|
||||||
|
* Options (toutes facultatives, defaut = livret MJ complet en A4) :
|
||||||
|
* {@code edition=gm|player}, {@code format=A4|A5|LETTER}, {@code print=true} (sans aplats),
|
||||||
|
* {@code sections=NARRATIVE,QUESTS,NPCS,ENEMIES,TABLES,LORE}, {@code lore=ALL|LINKED}.
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/campaigns/{campaignId}/pdf-export")
|
@RequestMapping("/api/campaigns/{campaignId}/pdf-export")
|
||||||
@@ -30,17 +36,23 @@ public class PdfExportController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(produces = MediaType.APPLICATION_PDF_VALUE)
|
@GetMapping(produces = MediaType.APPLICATION_PDF_VALUE)
|
||||||
public ResponseEntity<byte[]> export(@PathVariable String campaignId) {
|
public ResponseEntity<byte[]> export(@PathVariable String campaignId,
|
||||||
|
@RequestParam(required = false) String edition,
|
||||||
|
@RequestParam(required = false) String format,
|
||||||
|
@RequestParam(required = false) Boolean print,
|
||||||
|
@RequestParam(required = false) String sections,
|
||||||
|
@RequestParam(required = false) String lore) {
|
||||||
|
PdfExportOptions options = PdfExportOptions.parse(edition, format, print, sections, lore);
|
||||||
byte[] pdf;
|
byte[] pdf;
|
||||||
String name;
|
String name;
|
||||||
try {
|
try {
|
||||||
name = pdfExportService.campaignName(campaignId);
|
name = pdfExportService.campaignName(campaignId);
|
||||||
pdf = pdfExportService.export(campaignId);
|
pdf = pdfExportService.export(campaignId, options);
|
||||||
} catch (NoSuchElementException e) {
|
} catch (NoSuchElementException e) {
|
||||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
String filename = slug(name) + ".pdf";
|
String filename = slug(name) + (options.gmContent() ? "" : "_joueurs") + ".pdf";
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||||
.contentType(MediaType.APPLICATION_PDF)
|
.contentType(MediaType.APPLICATION_PDF)
|
||||||
|
|||||||
+2
-2
@@ -61,14 +61,14 @@ public class RemoteAccessAdminController {
|
|||||||
/** Une tablette peut-elle joindre ce PC ? (type de réseau, règle du pare-feu) */
|
/** Une tablette peut-elle joindre ce PC ? (type de réseau, règle du pare-feu) */
|
||||||
@GetMapping("/network-check")
|
@GetMapping("/network-check")
|
||||||
public NetworkReadiness networkCheck() {
|
public NetworkReadiness networkCheck() {
|
||||||
return NetworkReadiness.evaluate(hostNetworkAccess.inspect());
|
return NetworkReadiness.evaluate(hostNetworkAccess.inspect(remoteAccessService.configuredPort()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ajoute la règle du pare-feu ; attend la réponse de l'utilisateur à la confirmation Windows (UAC). */
|
/** Ajoute la règle du pare-feu ; attend la réponse de l'utilisateur à la confirmation Windows (UAC). */
|
||||||
@PostMapping("/firewall-rule")
|
@PostMapping("/firewall-rule")
|
||||||
public FirewallFixResponse allowThroughFirewall() {
|
public FirewallFixResponse allowThroughFirewall() {
|
||||||
HostNetworkAccess.FirewallFixOutcome outcome = hostNetworkAccess.allowThroughFirewall();
|
HostNetworkAccess.FirewallFixOutcome outcome = hostNetworkAccess.allowThroughFirewall();
|
||||||
return new FirewallFixResponse(outcome, NetworkReadiness.evaluate(hostNetworkAccess.inspect()));
|
return new FirewallFixResponse(outcome, NetworkReadiness.evaluate(hostNetworkAccess.inspect(remoteAccessService.configuredPort())));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ouvre les réglages réseau de Windows (pour passer un Wi-Fi « Public » en « Privé »). */
|
/** Ouvre les réglages réseau de Windows (pour passer un Wi-Fi « Public » en « Privé »). */
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ public class ArcDTO {
|
|||||||
private String gmNotes;
|
private String gmNotes;
|
||||||
private String rewards;
|
private String rewards;
|
||||||
private String resolution;
|
private String resolution;
|
||||||
|
private String hiddenTruth;
|
||||||
|
private String hooks;
|
||||||
|
|
||||||
/** IDs des pages du Lore liées à cet arc (weak cross-context references). */
|
/** IDs des pages du Lore liées à cet arc (weak cross-context references). */
|
||||||
private List<String> relatedPageIds = new ArrayList<>();
|
private List<String> relatedPageIds = new ArrayList<>();
|
||||||
|
|||||||
@@ -24,5 +24,6 @@ public class NpcDTO {
|
|||||||
/** IDs de Pages de Lore référencées par ce PNJ (référence faible cross-context). */
|
/** IDs de Pages de Lore référencées par ce PNJ (référence faible cross-context). */
|
||||||
private List<String> relatedPageIds = new ArrayList<>();
|
private List<String> relatedPageIds = new ArrayList<>();
|
||||||
private String folder;
|
private String folder;
|
||||||
|
private com.loremind.domain.campaigncontext.bestiary.NpcStory story;
|
||||||
private int order;
|
private int order;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ public class SceneDTO {
|
|||||||
private String gmSecretNotes;
|
private String gmSecretNotes;
|
||||||
private String choicesConsequences;
|
private String choicesConsequences;
|
||||||
private String combatDifficulty;
|
private String combatDifficulty;
|
||||||
|
private String tactics;
|
||||||
|
private String purpose;
|
||||||
private String enemies;
|
private String enemies;
|
||||||
|
|
||||||
/** IDs des fiches du bestiaire engagées dans la rencontre (weak refs). */
|
/** IDs des fiches du bestiaire engagées dans la rencontre (weak refs). */
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ public class ArcMapper {
|
|||||||
dto.setGmNotes(arc.getGmNotes());
|
dto.setGmNotes(arc.getGmNotes());
|
||||||
dto.setRewards(arc.getRewards());
|
dto.setRewards(arc.getRewards());
|
||||||
dto.setResolution(arc.getResolution());
|
dto.setResolution(arc.getResolution());
|
||||||
|
dto.setHiddenTruth(arc.getHiddenTruth());
|
||||||
|
dto.setHooks(arc.getHooks());
|
||||||
dto.setRelatedPageIds(copyList(arc.getRelatedPageIds()));
|
dto.setRelatedPageIds(copyList(arc.getRelatedPageIds()));
|
||||||
dto.setIllustrationImageIds(copyList(arc.getIllustrationImageIds()));
|
dto.setIllustrationImageIds(copyList(arc.getIllustrationImageIds()));
|
||||||
return dto;
|
return dto;
|
||||||
@@ -55,6 +57,8 @@ public class ArcMapper {
|
|||||||
.gmNotes(dto.getGmNotes())
|
.gmNotes(dto.getGmNotes())
|
||||||
.rewards(dto.getRewards())
|
.rewards(dto.getRewards())
|
||||||
.resolution(dto.getResolution())
|
.resolution(dto.getResolution())
|
||||||
|
.hiddenTruth(dto.getHiddenTruth())
|
||||||
|
.hooks(dto.getHooks())
|
||||||
.relatedPageIds(copyList(dto.getRelatedPageIds()))
|
.relatedPageIds(copyList(dto.getRelatedPageIds()))
|
||||||
.illustrationImageIds(copyList(dto.getIllustrationImageIds()))
|
.illustrationImageIds(copyList(dto.getIllustrationImageIds()))
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ public class NpcMapper {
|
|||||||
dto.setCampaignId(n.getCampaignId());
|
dto.setCampaignId(n.getCampaignId());
|
||||||
dto.setRelatedPageIds(n.getRelatedPageIds() != null ? new ArrayList<>(n.getRelatedPageIds()) : new ArrayList<>());
|
dto.setRelatedPageIds(n.getRelatedPageIds() != null ? new ArrayList<>(n.getRelatedPageIds()) : new ArrayList<>());
|
||||||
dto.setFolder(n.getFolder());
|
dto.setFolder(n.getFolder());
|
||||||
|
dto.setStory(n.getStory());
|
||||||
dto.setOrder(n.getOrder());
|
dto.setOrder(n.getOrder());
|
||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
@@ -40,6 +41,7 @@ public class NpcMapper {
|
|||||||
.campaignId(dto.getCampaignId())
|
.campaignId(dto.getCampaignId())
|
||||||
.relatedPageIds(dto.getRelatedPageIds() != null ? new ArrayList<>(dto.getRelatedPageIds()) : new ArrayList<>())
|
.relatedPageIds(dto.getRelatedPageIds() != null ? new ArrayList<>(dto.getRelatedPageIds()) : new ArrayList<>())
|
||||||
.folder(dto.getFolder())
|
.folder(dto.getFolder())
|
||||||
|
.story(dto.getStory())
|
||||||
.order(dto.getOrder())
|
.order(dto.getOrder())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ public class SceneMapper {
|
|||||||
dto.setGmSecretNotes(scene.getGmSecretNotes());
|
dto.setGmSecretNotes(scene.getGmSecretNotes());
|
||||||
dto.setChoicesConsequences(scene.getChoicesConsequences());
|
dto.setChoicesConsequences(scene.getChoicesConsequences());
|
||||||
dto.setCombatDifficulty(scene.getCombatDifficulty());
|
dto.setCombatDifficulty(scene.getCombatDifficulty());
|
||||||
|
dto.setTactics(scene.getTactics());
|
||||||
|
dto.setPurpose(scene.getPurpose());
|
||||||
dto.setEnemies(scene.getEnemies());
|
dto.setEnemies(scene.getEnemies());
|
||||||
dto.setEnemyIds(scene.getEnemyIds() != null
|
dto.setEnemyIds(scene.getEnemyIds() != null
|
||||||
? new ArrayList<>(scene.getEnemyIds())
|
? new ArrayList<>(scene.getEnemyIds())
|
||||||
@@ -81,6 +83,8 @@ public class SceneMapper {
|
|||||||
.gmSecretNotes(dto.getGmSecretNotes())
|
.gmSecretNotes(dto.getGmSecretNotes())
|
||||||
.choicesConsequences(dto.getChoicesConsequences())
|
.choicesConsequences(dto.getChoicesConsequences())
|
||||||
.combatDifficulty(dto.getCombatDifficulty())
|
.combatDifficulty(dto.getCombatDifficulty())
|
||||||
|
.tactics(dto.getTactics())
|
||||||
|
.purpose(dto.getPurpose())
|
||||||
.enemies(dto.getEnemies())
|
.enemies(dto.getEnemies())
|
||||||
.enemyIds(dto.getEnemyIds() != null
|
.enemyIds(dto.getEnemyIds() != null
|
||||||
? new ArrayList<>(dto.getEnemyIds())
|
? new ArrayList<>(dto.getEnemyIds())
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- Fiche « Publication » d'une campagne (module à vendre ou à partager) : sous-titre,
|
||||||
|
-- auteur, page technique, argument, contexte MJ, accroches, crédits, licence,
|
||||||
|
-- image de couverture… Stockée en JSON (texte libre, évolutif) ; NULL = jamais renseignée.
|
||||||
|
ALTER TABLE campaigns ADD COLUMN publication TEXT;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Champs d'écriture (mentor) :
|
||||||
|
-- scène : tactique et moral des adversaires, utilité (ce qu'on perd si on la coupe) ;
|
||||||
|
-- arc : histoire cachée, accroches ;
|
||||||
|
-- PNJ : fiche « rôle dans l'histoire » (rôle, motivation, ce qu'il sait, signe distinctif) en JSON.
|
||||||
|
ALTER TABLE scenes ADD COLUMN tactics TEXT;
|
||||||
|
ALTER TABLE scenes ADD COLUMN purpose TEXT;
|
||||||
|
ALTER TABLE arcs ADD COLUMN hidden_truth TEXT;
|
||||||
|
ALTER TABLE arcs ADD COLUMN hooks TEXT;
|
||||||
|
ALTER TABLE npcs ADD COLUMN story TEXT;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/* Format A5 : surcharges ajoutees apres export.css (page etroite, couverture sur une seule page).
|
||||||
|
ATTENTION : ce CSS est injecte tel quel dans le document XML — ni esperluette ni chevron ici. */
|
||||||
|
.cover { padding-top: 3.2cm; }
|
||||||
|
.cover.has-art { padding-top: .3cm; }
|
||||||
|
.cover-kicker { font-size: 8.5pt; letter-spacing: .25em; }
|
||||||
|
.cover-title { font-size: 21pt; margin-top: .3cm; }
|
||||||
|
.cover-subtitle { font-size: 11pt; margin-top: .2cm; }
|
||||||
|
.cover-rule { margin: .35cm auto; }
|
||||||
|
.cover-art { margin: .1cm 0 .35cm; }
|
||||||
|
.cover-edition { margin-top: .25cm; }
|
||||||
|
.cover-author { margin-top: .5cm; font-size: 11pt; }
|
||||||
|
.cover-version { margin-top: .15cm; }
|
||||||
|
h1.part, h1.toc-title { font-size: 16pt; }
|
||||||
|
.arc-head { font-size: 12.5pt; }
|
||||||
|
.chapter-head { font-size: 11.5pt; }
|
||||||
|
.scene { margin-left: .15cm; }
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
/* Mode impression : surcharges ajoutees apres export.css. Aucun aplat de couleur (economie
|
||||||
|
d'encre, rendu net en noir et blanc) ; les filets et bordures portent la hierarchie.
|
||||||
|
ATTENTION : ce CSS est injecte tel quel dans le document XML — ni esperluette ni chevron ici. */
|
||||||
|
.arc-head { background: none; color: #1f1c33; border-top: 2pt solid #2e2a4a; border-bottom: 2pt solid #2e2a4a;
|
||||||
|
border-radius: 0; }
|
||||||
|
.arc-head .eyebrow-light { color: #6d6787; }
|
||||||
|
.chapter-head { background: none; border-left: 4pt solid #555; }
|
||||||
|
.scene, .room, .card { background: none; }
|
||||||
|
.readaloud { background: none; }
|
||||||
|
.secret { background: none; border: 1pt dashed #777; }
|
||||||
|
.combat { background: none; border-left: 3pt solid #555; }
|
||||||
|
.warning { background: none; border-left: 3pt solid #555; }
|
||||||
|
.stats-table thead th, .stats-table tbody th, .stat-array th { background: none; }
|
||||||
|
.stats-table tr.alt td { background: none; }
|
||||||
@@ -1,20 +1,41 @@
|
|||||||
@page { size: A4; margin: 2.2cm 1.7cm 2cm;
|
@page { size: __PAGE_SIZE__; margin: __PAGE_MARGIN__;
|
||||||
@top-center { content: '__HEADER__'; font-family: 'DejaVu Sans', sans-serif; font-size: 7.5pt;
|
@top-center { content: '__HEADER__'; font-family: 'DejaVu Sans', sans-serif; font-size: 7.5pt;
|
||||||
letter-spacing: .22em; text-transform: uppercase; color: #b3a9d6; }
|
letter-spacing: .22em; text-transform: uppercase; color: #b3a9d6; }
|
||||||
@bottom-center { content: counter(page); font-family: 'DejaVu Sans', sans-serif; font-size: 9pt; color: #999; } }
|
@bottom-center { content: counter(page); font-family: 'DejaVu Sans', sans-serif; font-size: 9pt; color: #999; } }
|
||||||
@page:first { @top-center { content: none; } } /* NOSONAR css:S4662 — pseudo-page CSS paged media, supportee par openhtmltopdf */
|
@page:first { @top-center { content: none; } } /* NOSONAR css:S4662 — pseudo-page CSS paged media, supportee par openhtmltopdf */
|
||||||
body { font-family: 'DejaVu Serif', serif; font-size: 10pt; color: #26243a; line-height: 1.5; }
|
body { font-family: 'DejaVu Serif', serif; font-size: __BODY_PT__; color: #26243a; line-height: 1.5; }
|
||||||
a { color: inherit; text-decoration: none; }
|
a { color: inherit; text-decoration: none; }
|
||||||
/* --- Couverture --- */
|
/* --- Couverture --- */
|
||||||
.cover { text-align: center; padding-top: 5.5cm; page-break-after: always; }
|
.cover { text-align: center; padding-top: 5.5cm; page-break-after: always; }
|
||||||
.cover .subtitle { font-family: 'DejaVu Sans', sans-serif; font-size: 11pt; letter-spacing: .35em;
|
.cover.has-art { padding-top: 1.2cm; }
|
||||||
|
.cover-kicker { font-family: 'DejaVu Sans', sans-serif; font-size: 11pt; letter-spacing: .35em;
|
||||||
text-transform: uppercase; color: #8a7bc8; }
|
text-transform: uppercase; color: #8a7bc8; }
|
||||||
|
.cover-subtitle { font-family: 'DejaVu Sans', sans-serif; font-size: 13pt; color: #5b5180; margin-top: .3cm; }
|
||||||
|
.cover-art { margin: .2cm 0 .6cm; }
|
||||||
|
.cover-art img { border: 1pt solid #cfc9e0; }
|
||||||
|
.cover-edition { margin-top: .4cm; font-family: 'DejaVu Sans', sans-serif; font-size: 9pt; letter-spacing: .2em;
|
||||||
|
text-transform: uppercase; color: #a08b4f; }
|
||||||
|
.cover-author { margin-top: 1cm; font-family: 'DejaVu Sans', sans-serif; font-size: 12pt; color: #2e2a4a; }
|
||||||
|
.cover-version { margin-top: .3cm; font-family: 'DejaVu Sans', sans-serif; font-size: 8.5pt; color: #b0aac4; }
|
||||||
.cover-title { font-family: 'DejaVu Sans', sans-serif; font-size: 30pt; text-transform: uppercase;
|
.cover-title { font-family: 'DejaVu Sans', sans-serif; font-size: 30pt; text-transform: uppercase;
|
||||||
letter-spacing: .04em; color: #2e2a4a; margin: .45cm 0 0; }
|
letter-spacing: .04em; color: #2e2a4a; margin: .45cm 0 0; }
|
||||||
.cover-rule { width: 3.6cm; border-bottom: 2.5pt solid #8a7bc8; margin: .5cm auto; }
|
.cover-rule { width: 3.6cm; border-bottom: 2.5pt solid #8a7bc8; margin: .5cm auto; }
|
||||||
.cover-meta { font-family: 'DejaVu Sans', sans-serif; font-size: 9.5pt; color: #8076a3; letter-spacing: .06em; }
|
.cover-meta { font-family: 'DejaVu Sans', sans-serif; font-size: 9.5pt; color: #8076a3; letter-spacing: .06em; }
|
||||||
.cover-desc { margin: 1.1cm auto 0; max-width: 12.5cm; color: #444; }
|
.cover-desc { margin: 1.1cm auto 0; max-width: 12.5cm; color: #444; }
|
||||||
.cover-date { margin-top: 1.4cm; font-family: 'DejaVu Sans', sans-serif; font-size: 8.5pt; color: #b0aac4; }
|
/* --- Page de credits (verso de couverture) --- */
|
||||||
|
.credits-page { page-break-after: always; padding-top: 1cm; font-size: 9pt; }
|
||||||
|
.credits-title { font-family: 'DejaVu Sans', sans-serif; font-size: 14pt; font-weight: bold; color: #2e2a4a; }
|
||||||
|
.credits-subtitle { font-family: 'DejaVu Sans', sans-serif; color: #5b5180; margin-bottom: .5cm; }
|
||||||
|
.legal { margin-top: .8cm; padding-top: .3cm; border-top: 1pt solid #d8d2e8; font-size: 8pt; color: #555; }
|
||||||
|
/* --- Introduction (module publie) --- */
|
||||||
|
h2.section-head { page-break-after: avoid; font-family: 'DejaVu Sans', sans-serif; font-size: 12.5pt;
|
||||||
|
color: #463b78; border-bottom: 1pt solid #d8d2e8; padding-bottom: 2pt; margin: .55cm 0 .2cm; }
|
||||||
|
p.prose { margin: 0 0 .2cm; text-align: justify; }
|
||||||
|
ul.prose-list { margin: .05cm 0 .25cm; padding-left: .55cm; }
|
||||||
|
ul.prose-list li { margin: 0 0 .08cm; }
|
||||||
|
.tech-table { width: auto; min-width: 60%; }
|
||||||
|
.warning { background: #fff6e8; border-left: 3pt solid #d39a3a; }
|
||||||
|
.warning .box-label { color: #a8701f; }
|
||||||
/* --- Sommaire --- */
|
/* --- Sommaire --- */
|
||||||
.toc-page { page-break-after: always; }
|
.toc-page { page-break-after: always; }
|
||||||
h1.toc-title { font-family: 'DejaVu Sans', sans-serif; font-size: 20pt; text-transform: uppercase;
|
h1.toc-title { font-family: 'DejaVu Sans', sans-serif; font-size: 20pt; text-transform: uppercase;
|
||||||
@@ -55,9 +76,11 @@ h3.folder { page-break-after: avoid; font-family: 'DejaVu Sans', sans-serif; col
|
|||||||
.eyebrow-light { color: #c9c0e8; }
|
.eyebrow-light { color: #c9c0e8; }
|
||||||
.scene-meta { font-style: italic; color: #6d6787; margin: -.05cm 0 .16cm; }
|
.scene-meta { font-style: italic; color: #6d6787; margin: -.05cm 0 .16cm; }
|
||||||
/* --- Encadres speciaux (codes visuels des livres de JdR) --- */
|
/* --- Encadres speciaux (codes visuels des livres de JdR) --- */
|
||||||
.box { border-radius: 3pt; padding: .2cm .35cm; margin: .2cm 0; page-break-inside: avoid; }
|
/* Encadres coupables entre deux pages (un long secret MJ ne laisse plus une demi-page blanche) ;
|
||||||
|
le libelle reste solidaire de sa premiere ligne. */
|
||||||
|
.box { border-radius: 3pt; padding: .2cm .35cm; margin: .2cm 0; page-break-inside: auto; }
|
||||||
.box-label { font-family: 'DejaVu Sans', sans-serif; font-size: 7.5pt; text-transform: uppercase;
|
.box-label { font-family: 'DejaVu Sans', sans-serif; font-size: 7.5pt; text-transform: uppercase;
|
||||||
letter-spacing: .1em; font-weight: bold; font-style: normal; margin-bottom: .06cm; }
|
letter-spacing: .1em; font-weight: bold; font-style: normal; margin-bottom: .06cm; page-break-after: avoid; }
|
||||||
.readaloud { background: #faf6ea; border-top: 2pt solid #cbbd93; border-bottom: 2pt solid #cbbd93;
|
.readaloud { background: #faf6ea; border-top: 2pt solid #cbbd93; border-bottom: 2pt solid #cbbd93;
|
||||||
border-radius: 0; font-style: italic; }
|
border-radius: 0; font-style: italic; }
|
||||||
.readaloud .box-label { color: #a08b4f; }
|
.readaloud .box-label { color: #a08b4f; }
|
||||||
@@ -78,6 +101,7 @@ div.field-label { margin: .12cm 0 .06cm; padding-right: 0; }
|
|||||||
/* --- Cartes (fiches PNJ/ennemis, pages de lore) --- */
|
/* --- Cartes (fiches PNJ/ennemis, pages de lore) --- */
|
||||||
.card { page-break-inside: avoid; border: 1pt solid #e3e0ee; border-radius: 4pt;
|
.card { page-break-inside: avoid; border: 1pt solid #e3e0ee; border-radius: 4pt;
|
||||||
padding: .32cm .4cm; margin: .32cm 0; background: #fcfcfe; }
|
padding: .32cm .4cm; margin: .32cm 0; background: #fcfcfe; }
|
||||||
|
.card.flow { page-break-inside: auto; }
|
||||||
.card-body { display: block; }
|
.card-body { display: block; }
|
||||||
.persona { width: 100%; border-collapse: collapse; }
|
.persona { width: 100%; border-collapse: collapse; }
|
||||||
.persona-portrait { width: 3cm; vertical-align: top; padding: 0 .45cm 0 0; }
|
.persona-portrait { width: 3cm; vertical-align: top; padding: 0 .45cm 0 0; }
|
||||||
@@ -99,6 +123,7 @@ div.field-label { margin: .12cm 0 .06cm; padding-right: 0; }
|
|||||||
.stats-table thead th { background: #f1eef9; color: #4a3f7a; border-bottom: 1pt solid #d8d1ec; }
|
.stats-table thead th { background: #f1eef9; color: #4a3f7a; border-bottom: 1pt solid #d8d1ec; }
|
||||||
.stats-table tbody th { width: 32%; color: #555; font-weight: bold; background: #f8f7fc; }
|
.stats-table tbody th { width: 32%; color: #555; font-weight: bold; background: #f8f7fc; }
|
||||||
.stats-table tr.alt td { background: #f6f5fa; }
|
.stats-table tr.alt td { background: #f6f5fa; }
|
||||||
|
.stats-table tr { page-break-inside: avoid; }
|
||||||
.stats-table .roll-col { width: 1.8cm; text-align: center; font-weight: bold; color: #4a3f7a; }
|
.stats-table .roll-col { width: 1.8cm; text-align: center; font-weight: bold; color: #4a3f7a; }
|
||||||
.stats-table .entry-detail { color: #555; font-size: 8.5pt; }
|
.stats-table .entry-detail { color: #555; font-size: 8.5pt; }
|
||||||
.stat-array { border-collapse: collapse; font-family: 'DejaVu Sans', sans-serif; font-size: 9pt;
|
.stat-array { border-collapse: collapse; font-family: 'DejaVu Sans', sans-serif; font-size: 9pt;
|
||||||
@@ -106,3 +131,23 @@ div.field-label { margin: .12cm 0 .06cm; padding-right: 0; }
|
|||||||
.stat-array th { background: #f1eef9; color: #4a3f7a; border: 1pt solid #ddd6ee;
|
.stat-array th { background: #f1eef9; color: #4a3f7a; border: 1pt solid #ddd6ee;
|
||||||
padding: 2.5pt 9pt; text-align: center; }
|
padding: 2.5pt 9pt; text-align: center; }
|
||||||
.stat-array td { border: 1pt solid #e6e2f2; padding: 2.5pt 9pt; text-align: center; }
|
.stat-array td { border: 1pt solid #e6e2f2; padding: 2.5pt 9pt; text-align: center; }
|
||||||
|
/* --- Renvois internes : nom cliquable + numero de page « (p. 12) » --- */
|
||||||
|
a.xref { color: #463b78; border-bottom: .5pt dotted #b9aede; }
|
||||||
|
a.pref:after { content: "(p. " target-counter(attr(href), page) ")"; font-family: 'DejaVu Sans', sans-serif;
|
||||||
|
font-size: 7.5pt; color: #8a7bc8; }
|
||||||
|
/* --- Annexes --- */
|
||||||
|
.annex-intro { color: #555; font-size: 9pt; }
|
||||||
|
.annex-table td { vertical-align: top; }
|
||||||
|
.annex-table .page-col { width: 1.6cm; text-align: right; }
|
||||||
|
ul.annex-list { margin: 0; padding-left: .45cm; }
|
||||||
|
ul.annex-list li { margin: 0 0 .04cm; }
|
||||||
|
.annex-kind { font-family: 'DejaVu Sans', sans-serif; font-size: 7pt; text-transform: uppercase;
|
||||||
|
letter-spacing: .06em; color: #7d6fb0; }
|
||||||
|
.annex-warn { color: #a84f49; font-style: italic; }
|
||||||
|
/* --- Cartes en pleine page paysage (page nommee) --- */
|
||||||
|
@page landscape { size: __PAGE_SIZE__ landscape; margin: 1cm; @top-center { content: none; }
|
||||||
|
@bottom-center { content: counter(page); font-family: 'DejaVu Sans', sans-serif; font-size: 8pt; color: #999; } }
|
||||||
|
.map-page { page: landscape; page-break-before: always; text-align: center; }
|
||||||
|
.map-title { font-family: 'DejaVu Sans', sans-serif; font-size: 11pt; font-weight: bold; color: #2e2a4a;
|
||||||
|
text-align: left; margin: 0 0 .3cm; }
|
||||||
|
.map-page img { display: block; margin: 0 auto; border: 1pt solid #cfc9e0; }
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.loremind.application.campaigncontext;
|
|||||||
import com.loremind.application.playcontext.PlaythroughService;
|
import com.loremind.application.playcontext.PlaythroughService;
|
||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
@@ -407,4 +408,37 @@ class CampaignServiceTest {
|
|||||||
assertThrows(IllegalArgumentException.class,
|
assertThrows(IllegalArgumentException.class,
|
||||||
() -> campaignService.updateGraphPositions("missing", "{}"));
|
() -> campaignService.updateGraphPositions("missing", "{}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void publication_isEmptyWhenNeverFilled_andSavedCleaned() {
|
||||||
|
when(campaignRepository.findById("campaign-1")).thenReturn(Optional.of(testCampaign));
|
||||||
|
assertFalse(campaignService.getPublication("campaign-1").hasContent());
|
||||||
|
|
||||||
|
when(campaignRepository.save(any(Campaign.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
CampaignPublication saved = campaignService.updatePublication("campaign-1",
|
||||||
|
new CampaignPublication(" Sous-titre ", " ", null, null, null, null, null, null, null,
|
||||||
|
null, null, null, null, null));
|
||||||
|
|
||||||
|
assertEquals("Sous-titre", saved.subtitle());
|
||||||
|
assertNull(saved.author());
|
||||||
|
assertEquals("Sous-titre", testCampaign.getPublication().subtitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void publication_emptiedIsStoredAsNull() {
|
||||||
|
when(campaignRepository.findById("campaign-1")).thenReturn(Optional.of(testCampaign));
|
||||||
|
when(campaignRepository.save(any(Campaign.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
campaignService.updatePublication("campaign-1", CampaignPublication.empty());
|
||||||
|
|
||||||
|
assertNull(testCampaign.getPublication());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void publication_unknownCampaign_throws() {
|
||||||
|
when(campaignRepository.findById("nope")).thenReturn(Optional.empty());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> campaignService.getPublication("nope"));
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> campaignService.updatePublication("nope", CampaignPublication.empty()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+76
@@ -1,13 +1,18 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.application.playcontext.ClockService;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
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.Scene;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.domain.playcontext.ClockTrigger;
|
||||||
|
import com.loremind.domain.playcontext.Playthrough;
|
||||||
|
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
@@ -45,6 +50,8 @@ class GuidedSkeletonServiceTest {
|
|||||||
@Mock private ArcService arcService;
|
@Mock private ArcService arcService;
|
||||||
@Mock private ChapterService chapterService;
|
@Mock private ChapterService chapterService;
|
||||||
@Mock private SceneService sceneService;
|
@Mock private SceneService sceneService;
|
||||||
|
@Mock private PlaythroughRepository playthroughRepository;
|
||||||
|
@Mock private ClockService clockService;
|
||||||
|
|
||||||
@InjectMocks private GuidedSkeletonService service;
|
@InjectMocks private GuidedSkeletonService service;
|
||||||
|
|
||||||
@@ -196,4 +203,73 @@ class GuidedSkeletonServiceTest {
|
|||||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noChapterName));
|
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noChapterName));
|
||||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noScene));
|
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noScene));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Liens explicites (Enquête en nœuds) et horloge (Plan du méchant) ---
|
||||||
|
|
||||||
|
private static GuidedSkeleton withLinks(List<GuidedSkeleton.SceneSpec> scenes, List<GuidedSkeleton.LinkSpec> links,
|
||||||
|
GuidedSkeleton.ClockSpec clock) {
|
||||||
|
return new GuidedSkeleton(null, "Arc",
|
||||||
|
new GuidedSkeleton.ChapterSpec("Enquête", "Accroche", null, null, "Le notaire est coupable"),
|
||||||
|
scenes, false, null, links, clock);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void explicitLinks_areAddedWithTheirKind_andIndexesSurviveSkippedScenes() {
|
||||||
|
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||||
|
// La scène d'index 1 n'a pas de nom : ignorée, mais les index des liens restent ceux d'origine.
|
||||||
|
List<GuidedSkeleton.SceneSpec> scenes = List.of(
|
||||||
|
room("Accroche", SceneType.EVENT), room(" ", SceneType.LOCATION),
|
||||||
|
room("Piste", SceneType.NPC), room("Conclusion", SceneType.REVELATION));
|
||||||
|
|
||||||
|
service.create(CAMP, withLinks(scenes, List.of(
|
||||||
|
new GuidedSkeleton.LinkSpec(0, 2, "Piste", LinkType.LEAD),
|
||||||
|
new GuidedSkeleton.LinkSpec(2, 3, "Indice", LinkType.CLUE),
|
||||||
|
new GuidedSkeleton.LinkSpec(0, 1, "Vers la scène ignorée", LinkType.LEAD),
|
||||||
|
new GuidedSkeleton.LinkSpec(3, 3, "Boucle sur soi", LinkType.EXIT),
|
||||||
|
new GuidedSkeleton.LinkSpec(0, 9, "Hors limites", LinkType.EXIT)), null));
|
||||||
|
|
||||||
|
Scene hook = createdScenes.get(0);
|
||||||
|
Scene lead = createdScenes.get(1);
|
||||||
|
Scene end = createdScenes.get(2);
|
||||||
|
assertEquals(1, hook.getBranches().size(), "seul le lien valide de l'accroche est gardé");
|
||||||
|
assertEquals(lead.getId(), hook.getBranches().get(0).targetSceneId());
|
||||||
|
assertEquals(LinkType.LEAD, hook.getBranches().get(0).kind());
|
||||||
|
assertEquals(end.getId(), lead.getBranches().get(0).targetSceneId());
|
||||||
|
assertEquals(LinkType.CLUE, lead.getBranches().get(0).kind());
|
||||||
|
assertTrue(end.getBranches() == null || end.getBranches().isEmpty());
|
||||||
|
verify(sceneRepository, times(2)).save(any(Scene.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void chapterGmNotes_arePersisted() {
|
||||||
|
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||||
|
service.create(CAMP, withLinks(List.of(room("S", SceneType.EVENT)), null, null));
|
||||||
|
|
||||||
|
ArgumentCaptor<Chapter> chapter = ArgumentCaptor.forClass(Chapter.class);
|
||||||
|
verify(chapterService).createChapter(chapter.capture());
|
||||||
|
assertEquals("Le notaire est coupable", chapter.getValue().getGmNotes());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void clock_isCreatedInEveryPlaythroughOfTheCampaign() {
|
||||||
|
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||||
|
when(playthroughRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||||
|
Playthrough.builder().id("p1").campaignId(CAMP).build(),
|
||||||
|
Playthrough.builder().id("p2").campaignId(CAMP).build()));
|
||||||
|
|
||||||
|
GuidedSkeleton.Result result = service.create(CAMP, withLinks(List.of(room("Étape 1", SceneType.EVENT)), null,
|
||||||
|
new GuidedSkeleton.ClockSpec(" La régence ", "La loi martiale", 6)));
|
||||||
|
|
||||||
|
assertEquals(2, result.clocks());
|
||||||
|
verify(clockService).create("p1", "La régence", "La loi martiale", 6, ClockTrigger.NONE, null, null);
|
||||||
|
verify(clockService).create("p2", "La régence", "La loi martiale", 6, ClockTrigger.NONE, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noClock_whenNotRequested() {
|
||||||
|
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||||
|
GuidedSkeleton.Result result = service.create(CAMP, skeleton(null, "Arc", false));
|
||||||
|
assertEquals(0, result.clocks());
|
||||||
|
verify(clockService, never()).create(any(), any(), any(), org.mockito.ArgumentMatchers.anyInt(), any(), any(), any());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+194
-1
@@ -4,6 +4,9 @@ import com.loremind.domain.campaigncontext.Campaign;
|
|||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||||
@@ -11,6 +14,8 @@ import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
|||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Room;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
@@ -45,6 +50,7 @@ class WritingReviewServiceTest {
|
|||||||
@Mock private ChapterRepository chapterRepository;
|
@Mock private ChapterRepository chapterRepository;
|
||||||
@Mock private SceneRepository sceneRepository;
|
@Mock private SceneRepository sceneRepository;
|
||||||
@Mock private QuestRepository questRepository;
|
@Mock private QuestRepository questRepository;
|
||||||
|
@Mock private NpcRepository npcRepository;
|
||||||
|
|
||||||
@InjectMocks private WritingReviewService service;
|
@InjectMocks private WritingReviewService service;
|
||||||
|
|
||||||
@@ -153,12 +159,23 @@ class WritingReviewServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void singleClue_notRaised_withTwoPaths_orInChapterWithoutLinks() {
|
void singleClue_twoPathsAreStillBelowTheThreeClueRule() {
|
||||||
tree(List.of(
|
tree(List.of(
|
||||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
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("s2", 1).type(SceneType.LOCATION).branches(List.of(SceneBranch.of("B", "rev"))).build(),
|
||||||
scene("rev", 2).type(SceneType.REVELATION).build()));
|
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||||
|
assertEquals("2", remark("WRITE-003-SINGLE-CLUE").params().get("incoming"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void singleClue_notRaised_withThreeVariedPaths() {
|
||||||
|
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("s3", 2).type(SceneType.EVENT).branches(List.of(SceneBranch.of("C", "rev"))).build(),
|
||||||
|
scene("rev", 3).type(SceneType.REVELATION).build()));
|
||||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-015-SAME-SOURCE-CLUES"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -319,4 +336,180 @@ class WritingReviewServiceTest {
|
|||||||
tree(List.of(scene("s1", 0).type(SceneType.GENERIC).build()));
|
tree(List.of(scene("s1", 0).type(SceneType.GENERIC).build()));
|
||||||
assertFalse(ruleIds().contains("WRITE-010-UNTYPED-SCENES"));
|
assertFalse(ruleIds().contains("WRITE-010-UNTYPED-SCENES"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- WRITE-011 : scène isolée ---
|
||||||
|
|
||||||
|
private static SceneBranch to(String target) {
|
||||||
|
return SceneBranch.of("vers " + target, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isolatedScene_noLinkInNorOut_inALinkedChapter() {
|
||||||
|
tree(List.of(
|
||||||
|
scene("s1", 0).branches(List.of(to("s2"))).build(),
|
||||||
|
scene("s2", 1).type(SceneType.LOCATION).branches(List.of(to("s3"))).build(),
|
||||||
|
scene("s3", 2).build(),
|
||||||
|
scene("lost", 3).type(SceneType.LOCATION).build()));
|
||||||
|
|
||||||
|
WritingRemark r = remark("WRITE-011-ISOLATED-SCENE");
|
||||||
|
assertEquals("lost", r.entityId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isolatedScene_notRaised_forAnOpeningOrAProactiveScene_orWithoutLinks() {
|
||||||
|
// « event » n'a pas de lien entrant mais en a un sortant : scène que le MJ déclenche.
|
||||||
|
tree(List.of(
|
||||||
|
scene("s1", 0).branches(List.of(to("s2"))).build(),
|
||||||
|
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||||
|
scene("event", 2).type(SceneType.EVENT).branches(List.of(to("s2"))).build()));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-011-ISOLATED-SCENE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isolatedScene_notRaised_whenTheChapterDoesNotUseLinks() {
|
||||||
|
tree(List.of(scene("s1", 0).branches(List.of(to("s2"))).build(),
|
||||||
|
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||||
|
scene("s3", 2).build()));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-011-ISOLATED-SCENE"), "une seule scène reliée : pas un graphe");
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- WRITE-012 : passage obligé ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void chokepoint_everyPathGoesThroughOneScene() {
|
||||||
|
// s1 → (a | b) → gate → (end1 | end2)
|
||||||
|
tree(List.of(
|
||||||
|
scene("s1", 0).branches(List.of(to("a"), to("b"))).build(),
|
||||||
|
scene("a", 1).type(SceneType.LOCATION).branches(List.of(to("gate"))).build(),
|
||||||
|
scene("b", 2).branches(List.of(to("gate"))).build(),
|
||||||
|
scene("gate", 3).type(SceneType.LOCATION).branches(List.of(to("end1"), to("end2"))).build(),
|
||||||
|
scene("end1", 4).build(),
|
||||||
|
scene("end2", 5).type(SceneType.EVENT).build()));
|
||||||
|
|
||||||
|
WritingRemark r = remark("WRITE-012-CHOKEPOINT");
|
||||||
|
assertEquals("gate", r.entityId());
|
||||||
|
assertEquals("1", r.params().get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void chokepoint_notRaised_whenAnotherRouteExists() {
|
||||||
|
// s1 → a → end ; s1 → b → end : deux routes indépendantes.
|
||||||
|
tree(List.of(
|
||||||
|
scene("s1", 0).branches(List.of(to("a"), to("b"))).build(),
|
||||||
|
scene("a", 1).type(SceneType.LOCATION).branches(List.of(to("end"))).build(),
|
||||||
|
scene("b", 2).branches(List.of(to("end"))).build(),
|
||||||
|
scene("end", 3).type(SceneType.EVENT).build()));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-012-CHOKEPOINT"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- WRITE-013 : donjon en couloir ---
|
||||||
|
|
||||||
|
private static Room room(String id, String... targets) {
|
||||||
|
List<RoomBranch> branches = new ArrayList<>();
|
||||||
|
for (String t : targets) branches.add(RoomBranch.of("porte", t));
|
||||||
|
return Room.builder().id(id).name(id).order(0).branches(branches).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void linearDungeon_roomsLinkedWithoutAnyLoop() {
|
||||||
|
tree(List.of(scene("crypt", 0).type(SceneType.LOCATION).rooms(List.of(
|
||||||
|
room("r1", "r2"), room("r2", "r1", "r3"), room("r3", "r4"), room("r4"))).build()));
|
||||||
|
|
||||||
|
WritingRemark r = remark("WRITE-013-LINEAR-DUNGEON");
|
||||||
|
assertEquals("4", r.params().get("rooms"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void linearDungeon_notRaised_withALoop_orUnlinkedRooms() {
|
||||||
|
tree(List.of(
|
||||||
|
scene("loop", 0).type(SceneType.LOCATION).rooms(List.of(
|
||||||
|
room("r1", "r2"), room("r2", "r3"), room("r3", "r4"), room("r4", "r1"))).build(),
|
||||||
|
scene("plain", 1).rooms(List.of(room("x1"), room("x2"), room("x3"), room("x4"))).build()));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-013-LINEAR-DUNGEON"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- WRITE-014 : enquête sans relance ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noProactive_investigationWithoutAnyEvent() {
|
||||||
|
tree(List.of(
|
||||||
|
scene("s1", 0).branches(List.of(to("s2"), to("rev"))).build(),
|
||||||
|
scene("s2", 1).type(SceneType.LOCATION).branches(List.of(to("rev"))).build(),
|
||||||
|
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||||
|
assertEquals(ReadinessEntityType.CHAPTER, remark("WRITE-014-NO-PROACTIVE").entityType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noProactive_notRaised_withAnEventScene() {
|
||||||
|
tree(List.of(
|
||||||
|
scene("s1", 0).branches(List.of(to("s2"), to("rev"))).build(),
|
||||||
|
scene("s2", 1).type(SceneType.EVENT).branches(List.of(to("rev"))).build(),
|
||||||
|
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-014-NO-PROACTIVE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- WRITE-015 : indices tous du même genre ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void sameSourceClues_threePathsAllFromNpcScenes() {
|
||||||
|
tree(List.of(
|
||||||
|
scene("n1", 0).branches(List.of(to("rev"))).build(),
|
||||||
|
scene("n2", 1).branches(List.of(to("rev"))).build(),
|
||||||
|
scene("n3", 2).branches(List.of(to("rev"))).build(),
|
||||||
|
scene("rev", 3).type(SceneType.REVELATION).build()));
|
||||||
|
|
||||||
|
WritingRemark r = remark("WRITE-015-SAME-SOURCE-CLUES");
|
||||||
|
assertEquals("NPC", r.params().get("kind"));
|
||||||
|
assertEquals("3", r.params().get("count"));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- WRITE-008 : la tactique des adversaires donne un but au combat ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void combatPurpose_notRaised_whenTacticsAreWritten() {
|
||||||
|
tree(List.of(scene("fight", 0).type(SceneType.ENCOUNTER).choicesConsequences(null)
|
||||||
|
.tactics("Ils fuient dès que leur chef tombe").build()));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-008-COMBAT-NO-PURPOSE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- WRITE-016 : opposant ou allié sans motivation ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void npcWithoutMotivation_onlyForPlotDrivingRoles() {
|
||||||
|
when(npcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||||
|
Npc.builder().id("n1").name("Ysolde").story(new NpcStory("OPPONENT", " ", null, null)).build(),
|
||||||
|
Npc.builder().id("n2").name("Borin").story(new NpcStory("ALLY", "Protéger sa fille", null, null)).build(),
|
||||||
|
Npc.builder().id("n3").name("Le passant").story(new NpcStory("EXTRA", null, null, null)).build(),
|
||||||
|
Npc.builder().id("n4").name("Sans fiche").build()));
|
||||||
|
|
||||||
|
List<WritingRemark> remarks = service.review(CAMP).remarks().stream()
|
||||||
|
.filter(r -> r.ruleId().equals("WRITE-016-NPC-NO-MOTIVATION")).toList();
|
||||||
|
assertEquals(1, remarks.size());
|
||||||
|
assertEquals("n1", remarks.get(0).entityId());
|
||||||
|
assertEquals(ReadinessEntityType.NPC, remarks.get(0).entityType());
|
||||||
|
assertEquals("OPPONENT", remarks.get(0).params().get("role"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- WRITE-017 : une seule accroche ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void singleHook_whenTheArcHasExactlyOne() {
|
||||||
|
Arc arc = arc("arc", ArcType.HUB);
|
||||||
|
arc.setHooks("- Le prêtre a disparu");
|
||||||
|
tree(arc, chapter("chap", "arc"), List.of(scene("s1", 0).build()));
|
||||||
|
assertEquals(ReadinessEntityType.ARC, remark("WRITE-017-SINGLE-HOOK").entityType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void singleHook_notRaised_withSeveralHooks_orNone() {
|
||||||
|
Arc several = arc("arc", ArcType.HUB);
|
||||||
|
several.setHooks("- Le prêtre a disparu\n\n- Une récompense est offerte");
|
||||||
|
tree(several, chapter("chap", "arc"), List.of(scene("s1", 0).build()));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-017-SINGLE-HOOK"));
|
||||||
|
|
||||||
|
Arc none = arc("arc", ArcType.HUB);
|
||||||
|
tree(none, chapter("chap", "arc"), List.of(scene("s1", 0).build()));
|
||||||
|
assertFalse(ruleIds().contains("WRITE-017-SINGLE-HOOK"), "accroches non renseignées : pas de remarque");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ class NetworkReadinessTest {
|
|||||||
private static final FirewallRule ALLOW_PRIVATE = new FirewallRule("Allow", "Private", "True");
|
private static final FirewallRule ALLOW_PRIVATE = new FirewallRule("Allow", "Private", "True");
|
||||||
|
|
||||||
private static NetworkReadiness eval(List<Network> networks, List<FirewallRule> rules) {
|
private static NetworkReadiness eval(List<Network> networks, List<FirewallRule> rules) {
|
||||||
return NetworkReadiness.evaluate(new NetworkSnapshot(true, "C:\\DM Loremind.exe", networks, rules));
|
return NetworkReadiness.evaluate(new NetworkSnapshot(true, "C:\\DM Loremind.exe", networks, rules, List.of()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -71,9 +71,48 @@ class NetworkReadinessTest {
|
|||||||
assertTrue(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Any", "True"))).ready());
|
assertTrue(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Any", "True"))).ready());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void thirdPartyFirewall_isReported_withoutPretendingToKnowItsRules() {
|
||||||
|
// Cas réel du 2026-10-17 : Windows prêt, mais Bitdefender filtre en plus avec ses propres règles.
|
||||||
|
NetworkReadiness r = NetworkReadiness.evaluate(new NetworkSnapshot(true, "C:\\DM Loremind.exe",
|
||||||
|
List.of(HOME_PRIVATE), List.of(ALLOW_PRIVATE), List.of("Bitdefender Pare-feu")));
|
||||||
|
assertTrue(r.ready(), "Windows est prêt…");
|
||||||
|
assertEquals(List.of("Bitdefender Pare-feu"), r.thirdPartyFirewalls(), "…mais le pare-feu tiers est signalé");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void publicNetwork_withoutName_usesInterfaceAlias() {
|
void publicNetwork_withoutName_usesInterfaceAlias() {
|
||||||
NetworkReadiness r = eval(List.of(new Network(null, "Wi-Fi", "Public")), List.of(ALLOW_PRIVATE));
|
NetworkReadiness r = eval(List.of(new Network(null, "Wi-Fi", "Public")), List.of(ALLOW_PRIVATE));
|
||||||
assertEquals(List.of("Wi-Fi"), r.publicNetworks());
|
assertEquals(List.of("Wi-Fi"), r.publicNetworks());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Linux ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void linux_withoutFirewall_isReady() {
|
||||||
|
NetworkReadiness r = NetworkReadiness.evaluate(NetworkSnapshot.linux("none", 8765, null));
|
||||||
|
assertTrue(r.ready());
|
||||||
|
assertEquals("linux", r.platform());
|
||||||
|
assertNull(r.fixCommand());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void linux_ufw_portUnknown_proposesTheCommand() {
|
||||||
|
NetworkReadiness r = NetworkReadiness.evaluate(NetworkSnapshot.linux("ufw", 8765, null));
|
||||||
|
assertFalse(r.ready());
|
||||||
|
assertNull(r.portOpen());
|
||||||
|
assertEquals("sudo ufw allow 8765/tcp", r.fixCommand());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void linux_firewalld_closedThenOpen() {
|
||||||
|
NetworkReadiness closed = NetworkReadiness.evaluate(NetworkSnapshot.linux("firewalld", 9000, false));
|
||||||
|
assertFalse(closed.ready());
|
||||||
|
assertEquals("sudo firewall-cmd --permanent --add-port=9000/tcp && sudo firewall-cmd --reload", closed.fixCommand());
|
||||||
|
|
||||||
|
NetworkReadiness open = NetworkReadiness.evaluate(NetworkSnapshot.linux("firewalld", 9000, true));
|
||||||
|
assertTrue(open.ready());
|
||||||
|
assertNull(open.fixCommand());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Fiche « Publication » : nettoyage de saisie et regroupements utilisés par l'export PDF. */
|
||||||
|
class CampaignPublicationTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void normalized_trimsBlanksAndCapsLengths() {
|
||||||
|
CampaignPublication p = new CampaignPublication(" Sous-titre ", " ", null, null, null, null,
|
||||||
|
"x".repeat(25_000), null, null, null, null, null, "v".repeat(300), "");
|
||||||
|
|
||||||
|
CampaignPublication n = p.normalized();
|
||||||
|
|
||||||
|
assertEquals("Sous-titre", n.subtitle());
|
||||||
|
assertNull(n.author(), "un texte blanc devient null");
|
||||||
|
assertNull(n.coverImageId());
|
||||||
|
assertEquals(20_000, n.pitch().length(), "texte long borné");
|
||||||
|
assertEquals(200, n.version().length(), "texte court borné");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void emptiness_andGroups() {
|
||||||
|
assertFalse(CampaignPublication.empty().hasContent());
|
||||||
|
assertFalse(new CampaignPublication(" ", "", null, null, null, null, null, null, null, null,
|
||||||
|
null, null, null, null).hasContent(), "que des blancs = vide");
|
||||||
|
|
||||||
|
CampaignPublication tech = new CampaignPublication(null, null, null, null, "3 à 5", null,
|
||||||
|
null, null, null, null, null, null, null, null);
|
||||||
|
assertTrue(tech.hasContent());
|
||||||
|
assertTrue(tech.hasTechnicalSheet());
|
||||||
|
assertFalse(tech.hasCredits());
|
||||||
|
|
||||||
|
CampaignPublication credits = new CampaignPublication(null, null, null, null, null, null,
|
||||||
|
null, null, null, null, null, "CC BY 4.0", null, null);
|
||||||
|
assertTrue(credits.hasCredits());
|
||||||
|
assertFalse(credits.hasTechnicalSheet());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.bestiary;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Fiche « rôle dans l'histoire » d'un PNJ : nettoyage et rôle moteur de l'intrigue. */
|
||||||
|
class NpcStoryTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void normalized_cleansRoleAndTexts() {
|
||||||
|
NpcStory s = new NpcStory(" ally ", " Venger son frère ", " ", "x".repeat(400)).normalized();
|
||||||
|
assertEquals("ALLY", s.role());
|
||||||
|
assertEquals("Venger son frère", s.motivation());
|
||||||
|
assertNull(s.knowledge());
|
||||||
|
assertEquals(300, s.mannerism().length());
|
||||||
|
assertNull(new NpcStory("BOSS", null, null, null).normalized().role(), "rôle inconnu écarté");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void contentAndPlotRole() {
|
||||||
|
assertFalse(new NpcStory(" ", "", null, null).hasContent());
|
||||||
|
assertTrue(new NpcStory(null, null, null, "Se gratte la barbe").hasContent());
|
||||||
|
assertTrue(new NpcStory("OPPONENT", null, null, null).drivesThePlot());
|
||||||
|
assertTrue(new NpcStory("ally", null, null, null).drivesThePlot());
|
||||||
|
assertFalse(new NpcStory("EXTRA", null, null, null).drivesThePlot());
|
||||||
|
assertFalse(new NpcStory(null, "x", null, null).drivesThePlot());
|
||||||
|
}
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||||
|
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test de {@link LinuxHostNetworkAccess} : lecture de ufw.conf, interprétation de
|
||||||
|
* {@code firewall-cmd --query-port}, et cas ufw actif sans droits root (port inconnu).
|
||||||
|
*/
|
||||||
|
class LinuxHostNetworkAccessTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ufwEnabled_readsTheConfigFile() {
|
||||||
|
assertTrue(LinuxHostNetworkAccess.ufwEnabled("# commentaire\nENABLED=yes\nLOGLEVEL=low"));
|
||||||
|
assertTrue(LinuxHostNetworkAccess.ufwEnabled("ENABLED=\"yes\""));
|
||||||
|
assertFalse(LinuxHostNetworkAccess.ufwEnabled("ENABLED=no"));
|
||||||
|
assertFalse(LinuxHostNetworkAccess.ufwEnabled("#ENABLED=yes"));
|
||||||
|
assertFalse(LinuxHostNetworkAccess.ufwEnabled(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void firewalldQuery_yesNoOrUnknown() {
|
||||||
|
assertEquals(Boolean.TRUE, LinuxHostNetworkAccess.interpretQuery(0, "yes\n"));
|
||||||
|
assertEquals(Boolean.FALSE, LinuxHostNetworkAccess.interpretQuery(1, "no\n"));
|
||||||
|
// Refus D-Bus / commande absente : on ne prétend rien.
|
||||||
|
assertNull(LinuxHostNetworkAccess.interpretQuery(-1, ""));
|
||||||
|
assertNull(LinuxHostNetworkAccess.interpretQuery(11, "Authorization failed."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void activeUfw_meansPortUnknownWithoutRoot(@TempDir Path dir) throws Exception {
|
||||||
|
Path conf = dir.resolve("ufw.conf");
|
||||||
|
Files.writeString(conf, "ENABLED=yes\n");
|
||||||
|
|
||||||
|
NetworkSnapshot s = new LinuxHostNetworkAccess(conf).inspect(8765);
|
||||||
|
|
||||||
|
assertTrue(s.supported());
|
||||||
|
assertEquals("linux", s.platform());
|
||||||
|
assertEquals("ufw", s.linuxFirewall());
|
||||||
|
assertEquals(8765, s.port());
|
||||||
|
assertNull(s.portOpen());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noOneClickFixOnLinux() {
|
||||||
|
assertEquals(HostNetworkAccess.FirewallFixOutcome.UNSUPPORTED,
|
||||||
|
new LinuxHostNetworkAccess(Path.of("absent")).allowThroughFirewall());
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-1
@@ -33,6 +33,18 @@ class WindowsHostNetworkAccessTest {
|
|||||||
assertEquals("Private", s.networks().get(0).category());
|
assertEquals("Private", s.networks().get(0).category());
|
||||||
assertEquals(2, s.rules().size());
|
assertEquals(2, s.rules().size());
|
||||||
assertEquals("Block", s.rules().get(1).action());
|
assertEquals("Block", s.rules().get(1).action());
|
||||||
|
assertTrue(s.thirdPartyFirewalls().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_readsThirdPartyFirewalls_asSingleValueOrArray() throws Exception {
|
||||||
|
NetworkSnapshot one = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe",
|
||||||
|
"{\"networks\":[],\"rules\":[],\"thirdPartyFirewalls\":\"Bitdefender Pare-feu\"}");
|
||||||
|
assertEquals(java.util.List.of("Bitdefender Pare-feu"), one.thirdPartyFirewalls());
|
||||||
|
|
||||||
|
NetworkSnapshot two = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe",
|
||||||
|
"{\"networks\":[],\"rules\":[],\"thirdPartyFirewalls\":[\"Norton\",\"\"]}");
|
||||||
|
assertEquals(java.util.List.of("Norton"), two.thirdPartyFirewalls());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -55,6 +67,7 @@ class WindowsHostNetworkAccessTest {
|
|||||||
assertFalse(allow.contains("Public"), "la règle ne doit jamais ouvrir les réseaux publics");
|
assertFalse(allow.contains("Public"), "la règle ne doit jamais ouvrir les réseaux publics");
|
||||||
assertTrue(allow.contains("Remove-NetFirewallRule"), "les blocages de CE programme sont retirés");
|
assertTrue(allow.contains("Remove-NetFirewallRule"), "les blocages de CE programme sont retirés");
|
||||||
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("ConvertTo-Json"));
|
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("ConvertTo-Json"));
|
||||||
|
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("SecurityCenter2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -66,8 +79,9 @@ class WindowsHostNetworkAccessTest {
|
|||||||
@Test
|
@Test
|
||||||
@EnabledOnOs(OS.WINDOWS)
|
@EnabledOnOs(OS.WINDOWS)
|
||||||
void inspect_readsTheRealSystem_onWindows() {
|
void inspect_readsTheRealSystem_onWindows() {
|
||||||
NetworkSnapshot s = new WindowsHostNetworkAccess(mapper).inspect();
|
NetworkSnapshot s = new WindowsHostNetworkAccess(mapper).inspect(8765);
|
||||||
assertTrue(s.supported(), "PowerShell doit répondre en lecture seule sur Windows");
|
assertTrue(s.supported(), "PowerShell doit répondre en lecture seule sur Windows");
|
||||||
assertNotNull(s.program());
|
assertNotNull(s.program());
|
||||||
|
assertNotNull(s.thirdPartyFirewalls());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.converter;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class CampaignPublicationJsonConverterTest {
|
||||||
|
|
||||||
|
private final CampaignPublicationJsonConverter converter = new CampaignPublicationJsonConverter();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void roundTrip() {
|
||||||
|
CampaignPublication p = new CampaignPublication("Sous-titre", "Autrice", "D&D 5e", "1-3", "4",
|
||||||
|
"3 h", "Argument", "Contexte", "- A\n- B", null, "Crédits", "Licence", "1.0", "42");
|
||||||
|
|
||||||
|
String json = converter.convertToDatabaseColumn(p);
|
||||||
|
|
||||||
|
assertEquals(p, converter.convertToEntityAttribute(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void emptyIsNull_andUnknownFieldsAreIgnored() {
|
||||||
|
assertNull(converter.convertToDatabaseColumn(CampaignPublication.empty()));
|
||||||
|
assertNull(converter.convertToDatabaseColumn(null));
|
||||||
|
assertNull(converter.convertToEntityAttribute(null));
|
||||||
|
assertNull(converter.convertToEntityAttribute(" "));
|
||||||
|
// Fiche écrite par une version plus récente : champ inconnu toléré.
|
||||||
|
assertEquals("T", converter.convertToEntityAttribute("{\"subtitle\":\"T\",\"futureField\":1}").subtitle());
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
@@ -165,6 +165,7 @@ class ContentExportImportRoundTripTest {
|
|||||||
|
|
||||||
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder()
|
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder()
|
||||||
.name("RT Arc").campaignId(campaign.getId()).order(0).type(ArcType.HUB)
|
.name("RT Arc").campaignId(campaign.getId()).order(0).type(ArcType.HUB)
|
||||||
|
.hiddenTruth("RT vérité").hooks("- RT accroche 1\n- RT accroche 2")
|
||||||
.relatedPageIds(new ArrayList<>(List.of(String.valueOf(page.getId()))))
|
.relatedPageIds(new ArrayList<>(List.of(String.valueOf(page.getId()))))
|
||||||
.illustrationImageIds(new ArrayList<>(List.of(imageRef))).build());
|
.illustrationImageIds(new ArrayList<>(List.of(imageRef))).build());
|
||||||
|
|
||||||
@@ -189,6 +190,7 @@ class ContentExportImportRoundTripTest {
|
|||||||
|
|
||||||
sceneRepo.save(SceneJpaEntity.builder()
|
sceneRepo.save(SceneJpaEntity.builder()
|
||||||
.name("RT Scene").chapterId(chapterB.getId()).order(0)
|
.name("RT Scene").chapterId(chapterB.getId()).order(0)
|
||||||
|
.tactics("RT fuient à la moitié").purpose("RT révèle le traître")
|
||||||
.enemyIds(new ArrayList<>(List.of(String.valueOf(enemy.getId()))))
|
.enemyIds(new ArrayList<>(List.of(String.valueOf(enemy.getId()))))
|
||||||
.relatedPageIds(new ArrayList<>(List.of(String.valueOf(page.getId()))))
|
.relatedPageIds(new ArrayList<>(List.of(String.valueOf(page.getId()))))
|
||||||
.illustrationImageIds(new ArrayList<>(List.of(imageRef)))
|
.illustrationImageIds(new ArrayList<>(List.of(imageRef)))
|
||||||
@@ -198,6 +200,7 @@ class ContentExportImportRoundTripTest {
|
|||||||
|
|
||||||
npcRepo.save(NpcJpaEntity.builder()
|
npcRepo.save(NpcJpaEntity.builder()
|
||||||
.name("RT Npc").campaignId(campaign.getId()).portraitImageId(imageRef).folder("Ville").order(0)
|
.name("RT Npc").campaignId(campaign.getId()).portraitImageId(imageRef).folder("Ville").order(0)
|
||||||
|
.story(new com.loremind.domain.campaigncontext.bestiary.NpcStory("ALLY", "RT venger son frère", null, "RT tic"))
|
||||||
.relatedPageIds(new ArrayList<>(List.of(String.valueOf(page.getId())))).build());
|
.relatedPageIds(new ArrayList<>(List.of(String.valueOf(page.getId())))).build());
|
||||||
|
|
||||||
ItemCatalogJpaEntity catalog = ItemCatalogJpaEntity.builder()
|
ItemCatalogJpaEntity catalog = ItemCatalogJpaEntity.builder()
|
||||||
@@ -353,6 +356,18 @@ class ContentExportImportRoundTripTest {
|
|||||||
assertEquals((int) playthroughsBefore, result.created().get("playthroughs"));
|
assertEquals((int) playthroughsBefore, result.created().get("playthroughs"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void import_keepsStoryFields_ofArcsScenesAndNpcs() {
|
||||||
|
assertEquals("RT vérité", importedArc.getHiddenTruth());
|
||||||
|
assertTrue(importedArc.getHooks().contains("RT accroche 2"));
|
||||||
|
assertEquals(2, rtScenes.size());
|
||||||
|
assertTrue(rtScenes.stream().allMatch(s -> "RT fuient à la moitié".equals(s.getTactics())
|
||||||
|
&& "RT révèle le traître".equals(s.getPurpose())));
|
||||||
|
List<NpcJpaEntity> npcs = npcRepo.findAll().stream().filter(n -> "RT Npc".equals(n.getName())).toList();
|
||||||
|
assertEquals(2, npcs.size());
|
||||||
|
assertTrue(npcs.stream().allMatch(n -> n.getStory() != null && "RT venger son frère".equals(n.getStory().motivation())));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void import_remapsPrepEntities_arcPointsToImportedPage() {
|
void import_remapsPrepEntities_arcPointsToImportedPage() {
|
||||||
assertTrue(importedArc.getRelatedPageIds().contains(String.valueOf(importedPageId)));
|
assertTrue(importedArc.getRelatedPageIds().contains(String.valueOf(importedPageId)));
|
||||||
|
|||||||
+12
-1
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.infrastructure.transfer;
|
package com.loremind.infrastructure.transfer;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
import com.loremind.domain.campaigncontext.structure.Room;
|
import com.loremind.domain.campaigncontext.structure.Room;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||||
import com.loremind.domain.files.ports.FileStorage;
|
import com.loremind.domain.files.ports.FileStorage;
|
||||||
@@ -90,7 +91,10 @@ class ImageRefRemapOnImportTest {
|
|||||||
String oldFileRef = String.valueOf(file.getId());
|
String oldFileRef = String.valueOf(file.getId());
|
||||||
|
|
||||||
CampaignJpaEntity campaign = campaignRepo.save(CampaignJpaEntity.builder()
|
CampaignJpaEntity campaign = campaignRepo.save(CampaignJpaEntity.builder()
|
||||||
.name("Remap Campaign").description("d").arcsCount(1).build());
|
.name("Remap Campaign").description("d").arcsCount(1)
|
||||||
|
.publication(new CampaignPublication("Sous-titre", "Autrice", null, null, null, null,
|
||||||
|
null, null, null, null, null, null, "1.0", oldImageRef))
|
||||||
|
.build());
|
||||||
|
|
||||||
Long originalNpcId = npcRepo.save(NpcJpaEntity.builder()
|
Long originalNpcId = npcRepo.save(NpcJpaEntity.builder()
|
||||||
.name("Remap Npc").campaignId(campaign.getId())
|
.name("Remap Npc").campaignId(campaign.getId())
|
||||||
@@ -149,6 +153,13 @@ class ImageRefRemapOnImportTest {
|
|||||||
String newFileRef = String.valueOf(newFile.getId());
|
String newFileRef = String.valueOf(newFile.getId());
|
||||||
assertNotEquals(oldFileRef, newFileRef, "le fichier importé doit avoir un id neuf");
|
assertNotEquals(oldFileRef, newFileRef, "le fichier importé doit avoir un id neuf");
|
||||||
|
|
||||||
|
// Campagne importée : fiche Publication conservée, couverture remappée.
|
||||||
|
CampaignJpaEntity importedCampaign = campaignRepo.findAll().stream()
|
||||||
|
.filter(c -> "Remap Campaign".equals(c.getName()) && !c.getId().equals(campaign.getId()))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
assertEquals("Sous-titre", importedCampaign.getPublication().subtitle(), "fiche Publication importée");
|
||||||
|
assertEquals(newImageRef, importedCampaign.getPublication().coverImageId(), "couverture remappée");
|
||||||
|
|
||||||
// NPC importé : portrait + header + galerie pointent la nouvelle image.
|
// NPC importé : portrait + header + galerie pointent la nouvelle image.
|
||||||
NpcJpaEntity importedNpc = npcRepo.findAll().stream()
|
NpcJpaEntity importedNpc = npcRepo.findAll().stream()
|
||||||
.filter(n -> "Remap Npc".equals(n.getName()) && !n.getId().equals(originalNpcId))
|
.filter(n -> "Remap Npc".equals(n.getName()) && !n.getId().equals(originalNpcId))
|
||||||
|
|||||||
+171
@@ -0,0 +1,171 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.domain.files.ports.FileStorage;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.*;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.*;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.LoreScope;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.PageFormat;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.Section;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mise en page « module » : renvois « (p. N) » vers les scènes et les fiches, renvois morts
|
||||||
|
* neutralisés, annexes MJ (révélations et indices, index PNJ et adversaires avec leurs
|
||||||
|
* apparitions) et cartes en pleine page paysage.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
@Transactional
|
||||||
|
class PdfExportModuleLayoutTest {
|
||||||
|
|
||||||
|
@Autowired private PdfExportService service;
|
||||||
|
@Autowired private CampaignJpaRepository campaignRepo;
|
||||||
|
@Autowired private ArcJpaRepository arcRepo;
|
||||||
|
@Autowired private ChapterJpaRepository chapterRepo;
|
||||||
|
@Autowired private SceneJpaRepository sceneRepo;
|
||||||
|
@Autowired private NpcJpaRepository npcRepo;
|
||||||
|
@Autowired private EnemyJpaRepository enemyRepo;
|
||||||
|
@Autowired private StoredFileJpaRepository storedFileRepo;
|
||||||
|
|
||||||
|
@MockitoBean private FileStorage fileStorage;
|
||||||
|
|
||||||
|
private String campaignId;
|
||||||
|
private Long revId;
|
||||||
|
private Long enemyId;
|
||||||
|
private Long npcId;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void seed() throws Exception {
|
||||||
|
byte[] png = png(300, 200);
|
||||||
|
StoredFileJpaEntity map = storedFileRepo.save(StoredFileJpaEntity.builder()
|
||||||
|
.filename("map.png").contentType("image/png").sizeBytes(png.length).storageKey("files/layout-map.png").build());
|
||||||
|
when(fileStorage.download("files/layout-map.png")).thenAnswer(inv -> new ByteArrayInputStream(png));
|
||||||
|
|
||||||
|
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder().name("Module").arcsCount(1).build());
|
||||||
|
campaignId = String.valueOf(camp.getId());
|
||||||
|
enemyId = enemyRepo.save(EnemyJpaEntity.builder().campaignId(camp.getId()).name("Goule").level("3")
|
||||||
|
.folder("Morts-vivants").order(0).build()).getId();
|
||||||
|
npcId = npcRepo.save(NpcJpaEntity.builder().campaignId(camp.getId()).name("Maëlis").folder("Valfroide")
|
||||||
|
.order(0).build()).getId();
|
||||||
|
|
||||||
|
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder().name("Acte I").campaignId(camp.getId()).order(0).build());
|
||||||
|
ChapterJpaEntity ch = chapterRepo.save(ChapterJpaEntity.builder().name("La foire").arcId(arc.getId()).order(0).build());
|
||||||
|
chapterRepo.save(ChapterJpaEntity.builder().name("La crypte").arcId(arc.getId()).order(1).build());
|
||||||
|
|
||||||
|
revId = sceneRepo.save(SceneJpaEntity.builder().name("Le secret du stand").chapterId(ch.getId()).order(2)
|
||||||
|
.type(SceneType.REVELATION).build()).getId();
|
||||||
|
sceneRepo.save(SceneJpaEntity.builder().name("L'auberge").chapterId(ch.getId()).order(0)
|
||||||
|
.branches(new ArrayList<>(List.of(
|
||||||
|
new SceneBranch("Fouiller le stand", String.valueOf(revId), null, LinkType.CLUE),
|
||||||
|
SceneBranch.of("Vers nulle part", "999999"))))
|
||||||
|
.build());
|
||||||
|
sceneRepo.save(SceneJpaEntity.builder().name("L'embuscade").chapterId(ch.getId()).order(1)
|
||||||
|
.type(SceneType.ENCOUNTER).combatDifficulty("Moyenne")
|
||||||
|
.enemyIds(new ArrayList<>(List.of(String.valueOf(enemyId))))
|
||||||
|
.battlemaps(new ArrayList<>(List.of(new SceneBattlemap("Nuit", String.valueOf(map.getId()), null))))
|
||||||
|
.branches(new ArrayList<>(List.of(SceneBranch.of("Le carnet", String.valueOf(revId)))))
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PdfExportOptions options(boolean gm, Section... sections) {
|
||||||
|
return new PdfExportOptions(gm, PageFormat.A4, false,
|
||||||
|
sections.length == 0 ? EnumSet.allOf(Section.class) : EnumSet.of(sections[0], sections), LoreScope.ALL);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void sceneExitsAndEnemies_pointToTheirPage() {
|
||||||
|
String x = service.xhtml(campaignId, PdfExportOptions.defaults());
|
||||||
|
|
||||||
|
String rev = "#scene-" + revId;
|
||||||
|
assertTrue(x.contains("<a class=\"xref\" href=\"" + rev + "\">Le secret du stand</a>"), "nom de scène cliquable");
|
||||||
|
assertTrue(x.contains("<a class=\"pref\" href=\"" + rev + "\"></a>"), "numéro de page de la scène");
|
||||||
|
assertTrue(x.contains("<a class=\"xref\" href=\"#enemy-" + enemyId + "\">Goule</a>"), "adversaire renvoyé à sa fiche");
|
||||||
|
assertTrue(x.contains("id=\"enemy-" + enemyId + "\""), "fiche du bestiaire ancrée");
|
||||||
|
assertTrue(x.contains("id=\"npc-" + npcId + "\""), "fiche PNJ ancrée");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deadReferences_areReducedToPlainText() {
|
||||||
|
String x = service.xhtml(campaignId, PdfExportOptions.defaults());
|
||||||
|
assertFalse(x.contains("#scene-999999"), "lien vers une scène inexistante neutralisé");
|
||||||
|
|
||||||
|
// Sans bestiaire : le nom de l'adversaire reste, sans lien ni page.
|
||||||
|
String noBestiary = service.xhtml(campaignId, options(true, Section.NARRATIVE));
|
||||||
|
assertFalse(noBestiary.contains("#enemy-" + enemyId));
|
||||||
|
assertTrue(noBestiary.contains("Goule"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void gmAppendix_listsRevelationSourcesAndIndexes() {
|
||||||
|
String x = service.xhtml(campaignId, PdfExportOptions.defaults());
|
||||||
|
|
||||||
|
assertTrue(x.contains("id=\"part-annex\""));
|
||||||
|
assertTrue(x.contains("Révélations et indices"));
|
||||||
|
int table = x.indexOf("id=\"annex-revelations\"");
|
||||||
|
String annex = x.substring(table);
|
||||||
|
assertTrue(annex.contains(">L'auberge</a>"), "source de la révélation listée");
|
||||||
|
assertTrue(annex.contains(">L'embuscade</a>"));
|
||||||
|
assertTrue(annex.contains("indice"), "nature du lien");
|
||||||
|
assertTrue(annex.contains("Index des PNJ"));
|
||||||
|
assertTrue(annex.contains("Index des adversaires"));
|
||||||
|
assertTrue(annex.contains("Morts-vivants"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void playerEdition_hasNoGmAppendix() {
|
||||||
|
String x = service.xhtml(campaignId, options(false));
|
||||||
|
assertFalse(x.contains("id=\"part-annex\""));
|
||||||
|
assertFalse(x.contains("Révélations et indices"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mapsAppendix_replacesInlineBattlemaps() {
|
||||||
|
String withMaps = service.xhtml(campaignId, PdfExportOptions.defaults());
|
||||||
|
assertTrue(withMaps.contains("class=\"map-page\""));
|
||||||
|
assertTrue(withMaps.contains("L'embuscade — Nuit"));
|
||||||
|
assertFalse(withMaps.contains("Battlemap — Nuit"), "pas de doublon en petit dans la scène");
|
||||||
|
|
||||||
|
String inline = service.xhtml(campaignId, options(true, Section.NARRATIVE));
|
||||||
|
assertFalse(inline.contains("class=\"map-page\""));
|
||||||
|
assertTrue(inline.contains("Battlemap — Nuit"), "sans annexe, la carte reste dans la scène");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mapPages_areLandscape() throws Exception {
|
||||||
|
byte[] pdf = service.export(campaignId, PdfExportOptions.defaults());
|
||||||
|
try (PDDocument doc = PDDocument.load(pdf)) {
|
||||||
|
PDRectangle last = doc.getPage(doc.getNumberOfPages() - 1).getMediaBox();
|
||||||
|
assertTrue(last.getWidth() > last.getHeight(), "la carte est sur une page paysage");
|
||||||
|
PDRectangle first = doc.getPage(0).getMediaBox();
|
||||||
|
assertTrue(first.getWidth() < first.getHeight(), "le reste du livret reste en portrait");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] png(int w, int h) throws Exception {
|
||||||
|
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
ImageIO.write(img, "png", out);
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.LoreScope;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.PageFormat;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.Section;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.EnumSet;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Options d'export lues depuis la requête, et libellés de stats Foundry traduits. */
|
||||||
|
class PdfExportOptionsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_defaultsToTheFullGmBooklet() {
|
||||||
|
PdfExportOptions o = PdfExportOptions.parse(null, null, null, null, null);
|
||||||
|
assertEquals(PdfExportOptions.defaults(), o);
|
||||||
|
assertTrue(o.gmContent());
|
||||||
|
assertEquals(PageFormat.A4, o.format());
|
||||||
|
assertEquals(EnumSet.allOf(Section.class), o.sections());
|
||||||
|
assertEquals(LoreScope.ALL, o.loreScope());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_readsEveryOption_andIgnoresUnknownValues() {
|
||||||
|
PdfExportOptions o = PdfExportOptions.parse("player", "a5", true, "narrative, lore,bogus", "linked");
|
||||||
|
assertFalse(o.gmContent());
|
||||||
|
assertEquals(PageFormat.A5, o.format());
|
||||||
|
assertTrue(o.printFriendly());
|
||||||
|
assertEquals(EnumSet.of(Section.NARRATIVE, Section.LORE), o.sections());
|
||||||
|
assertEquals(LoreScope.LINKED, o.loreScope());
|
||||||
|
|
||||||
|
PdfExportOptions bad = PdfExportOptions.parse("gm", "tabloid", false, "", "nope");
|
||||||
|
assertEquals(PageFormat.A4, bad.format());
|
||||||
|
assertEquals(LoreScope.ALL, bad.loreScope());
|
||||||
|
assertEquals(EnumSet.allOf(Section.class), bad.sections(), "aucune partie reconnue = toutes");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formats_haveConsistentContentWidths() {
|
||||||
|
assertEquals(17.6, PageFormat.A4.contentWidthCm(), 0.01);
|
||||||
|
assertEquals(12.2, PageFormat.A5.contentWidthCm(), 0.01);
|
||||||
|
assertTrue(PageFormat.LETTER.contentWidthCm() > PageFormat.A4.contentWidthCm());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void foundryStatKeys_areTranslated() {
|
||||||
|
assertEquals("PV", PdfExportService.humanizeStatKey("attributes.hp.value"));
|
||||||
|
assertEquals("PV max", PdfExportService.humanizeStatKey("attributes.hp.max"));
|
||||||
|
assertEquals("CA", PdfExportService.humanizeStatKey("attributes.ac.value"));
|
||||||
|
assertEquals("FOR", PdfExportService.humanizeStatKey("abilities.str.value"));
|
||||||
|
assertEquals("FP", PdfExportService.humanizeStatKey("system.details.cr"));
|
||||||
|
assertEquals("Déplacement marche", PdfExportService.humanizeStatKey("attributes.movement.walk"));
|
||||||
|
assertEquals("Type de créature", PdfExportService.humanizeStatKey("details.creatureType"));
|
||||||
|
assertEquals("Spell slots", PdfExportService.humanizeStatKey("spellSlots"), "terme inconnu : humanisé");
|
||||||
|
}
|
||||||
|
}
|
||||||
+24
-1
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.infrastructure.transfer.pdf;
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||||
@@ -9,6 +10,7 @@ import com.loremind.domain.campaigncontext.structure.Room;
|
|||||||
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
import com.loremind.domain.files.ports.FileStorage;
|
import com.loremind.domain.files.ports.FileStorage;
|
||||||
import com.loremind.domain.images.ports.ImageStorage;
|
import com.loremind.domain.images.ports.ImageStorage;
|
||||||
import com.loremind.domain.shared.template.TemplateField;
|
import com.loremind.domain.shared.template.TemplateField;
|
||||||
@@ -83,7 +85,20 @@ class PdfExportPreviewTest {
|
|||||||
.id(1L).name("Les Cendres de la Tour de Jais")
|
.id(1L).name("Les Cendres de la Tour de Jais")
|
||||||
.description("Une campagne d'enquête et d'exploration pour 4 à 5 joueurs, du niveau 3 au niveau 8.\n"
|
.description("Une campagne d'enquête et d'exploration pour 4 à 5 joueurs, du niveau 3 au niveau 8.\n"
|
||||||
+ "Les héros devront démêler les fils d'un pacte ancien avant que la Tour ne s'éveille tout à fait.")
|
+ "Les héros devront démêler les fils d'un pacte ancien avant que la Tour ne s'éveille tout à fait.")
|
||||||
.gameSystemId("10").loreId("20").arcsCount(2).build()));
|
.gameSystemId("10").loreId("20").arcsCount(2)
|
||||||
|
.publication(new CampaignPublication("Une enquête dans les terres du Nord", "Camille Martin",
|
||||||
|
"Chroniques Oubliées Fantasy", "3 à 8", "4 à 5", "6 à 8 séances",
|
||||||
|
"Le vent du nord charrie des cendres : la Tour de Jais s'est rallumée. Les héros ont "
|
||||||
|
+ "jusqu'à la nuit des Cendres pour comprendre qui ravive ses sceaux.",
|
||||||
|
LOREM + "\n\n" + LONG_NOTES,
|
||||||
|
"- Un colporteur ami des PJ disparaît sur la route de Valfroide.\n"
|
||||||
|
+ "- Le conseil de Valfroide offre 500 po pour une escorte.\n"
|
||||||
|
+ "- Le médaillon d'un PJ se met à chauffer.",
|
||||||
|
"Violence, mort d'un personnage secondaire, possession.",
|
||||||
|
"Écriture : Camille Martin\nIllustrations : générées pour l'aperçu\nTesteurs : la table du jeudi",
|
||||||
|
"Texte placé sous licence CC BY-NC 4.0. Les noms et marques cités appartiennent à leurs détenteurs.",
|
||||||
|
"1.0", "401"))
|
||||||
|
.build()));
|
||||||
|
|
||||||
// --- Structure narrative : 2 arcs -> chapitres -> scenes -------------
|
// --- Structure narrative : 2 arcs -> chapitres -> scenes -------------
|
||||||
when(arcRepo.findByCampaignId(1L)).thenReturn(List.of(
|
when(arcRepo.findByCampaignId(1L)).thenReturn(List.of(
|
||||||
@@ -144,6 +159,7 @@ class PdfExportPreviewTest {
|
|||||||
"si un PJ a repéré Maëlis", LinkType.CLUE)))
|
"si un PJ a repéré Maëlis", LinkType.CLUE)))
|
||||||
.build(),
|
.build(),
|
||||||
SceneJpaEntity.builder().id(301L).chapterId(200L).order(1).name("Le stand du colporteur")
|
SceneJpaEntity.builder().id(301L).chapterId(200L).order(1).name("Le stand du colporteur")
|
||||||
|
.type(SceneType.REVELATION)
|
||||||
.location("Allée marchande, place du Guet.")
|
.location("Allée marchande, place du Guet.")
|
||||||
.atmosphere("Le stand est intact mais abandonné ; la marchandise n'a pas été pillée, ce qui inquiète plus que tout.")
|
.atmosphere("Le stand est intact mais abandonné ; la marchandise n'a pas été pillée, ce qui inquiète plus que tout.")
|
||||||
.gmSecretNotes("Sous le comptoir : un carnet dont trois pages ont été arrachées, imprégnées d'odeur de cendre.")
|
.gmSecretNotes("Sous le comptoir : un carnet dont trois pages ont été arrachées, imprégnées d'odeur de cendre.")
|
||||||
@@ -157,6 +173,7 @@ class PdfExportPreviewTest {
|
|||||||
.enemies("Le sergent : profil du sbire avec +5 PV et une rapière (+1 aux dégâts).")
|
.enemies("Le sergent : profil du sbire avec +5 PV et une rapière (+1 aux dégâts).")
|
||||||
.battlemaps(List.of(new SceneBattlemap("Nuit", "500", null),
|
.battlemaps(List.of(new SceneBattlemap("Nuit", "500", null),
|
||||||
new SceneBattlemap("Jour", "501", null)))
|
new SceneBattlemap("Jour", "501", null)))
|
||||||
|
.branches(List.of(new SceneBranch("Le carnet volé désigne le stand", "301", null, LinkType.CLUE)))
|
||||||
.build()));
|
.build()));
|
||||||
when(sceneRepo.findByChapterId(201L)).thenReturn(List.of(
|
when(sceneRepo.findByChapterId(201L)).thenReturn(List.of(
|
||||||
SceneJpaEntity.builder().id(303L).chapterId(201L).order(0).name("Le seuil scellé")
|
SceneJpaEntity.builder().id(303L).chapterId(201L).order(0).name("Le seuil scellé")
|
||||||
@@ -379,6 +396,12 @@ class PdfExportPreviewTest {
|
|||||||
Files.createDirectories(out.getParent());
|
Files.createDirectories(out.getParent());
|
||||||
Files.write(out, pdf);
|
Files.write(out, pdf);
|
||||||
System.out.println("[preview] PDF écrit : " + out.toAbsolutePath());
|
System.out.println("[preview] PDF écrit : " + out.toAbsolutePath());
|
||||||
|
|
||||||
|
// Variante : édition joueurs, A5, mode impression.
|
||||||
|
byte[] player = service.export("1", PdfExportOptions.parse("player", "A5", true, null, null));
|
||||||
|
Path outPlayer = Path.of("target", "campaign-preview-joueurs-a5.pdf");
|
||||||
|
Files.write(outPlayer, player);
|
||||||
|
System.out.println("[preview] PDF écrit : " + outPlayer.toAbsolutePath());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Image placeholder deterministe : portrait carre ou battlemap avec grille. */
|
/** Image placeholder deterministe : portrait carre ou battlemap avec grille. */
|
||||||
|
|||||||
+188
@@ -0,0 +1,188 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
|
import com.loremind.domain.images.ports.ImageStorage;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.*;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.*;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.LoreScope;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.PageFormat;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.Section;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export PDF « module publiable » : fiche Publication (couverture, crédits, introduction,
|
||||||
|
* propriétés du fichier), corrections du livret (résumé de scène, libellés accentués),
|
||||||
|
* version joueurs sans secrets, choix des parties, lore limité aux pages liées, formats.
|
||||||
|
* Le contenu est vérifié sur le XHTML intermédiaire, le fichier sur le PDF réel.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
@Transactional
|
||||||
|
class PdfExportPublicationTest {
|
||||||
|
|
||||||
|
@Autowired private PdfExportService service;
|
||||||
|
@Autowired private CampaignJpaRepository campaignRepo;
|
||||||
|
@Autowired private ArcJpaRepository arcRepo;
|
||||||
|
@Autowired private ChapterJpaRepository chapterRepo;
|
||||||
|
@Autowired private SceneJpaRepository sceneRepo;
|
||||||
|
@Autowired private LoreJpaRepository loreRepo;
|
||||||
|
@Autowired private LoreNodeJpaRepository loreNodeRepo;
|
||||||
|
@Autowired private PageJpaRepository pageRepo;
|
||||||
|
|
||||||
|
@MockitoBean private ImageStorage imageStorage;
|
||||||
|
|
||||||
|
private String campaignId;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void seed() {
|
||||||
|
LoreJpaEntity lore = loreRepo.save(LoreJpaEntity.builder().name("Univers").build());
|
||||||
|
LoreNodeJpaEntity node = loreNodeRepo.save(LoreNodeJpaEntity.builder()
|
||||||
|
.name("Lieux").loreId(lore.getId()).order(0).build());
|
||||||
|
PageJpaEntity linked = pageRepo.save(PageJpaEntity.builder()
|
||||||
|
.loreId(lore.getId()).nodeId(node.getId()).title("Valfroide").order(0).build());
|
||||||
|
pageRepo.save(PageJpaEntity.builder()
|
||||||
|
.loreId(lore.getId()).nodeId(node.getId()).title("Secret d'une autre campagne").order(1).build());
|
||||||
|
|
||||||
|
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder()
|
||||||
|
.name("Les Cendres de Jais").description("Description interne.").arcsCount(1)
|
||||||
|
.loreId(String.valueOf(lore.getId()))
|
||||||
|
.publication(new CampaignPublication("Une enquête dans le Nord", "Camille Martin",
|
||||||
|
"Chroniques Oubliées", "1 à 3", "3 à 5", "2 séances de 4 h",
|
||||||
|
"Une tour se rallume.", "Le maître de la tour a survécu.",
|
||||||
|
"- Un colporteur disparaît\n- Une lettre anonyme", "Mort d'un enfant évoquée.",
|
||||||
|
"Relecture : Alex", "Texte sous licence CC BY-NC 4.0.", "1.2", null))
|
||||||
|
.build());
|
||||||
|
campaignId = String.valueOf(camp.getId());
|
||||||
|
|
||||||
|
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder().name("Acte I").campaignId(camp.getId()).order(0)
|
||||||
|
.themes("Trahison").rewards("Or").resolution("Victoire").gmNotes("Note d'arc MJ").build());
|
||||||
|
ChapterJpaEntity ch1 = chapterRepo.save(ChapterJpaEntity.builder()
|
||||||
|
.name("La foire").arcId(arc.getId()).order(0).playerObjectives("Trouver le colporteur").build());
|
||||||
|
chapterRepo.save(ChapterJpaEntity.builder().name("La crypte").arcId(arc.getId()).order(1).build());
|
||||||
|
sceneRepo.save(SceneJpaEntity.builder()
|
||||||
|
.name("L'auberge").chapterId(ch1.getId()).order(0)
|
||||||
|
.description("Les PJ rencontrent Maëlis.")
|
||||||
|
.playerNarration("La porte s'ouvre sur une vague de chaleur.")
|
||||||
|
.gmSecretNotes("Maëlis ment.").choicesConsequences("Payer une tournée")
|
||||||
|
.combatDifficulty("Facile")
|
||||||
|
.relatedPageIds(new ArrayList<>(List.of(String.valueOf(linked.getId()))))
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void gmEdition_rendersPublicationIntroCreditsAndFixedLabels() {
|
||||||
|
String x = service.xhtml(campaignId, PdfExportOptions.defaults());
|
||||||
|
|
||||||
|
// Couverture : système en surtitre, sous-titre, ligne technique, auteur, version — pas de date.
|
||||||
|
assertTrue(x.contains("cover-kicker\">Chroniques Oubliées"));
|
||||||
|
assertTrue(x.contains("cover-subtitle\">Une enquête dans le Nord"));
|
||||||
|
assertTrue(x.contains("Niveaux : 1 à 3"));
|
||||||
|
assertTrue(x.contains("cover-author\">Camille Martin"));
|
||||||
|
assertTrue(x.contains("Version 1.2"));
|
||||||
|
assertFalse(x.contains("Exporté le"));
|
||||||
|
assertFalse(x.contains("Livret de campagne"));
|
||||||
|
// Crédits + mentions légales.
|
||||||
|
assertTrue(x.contains("class=\"credits-page\""));
|
||||||
|
assertTrue(x.contains("Relecture : Alex"));
|
||||||
|
assertTrue(x.contains("CC BY-NC 4.0"));
|
||||||
|
// Introduction MJ.
|
||||||
|
assertTrue(x.contains("L'aventure en bref"));
|
||||||
|
assertTrue(x.contains("Une tour se rallume."));
|
||||||
|
assertTrue(x.contains("Contexte pour le MJ"));
|
||||||
|
assertTrue(x.contains("<li>Un colporteur disparaît</li>"));
|
||||||
|
assertTrue(x.contains("Avertissements de contenu"));
|
||||||
|
assertTrue(x.contains("Acte I : La foire, La crypte"), "structure de l'aventure");
|
||||||
|
// Corrections du livret : résumé de scène rendu, libellés accentués.
|
||||||
|
assertTrue(x.contains("Résumé"));
|
||||||
|
assertTrue(x.contains("Les PJ rencontrent Maëlis."));
|
||||||
|
assertTrue(x.contains(">Thèmes<"));
|
||||||
|
assertTrue(x.contains(">Récompenses<"));
|
||||||
|
assertTrue(x.contains(">Résolution<"));
|
||||||
|
assertTrue(x.contains("Choix et conséquences"));
|
||||||
|
// Propriétés du fichier.
|
||||||
|
assertTrue(x.contains("<title>Les Cendres de Jais</title>"));
|
||||||
|
assertTrue(x.contains("<meta name=\"author\" content=\"Camille Martin\"/>"));
|
||||||
|
assertTrue(x.contains("lang=\"fr\""));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void playerEdition_dropsEverySecret() {
|
||||||
|
PdfExportOptions player = new PdfExportOptions(false, PageFormat.A4, false,
|
||||||
|
EnumSet.allOf(Section.class), LoreScope.ALL);
|
||||||
|
String x = service.xhtml(campaignId, player);
|
||||||
|
|
||||||
|
assertTrue(x.contains("La porte s'ouvre sur une vague de chaleur."), "le texte à lire reste");
|
||||||
|
assertTrue(x.contains("Trouver le colporteur"), "les objectifs joueurs restent");
|
||||||
|
assertTrue(x.contains("Édition joueurs"));
|
||||||
|
for (String secret : List.of("Maëlis ment.", "Payer une tournée", "Facile", "Les PJ rencontrent Maëlis.",
|
||||||
|
"Note d'arc MJ", "Trahison", "Victoire", "Le maître de la tour a survécu.", "Un colporteur disparaît")) {
|
||||||
|
assertFalse(x.contains(secret), "secret présent dans la version joueurs : " + secret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void sectionsAndLinkedLore_limitTheBooklet() {
|
||||||
|
String all = service.xhtml(campaignId, PdfExportOptions.defaults());
|
||||||
|
assertTrue(all.contains("Secret d'une autre campagne"), "lore complet par défaut");
|
||||||
|
|
||||||
|
PdfExportOptions linked = new PdfExportOptions(true, PageFormat.A4, false,
|
||||||
|
EnumSet.of(Section.LORE), LoreScope.LINKED);
|
||||||
|
String x = service.xhtml(campaignId, linked);
|
||||||
|
assertTrue(x.contains("Valfroide"), "page liée à une scène");
|
||||||
|
assertFalse(x.contains("Secret d'une autre campagne"), "page non liée exclue");
|
||||||
|
assertFalse(x.contains("id=\"part-narrative\""), "partie narrative non demandée");
|
||||||
|
assertFalse(x.contains("Structure de l'aventure"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formatAndPrintMode_shapeTheStylesheet() {
|
||||||
|
String a5 = service.xhtml(campaignId, new PdfExportOptions(true, PageFormat.A5, true,
|
||||||
|
EnumSet.allOf(Section.class), LoreScope.ALL));
|
||||||
|
assertTrue(a5.contains("size: A5"));
|
||||||
|
assertTrue(a5.contains("font-size: 9.0pt"));
|
||||||
|
assertTrue(a5.contains(".arc-head { background: none"), "feuille impression ajoutée");
|
||||||
|
|
||||||
|
String a4 = service.xhtml(campaignId, PdfExportOptions.defaults());
|
||||||
|
assertTrue(a4.contains("size: A4"));
|
||||||
|
assertFalse(a4.contains(".arc-head { background: none"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void pdfFile_carriesTitleAndAuthor() throws Exception {
|
||||||
|
// Mode impression inclus : sa feuille de style doit rester du XML valide.
|
||||||
|
byte[] pdf = service.export(campaignId, new PdfExportOptions(true, PageFormat.LETTER, true,
|
||||||
|
EnumSet.allOf(Section.class), LoreScope.ALL));
|
||||||
|
try (PDDocument doc = PDDocument.load(pdf)) {
|
||||||
|
PDDocumentInformation info = doc.getDocumentInformation();
|
||||||
|
assertEquals("Les Cendres de Jais", info.getTitle());
|
||||||
|
assertEquals("Camille Martin", info.getAuthor());
|
||||||
|
assertEquals("Une enquête dans le Nord", info.getSubject());
|
||||||
|
// US Letter : 8,5 pouces de large (612 points).
|
||||||
|
assertEquals(612f, doc.getPage(0).getMediaBox().getWidth(), 1f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void withoutPublication_keepsTheHistoricalBooklet() {
|
||||||
|
CampaignJpaEntity bare = campaignRepo.save(CampaignJpaEntity.builder()
|
||||||
|
.name("Brouillon").description("Ma description.").arcsCount(0).build());
|
||||||
|
String x = service.xhtml(String.valueOf(bare.getId()), PdfExportOptions.defaults());
|
||||||
|
|
||||||
|
assertTrue(x.contains("Livret de campagne"));
|
||||||
|
assertTrue(x.contains("cover-desc\">Ma description."));
|
||||||
|
assertFalse(x.contains("id=\"part-intro\""));
|
||||||
|
assertFalse(x.contains("class=\"credits-page\""));
|
||||||
|
}
|
||||||
|
}
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.*;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.*;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.LoreScope;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.PageFormat;
|
||||||
|
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.Section;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Champs d'écriture dans le livret : histoire cachée et accroches de l'arc, utilité et
|
||||||
|
* tactique des scènes, rôle dans l'histoire des PNJ — secrets réservés à la version MJ,
|
||||||
|
* signe distinctif visible de tous.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
@Transactional
|
||||||
|
class PdfExportStoryFieldsTest {
|
||||||
|
|
||||||
|
@Autowired private PdfExportService service;
|
||||||
|
@Autowired private CampaignJpaRepository campaignRepo;
|
||||||
|
@Autowired private ArcJpaRepository arcRepo;
|
||||||
|
@Autowired private ChapterJpaRepository chapterRepo;
|
||||||
|
@Autowired private SceneJpaRepository sceneRepo;
|
||||||
|
@Autowired private NpcJpaRepository npcRepo;
|
||||||
|
|
||||||
|
private String campaignId;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void seed() {
|
||||||
|
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder().name("Récit").arcsCount(1).build());
|
||||||
|
campaignId = String.valueOf(camp.getId());
|
||||||
|
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder().name("Acte I").campaignId(camp.getId()).order(0)
|
||||||
|
.hiddenTruth("Le régent a empoisonné le roi.").hooks("- Un ami disparaît\n- Une prime est offerte").build());
|
||||||
|
ChapterJpaEntity ch = chapterRepo.save(ChapterJpaEntity.builder().name("Chap").arcId(arc.getId()).order(0).build());
|
||||||
|
chapterRepo.save(ChapterJpaEntity.builder().name("Chap 2").arcId(arc.getId()).order(1).build());
|
||||||
|
sceneRepo.save(SceneJpaEntity.builder().name("L'embuscade").chapterId(ch.getId()).order(0)
|
||||||
|
.type(SceneType.ENCOUNTER).combatDifficulty("Moyenne")
|
||||||
|
.purpose("Montrer que le régent a des hommes partout.")
|
||||||
|
.tactics("Ils fuient dès que leur sergent tombe.").build());
|
||||||
|
npcRepo.save(NpcJpaEntity.builder().campaignId(camp.getId()).name("Ysolde").order(0)
|
||||||
|
.story(new NpcStory("OPPONENT", "Garder le trône.", "Où est caché le prince.", "Tapote sa bague."))
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void gmEdition_showsEveryStoryField() {
|
||||||
|
String x = service.xhtml(campaignId, PdfExportOptions.defaults());
|
||||||
|
for (String s : List.of("Histoire cachée", "Le régent a empoisonné le roi.", ">Accroches<", "Une prime est offerte",
|
||||||
|
">Utilité<", "Montrer que le régent a des hommes partout.",
|
||||||
|
"Tactique et moral", "Ils fuient dès que leur sergent tombe.",
|
||||||
|
">Opposant<", "Garder le trône.", "Où est caché le prince.", "Tapote sa bague.")) {
|
||||||
|
assertTrue(x.contains(s), "absent de la version MJ : " + s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void playerEdition_keepsOnlyTheMannerism() {
|
||||||
|
String x = service.xhtml(campaignId, new PdfExportOptions(false, PageFormat.A4, false,
|
||||||
|
EnumSet.allOf(Section.class), LoreScope.ALL));
|
||||||
|
assertTrue(x.contains("Tapote sa bague."), "le signe distinctif se voit");
|
||||||
|
for (String s : List.of("Le régent a empoisonné le roi.", "Une prime est offerte",
|
||||||
|
"Montrer que le régent a des hommes partout.", "Ils fuient dès que leur sergent tombe.",
|
||||||
|
">Opposant<", "Garder le trône.", "Où est caché le prince.")) {
|
||||||
|
assertFalse(x.contains(s), "secret présent dans la version joueurs : " + s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+34
@@ -92,4 +92,38 @@ class CampaignControllerTest {
|
|||||||
mockMvc.perform(delete("/api/campaigns/{id}", saved.getId()))
|
mockMvc.perform(delete("/api/campaigns/{id}", saved.getId()))
|
||||||
.andExpect(status().isNoContent());
|
.andExpect(status().isNoContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void publication_roundTripsThroughTheApi() throws Exception {
|
||||||
|
Campaign saved = campaignRepository.save(Campaign.builder().name("Module").description("").build());
|
||||||
|
|
||||||
|
mockMvc.perform(get("/api/campaigns/{id}/publication", saved.getId()))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.subtitle").doesNotExist());
|
||||||
|
|
||||||
|
mockMvc.perform(put("/api/campaigns/{id}/publication", saved.getId())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("{\"subtitle\":\" Une enquête \",\"players\":\"3 à 5\"}"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.subtitle").value("Une enquête"));
|
||||||
|
|
||||||
|
mockMvc.perform(get("/api/campaigns/{id}/publication", saved.getId()))
|
||||||
|
.andExpect(jsonPath("$.subtitle").value("Une enquête"))
|
||||||
|
.andExpect(jsonPath("$.players").value("3 à 5"))
|
||||||
|
// Aucun champ calculé (hasContent, hasCredits…) ne fuit dans le JSON.
|
||||||
|
.andExpect(jsonPath("$.empty").doesNotExist())
|
||||||
|
.andExpect(jsonPath("$.content").doesNotExist());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void pdfExport_acceptsOptions_andNamesThePlayerEdition() throws Exception {
|
||||||
|
Campaign saved = campaignRepository.save(Campaign.builder().name("Module").description("").build());
|
||||||
|
|
||||||
|
mockMvc.perform(get("/api/campaigns/{id}/pdf-export", saved.getId())
|
||||||
|
.param("edition", "player").param("format", "A5").param("print", "true")
|
||||||
|
.param("sections", "NARRATIVE,LORE").param("lore", "LINKED"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header()
|
||||||
|
.string("Content-Disposition", "attachment; filename=\"Module_joueurs.pdf\""));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,19 +133,30 @@ test.describe('Shell mobile (375 px)', () => {
|
|||||||
await page.getByRole('button', { name: "Ouvrir l'arborescence" }).tap();
|
await page.getByRole('button', { name: "Ouvrir l'arborescence" }).tap();
|
||||||
await expect(tree).toBeVisible();
|
await expect(tree).toBeVisible();
|
||||||
|
|
||||||
// Déplie « Scènes » puis l'arc / le chapitre jusqu'à la scène, au doigt.
|
// Navigation par niveaux : toucher une ligne qui a des enfants « entre » dedans
|
||||||
for (const label of [/Scènes/, new RegExp(arc.name), new RegExp(chapter.name)]) {
|
// (sans quitter le volet), jusqu'à la scène. Mode plat ou arc/chapitre selon le seed.
|
||||||
const row = tree.locator('.tree-row', { has: page.locator('.tree-btn', { hasText: label }) }).first();
|
const sceneRow = tree.locator('.drill-row', { hasText: scene.name });
|
||||||
if (await tree.getByRole('button', { name: scene.name }).isVisible()) break;
|
for (const label of ['Scènes', arc.name, chapter.name]) {
|
||||||
const chevron = row.locator('.chevron-btn');
|
if (await sceneRow.isVisible()) break;
|
||||||
if (await chevron.count()) await chevron.tap();
|
const row = tree.locator('.drill-row', { hasText: label }).first();
|
||||||
|
if (await row.count()) {
|
||||||
|
await row.tap();
|
||||||
|
await expect(tree.locator('.drill-back')).toBeVisible();
|
||||||
|
await expect(tree).toBeVisible();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
await tree.getByRole('button', { name: scene.name }).tap();
|
await sceneRow.tap();
|
||||||
|
|
||||||
await expect(page).toHaveURL(new RegExp(`/scenes/${scene.id}$`));
|
await expect(page).toHaveURL(new RegExp(`/scenes/${scene.id}$`));
|
||||||
await expect(page.getByRole('heading', { level: 1, name: scene.name })).toBeVisible();
|
await expect(page.getByRole('heading', { level: 1, name: scene.name })).toBeVisible();
|
||||||
await expect(tree).toBeHidden();
|
await expect(tree).toBeHidden();
|
||||||
await expectNoHorizontalScroll(page);
|
await expectNoHorizontalScroll(page);
|
||||||
|
|
||||||
|
// En rouvrant le volet, on retrouve le niveau de la scène, surlignée ; « retour » remonte.
|
||||||
|
await page.getByRole('button', { name: "Ouvrir l'arborescence" }).tap();
|
||||||
|
await expect(tree.locator('.drill-row.active', { hasText: scene.name })).toBeVisible();
|
||||||
|
await tree.locator('.drill-back').tap();
|
||||||
|
await expect(tree.locator('.drill-row.active', { hasText: scene.name })).toHaveCount(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('écran de séance : journal et horloges lisibles sans scroll horizontal', async ({ page, request }) => {
|
test('écran de séance : journal et horloges lisibles sans scroll horizontal', async ({ page, request }) => {
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "1.0.3",
|
"version": "1.4.0-beta",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "1.0.3",
|
"version": "1.4.0-beta",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular/animations": "^21.2.17",
|
"@angular/animations": "^21.2.17",
|
||||||
"@angular/cdk": "^21.2.14",
|
"@angular/cdk": "^21.2.14",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "1.0.3",
|
"version": "1.4.0-beta",
|
||||||
"description": "LoreMind Frontend - Angular",
|
"description": "LoreMind Frontend - Angular",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"ng": "ng",
|
"ng": "ng",
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ export const routes: Routes = [
|
|||||||
{ path: 'campaigns', loadComponent: () => import('./campaigns/campaigns.component').then(m => m.CampaignsComponent) },
|
{ path: 'campaigns', loadComponent: () => import('./campaigns/campaigns.component').then(m => m.CampaignsComponent) },
|
||||||
{ path: 'campaigns/:id', loadComponent: () => import('./campaigns/campaign/campaign-detail/campaign-detail.component').then(m => m.CampaignDetailComponent) },
|
{ path: 'campaigns/:id', loadComponent: () => import('./campaigns/campaign/campaign-detail/campaign-detail.component').then(m => m.CampaignDetailComponent) },
|
||||||
{ path: 'campaigns/:campaignId/graph', loadComponent: () => import('./campaigns/campaign-graph/campaign-graph.component').then(m => m.CampaignGraphComponent) },
|
{ path: 'campaigns/:campaignId/graph', loadComponent: () => import('./campaigns/campaign-graph/campaign-graph.component').then(m => m.CampaignGraphComponent) },
|
||||||
|
{ path: 'campaigns/:campaignId/publication', loadComponent: () => import('./campaigns/campaign/campaign-publication/campaign-publication.component').then(m => m.CampaignPublicationComponent) },
|
||||||
{ path: 'campaigns/:campaignId/import', loadComponent: () => import('./campaigns/campaign/campaign-import/campaign-import.component').then(m => m.CampaignImportComponent) },
|
{ path: 'campaigns/:campaignId/import', loadComponent: () => import('./campaigns/campaign/campaign-import/campaign-import.component').then(m => m.CampaignImportComponent) },
|
||||||
{ path: 'campaigns/:campaignId/playthroughs/:playthroughId', loadComponent: () => import('./campaigns/playthrough/playthrough-detail/playthrough-detail.component').then(m => m.PlaythroughDetailComponent) },
|
{ path: 'campaigns/:campaignId/playthroughs/:playthroughId', loadComponent: () => import('./campaigns/playthrough/playthrough-detail/playthrough-detail.component').then(m => m.PlaythroughDetailComponent) },
|
||||||
{ path: 'campaigns/:campaignId/playthroughs/:playthroughId/flags', loadComponent: () => import('./campaigns/playthrough/playthrough-flags-page/playthrough-flags-page.component').then(m => m.PlaythroughFlagsPageComponent) },
|
{ path: 'campaigns/:campaignId/playthroughs/:playthroughId/flags', loadComponent: () => import('./campaigns/playthrough/playthrough-flags-page/playthrough-flags-page.component').then(m => m.PlaythroughFlagsPageComponent) },
|
||||||
@@ -45,6 +46,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/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/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/arcs/create', loadComponent: () => import('./campaigns/arc/arc-create/arc-create.component').then(m => m.ArcCreateComponent) },
|
||||||
|
{ path: 'campaigns/:campaignId/guided', loadComponent: () => import('./campaigns/guided/guided-chooser/guided-chooser.component').then(m => m.GuidedChooserComponent) },
|
||||||
{ path: 'campaigns/:campaignId/guided/:method', loadComponent: () => import('./campaigns/guided/guided-wizard/guided-wizard.component').then(m => m.GuidedWizardComponent) },
|
{ 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', 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/edit', loadComponent: () => import('./campaigns/arc/arc-edit/arc-edit.component').then(m => m.ArcEditComponent) },
|
||||||
|
|||||||
@@ -95,6 +95,35 @@
|
|||||||
</app-expandable-section>
|
</app-expandable-section>
|
||||||
|
|
||||||
<!-- Thèmes et enjeux -->
|
<!-- Thèmes et enjeux -->
|
||||||
|
<!-- Histoire cachée et accroches : la vérité que les joueurs découvriront, et pourquoi ils s'en mêlent. -->
|
||||||
|
<app-expandable-section [title]="'arcEdit.truthHooksSectionTitle' | translate" icon="🗝️" [initiallyOpen]="focusSection === 'hooks'" [filled]="truthHooksFilled">
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="arc-edit-hidden-truth">{{ 'arcEdit.hiddenTruthLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="arc.hiddenTruth"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
id="arc-edit-hidden-truth"
|
||||||
|
formControlName="hiddenTruth"
|
||||||
|
[placeholder]="'arcEdit.hiddenTruthPlaceholder' | translate"
|
||||||
|
rows="4">
|
||||||
|
</textarea>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="arc-edit-hooks">{{ 'arcEdit.hooksLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="arc.hooks"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
id="arc-edit-hooks"
|
||||||
|
formControlName="hooks"
|
||||||
|
[placeholder]="'arcEdit.hooksPlaceholder' | translate"
|
||||||
|
rows="4">
|
||||||
|
</textarea>
|
||||||
|
<small class="field-hint">{{ 'arcEdit.hooksHint' | translate }}</small>
|
||||||
|
</div>
|
||||||
|
</app-expandable-section>
|
||||||
|
|
||||||
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [initiallyOpen]="focusSection === 'stakes'" [filled]="themesStakesFilled">
|
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [initiallyOpen]="focusSection === 'stakes'" [filled]="themesStakesFilled">
|
||||||
<div class="field-row">
|
<div class="field-row">
|
||||||
<div class="field">
|
<div class="field">
|
||||||
|
|||||||
@@ -97,6 +97,10 @@ export class ArcEditComponent implements OnInit {
|
|||||||
return !!(v.themes || v.stakes);
|
return !!(v.themes || v.stakes);
|
||||||
}
|
}
|
||||||
get gmNotesFilled(): boolean { return !!this.form.value.gmNotes; }
|
get gmNotesFilled(): boolean { return !!this.form.value.gmNotes; }
|
||||||
|
get truthHooksFilled(): boolean {
|
||||||
|
const v = this.form.value;
|
||||||
|
return !!(v.hiddenTruth || v.hooks);
|
||||||
|
}
|
||||||
get rewardsResolutionFilled(): boolean {
|
get rewardsResolutionFilled(): boolean {
|
||||||
const v = this.form.value;
|
const v = this.form.value;
|
||||||
return !!(v.rewards || v.resolution);
|
return !!(v.rewards || v.resolution);
|
||||||
@@ -126,7 +130,9 @@ export class ArcEditComponent implements OnInit {
|
|||||||
stakes: [''],
|
stakes: [''],
|
||||||
gmNotes: [''],
|
gmNotes: [''],
|
||||||
rewards: [''],
|
rewards: [''],
|
||||||
resolution: ['']
|
resolution: [''],
|
||||||
|
hiddenTruth: [''],
|
||||||
|
hooks: ['']
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +185,9 @@ export class ArcEditComponent implements OnInit {
|
|||||||
stakes: arc.stakes ?? '',
|
stakes: arc.stakes ?? '',
|
||||||
gmNotes: arc.gmNotes ?? '',
|
gmNotes: arc.gmNotes ?? '',
|
||||||
rewards: arc.rewards ?? '',
|
rewards: arc.rewards ?? '',
|
||||||
resolution: arc.resolution ?? ''
|
resolution: arc.resolution ?? '',
|
||||||
|
hiddenTruth: arc.hiddenTruth ?? '',
|
||||||
|
hooks: arc.hooks ?? ''
|
||||||
});
|
});
|
||||||
|
|
||||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
|
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
|
||||||
@@ -199,6 +207,8 @@ export class ArcEditComponent implements OnInit {
|
|||||||
gmNotes: this.form.value.gmNotes,
|
gmNotes: this.form.value.gmNotes,
|
||||||
rewards: this.form.value.rewards,
|
rewards: this.form.value.rewards,
|
||||||
resolution: this.form.value.resolution,
|
resolution: this.form.value.resolution,
|
||||||
|
hiddenTruth: this.form.value.hiddenTruth,
|
||||||
|
hooks: this.form.value.hooks,
|
||||||
relatedPageIds: this.relatedPageIds,
|
relatedPageIds: this.relatedPageIds,
|
||||||
illustrationImageIds: this.illustrationImageIds,
|
illustrationImageIds: this.illustrationImageIds,
|
||||||
icon: this.selectedIcon
|
icon: this.selectedIcon
|
||||||
|
|||||||
@@ -84,6 +84,18 @@
|
|||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
@if (arc.hooks?.trim()) {
|
||||||
|
<section class="view-section">
|
||||||
|
<h2 class="view-section-title"><span class="view-section-icon">🪝</span> {{ 'arcView.hooksTitle' | translate }}</h2>
|
||||||
|
<p class="view-section-body">{{ arc.hooks }}</p>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
@if (arc.hiddenTruth?.trim()) {
|
||||||
|
<section class="view-section view-section--private">
|
||||||
|
<h2 class="view-section-title"><span class="view-section-icon">🗝️</span> {{ 'arcView.hiddenTruthTitle' | translate }}</h2>
|
||||||
|
<p class="view-section-body">{{ arc.hiddenTruth }}</p>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
<section class="view-section">
|
<section class="view-section">
|
||||||
<h2 class="view-section-title"><span class="view-section-icon">🎁</span> {{ 'arcView.rewardsTitle' | translate }}</h2>
|
<h2 class="view-section-title"><span class="view-section-icon">🎁</span> {{ 'arcView.rewardsTitle' | translate }}</h2>
|
||||||
@if (arc.rewards?.trim()) {
|
@if (arc.rewards?.trim()) {
|
||||||
|
|||||||
@@ -217,7 +217,7 @@
|
|||||||
{{ 'campaignDetail.newArc' | translate }}
|
{{ 'campaignDetail.newArc' | translate }}
|
||||||
</button>
|
</button>
|
||||||
<!-- Mentor d'écriture (M3) : écrire une aventure question par question. -->
|
<!-- Mentor d'écriture (M3) : écrire une aventure question par question. -->
|
||||||
<a class="btn-add btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided', 'five-room']">
|
<a class="btn-add btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided']">
|
||||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||||
{{ 'guided.entry' | translate }}
|
{{ 'guided.entry' | translate }}
|
||||||
</a>
|
</a>
|
||||||
@@ -250,7 +250,7 @@
|
|||||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||||
{{ 'campaignDetail.quickSceneFirst' | translate }}
|
{{ 'campaignDetail.quickSceneFirst' | translate }}
|
||||||
</button>
|
</button>
|
||||||
<a class="btn-add-first btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided', 'five-room']">
|
<a class="btn-add-first btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided']">
|
||||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||||
{{ 'guided.entryFirst' | translate }}
|
{{ 'guided.entryFirst' | translate }}
|
||||||
</a>
|
</a>
|
||||||
@@ -322,6 +322,15 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
<!-- Options du livret PDF (version MJ/joueurs, format, parties, lore) + accès à la fiche Publication. -->
|
||||||
|
<app-pdf-export-dialog
|
||||||
|
[open]="pdfDialogOpen"
|
||||||
|
[exporting]="exportingPdf"
|
||||||
|
[hasPublication]="hasPublication"
|
||||||
|
(cancelled)="pdfDialogOpen = false"
|
||||||
|
(confirmed)="onPdfExportConfirmed($event)"
|
||||||
|
(editPublication)="openPublication()"></app-pdf-export-dialog>
|
||||||
|
|
||||||
<!-- Choix du périmètre de l'export Foundry (tout / cartes+ennemis / journaux / tables). -->
|
<!-- Choix du périmètre de l'export Foundry (tout / cartes+ennemis / journaux / tables). -->
|
||||||
<app-foundry-export-dialog
|
<app-foundry-export-dialog
|
||||||
[open]="foundryDialogOpen"
|
[open]="foundryDialogOpen"
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
|||||||
import { Router, RouterLink } from '@angular/router';
|
import { Router, RouterLink } from '@angular/router';
|
||||||
import { forkJoin, of, Observable } from 'rxjs';
|
import { forkJoin, of, Observable } from 'rxjs';
|
||||||
import { catchError, switchMap, filter, map } from 'rxjs/operators';
|
import { catchError, switchMap, filter, map } from 'rxjs/operators';
|
||||||
import { CampaignService, FoundryExportOptions } from '../../../services/campaign.service';
|
import { CampaignService, FoundryExportOptions, PdfExportOptions } from '../../../services/campaign.service';
|
||||||
import { LoreService } from '../../../services/lore.service';
|
import { LoreService } from '../../../services/lore.service';
|
||||||
import { GameSystemService } from '../../../services/game-system.service';
|
import { GameSystemService } from '../../../services/game-system.service';
|
||||||
import { GameSystem } from '../../../services/game-system.model';
|
import { GameSystem } from '../../../services/game-system.model';
|
||||||
@@ -35,10 +35,12 @@ import { ReadinessPanelComponent } from '../../../shared/readiness-panel/readine
|
|||||||
import { WritingReviewPanelComponent } from '../../../shared/writing-review/writing-review-panel.component';
|
import { WritingReviewPanelComponent } from '../../../shared/writing-review/writing-review-panel.component';
|
||||||
import { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play-block.component';
|
import { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play-block.component';
|
||||||
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
|
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
|
||||||
|
import { PdfExportDialogComponent } from '../pdf-export-dialog/pdf-export-dialog.component';
|
||||||
|
import { downloadBlob, safeFileName } from '../../../shared/download.util';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-campaign-detail',
|
selector: 'app-campaign-detail',
|
||||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, WritingReviewPanelComponent, CampaignPlayBlockComponent, FoundryExportDialogComponent],
|
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, WritingReviewPanelComponent, CampaignPlayBlockComponent, FoundryExportDialogComponent, PdfExportDialogComponent],
|
||||||
templateUrl: './campaign-detail.component.html',
|
templateUrl: './campaign-detail.component.html',
|
||||||
styleUrls: ['./campaign-detail.component.scss']
|
styleUrls: ['./campaign-detail.component.scss']
|
||||||
})
|
})
|
||||||
@@ -67,6 +69,10 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
foundryDialogOpen = false;
|
foundryDialogOpen = false;
|
||||||
/** Export PDF en cours (anti double-clic). */
|
/** Export PDF en cours (anti double-clic). */
|
||||||
exportingPdf = false;
|
exportingPdf = false;
|
||||||
|
/** Modale des options du livret PDF. */
|
||||||
|
pdfDialogOpen = false;
|
||||||
|
/** Fiche Publication remplie (sinon la modale propose de la compléter). */
|
||||||
|
hasPublication = true;
|
||||||
|
|
||||||
campaign: Campaign | null = null;
|
campaign: Campaign | null = null;
|
||||||
arcs: Arc[] = [];
|
arcs: Arc[] = [];
|
||||||
@@ -430,22 +436,27 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Génère et télécharge le livret PDF de la campagne. */
|
/** Ouvre la modale d'options du livret PDF (en vérifiant si la fiche Publication est remplie). */
|
||||||
exportPdf(): void {
|
exportPdf(): void {
|
||||||
|
if (!this.campaign?.id || this.exportingPdf) return;
|
||||||
|
this.pdfDialogOpen = true;
|
||||||
|
this.campaignService.getPublication(this.campaign.id).subscribe({
|
||||||
|
next: (p) => this.hasPublication = Object.values(p ?? {}).some(v => typeof v === 'string' && v.trim().length > 0),
|
||||||
|
error: () => this.hasPublication = true // inconnu : pas d'incitation à tort
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Génère et télécharge le livret PDF selon les options choisies. */
|
||||||
|
onPdfExportConfirmed(opts: PdfExportOptions): void {
|
||||||
if (!this.campaign?.id || this.exportingPdf) return;
|
if (!this.campaign?.id || this.exportingPdf) return;
|
||||||
this.exportingPdf = true;
|
this.exportingPdf = true;
|
||||||
const name = this.campaign.name;
|
const name = this.campaign.name;
|
||||||
this.campaignService.exportPdf(this.campaign.id).subscribe({
|
this.campaignService.exportPdf(this.campaign.id, opts).subscribe({
|
||||||
next: (blob) => {
|
next: (blob) => {
|
||||||
const url = URL.createObjectURL(blob);
|
const suffix = opts.edition === 'player' ? '_joueurs' : '';
|
||||||
const a = document.createElement('a');
|
downloadBlob(blob, `${safeFileName(name, 'campagne')}${suffix}.pdf`);
|
||||||
a.href = url;
|
|
||||||
a.download = `${(name || 'campagne').replace(/[^a-zA-Z0-9-_]+/g, '_')}.pdf`;
|
|
||||||
document.body.appendChild(a);
|
|
||||||
a.click();
|
|
||||||
document.body.removeChild(a);
|
|
||||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
||||||
this.exportingPdf = false;
|
this.exportingPdf = false;
|
||||||
|
this.pdfDialogOpen = false;
|
||||||
},
|
},
|
||||||
error: (err) => {
|
error: (err) => {
|
||||||
console.error('Échec de l\'export PDF', err);
|
console.error('Échec de l\'export PDF', err);
|
||||||
@@ -454,6 +465,13 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Depuis la modale PDF : compléter la fiche Publication (couverture, crédits…). */
|
||||||
|
openPublication(): void {
|
||||||
|
if (!this.campaign?.id) return;
|
||||||
|
this.pdfDialogOpen = false;
|
||||||
|
this.router.navigate(['/campaigns', this.campaign.id, 'publication']);
|
||||||
|
}
|
||||||
|
|
||||||
/** Réordonne les arcs par glisser-déposer et persiste le nouvel ordre. */
|
/** Réordonne les arcs par glisser-déposer et persiste le nouvel ordre. */
|
||||||
dropArc(event: CdkDragDrop<Arc[]>): void {
|
dropArc(event: CdkDragDrop<Arc[]>): void {
|
||||||
if (event.previousIndex === event.currentIndex) return;
|
if (event.previousIndex === event.currentIndex) return;
|
||||||
|
|||||||
+159
@@ -0,0 +1,159 @@
|
|||||||
|
<div class="edit-page">
|
||||||
|
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1>{{ 'publication.title' | translate }}</h1>
|
||||||
|
<p class="subtitle">{{ campaignName }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="header-actions">
|
||||||
|
<button type="button" class="btn-secondary" (click)="back()">
|
||||||
|
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||||
|
{{ 'common.back' | translate }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-secondary" (click)="pdfDialogOpen = true" [disabled]="loading">
|
||||||
|
<lucide-icon [img]="FileText" [size]="14"></lucide-icon>
|
||||||
|
{{ 'campaignDetail.pdfExport' | translate }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-primary" (click)="save()" [disabled]="loading || saving || !dirty">
|
||||||
|
<lucide-icon [img]="Save" [size]="14"></lucide-icon>
|
||||||
|
{{ (saving ? 'common.saving' : (savedFlash ? 'publication.saved' : 'common.save')) | translate }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (errorMessage) {
|
||||||
|
<div class="pub-error" role="alert">{{ errorMessage }}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (!loading) {
|
||||||
|
<div class="edit-form">
|
||||||
|
<p class="optional-hint">{{ 'publication.intro' | translate }}</p>
|
||||||
|
|
||||||
|
<app-expandable-section [title]="'publication.coverSection' | translate" icon="📕" [initiallyOpen]="true"
|
||||||
|
[filled]="filledAny('subtitle', 'author', 'version', 'coverImageId')">
|
||||||
|
<div class="cover-grid">
|
||||||
|
<div class="cover-fields">
|
||||||
|
<div class="field">
|
||||||
|
<label for="pub-subtitle">{{ 'publication.subtitleLabel' | translate }}</label>
|
||||||
|
<input id="pub-subtitle" type="text" [ngModel]="pub.subtitle" (ngModelChange)="set('subtitle', $event)"
|
||||||
|
[placeholder]="'publication.subtitlePlaceholder' | translate" />
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="pub-author">{{ 'publication.authorLabel' | translate }}</label>
|
||||||
|
<input id="pub-author" type="text" [ngModel]="pub.author" (ngModelChange)="set('author', $event)"
|
||||||
|
[placeholder]="'publication.authorPlaceholder' | translate" />
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="pub-version">{{ 'publication.versionLabel' | translate }}</label>
|
||||||
|
<input id="pub-version" type="text" [ngModel]="pub.version" (ngModelChange)="set('version', $event)"
|
||||||
|
placeholder="1.0" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<p class="cover-label">{{ 'publication.coverLabel' | translate }}</p>
|
||||||
|
<app-single-image-picker
|
||||||
|
[imageId]="pub.coverImageId ?? null"
|
||||||
|
aspectRatio="3 / 4"
|
||||||
|
[hint]="'publication.coverHint' | translate"
|
||||||
|
(imageIdChange)="setCover($event)"></app-single-image-picker>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</app-expandable-section>
|
||||||
|
|
||||||
|
<app-expandable-section [title]="'publication.techSection' | translate" icon="🎲" [initiallyOpen]="true"
|
||||||
|
[filled]="filledAny('system', 'levels', 'players', 'duration')">
|
||||||
|
<p class="field-hint">{{ 'publication.techHint' | translate }}</p>
|
||||||
|
<div class="field-row">
|
||||||
|
<div class="field">
|
||||||
|
<label for="pub-system">{{ 'publication.systemLabel' | translate }}</label>
|
||||||
|
<input id="pub-system" type="text" [ngModel]="pub.system" (ngModelChange)="set('system', $event)"
|
||||||
|
[placeholder]="'publication.systemPlaceholder' | translate" />
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="pub-levels">{{ 'publication.levelsLabel' | translate }}</label>
|
||||||
|
<input id="pub-levels" type="text" [ngModel]="pub.levels" (ngModelChange)="set('levels', $event)"
|
||||||
|
[placeholder]="'publication.levelsPlaceholder' | translate" />
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="pub-players">{{ 'publication.playersLabel' | translate }}</label>
|
||||||
|
<input id="pub-players" type="text" [ngModel]="pub.players" (ngModelChange)="set('players', $event)"
|
||||||
|
[placeholder]="'publication.playersPlaceholder' | translate" />
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="pub-duration">{{ 'publication.durationLabel' | translate }}</label>
|
||||||
|
<input id="pub-duration" type="text" [ngModel]="pub.duration" (ngModelChange)="set('duration', $event)"
|
||||||
|
[placeholder]="'publication.durationPlaceholder' | translate" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</app-expandable-section>
|
||||||
|
|
||||||
|
<app-expandable-section [title]="'publication.presentationSection' | translate" icon="📣"
|
||||||
|
[filled]="filledAny('pitch', 'contentWarnings')">
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="pub-pitch">{{ 'publication.pitchLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="publication.pitch"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea id="pub-pitch" rows="4" [ngModel]="pub.pitch" (ngModelChange)="set('pitch', $event)"
|
||||||
|
[placeholder]="'publication.pitchPlaceholder' | translate"></textarea>
|
||||||
|
<small class="field-hint">{{ 'publication.pitchHint' | translate }}</small>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="pub-warnings">{{ 'publication.warningsLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="publication.contentWarnings"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea id="pub-warnings" rows="2" [ngModel]="pub.contentWarnings" (ngModelChange)="set('contentWarnings', $event)"
|
||||||
|
[placeholder]="'publication.warningsPlaceholder' | translate"></textarea>
|
||||||
|
</div>
|
||||||
|
</app-expandable-section>
|
||||||
|
|
||||||
|
<app-expandable-section [title]="'publication.gmSection' | translate" icon="🔒" variant="private"
|
||||||
|
[filled]="filledAny('gmBackground', 'hooks')">
|
||||||
|
<p class="field-hint">{{ 'publication.gmHint' | translate }}</p>
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="pub-background">{{ 'publication.backgroundLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="publication.gmBackground"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea id="pub-background" rows="7" [ngModel]="pub.gmBackground" (ngModelChange)="set('gmBackground', $event)"
|
||||||
|
[placeholder]="'publication.backgroundPlaceholder' | translate"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="pub-hooks">{{ 'publication.hooksLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="publication.hooks"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea id="pub-hooks" rows="4" [ngModel]="pub.hooks" (ngModelChange)="set('hooks', $event)"
|
||||||
|
[placeholder]="'publication.hooksPlaceholder' | translate"></textarea>
|
||||||
|
<small class="field-hint">{{ 'publication.listHint' | translate }}</small>
|
||||||
|
</div>
|
||||||
|
</app-expandable-section>
|
||||||
|
|
||||||
|
<app-expandable-section [title]="'publication.creditsSection' | translate" icon="©️"
|
||||||
|
[filled]="filledAny('credits', 'legal')">
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="pub-credits">{{ 'publication.creditsLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="publication.credits"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea id="pub-credits" rows="4" [ngModel]="pub.credits" (ngModelChange)="set('credits', $event)"
|
||||||
|
[placeholder]="'publication.creditsPlaceholder' | translate"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="pub-legal">{{ 'publication.legalLabel' | translate }}</label>
|
||||||
|
<textarea id="pub-legal" rows="4" [ngModel]="pub.legal" (ngModelChange)="set('legal', $event)"
|
||||||
|
[placeholder]="'publication.legalPlaceholder' | translate"></textarea>
|
||||||
|
<small class="field-hint">{{ 'publication.legalHint' | translate }}</small>
|
||||||
|
</div>
|
||||||
|
</app-expandable-section>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<app-pdf-export-dialog
|
||||||
|
[open]="pdfDialogOpen"
|
||||||
|
[exporting]="exportingPdf"
|
||||||
|
[showPublicationLink]="false"
|
||||||
|
(cancelled)="pdfDialogOpen = false"
|
||||||
|
(confirmed)="onPdfConfirmed($event)"></app-pdf-export-dialog>
|
||||||
+84
@@ -0,0 +1,84 @@
|
|||||||
|
.edit-page {
|
||||||
|
padding: 2.5rem 2rem;
|
||||||
|
max-width: 720px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 1rem;
|
||||||
|
|
||||||
|
.header-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
|
||||||
|
button {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.edit-form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.optional-hint {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.6rem 0.85rem;
|
||||||
|
background: rgba(108, 99, 255, 0.08);
|
||||||
|
border: 1px solid rgba(108, 99, 255, 0.25);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #a5b4fc;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pub-error {
|
||||||
|
padding: 0.6rem 0.9rem;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: rgba(224, 90, 90, 0.12);
|
||||||
|
border: 1px solid rgba(224, 90, 90, 0.4);
|
||||||
|
color: #fca5a5;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Couverture : champs à gauche, illustration (portrait 3/4) à droite.
|
||||||
|
.cover-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) 180px;
|
||||||
|
gap: 1.25rem;
|
||||||
|
align-items: start;
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Libellé de l'illustration (pas un <label> : le sélecteur d'image n'est pas un champ).
|
||||||
|
.cover-label {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: #d1d5db;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cover-fields {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
app-expandable-section .field + .field { margin-top: 1rem; }
|
||||||
|
|
||||||
|
.field-hint { margin: 0 0 0.75rem; }
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.edit-page { padding: 1rem; }
|
||||||
|
}
|
||||||
+165
@@ -0,0 +1,165 @@
|
|||||||
|
import { Component, OnInit } from '@angular/core';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
|
import { forkJoin, Observable, of } from 'rxjs';
|
||||||
|
import { switchMap } from 'rxjs/operators';
|
||||||
|
import { LucideAngularModule, ArrowLeft, Save, FileText } from 'lucide-angular';
|
||||||
|
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||||
|
import { CampaignPublication, CampaignService, PdfExportOptions } from '../../../services/campaign.service';
|
||||||
|
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||||
|
import { PageTitleService } from '../../../services/page-title.service';
|
||||||
|
import { ExpandableSectionComponent } from '../../../shared/expandable-section/expandable-section.component';
|
||||||
|
import { SingleImagePickerComponent } from '../../../shared/single-image-picker/single-image-picker.component';
|
||||||
|
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||||
|
import { PdfExportDialogComponent } from '../pdf-export-dialog/pdf-export-dialog.component';
|
||||||
|
import { downloadBlob, safeFileName } from '../../../shared/download.util';
|
||||||
|
|
||||||
|
type PublicationField = Exclude<keyof CampaignPublication, 'coverImageId'>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche « Publication » d'une campagne : ce que le PDF affiche quand l'aventure est
|
||||||
|
* vendue ou partagée — couverture (sous-titre, auteur, illustration), page technique,
|
||||||
|
* présentation, introduction pour le MJ, crédits et licence. Tout est facultatif ; une
|
||||||
|
* fiche vide garde le livret de campagne habituel.
|
||||||
|
* Route : /campaigns/:campaignId/publication
|
||||||
|
*/
|
||||||
|
@Component({
|
||||||
|
selector: 'app-campaign-publication',
|
||||||
|
imports: [FormsModule, LucideAngularModule, TranslatePipe, ExpandableSectionComponent,
|
||||||
|
SingleImagePickerComponent, WritingCoachTriggerComponent, PdfExportDialogComponent],
|
||||||
|
templateUrl: './campaign-publication.component.html',
|
||||||
|
styleUrls: ['./campaign-publication.component.scss']
|
||||||
|
})
|
||||||
|
export class CampaignPublicationComponent implements OnInit {
|
||||||
|
readonly ArrowLeft = ArrowLeft;
|
||||||
|
readonly Save = Save;
|
||||||
|
readonly FileText = FileText;
|
||||||
|
|
||||||
|
campaignId = '';
|
||||||
|
campaignName = '';
|
||||||
|
pub: CampaignPublication = {};
|
||||||
|
/** Dernier état enregistré (JSON) : détecte les modifications non sauvegardées. */
|
||||||
|
private savedSnapshot = '{}';
|
||||||
|
|
||||||
|
loading = true;
|
||||||
|
saving = false;
|
||||||
|
savedFlash = false;
|
||||||
|
errorMessage = '';
|
||||||
|
|
||||||
|
pdfDialogOpen = false;
|
||||||
|
exportingPdf = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private route: ActivatedRoute,
|
||||||
|
private router: Router,
|
||||||
|
private campaignService: CampaignService,
|
||||||
|
private campaignSidebar: CampaignSidebarService,
|
||||||
|
private pageTitle: PageTitleService,
|
||||||
|
private translate: TranslateService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.campaignId = this.route.snapshot.paramMap.get('campaignId') ?? '';
|
||||||
|
if (!this.campaignId) return;
|
||||||
|
this.campaignSidebar.show(this.campaignId);
|
||||||
|
forkJoin({
|
||||||
|
campaign: this.campaignService.getCampaignById(this.campaignId),
|
||||||
|
publication: this.campaignService.getPublication(this.campaignId),
|
||||||
|
}).subscribe({
|
||||||
|
next: ({ campaign, publication }) => {
|
||||||
|
this.campaignName = campaign.name;
|
||||||
|
this.pageTitle.set(this.translate.instant('publication.pageTitle', { name: campaign.name }));
|
||||||
|
this.pub = { ...publication };
|
||||||
|
this.savedSnapshot = this.snapshot();
|
||||||
|
this.loading = false;
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.errorMessage = this.translate.instant('publication.loadError');
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
get dirty(): boolean { return this.snapshot() !== this.savedSnapshot; }
|
||||||
|
|
||||||
|
/** Au moins un champ renseigné (le PDF passe alors en présentation « module »). */
|
||||||
|
get filled(): boolean {
|
||||||
|
return Object.values(this.pub).some(v => typeof v === 'string' && v.trim().length > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
filledAny(...fields: (keyof CampaignPublication)[]): boolean {
|
||||||
|
return fields.some(f => !!this.pub[f]?.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
set(field: PublicationField, value: string): void {
|
||||||
|
this.pub = { ...this.pub, [field]: value };
|
||||||
|
}
|
||||||
|
|
||||||
|
setCover(id: string | null): void {
|
||||||
|
this.pub = { ...this.pub, coverImageId: id };
|
||||||
|
}
|
||||||
|
|
||||||
|
back(): void {
|
||||||
|
this.router.navigate(['/campaigns', this.campaignId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
save(): void {
|
||||||
|
this.persist().subscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enregistre si besoin, puis émet la fiche à jour (ou rien en cas d'erreur). */
|
||||||
|
private persist(): Observable<CampaignPublication | null> {
|
||||||
|
if (!this.dirty) return of(this.pub);
|
||||||
|
this.saving = true;
|
||||||
|
this.errorMessage = '';
|
||||||
|
return new Observable(observer => {
|
||||||
|
this.campaignService.updatePublication(this.campaignId, this.pub).subscribe({
|
||||||
|
next: saved => {
|
||||||
|
this.pub = { ...saved };
|
||||||
|
this.savedSnapshot = this.snapshot();
|
||||||
|
this.saving = false;
|
||||||
|
this.savedFlash = true;
|
||||||
|
setTimeout(() => this.savedFlash = false, 1800);
|
||||||
|
observer.next(saved);
|
||||||
|
observer.complete();
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.saving = false;
|
||||||
|
this.errorMessage = this.translate.instant('publication.saveError');
|
||||||
|
observer.next(null);
|
||||||
|
observer.complete();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Export PDF : la fiche est d'abord enregistrée pour que le livret reflète l'écran. */
|
||||||
|
onPdfConfirmed(opts: PdfExportOptions): void {
|
||||||
|
if (this.exportingPdf) return;
|
||||||
|
this.exportingPdf = true;
|
||||||
|
this.persist().pipe(
|
||||||
|
switchMap(saved => saved ? this.campaignService.exportPdf(this.campaignId, opts) : of(null))
|
||||||
|
).subscribe({
|
||||||
|
next: blob => {
|
||||||
|
if (blob) {
|
||||||
|
const suffix = opts.edition === 'player' ? '_joueurs' : '';
|
||||||
|
downloadBlob(blob, `${safeFileName(this.campaignName, 'campagne')}${suffix}.pdf`);
|
||||||
|
this.pdfDialogOpen = false;
|
||||||
|
}
|
||||||
|
this.exportingPdf = false;
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.errorMessage = this.translate.instant('publication.exportError');
|
||||||
|
this.exportingPdf = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private snapshot(): string {
|
||||||
|
const clean: Record<string, string> = {};
|
||||||
|
for (const [k, v] of Object.entries(this.pub)) {
|
||||||
|
if (typeof v === 'string' && v.trim()) clean[k] = v.trim();
|
||||||
|
}
|
||||||
|
return JSON.stringify(clean, Object.keys(clean).sort());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
@if (open) {
|
||||||
|
<div class="confirm-backdrop" (click)="onCancel()">
|
||||||
|
<div class="confirm-modal variant-info"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
[attr.aria-label]="'pdfDialog.title' | translate"
|
||||||
|
(click)="$event.stopPropagation()">
|
||||||
|
<div class="confirm-header">
|
||||||
|
<div class="confirm-icon">
|
||||||
|
<lucide-icon [img]="FileText" [size]="20"></lucide-icon>
|
||||||
|
</div>
|
||||||
|
<h2>{{ 'pdfDialog.title' | translate }}</h2>
|
||||||
|
<button type="button" class="btn-close" (click)="onCancel()" [attr.aria-label]="'common.close' | translate">
|
||||||
|
<lucide-icon [img]="X" [size]="18"></lucide-icon>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="confirm-body">
|
||||||
|
@if (showPublicationLink) {
|
||||||
|
<div class="pdf-publication" [class.empty]="!hasPublication">
|
||||||
|
<lucide-icon [img]="BookOpen" [size]="16"></lucide-icon>
|
||||||
|
<span>{{ (hasPublication ? 'pdfDialog.publicationFilled' : 'pdfDialog.publicationEmpty') | translate }}</span>
|
||||||
|
<button type="button" class="link-btn" (click)="editPublication.emit()">
|
||||||
|
{{ (hasPublication ? 'pdfDialog.publicationEdit' : 'pdfDialog.publicationFill') | translate }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="pdf-group">
|
||||||
|
<span class="pdf-group-label">{{ 'pdfDialog.editionLabel' | translate }}</span>
|
||||||
|
<div class="pdf-choice">
|
||||||
|
<label class="pdf-choice-option" [class.selected]="edition === 'gm'">
|
||||||
|
<input type="radio" name="pdf-edition" value="gm" [checked]="edition === 'gm'" (change)="setEdition('gm')" />
|
||||||
|
<strong>{{ 'pdfDialog.editionGm' | translate }}</strong>
|
||||||
|
<small>{{ 'pdfDialog.editionGmHint' | translate }}</small>
|
||||||
|
</label>
|
||||||
|
<label class="pdf-choice-option" [class.selected]="edition === 'player'">
|
||||||
|
<input type="radio" name="pdf-edition" value="player" [checked]="edition === 'player'" (change)="setEdition('player')" />
|
||||||
|
<strong>{{ 'pdfDialog.editionPlayer' | translate }}</strong>
|
||||||
|
<small>{{ 'pdfDialog.editionPlayerHint' | translate }}</small>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pdf-group">
|
||||||
|
<span class="pdf-group-label">{{ 'pdfDialog.sectionsLabel' | translate }}</span>
|
||||||
|
<div class="pdf-sections">
|
||||||
|
@for (s of allSections; track s) {
|
||||||
|
<label class="pdf-check">
|
||||||
|
<input type="checkbox" [attr.name]="'pdf-section-' + s" [checked]="has(s)" (change)="toggle(s)" />
|
||||||
|
{{ ('pdfDialog.section.' + s) | translate }}
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (has('LORE')) {
|
||||||
|
<div class="pdf-lore">
|
||||||
|
<label class="pdf-check">
|
||||||
|
<input type="radio" name="pdf-lore" value="LINKED" [checked]="lore === 'LINKED'" (change)="lore = 'LINKED'" />
|
||||||
|
{{ 'pdfDialog.loreLinked' | translate }}
|
||||||
|
</label>
|
||||||
|
<label class="pdf-check">
|
||||||
|
<input type="radio" name="pdf-lore" value="ALL" [checked]="lore === 'ALL'" (change)="lore = 'ALL'" />
|
||||||
|
{{ 'pdfDialog.loreAll' | translate }}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pdf-group pdf-inline">
|
||||||
|
<label class="pdf-format">
|
||||||
|
<span class="pdf-group-label">{{ 'pdfDialog.formatLabel' | translate }}</span>
|
||||||
|
<select name="pdf-format" [value]="format" (change)="format = $any($event.target).value">
|
||||||
|
<option value="A4">A4</option>
|
||||||
|
<option value="A5">A5</option>
|
||||||
|
<option value="LETTER">US Letter</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="pdf-check">
|
||||||
|
<input type="checkbox" name="pdf-print" [checked]="print" (change)="print = !print" />
|
||||||
|
<span>
|
||||||
|
{{ 'pdfDialog.print' | translate }}
|
||||||
|
<small>{{ 'pdfDialog.printHint' | translate }}</small>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="confirm-actions">
|
||||||
|
<button type="button" class="btn-secondary" (click)="onCancel()" [disabled]="exporting">
|
||||||
|
{{ 'common.cancel' | translate }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-confirm" (click)="onConfirm()" [disabled]="nothingSelected || exporting">
|
||||||
|
{{ (exporting ? 'campaignDetail.pdfExporting' : 'pdfDialog.confirm') | translate }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
// Même squelette visuel que la modale d'export Foundry (backdrop/modal/header/actions),
|
||||||
|
// avec un corps défilant : la modale reste utilisable sur téléphone.
|
||||||
|
.confirm-backdrop {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.75);
|
||||||
|
backdrop-filter: blur(2px);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 1rem;
|
||||||
|
z-index: 200;
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-modal {
|
||||||
|
background: #111827;
|
||||||
|
border: 1px solid #1f2937;
|
||||||
|
border-radius: 16px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 560px;
|
||||||
|
max-height: calc(100dvh - 2rem);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||||
|
overflow: hidden;
|
||||||
|
|
||||||
|
&.variant-info { border-top: 4px solid #6c63ff; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 1.1rem 1.5rem;
|
||||||
|
border-bottom: 1px solid #1f2937;
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
flex: 1;
|
||||||
|
color: white;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-icon {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 36px;
|
||||||
|
height: 36px;
|
||||||
|
border-radius: 50%;
|
||||||
|
flex-shrink: 0;
|
||||||
|
background: rgba(108, 99, 255, 0.15);
|
||||||
|
color: #6c63ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-close {
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
color: #6b7280;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.25rem;
|
||||||
|
border-radius: 6px;
|
||||||
|
display: flex;
|
||||||
|
|
||||||
|
&:hover { color: white; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-body {
|
||||||
|
padding: 1.1rem 1.5rem;
|
||||||
|
color: #d1d5db;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
overflow-y: auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-publication {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.6rem 0.75rem;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: rgba(108, 99, 255, 0.08);
|
||||||
|
border: 1px solid rgba(108, 99, 255, 0.25);
|
||||||
|
color: #c7d2fe;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
|
||||||
|
&.empty {
|
||||||
|
background: rgba(234, 179, 8, 0.08);
|
||||||
|
border-color: rgba(234, 179, 8, 0.3);
|
||||||
|
color: #fde68a;
|
||||||
|
}
|
||||||
|
|
||||||
|
span { flex: 1; min-width: 12rem; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.link-btn {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
color: #a5b4fc;
|
||||||
|
font-weight: 600;
|
||||||
|
text-decoration: underline;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-group {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.45rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-group-label {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
color: #9ca3af;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-choice {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 0.5rem;
|
||||||
|
|
||||||
|
@media (max-width: 480px) { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-choice-option {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.15rem;
|
||||||
|
padding: 0.6rem 0.75rem;
|
||||||
|
border: 1px solid #1f2937;
|
||||||
|
border-radius: 10px;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&.selected { border-color: #6c63ff; background: rgba(108, 99, 255, 0.08); }
|
||||||
|
|
||||||
|
input { position: absolute; opacity: 0; pointer-events: none; }
|
||||||
|
strong { color: white; font-size: 0.9rem; }
|
||||||
|
small { color: #9ca3af; font-size: 0.78rem; line-height: 1.35; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-sections {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 0.35rem 1rem;
|
||||||
|
|
||||||
|
@media (max-width: 480px) { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-check {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
input { margin-top: 0.25rem; accent-color: #6c63ff; }
|
||||||
|
span { display: flex; flex-direction: column; }
|
||||||
|
small { color: #9ca3af; font-size: 0.78rem; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-lore {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.35rem 1.25rem;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-left: 2px solid #374151;
|
||||||
|
margin-left: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-inline {
|
||||||
|
flex-direction: row;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: flex-end;
|
||||||
|
gap: 1rem 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pdf-format {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.3rem;
|
||||||
|
|
||||||
|
select {
|
||||||
|
background: #1a1a2e;
|
||||||
|
color: #e5e7eb;
|
||||||
|
border: 1px solid #374151;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 0.4rem 0.6rem;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0.9rem 1.5rem;
|
||||||
|
background: #0d121d;
|
||||||
|
border-top: 1px solid #1f2937;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
padding: 0.6rem 1.25rem;
|
||||||
|
background: #1f2937;
|
||||||
|
color: #d1d5db;
|
||||||
|
border: 1px solid #374151;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover { background: #374151; }
|
||||||
|
&:disabled { opacity: 0.6; cursor: default; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-confirm {
|
||||||
|
padding: 0.6rem 1.25rem;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
background: #6c63ff;
|
||||||
|
|
||||||
|
&:hover { background: #5b52e0; }
|
||||||
|
&:disabled { opacity: 0.6; cursor: default; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
|
||||||
|
import { LucideAngularModule, FileText, X, BookOpen } from 'lucide-angular';
|
||||||
|
import { TranslatePipe } from '@ngx-translate/core';
|
||||||
|
import { PDF_SECTIONS, PdfExportOptions, PdfSection } from '../../../services/pdf-export.model';
|
||||||
|
import { editionPreset, toExportOptions, toggleSection } from './pdf-export-presets';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Modale des options de l'export PDF : version MJ ou joueurs, format de page, mode
|
||||||
|
* impression, parties incluses et périmètre du lore. Passer en version joueurs
|
||||||
|
* pré-sélectionne ce qui convient à des joueurs (sans bestiaire, quêtes ni tables,
|
||||||
|
* lore limité aux pages liées) ; tout reste modifiable. Le parent télécharge au confirm.
|
||||||
|
*/
|
||||||
|
@Component({
|
||||||
|
selector: 'app-pdf-export-dialog',
|
||||||
|
imports: [LucideAngularModule, TranslatePipe],
|
||||||
|
templateUrl: './pdf-export-dialog.component.html',
|
||||||
|
styleUrls: ['./pdf-export-dialog.component.scss']
|
||||||
|
})
|
||||||
|
export class PdfExportDialogComponent implements OnChanges {
|
||||||
|
readonly FileText = FileText;
|
||||||
|
readonly X = X;
|
||||||
|
readonly BookOpen = BookOpen;
|
||||||
|
readonly allSections = PDF_SECTIONS;
|
||||||
|
|
||||||
|
@Input() open = false;
|
||||||
|
@Input() exporting = false;
|
||||||
|
/** Faux = fiche Publication vide : la modale propose de la compléter. */
|
||||||
|
@Input() hasPublication = true;
|
||||||
|
/** Masque le lien vers la fiche (on est déjà dessus). */
|
||||||
|
@Input() showPublicationLink = true;
|
||||||
|
@Output() cancelled = new EventEmitter<void>();
|
||||||
|
@Output() confirmed = new EventEmitter<PdfExportOptions>();
|
||||||
|
@Output() editPublication = new EventEmitter<void>();
|
||||||
|
|
||||||
|
edition: 'gm' | 'player' = 'gm';
|
||||||
|
format: 'A4' | 'A5' | 'LETTER' = 'A4';
|
||||||
|
print = false;
|
||||||
|
sections: ReadonlySet<PdfSection> = editionPreset('gm').sections;
|
||||||
|
lore: 'ALL' | 'LINKED' = 'ALL';
|
||||||
|
|
||||||
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
|
// Réouverture : on repart du livret MJ complet (pas de parties fantômes d'un export précédent).
|
||||||
|
if (changes['open']?.currentValue && !changes['open'].previousValue) this.setEdition('gm');
|
||||||
|
}
|
||||||
|
|
||||||
|
get nothingSelected(): boolean { return this.sections.size === 0; }
|
||||||
|
|
||||||
|
setEdition(edition: 'gm' | 'player'): void {
|
||||||
|
this.edition = edition;
|
||||||
|
({ sections: this.sections, lore: this.lore } = editionPreset(edition));
|
||||||
|
}
|
||||||
|
|
||||||
|
has(section: PdfSection): boolean { return this.sections.has(section); }
|
||||||
|
|
||||||
|
toggle(section: PdfSection): void {
|
||||||
|
this.sections = toggleSection(this.sections, section);
|
||||||
|
}
|
||||||
|
|
||||||
|
onCancel(): void {
|
||||||
|
if (this.exporting) return;
|
||||||
|
this.cancelled.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
onConfirm(): void {
|
||||||
|
if (this.exporting) return;
|
||||||
|
const options = toExportOptions({
|
||||||
|
edition: this.edition, format: this.format, print: this.print, sections: this.sections, lore: this.lore,
|
||||||
|
});
|
||||||
|
if (options) this.confirmed.emit(options);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { editionPreset, toExportOptions, toggleSection, PdfExportChoice } from './pdf-export-presets';
|
||||||
|
import { safeFileName } from '../../../shared/download.util';
|
||||||
|
|
||||||
|
describe('PDF export presets', () => {
|
||||||
|
const gm = (): PdfExportChoice => ({ edition: 'gm', format: 'A4', print: false, ...editionPreset('gm') });
|
||||||
|
|
||||||
|
it('GM edition = complete booklet, whole lore', () => {
|
||||||
|
expect(toExportOptions(gm())).toEqual({
|
||||||
|
edition: 'gm', format: 'A4', print: false,
|
||||||
|
sections: ['NARRATIVE', 'QUESTS', 'NPCS', 'ENEMIES', 'TABLES', 'LORE', 'APPENDIX', 'MAPS'], lore: 'ALL',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('player edition preselects player-safe parts and linked lore only', () => {
|
||||||
|
const o = toExportOptions({ edition: 'player', format: 'A5', print: true, ...editionPreset('player') })!;
|
||||||
|
expect(o.sections).toEqual(['NARRATIVE', 'NPCS', 'LORE', 'MAPS']);
|
||||||
|
expect(o.lore).toBe('LINKED');
|
||||||
|
expect(o.format).toBe('A5');
|
||||||
|
expect(o.print).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the canonical order when a section is unchecked then checked again', () => {
|
||||||
|
const base = gm();
|
||||||
|
const sections = toggleSection(toggleSection(base.sections, 'NARRATIVE'), 'NARRATIVE');
|
||||||
|
expect(toExportOptions({ ...base, sections })!.sections[0]).toBe('NARRATIVE');
|
||||||
|
expect(base.sections.has('NARRATIVE')).toBe(true); // ensemble d'origine intact
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses an empty selection', () => {
|
||||||
|
expect(toExportOptions({ ...gm(), sections: new Set() })).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('safeFileName', () => {
|
||||||
|
it('matches the server-side slug', () => {
|
||||||
|
expect(safeFileName("Les Cendres d'Été", 'campagne')).toBe('Les_Cendres_d_t');
|
||||||
|
expect(safeFileName(' ', 'campagne')).toBe('campagne');
|
||||||
|
expect(safeFileName(null, 'campagne')).toBe('campagne');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { PDF_SECTIONS, PdfExportOptions, PdfSection } from '../../../services/pdf-export.model';
|
||||||
|
|
||||||
|
/** Choix de la modale d'export PDF (état éditable). */
|
||||||
|
export interface PdfExportChoice {
|
||||||
|
edition: 'gm' | 'player';
|
||||||
|
format: 'A4' | 'A5' | 'LETTER';
|
||||||
|
print: boolean;
|
||||||
|
sections: ReadonlySet<PdfSection>;
|
||||||
|
lore: 'ALL' | 'LINKED';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Préréglages d'une version : MJ = livret complet ; joueurs = ce qu'on peut leur montrer
|
||||||
|
* (narration, PNJ, lore limité aux pages liées, cartes en grand), sans bestiaire, quêtes,
|
||||||
|
* tables ni annexes MJ.
|
||||||
|
*/
|
||||||
|
export function editionPreset(edition: 'gm' | 'player'): Pick<PdfExportChoice, 'sections' | 'lore'> {
|
||||||
|
return edition === 'player'
|
||||||
|
? { sections: new Set<PdfSection>(['NARRATIVE', 'NPCS', 'LORE', 'MAPS']), lore: 'LINKED' }
|
||||||
|
: { sections: new Set<PdfSection>(PDF_SECTIONS), lore: 'ALL' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Coche ou décoche une partie (nouvel ensemble, l'ancien n'est pas modifié). */
|
||||||
|
export function toggleSection(sections: ReadonlySet<PdfSection>, section: PdfSection): Set<PdfSection> {
|
||||||
|
const next = new Set(sections);
|
||||||
|
if (next.has(section)) next.delete(section); else next.add(section);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Options envoyées au serveur, parties dans l'ordre canonique du livret ; null si rien n'est coché. */
|
||||||
|
export function toExportOptions(choice: PdfExportChoice): PdfExportOptions | null {
|
||||||
|
const sections = PDF_SECTIONS.filter(s => choice.sections.has(s));
|
||||||
|
if (sections.length === 0) return null;
|
||||||
|
return { edition: choice.edition, format: choice.format, print: choice.print, sections, lore: choice.lore };
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<div class="chooser">
|
||||||
|
<a class="chooser-back" [routerLink]="['/campaigns', campaignId]">
|
||||||
|
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||||
|
{{ 'guided.backToCampaign' | translate }}
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<h1>
|
||||||
|
<lucide-icon [img]="Sparkles" [size]="20"></lucide-icon>
|
||||||
|
{{ 'guided.chooserTitle' | translate }}
|
||||||
|
</h1>
|
||||||
|
<p class="chooser-intro">{{ 'guided.chooserIntro' | translate }}</p>
|
||||||
|
|
||||||
|
<ul class="method-list">
|
||||||
|
@for (method of methods; track method.id) {
|
||||||
|
<li class="method-card">
|
||||||
|
<div class="method-text">
|
||||||
|
<h2>{{ ('guided.' + method.i18nKey + '.name') | translate }}</h2>
|
||||||
|
<p>{{ ('guided.' + method.i18nKey + '.tagline') | translate }}</p>
|
||||||
|
<span class="method-meta">{{ 'guided.chooserScenes' | translate:{ count: sceneCount(method) } }}</span>
|
||||||
|
</div>
|
||||||
|
<a class="btn-primary method-start" [routerLink]="['/campaigns', campaignId, 'guided', method.id]">
|
||||||
|
{{ 'guided.chooserStart' | translate }}
|
||||||
|
<lucide-icon [img]="ArrowRight" [size]="14"></lucide-icon>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
.chooser {
|
||||||
|
max-width: 760px;
|
||||||
|
padding: 2rem;
|
||||||
|
margin: 0 auto;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
color: white;
|
||||||
|
margin: 1rem 0 0.5rem;
|
||||||
|
|
||||||
|
lucide-icon { color: #fbbf24; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chooser-back {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
color: #9ca3af;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
text-decoration: none;
|
||||||
|
|
||||||
|
&:hover { color: white; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.chooser-intro {
|
||||||
|
color: #9ca3af;
|
||||||
|
line-height: 1.55;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.method-list {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.method-card {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1.25rem;
|
||||||
|
padding: 1rem 1.15rem;
|
||||||
|
background: #111827;
|
||||||
|
border: 1px solid #1f2937;
|
||||||
|
border-radius: 12px;
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.method-text {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
|
||||||
|
h2 { font-size: 1.05rem; color: white; margin: 0 0 0.3rem; }
|
||||||
|
p { color: #d1d5db; font-size: 0.88rem; line-height: 1.5; margin: 0 0 0.4rem; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.method-meta {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: #9ca3af;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.method-start {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
text-decoration: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.chooser { padding: 1rem; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { Component, inject } from '@angular/core';
|
||||||
|
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||||
|
import { LucideAngularModule, ArrowLeft, ArrowRight, Sparkles } from 'lucide-angular';
|
||||||
|
import { TranslatePipe } from '@ngx-translate/core';
|
||||||
|
import { GUIDED_METHODS } from '../guided-methods';
|
||||||
|
import { GuidedMethod } from '../guided-method.model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Choix d'une méthode guidée (Mentor d'écriture) : une carte par méthode, avec son
|
||||||
|
* accroche et le nombre de scènes qu'elle crée. Route : /campaigns/:campaignId/guided
|
||||||
|
*/
|
||||||
|
@Component({
|
||||||
|
selector: 'app-guided-chooser',
|
||||||
|
imports: [RouterLink, TranslatePipe, LucideAngularModule],
|
||||||
|
templateUrl: './guided-chooser.component.html',
|
||||||
|
styleUrls: ['./guided-chooser.component.scss']
|
||||||
|
})
|
||||||
|
export class GuidedChooserComponent {
|
||||||
|
readonly ArrowLeft = ArrowLeft;
|
||||||
|
readonly ArrowRight = ArrowRight;
|
||||||
|
readonly Sparkles = Sparkles;
|
||||||
|
readonly methods = GUIDED_METHODS;
|
||||||
|
readonly campaignId = inject(ActivatedRoute).snapshot.paramMap.get('campaignId') ?? '';
|
||||||
|
|
||||||
|
/** Nombre de scènes produites (brouillon vide : la structure ne dépend pas des réponses). */
|
||||||
|
sceneCount(method: GuidedMethod): number {
|
||||||
|
return method.toDraft({}).scenes.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { GuidedChapterSpec, GuidedSceneSpec } from '../../services/guided-skeleton.model';
|
import { GuidedChapterSpec, GuidedClockSpec, GuidedSceneSpec } from '../../services/guided-skeleton.model';
|
||||||
|
import { LinkType } from '../../services/campaign.model';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Définition d'une méthode guidée (Mentor d'écriture, phases M3/M5). L'assistant
|
* Définition d'une méthode guidée (Mentor d'écriture, phases M3/M5). L'assistant
|
||||||
@@ -40,6 +41,23 @@ export interface GuidedStep {
|
|||||||
export interface GuidedDraft {
|
export interface GuidedDraft {
|
||||||
chapter: GuidedChapterSpec;
|
chapter: GuidedChapterSpec;
|
||||||
scenes: GuidedSceneSpec[];
|
scenes: GuidedSceneSpec[];
|
||||||
|
/**
|
||||||
|
* Liens propres à la méthode (réseau d'enquête). Absent : l'assistant propose de relier
|
||||||
|
* les scènes en chaîne. Le libellé est une clé i18n relative à la méthode (`links.<clé>`).
|
||||||
|
*/
|
||||||
|
links?: GuidedDraftLink[];
|
||||||
|
/** Pas de chaînage proposé (les scènes sont des événements que le MJ déclenche). */
|
||||||
|
noChain?: boolean;
|
||||||
|
/** Horloge à créer dans chaque partie. */
|
||||||
|
clock?: GuidedClockSpec;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GuidedDraftLink {
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
kind: LinkType;
|
||||||
|
/** Clé sous `guided.<i18nKey>.links.` */
|
||||||
|
labelKey: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GuidedMethod {
|
export interface GuidedMethod {
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { join } from 'node:path';
|
|||||||
import { GuidedField, GuidedStep } from './guided-method.model';
|
import { GuidedField, GuidedStep } from './guided-method.model';
|
||||||
import { GUIDED_METHODS } from './guided-methods';
|
import { GUIDED_METHODS } from './guided-methods';
|
||||||
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
|
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
|
||||||
|
import { INVESTIGATION_METHOD } from './methods/investigation.method';
|
||||||
|
import { VILLAIN_PLAN_METHOD } from './methods/villain-plan.method';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Garde-fous des méthodes guidées : chaque étape / champ / option / valeur par défaut
|
* Garde-fous des méthodes guidées : chaque étape / champ / option / valeur par défaut
|
||||||
@@ -40,7 +42,15 @@ function stepKeys(p: string, step: GuidedStep): string[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function requiredKeys(): string[] {
|
function requiredKeys(): string[] {
|
||||||
return GUIDED_METHODS.flatMap(m => [`${m.i18nKey}.name`, ...m.steps.flatMap(s => stepKeys(m.i18nKey, s))]);
|
return GUIDED_METHODS.flatMap(m => {
|
||||||
|
const draft = m.toDraft({});
|
||||||
|
return [
|
||||||
|
`${m.i18nKey}.name`, `${m.i18nKey}.tagline`,
|
||||||
|
...m.steps.flatMap(s => stepKeys(m.i18nKey, s)),
|
||||||
|
...(draft.links?.length ? [`${m.i18nKey}.reviewLinks`] : []),
|
||||||
|
...[...new Set((draft.links ?? []).map(l => l.labelKey))].map(k => `${m.i18nKey}.links.${k}`)
|
||||||
|
];
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('guided methods content', () => {
|
describe('guided methods content', () => {
|
||||||
@@ -102,3 +112,67 @@ describe('five-room method', () => {
|
|||||||
expect(FIVE_ROOM_METHOD.toDraft({}).scenes[0].type).toBe('ENCOUNTER');
|
expect(FIVE_ROOM_METHOD.toDraft({}).scenes[0].type).toBe('ENCOUNTER');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('investigation method', () => {
|
||||||
|
const draft = INVESTIGATION_METHOD.toDraft({
|
||||||
|
title: "L'héritage empoisonné", truth: 'Le notaire est coupable', stakes: 'Le palefrenier sera pendu',
|
||||||
|
'hook.name': "L'arrestation", 'hook.description': 'Le palefrenier est arrêté',
|
||||||
|
'node1.name': 'Le bureau', 'node1.nature': 'location',
|
||||||
|
'node2.name': 'La servante', 'node2.nature': 'npc',
|
||||||
|
'node3.name': "L'enterrement", 'node3.nature': 'event',
|
||||||
|
'conclusion.name': 'La fuite', 'proactive.name': "L'incendie"
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the hidden truth in the GM notes, the hook as the chapter description', () => {
|
||||||
|
expect(draft.chapter.gmNotes).toBe('Le notaire est coupable');
|
||||||
|
expect(draft.chapter.description).toBe('Le palefrenier est arrêté');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds six typed scenes: hook, three varied leads, conclusion, fallback event', () => {
|
||||||
|
expect(draft.scenes.map(s => s.type)).toEqual(['EVENT', 'LOCATION', 'NPC', 'EVENT', 'REVELATION', 'EVENT']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('links the conclusion from three leads, with no single point of failure', () => {
|
||||||
|
const into = (i: number) => draft.links!.filter(l => l.to === i);
|
||||||
|
expect(into(4).map(l => l.from).sort()).toEqual([1, 2, 3]);
|
||||||
|
expect(into(4).every(l => l.kind === 'CLUE')).toBe(true);
|
||||||
|
// Chaque piste est atteinte depuis l'accroche, une autre piste et la relance.
|
||||||
|
for (const lead of [1, 2, 3]) expect(new Set(into(lead).map(l => l.from)).size).toBe(3);
|
||||||
|
expect(draft.links!.some(l => l.from === l.to)).toBe(false);
|
||||||
|
expect(draft.noChain).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('offers varied lead natures by default', () => {
|
||||||
|
const empty = INVESTIGATION_METHOD.steps.filter(s => s.id.startsWith('node'))
|
||||||
|
.map(s => s.fields!.find(f => f.kind === 'choice')!.options![0]);
|
||||||
|
expect(new Set(empty).size).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('villain plan method', () => {
|
||||||
|
const answers = {
|
||||||
|
title: "La régence d'Ysolde", villain: 'Dame Ysolde', goal: 'Le trône du prince',
|
||||||
|
stakes: 'La loi martiale', clockName: 'La régence',
|
||||||
|
'step1.name': 'Le capitaine remplacé', 'step1.action': 'Elle place un homme à elle',
|
||||||
|
'step6.name': 'Le couronnement'
|
||||||
|
};
|
||||||
|
|
||||||
|
it('writes the whole plan in the GM notes and the villain in the description', () => {
|
||||||
|
const draft = VILLAIN_PLAN_METHOD.toDraft(answers);
|
||||||
|
expect(draft.chapter.description).toBe('Dame Ysolde\n\nLe trône du prince');
|
||||||
|
expect(draft.chapter.gmNotes).toBe('1. Le capitaine remplacé — Elle place un homme à elle\n2. Le couronnement');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates six unchained scenes with a varied rhythm by default', () => {
|
||||||
|
const draft = VILLAIN_PLAN_METHOD.toDraft(answers);
|
||||||
|
expect(draft.scenes).toHaveLength(6);
|
||||||
|
expect(draft.noChain).toBe(true);
|
||||||
|
expect(draft.links).toBeUndefined();
|
||||||
|
expect(draft.scenes.map(s => s.type)).toEqual(['EVENT', 'NPC', 'LOCATION', 'EVENT', 'NPC', 'ENCOUNTER']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds a six-segment clock unless the GM declines it', () => {
|
||||||
|
expect(VILLAIN_PLAN_METHOD.toDraft(answers).clock).toEqual({ name: 'La régence', description: 'La loi martiale', segments: 6 });
|
||||||
|
expect(VILLAIN_PLAN_METHOD.toDraft({ ...answers, clockWanted: 'no' }).clock).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { GuidedMethod } from './guided-method.model';
|
import { GuidedMethod } from './guided-method.model';
|
||||||
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
|
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
|
||||||
|
import { INVESTIGATION_METHOD } from './methods/investigation.method';
|
||||||
|
import { VILLAIN_PLAN_METHOD } from './methods/villain-plan.method';
|
||||||
|
|
||||||
/** Méthodes guidées disponibles (M5 : préparation minimale, enquête, casse, bac à sable…). */
|
/** Méthodes guidées disponibles (à venir : préparation minimale, casse, bac à sable…). */
|
||||||
export const GUIDED_METHODS: GuidedMethod[] = [FIVE_ROOM_METHOD];
|
export const GUIDED_METHODS: GuidedMethod[] = [FIVE_ROOM_METHOD, INVESTIGATION_METHOD, VILLAIN_PLAN_METHOD];
|
||||||
|
|
||||||
export function findGuidedMethod(id: string | null): GuidedMethod | undefined {
|
export function findGuidedMethod(id: string | null): GuidedMethod | undefined {
|
||||||
return GUIDED_METHODS.find(m => m.id === id);
|
return GUIDED_METHODS.find(m => m.id === id);
|
||||||
|
|||||||
@@ -128,10 +128,18 @@
|
|||||||
</li>
|
</li>
|
||||||
}
|
}
|
||||||
</ol>
|
</ol>
|
||||||
<label class="link-toggle">
|
@if (offersChain(d)) {
|
||||||
<input type="checkbox" [(ngModel)]="linkScenes" />
|
<label class="link-toggle">
|
||||||
{{ 'guided.linkScenes' | translate }}
|
<input type="checkbox" [(ngModel)]="linkScenes" />
|
||||||
</label>
|
{{ 'guided.linkScenes' | translate }}
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
@if (d.links?.length) {
|
||||||
|
<p class="review-note">{{ k('reviewLinks') | translate:{ count: d.links!.length } }}</p>
|
||||||
|
}
|
||||||
|
@if (d.clock) {
|
||||||
|
<p class="review-note">{{ 'guided.reviewClock' | translate:{ name: d.clock.name, segments: d.clock.segments } }}</p>
|
||||||
|
}
|
||||||
<p class="review-after">{{ 'guided.reviewAfter' | translate }}</p>
|
<p class="review-after">{{ 'guided.reviewAfter' | translate }}</p>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -272,6 +272,17 @@
|
|||||||
input { accent-color: #6c63ff; width: 18px; height: 18px; margin: 0; }
|
input { accent-color: #6c63ff; width: 18px; height: 18px; margin: 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.review-note {
|
||||||
|
margin: 0.75rem 0 0;
|
||||||
|
padding: 0.55rem 0.75rem;
|
||||||
|
border-left: 3px solid #6c63ff;
|
||||||
|
background: rgba(108, 99, 255, 0.08);
|
||||||
|
border-radius: 0 6px 6px 0;
|
||||||
|
color: #c7d2fe;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
.review-after {
|
.review-after {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
color: #9ca3af;
|
color: #9ca3af;
|
||||||
|
|||||||
@@ -186,6 +186,11 @@ export class GuidedWizardComponent implements OnInit {
|
|||||||
this.setAnswer(LINK_SCENES, String(value));
|
this.setAnswer(LINK_SCENES, String(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Chaînage proposé seulement quand la méthode ne relie pas elle-même ses scènes. */
|
||||||
|
offersChain(draft: GuidedDraft): boolean {
|
||||||
|
return !draft.links?.length && !draft.noChain;
|
||||||
|
}
|
||||||
|
|
||||||
create(): void {
|
create(): void {
|
||||||
const draft = this.draft;
|
const draft = this.draft;
|
||||||
if (!draft || this.submitting) return;
|
if (!draft || this.submitting) return;
|
||||||
@@ -197,8 +202,12 @@ export class GuidedWizardComponent implements OnInit {
|
|||||||
newArcName: existing ? null : answer(this.answers, PLACEMENT_NEW_ARC),
|
newArcName: existing ? null : answer(this.answers, PLACEMENT_NEW_ARC),
|
||||||
chapter: draft.chapter,
|
chapter: draft.chapter,
|
||||||
scenes: draft.scenes,
|
scenes: draft.scenes,
|
||||||
linkSequentially: this.linkScenes,
|
linkSequentially: this.offersChain(draft) && this.linkScenes,
|
||||||
linkLabel: this.translate.instant('guided.linkLabel')
|
linkLabel: this.translate.instant('guided.linkLabel'),
|
||||||
|
links: (draft.links ?? []).map(l => ({
|
||||||
|
from: l.from, to: l.to, kind: l.kind, label: this.translate.instant(this.k(`links.${l.labelKey}`))
|
||||||
|
})),
|
||||||
|
clock: draft.clock ?? null
|
||||||
}).subscribe({
|
}).subscribe({
|
||||||
next: result => {
|
next: result => {
|
||||||
this.clearDraft();
|
this.clearDraft();
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { SceneType } from '../../../services/campaign.model';
|
||||||
|
import { GuidedSceneSpec } from '../../../services/guided-skeleton.model';
|
||||||
|
import { GuidedAnswers, GuidedDraftLink, GuidedField, GuidedMethod, answer } from '../guided-method.model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* « Enquête en nœuds » (principe des scénarios d'enquête non linéaires ; textes écrits
|
||||||
|
* pour LoreMind). Au lieu d'une chaîne d'indices où un seul raté bloque tout, l'enquête
|
||||||
|
* est un réseau : une accroche ouvre trois pistes qui se renvoient les unes aux autres et
|
||||||
|
* mènent toutes à la conclusion, plus une scène que le MJ déclenche si la table piétine.
|
||||||
|
*
|
||||||
|
* Produit 1 chapitre (vérité cachée en notes MJ) + 6 scènes typées et reliées :
|
||||||
|
* accroche → pistes 1, 2, 3 (pistes) ; 1 → 2 → 3 → 1 (pistes) ;
|
||||||
|
* pistes 1, 2, 3 → conclusion (indices) ; relance → pistes 1, 2, 3.
|
||||||
|
* La conclusion est donc atteinte par trois chemins (règle des 3 indices) et aucune
|
||||||
|
* scène n'est un passage obligé.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const HOOK = 0;
|
||||||
|
const NODES = [1, 2, 3];
|
||||||
|
const CONCLUSION = 4;
|
||||||
|
const PROACTIVE = 5;
|
||||||
|
|
||||||
|
const NATURE_TO_TYPE: Record<string, SceneType> = {
|
||||||
|
location: 'LOCATION',
|
||||||
|
npc: 'NPC',
|
||||||
|
event: 'EVENT',
|
||||||
|
encounter: 'ENCOUNTER',
|
||||||
|
revelation: 'REVELATION'
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Natures proposées pour chaque piste, dans un ordre différent : des sources variées par défaut. */
|
||||||
|
const NODE_NATURES: Record<number, string[]> = {
|
||||||
|
1: ['location', 'npc', 'event'],
|
||||||
|
2: ['npc', 'location', 'event'],
|
||||||
|
3: ['event', 'location', 'npc']
|
||||||
|
};
|
||||||
|
|
||||||
|
function nodeFields(n: number): GuidedField[] {
|
||||||
|
return [
|
||||||
|
{ key: `node${n}.name`, kind: 'text', required: true, prefilled: true },
|
||||||
|
{ key: `node${n}.nature`, kind: 'choice', options: NODE_NATURES[n] },
|
||||||
|
{ key: `node${n}.description`, kind: 'textarea', coachTopic: 'scene.description' },
|
||||||
|
{ key: `node${n}.clues`, kind: 'textarea', coachTopic: 'scene.branches' },
|
||||||
|
{ key: `node${n}.secret`, kind: 'textarea', coachTopic: 'scene.gmNotes' }
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Réseau de liens entre les six scènes (indices dans l'ordre de `scenes`). */
|
||||||
|
function investigationLinks(): GuidedDraftLink[] {
|
||||||
|
const links: GuidedDraftLink[] = [];
|
||||||
|
for (const n of NODES) links.push({ from: HOOK, to: n, kind: 'LEAD', labelKey: 'lead' });
|
||||||
|
links.push({ from: 1, to: 2, kind: 'LEAD', labelKey: 'lead' });
|
||||||
|
links.push({ from: 2, to: 3, kind: 'LEAD', labelKey: 'lead' });
|
||||||
|
links.push({ from: 3, to: 1, kind: 'LEAD', labelKey: 'lead' });
|
||||||
|
for (const n of NODES) links.push({ from: n, to: CONCLUSION, kind: 'CLUE', labelKey: 'clue' });
|
||||||
|
for (const n of NODES) links.push({ from: PROACTIVE, to: n, kind: 'LEAD', labelKey: 'proactive' });
|
||||||
|
return links;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const INVESTIGATION_METHOD: GuidedMethod = {
|
||||||
|
id: 'investigation',
|
||||||
|
i18nKey: 'investigation',
|
||||||
|
steps: [
|
||||||
|
{ id: 'placement', kind: 'placement' },
|
||||||
|
{
|
||||||
|
id: 'mystery', kind: 'form', fields: [
|
||||||
|
{ key: 'title', kind: 'text', required: true },
|
||||||
|
{ key: 'truth', kind: 'textarea', coachTopic: 'publication.gmBackground' },
|
||||||
|
{ key: 'stakes', kind: 'textarea', coachTopic: 'chapter.stakes' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'hook', kind: 'form', fields: [
|
||||||
|
{ key: 'hook.name', kind: 'text', required: true, prefilled: true },
|
||||||
|
{ key: 'hook.nature', kind: 'choice', options: ['event', 'npc'] },
|
||||||
|
{ key: 'hook.description', kind: 'textarea', coachTopic: 'chapter.synopsis' },
|
||||||
|
{ key: 'hook.clues', kind: 'textarea', coachTopic: 'scene.branches' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ id: 'node1', kind: 'form', fields: nodeFields(1) },
|
||||||
|
{ id: 'node2', kind: 'form', fields: nodeFields(2) },
|
||||||
|
{ id: 'node3', kind: 'form', fields: nodeFields(3) },
|
||||||
|
{
|
||||||
|
id: 'conclusion', kind: 'form', fields: [
|
||||||
|
{ key: 'conclusion.name', kind: 'text', required: true, prefilled: true },
|
||||||
|
{ key: 'conclusion.nature', kind: 'choice', options: ['revelation', 'encounter'] },
|
||||||
|
{ key: 'conclusion.description', kind: 'textarea', coachTopic: 'scene.description' },
|
||||||
|
{ key: 'conclusion.choices', kind: 'textarea', coachTopic: 'scene.choices' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'proactive', kind: 'form', fields: [
|
||||||
|
{ key: 'proactive.name', kind: 'text', required: true, prefilled: true },
|
||||||
|
{ key: 'proactive.description', kind: 'textarea', coachTopic: 'scene.description' },
|
||||||
|
{ key: 'proactive.clues', kind: 'textarea', coachTopic: 'scene.branches' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ id: 'review', kind: 'review' }
|
||||||
|
],
|
||||||
|
|
||||||
|
toDraft(answers: GuidedAnswers) {
|
||||||
|
const scene = (prefix: string, type: SceneType, choicesKey = 'clues', secretKey?: string): GuidedSceneSpec => ({
|
||||||
|
name: answer(answers, `${prefix}.name`) ?? '',
|
||||||
|
description: answer(answers, `${prefix}.description`),
|
||||||
|
type,
|
||||||
|
choicesConsequences: answer(answers, `${prefix}.${choicesKey}`),
|
||||||
|
gmSecretNotes: secretKey ? answer(answers, `${prefix}.${secretKey}`) : null
|
||||||
|
});
|
||||||
|
const nature = (key: string, fallback: SceneType): SceneType => NATURE_TO_TYPE[answers[key]] ?? fallback;
|
||||||
|
return {
|
||||||
|
chapter: {
|
||||||
|
name: answer(answers, 'title') ?? '',
|
||||||
|
description: answer(answers, 'hook.description'),
|
||||||
|
narrativeStakes: answer(answers, 'stakes'),
|
||||||
|
gmNotes: answer(answers, 'truth')
|
||||||
|
},
|
||||||
|
scenes: [
|
||||||
|
scene('hook', nature('hook.nature', 'EVENT')),
|
||||||
|
...NODES.map(n => scene(`node${n}`, nature(`node${n}.nature`, 'LOCATION'), 'clues', 'secret')),
|
||||||
|
scene('conclusion', nature('conclusion.nature', 'REVELATION'), 'choices'),
|
||||||
|
scene('proactive', 'EVENT')
|
||||||
|
],
|
||||||
|
links: investigationLinks()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { SceneType } from '../../../services/campaign.model';
|
||||||
|
import { GuidedAnswers, GuidedField, GuidedMethod, GuidedStep, answer } from '../guided-method.model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* « Plan du méchant » (textes écrits pour LoreMind). L'adversaire ne reste pas assis à
|
||||||
|
* attendre les héros : il poursuit un plan en six étapes, trois discrètes pour se préparer
|
||||||
|
* puis trois visibles pour agir. Chaque étape le rapproche de son but, frappe plus fort que
|
||||||
|
* la précédente et laisse aux joueurs une occasion de réagir.
|
||||||
|
*
|
||||||
|
* Produit 1 chapitre (le plan complet en notes MJ) + 6 scènes d'événement que le MJ
|
||||||
|
* déclenche au fil des séances (non chaînées : c'est l'adversaire qui avance, pas les
|
||||||
|
* joueurs), et, au choix, une horloge de 6 segments dans chaque partie de la campagne.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const STEPS = [1, 2, 3, 4, 5, 6];
|
||||||
|
|
||||||
|
const NATURE_TO_TYPE: Record<string, SceneType> = {
|
||||||
|
event: 'EVENT',
|
||||||
|
npc: 'NPC',
|
||||||
|
location: 'LOCATION',
|
||||||
|
encounter: 'ENCOUNTER'
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Nature proposée en premier pour chaque étape : un rythme varié par défaut. */
|
||||||
|
const FIRST_NATURE: Record<number, string> = { 1: 'event', 2: 'npc', 3: 'location', 4: 'event', 5: 'npc', 6: 'encounter' };
|
||||||
|
|
||||||
|
function natures(step: number): string[] {
|
||||||
|
const first = FIRST_NATURE[step];
|
||||||
|
return [first, ...Object.keys(NATURE_TO_TYPE).filter(n => n !== first)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function planStep(n: number): GuidedStep {
|
||||||
|
const fields: GuidedField[] = [
|
||||||
|
{ key: `step${n}.name`, kind: 'text', required: true, prefilled: true },
|
||||||
|
{ key: `step${n}.nature`, kind: 'choice', options: natures(n) },
|
||||||
|
{ key: `step${n}.action`, kind: 'textarea', coachTopic: 'scene.description' },
|
||||||
|
{ key: `step${n}.sign`, kind: 'textarea', coachTopic: 'scene.choices' }
|
||||||
|
];
|
||||||
|
return { id: `step${n}`, kind: 'form', fields };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const VILLAIN_PLAN_METHOD: GuidedMethod = {
|
||||||
|
id: 'villain-plan',
|
||||||
|
i18nKey: 'villainPlan',
|
||||||
|
steps: [
|
||||||
|
{ id: 'placement', kind: 'placement' },
|
||||||
|
{
|
||||||
|
id: 'villain', kind: 'form', fields: [
|
||||||
|
{ key: 'title', kind: 'text', required: true },
|
||||||
|
{ key: 'villain', kind: 'text', required: true },
|
||||||
|
{ key: 'goal', kind: 'textarea', coachTopic: 'arc.synopsis' },
|
||||||
|
{ key: 'stakes', kind: 'textarea', coachTopic: 'arc.stakes' },
|
||||||
|
{ key: 'objectives', kind: 'textarea', coachTopic: 'chapter.objectives' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
...STEPS.map(planStep),
|
||||||
|
{
|
||||||
|
id: 'clock', kind: 'form', fields: [
|
||||||
|
{ key: 'clockWanted', kind: 'choice', options: ['yes', 'no'] },
|
||||||
|
{ key: 'clockName', kind: 'text', prefilled: true }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ id: 'review', kind: 'review' }
|
||||||
|
],
|
||||||
|
|
||||||
|
toDraft(answers: GuidedAnswers) {
|
||||||
|
const villain = answer(answers, 'villain');
|
||||||
|
const goal = answer(answers, 'goal');
|
||||||
|
const stakes = answer(answers, 'stakes');
|
||||||
|
const plan = STEPS
|
||||||
|
.map(n => [answer(answers, `step${n}.name`), answer(answers, `step${n}.action`)])
|
||||||
|
.filter(([name]) => !!name)
|
||||||
|
.map(([name, action], i) => `${i + 1}. ${name}${action ? ' — ' + action : ''}`);
|
||||||
|
const description = [villain, goal].filter(Boolean).join('\n\n') || null;
|
||||||
|
const wantsClock = answers['clockWanted'] !== 'no';
|
||||||
|
return {
|
||||||
|
chapter: {
|
||||||
|
name: answer(answers, 'title') ?? '',
|
||||||
|
description,
|
||||||
|
playerObjectives: answer(answers, 'objectives'),
|
||||||
|
narrativeStakes: stakes,
|
||||||
|
gmNotes: plan.length ? plan.join('\n') : null
|
||||||
|
},
|
||||||
|
scenes: STEPS.map(n => ({
|
||||||
|
name: answer(answers, `step${n}.name`) ?? '',
|
||||||
|
description: answer(answers, `step${n}.action`),
|
||||||
|
type: NATURE_TO_TYPE[answers[`step${n}.nature`]] ?? NATURE_TO_TYPE[FIRST_NATURE[n]],
|
||||||
|
choicesConsequences: answer(answers, `step${n}.sign`)
|
||||||
|
})),
|
||||||
|
noChain: true,
|
||||||
|
clock: wantsClock
|
||||||
|
? { name: answer(answers, 'clockName') ?? answer(answers, 'title') ?? '', description: stakes, segments: STEPS.length }
|
||||||
|
: undefined
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -87,6 +87,48 @@
|
|||||||
</app-dynamic-fields-form>
|
</app-dynamic-fields-form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Rôle dans l'histoire : indépendant du système de jeu (le gabarit porte les caractéristiques). -->
|
||||||
|
<fieldset class="story-block">
|
||||||
|
<legend>{{ 'npcEdit.storyTitle' | translate }}</legend>
|
||||||
|
<p class="hint">{{ 'npcEdit.storyHint' | translate }}</p>
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="npc-role">{{ 'npcEdit.roleLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="npc.role"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<select id="npc-role" name="role" [(ngModel)]="story.role">
|
||||||
|
<option [ngValue]="null">{{ 'npcEdit.roleNone' | translate }}</option>
|
||||||
|
@for (r of roles; track r) {
|
||||||
|
<option [ngValue]="r">{{ ('npcEdit.role.' + r) | translate }}</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="npc-motivation">{{ 'npcEdit.motivationLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="npc.motivation"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea id="npc-motivation" name="motivation" rows="3" [(ngModel)]="story.motivation"
|
||||||
|
[placeholder]="'npcEdit.motivationPlaceholder' | translate"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="npc-knowledge">{{ 'npcEdit.knowledgeLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="npc.knowledge"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<textarea id="npc-knowledge" name="knowledge" rows="3" [(ngModel)]="story.knowledge"
|
||||||
|
[placeholder]="'npcEdit.knowledgePlaceholder' | translate"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<div class="field-label-row">
|
||||||
|
<label for="npc-mannerism">{{ 'npcEdit.mannerismLabel' | translate }}</label>
|
||||||
|
<app-writing-coach-trigger topic="npc.mannerism"></app-writing-coach-trigger>
|
||||||
|
</div>
|
||||||
|
<input id="npc-mannerism" name="mannerism" type="text" [(ngModel)]="story.mannerism"
|
||||||
|
[placeholder]="'npcEdit.mannerismPlaceholder' | translate" />
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
<!-- Pages de Lore liées (uniquement si la campagne est rattachée à un Lore) -->
|
<!-- Pages de Lore liées (uniquement si la campagne est rattachée à un Lore) -->
|
||||||
@if (loreId) {
|
@if (loreId) {
|
||||||
<div class="field">
|
<div class="field">
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user