Export PDF : fiche Publication et options d'export (module à partager ou vendre)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 44s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 57s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m41s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 44s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 57s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m41s
- Correctifs du livret : le résumé des scènes est enfin exporté, libellés
accentués (Thèmes, Récompenses, Résolution, Choix et conséquences), stats
Foundry en français (PV, CA, FOR, FP…), encadrés et longues pages de lore
coupables entre deux pages (fini les grands blancs), plus de date d'export
en couverture, titre/auteur/sujet/langue dans les propriétés du PDF.
- Fiche Publication de la campagne (écran /campaigns/:id/publication) :
sous-titre, auteur, version, illustration de couverture, page technique
(système, niveaux, joueurs, durée), argument, avertissements de contenu,
contexte caché et accroches pour le MJ, crédits et licence. Stockée en JSON
(migration V26), API GET/PUT /api/campaigns/{id}/publication, conservée à
l'export/import de campagne (couverture remappée).
- Dans le PDF : couverture illustrée, page de crédits, introduction (page
technique, l'aventure en bref, contexte MJ, accroches, structure). Fiche
vide : livret de campagne inchangé.
- Options d'export (modale au clic sur « Exporter en PDF ») : version MJ ou
joueurs (aucun secret : notes MJ, conséquences, sorties, combats, contexte),
format A4 / A5 / US Letter, mode impression sans aplats, choix des parties,
lore complet ou seulement les pages liées à la campagne.
- Cinq nouvelles fiches du coach d'écriture sur l'écran Publication
(argument, avertissements, contexte caché, accroches, crédits).
Vérifié : core clean verify (1247 tests, dont contenu du PDF par option,
version joueurs sans secret, propriétés du fichier, format Letter, remap de
la couverture à l'import), web build + 357 vitest, lint sans erreur, essai
dans le navigateur (migration V26 sur une base existante, enregistrement de
la fiche, export joueurs A5).
À redéployer : core + web (migration V26).
This commit is contained in:
@@ -3,6 +3,7 @@ package com.loremind.application.campaigncontext;
|
||||
import com.loremind.application.playcontext.PlaythroughService;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
@@ -108,6 +109,23 @@ public class CampaignService {
|
||||
campaignRepository.save(campaign);
|
||||
}
|
||||
|
||||
/** Fiche « Publication » de la campagne (vide si jamais renseignée). */
|
||||
public CampaignPublication getPublication(String id) {
|
||||
Campaign campaign = campaignRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||
return campaign.getPublication() != null ? campaign.getPublication() : CampaignPublication.empty();
|
||||
}
|
||||
|
||||
/** Remplace la fiche « Publication » (nettoyée : blancs → vide, longueurs bornées). */
|
||||
public CampaignPublication updatePublication(String id, CampaignPublication publication) {
|
||||
Campaign campaign = campaignRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||
CampaignPublication clean = publication != null ? publication.normalized() : CampaignPublication.empty();
|
||||
campaign.setPublication(clean.hasContent() ? clean : null);
|
||||
campaignRepository.save(campaign);
|
||||
return clean;
|
||||
}
|
||||
|
||||
private String normalizeId(String id) {
|
||||
return (id == null || id.isBlank()) ? null : id;
|
||||
}
|
||||
|
||||
@@ -44,6 +44,9 @@ public class Campaign {
|
||||
*/
|
||||
private String graphPositions;
|
||||
|
||||
/** Fiche « Publication » (couverture, page technique, crédits…). Null = jamais renseignée. */
|
||||
private CampaignPublication publication;
|
||||
|
||||
public boolean isLinkedToLore() {
|
||||
return this.loreId != null && !this.loreId.isBlank();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
@@ -1,5 +1,7 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.infrastructure.persistence.converter.CampaignPublicationJsonConverter;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -63,6 +65,11 @@ public class CampaignJpaEntity {
|
||||
@Column(name = "graph_positions", columnDefinition = "TEXT")
|
||||
private String graphPositions;
|
||||
|
||||
/** Fiche « Publication » (JSON). NULL = jamais renseignée. */
|
||||
@Column(name = "publication", columnDefinition = "TEXT")
|
||||
@Convert(converter = CampaignPublicationJsonConverter.class)
|
||||
private CampaignPublication publication;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
|
||||
+2
@@ -76,6 +76,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
||||
.loreId(jpaEntity.getLoreId())
|
||||
.gameSystemId(jpaEntity.getGameSystemId())
|
||||
.graphPositions(jpaEntity.getGraphPositions())
|
||||
.publication(jpaEntity.getPublication())
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -92,6 +93,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
||||
.loreId(campaign.getLoreId())
|
||||
.gameSystemId(campaign.getGameSystemId())
|
||||
.graphPositions(campaign.getGraphPositions())
|
||||
.publication(campaign.getPublication())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.loremind.infrastructure.transfer;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||
@@ -99,11 +100,20 @@ class CampaignContentInserter {
|
||||
e.setPlayerCount(d.playerCount());
|
||||
e.setLoreId(d.loreId()); // 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());
|
||||
}
|
||||
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). */
|
||||
private void insertArcs(ContentExport export, ImportIdMaps maps, ImportResult.Builder result) {
|
||||
for (ContentExport.ArcDto d : nullSafe(export.arcs())) {
|
||||
|
||||
@@ -200,7 +200,7 @@ public class ExportService {
|
||||
List<QuestJpaEntity> campaignQuests = questRepo.findByCampaignId(cid);
|
||||
// Images/fichiers : uniquement les binaires RÉFÉRENCÉS par la clôture (si option active).
|
||||
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());
|
||||
|
||||
@@ -304,9 +304,11 @@ public class ExportService {
|
||||
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) {
|
||||
Set<String> imageRefs = new LinkedHashSet<>();
|
||||
if (campaign.getPublication() != null) add(imageRefs, campaign.getPublication().coverImageId());
|
||||
structure.arcs().forEach(a -> addAll(imageRefs, a.getIllustrationImageIds()));
|
||||
structure.chapters().forEach(c -> addAll(imageRefs, c.getIllustrationImageIds()));
|
||||
campaignQuests.forEach(q -> addAll(imageRefs, q.getIllustrationImageIds()));
|
||||
@@ -340,7 +342,7 @@ public class ExportService {
|
||||
ContentExport.CampaignDto dto = toCampaignDto(campaign);
|
||||
if (includeLore) return dto;
|
||||
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 -----
|
||||
@@ -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). */
|
||||
private Set<String> collectImageIdRefs(ContentExport export) {
|
||||
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.ChapterDto c : export.chapters()) addAll(refs, c.illustrationImageIds());
|
||||
addQuestImageRefs(refs, export.quests());
|
||||
@@ -599,7 +604,8 @@ public class ExportService {
|
||||
|
||||
private ContentExport.CampaignDto toCampaignDto(CampaignJpaEntity e) {
|
||||
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) {
|
||||
|
||||
@@ -128,7 +128,9 @@ public record ContentExport(
|
||||
int arcsCount,
|
||||
int playerCount,
|
||||
String loreId,
|
||||
String gameSystemId
|
||||
String gameSystemId,
|
||||
/** Fiche « Publication » ; absente des bundles antérieurs (null). */
|
||||
com.loremind.domain.campaigncontext.CampaignPublication publication
|
||||
) {}
|
||||
|
||||
public record ArcDto(
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
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. */
|
||||
public enum Section { NARRATIVE, QUESTS, NPCS, ENEMIES, TABLES, LORE }
|
||||
|
||||
/** 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, 2.2, 1.7, 2.0, 10.0, 12.5),
|
||||
A5("A5", 14.8, 1.7, 1.3, 1.6, 9.0, 7.0),
|
||||
LETTER("letter", 21.59, 2.2, 1.8, 2.0, 10.0, 12.0);
|
||||
|
||||
final String cssSize;
|
||||
final double widthCm;
|
||||
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 marginTopCm, double marginSideCm,
|
||||
double marginBottomCm, double bodyPt, double coverArtMaxCm) {
|
||||
this.cssSize = cssSize;
|
||||
this.widthCm = widthCm;
|
||||
this.marginTopCm = marginTopCm;
|
||||
this.marginSideCm = marginSideCm;
|
||||
this.marginBottomCm = marginBottomCm;
|
||||
this.bodyPt = bodyPt;
|
||||
this.coverArtMaxCm = coverArtMaxCm;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+398
-117
@@ -1,5 +1,6 @@
|
||||
package com.loremind.infrastructure.transfer.pdf;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||
import com.loremind.domain.campaigncontext.quest.Prerequisite;
|
||||
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||
@@ -9,6 +10,8 @@ import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
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.Section;
|
||||
import com.openhtmltopdf.outputdevice.helper.BaseRendererBuilder;
|
||||
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
|
||||
import org.slf4j.Logger;
|
||||
@@ -20,9 +23,6 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
|
||||
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.*;
|
||||
@@ -51,15 +51,11 @@ public class PdfExportService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PdfExportService.class);
|
||||
|
||||
/** Largeur utile d'une page A4 (21cm - 2 x 1.7cm de marges). */
|
||||
private static final double CONTENT_WIDTH_CM = 17.6;
|
||||
/** Hauteur max affichee d'une illustration : evite qu'une image portrait mange la page. */
|
||||
private static final double ILLUSTRATION_MAX_HEIGHT_CM = 11.0;
|
||||
/** Hauteur max affichee d'un portrait de fiche (colonne de 3cm de large). */
|
||||
private static final double PORTRAIT_MAX_HEIGHT_CM = 4.5;
|
||||
|
||||
private static final DateTimeFormatter FR_DATE = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.FRENCH);
|
||||
|
||||
// ----- Libelles/police repetes (S1192 ; fragments HTML generiques dans PdfHtml) -----
|
||||
private static final String FONT_SERIF = "DejaVu Serif";
|
||||
private static final String FONT_SANS = "DejaVu Sans";
|
||||
@@ -70,6 +66,12 @@ public class PdfExportService {
|
||||
private static final String CSS_SECRET = "secret";
|
||||
private static final String LABEL_NOTES_MJ = "Notes MJ";
|
||||
private static final String LABEL_SANS_DOSSIER = "Sans dossier";
|
||||
private static final String LABEL_THEMES = "Thèmes";
|
||||
private static final String LABEL_ENJEUX = "Enjeux";
|
||||
private static final String LABEL_RECOMPENSES = "Récompenses";
|
||||
private static final String LABEL_RESOLUTION = "Résolution";
|
||||
private static final String LABEL_CONDITIONS = "Conditions de déblocage";
|
||||
private static final String LABEL_NOEUDS = "Nœuds liés";
|
||||
|
||||
private final CampaignJpaRepository campaignRepo;
|
||||
private final NpcJpaRepository npcRepo;
|
||||
@@ -106,10 +108,14 @@ public class PdfExportService {
|
||||
return campaign(campaignId).getName();
|
||||
}
|
||||
|
||||
/** Construit le PDF complet de la campagne. @throws NoSuchElementException si absente. */
|
||||
/** Livret MJ complet en A4 (options par défaut). @throws NoSuchElementException si absente. */
|
||||
public byte[] export(String campaignId) {
|
||||
CampaignJpaEntity campaign = campaign(campaignId);
|
||||
String xhtml = buildXhtml(campaign);
|
||||
return export(campaignId, PdfExportOptions.defaults());
|
||||
}
|
||||
|
||||
/** Construit le PDF de la campagne selon les options. @throws NoSuchElementException si absente. */
|
||||
public byte[] export(String campaignId, PdfExportOptions options) {
|
||||
String xhtml = xhtml(campaignId, options);
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
PdfRendererBuilder builder = new PdfRendererBuilder();
|
||||
@@ -124,6 +130,11 @@ public class PdfExportService {
|
||||
}
|
||||
}
|
||||
|
||||
/** Document XHTML intermédiaire (exposé au paquet pour les tests de contenu). */
|
||||
String xhtml(String campaignId, PdfExportOptions options) {
|
||||
return buildXhtml(campaign(campaignId), options != null ? options : PdfExportOptions.defaults());
|
||||
}
|
||||
|
||||
private CampaignJpaEntity campaign(String campaignId) {
|
||||
return campaignRepo.findById(Long.parseLong(campaignId))
|
||||
.orElseThrow(() -> new NoSuchElementException("Campagne introuvable : " + campaignId));
|
||||
@@ -168,6 +179,9 @@ public class PdfExportService {
|
||||
* le sommaire et les compteurs (repris ensuite sur la couverture).
|
||||
*/
|
||||
private static final class Ctx {
|
||||
final PdfExportOptions opt;
|
||||
/** Version MJ : les contenus reserves au MJ (secrets, consequences, combats...) sont rendus. */
|
||||
final boolean gm;
|
||||
final StringBuilder body = new StringBuilder();
|
||||
final StringBuilder bookmarks = new StringBuilder();
|
||||
final List<TocEntry> toc = new ArrayList<>();
|
||||
@@ -178,57 +192,235 @@ public class PdfExportService {
|
||||
int randomTables;
|
||||
int lorePages;
|
||||
|
||||
Ctx(PdfExportOptions opt) {
|
||||
this.opt = opt;
|
||||
this.gm = opt.gmContent();
|
||||
}
|
||||
|
||||
void addToc(int level, String title, String anchor) {
|
||||
toc.add(new TocEntry(level, title, anchor));
|
||||
}
|
||||
|
||||
double contentWidthCm() {
|
||||
return opt.format().contentWidthCm();
|
||||
}
|
||||
|
||||
/** Champ reserve au MJ : absent de la version joueurs. */
|
||||
void gmBlock(String label, String value) {
|
||||
if (gm) block(body, label, value);
|
||||
}
|
||||
|
||||
/** Encadre reserve au MJ : absent de la version joueurs. */
|
||||
void gmBox(String cssClass, String label, String value) {
|
||||
if (gm) box(body, cssClass, label, value);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildXhtml(CampaignJpaEntity campaign) {
|
||||
private String buildXhtml(CampaignJpaEntity campaign, PdfExportOptions opt) {
|
||||
List<TemplateField> npcTemplate = resolveTemplate(campaign.getGameSystemId(), true);
|
||||
List<TemplateField> enemyTemplate = resolveTemplate(campaign.getGameSystemId(), false);
|
||||
CampaignPublication pub = campaign.getPublication() != null
|
||||
? campaign.getPublication() : CampaignPublication.empty();
|
||||
|
||||
// Les sections d'abord (elles remplissent sommaire + compteurs), la couverture
|
||||
// et le sommaire sont assembles ensuite en tete de document.
|
||||
Structure st = structureLoader.load(campaign);
|
||||
Ctx ctx = new Ctx();
|
||||
ctx.quests = st.quests.size();
|
||||
narrative(ctx, st);
|
||||
quests(ctx, st);
|
||||
personas(ctx, "part-npcs", "Personnages non-joueurs (PNJ)", npcEntries(campaign), npcTemplate, false);
|
||||
personas(ctx, "part-enemies", "Bestiaire", enemyEntries(campaign), enemyTemplate, true);
|
||||
randomTables(ctx, campaign);
|
||||
lore(ctx, campaign);
|
||||
Ctx ctx = new Ctx(opt);
|
||||
introduction(ctx, campaign, pub, st);
|
||||
if (opt.includes(Section.NARRATIVE)) narrative(ctx, st);
|
||||
if (opt.includes(Section.QUESTS)) {
|
||||
ctx.quests = st.quests.size();
|
||||
quests(ctx, st);
|
||||
}
|
||||
if (opt.includes(Section.NPCS)) {
|
||||
personas(ctx, "part-npcs", "Personnages non-joueurs (PNJ)", npcEntries(campaign), npcTemplate, false);
|
||||
}
|
||||
if (opt.includes(Section.ENEMIES)) {
|
||||
personas(ctx, "part-enemies", "Bestiaire", enemyEntries(campaign), enemyTemplate, true);
|
||||
}
|
||||
if (opt.includes(Section.TABLES)) randomTables(ctx, campaign);
|
||||
if (opt.includes(Section.LORE)) lore(ctx, campaign, st);
|
||||
|
||||
StringBuilder full = new StringBuilder();
|
||||
cover(full, campaign, ctx);
|
||||
cover(full, ctx, campaign, pub);
|
||||
creditsPage(full, campaign, pub);
|
||||
full.append(tocHtml(ctx.toc));
|
||||
full.append(ctx.body);
|
||||
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
|
||||
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta charset=\"utf-8\"/>\n"
|
||||
+ "<style>" + cssFor(campaign.getName()) + "</style>\n"
|
||||
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"fr\" xml:lang=\"fr\"><head><meta charset=\"utf-8\"/>\n"
|
||||
+ documentInfo(campaign, pub)
|
||||
+ "<style>" + cssFor(campaign.getName(), opt) + "</style>\n"
|
||||
+ "<bookmarks>" + ctx.bookmarks + "</bookmarks>\n"
|
||||
+ "</head><body>" + full + "</body></html>";
|
||||
}
|
||||
|
||||
private void cover(StringBuilder b, CampaignJpaEntity c, Ctx ctx) {
|
||||
b.append("<div class=\"cover\">");
|
||||
b.append("<div class=\"subtitle\">Livret de campagne</div>");
|
||||
/**
|
||||
* Proprietes du fichier PDF (titre, auteur, sujet, mots-cles) lues par les liseuses
|
||||
* et les boutiques : openhtmltopdf les reprend du {@code <title>} et des {@code <meta>}.
|
||||
*/
|
||||
private static String documentInfo(CampaignJpaEntity c, CampaignPublication pub) {
|
||||
StringBuilder m = new StringBuilder();
|
||||
m.append("<title>").append(esc(c.getName())).append("</title>\n");
|
||||
meta(m, "author", pub.author());
|
||||
meta(m, "subject", notBlank(pub.subtitle()) ? pub.subtitle() : firstLine(pub.pitch()));
|
||||
meta(m, "keywords", pub.system());
|
||||
return m.toString();
|
||||
}
|
||||
|
||||
private static void meta(StringBuilder m, String name, String content) {
|
||||
if (!notBlank(content)) return;
|
||||
m.append("<meta name=\"").append(name).append("\" content=\"").append(esc(content.trim())).append("\"/>\n");
|
||||
}
|
||||
|
||||
private static String firstLine(String s) {
|
||||
if (!notBlank(s)) return null;
|
||||
String line = s.strip().split("\\R", 2)[0];
|
||||
return line.length() > 200 ? line.substring(0, 199) + "…" : line;
|
||||
}
|
||||
|
||||
/**
|
||||
* Couverture. Sans fiche Publication : le livret historique (titre, compteurs, description).
|
||||
* Avec : systeme en surtitre, sous-titre, illustration, ligne technique, auteur, version —
|
||||
* jamais de date d'export (un module vendu n'a pas a dater sa generation).
|
||||
*/
|
||||
private void cover(StringBuilder b, Ctx ctx, CampaignJpaEntity c, CampaignPublication pub) {
|
||||
boolean published = pub.hasContent();
|
||||
PdfImage art = imageEncoder.image(pub.coverImageId(), PdfImageEncoder.ILLUSTRATION_MAX);
|
||||
b.append("<div class=\"cover").append(art != null ? " has-art" : "").append("\">");
|
||||
String kicker = coverKicker(ctx, pub);
|
||||
if (kicker != null) b.append("<div class=\"cover-kicker\">").append(esc(kicker)).append(DIV_CLOSE);
|
||||
b.append("<h1 class=\"cover-title\">").append(esc(c.getName())).append("</h1>");
|
||||
if (notBlank(pub.subtitle())) {
|
||||
b.append("<div class=\"cover-subtitle\">").append(esc(pub.subtitle())).append(DIV_CLOSE);
|
||||
}
|
||||
b.append("<div class=\"cover-rule\"></div>");
|
||||
String meta = coverMeta(ctx);
|
||||
if (art != null) {
|
||||
double maxH = ctx.opt.format().coverArtMaxCm;
|
||||
double widthCm = Math.min(ctx.contentWidthCm(), maxH * art.w() / art.h());
|
||||
b.append("<div class=\"cover-art\"><img style=\"width:").append(cm(widthCm))
|
||||
.append("\" src=\"").append(art.uri()).append("\"/></div>");
|
||||
}
|
||||
String meta = published ? technicalLine(pub) : coverMeta(ctx);
|
||||
if (!meta.isEmpty()) {
|
||||
b.append("<div class=\"cover-meta\">").append(esc(meta)).append(DIV_CLOSE);
|
||||
}
|
||||
if (notBlank(c.getDescription())) {
|
||||
if (!ctx.gm && published) {
|
||||
b.append("<div class=\"cover-edition\">Édition joueurs</div>");
|
||||
}
|
||||
if (!published && notBlank(c.getDescription())) {
|
||||
b.append("<div class=\"cover-desc\">").append(multiline(c.getDescription())).append(DIV_CLOSE);
|
||||
}
|
||||
b.append("<div class=\"cover-date\">Exporté le ")
|
||||
.append(esc(LocalDate.now(ZoneId.systemDefault()).format(FR_DATE)))
|
||||
.append(DIV_CLOSE);
|
||||
if (notBlank(pub.author())) {
|
||||
b.append("<div class=\"cover-author\">").append(esc(pub.author())).append(DIV_CLOSE);
|
||||
}
|
||||
if (notBlank(pub.version())) {
|
||||
b.append("<div class=\"cover-version\">Version ").append(esc(pub.version())).append(DIV_CLOSE);
|
||||
}
|
||||
b.append(DIV_CLOSE);
|
||||
}
|
||||
|
||||
/** Surtitre : le systeme de jeu s'il est renseigne ; sinon l'intitule historique du livret. */
|
||||
private static String coverKicker(Ctx ctx, CampaignPublication pub) {
|
||||
if (notBlank(pub.system())) return pub.system();
|
||||
if (pub.hasContent()) return null;
|
||||
return ctx.gm ? "Livret de campagne" : "Livret des joueurs";
|
||||
}
|
||||
|
||||
/** "Niveaux : 1 à 3 · Joueurs : 3 à 5 · Durée : 2 séances" (morceaux renseignés seulement). */
|
||||
private static String technicalLine(CampaignPublication pub) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
if (notBlank(pub.levels())) parts.add("Niveaux : " + pub.levels());
|
||||
if (notBlank(pub.players())) parts.add("Joueurs : " + pub.players());
|
||||
if (notBlank(pub.duration())) parts.add("Durée : " + pub.duration());
|
||||
return String.join(" · ", parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Page de credits (verso de couverture) : titre, auteur, version, credits et mentions
|
||||
* legales — attendue dans tout module diffuse. Absente si rien n'est renseigne.
|
||||
*/
|
||||
private static void creditsPage(StringBuilder b, CampaignJpaEntity c, CampaignPublication pub) {
|
||||
if (!pub.hasCredits()) return;
|
||||
b.append("<div class=\"credits-page\"><div class=\"credits-title\">").append(esc(c.getName())).append(DIV_CLOSE);
|
||||
if (notBlank(pub.subtitle())) {
|
||||
b.append("<div class=\"credits-subtitle\">").append(esc(pub.subtitle())).append(DIV_CLOSE);
|
||||
}
|
||||
block(b, "Auteur", pub.author());
|
||||
block(b, "Version", pub.version());
|
||||
block(b, "Crédits", pub.credits());
|
||||
if (notBlank(pub.legal())) {
|
||||
b.append("<div class=\"legal\">");
|
||||
prose(b, pub.legal());
|
||||
b.append(DIV_CLOSE);
|
||||
}
|
||||
b.append(DIV_CLOSE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Introduction d'un module publie (ordre attendu par les MJ qui l'achetent) : page
|
||||
* technique, argument, avertissements, puis — version MJ — contexte cache, accroches et
|
||||
* structure de l'aventure. Rien si la fiche Publication est vide (livret historique).
|
||||
*/
|
||||
private void introduction(Ctx ctx, CampaignJpaEntity c, CampaignPublication pub, Structure st) {
|
||||
if (!pub.hasContent()) return;
|
||||
StringBuilder b = ctx.body;
|
||||
b.append("<h1 class=\"part\" id=\"part-intro\">Introduction</h1>");
|
||||
ctx.addToc(0, "Introduction", "part-intro");
|
||||
ctx.bookmarks.append(bookmark("Introduction", "part-intro", ""));
|
||||
|
||||
technicalTable(b, pub);
|
||||
String pitch = notBlank(pub.pitch()) ? pub.pitch() : c.getDescription();
|
||||
introSection(b, "L'aventure en bref", pitch);
|
||||
box(b, "warning", "Avertissements de contenu", pub.contentWarnings());
|
||||
if (!ctx.gm) return;
|
||||
introSection(b, "Contexte pour le MJ", pub.gmBackground());
|
||||
introSection(b, "Accroches", pub.hooks());
|
||||
if (ctx.opt.includes(Section.NARRATIVE)) introSection(b, "Structure de l'aventure", structureOutline(st));
|
||||
}
|
||||
|
||||
/** Tableau « Système / Niveaux / Joueurs / Durée » de la page technique. */
|
||||
private static void technicalTable(StringBuilder b, CampaignPublication pub) {
|
||||
if (!pub.hasTechnicalSheet()) return;
|
||||
b.append("<table class=\"stats-table tech-table\"><tbody>");
|
||||
int row = 0;
|
||||
row = techRow(b, row, "Système", pub.system());
|
||||
row = techRow(b, row, "Niveaux", pub.levels());
|
||||
row = techRow(b, row, "Joueurs", pub.players());
|
||||
techRow(b, row, "Durée", pub.duration());
|
||||
b.append(TBODY_TABLE_CLOSE);
|
||||
}
|
||||
|
||||
private static int techRow(StringBuilder b, int row, String label, String value) {
|
||||
if (!notBlank(value)) return row;
|
||||
b.append(trTag(row)).append("<th>").append(esc(label)).append("</th><td>")
|
||||
.append(esc(value)).append(TD_TR_CLOSE);
|
||||
return row + 1;
|
||||
}
|
||||
|
||||
/** Intertitre + texte (paragraphes, listes « - … ») ; rien si le texte est vide. */
|
||||
private static void introSection(StringBuilder b, String title, String text) {
|
||||
if (!notBlank(text)) return;
|
||||
b.append("<h2 class=\"section-head\">").append(esc(title)).append("</h2>");
|
||||
prose(b, text);
|
||||
}
|
||||
|
||||
/** Plan de l'aventure : un arc par puce, suivi de ses chapitres. Null en mode plat. */
|
||||
private static String structureOutline(Structure st) {
|
||||
List<ArcJpaEntity> arcs = st.visibleArcs;
|
||||
if (arcs.isEmpty()) return null;
|
||||
if (arcs.size() == 1 && st.chaptersByArc.get(arcs.get(0).getId()).size() <= 1) return null;
|
||||
StringBuilder s = new StringBuilder();
|
||||
for (ArcJpaEntity arc : arcs) {
|
||||
List<String> chapters = new ArrayList<>();
|
||||
for (ChapterJpaEntity ch : st.chaptersByArc.get(arc.getId())) chapters.add(ch.getName());
|
||||
s.append("- ").append(arc.getName());
|
||||
if (!chapters.isEmpty()) s.append(" : ").append(String.join(", ", chapters));
|
||||
s.append('\n');
|
||||
}
|
||||
return s.toString();
|
||||
}
|
||||
|
||||
/** Ligne "3 scènes · 2 quêtes · 4 PNJ ..." de la couverture (parties non vides seulement). */
|
||||
private static String coverMeta(Ctx ctx) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
@@ -305,13 +497,7 @@ public class PdfExportService {
|
||||
b.append("<div class=\"arc\"><h2 class=\"arc-head\" id=\"arc-").append(arc.getId()).append("\">")
|
||||
.append("<span class=\"eyebrow eyebrow-light\">Arc</span>")
|
||||
.append(esc(arc.getName())).append("</h2>");
|
||||
illustrations(b, arc.getIllustrationImageIds());
|
||||
block(b, LABEL_DESCRIPTION, arc.getDescription());
|
||||
block(b, "Themes", arc.getThemes());
|
||||
block(b, "Enjeux", arc.getStakes());
|
||||
block(b, "Recompenses", arc.getRewards());
|
||||
block(b, "Resolution", arc.getResolution());
|
||||
box(b, CSS_SECRET, LABEL_NOTES_MJ, arc.getGmNotes());
|
||||
arcFields(ctx, arc);
|
||||
|
||||
for (ChapterJpaEntity ch : st.chaptersByArc.get(arc.getId())) {
|
||||
chapterSection(ctx, st, ch);
|
||||
@@ -319,6 +505,17 @@ public class PdfExportService {
|
||||
b.append(DIV_CLOSE);
|
||||
}
|
||||
|
||||
/** Champs d'un arc ; tout est reserve au MJ (synopsis, enjeux, resolution...) sauf les illustrations. */
|
||||
private void arcFields(Ctx ctx, ArcJpaEntity arc) {
|
||||
illustrations(ctx, arc.getIllustrationImageIds());
|
||||
ctx.gmBlock(LABEL_DESCRIPTION, arc.getDescription());
|
||||
ctx.gmBlock(LABEL_THEMES, arc.getThemes());
|
||||
ctx.gmBlock(LABEL_ENJEUX, arc.getStakes());
|
||||
ctx.gmBlock(LABEL_RECOMPENSES, arc.getRewards());
|
||||
ctx.gmBlock(LABEL_RESOLUTION, arc.getResolution());
|
||||
ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, arc.getGmNotes());
|
||||
}
|
||||
|
||||
/** Un chapitre narratif complet (dans son arc) : en-tete + champs (fusionnes ou non) + scenes. */
|
||||
private void chapterSection(Ctx ctx, Structure st, ChapterJpaEntity ch) {
|
||||
StringBuilder b = ctx.body;
|
||||
@@ -327,10 +524,10 @@ public class PdfExportService {
|
||||
b.append("<div class=\"chapter\"><div class=\"chapter-head\" id=\"ch-").append(ch.getId()).append("\">")
|
||||
.append("<span class=\"eyebrow\">").append(fused != null ? "Quête" : "Chapitre").append(SPAN_CLOSE)
|
||||
.append(esc(ch.getName())).append(DIV_CLOSE);
|
||||
chapterFields(b, ch, fused, st);
|
||||
chapterFields(ctx, ch, fused, st);
|
||||
|
||||
for (SceneJpaEntity sc : st.scenesByChapter.get(ch.getId())) {
|
||||
scene(b, sc, st);
|
||||
scene(ctx, sc, st);
|
||||
ctx.scenes++;
|
||||
}
|
||||
b.append(DIV_CLOSE);
|
||||
@@ -341,22 +538,22 @@ public class PdfExportService {
|
||||
* champs sont integres au meme bloc — conditions de deblocage comprises — en dedupliquant
|
||||
* les textes identiques (les quetes converties du legacy dupliquent le chapitre).
|
||||
*/
|
||||
private void chapterFields(StringBuilder b, ChapterJpaEntity ch, QuestJpaEntity fused, Structure st) {
|
||||
illustrations(b, ch.getIllustrationImageIds());
|
||||
private void chapterFields(Ctx ctx, ChapterJpaEntity ch, QuestJpaEntity fused, Structure st) {
|
||||
illustrations(ctx, ch.getIllustrationImageIds());
|
||||
if (fused == null) {
|
||||
block(b, LABEL_DESCRIPTION, ch.getDescription());
|
||||
block(b, LABEL_OBJECTIFS_JOUEURS, ch.getPlayerObjectives());
|
||||
block(b, LABEL_ENJEUX_NARRATIFS, ch.getNarrativeStakes());
|
||||
box(b, CSS_SECRET, LABEL_NOTES_MJ, ch.getGmNotes());
|
||||
ctx.gmBlock(LABEL_DESCRIPTION, ch.getDescription());
|
||||
block(ctx.body, LABEL_OBJECTIFS_JOUEURS, ch.getPlayerObjectives());
|
||||
ctx.gmBlock(LABEL_ENJEUX_NARRATIFS, ch.getNarrativeStakes());
|
||||
ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, ch.getGmNotes());
|
||||
return;
|
||||
}
|
||||
illustrations(b, fused.getIllustrationImageIds());
|
||||
block(b, LABEL_DESCRIPTION, mergeField(ch.getDescription(), fused.getDescription()));
|
||||
block(b, "Conditions de déblocage", renderPrerequisites(fused.getPrerequisites(), st.questNames));
|
||||
block(b, "Nœuds liés", renderQuestNodes(fused, st));
|
||||
block(b, LABEL_OBJECTIFS_JOUEURS, mergeField(ch.getPlayerObjectives(), fused.getPlayerObjectives()));
|
||||
block(b, LABEL_ENJEUX_NARRATIFS, mergeField(ch.getNarrativeStakes(), fused.getNarrativeStakes()));
|
||||
box(b, CSS_SECRET, LABEL_NOTES_MJ, mergeField(ch.getGmNotes(), fused.getGmNotes()));
|
||||
illustrations(ctx, fused.getIllustrationImageIds());
|
||||
ctx.gmBlock(LABEL_DESCRIPTION, mergeField(ch.getDescription(), fused.getDescription()));
|
||||
ctx.gmBlock(LABEL_CONDITIONS, renderPrerequisites(fused.getPrerequisites(), st.questNames));
|
||||
ctx.gmBlock(LABEL_NOEUDS, renderQuestNodes(fused, st));
|
||||
block(ctx.body, LABEL_OBJECTIFS_JOUEURS, mergeField(ch.getPlayerObjectives(), fused.getPlayerObjectives()));
|
||||
ctx.gmBlock(LABEL_ENJEUX_NARRATIFS, mergeField(ch.getNarrativeStakes(), fused.getNarrativeStakes()));
|
||||
ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, mergeField(ch.getGmNotes(), fused.getGmNotes()));
|
||||
}
|
||||
|
||||
/** Deux sources pour un meme champ : garde la non-vide, ou les deux si differentes. */
|
||||
@@ -377,42 +574,43 @@ public class PdfExportService {
|
||||
b.append("<h1 class=\"part\" id=\"part-narrative\">Scènes</h1>");
|
||||
ctx.addToc(0, "Scènes", ANCHOR_PART_NARRATIVE);
|
||||
|
||||
illustrations(b, arc.getIllustrationImageIds());
|
||||
block(b, LABEL_DESCRIPTION, arc.getDescription());
|
||||
block(b, "Themes", arc.getThemes());
|
||||
block(b, "Enjeux", arc.getStakes());
|
||||
block(b, "Recompenses", arc.getRewards());
|
||||
block(b, "Resolution", arc.getResolution());
|
||||
box(b, CSS_SECRET, LABEL_NOTES_MJ, arc.getGmNotes());
|
||||
chapterFields(b, ch, st.questByContainerChapter.get(ch.getId()), st);
|
||||
arcFields(ctx, arc);
|
||||
chapterFields(ctx, ch, st.questByContainerChapter.get(ch.getId()), st);
|
||||
|
||||
StringBuilder scBms = new StringBuilder();
|
||||
for (SceneJpaEntity sc : st.scenesByChapter.get(ch.getId())) {
|
||||
ctx.addToc(1, sc.getName(), "scene-" + sc.getId());
|
||||
scBms.append(bookmark(sc.getName(), "scene-" + sc.getId(), ""));
|
||||
scene(b, sc, st);
|
||||
scene(ctx, sc, st);
|
||||
ctx.scenes++;
|
||||
}
|
||||
ctx.bookmarks.append(bookmark("Scènes", ANCHOR_PART_NARRATIVE, scBms.toString()));
|
||||
}
|
||||
|
||||
private void scene(StringBuilder b, SceneJpaEntity sc, Structure st) {
|
||||
/**
|
||||
* Une scene. Version joueurs : seuls le contexte (lieu, moment), l'ambiance, le texte a
|
||||
* lire, les illustrations et les cartes restent — resume, secrets, consequences, sorties
|
||||
* et combats sont reserves au MJ.
|
||||
*/
|
||||
private void scene(Ctx ctx, SceneJpaEntity sc, Structure st) {
|
||||
StringBuilder b = ctx.body;
|
||||
b.append("<div class=\"scene\" id=\"scene-").append(sc.getId()).append("\"><div class=\"scene-head\">")
|
||||
.append("<span class=\"eyebrow\">Scène</span>")
|
||||
.append(esc(sc.getName())).append(DIV_CLOSE);
|
||||
sceneMeta(b, sc);
|
||||
ctx.gmBlock("Résumé", sc.getDescription());
|
||||
block(b, "Ambiance", sc.getAtmosphere(), "ambiance");
|
||||
box(b, "readaloud", "À lire aux joueurs", sc.getPlayerNarration());
|
||||
box(b, CSS_SECRET, "Notes secrètes MJ", sc.getGmSecretNotes());
|
||||
block(b, "Choix & consequences", sc.getChoicesConsequences());
|
||||
block(b, "Sorties", renderSceneBranches(sc.getBranches(), st));
|
||||
ctx.gmBox(CSS_SECRET, "Notes secrètes MJ", sc.getGmSecretNotes());
|
||||
ctx.gmBlock("Choix et conséquences", sc.getChoicesConsequences());
|
||||
ctx.gmBlock("Sorties", renderSceneBranches(sc.getBranches(), st));
|
||||
// Combat : difficulte + ennemis de la rencontre (refs bestiaire resolues en noms
|
||||
// + texte libre) dans le meme encadre rouge.
|
||||
box(b, "combat", "Combat", joinNonBlank(sc.getCombatDifficulty(),
|
||||
ctx.gmBox("combat", "Combat", joinNonBlank(sc.getCombatDifficulty(),
|
||||
enemyLines(sc.getEnemyIds(), sc.getEnemies(), st)));
|
||||
illustrations(b, sc.getIllustrationImageIds());
|
||||
sceneBattlemaps(b, sc);
|
||||
rooms(b, sc, st);
|
||||
illustrations(ctx, sc.getIllustrationImageIds());
|
||||
sceneBattlemaps(ctx, sc);
|
||||
rooms(ctx, sc, st);
|
||||
b.append(DIV_CLOSE);
|
||||
}
|
||||
|
||||
@@ -438,19 +636,23 @@ public class PdfExportService {
|
||||
* Battlemaps (images uniquement ; les videos ne sont pas rendables en PDF). Le libellé
|
||||
* de la variante (Jour/Nuit…) est rendu en légende sous l'image.
|
||||
*/
|
||||
private void sceneBattlemaps(StringBuilder b, SceneJpaEntity sc) {
|
||||
private void sceneBattlemaps(Ctx ctx, SceneJpaEntity sc) {
|
||||
if (sc.getBattlemaps() == null) return;
|
||||
for (var bm : sc.getBattlemaps()) {
|
||||
PdfImage battlemap = imageEncoder.fileImage(bm.mediaFileId());
|
||||
if (battlemap == null) continue;
|
||||
String caption = bm.label() == null || bm.label().isBlank()
|
||||
? "Battlemap" : "Battlemap — " + bm.label();
|
||||
illustration(b, battlemap, caption);
|
||||
illustration(ctx, battlemap, caption);
|
||||
}
|
||||
}
|
||||
|
||||
/** Pieces explorables de la scene (donjon, crypte...) — sous-blocs ambres. */
|
||||
private void rooms(StringBuilder b, SceneJpaEntity sc, Structure st) {
|
||||
/**
|
||||
* Pieces explorables de la scene (donjon, crypte...) — sous-blocs ambres. Version joueurs :
|
||||
* nom, plan et illustrations seulement.
|
||||
*/
|
||||
private void rooms(Ctx ctx, SceneJpaEntity sc, Structure st) {
|
||||
StringBuilder b = ctx.body;
|
||||
if (sc.getRooms() == null || sc.getRooms().isEmpty()) return;
|
||||
List<Room> rooms = new ArrayList<>(sc.getRooms());
|
||||
rooms.sort(java.util.Comparator.comparingInt(Room::getOrder));
|
||||
@@ -461,15 +663,15 @@ public class PdfExportService {
|
||||
b.append("<div class=\"room\"><div class=\"room-head\"><span class=\"eyebrow\">Pièce");
|
||||
if (r.getFloor() != null) b.append(" · Étage ").append(r.getFloor());
|
||||
b.append(SPAN_CLOSE).append(esc(r.getName())).append(DIV_CLOSE);
|
||||
block(b, LABEL_DESCRIPTION, r.getDescription());
|
||||
box(b, "combat", "Ennemis", enemyLines(r.getEnemyIds(), r.getEnemies(), st));
|
||||
block(b, "Butin", r.getLoot());
|
||||
block(b, "Pièges", r.getTraps());
|
||||
box(b, CSS_SECRET, LABEL_NOTES_MJ, r.getGmNotes());
|
||||
ctx.gmBlock(LABEL_DESCRIPTION, r.getDescription());
|
||||
ctx.gmBox("combat", "Ennemis", enemyLines(r.getEnemyIds(), r.getEnemies(), st));
|
||||
ctx.gmBlock("Butin", r.getLoot());
|
||||
ctx.gmBlock("Pièges", r.getTraps());
|
||||
ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, r.getGmNotes());
|
||||
PdfImage map = imageEncoder.image(r.getMapImageId(), PdfImageEncoder.ILLUSTRATION_MAX);
|
||||
if (map != null) illustration(b, map, "Plan — " + r.getName());
|
||||
illustrations(b, r.getIllustrationImageIds());
|
||||
if (r.getBranches() != null && !r.getBranches().isEmpty()) {
|
||||
if (map != null) illustration(ctx, map, "Plan — " + r.getName());
|
||||
illustrations(ctx, r.getIllustrationImageIds());
|
||||
if (ctx.gm && r.getBranches() != null && !r.getBranches().isEmpty()) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
for (RoomBranch br : r.getBranches()) {
|
||||
parts.add(branchLine(roomNames.getOrDefault(br.targetRoomId(), "?"),
|
||||
@@ -556,13 +758,13 @@ public class PdfExportService {
|
||||
StringBuilder b = ctx.body;
|
||||
b.append("<div class=\"chapter\"><div class=\"chapter-head\" id=\"quest-").append(q.getId())
|
||||
.append("\"><span class=\"eyebrow\">Quête</span>").append(esc(q.getName())).append(DIV_CLOSE);
|
||||
illustrations(b, q.getIllustrationImageIds());
|
||||
block(b, LABEL_DESCRIPTION, q.getDescription());
|
||||
block(b, "Conditions de déblocage", renderPrerequisites(q.getPrerequisites(), st.questNames));
|
||||
block(b, "Nœuds liés", renderQuestNodes(q, st));
|
||||
illustrations(ctx, q.getIllustrationImageIds());
|
||||
ctx.gmBlock(LABEL_DESCRIPTION, q.getDescription());
|
||||
ctx.gmBlock(LABEL_CONDITIONS, renderPrerequisites(q.getPrerequisites(), st.questNames));
|
||||
ctx.gmBlock(LABEL_NOEUDS, renderQuestNodes(q, st));
|
||||
block(b, LABEL_OBJECTIFS_JOUEURS, q.getPlayerObjectives());
|
||||
block(b, LABEL_ENJEUX_NARRATIFS, q.getNarrativeStakes());
|
||||
box(b, CSS_SECRET, LABEL_NOTES_MJ, q.getGmNotes());
|
||||
ctx.gmBlock(LABEL_ENJEUX_NARRATIFS, q.getNarrativeStakes());
|
||||
ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, q.getGmNotes());
|
||||
// Scenes de ses conteneurs (arc SYSTEM, masque de la narration) : c'est ICI
|
||||
// que vit le contenu jouable d'une quete libre.
|
||||
questContainerScenes(ctx, q, st);
|
||||
@@ -574,7 +776,7 @@ public class PdfExportService {
|
||||
Set<String> containers = st.containerChapterIds(q);
|
||||
for (QuestNodeRef n : q.getNodes()) {
|
||||
for (SceneJpaEntity sc : containerScenes(n, containers, st)) {
|
||||
scene(ctx.body, sc, st);
|
||||
scene(ctx, sc, st);
|
||||
ctx.scenes++;
|
||||
}
|
||||
}
|
||||
@@ -705,7 +907,7 @@ public class PdfExportService {
|
||||
fBms.append(bookmark(label, anchor, ""));
|
||||
b.append(H3_FOLDER_OPEN).append(anchor).append("\">").append(esc(label)).append("</h3>");
|
||||
rows.sort(java.util.Comparator.comparingInt(PersonaRow::order));
|
||||
for (PersonaRow r : rows) personaCard(b, r, template, enemy);
|
||||
for (PersonaRow r : rows) personaCard(ctx, r, template, enemy);
|
||||
}
|
||||
|
||||
private void personaUngroupedSection(Ctx ctx, List<TemplateField> template, boolean enemy, String anchor,
|
||||
@@ -717,10 +919,11 @@ public class PdfExportService {
|
||||
b.append(H3_FOLDER_OPEN).append(anchor).append("\">Sans dossier</h3>");
|
||||
}
|
||||
ungrouped.sort(java.util.Comparator.comparingInt(PersonaRow::order));
|
||||
for (PersonaRow r : ungrouped) personaCard(b, r, template, enemy);
|
||||
for (PersonaRow r : ungrouped) personaCard(ctx, r, template, enemy);
|
||||
}
|
||||
|
||||
private void personaCard(StringBuilder b, PersonaRow r, List<TemplateField> template, boolean enemy) {
|
||||
private void personaCard(Ctx ctx, PersonaRow r, List<TemplateField> template, boolean enemy) {
|
||||
StringBuilder b = ctx.body;
|
||||
// Mise en page en TABLE (portrait | contenu) : openhtmltopdf gere mal le float
|
||||
// + overflow (le texte se superposait au portrait).
|
||||
b.append("<div class=\"card\"><table class=\"persona\"><tr>");
|
||||
@@ -735,7 +938,7 @@ public class PdfExportService {
|
||||
if (notBlank(r.level())) b.append(" <span class=\"level\">Niv. ").append(esc(r.level())).append(SPAN_CLOSE);
|
||||
b.append(DIV_CLOSE);
|
||||
|
||||
renderFields(b, template, r.values(), r.keyValueValues(), r.imageValues(), null);
|
||||
renderFields(ctx, template, r.values(), r.keyValueValues(), r.imageValues(), null);
|
||||
|
||||
if (enemy && r.foundryStats() != null) {
|
||||
Map<String, String> clean = cleanStats(r.foundryStats());
|
||||
@@ -757,6 +960,26 @@ public class PdfExportService {
|
||||
private static final Set<String> STAT_NOISE_VALUES = Set.of("0", "0.0", "false", "none", "null", "", "-", "—");
|
||||
/** Premier segment de chemin a elaguer du libelle (purement structurel). */
|
||||
private static final Set<String> STAT_DROP_PREFIX = Set.of("attributes", "details", "system", "data");
|
||||
/** Segments sans information pour un lecteur ("hp value" -> "PV"). */
|
||||
private static final Set<String> STAT_DROP_SEGMENTS = Set.of("attributes", "abilities", "details",
|
||||
"system", "data", "value", "traits", "skills");
|
||||
/**
|
||||
* Abreviations et termes courants des systemes Foundry (dnd5e, pf2e...) traduits pour
|
||||
* un livret francais ; un segment inconnu garde son libelle humanise.
|
||||
*/
|
||||
private static final Map<String, String> STAT_TERMS = Map.ofEntries(
|
||||
Map.entry("hp", "PV"), Map.entry("ac", "CA"), Map.entry("cr", "FP"),
|
||||
Map.entry("str", "FOR"), Map.entry("dex", "DEX"), Map.entry("con", "CON"),
|
||||
Map.entry("int", "INT"), Map.entry("wis", "SAG"), Map.entry("cha", "CHA"),
|
||||
Map.entry("max", "max"), Map.entry("temp", "temp."), Map.entry("level", "niveau"),
|
||||
Map.entry("xp", "XP"), Map.entry("init", "initiative"), Map.entry("prof", "maîtrise"),
|
||||
Map.entry("movement", "déplacement"), Map.entry("speed", "vitesse"),
|
||||
Map.entry("walk", "marche"), Map.entry("fly", "vol"), Map.entry("swim", "nage"),
|
||||
Map.entry("climb", "escalade"), Map.entry("burrow", "fouissement"),
|
||||
Map.entry("senses", "sens"), Map.entry("darkvision", "vision dans le noir"),
|
||||
Map.entry("languages", "langues"), Map.entry("alignment", "alignement"),
|
||||
Map.entry("type", "type"), Map.entry("size", "taille"), Map.entry("perception", "perception"),
|
||||
Map.entry("spelldc", "DD des sorts"), Map.entry("dc", "DD"), Map.entry("creaturetype", "type de créature"));
|
||||
|
||||
/**
|
||||
* Nettoie le snapshot de stats Foundry pour le livret : retire le bruit (valeurs
|
||||
@@ -782,13 +1005,24 @@ public class PdfExportService {
|
||||
return v;
|
||||
}
|
||||
|
||||
/** "attributes.hp.value" -> "Hp value" ; "details.creatureType" -> "Creature type". */
|
||||
private static String humanizeStatKey(String key) {
|
||||
/**
|
||||
* "attributes.hp.value" -> "PV" ; "abilities.str.value" -> "FOR" ; "attributes.hp.max" ->
|
||||
* "PV max" ; "details.cr" -> "FP" ; segment inconnu : camelCase humanise ("Creature type").
|
||||
*/
|
||||
static String humanizeStatKey(String key) {
|
||||
String[] parts = key.split("\\.");
|
||||
int start = (parts.length > 1 && STAT_DROP_PREFIX.contains(parts[0].toLowerCase())) ? 1 : 0;
|
||||
String s = String.join(" ", Arrays.asList(parts).subList(start, parts.length));
|
||||
s = s.replaceAll("([a-z0-9])([A-Z])", "$1 $2").toLowerCase().trim(); // camelCase -> mots
|
||||
return s.isEmpty() ? key : Character.toUpperCase(s.charAt(0)) + s.substring(1);
|
||||
List<String> words = new ArrayList<>();
|
||||
for (String part : Arrays.asList(parts).subList(start, parts.length)) {
|
||||
String lower = part.toLowerCase(Locale.ROOT);
|
||||
if (STAT_DROP_SEGMENTS.contains(lower) && parts.length - start > 1) continue;
|
||||
String term = STAT_TERMS.get(lower);
|
||||
words.add(term != null ? term
|
||||
: part.replaceAll("([a-z0-9])([A-Z])", "$1 $2").toLowerCase(Locale.ROOT).trim()); // camelCase -> mots
|
||||
}
|
||||
String s = String.join(" ", words).trim();
|
||||
if (s.isEmpty()) return key;
|
||||
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
|
||||
}
|
||||
|
||||
// ----- Tables aleatoires (le contenu le plus « papier » du livret) -----
|
||||
@@ -847,13 +1081,17 @@ public class PdfExportService {
|
||||
|
||||
// ----- Lore (pages groupees par dossier) -----
|
||||
|
||||
private void lore(Ctx ctx, CampaignJpaEntity campaign) {
|
||||
private void lore(Ctx ctx, CampaignJpaEntity campaign, Structure st) {
|
||||
String loreId = campaign.getLoreId();
|
||||
if (loreId == null || loreId.isBlank()) return;
|
||||
Long lid;
|
||||
try { lid = Long.parseLong(loreId); } catch (NumberFormatException ex) { return; }
|
||||
|
||||
List<PageJpaEntity> pages = pageRepo.findByLoreId(lid);
|
||||
List<PageJpaEntity> pages = new ArrayList<>(pageRepo.findByLoreId(lid));
|
||||
if (ctx.opt.loreScope() == LoreScope.LINKED) {
|
||||
Set<String> linked = linkedPageIds(campaign, st);
|
||||
pages.removeIf(p -> !linked.contains(String.valueOf(p.getId())));
|
||||
}
|
||||
if (pages.isEmpty()) return;
|
||||
ctx.lorePages = pages.size();
|
||||
|
||||
@@ -881,17 +1119,42 @@ public class PdfExportService {
|
||||
b.append(H3_FOLDER_OPEN).append(anchor).append("\">").append(esc(label)).append("</h3>");
|
||||
e.getValue().sort(java.util.Comparator.comparingInt(PageJpaEntity::getOrder));
|
||||
for (PageJpaEntity p : e.getValue()) {
|
||||
b.append("<div class=\"card\"><div class=\"card-body\"><div class=\"persona-name\">")
|
||||
b.append("<div class=\"card flow\"><div class=\"card-body\"><div class=\"persona-name\">")
|
||||
.append(esc(p.getTitle())).append(DIV_CLOSE);
|
||||
List<TemplateField> tpl = p.getTemplateId() != null
|
||||
? fieldsOf(templates.get(p.getTemplateId())) : null;
|
||||
renderFields(b, tpl, p.getValues(), p.getKeyValueValues(), p.getImageValues(), p.getTableValues());
|
||||
renderFields(ctx, tpl, p.getValues(), p.getKeyValueValues(), p.getImageValues(), p.getTableValues());
|
||||
b.append("</div></div>");
|
||||
}
|
||||
}
|
||||
ctx.bookmarks.append(bookmark("Lore", "part-lore", fBms.toString()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Pages de lore citees par le contenu de la campagne (pages liees des arcs, chapitres,
|
||||
* scenes, quetes et PNJ) : l'export « pages liees » evite de livrer tout l'univers,
|
||||
* secrets des autres campagnes compris.
|
||||
*/
|
||||
private Set<String> linkedPageIds(CampaignJpaEntity campaign, Structure st) {
|
||||
Set<String> ids = new HashSet<>();
|
||||
for (ArcJpaEntity a : st.arcs) addAllNonNull(ids, a.getRelatedPageIds());
|
||||
for (List<ChapterJpaEntity> chs : st.chaptersByArc.values()) {
|
||||
for (ChapterJpaEntity ch : chs) addAllNonNull(ids, ch.getRelatedPageIds());
|
||||
}
|
||||
for (List<SceneJpaEntity> scs : st.scenesByChapter.values()) {
|
||||
for (SceneJpaEntity sc : scs) addAllNonNull(ids, sc.getRelatedPageIds());
|
||||
}
|
||||
for (QuestJpaEntity q : st.quests) addAllNonNull(ids, q.getRelatedPageIds());
|
||||
for (NpcJpaEntity n : npcRepo.findByCampaignIdOrderByOrderAsc(campaign.getId())) {
|
||||
addAllNonNull(ids, n.getRelatedPageIds());
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static void addAllNonNull(Set<String> into, List<String> values) {
|
||||
if (values != null) into.addAll(values);
|
||||
}
|
||||
|
||||
private String nodePath(Long nodeId, Map<Long, LoreNodeJpaEntity> nodes) {
|
||||
if (nodeId == null) return "";
|
||||
Deque<String> parts = new ArrayDeque<>();
|
||||
@@ -908,10 +1171,11 @@ public class PdfExportService {
|
||||
|
||||
// ----- Rendu des champs pilotes par template -----
|
||||
|
||||
private void renderFields(StringBuilder b, List<TemplateField> template, Map<String, String> values,
|
||||
private void renderFields(Ctx ctx, List<TemplateField> template, Map<String, String> values,
|
||||
Map<String, Map<String, String>> keyValueValues,
|
||||
Map<String, List<String>> imageValues,
|
||||
Map<String, List<Map<String, String>>> tableValues) {
|
||||
StringBuilder b = ctx.body;
|
||||
// Repli : pas de template -> paires brutes cle=valeur.
|
||||
if (template == null || template.isEmpty()) {
|
||||
if (values != null) {
|
||||
@@ -921,18 +1185,19 @@ public class PdfExportService {
|
||||
}
|
||||
for (TemplateField f : template) {
|
||||
if (f == null || f.getName() == null || f.getType() == null) continue;
|
||||
renderField(b, f, values, keyValueValues, imageValues, tableValues);
|
||||
renderField(ctx, f, values, keyValueValues, imageValues, tableValues);
|
||||
}
|
||||
}
|
||||
|
||||
private void renderField(StringBuilder b, TemplateField f, Map<String, String> values,
|
||||
private void renderField(Ctx ctx, TemplateField f, Map<String, String> values,
|
||||
Map<String, Map<String, String>> keyValueValues,
|
||||
Map<String, List<String>> imageValues,
|
||||
Map<String, List<Map<String, String>>> tableValues) {
|
||||
StringBuilder b = ctx.body;
|
||||
switch (f.getType()) {
|
||||
case TEXT, NUMBER -> block(b, f.getName(), values != null ? values.get(f.getName()) : null);
|
||||
case KEY_VALUE_LIST -> renderKeyValueField(b, f, keyValueValues);
|
||||
case IMAGE -> illustrations(b, imageValues != null ? imageValues.get(f.getName()) : null);
|
||||
case IMAGE -> illustrations(ctx, imageValues != null ? imageValues.get(f.getName()) : null);
|
||||
case TABLE -> renderTableField(b, f, tableValues);
|
||||
}
|
||||
}
|
||||
@@ -1012,11 +1277,11 @@ public class PdfExportService {
|
||||
// ----- Illustrations -----
|
||||
|
||||
/** Galerie d'illustrations (liste d'ids d'images) -> blocs image centres, hauteur bornee. */
|
||||
private void illustrations(StringBuilder b, List<String> imageIds) {
|
||||
private void illustrations(Ctx ctx, List<String> imageIds) {
|
||||
if (imageIds == null) return;
|
||||
for (String id : imageIds) {
|
||||
PdfImage img = imageEncoder.image(id, PdfImageEncoder.ILLUSTRATION_MAX);
|
||||
if (img != null) illustration(b, img, null);
|
||||
if (img != null) illustration(ctx, img, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1024,9 +1289,11 @@ public class PdfExportService {
|
||||
* Une illustration centree, avec legende optionnelle. La largeur est calculee pour que
|
||||
* la hauteur affichee reste bornee : une image tres verticale ne mange plus la page.
|
||||
*/
|
||||
private void illustration(StringBuilder b, PdfImage img, String caption) {
|
||||
double widthCm = Math.min(CONTENT_WIDTH_CM,
|
||||
ILLUSTRATION_MAX_HEIGHT_CM * img.w() / img.h());
|
||||
private void illustration(Ctx ctx, PdfImage img, String caption) {
|
||||
StringBuilder b = ctx.body;
|
||||
// Hauteur bornee proportionnellement au format (A5 : environ 7,8 cm).
|
||||
double maxHeight = ILLUSTRATION_MAX_HEIGHT_CM * ctx.opt.format().widthCm / PdfExportOptions.PageFormat.A4.widthCm;
|
||||
double widthCm = Math.min(ctx.contentWidthCm(), maxHeight * img.w() / img.h());
|
||||
b.append("<div class=\"illus\"><img style=\"width:").append(cm(widthCm))
|
||||
.append("\" src=\"").append(img.uri()).append("\"/>");
|
||||
if (caption != null) {
|
||||
@@ -1053,15 +1320,25 @@ public class PdfExportService {
|
||||
return t != null ? t.getFields() : null;
|
||||
}
|
||||
|
||||
/** CSS final : en-tete courant renseigne avec le nom de la campagne. */
|
||||
/**
|
||||
* CSS final : en-tete courant (nom de la campagne), format de page (taille, marges,
|
||||
* corps du texte) et, en mode impression, la feuille sans aplats ajoutee en dernier.
|
||||
*/
|
||||
// S125 : faux positif — commentaire explicatif (prose), pas de code mort.
|
||||
@SuppressWarnings("java:S125")
|
||||
private static String cssFor(String campaignName) {
|
||||
private static String cssFor(String campaignName, PdfExportOptions opt) {
|
||||
String header = campaignName == null ? "" : campaignName.trim();
|
||||
if (header.length() > 70) header = header.substring(0, 69) + "…";
|
||||
PdfExportOptions.PageFormat f = opt.format();
|
||||
String margins = cm(f.marginTopCm) + " " + cm(f.marginSideCm) + " " + cm(f.marginBottomCm);
|
||||
// Echappement CSS (chaine entre quotes) PUIS XML : le CSS vit dans <style>,
|
||||
// du PCDATA — un '&' ou '<' brut casserait le parse du document entier.
|
||||
return CSS.replace("__HEADER__", esc(header.replace("\\", "\\\\").replace("'", "\\'")));
|
||||
String css = CSS.replace("__HEADER__", esc(header.replace("\\", "\\\\").replace("'", "\\'")))
|
||||
.replace("__PAGE_SIZE__", f.cssSize)
|
||||
.replace("__PAGE_MARGIN__", margins)
|
||||
.replace("__BODY_PT__", String.format(Locale.ROOT, "%.1fpt", f.bodyPt));
|
||||
if (f == PdfExportOptions.PageFormat.A5) css += A5_CSS;
|
||||
return opt.printFriendly() ? css + PRINT_CSS : css;
|
||||
}
|
||||
|
||||
// CSS print (CSS 2.1 + paged media supporte par openhtmltopdf : pas de flexbox/grid).
|
||||
@@ -1071,12 +1348,16 @@ public class PdfExportService {
|
||||
// Contenu dans resources/pdf/export.css (extrait pour alleger cette classe).
|
||||
// S125 : faux positif — le bloc ci-dessus est de la prose explicative, pas du code mort.
|
||||
@SuppressWarnings("java:S125")
|
||||
private static final String CSS = loadCss();
|
||||
private static final String CSS = loadCss("/pdf/export.css");
|
||||
/** Surcharges « impression » : fonds blancs, filets conserves (economie d'encre). */
|
||||
private static final String PRINT_CSS = loadCss("/pdf/export-print.css");
|
||||
/** Surcharges A5 : couverture et titres resserres pour une page etroite. */
|
||||
private static final String A5_CSS = loadCss("/pdf/export-a5.css");
|
||||
|
||||
private static String loadCss() {
|
||||
try (InputStream in = PdfExportService.class.getResourceAsStream("/pdf/export.css")) {
|
||||
private static String loadCss(String resource) {
|
||||
try (InputStream in = PdfExportService.class.getResourceAsStream(resource)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("Ressource pdf/export.css introuvable dans le classpath");
|
||||
throw new IllegalStateException("Ressource " + resource + " introuvable dans le classpath");
|
||||
}
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -139,6 +139,20 @@ final class PdfHtml {
|
||||
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) {
|
||||
StringBuilder p = new StringBuilder();
|
||||
for (int i = 0; i < t.lines().size(); i++) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.CampaignService;
|
||||
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.mapper.CampaignMapper;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -72,6 +73,18 @@ public class CampaignController {
|
||||
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}")
|
||||
public ResponseEntity<CampaignDTO> updateCampaign(@PathVariable String id, @RequestBody CampaignDTO campaignDTO) {
|
||||
Campaign updatedCampaign = campaignService.updateCampaign(
|
||||
|
||||
+15
-3
@@ -1,5 +1,6 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions;
|
||||
import com.loremind.infrastructure.transfer.pdf.PdfExportService;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
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.PathVariable;
|
||||
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.server.ResponseStatusException;
|
||||
|
||||
@@ -18,6 +20,10 @@ import java.util.NoSuchElementException;
|
||||
* <p>
|
||||
* {@code GET /api/campaigns/{campaignId}/pdf-export} -> application/pdf (structure
|
||||
* 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
|
||||
@RequestMapping("/api/campaigns/{campaignId}/pdf-export")
|
||||
@@ -30,17 +36,23 @@ public class PdfExportController {
|
||||
}
|
||||
|
||||
@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;
|
||||
String name;
|
||||
try {
|
||||
name = pdfExportService.campaignName(campaignId);
|
||||
pdf = pdfExportService.export(campaignId);
|
||||
pdf = pdfExportService.export(campaignId, options);
|
||||
} catch (NoSuchElementException e) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
}
|
||||
|
||||
String filename = slug(name) + ".pdf";
|
||||
String filename = slug(name) + (options.gmContent() ? "" : "_joueurs") + ".pdf";
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||
.contentType(MediaType.APPLICATION_PDF)
|
||||
|
||||
@@ -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,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;
|
||||
letter-spacing: .22em; text-transform: uppercase; color: #b3a9d6; }
|
||||
@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 */
|
||||
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; }
|
||||
/* --- Couverture --- */
|
||||
.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; }
|
||||
.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;
|
||||
letter-spacing: .04em; color: #2e2a4a; margin: .45cm 0 0; }
|
||||
.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-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 --- */
|
||||
.toc-page { page-break-after: always; }
|
||||
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; }
|
||||
.scene-meta { font-style: italic; color: #6d6787; margin: -.05cm 0 .16cm; }
|
||||
/* --- 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;
|
||||
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;
|
||||
border-radius: 0; font-style: italic; }
|
||||
.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) --- */
|
||||
.card { page-break-inside: avoid; border: 1pt solid #e3e0ee; border-radius: 4pt;
|
||||
padding: .32cm .4cm; margin: .32cm 0; background: #fcfcfe; }
|
||||
.card.flow { page-break-inside: auto; }
|
||||
.card-body { display: block; }
|
||||
.persona { width: 100%; border-collapse: collapse; }
|
||||
.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 tbody th { width: 32%; color: #555; font-weight: bold; background: #f8f7fc; }
|
||||
.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 .entry-detail { color: #555; font-size: 8.5pt; }
|
||||
.stat-array { border-collapse: collapse; font-family: 'DejaVu Sans', sans-serif; font-size: 9pt;
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.loremind.application.campaigncontext;
|
||||
import com.loremind.application.playcontext.PlaythroughService;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
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.Scene;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
@@ -407,4 +408,37 @@ class CampaignServiceTest {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> 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()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -1,5 +1,6 @@
|
||||
package com.loremind.infrastructure.transfer;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.structure.Room;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||
import com.loremind.domain.files.ports.FileStorage;
|
||||
@@ -90,7 +91,10 @@ class ImageRefRemapOnImportTest {
|
||||
String oldFileRef = String.valueOf(file.getId());
|
||||
|
||||
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()
|
||||
.name("Remap Npc").campaignId(campaign.getId())
|
||||
@@ -149,6 +153,13 @@ class ImageRefRemapOnImportTest {
|
||||
String newFileRef = String.valueOf(newFile.getId());
|
||||
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.
|
||||
NpcJpaEntity importedNpc = npcRepo.findAll().stream()
|
||||
.filter(n -> "Remap Npc".equals(n.getName()) && !n.getId().equals(originalNpcId))
|
||||
|
||||
@@ -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é");
|
||||
}
|
||||
}
|
||||
+21
-1
@@ -1,5 +1,6 @@
|
||||
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.LinkType;
|
||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||
@@ -83,7 +84,20 @@ class PdfExportPreviewTest {
|
||||
.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"
|
||||
+ "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 -------------
|
||||
when(arcRepo.findByCampaignId(1L)).thenReturn(List.of(
|
||||
@@ -379,6 +393,12 @@ class PdfExportPreviewTest {
|
||||
Files.createDirectories(out.getParent());
|
||||
Files.write(out, pdf);
|
||||
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. */
|
||||
|
||||
+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\""));
|
||||
}
|
||||
}
|
||||
+34
@@ -92,4 +92,38 @@ class CampaignControllerTest {
|
||||
mockMvc.perform(delete("/api/campaigns/{id}", saved.getId()))
|
||||
.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\""));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ export const routes: Routes = [
|
||||
{ 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/: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/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) },
|
||||
|
||||
@@ -322,6 +322,15 @@
|
||||
</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). -->
|
||||
<app-foundry-export-dialog
|
||||
[open]="foundryDialogOpen"
|
||||
|
||||
@@ -11,7 +11,7 @@ import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { forkJoin, of, Observable } from 'rxjs';
|
||||
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 { GameSystemService } from '../../../services/game-system.service';
|
||||
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 { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play-block.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({
|
||||
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',
|
||||
styleUrls: ['./campaign-detail.component.scss']
|
||||
})
|
||||
@@ -67,6 +69,10 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
foundryDialogOpen = false;
|
||||
/** Export PDF en cours (anti double-clic). */
|
||||
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;
|
||||
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 {
|
||||
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;
|
||||
this.exportingPdf = true;
|
||||
const name = this.campaign.name;
|
||||
this.campaignService.exportPdf(this.campaign.id).subscribe({
|
||||
this.campaignService.exportPdf(this.campaign.id, opts).subscribe({
|
||||
next: (blob) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
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);
|
||||
const suffix = opts.edition === 'player' ? '_joueurs' : '';
|
||||
downloadBlob(blob, `${safeFileName(name, 'campagne')}${suffix}.pdf`);
|
||||
this.exportingPdf = false;
|
||||
this.pdfDialogOpen = false;
|
||||
},
|
||||
error: (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. */
|
||||
dropArc(event: CdkDragDrop<Arc[]>): void {
|
||||
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'], 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']);
|
||||
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,34 @@
|
||||
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), sans bestiaire, quêtes ni tables.
|
||||
*/
|
||||
export function editionPreset(edition: 'gm' | 'player'): Pick<PdfExportChoice, 'sections' | 'lore'> {
|
||||
return edition === 'player'
|
||||
? { sections: new Set<PdfSection>(['NARRATIVE', 'NPCS', 'LORE']), 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 };
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { CampaignReadinessAssessment } from './readiness.model';
|
||||
import { Npc } from './npc.model';
|
||||
import { RandomTable } from './random-table.model';
|
||||
import { Enemy } from './enemy.model';
|
||||
import { PdfExportOptions } from './pdf-export.model';
|
||||
|
||||
/**
|
||||
* Arbre de campagne AGRÉGÉ (une seule requête HTTP) — miroir de CampaignTreeDTO.
|
||||
@@ -36,6 +37,30 @@ export interface FoundryExportOptions {
|
||||
tables: boolean;
|
||||
}
|
||||
|
||||
export { PDF_SECTIONS } from './pdf-export.model';
|
||||
export type { PdfSection, PdfExportOptions } from './pdf-export.model';
|
||||
|
||||
/**
|
||||
* Fiche « Publication » d'une campagne (module à vendre ou à partager) : couverture,
|
||||
* page technique, introduction pour le MJ et page de crédits du PDF. Texte libre.
|
||||
*/
|
||||
export interface CampaignPublication {
|
||||
subtitle?: string | null;
|
||||
author?: string | null;
|
||||
system?: string | null;
|
||||
levels?: string | null;
|
||||
players?: string | null;
|
||||
duration?: string | null;
|
||||
pitch?: string | null;
|
||||
gmBackground?: string | null;
|
||||
hooks?: string | null;
|
||||
contentWarnings?: string | null;
|
||||
credits?: string | null;
|
||||
legal?: string | null;
|
||||
version?: string | null;
|
||||
coverImageId?: string | null;
|
||||
}
|
||||
|
||||
/** Compte des entités qui seront supprimées en cascade avec la campagne. */
|
||||
export interface CampaignDeletionImpact {
|
||||
arcs: number;
|
||||
@@ -106,8 +131,25 @@ export class CampaignService {
|
||||
}
|
||||
|
||||
/** Génère et télécharge le livret PDF de la campagne. */
|
||||
exportPdf(id: string): Observable<Blob> {
|
||||
return this.http.get(`${this.apiUrl}/${id}/pdf-export`, { responseType: 'blob' });
|
||||
exportPdf(id: string, opts?: PdfExportOptions): Observable<Blob> {
|
||||
let params = new HttpParams();
|
||||
if (opts) {
|
||||
params = params
|
||||
.set('edition', opts.edition)
|
||||
.set('format', opts.format)
|
||||
.set('print', String(opts.print))
|
||||
.set('sections', opts.sections.join(','))
|
||||
.set('lore', opts.lore);
|
||||
}
|
||||
return this.http.get(`${this.apiUrl}/${id}/pdf-export`, { responseType: 'blob', params });
|
||||
}
|
||||
|
||||
getPublication(id: string): Observable<CampaignPublication> {
|
||||
return this.http.get<CampaignPublication>(`${this.apiUrl}/${id}/publication`);
|
||||
}
|
||||
|
||||
updatePublication(id: string, publication: CampaignPublication): Observable<CampaignPublication> {
|
||||
return this.http.put<CampaignPublication>(`${this.apiUrl}/${id}/publication`, publication);
|
||||
}
|
||||
|
||||
createCampaign(campaign: CampaignCreate): Observable<Campaign> {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Parties du livret PDF qu'on peut inclure ou non (miroir de PdfExportOptions.Section). */
|
||||
export type PdfSection = 'NARRATIVE' | 'QUESTS' | 'NPCS' | 'ENEMIES' | 'TABLES' | 'LORE';
|
||||
|
||||
/** Ordre canonique des parties dans le livret. */
|
||||
export const PDF_SECTIONS: PdfSection[] = ['NARRATIVE', 'QUESTS', 'NPCS', 'ENEMIES', 'TABLES', 'LORE'];
|
||||
|
||||
/**
|
||||
* Options de l'export PDF (modale) :
|
||||
* - edition : 'gm' = livret MJ complet ; 'player' = version joueurs sans aucun secret.
|
||||
* - format : A4, A5 ou US Letter.
|
||||
* - print : sans aplats de couleur (économie d'encre).
|
||||
* - sections : parties incluses.
|
||||
* - lore : toutes les pages du lore, ou seulement celles liées au contenu de la campagne.
|
||||
*/
|
||||
export interface PdfExportOptions {
|
||||
edition: 'gm' | 'player';
|
||||
format: 'A4' | 'A5' | 'LETTER';
|
||||
print: boolean;
|
||||
sections: PdfSection[];
|
||||
lore: 'ALL' | 'LINKED';
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Déclenche le téléchargement d'un fichier reçu en Blob (lien temporaire). */
|
||||
export function downloadBlob(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/** Nom de fichier sûr (alphanumérique, tirets, soulignés), comme côté serveur. */
|
||||
export function safeFileName(name: string | null | undefined, fallback: string): string {
|
||||
let slug = (name || '').trim().replace(/[^a-zA-Z0-9-_]+/g, '_');
|
||||
// Au plus un « _ » de bord après la fusion ci-dessus : retiré sans regex ancrée.
|
||||
if (slug.startsWith('_')) slug = slug.slice(1);
|
||||
if (slug.endsWith('_')) slug = slug.slice(0, -1);
|
||||
return slug || fallback;
|
||||
}
|
||||
@@ -2083,6 +2083,63 @@
|
||||
"example": "The guild is publicly exposed; or the PCs buy it out themselves; or the villages are lost and the next arc opens with the exodus.",
|
||||
"pitfall": "A single ending written in advance: the players' choices no longer matter. Prepare outcomes, not a script."
|
||||
}
|
||||
},
|
||||
"publication": {
|
||||
"pitch": {
|
||||
"title": "The adventure at a glance",
|
||||
"purpose": "Make people want to play in a few lines: the starting situation, what the characters will do and the mood. It's the text a GM reads before picking your module.",
|
||||
"questions": [
|
||||
"What situation troubles the characters at the start?",
|
||||
"What will they actually have to do: investigate, explore, protect, flee?",
|
||||
"Which image or detail sets this adventure apart?"
|
||||
],
|
||||
"example": "A tower thought long dead lights up again above Coldvale, in the middle of the autumn fair. The characters have three days to find out who is reviving its seals before the town falls into panic.",
|
||||
"pitfall": "Giving away the ending or the central secret. The pitch is a promise of play; the hidden truth belongs in the GM-only background."
|
||||
},
|
||||
"contentWarnings": {
|
||||
"title": "Content warnings",
|
||||
"purpose": "Warn the GM about difficult themes so they can talk about them with their table before playing, and adjust what needs adjusting.",
|
||||
"questions": [
|
||||
"Which themes might make players uncomfortable: graphic violence, death of a child, grief, possession, harassment…?",
|
||||
"Can a scene be played off-screen without breaking the adventure? Say so."
|
||||
],
|
||||
"example": "Physical violence, death of a secondary character, possession. The crypt scene can be summarised rather than described.",
|
||||
"pitfall": "Leaving it empty for fear of spoiling the surprise. Naming a theme reveals nothing of the plot, and a prepared GM runs it better."
|
||||
},
|
||||
"gmBackground": {
|
||||
"title": "Hidden background",
|
||||
"purpose": "What the GM needs to know and the players don't: what really happened, who wants what, and what happens if nobody steps in.",
|
||||
"questions": [
|
||||
"What happened before the characters arrived?",
|
||||
"Who is pulling the strings, what do they want and through which steps?",
|
||||
"What becomes of the situation if the characters do nothing?",
|
||||
"Can the players piece this truth together from the adventure's clues?"
|
||||
],
|
||||
"example": "The tower's master isn't dead: he traded his name for his survival. His scribe revives one seal each night; at the third, he takes form again. Without the characters, the fair ends with the lower town in flames.",
|
||||
"pitfall": "A secret story too complicated to be discovered in play. If the players can't understand it by the end, simplify it."
|
||||
},
|
||||
"hooks": {
|
||||
"title": "Hooks",
|
||||
"purpose": "The reasons that bring the characters into the adventure. A published module doesn't know the buyer's characters: offer several, of different kinds.",
|
||||
"questions": [
|
||||
"Which hook plays on interest (reward, contract, opportunity)?",
|
||||
"Which one plays on a personal tie (a relative, a debt, a past)?",
|
||||
"Which one starts from an event that falls on the characters without them seeking it?"
|
||||
],
|
||||
"example": "- The council offers 500 coins to escort a pedlar.\n- A childhood friend of one character vanished in Coldvale.\n- One character's medallion grows warm near the tower.",
|
||||
"pitfall": "A single hook, presented as an obligation. Players get more involved when the adventure is an opportunity they choose."
|
||||
},
|
||||
"credits": {
|
||||
"title": "Credits",
|
||||
"purpose": "Name everyone who contributed: it's expected in a released module, and it's a mark of respect.",
|
||||
"questions": [
|
||||
"Who wrote, illustrated, mapped, edited?",
|
||||
"Which tables playtested the adventure?",
|
||||
"Are you using licensed artwork or rules that must be credited?"
|
||||
],
|
||||
"example": "Writing: Camille Martin\nMaps: Léo Dubois\nEditing: Alex\nPlaytesters: the Thursday table (Inès, Yanis, Paul, Mira)",
|
||||
"pitfall": "Forgetting the playtesters, or the credits required by an artwork's or a game system's licence."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -2524,5 +2581,78 @@
|
||||
"treeDrill": {
|
||||
"open": "Open page",
|
||||
"empty": "Nothing here yet."
|
||||
},
|
||||
"publication": {
|
||||
"pageTitle": "Publishing · {{name}}",
|
||||
"title": "Publishing sheet",
|
||||
"intro": "This information turns the PDF booklet into a module ready to share or sell: cover, technical page, GM introduction and credits. Everything is optional: an empty sheet keeps the usual campaign booklet.",
|
||||
"saved": "Saved",
|
||||
"loadError": "Could not load the publishing sheet.",
|
||||
"saveError": "Saving failed. Please try again.",
|
||||
"exportError": "PDF generation failed.",
|
||||
"coverSection": "Cover",
|
||||
"subtitleLabel": "Subtitle",
|
||||
"subtitlePlaceholder": "E.g. An investigation in the northern lands",
|
||||
"authorLabel": "Author",
|
||||
"authorPlaceholder": "Your name or your studio's",
|
||||
"versionLabel": "Version",
|
||||
"coverLabel": "Cover illustration",
|
||||
"coverHint": "Portrait format recommended.",
|
||||
"techSection": "Technical page",
|
||||
"techHint": "What a GM checks first to know whether the adventure suits their table. Write it as it should be printed.",
|
||||
"systemLabel": "Game system",
|
||||
"systemPlaceholder": "E.g. D&D 5e, Pathfinder…",
|
||||
"levelsLabel": "Character levels",
|
||||
"levelsPlaceholder": "E.g. 1 to 3",
|
||||
"playersLabel": "Number of players",
|
||||
"playersPlaceholder": "E.g. 3 to 5",
|
||||
"durationLabel": "Estimated length",
|
||||
"durationPlaceholder": "E.g. two 4-hour sessions",
|
||||
"presentationSection": "Presentation",
|
||||
"pitchLabel": "The adventure at a glance",
|
||||
"pitchPlaceholder": "The starting situation and what the characters will go through, in a few lines…",
|
||||
"pitchHint": "Empty: the campaign description is used.",
|
||||
"warningsLabel": "Content warnings",
|
||||
"warningsPlaceholder": "Sensitive themes covered (violence, grief, horror…)",
|
||||
"gmSection": "GM introduction",
|
||||
"gmHint": "Only in the GM version of the PDF: the player version never shows it.",
|
||||
"backgroundLabel": "Hidden background",
|
||||
"backgroundPlaceholder": "What really happened, who pulls the strings and what will happen if the characters don't step in…",
|
||||
"hooksLabel": "Hooks",
|
||||
"hooksPlaceholder": "- A friend of the characters vanishes on the road\n- A reward is offered for…",
|
||||
"listHint": "A line starting with \"- \" becomes a bullet in the PDF.",
|
||||
"creditsSection": "Credits and licence",
|
||||
"creditsLabel": "Credits",
|
||||
"creditsPlaceholder": "Writing, art, maps, editing, playtesters…",
|
||||
"legalLabel": "Licence and legal notice",
|
||||
"legalPlaceholder": "E.g. Text licensed under CC BY-NC 4.0…",
|
||||
"legalHint": "If you use licensed content (a system's reference rules, artwork…), state its licence and required notices here."
|
||||
},
|
||||
"pdfDialog": {
|
||||
"title": "Export to PDF",
|
||||
"publicationEmpty": "No publishing sheet yet: the PDF will be a plain campaign booklet.",
|
||||
"publicationFilled": "The publishing sheet is filled in: cover, credits and introduction will be added.",
|
||||
"publicationFill": "Fill in the sheet",
|
||||
"publicationEdit": "Edit the sheet",
|
||||
"editionLabel": "Version",
|
||||
"editionGm": "GM (complete)",
|
||||
"editionGmHint": "All content, secrets and notes included.",
|
||||
"editionPlayer": "Players",
|
||||
"editionPlayerHint": "No secrets at all: read-aloud text, atmosphere, illustrations and maps.",
|
||||
"sectionsLabel": "Included parts",
|
||||
"section": {
|
||||
"NARRATIVE": "Narrative structure",
|
||||
"QUESTS": "Quests",
|
||||
"NPCS": "NPCs",
|
||||
"ENEMIES": "Bestiary",
|
||||
"TABLES": "Random tables",
|
||||
"LORE": "Lore"
|
||||
},
|
||||
"loreLinked": "Only pages linked to the campaign",
|
||||
"loreAll": "The whole lore",
|
||||
"formatLabel": "Format",
|
||||
"print": "Print mode",
|
||||
"printHint": "No colour fills, to save ink.",
|
||||
"confirm": "Generate the PDF"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2083,6 +2083,63 @@
|
||||
"example": "La guilde est démasquée publiquement ; ou bien elle est rachetée par les PJ eux-mêmes ; ou bien les villages sont perdus et l'arc suivant commence par l'exode.",
|
||||
"pitfall": "Une seule fin écrite d'avance : les choix des joueurs ne comptent plus. Prépare des issues, pas un scénario."
|
||||
}
|
||||
},
|
||||
"publication": {
|
||||
"pitch": {
|
||||
"title": "L'aventure en bref",
|
||||
"purpose": "Donner envie en quelques lignes : la situation de départ, ce que les personnages vont faire et l'ambiance. C'est le texte qu'un MJ lit avant de choisir votre module.",
|
||||
"questions": [
|
||||
"Quelle situation trouble les personnages au début ?",
|
||||
"Que vont-ils devoir faire, concrètement : enquêter, explorer, protéger, fuir ?",
|
||||
"Quelle image ou quel détail rend cette aventure différente des autres ?"
|
||||
],
|
||||
"example": "Une tour qu'on croyait éteinte se rallume au-dessus de Valfroide, en pleine foire d'automne. Les personnages ont trois jours pour découvrir qui ravive ses sceaux avant que la ville ne bascule dans la panique.",
|
||||
"pitfall": "Raconter la fin ou le secret central. L'argument présente une promesse de jeu ; la vérité cachée va dans le contexte réservé au MJ."
|
||||
},
|
||||
"contentWarnings": {
|
||||
"title": "Avertissements de contenu",
|
||||
"purpose": "Prévenir le MJ des thèmes difficiles pour qu'il en parle avec sa table avant de jouer, et ajuste ce qui doit l'être.",
|
||||
"questions": [
|
||||
"Quels thèmes pourraient mettre mal à l'aise : violence explicite, mort d'enfant, deuil, possession, harcèlement… ?",
|
||||
"Une scène peut-elle être jouée hors champ sans casser l'aventure ? Dites-le."
|
||||
],
|
||||
"example": "Violence physique, mort d'un personnage secondaire, possession. La scène de la crypte peut être résumée sans être décrite.",
|
||||
"pitfall": "Laisser vide par peur de « gâcher la surprise ». Annoncer un thème n'en révèle pas l'intrigue, et un MJ préparé mène mieux."
|
||||
},
|
||||
"gmBackground": {
|
||||
"title": "Contexte caché",
|
||||
"purpose": "Ce que le MJ doit savoir et que les joueurs ignorent : ce qui s'est vraiment passé, qui veut quoi, et ce qui arrive si personne n'intervient.",
|
||||
"questions": [
|
||||
"Qu'est-ce qui s'est passé avant l'arrivée des personnages ?",
|
||||
"Qui tire les ficelles, que veut-il obtenir et par quelles étapes ?",
|
||||
"Que devient la situation si les personnages ne font rien ?",
|
||||
"Les joueurs peuvent-ils reconstituer cette vérité avec les indices de l'aventure ?"
|
||||
],
|
||||
"example": "Le maître de la tour n'est pas mort : il a échangé son nom contre sa survie. Sa scribe ravive un sceau par nuit ; au troisième, il reprend corps. Sans les personnages, la foire se termine par l'incendie de la ville basse.",
|
||||
"pitfall": "Une histoire secrète trop compliquée pour être découverte en jeu. Si les joueurs ne peuvent pas la comprendre à la fin, simplifiez-la."
|
||||
},
|
||||
"hooks": {
|
||||
"title": "Accroches",
|
||||
"purpose": "Les raisons qui amènent les personnages dans l'aventure. Un module publié ne connaît pas les personnages de l'acheteur : proposez-en plusieurs, de nature différente.",
|
||||
"questions": [
|
||||
"Quelle accroche joue sur l'intérêt (récompense, contrat, opportunité) ?",
|
||||
"Laquelle joue sur un lien personnel (un proche, une dette, un passé) ?",
|
||||
"Laquelle part d'un événement qui tombe sur les personnages sans qu'ils le cherchent ?"
|
||||
],
|
||||
"example": "- Le conseil offre 500 pièces pour escorter un colporteur.\n- Un ami d'enfance d'un personnage a disparu à Valfroide.\n- Le médaillon d'un personnage se met à chauffer à l'approche de la tour.",
|
||||
"pitfall": "Une seule accroche, présentée comme une obligation. Les joueurs s'impliquent mieux quand l'aventure est une opportunité qu'ils choisissent."
|
||||
},
|
||||
"credits": {
|
||||
"title": "Crédits",
|
||||
"purpose": "Nommer tous ceux qui ont contribué : c'est attendu dans un module diffusé, et c'est une marque de respect.",
|
||||
"questions": [
|
||||
"Qui a écrit, illustré, cartographié, relu ?",
|
||||
"Quelles tables ont testé l'aventure ?",
|
||||
"Utilisez-vous des illustrations ou des règles sous licence qu'il faut créditer ?"
|
||||
],
|
||||
"example": "Écriture : Camille Martin\nCartes : Léo Dubois\nRelecture : Alex\nTesteurs : la table du jeudi (Inès, Yanis, Paul, Mira)",
|
||||
"pitfall": "Oublier les testeurs, ou les crédits exigés par la licence d'une illustration ou d'un système de jeu."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -2524,5 +2581,78 @@
|
||||
"treeDrill": {
|
||||
"open": "Ouvrir la fiche",
|
||||
"empty": "Rien ici pour le moment."
|
||||
},
|
||||
"publication": {
|
||||
"pageTitle": "Publication · {{name}}",
|
||||
"title": "Fiche de publication",
|
||||
"intro": "Ces informations transforment le livret PDF en module prêt à partager ou à vendre : couverture, page technique, introduction pour le MJ et crédits. Tout est facultatif : une fiche vide garde le livret de campagne habituel.",
|
||||
"saved": "Enregistré",
|
||||
"loadError": "Impossible de charger la fiche de publication.",
|
||||
"saveError": "L'enregistrement a échoué. Réessayez.",
|
||||
"exportError": "La génération du PDF a échoué.",
|
||||
"coverSection": "Couverture",
|
||||
"subtitleLabel": "Sous-titre",
|
||||
"subtitlePlaceholder": "Ex : Une enquête dans les terres du Nord",
|
||||
"authorLabel": "Auteur ou autrice",
|
||||
"authorPlaceholder": "Votre nom ou celui de votre studio",
|
||||
"versionLabel": "Version",
|
||||
"coverLabel": "Illustration de couverture",
|
||||
"coverHint": "Format portrait conseillé.",
|
||||
"techSection": "Page technique",
|
||||
"techHint": "Ce qu'un MJ regarde en premier pour savoir si l'aventure convient à sa table. Écrivez-le comme il doit apparaître.",
|
||||
"systemLabel": "Système de jeu",
|
||||
"systemPlaceholder": "Ex : Chroniques Oubliées, D&D 5e…",
|
||||
"levelsLabel": "Niveaux des personnages",
|
||||
"levelsPlaceholder": "Ex : 1 à 3",
|
||||
"playersLabel": "Nombre de joueurs",
|
||||
"playersPlaceholder": "Ex : 3 à 5",
|
||||
"durationLabel": "Durée estimée",
|
||||
"durationPlaceholder": "Ex : 2 séances de 4 h",
|
||||
"presentationSection": "Présentation",
|
||||
"pitchLabel": "L'aventure en bref",
|
||||
"pitchPlaceholder": "La situation de départ et ce que les personnages vont vivre, en quelques lignes…",
|
||||
"pitchHint": "Vide : la description de la campagne est utilisée.",
|
||||
"warningsLabel": "Avertissements de contenu",
|
||||
"warningsPlaceholder": "Thèmes sensibles abordés (violence, deuil, horreur…)",
|
||||
"gmSection": "Introduction pour le MJ",
|
||||
"gmHint": "Réservé à la version MJ du PDF : la version joueurs ne l'affiche jamais.",
|
||||
"backgroundLabel": "Contexte caché",
|
||||
"backgroundPlaceholder": "Ce qui s'est vraiment passé, qui tire les ficelles et ce qui arrivera si les personnages n'interviennent pas…",
|
||||
"hooksLabel": "Accroches",
|
||||
"hooksPlaceholder": "- Un ami des personnages disparaît sur la route\n- Une récompense est offerte pour…",
|
||||
"listHint": "Une ligne commençant par « - » devient une puce dans le PDF.",
|
||||
"creditsSection": "Crédits et licence",
|
||||
"creditsLabel": "Crédits",
|
||||
"creditsPlaceholder": "Écriture, illustrations, cartes, relecture, testeurs…",
|
||||
"legalLabel": "Licence et mentions légales",
|
||||
"legalPlaceholder": "Ex : Texte sous licence CC BY-NC 4.0…",
|
||||
"legalHint": "Si vous utilisez du contenu sous licence (règles de référence d'un système, illustrations…), citez-en ici la licence et les mentions exigées."
|
||||
},
|
||||
"pdfDialog": {
|
||||
"title": "Exporter en PDF",
|
||||
"publicationEmpty": "Pas encore de fiche de publication : le PDF sera un simple livret de campagne.",
|
||||
"publicationFilled": "La fiche de publication est remplie : couverture, crédits et introduction seront ajoutés.",
|
||||
"publicationFill": "Compléter la fiche",
|
||||
"publicationEdit": "Modifier la fiche",
|
||||
"editionLabel": "Version",
|
||||
"editionGm": "MJ (complète)",
|
||||
"editionGmHint": "Tout le contenu, secrets et notes compris.",
|
||||
"editionPlayer": "Joueurs",
|
||||
"editionPlayerHint": "Sans aucun secret : textes à lire, ambiances, illustrations et cartes.",
|
||||
"sectionsLabel": "Parties incluses",
|
||||
"section": {
|
||||
"NARRATIVE": "Structure narrative",
|
||||
"QUESTS": "Quêtes",
|
||||
"NPCS": "PNJ",
|
||||
"ENEMIES": "Bestiaire",
|
||||
"TABLES": "Tables aléatoires",
|
||||
"LORE": "Lore"
|
||||
},
|
||||
"loreLinked": "Seulement les pages liées à la campagne",
|
||||
"loreAll": "Tout le lore",
|
||||
"formatLabel": "Format",
|
||||
"print": "Mode impression",
|
||||
"printHint": "Sans aplats de couleur, pour économiser l'encre.",
|
||||
"confirm": "Générer le PDF"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"publication": {
|
||||
"pageTitle": "Publishing · {{name}}",
|
||||
"title": "Publishing sheet",
|
||||
"intro": "This information turns the PDF booklet into a module ready to share or sell: cover, technical page, GM introduction and credits. Everything is optional: an empty sheet keeps the usual campaign booklet.",
|
||||
"saved": "Saved",
|
||||
"loadError": "Could not load the publishing sheet.",
|
||||
"saveError": "Saving failed. Please try again.",
|
||||
"exportError": "PDF generation failed.",
|
||||
"coverSection": "Cover",
|
||||
"subtitleLabel": "Subtitle",
|
||||
"subtitlePlaceholder": "E.g. An investigation in the northern lands",
|
||||
"authorLabel": "Author",
|
||||
"authorPlaceholder": "Your name or your studio's",
|
||||
"versionLabel": "Version",
|
||||
"coverLabel": "Cover illustration",
|
||||
"coverHint": "Portrait format recommended.",
|
||||
"techSection": "Technical page",
|
||||
"techHint": "What a GM checks first to know whether the adventure suits their table. Write it as it should be printed.",
|
||||
"systemLabel": "Game system",
|
||||
"systemPlaceholder": "E.g. D&D 5e, Pathfinder…",
|
||||
"levelsLabel": "Character levels",
|
||||
"levelsPlaceholder": "E.g. 1 to 3",
|
||||
"playersLabel": "Number of players",
|
||||
"playersPlaceholder": "E.g. 3 to 5",
|
||||
"durationLabel": "Estimated length",
|
||||
"durationPlaceholder": "E.g. two 4-hour sessions",
|
||||
"presentationSection": "Presentation",
|
||||
"pitchLabel": "The adventure at a glance",
|
||||
"pitchPlaceholder": "The starting situation and what the characters will go through, in a few lines…",
|
||||
"pitchHint": "Empty: the campaign description is used.",
|
||||
"warningsLabel": "Content warnings",
|
||||
"warningsPlaceholder": "Sensitive themes covered (violence, grief, horror…)",
|
||||
"gmSection": "GM introduction",
|
||||
"gmHint": "Only in the GM version of the PDF: the player version never shows it.",
|
||||
"backgroundLabel": "Hidden background",
|
||||
"backgroundPlaceholder": "What really happened, who pulls the strings and what will happen if the characters don't step in…",
|
||||
"hooksLabel": "Hooks",
|
||||
"hooksPlaceholder": "- A friend of the characters vanishes on the road\n- A reward is offered for…",
|
||||
"listHint": "A line starting with \"- \" becomes a bullet in the PDF.",
|
||||
"creditsSection": "Credits and licence",
|
||||
"creditsLabel": "Credits",
|
||||
"creditsPlaceholder": "Writing, art, maps, editing, playtesters…",
|
||||
"legalLabel": "Licence and legal notice",
|
||||
"legalPlaceholder": "E.g. Text licensed under CC BY-NC 4.0…",
|
||||
"legalHint": "If you use licensed content (a system's reference rules, artwork…), state its licence and required notices here."
|
||||
},
|
||||
"pdfDialog": {
|
||||
"title": "Export to PDF",
|
||||
"publicationEmpty": "No publishing sheet yet: the PDF will be a plain campaign booklet.",
|
||||
"publicationFilled": "The publishing sheet is filled in: cover, credits and introduction will be added.",
|
||||
"publicationFill": "Fill in the sheet",
|
||||
"publicationEdit": "Edit the sheet",
|
||||
"editionLabel": "Version",
|
||||
"editionGm": "GM (complete)",
|
||||
"editionGmHint": "All content, secrets and notes included.",
|
||||
"editionPlayer": "Players",
|
||||
"editionPlayerHint": "No secrets at all: read-aloud text, atmosphere, illustrations and maps.",
|
||||
"sectionsLabel": "Included parts",
|
||||
"section": {
|
||||
"NARRATIVE": "Narrative structure",
|
||||
"QUESTS": "Quests",
|
||||
"NPCS": "NPCs",
|
||||
"ENEMIES": "Bestiary",
|
||||
"TABLES": "Random tables",
|
||||
"LORE": "Lore"
|
||||
},
|
||||
"loreLinked": "Only pages linked to the campaign",
|
||||
"loreAll": "The whole lore",
|
||||
"formatLabel": "Format",
|
||||
"print": "Print mode",
|
||||
"printHint": "No colour fills, to save ink.",
|
||||
"confirm": "Generate the PDF"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"publication": {
|
||||
"pageTitle": "Publication · {{name}}",
|
||||
"title": "Fiche de publication",
|
||||
"intro": "Ces informations transforment le livret PDF en module prêt à partager ou à vendre : couverture, page technique, introduction pour le MJ et crédits. Tout est facultatif : une fiche vide garde le livret de campagne habituel.",
|
||||
"saved": "Enregistré",
|
||||
"loadError": "Impossible de charger la fiche de publication.",
|
||||
"saveError": "L'enregistrement a échoué. Réessayez.",
|
||||
"exportError": "La génération du PDF a échoué.",
|
||||
"coverSection": "Couverture",
|
||||
"subtitleLabel": "Sous-titre",
|
||||
"subtitlePlaceholder": "Ex : Une enquête dans les terres du Nord",
|
||||
"authorLabel": "Auteur ou autrice",
|
||||
"authorPlaceholder": "Votre nom ou celui de votre studio",
|
||||
"versionLabel": "Version",
|
||||
"coverLabel": "Illustration de couverture",
|
||||
"coverHint": "Format portrait conseillé.",
|
||||
"techSection": "Page technique",
|
||||
"techHint": "Ce qu'un MJ regarde en premier pour savoir si l'aventure convient à sa table. Écrivez-le comme il doit apparaître.",
|
||||
"systemLabel": "Système de jeu",
|
||||
"systemPlaceholder": "Ex : Chroniques Oubliées, D&D 5e…",
|
||||
"levelsLabel": "Niveaux des personnages",
|
||||
"levelsPlaceholder": "Ex : 1 à 3",
|
||||
"playersLabel": "Nombre de joueurs",
|
||||
"playersPlaceholder": "Ex : 3 à 5",
|
||||
"durationLabel": "Durée estimée",
|
||||
"durationPlaceholder": "Ex : 2 séances de 4 h",
|
||||
"presentationSection": "Présentation",
|
||||
"pitchLabel": "L'aventure en bref",
|
||||
"pitchPlaceholder": "La situation de départ et ce que les personnages vont vivre, en quelques lignes…",
|
||||
"pitchHint": "Vide : la description de la campagne est utilisée.",
|
||||
"warningsLabel": "Avertissements de contenu",
|
||||
"warningsPlaceholder": "Thèmes sensibles abordés (violence, deuil, horreur…)",
|
||||
"gmSection": "Introduction pour le MJ",
|
||||
"gmHint": "Réservé à la version MJ du PDF : la version joueurs ne l'affiche jamais.",
|
||||
"backgroundLabel": "Contexte caché",
|
||||
"backgroundPlaceholder": "Ce qui s'est vraiment passé, qui tire les ficelles et ce qui arrivera si les personnages n'interviennent pas…",
|
||||
"hooksLabel": "Accroches",
|
||||
"hooksPlaceholder": "- Un ami des personnages disparaît sur la route\n- Une récompense est offerte pour…",
|
||||
"listHint": "Une ligne commençant par « - » devient une puce dans le PDF.",
|
||||
"creditsSection": "Crédits et licence",
|
||||
"creditsLabel": "Crédits",
|
||||
"creditsPlaceholder": "Écriture, illustrations, cartes, relecture, testeurs…",
|
||||
"legalLabel": "Licence et mentions légales",
|
||||
"legalPlaceholder": "Ex : Texte sous licence CC BY-NC 4.0…",
|
||||
"legalHint": "Si vous utilisez du contenu sous licence (règles de référence d'un système, illustrations…), citez-en ici la licence et les mentions exigées."
|
||||
},
|
||||
"pdfDialog": {
|
||||
"title": "Exporter en PDF",
|
||||
"publicationEmpty": "Pas encore de fiche de publication : le PDF sera un simple livret de campagne.",
|
||||
"publicationFilled": "La fiche de publication est remplie : couverture, crédits et introduction seront ajoutés.",
|
||||
"publicationFill": "Compléter la fiche",
|
||||
"publicationEdit": "Modifier la fiche",
|
||||
"editionLabel": "Version",
|
||||
"editionGm": "MJ (complète)",
|
||||
"editionGmHint": "Tout le contenu, secrets et notes compris.",
|
||||
"editionPlayer": "Joueurs",
|
||||
"editionPlayerHint": "Sans aucun secret : textes à lire, ambiances, illustrations et cartes.",
|
||||
"sectionsLabel": "Parties incluses",
|
||||
"section": {
|
||||
"NARRATIVE": "Structure narrative",
|
||||
"QUESTS": "Quêtes",
|
||||
"NPCS": "PNJ",
|
||||
"ENEMIES": "Bestiaire",
|
||||
"TABLES": "Tables aléatoires",
|
||||
"LORE": "Lore"
|
||||
},
|
||||
"loreLinked": "Seulement les pages liées à la campagne",
|
||||
"loreAll": "Tout le lore",
|
||||
"formatLabel": "Format",
|
||||
"print": "Mode impression",
|
||||
"printHint": "Sans aplats de couleur, pour économiser l'encre.",
|
||||
"confirm": "Générer le PDF"
|
||||
}
|
||||
}
|
||||
@@ -198,6 +198,63 @@
|
||||
"example": "The guild is publicly exposed; or the PCs buy it out themselves; or the villages are lost and the next arc opens with the exodus.",
|
||||
"pitfall": "A single ending written in advance: the players' choices no longer matter. Prepare outcomes, not a script."
|
||||
}
|
||||
},
|
||||
"publication": {
|
||||
"pitch": {
|
||||
"title": "The adventure at a glance",
|
||||
"purpose": "Make people want to play in a few lines: the starting situation, what the characters will do and the mood. It's the text a GM reads before picking your module.",
|
||||
"questions": [
|
||||
"What situation troubles the characters at the start?",
|
||||
"What will they actually have to do: investigate, explore, protect, flee?",
|
||||
"Which image or detail sets this adventure apart?"
|
||||
],
|
||||
"example": "A tower thought long dead lights up again above Coldvale, in the middle of the autumn fair. The characters have three days to find out who is reviving its seals before the town falls into panic.",
|
||||
"pitfall": "Giving away the ending or the central secret. The pitch is a promise of play; the hidden truth belongs in the GM-only background."
|
||||
},
|
||||
"contentWarnings": {
|
||||
"title": "Content warnings",
|
||||
"purpose": "Warn the GM about difficult themes so they can talk about them with their table before playing, and adjust what needs adjusting.",
|
||||
"questions": [
|
||||
"Which themes might make players uncomfortable: graphic violence, death of a child, grief, possession, harassment…?",
|
||||
"Can a scene be played off-screen without breaking the adventure? Say so."
|
||||
],
|
||||
"example": "Physical violence, death of a secondary character, possession. The crypt scene can be summarised rather than described.",
|
||||
"pitfall": "Leaving it empty for fear of spoiling the surprise. Naming a theme reveals nothing of the plot, and a prepared GM runs it better."
|
||||
},
|
||||
"gmBackground": {
|
||||
"title": "Hidden background",
|
||||
"purpose": "What the GM needs to know and the players don't: what really happened, who wants what, and what happens if nobody steps in.",
|
||||
"questions": [
|
||||
"What happened before the characters arrived?",
|
||||
"Who is pulling the strings, what do they want and through which steps?",
|
||||
"What becomes of the situation if the characters do nothing?",
|
||||
"Can the players piece this truth together from the adventure's clues?"
|
||||
],
|
||||
"example": "The tower's master isn't dead: he traded his name for his survival. His scribe revives one seal each night; at the third, he takes form again. Without the characters, the fair ends with the lower town in flames.",
|
||||
"pitfall": "A secret story too complicated to be discovered in play. If the players can't understand it by the end, simplify it."
|
||||
},
|
||||
"hooks": {
|
||||
"title": "Hooks",
|
||||
"purpose": "The reasons that bring the characters into the adventure. A published module doesn't know the buyer's characters: offer several, of different kinds.",
|
||||
"questions": [
|
||||
"Which hook plays on interest (reward, contract, opportunity)?",
|
||||
"Which one plays on a personal tie (a relative, a debt, a past)?",
|
||||
"Which one starts from an event that falls on the characters without them seeking it?"
|
||||
],
|
||||
"example": "- The council offers 500 coins to escort a pedlar.\n- A childhood friend of one character vanished in Coldvale.\n- One character's medallion grows warm near the tower.",
|
||||
"pitfall": "A single hook, presented as an obligation. Players get more involved when the adventure is an opportunity they choose."
|
||||
},
|
||||
"credits": {
|
||||
"title": "Credits",
|
||||
"purpose": "Name everyone who contributed: it's expected in a released module, and it's a mark of respect.",
|
||||
"questions": [
|
||||
"Who wrote, illustrated, mapped, edited?",
|
||||
"Which tables playtested the adventure?",
|
||||
"Are you using licensed artwork or rules that must be credited?"
|
||||
],
|
||||
"example": "Writing: Camille Martin\nMaps: Léo Dubois\nEditing: Alex\nPlaytesters: the Thursday table (Inès, Yanis, Paul, Mira)",
|
||||
"pitfall": "Forgetting the playtesters, or the credits required by an artwork's or a game system's licence."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,6 +198,63 @@
|
||||
"example": "La guilde est démasquée publiquement ; ou bien elle est rachetée par les PJ eux-mêmes ; ou bien les villages sont perdus et l'arc suivant commence par l'exode.",
|
||||
"pitfall": "Une seule fin écrite d'avance : les choix des joueurs ne comptent plus. Prépare des issues, pas un scénario."
|
||||
}
|
||||
},
|
||||
"publication": {
|
||||
"pitch": {
|
||||
"title": "L'aventure en bref",
|
||||
"purpose": "Donner envie en quelques lignes : la situation de départ, ce que les personnages vont faire et l'ambiance. C'est le texte qu'un MJ lit avant de choisir votre module.",
|
||||
"questions": [
|
||||
"Quelle situation trouble les personnages au début ?",
|
||||
"Que vont-ils devoir faire, concrètement : enquêter, explorer, protéger, fuir ?",
|
||||
"Quelle image ou quel détail rend cette aventure différente des autres ?"
|
||||
],
|
||||
"example": "Une tour qu'on croyait éteinte se rallume au-dessus de Valfroide, en pleine foire d'automne. Les personnages ont trois jours pour découvrir qui ravive ses sceaux avant que la ville ne bascule dans la panique.",
|
||||
"pitfall": "Raconter la fin ou le secret central. L'argument présente une promesse de jeu ; la vérité cachée va dans le contexte réservé au MJ."
|
||||
},
|
||||
"contentWarnings": {
|
||||
"title": "Avertissements de contenu",
|
||||
"purpose": "Prévenir le MJ des thèmes difficiles pour qu'il en parle avec sa table avant de jouer, et ajuste ce qui doit l'être.",
|
||||
"questions": [
|
||||
"Quels thèmes pourraient mettre mal à l'aise : violence explicite, mort d'enfant, deuil, possession, harcèlement… ?",
|
||||
"Une scène peut-elle être jouée hors champ sans casser l'aventure ? Dites-le."
|
||||
],
|
||||
"example": "Violence physique, mort d'un personnage secondaire, possession. La scène de la crypte peut être résumée sans être décrite.",
|
||||
"pitfall": "Laisser vide par peur de « gâcher la surprise ». Annoncer un thème n'en révèle pas l'intrigue, et un MJ préparé mène mieux."
|
||||
},
|
||||
"gmBackground": {
|
||||
"title": "Contexte caché",
|
||||
"purpose": "Ce que le MJ doit savoir et que les joueurs ignorent : ce qui s'est vraiment passé, qui veut quoi, et ce qui arrive si personne n'intervient.",
|
||||
"questions": [
|
||||
"Qu'est-ce qui s'est passé avant l'arrivée des personnages ?",
|
||||
"Qui tire les ficelles, que veut-il obtenir et par quelles étapes ?",
|
||||
"Que devient la situation si les personnages ne font rien ?",
|
||||
"Les joueurs peuvent-ils reconstituer cette vérité avec les indices de l'aventure ?"
|
||||
],
|
||||
"example": "Le maître de la tour n'est pas mort : il a échangé son nom contre sa survie. Sa scribe ravive un sceau par nuit ; au troisième, il reprend corps. Sans les personnages, la foire se termine par l'incendie de la ville basse.",
|
||||
"pitfall": "Une histoire secrète trop compliquée pour être découverte en jeu. Si les joueurs ne peuvent pas la comprendre à la fin, simplifiez-la."
|
||||
},
|
||||
"hooks": {
|
||||
"title": "Accroches",
|
||||
"purpose": "Les raisons qui amènent les personnages dans l'aventure. Un module publié ne connaît pas les personnages de l'acheteur : proposez-en plusieurs, de nature différente.",
|
||||
"questions": [
|
||||
"Quelle accroche joue sur l'intérêt (récompense, contrat, opportunité) ?",
|
||||
"Laquelle joue sur un lien personnel (un proche, une dette, un passé) ?",
|
||||
"Laquelle part d'un événement qui tombe sur les personnages sans qu'ils le cherchent ?"
|
||||
],
|
||||
"example": "- Le conseil offre 500 pièces pour escorter un colporteur.\n- Un ami d'enfance d'un personnage a disparu à Valfroide.\n- Le médaillon d'un personnage se met à chauffer à l'approche de la tour.",
|
||||
"pitfall": "Une seule accroche, présentée comme une obligation. Les joueurs s'impliquent mieux quand l'aventure est une opportunité qu'ils choisissent."
|
||||
},
|
||||
"credits": {
|
||||
"title": "Crédits",
|
||||
"purpose": "Nommer tous ceux qui ont contribué : c'est attendu dans un module diffusé, et c'est une marque de respect.",
|
||||
"questions": [
|
||||
"Qui a écrit, illustré, cartographié, relu ?",
|
||||
"Quelles tables ont testé l'aventure ?",
|
||||
"Utilisez-vous des illustrations ou des règles sous licence qu'il faut créditer ?"
|
||||
],
|
||||
"example": "Écriture : Camille Martin\nCartes : Léo Dubois\nRelecture : Alex\nTesteurs : la table du jeudi (Inès, Yanis, Paul, Mira)",
|
||||
"pitfall": "Oublier les testeurs, ou les crédits exigés par la licence d'une illustration ou d'un système de jeu."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user