Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0cd99dfb32 | |||
| f24ef0891e | |||
| 7c74c12f3e | |||
| 86836ad81c | |||
| 7c4a42327d | |||
| 52e389db24 |
@@ -42,19 +42,24 @@ jobs:
|
||||
username: ${{ env.GHCR_NAMESPACE }}
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
|
||||
- name: Extract version
|
||||
# Detection du canal :
|
||||
# - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics)
|
||||
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR prives
|
||||
# loremind-beta-<component> ; backup Gitea avec :version)
|
||||
- name: Extract version & channel
|
||||
id: meta
|
||||
run: echo "version=${GITHUB_REF_NAME#v}" >> $GITHUB_OUTPUT
|
||||
run: |
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
if [[ "${VERSION}" == *-beta* ]]; then
|
||||
echo "channel=beta" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "channel=stable" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
# Push vers les deux registries en un seul build (build-push-action
|
||||
# accepte une liste de tags ; aucun build supplementaire necessaire).
|
||||
# Naming :
|
||||
# - Gitea : conserve l'ancien pattern ietm64/<component> pour ne pas
|
||||
# casser les installs existantes qui ont REGISTRY=git.igmlcreation.fr
|
||||
# dans leur .env.
|
||||
# - GHCR : nouveau pattern igmlcreation/loremind-<component> qui evite
|
||||
# la collision avec d'autres projets de l'org.
|
||||
- name: Build & push ${{ matrix.component }}
|
||||
# Build & push canal STABLE
|
||||
- name: Build & push ${{ matrix.component }} (stable)
|
||||
if: steps.meta.outputs.channel == 'stable'
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./${{ matrix.component }}
|
||||
@@ -64,3 +69,19 @@ jobs:
|
||||
${{ env.GITEA_REGISTRY }}/${{ env.GITEA_REGISTRY_USER }}/${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:latest
|
||||
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||
|
||||
# Build & push canal BETA
|
||||
# GHCR : repos prives loremind-beta-<component> (gated par PAT distribue
|
||||
# via le relais Patreon aux tiers Compagnon).
|
||||
# Gitea : backup prive avec :version uniquement (pas de :latest pour ne
|
||||
# pas faire upgrader les installs branchees sur Gitea).
|
||||
- name: Build & push ${{ matrix.component }} (beta)
|
||||
if: steps.meta.outputs.channel == 'beta'
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./${{ matrix.component }}
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.GITEA_REGISTRY }}/${{ env.GITEA_REGISTRY_USER }}/${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-beta-${{ matrix.component }}:beta
|
||||
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-beta-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -107,3 +107,4 @@ docker-compose.override.yml
|
||||
# Relais OAuth Patreon (repo Gitea separe, clone localement pour facilite)
|
||||
# ============================================================================
|
||||
relay/
|
||||
scripts/bump-version.mjs
|
||||
|
||||
67
README.md
67
README.md
@@ -1,37 +1,66 @@
|
||||
# LoreMind
|
||||
|
||||
> Application web auto-hébergeable pour MJ qui veulent centraliser leur univers, leurs campagnes et leurs personnages — avec un assistant IA contextuel.
|
||||
|
||||
[](LICENSE)
|
||||
[](https://loremind-docs.igmlcreation.fr/)
|
||||
[](https://loremind-demo.igmlcreation.fr/)
|
||||
[](https://www.patreon.com/c/IGMLCreation)
|
||||
[](https://discord.gg/cPpFzCjEzQ)
|
||||
|
||||
## Découvrir LoreMind en vidéo
|
||||
|
||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||
|
||||

|
||||
|
||||
Loremind est une application web angular auto-hébergable afin de venir en aide aux Maîtres de jeu qui souhaitent centraliser leur univers et leurs campagnes.
|
||||
Cette dernière intègre un moteur IA qui va ingérer le contenu du lore et de la campagne afin de pouvoir répondre à des questions précises sur l'univers ou la campagne, mais également proposer des idées de création dans le contexte de la campagne et du lore.
|
||||
Pour le moment seul Ollama est supporté pour la partie locale, il y-a également une intégration pour 1min.ai. Plus tard, d'autres moteurs seront supportés.
|
||||
## Ce que ça fait
|
||||
|
||||
LoreMind regroupe ce qu'un MJ utilise habituellement éparpillé entre plusieurs outils. L'application s'articule autour de trois modules principaux, augmentés par un assistant IA qui exploite tout votre contenu.
|
||||
|
||||
### Lore
|
||||
|
||||
Construire votre univers avec une arborescence de pages templatées : lieux, factions, PNJ, événements, organisations... Chaque type de page suit un template configurable, ce qui garantit la cohérence et facilite la navigation dans des univers riches.
|
||||
|
||||
### Game System
|
||||
|
||||
Stocker les règles de votre système de jeu (D&D, Nimble, créations maison...) et définir les modèles de fiches de personnages associés. Les règles indexées peuvent être injectées dans le contexte de l'IA pour des réponses fidèles à votre système.
|
||||
|
||||
### Campaign
|
||||
|
||||
Structurer vos campagnes en Arcs → Chapitres → Scènes avec séparation claire du contenu MJ et du contenu joueurs. Gérer les PJ et PNJ via des fiches dynamiques basées sur les templates du game system retenu.
|
||||
|
||||
### Assistant IA
|
||||
|
||||
Un assistant contextuel qui pioche dans votre Lore, vos règles et vos campagnes pour répondre à vos questions, suggérer du contenu cohérent, ou rebondir sur une situation improvisée en table.
|
||||
|
||||
L'IA s'exécute **en local via [Ollama](https://ollama.com/)** ou via **[1min.ai](https://1min.ai/)**. D'autres moteurs seront supportés à l'avenir.
|
||||
|
||||
## Documentation
|
||||
|
||||
La documentation complète est accessible sur le site [loremind-docs](https://loremind-docs.igmlcreation.fr/)
|
||||
Toute la documentation (installation, configuration, prise en main) est sur **[loremind-docs.igmlcreation.fr](https://loremind-docs.igmlcreation.fr/)**.
|
||||
|
||||
Pour l'installation, consultez le guide dans cette dernière .
|
||||
## Démo en ligne
|
||||
|
||||
## Fonctionnalités
|
||||
Une instance de démonstration est disponible sur **[loremind-demo.igmlcreation.fr](https://loremind-demo.igmlcreation.fr/)**.
|
||||
|
||||
- Gestion centralisée du Lore : Lieux, Factions, PNJ, et tous les éléments de votre univers
|
||||
- Suivi de campagnes : Sessions, actions des joueurs, chronologie
|
||||
- Moteur IA intégré : Génération automatique de contenu (PNJ, Villes, Quêtes) à partir de templates
|
||||
Quelques limites à connaître :
|
||||
- 10 utilisateurs maximum simultanés (instances isolées)
|
||||
- Session limitée à 20 minutes avant réinitialisation
|
||||
- Partie IA non incluse dans la démo (nécessite Ollama ou 1min.ai côté serveur)
|
||||
|
||||
## Démo
|
||||
## Soutenir le projet
|
||||
|
||||
Une démo est disponible sur le site [loremind-demo](https://loremind-demo.igmlcreation.fr/)
|
||||
LoreMind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||
|
||||
!! Attention, la démo est uniquement accessible à 10 personnes à la fois (instances personnalisées). Cette limite est mise en place pour éviter l'overhead sur les ressources serveur.
|
||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
||||
|
||||
Cette dernière est utilisable 20 minutes maximum par session avant d'être réinitialiser.
|
||||
Vous comprendrez également qu'elle ne contient pas de démo pour la partie IA, pour laquelle il faut configurer un serveur Ollama (et qui ferait donc exploser le serveur) ou utiliser 1min.ai.
|
||||
|
||||
## License
|
||||
## Licence
|
||||
|
||||
LoreMind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
||||
|
||||
En pratique :
|
||||
- Tu peux l'utiliser gratuitement, l'héberger où tu veux, le modifier, le redistribuer.
|
||||
- Si tu modifies le code et que tu exposes l'application modifiée sur un réseau (même en SaaS privé), tu dois rendre tes modifications publiques sous la même licence.
|
||||
- Les univers (Lore) et campagnes que tu crées avec LoreMind **t'appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
||||
- Vous pouvez l'utiliser gratuitement, l'héberger, la modifier, la redistribuer.
|
||||
- Si vous modifiez le code et que vous exposez l'application modifiée sur un réseau (même en SaaS privé), vous devez rendre vos modifications publiques sous la même licence.
|
||||
- Les univers (Lore) et campagnes que vous créez avec LoreMind **vous appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
||||
|
||||
@@ -41,7 +41,7 @@ from app.infrastructure.onemin_adapter import OneMinAiLLMProvider
|
||||
app = FastAPI(
|
||||
title="LoreMind Brain",
|
||||
description="Backend IA pour la génération de contenu narratif.",
|
||||
version="0.6.6",
|
||||
version="0.8.4-beta",
|
||||
)
|
||||
|
||||
|
||||
|
||||
13
core/pom.xml
13
core/pom.xml
@@ -8,13 +8,13 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.2.0</version>
|
||||
<version>3.2.12</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>0.8.1</version>
|
||||
<version>0.8.4-beta</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
@@ -96,6 +96,15 @@
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.78.1</version>
|
||||
</dependency>
|
||||
<!-- Google Tink : runtime requis par com.nimbusds.jose.crypto.Ed25519Verifier
|
||||
(depuis Nimbus 9.x, la verification EdDSA delegue a Tink.subtle.Ed25519Verify).
|
||||
Tink n'est PAS une dependance transitive de nimbus-jose-jwt → il faut
|
||||
l'ajouter explicitement, sinon NoClassDefFoundError au premier verify(). -->
|
||||
<dependency>
|
||||
<groupId>com.google.crypto.tink</groupId>
|
||||
<artifactId>tink</artifactId>
|
||||
<version>1.14.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -4,7 +4,9 @@ import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -22,8 +24,18 @@ public class CharacterService {
|
||||
/**
|
||||
* Parameter Object pour la création / mise à jour d'un Character.
|
||||
* `order` est fourni par le controller ; si absent, le service le calcule.
|
||||
* Les maps {@code values}/{@code imageValues} peuvent etre null (interpretees vides).
|
||||
*/
|
||||
public record CharacterData(String name, String markdownContent, String campaignId, Integer order) {}
|
||||
public record CharacterData(
|
||||
String name,
|
||||
String portraitImageId,
|
||||
String headerImageId,
|
||||
Map<String, String> values,
|
||||
Map<String, List<String>> imageValues,
|
||||
Map<String, Map<String, String>> keyValueValues,
|
||||
String campaignId,
|
||||
Integer order
|
||||
) {}
|
||||
|
||||
public Character createCharacter(CharacterData data) {
|
||||
int order = data.order() != null
|
||||
@@ -31,7 +43,11 @@ public class CharacterService {
|
||||
: nextOrderFor(data.campaignId());
|
||||
Character character = Character.builder()
|
||||
.name(data.name())
|
||||
.markdownContent(data.markdownContent())
|
||||
.portraitImageId(data.portraitImageId())
|
||||
.headerImageId(data.headerImageId())
|
||||
.values(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>())
|
||||
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
|
||||
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
|
||||
.campaignId(data.campaignId())
|
||||
.order(order)
|
||||
.build();
|
||||
@@ -50,7 +66,11 @@ public class CharacterService {
|
||||
Character existing = characterRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Character non trouvé avec l'ID: " + id));
|
||||
existing.setName(data.name());
|
||||
existing.setMarkdownContent(data.markdownContent());
|
||||
existing.setPortraitImageId(data.portraitImageId());
|
||||
existing.setHeaderImageId(data.headerImageId());
|
||||
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
|
||||
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
|
||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||
if (data.order() != null) {
|
||||
existing.setOrder(data.order());
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ import com.loremind.domain.campaigncontext.Npc;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -19,11 +21,16 @@ public class NpcService {
|
||||
this.npcRepository = npcRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameter Object pour la création / mise à jour d'un Npc.
|
||||
* `order` est fourni par le controller ; si absent, le service le calcule.
|
||||
*/
|
||||
public record NpcData(String name, String markdownContent, String campaignId, Integer order) {}
|
||||
public record NpcData(
|
||||
String name,
|
||||
String portraitImageId,
|
||||
String headerImageId,
|
||||
Map<String, String> values,
|
||||
Map<String, List<String>> imageValues,
|
||||
Map<String, Map<String, String>> keyValueValues,
|
||||
String campaignId,
|
||||
Integer order
|
||||
) {}
|
||||
|
||||
public Npc createNpc(NpcData data) {
|
||||
int order = data.order() != null
|
||||
@@ -31,7 +38,11 @@ public class NpcService {
|
||||
: nextOrderFor(data.campaignId());
|
||||
Npc npc = Npc.builder()
|
||||
.name(data.name())
|
||||
.markdownContent(data.markdownContent())
|
||||
.portraitImageId(data.portraitImageId())
|
||||
.headerImageId(data.headerImageId())
|
||||
.values(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>())
|
||||
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
|
||||
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
|
||||
.campaignId(data.campaignId())
|
||||
.order(order)
|
||||
.build();
|
||||
@@ -50,7 +61,11 @@ public class NpcService {
|
||||
Npc existing = npcRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Npc non trouvé avec l'ID: " + id));
|
||||
existing.setName(data.name());
|
||||
existing.setMarkdownContent(data.markdownContent());
|
||||
existing.setPortraitImageId(data.portraitImageId());
|
||||
existing.setHeaderImageId(data.headerImageId());
|
||||
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
|
||||
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
|
||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||
if (data.order() != null) {
|
||||
existing.setOrder(data.order());
|
||||
}
|
||||
@@ -61,7 +76,6 @@ public class NpcService {
|
||||
npcRepository.deleteById(id);
|
||||
}
|
||||
|
||||
/** Renvoie la prochaine position libre — append en fin de liste. */
|
||||
private int nextOrderFor(String campaignId) {
|
||||
return npcRepository.findByCampaignId(campaignId).stream()
|
||||
.mapToInt(Npc::getOrder)
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.loremind.application.gamesystemcontext;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
@@ -18,11 +19,14 @@ public class GameSystemService {
|
||||
|
||||
/**
|
||||
* Parameter Object pour la création / mise à jour d'un GameSystem.
|
||||
* Les templates peuvent etre null (interpretes comme listes vides).
|
||||
*/
|
||||
public record GameSystemData(
|
||||
String name,
|
||||
String description,
|
||||
String rulesMarkdown,
|
||||
List<TemplateField> characterTemplate,
|
||||
List<TemplateField> npcTemplate,
|
||||
String author,
|
||||
boolean isPublic
|
||||
) {}
|
||||
@@ -35,6 +39,8 @@ public class GameSystemService {
|
||||
.author(normalize(data.author()))
|
||||
.isPublic(data.isPublic())
|
||||
.build();
|
||||
gameSystem.replaceCharacterTemplate(data.characterTemplate());
|
||||
gameSystem.replaceNpcTemplate(data.npcTemplate());
|
||||
return gameSystemRepository.save(gameSystem);
|
||||
}
|
||||
|
||||
@@ -52,6 +58,8 @@ public class GameSystemService {
|
||||
existing.setName(data.name());
|
||||
existing.setDescription(data.description());
|
||||
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||
existing.replaceCharacterTemplate(data.characterTemplate());
|
||||
existing.replaceNpcTemplate(data.npcTemplate());
|
||||
existing.setAuthor(normalize(data.author()));
|
||||
existing.setPublic(data.isPublic());
|
||||
return gameSystemRepository.save(existing);
|
||||
|
||||
@@ -104,23 +104,32 @@ public class CampaignStructuralContextBuilder {
|
||||
* sans injecter toute sa fiche.
|
||||
*/
|
||||
private CharacterSummary toCharacterSummary(Character c) {
|
||||
return new CharacterSummary(c.getName(), extractSnippet(c.getMarkdownContent()));
|
||||
return new CharacterSummary(c.getName(), extractSnippet(c.getValues()));
|
||||
}
|
||||
|
||||
/** Symétrique à {@link #toCharacterSummary} pour les PNJ. */
|
||||
private NpcSummary toNpcSummary(Npc n) {
|
||||
return new NpcSummary(n.getName(), extractSnippet(n.getMarkdownContent()));
|
||||
return new NpcSummary(n.getName(), extractSnippet(n.getValues()));
|
||||
}
|
||||
|
||||
private static String extractSnippet(String markdown) {
|
||||
if (markdown == null || markdown.isBlank()) return "";
|
||||
String firstLine = markdown.lines()
|
||||
.map(String::strip)
|
||||
.filter(l -> !l.isEmpty() && !l.startsWith("#"))
|
||||
.findFirst()
|
||||
.orElse("");
|
||||
if (firstLine.length() <= CHARACTER_SNIPPET_MAX_LEN) return firstLine;
|
||||
return firstLine.substring(0, CHARACTER_SNIPPET_MAX_LEN - 1).stripTrailing() + "…";
|
||||
/**
|
||||
* Snippet pour le resume IA : 1re ligne signifiante de la 1re valeur non vide
|
||||
* du template (refonte 2026-04-30 — remplace l'ancien parsing markdown).
|
||||
*/
|
||||
private static String extractSnippet(java.util.Map<String, String> values) {
|
||||
if (values == null || values.isEmpty()) return "";
|
||||
for (String value : values.values()) {
|
||||
if (value == null || value.isBlank()) continue;
|
||||
String firstLine = value.lines()
|
||||
.map(String::strip)
|
||||
.filter(l -> !l.isEmpty() && !l.startsWith("#"))
|
||||
.findFirst()
|
||||
.orElse("");
|
||||
if (firstLine.isEmpty()) continue;
|
||||
if (firstLine.length() <= CHARACTER_SNIPPET_MAX_LEN) return firstLine;
|
||||
return firstLine.substring(0, CHARACTER_SNIPPET_MAX_LEN - 1).stripTrailing() + "…";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private ArcSummary toArcSummary(Arc arc) {
|
||||
|
||||
@@ -130,13 +130,19 @@ public class NarrativeEntityContextBuilder {
|
||||
|
||||
private NarrativeEntityContext fromCharacter(Character c) {
|
||||
Map<String, String> fields = new LinkedHashMap<>();
|
||||
putField(fields, "fiche complète (markdown)", c.getMarkdownContent());
|
||||
if (c.getValues() != null) {
|
||||
// Champs templates exposes individuellement — meilleur pour le LLM que
|
||||
// l'ancien blob markdown monolithique.
|
||||
c.getValues().forEach((k, v) -> putField(fields, k, v));
|
||||
}
|
||||
return new NarrativeEntityContext("character", c.getName(), fields);
|
||||
}
|
||||
|
||||
private NarrativeEntityContext fromNpc(Npc n) {
|
||||
Map<String, String> fields = new LinkedHashMap<>();
|
||||
putField(fields, "fiche complète (markdown)", n.getMarkdownContent());
|
||||
if (n.getValues() != null) {
|
||||
n.getValues().forEach((k, v) -> putField(fields, k, v));
|
||||
}
|
||||
return new NarrativeEntityContext("npc", n.getName(), fields);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.loremind.application.lorecontext;
|
||||
|
||||
import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.domain.lorecontext.ports.TemplateRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
|
||||
@@ -4,18 +4,26 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Fiche de personnage joueur (PJ) d'une campagne.
|
||||
* <p>
|
||||
* MVP : contenu markdown libre, l'utilisateur met ce qu'il veut (stats,
|
||||
* backstory, équipement). Évolution prévue vers un système templaté par
|
||||
* GameSystem (la fiche Nimble n'a pas les mêmes champs qu'une fiche D&D).
|
||||
* Champs universels hard-codes : {@code name}, {@code portraitImageId},
|
||||
* {@code headerImageId}. Tout le reste est piloté par le template PJ du
|
||||
* GameSystem associé à la campagne (cf. {@link com.loremind.domain.gamesystemcontext.GameSystem#getCharacterTemplate}).
|
||||
* <p>
|
||||
* Scope strict PJ : les PNJ sont gérés par l'entité {@link Npc} dédiée
|
||||
* (entité distincte plutôt qu'enum PJ/PNJ — invariants métier divergents).
|
||||
* Évolution prévue : système de templating partagé PJ/PNJ piloté par
|
||||
* GameSystem pour adapter les blocs aux différents systèmes de JDR.
|
||||
* Les valeurs des champs templates sont stockées dans deux maps :
|
||||
* - {@code values} : champs TEXT et NUMBER (numérique sérialisé en string,
|
||||
* parsé à l'usage cote presentation)
|
||||
* - {@code imageValues} : champs IMAGE (liste ordonnée d'IDs d'images par champ)
|
||||
* <p>
|
||||
* Le champ historique {@code markdownContent} a été supprimé (refonte 2026-04-30).
|
||||
* Le contenu pre-existant est migré dans {@code values["Notes"]} par défaut.
|
||||
* <p>
|
||||
* Scope strict PJ : les PNJ sont gérés par l'entité {@link Npc} (invariants divergents).
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@@ -24,11 +32,32 @@ public class Character {
|
||||
private String id;
|
||||
private String name;
|
||||
|
||||
/** ID de l'image portrait (champ universel hard-codé). Nullable. */
|
||||
private String portraitImageId;
|
||||
|
||||
/** ID de l'image header/banniere (champ universel hard-codé). Nullable. */
|
||||
private String headerImageId;
|
||||
|
||||
/**
|
||||
* Contenu libre en markdown — stats + backstory + notes. Nullable à la création,
|
||||
* renseigné progressivement par le MJ.
|
||||
* Valeurs des champs TEXT et NUMBER du template PJ. Cle = nom du champ
|
||||
* (sensible a la casse cote stockage mais comparaison case-insensitive
|
||||
* dans le domaine GameSystem). Jamais null apres construction.
|
||||
*/
|
||||
private String markdownContent;
|
||||
private Map<String, String> values;
|
||||
|
||||
/**
|
||||
* Valeurs des champs IMAGE du template PJ. Cle = nom du champ, valeur =
|
||||
* liste ordonnee d'IDs d'images. Jamais null apres construction.
|
||||
*/
|
||||
private Map<String, List<String>> imageValues;
|
||||
|
||||
/**
|
||||
* Valeurs des champs KEY_VALUE_LIST du template PJ. Cle externe = nom du
|
||||
* champ template (ex: "Caracteristiques"), cle interne = label predefini
|
||||
* dans le template (ex: "FOR"), valeur = valeur saisie (ex: "16").
|
||||
* Les labels suivent l'ordre defini dans TemplateField.labels.
|
||||
*/
|
||||
private Map<String, Map<String, String>> keyValueValues;
|
||||
|
||||
/** Référence vers la Campaign parente. */
|
||||
private String campaignId;
|
||||
@@ -38,4 +67,20 @@ public class Character {
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
/** Garantit que les maps ne sont jamais null cote consommateur. */
|
||||
public Map<String, String> getValues() {
|
||||
if (values == null) values = new HashMap<>();
|
||||
return values;
|
||||
}
|
||||
|
||||
public Map<String, List<String>> getImageValues() {
|
||||
if (imageValues == null) imageValues = new HashMap<>();
|
||||
return imageValues;
|
||||
}
|
||||
|
||||
public Map<String, Map<String, String>> getKeyValueValues() {
|
||||
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||
return keyValueValues;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,21 +4,22 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Fiche de personnage non-joueur (PNJ) d'une campagne.
|
||||
* <p>
|
||||
* MVP : entité dédiée, distincte de {@link Character} (PJ). Choix DDD assumé —
|
||||
* un PNJ a vocation à porter à terme des invariants métier propres (faction,
|
||||
* statut vivant/mort/disparu, visibilité côté joueurs, relations inter-PNJ)
|
||||
* qui n'ont aucun sens sur un PJ. Mutualiser via un enum aurait pollué l'entité
|
||||
* PJ avec des champs inutiles ({@code if (type == NPC)} partout = anti-pattern).
|
||||
* Entité dédiée distincte de {@link Character} (DDD assumé : invariants divergents
|
||||
* à terme — faction, statut vivant/mort, visibilité côté joueurs, etc.).
|
||||
* <p>
|
||||
* Contenu markdown libre comme les PJ. Évolution prévue : templating partagé
|
||||
* PJ/PNJ piloté par GameSystem.
|
||||
* Mêmes champs universels hard-codés et meme structure de templating que Character,
|
||||
* pilotée par le template PNJ du GameSystem
|
||||
* ({@link com.loremind.domain.gamesystemcontext.GameSystem#getNpcTemplate}).
|
||||
* <p>
|
||||
* Scope campagne : les PNJ "univers" (worldboss, figures du Lore) restent
|
||||
* gérés via le système Page/Template du LoreContext.
|
||||
* Scope campagne : les PNJ "univers" (worldboss, figures du Lore) restent gérés
|
||||
* via le système Page/Template du LoreContext.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@@ -27,10 +28,22 @@ public class Npc {
|
||||
private String id;
|
||||
private String name;
|
||||
|
||||
/** Contenu libre markdown — description, motivation, stats, notes MJ. Nullable à la création. */
|
||||
private String markdownContent;
|
||||
/** ID de l'image portrait (champ universel hard-code). Nullable. */
|
||||
private String portraitImageId;
|
||||
|
||||
/** Référence vers la Campaign parente (cross-aggregate via ID, jamais d'objet). */
|
||||
/** ID de l'image header/banniere (champ universel hard-code). Nullable. */
|
||||
private String headerImageId;
|
||||
|
||||
/** Valeurs TEXT/NUMBER du template PNJ. Jamais null apres construction. */
|
||||
private Map<String, String> values;
|
||||
|
||||
/** Valeurs IMAGE du template PNJ (listes d'IDs ordonnees par champ). Jamais null. */
|
||||
private Map<String, List<String>> imageValues;
|
||||
|
||||
/** Valeurs KEY_VALUE_LIST : fieldName -> label -> value. Jamais null. */
|
||||
private Map<String, Map<String, String>> keyValueValues;
|
||||
|
||||
/** Référence vers la Campaign parente (cross-aggregate via ID). */
|
||||
private String campaignId;
|
||||
|
||||
/** Ordre d'affichage dans la liste des PNJ de la campagne. */
|
||||
@@ -38,4 +51,19 @@ public class Npc {
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
|
||||
public Map<String, String> getValues() {
|
||||
if (values == null) values = new HashMap<>();
|
||||
return values;
|
||||
}
|
||||
|
||||
public Map<String, List<String>> getImageValues() {
|
||||
if (imageValues == null) imageValues = new HashMap<>();
|
||||
return imageValues;
|
||||
}
|
||||
|
||||
public Map<String, Map<String, String>> getKeyValueValues() {
|
||||
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||
return keyValueValues;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.loremind.domain.gamesystemcontext;
|
||||
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Entité de domaine représentant un GameSystem (système de JDR).
|
||||
@@ -12,6 +16,10 @@ import java.time.LocalDateTime;
|
||||
* d'un markdown monolithique structuré par titres H2. Les sections sont extraites
|
||||
* à la volée lors de l'injection dans les prompts IA (cf. GameSystemContextSelector).
|
||||
* <p>
|
||||
* Porte aussi deux templates piloтant la structure des fiches PJ et PNJ d'une
|
||||
* campagne adossée à ce système. Les fiches markdown libres ont laissé place à
|
||||
* un système de champs typés (TEXT/IMAGE/NUMBER) défini ici.
|
||||
* <p>
|
||||
* {@code author} et {@code isPublic} sont des champs pensés pour un futur marketplace
|
||||
* de rulesets partagés — non exploités au MVP mais persistés dès maintenant pour
|
||||
* éviter une migration ultérieure.
|
||||
@@ -27,6 +35,21 @@ public class GameSystem {
|
||||
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
||||
private String rulesMarkdown;
|
||||
|
||||
/**
|
||||
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
|
||||
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après
|
||||
* persistance — un template vide est représenté par une liste vide.
|
||||
*/
|
||||
private List<TemplateField> characterTemplate;
|
||||
|
||||
/**
|
||||
* Template de fiche PNJ. Mêmes règles que {@link #characterTemplate}.
|
||||
* Distinct du template PJ car les invariants métier divergent (un PNJ peut
|
||||
* n'avoir qu'un nom + une motivation, un PJ porte généralement une feuille
|
||||
* de stats complète).
|
||||
*/
|
||||
private List<TemplateField> npcTemplate;
|
||||
|
||||
/** Auteur déclaré — futur marketplace. Nullable. */
|
||||
private String author;
|
||||
|
||||
@@ -35,4 +58,88 @@ public class GameSystem {
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
// --- Méthodes métier : templates PJ/PNJ --------------------------------
|
||||
|
||||
/**
|
||||
* Ajoute un champ au template PJ. Refuse les doublons de nom (insensible à la casse)
|
||||
* pour éviter les collisions de clés dans {@code Character.values}.
|
||||
*/
|
||||
public void addCharacterField(TemplateField field) {
|
||||
characterTemplate = appendField(characterTemplate, field);
|
||||
}
|
||||
|
||||
/** Pendant PNJ de {@link #addCharacterField}. */
|
||||
public void addNpcField(TemplateField field) {
|
||||
npcTemplate = appendField(npcTemplate, field);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retire un champ du template PJ par nom (insensible à la casse).
|
||||
* No-op silencieux si le champ n'existe pas — appelant n'a pas à pré-vérifier.
|
||||
*/
|
||||
public void removeCharacterField(String fieldName) {
|
||||
characterTemplate = removeFieldByName(characterTemplate, fieldName);
|
||||
}
|
||||
|
||||
public void removeNpcField(String fieldName) {
|
||||
npcTemplate = removeFieldByName(npcTemplate, fieldName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remplace intégralement le template PJ. Utilisé pour le réordonnancement
|
||||
* et l'édition en bloc côté UI. Valide l'unicité des noms.
|
||||
*/
|
||||
public void replaceCharacterTemplate(List<TemplateField> fields) {
|
||||
characterTemplate = validateAndCopy(fields);
|
||||
}
|
||||
|
||||
public void replaceNpcTemplate(List<TemplateField> fields) {
|
||||
npcTemplate = validateAndCopy(fields);
|
||||
}
|
||||
|
||||
// --- Helpers privés ----------------------------------------------------
|
||||
|
||||
private static List<TemplateField> appendField(List<TemplateField> current, TemplateField field) {
|
||||
if (field == null || field.getName() == null || field.getName().isBlank()) {
|
||||
throw new IllegalArgumentException("Field name is required");
|
||||
}
|
||||
List<TemplateField> next = current == null ? new ArrayList<>() : new ArrayList<>(current);
|
||||
if (containsName(next, field.getName())) {
|
||||
throw new IllegalArgumentException("Duplicate field name: " + field.getName());
|
||||
}
|
||||
next.add(field);
|
||||
return next;
|
||||
}
|
||||
|
||||
private static List<TemplateField> removeFieldByName(List<TemplateField> current, String fieldName) {
|
||||
if (current == null || fieldName == null) return current;
|
||||
List<TemplateField> next = new ArrayList<>(current);
|
||||
next.removeIf(f -> equalsIgnoreCase(f.getName(), fieldName));
|
||||
return next;
|
||||
}
|
||||
|
||||
private static List<TemplateField> validateAndCopy(List<TemplateField> fields) {
|
||||
if (fields == null) return new ArrayList<>();
|
||||
List<TemplateField> copy = new ArrayList<>(fields.size());
|
||||
for (TemplateField f : fields) {
|
||||
if (f == null || f.getName() == null || f.getName().isBlank()) {
|
||||
throw new IllegalArgumentException("Field name is required");
|
||||
}
|
||||
if (containsName(copy, f.getName())) {
|
||||
throw new IllegalArgumentException("Duplicate field name: " + f.getName());
|
||||
}
|
||||
copy.add(f);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static boolean containsName(List<TemplateField> fields, String name) {
|
||||
return fields.stream().anyMatch(f -> equalsIgnoreCase(f.getName(), name));
|
||||
}
|
||||
|
||||
private static boolean equalsIgnoreCase(String a, String b) {
|
||||
if (a == null || b == null) return a == b;
|
||||
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.loremind.domain.lorecontext;
|
||||
|
||||
/**
|
||||
* Type d'un champ dynamique d'un Template.
|
||||
* <p>
|
||||
* - TEXT : valeur textuelle libre (stockee dans Page.values : Map<String, String>)
|
||||
* - IMAGE : galerie d'images, represente comme une liste d'IDs d'images
|
||||
* (stockee dans Page.imageValues : Map<String, List<String>>)
|
||||
* <p>
|
||||
* Extension future possible : RICH_TEXT, NUMBER, DATE, BOOLEAN, LORE_LINK...
|
||||
*/
|
||||
public enum FieldType {
|
||||
TEXT,
|
||||
IMAGE
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.loremind.domain.lorecontext;
|
||||
|
||||
import com.loremind.domain.shared.template.FieldType;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.loremind.domain.lorecontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* Value Object d'un champ de Template.
|
||||
* <p>
|
||||
* Un champ a un nom (affiche dans l'UI) et un type (TEXT ou IMAGE, extensible).
|
||||
* Le type pilote le rendu cote front (textarea vs galerie d'images) ET
|
||||
* la logique metier (seuls les champs TEXT sont envoyes a l'IA pour generation).
|
||||
* <p>
|
||||
* Pour les champs IMAGE, {@link #layout} precise la variante de rendu
|
||||
* (gallery/hero/masonry/carousel). Nullable : l'absence equivaut a GALLERY.
|
||||
* Ignore pour les champs TEXT.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TemplateField {
|
||||
/** Nom du champ tel qu'affiche dans l'UI (ex: "Histoire", "Portrait"). */
|
||||
private String name;
|
||||
/** Type du champ, pilote le rendu et la generation IA. */
|
||||
private FieldType type;
|
||||
/** Variante de rendu pour les champs IMAGE. Null = GALLERY. */
|
||||
private ImageLayout layout;
|
||||
|
||||
/** Constructeur de retrocompat : type seul, layout=null. */
|
||||
public TemplateField(String name, FieldType type) {
|
||||
this(name, type, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ de type TEXT (cas le plus courant). */
|
||||
public static TemplateField text(String name) {
|
||||
return new TemplateField(name, FieldType.TEXT, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ de type IMAGE avec layout GALLERY. */
|
||||
public static TemplateField image(String name) {
|
||||
return new TemplateField(name, FieldType.IMAGE, ImageLayout.GALLERY);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ IMAGE avec un layout specifique. */
|
||||
public static TemplateField image(String name, ImageLayout layout) {
|
||||
return new TemplateField(name, FieldType.IMAGE, layout);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.loremind.domain.shared.template;
|
||||
|
||||
/**
|
||||
* Type d'un champ dynamique de template (kernel partage).
|
||||
* <p>
|
||||
* - TEXT : valeur textuelle libre (Map<String, String>)
|
||||
* - IMAGE : galerie d'images, liste d'IDs (Map<String, List<String>>)
|
||||
* - NUMBER : valeur numerique stockee en texte (parsee a l'usage)
|
||||
* - KEY_VALUE_LIST : liste de paires {label, value} avec labels figes au template
|
||||
* (Map<String, Map<String, String>> : fieldName -> label -> value).
|
||||
* Usage : stat blocks, listes de competences, traits.
|
||||
* <p>
|
||||
* Extension future possible : RICH_TEXT, DATE, BOOLEAN, REFERENCE...
|
||||
*/
|
||||
public enum FieldType {
|
||||
TEXT,
|
||||
IMAGE,
|
||||
NUMBER,
|
||||
KEY_VALUE_LIST
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.loremind.domain.lorecontext;
|
||||
package com.loremind.domain.shared.template;
|
||||
|
||||
/**
|
||||
* Variante de rendu pour un champ de type IMAGE.
|
||||
@@ -8,7 +8,7 @@ package com.loremind.domain.lorecontext;
|
||||
* - MASONRY : mosaique hauteurs variables facon Pinterest
|
||||
* - CAROUSEL : defilement horizontal
|
||||
* <p>
|
||||
* Uniquement significatif quand {@link FieldType} = IMAGE. Ignore pour TEXT.
|
||||
* Uniquement significatif quand {@link FieldType} = IMAGE. Ignore sinon.
|
||||
*/
|
||||
public enum ImageLayout {
|
||||
GALLERY,
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.loremind.domain.shared.template;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Value Object d'un champ de Template (kernel partage).
|
||||
* <p>
|
||||
* Un champ a un nom (affiche dans l'UI) et un type. Le type pilote
|
||||
* le rendu cote front et la logique metier (seuls les champs TEXT sont
|
||||
* envoyes a l'IA pour generation).
|
||||
* <p>
|
||||
* Pour les champs IMAGE, {@link #layout} precise la variante de rendu
|
||||
* (gallery/hero/masonry/carousel). Nullable : l'absence equivaut a GALLERY.
|
||||
* Ignore pour les autres types.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TemplateField {
|
||||
/** Nom du champ tel qu'affiche dans l'UI (ex: "Histoire", "Portrait"). */
|
||||
private String name;
|
||||
/** Type du champ, pilote le rendu et la generation IA. */
|
||||
private FieldType type;
|
||||
/** Variante de rendu pour les champs IMAGE. Null = GALLERY. */
|
||||
private ImageLayout layout;
|
||||
/**
|
||||
* Labels predefinis pour les champs KEY_VALUE_LIST (ordre significatif).
|
||||
* Ex: ["FOR","DEX","CON","INT","SAG","CHA"] pour un champ "Caracteristiques".
|
||||
* Null/vide pour les autres types.
|
||||
*/
|
||||
private List<String> labels;
|
||||
|
||||
/** Constructeur de retrocompat : type seul, layout/labels=null. */
|
||||
public TemplateField(String name, FieldType type) {
|
||||
this(name, type, null, null);
|
||||
}
|
||||
|
||||
/** Constructeur de retrocompat : type + layout, labels=null. */
|
||||
public TemplateField(String name, FieldType type, ImageLayout layout) {
|
||||
this(name, type, layout, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ de type TEXT (cas le plus courant). */
|
||||
public static TemplateField text(String name) {
|
||||
return new TemplateField(name, FieldType.TEXT, null, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ de type IMAGE avec layout GALLERY. */
|
||||
public static TemplateField image(String name) {
|
||||
return new TemplateField(name, FieldType.IMAGE, ImageLayout.GALLERY, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ IMAGE avec un layout specifique. */
|
||||
public static TemplateField image(String name, ImageLayout layout) {
|
||||
return new TemplateField(name, FieldType.IMAGE, layout, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ de type NUMBER. */
|
||||
public static TemplateField number(String name) {
|
||||
return new TemplateField(name, FieldType.NUMBER, null, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ KEY_VALUE_LIST avec labels predefinis. */
|
||||
public static TemplateField keyValueList(String name, List<String> labels) {
|
||||
return new TemplateField(name, FieldType.KEY_VALUE_LIST, null, labels);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.loremind.infrastructure.persistence;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Backfill one-shot des fiches Character / Npc post-refonte 2026-04-30.
|
||||
* <p>
|
||||
* Avant la refonte, les fiches stockaient leur contenu dans la colonne
|
||||
* {@code markdown_content}. Apres la refonte, le contenu est dans
|
||||
* {@code field_values} (JSON Map<String,String>). La colonne
|
||||
* {@code markdown_content} subsiste car Hibernate ddl-auto=update ne drop pas.
|
||||
* <p>
|
||||
* Ce backfill copie {@code markdown_content} dans {@code field_values["Notes"]}
|
||||
* pour toutes les fiches qui ont un markdown non vide ET un field_values vide.
|
||||
* Idempotent : si field_values contient deja des donnees, on ne touche pas.
|
||||
* <p>
|
||||
* La colonne {@code markdown_content} n'est PAS supprimee apres backfill —
|
||||
* permet un rollback applicatif au cas ou. Suppression definitive a faire dans
|
||||
* une release ulterieure quand la confiance est etablie.
|
||||
*/
|
||||
@Component
|
||||
public class CharacterNpcMarkdownBackfill {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(CharacterNpcMarkdownBackfill.class);
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public CharacterNpcMarkdownBackfill(JdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void backfillIfNeeded() {
|
||||
if (!hasMarkdownContentColumn("characters")) {
|
||||
log.debug("Backfill skip : colonne markdown_content absente (deja migre ou install propre).");
|
||||
return;
|
||||
}
|
||||
int chars = backfillTable("characters");
|
||||
int npcs = backfillTable("npcs");
|
||||
if (chars + npcs > 0) {
|
||||
log.info("Backfill markdown -> field_values : {} character(s), {} npc(s) migre(s).", chars, npcs);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasMarkdownContentColumn(String table) {
|
||||
try {
|
||||
Integer count = jdbc.queryForObject(
|
||||
"SELECT COUNT(*) FROM information_schema.columns "
|
||||
+ "WHERE table_name = ? AND column_name = 'markdown_content'",
|
||||
Integer.class, table);
|
||||
return count != null && count > 0;
|
||||
} catch (Exception e) {
|
||||
log.warn("Backfill : impossible de verifier la colonne markdown_content sur {}: {}",
|
||||
table, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int backfillTable(String table) {
|
||||
// Selection : fiches avec markdown non vide ET field_values vide ou absent.
|
||||
// field_values peut etre NULL (legacy avant refonte) ou "{}" (refonte appliquee mais sans data).
|
||||
String selectSql = "SELECT id, markdown_content FROM " + table
|
||||
+ " WHERE markdown_content IS NOT NULL "
|
||||
+ " AND markdown_content <> '' "
|
||||
+ " AND (field_values IS NULL OR field_values = '' OR field_values = '{}')";
|
||||
|
||||
var rows = jdbc.queryForList(selectSql);
|
||||
int migrated = 0;
|
||||
for (var row : rows) {
|
||||
Long id = ((Number) row.get("id")).longValue();
|
||||
String markdown = (String) row.get("markdown_content");
|
||||
String json;
|
||||
try {
|
||||
json = mapper.writeValueAsString(Map.of("Notes", markdown));
|
||||
} catch (Exception e) {
|
||||
log.error("Backfill {} id={} : echec serialisation JSON, ignore. {}", table, id, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
jdbc.update("UPDATE " + table + " SET field_values = ? WHERE id = ?", json, id);
|
||||
migrated++;
|
||||
}
|
||||
return migrated;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package com.loremind.infrastructure.persistence;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import com.loremind.domain.shared.template.ImageLayout;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
@@ -23,6 +25,10 @@ import java.util.List;
|
||||
* <p>
|
||||
* Idempotence : ne seed qu'une fois. Si l'utilisateur supprime un ruleset seedé,
|
||||
* il ne revient pas au redémarrage — c'est voulu (respect du choix utilisateur).
|
||||
* <p>
|
||||
* Backfill 2026-04-30 : pour les GameSystems existants (avant la refonte
|
||||
* template-based), on remplit aussi les templates PJ/PNJ par defaut s'ils
|
||||
* sont vides — sinon les fiches restent inutilisables.
|
||||
*/
|
||||
@Component
|
||||
public class GameSystemSeeder {
|
||||
@@ -37,15 +43,37 @@ public class GameSystemSeeder {
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void seedIfEmpty() {
|
||||
if (!gameSystemRepository.findAll().isEmpty()) {
|
||||
log.debug("GameSystem seed skipped — table non vide.");
|
||||
List<GameSystem> existing = gameSystemRepository.findAll();
|
||||
if (existing.isEmpty()) {
|
||||
log.info("Seed initial des GameSystems (table vide)...");
|
||||
for (GameSystem gs : defaultSystems()) {
|
||||
gameSystemRepository.save(gs);
|
||||
}
|
||||
log.info("GameSystems seedés : {}", defaultSystems().size());
|
||||
return;
|
||||
}
|
||||
log.info("Seed initial des GameSystems (table vide)...");
|
||||
for (GameSystem gs : defaultSystems()) {
|
||||
gameSystemRepository.save(gs);
|
||||
log.debug("GameSystem seed skipped — table non vide. Backfill templates si necessaire...");
|
||||
backfillEmptyTemplates(existing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Backfill idempotent : pour chaque GameSystem existant ou les deux templates
|
||||
* sont vides (PJ ET PNJ), injecte le template generique. Si l'utilisateur a
|
||||
* deja personnalise au moins un des deux, on ne touche a rien.
|
||||
*/
|
||||
private void backfillEmptyTemplates(List<GameSystem> systems) {
|
||||
int patched = 0;
|
||||
for (GameSystem gs : systems) {
|
||||
boolean charEmpty = gs.getCharacterTemplate() == null || gs.getCharacterTemplate().isEmpty();
|
||||
boolean npcEmpty = gs.getNpcTemplate() == null || gs.getNpcTemplate().isEmpty();
|
||||
if (charEmpty && npcEmpty) {
|
||||
gs.replaceCharacterTemplate(genericCharacterTemplate());
|
||||
gs.replaceNpcTemplate(genericNpcTemplate());
|
||||
gameSystemRepository.save(gs);
|
||||
patched++;
|
||||
}
|
||||
}
|
||||
log.info("GameSystems seedés : {}", defaultSystems().size());
|
||||
if (patched > 0) log.info("Backfill templates GameSystem : {} systeme(s) patche(s).", patched);
|
||||
}
|
||||
|
||||
private List<GameSystem> defaultSystems() {
|
||||
@@ -56,6 +84,8 @@ public class GameSystemSeeder {
|
||||
.author("LoreMind seed")
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(NIMBLE_RULES)
|
||||
.characterTemplate(nimbleCharacterTemplate())
|
||||
.npcTemplate(genericNpcTemplate())
|
||||
.build(),
|
||||
GameSystem.builder()
|
||||
.name("D&D 5e SRD (extrait)")
|
||||
@@ -63,6 +93,8 @@ public class GameSystemSeeder {
|
||||
.author("LoreMind seed")
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(DND_SRD_RULES)
|
||||
.characterTemplate(dndCharacterTemplate())
|
||||
.npcTemplate(genericNpcTemplate())
|
||||
.build(),
|
||||
GameSystem.builder()
|
||||
.name("Homebrew Exemple")
|
||||
@@ -70,10 +102,66 @@ public class GameSystemSeeder {
|
||||
.author("LoreMind seed")
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(HOMEBREW_EXAMPLE)
|
||||
.characterTemplate(genericCharacterTemplate())
|
||||
.npcTemplate(genericNpcTemplate())
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
// --- Templates par defaut ---------------------------------------------
|
||||
|
||||
/** Template generique PJ — utilise pour Homebrew, backfill, et fallback. */
|
||||
private static List<TemplateField> genericCharacterTemplate() {
|
||||
return List.of(
|
||||
TemplateField.text("Histoire"),
|
||||
TemplateField.text("Personnalite"),
|
||||
TemplateField.text("Apparence"),
|
||||
TemplateField.image("Galerie", ImageLayout.GALLERY),
|
||||
TemplateField.text("Notes")
|
||||
);
|
||||
}
|
||||
|
||||
/** Template generique PNJ — focus besoins MJ. */
|
||||
private static List<TemplateField> genericNpcTemplate() {
|
||||
return List.of(
|
||||
TemplateField.text("Apparence"),
|
||||
TemplateField.text("Motivation"),
|
||||
TemplateField.text("Faction"),
|
||||
TemplateField.text("Notes MJ")
|
||||
);
|
||||
}
|
||||
|
||||
private static List<TemplateField> nimbleCharacterTemplate() {
|
||||
return List.of(
|
||||
TemplateField.text("Classe"),
|
||||
TemplateField.number("Blessures graves max"),
|
||||
TemplateField.text("Capacites de classe"),
|
||||
TemplateField.text("Equipement"),
|
||||
TemplateField.text("Histoire"),
|
||||
TemplateField.text("Objectifs personnels"),
|
||||
TemplateField.image("Galerie", ImageLayout.GALLERY)
|
||||
);
|
||||
}
|
||||
|
||||
private static List<TemplateField> dndCharacterTemplate() {
|
||||
return List.of(
|
||||
TemplateField.text("Classe"),
|
||||
TemplateField.text("Race"),
|
||||
TemplateField.text("Historique"),
|
||||
TemplateField.text("Alignement"),
|
||||
TemplateField.number("Niveau"),
|
||||
TemplateField.number("PV max"),
|
||||
TemplateField.number("CA"),
|
||||
TemplateField.keyValueList("Caracteristiques",
|
||||
List.of("FOR", "DEX", "CON", "INT", "SAG", "CHA")),
|
||||
TemplateField.text("Competences"),
|
||||
TemplateField.text("Equipement"),
|
||||
TemplateField.text("Sorts"),
|
||||
TemplateField.text("Histoire"),
|
||||
TemplateField.image("Galerie", ImageLayout.GALLERY)
|
||||
);
|
||||
}
|
||||
|
||||
private static final String NIMBLE_RULES = """
|
||||
Système Nimble — résolution rapide, narration fluide, peu de tableaux. Agnostique (aucun univers imposé).
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.loremind.infrastructure.persistence.converter;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Convertit une Map<String, Map<String, String>> en JSON et inversement.
|
||||
* <p>
|
||||
* Utilise pour Character/Npc.keyValueValues : pour chaque champ KEY_VALUE_LIST
|
||||
* du template, stocke une map label -> value. Exemple :
|
||||
* {"Caracteristiques": {"FOR":"16","DEX":"12","CON":"14"}}
|
||||
* <p>
|
||||
* Adaptateur technique pur : le domaine ignore ce converter.
|
||||
*/
|
||||
@Converter
|
||||
public class StringMapMapJsonConverter
|
||||
implements AttributeConverter<Map<String, Map<String, String>>, String> {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final TypeReference<Map<String, Map<String, String>>> TYPE_REF =
|
||||
new TypeReference<>() {};
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(Map<String, Map<String, String>> attribute) {
|
||||
if (attribute == null || attribute.isEmpty()) return "{}";
|
||||
try {
|
||||
return MAPPER.writeValueAsString(attribute);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(
|
||||
"Erreur serialisation Map<String, Map<String,String>> -> JSON", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Map<String, String>> convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isBlank()) return Collections.emptyMap();
|
||||
try {
|
||||
return MAPPER.readValue(dbData, TYPE_REF);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(
|
||||
"Erreur deserialisation JSON -> Map<String, Map<String,String>>", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@ package com.loremind.infrastructure.persistence.converter;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.lorecontext.FieldType;
|
||||
import com.loremind.domain.lorecontext.ImageLayout;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.FieldType;
|
||||
import com.loremind.domain.shared.template.ImageLayout;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
@@ -85,8 +85,18 @@ public class TemplateFieldListJsonConverter
|
||||
}
|
||||
}
|
||||
}
|
||||
List<String> labels = null;
|
||||
if (type == FieldType.KEY_VALUE_LIST) {
|
||||
JsonNode labelsNode = item.path("labels");
|
||||
if (labelsNode.isArray()) {
|
||||
labels = new ArrayList<>();
|
||||
for (JsonNode label : labelsNode) {
|
||||
if (label.isTextual()) labels.add(label.asText());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (name != null && !name.isBlank()) {
|
||||
result.add(new TemplateField(name, type, layout));
|
||||
result.add(new TemplateField(name, type, layout, labels));
|
||||
}
|
||||
}
|
||||
// Autres types de noeuds (nombre, booleen...) : ignores silencieusement.
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import com.loremind.infrastructure.persistence.converter.StringListMapJsonConverter;
|
||||
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||
import com.loremind.infrastructure.persistence.converter.StringMapMapJsonConverter;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -7,11 +10,18 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Entité JPA pour les fiches de personnages (PJ) d'une campagne.
|
||||
* Pas de FK physique vers campaigns (weak reference cross-agrégat intra-contexte :
|
||||
* on reste dans le Campaign Context, mais l'agrégat Character est autonome).
|
||||
* Entité JPA pour les fiches de personnages (PJ).
|
||||
* <p>
|
||||
* Refonte 2026-04-30 : ancien champ markdownContent migré vers {@code values["Notes"]}
|
||||
* via Hibernate au demarrage. Hibernate ddl-auto=update ajoute les nouvelles colonnes
|
||||
* sans dropper {@code markdown_content} — les donnees existantes sont conservees mais
|
||||
* plus mappees au domaine. Migration manuelle prevue (script SQL one-shot) si le
|
||||
* deploiement passe en bluegreen.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "characters")
|
||||
@@ -28,8 +38,26 @@ public class CharacterJpaEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(name = "markdown_content", columnDefinition = "TEXT")
|
||||
private String markdownContent;
|
||||
@Column(name = "portrait_image_id")
|
||||
private String portraitImageId;
|
||||
|
||||
@Column(name = "header_image_id")
|
||||
private String headerImageId;
|
||||
|
||||
/** Valeurs TEXT/NUMBER serialisees JSON. */
|
||||
@Convert(converter = StringMapJsonConverter.class)
|
||||
@Column(name = "field_values", columnDefinition = "TEXT")
|
||||
private Map<String, String> values;
|
||||
|
||||
/** Valeurs IMAGE serialisees JSON. */
|
||||
@Convert(converter = StringListMapJsonConverter.class)
|
||||
@Column(name = "image_values", columnDefinition = "TEXT")
|
||||
private Map<String, List<String>> imageValues;
|
||||
|
||||
/** Valeurs KEY_VALUE_LIST serialisees JSON (fieldName -> label -> value). */
|
||||
@Convert(converter = StringMapMapJsonConverter.class)
|
||||
@Column(name = "key_value_values", columnDefinition = "TEXT")
|
||||
private Map<String, Map<String, String>> keyValueValues;
|
||||
|
||||
@Column(name = "campaign_id", nullable = false)
|
||||
private Long campaignId;
|
||||
@@ -47,6 +75,9 @@ public class CharacterJpaEntity {
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
if (values == null) values = new HashMap<>();
|
||||
if (imageValues == null) imageValues = new HashMap<>();
|
||||
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.persistence.converter.TemplateFieldListJsonConverter;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -7,6 +9,8 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Entité JPA pour la persistance des GameSystems (systèmes de JDR).
|
||||
@@ -32,6 +36,16 @@ public class GameSystemJpaEntity {
|
||||
@Column(name = "rules_markdown", columnDefinition = "TEXT")
|
||||
private String rulesMarkdown;
|
||||
|
||||
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
|
||||
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||
@Column(name = "character_template", columnDefinition = "TEXT")
|
||||
private List<TemplateField> characterTemplate;
|
||||
|
||||
/** Template PNJ serialise en JSON. */
|
||||
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||
@Column(name = "npc_template", columnDefinition = "TEXT")
|
||||
private List<TemplateField> npcTemplate;
|
||||
|
||||
@Column
|
||||
private String author;
|
||||
|
||||
@@ -48,6 +62,8 @@ public class GameSystemJpaEntity {
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
if (characterTemplate == null) characterTemplate = new ArrayList<>();
|
||||
if (npcTemplate == null) npcTemplate = new ArrayList<>();
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import com.loremind.infrastructure.persistence.converter.StringListMapJsonConverter;
|
||||
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||
import com.loremind.infrastructure.persistence.converter.StringMapMapJsonConverter;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -7,10 +10,13 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Entité JPA pour les fiches de PNJ d'une campagne.
|
||||
* Pas de FK physique vers campaigns (weak reference cross-agrégat intra-contexte).
|
||||
* Entité JPA pour les fiches de PNJ. Memes regles que CharacterJpaEntity
|
||||
* (cf. note de refonte 2026-04-30 sur la migration markdownContent).
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "npcs")
|
||||
@@ -27,8 +33,23 @@ public class NpcJpaEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(name = "markdown_content", columnDefinition = "TEXT")
|
||||
private String markdownContent;
|
||||
@Column(name = "portrait_image_id")
|
||||
private String portraitImageId;
|
||||
|
||||
@Column(name = "header_image_id")
|
||||
private String headerImageId;
|
||||
|
||||
@Convert(converter = StringMapJsonConverter.class)
|
||||
@Column(name = "field_values", columnDefinition = "TEXT")
|
||||
private Map<String, String> values;
|
||||
|
||||
@Convert(converter = StringListMapJsonConverter.class)
|
||||
@Column(name = "image_values", columnDefinition = "TEXT")
|
||||
private Map<String, List<String>> imageValues;
|
||||
|
||||
@Convert(converter = StringMapMapJsonConverter.class)
|
||||
@Column(name = "key_value_values", columnDefinition = "TEXT")
|
||||
private Map<String, Map<String, String>> keyValueValues;
|
||||
|
||||
@Column(name = "campaign_id", nullable = false)
|
||||
private Long campaignId;
|
||||
@@ -46,6 +67,9 @@ public class NpcJpaEntity {
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
if (values == null) values = new HashMap<>();
|
||||
if (imageValues == null) imageValues = new HashMap<>();
|
||||
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.persistence.converter.TemplateFieldListJsonConverter;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.loremind.infrastructure.persistence.entity.CharacterJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.CharacterJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -52,7 +53,11 @@ public class PostgresCharacterRepository implements CharacterRepository {
|
||||
return Character.builder()
|
||||
.id(e.getId().toString())
|
||||
.name(e.getName())
|
||||
.markdownContent(e.getMarkdownContent())
|
||||
.portraitImageId(e.getPortraitImageId())
|
||||
.headerImageId(e.getHeaderImageId())
|
||||
.values(e.getValues() != null ? new HashMap<>(e.getValues()) : new HashMap<>())
|
||||
.imageValues(e.getImageValues() != null ? new HashMap<>(e.getImageValues()) : new HashMap<>())
|
||||
.keyValueValues(e.getKeyValueValues() != null ? new HashMap<>(e.getKeyValueValues()) : new HashMap<>())
|
||||
.campaignId(e.getCampaignId().toString())
|
||||
.order(e.getOrder())
|
||||
.createdAt(e.getCreatedAt())
|
||||
@@ -65,7 +70,11 @@ public class PostgresCharacterRepository implements CharacterRepository {
|
||||
return CharacterJpaEntity.builder()
|
||||
.id(id)
|
||||
.name(c.getName())
|
||||
.markdownContent(c.getMarkdownContent())
|
||||
.portraitImageId(c.getPortraitImageId())
|
||||
.headerImageId(c.getHeaderImageId())
|
||||
.values(c.getValues() != null ? new HashMap<>(c.getValues()) : new HashMap<>())
|
||||
.imageValues(c.getImageValues() != null ? new HashMap<>(c.getImageValues()) : new HashMap<>())
|
||||
.keyValueValues(c.getKeyValueValues() != null ? new HashMap<>(c.getKeyValueValues()) : new HashMap<>())
|
||||
.campaignId(Long.parseLong(c.getCampaignId()))
|
||||
.order(c.getOrder())
|
||||
.createdAt(c.getCreatedAt())
|
||||
|
||||
@@ -61,6 +61,12 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
||||
.name(e.getName())
|
||||
.description(e.getDescription())
|
||||
.rulesMarkdown(e.getRulesMarkdown())
|
||||
.characterTemplate(e.getCharacterTemplate() != null
|
||||
? new java.util.ArrayList<>(e.getCharacterTemplate())
|
||||
: new java.util.ArrayList<>())
|
||||
.npcTemplate(e.getNpcTemplate() != null
|
||||
? new java.util.ArrayList<>(e.getNpcTemplate())
|
||||
: new java.util.ArrayList<>())
|
||||
.author(e.getAuthor())
|
||||
.isPublic(e.isPublic())
|
||||
.createdAt(e.getCreatedAt())
|
||||
@@ -75,6 +81,12 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
||||
.name(g.getName())
|
||||
.description(g.getDescription())
|
||||
.rulesMarkdown(g.getRulesMarkdown())
|
||||
.characterTemplate(g.getCharacterTemplate() != null
|
||||
? new java.util.ArrayList<>(g.getCharacterTemplate())
|
||||
: new java.util.ArrayList<>())
|
||||
.npcTemplate(g.getNpcTemplate() != null
|
||||
? new java.util.ArrayList<>(g.getNpcTemplate())
|
||||
: new java.util.ArrayList<>())
|
||||
.author(g.getAuthor())
|
||||
.isPublic(g.isPublic())
|
||||
.createdAt(g.getCreatedAt())
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.loremind.infrastructure.persistence.entity.NpcJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.NpcJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -52,7 +53,11 @@ public class PostgresNpcRepository implements NpcRepository {
|
||||
return Npc.builder()
|
||||
.id(e.getId().toString())
|
||||
.name(e.getName())
|
||||
.markdownContent(e.getMarkdownContent())
|
||||
.portraitImageId(e.getPortraitImageId())
|
||||
.headerImageId(e.getHeaderImageId())
|
||||
.values(e.getValues() != null ? new HashMap<>(e.getValues()) : new HashMap<>())
|
||||
.imageValues(e.getImageValues() != null ? new HashMap<>(e.getImageValues()) : new HashMap<>())
|
||||
.keyValueValues(e.getKeyValueValues() != null ? new HashMap<>(e.getKeyValueValues()) : new HashMap<>())
|
||||
.campaignId(e.getCampaignId().toString())
|
||||
.order(e.getOrder())
|
||||
.createdAt(e.getCreatedAt())
|
||||
@@ -65,7 +70,11 @@ public class PostgresNpcRepository implements NpcRepository {
|
||||
return NpcJpaEntity.builder()
|
||||
.id(id)
|
||||
.name(n.getName())
|
||||
.markdownContent(n.getMarkdownContent())
|
||||
.portraitImageId(n.getPortraitImageId())
|
||||
.headerImageId(n.getHeaderImageId())
|
||||
.values(n.getValues() != null ? new HashMap<>(n.getValues()) : new HashMap<>())
|
||||
.imageValues(n.getImageValues() != null ? new HashMap<>(n.getImageValues()) : new HashMap<>())
|
||||
.keyValueValues(n.getKeyValueValues() != null ? new HashMap<>(n.getKeyValueValues()) : new HashMap<>())
|
||||
.campaignId(Long.parseLong(n.getCampaignId()))
|
||||
.order(n.getOrder())
|
||||
.createdAt(n.getCreatedAt())
|
||||
|
||||
@@ -24,9 +24,7 @@ public class CharacterController {
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<CharacterDTO> createCharacter(@RequestBody CharacterDTO dto) {
|
||||
Character created = characterService.createCharacter(
|
||||
new CharacterService.CharacterData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), null)
|
||||
);
|
||||
Character created = characterService.createCharacter(toData(dto, null));
|
||||
return ResponseEntity.ok(characterMapper.toDTO(created));
|
||||
}
|
||||
|
||||
@@ -47,10 +45,7 @@ public class CharacterController {
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<CharacterDTO> updateCharacter(@PathVariable String id, @RequestBody CharacterDTO dto) {
|
||||
Character updated = characterService.updateCharacter(
|
||||
id,
|
||||
new CharacterService.CharacterData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), dto.getOrder())
|
||||
);
|
||||
Character updated = characterService.updateCharacter(id, toData(dto, dto.getOrder()));
|
||||
return ResponseEntity.ok(characterMapper.toDTO(updated));
|
||||
}
|
||||
|
||||
@@ -59,4 +54,17 @@ public class CharacterController {
|
||||
characterService.deleteCharacter(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private CharacterService.CharacterData toData(CharacterDTO dto, Integer order) {
|
||||
return new CharacterService.CharacterData(
|
||||
dto.getName(),
|
||||
dto.getPortraitImageId(),
|
||||
dto.getHeaderImageId(),
|
||||
dto.getValues(),
|
||||
dto.getImageValues(),
|
||||
dto.getKeyValueValues(),
|
||||
dto.getCampaignId(),
|
||||
order
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,16 @@ package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.gamesystemcontext.GameSystemService;
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import com.loremind.infrastructure.web.mapper.GameSystemMapper;
|
||||
import com.loremind.infrastructure.web.mapper.TemplateFieldMapper;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -16,10 +21,14 @@ public class GameSystemController {
|
||||
|
||||
private final GameSystemService gameSystemService;
|
||||
private final GameSystemMapper gameSystemMapper;
|
||||
private final TemplateFieldMapper templateFieldMapper;
|
||||
|
||||
public GameSystemController(GameSystemService gameSystemService, GameSystemMapper gameSystemMapper) {
|
||||
public GameSystemController(GameSystemService gameSystemService,
|
||||
GameSystemMapper gameSystemMapper,
|
||||
TemplateFieldMapper templateFieldMapper) {
|
||||
this.gameSystemService = gameSystemService;
|
||||
this.gameSystemMapper = gameSystemMapper;
|
||||
this.templateFieldMapper = templateFieldMapper;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@@ -63,13 +72,28 @@ public class GameSystemController {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/** Mappe les violations d'invariants domaine (doublons de champs, etc.) en 400. */
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<String> onIllegalArgument(IllegalArgumentException ex) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
|
||||
}
|
||||
|
||||
private GameSystemService.GameSystemData toData(GameSystemDTO dto) {
|
||||
return new GameSystemService.GameSystemData(
|
||||
dto.getName(),
|
||||
dto.getDescription(),
|
||||
dto.getRulesMarkdown(),
|
||||
toDomainFields(dto.getCharacterTemplate()),
|
||||
toDomainFields(dto.getNpcTemplate()),
|
||||
dto.getAuthor(),
|
||||
dto.isPublic()
|
||||
);
|
||||
}
|
||||
|
||||
private List<TemplateField> toDomainFields(List<TemplateFieldDTO> dtos) {
|
||||
if (dtos == null) return new ArrayList<>();
|
||||
List<TemplateField> out = new ArrayList<>(dtos.size());
|
||||
for (TemplateFieldDTO d : dtos) out.add(templateFieldMapper.toDomain(d));
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,9 +24,7 @@ public class NpcController {
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<NpcDTO> createNpc(@RequestBody NpcDTO dto) {
|
||||
Npc created = npcService.createNpc(
|
||||
new NpcService.NpcData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), null)
|
||||
);
|
||||
Npc created = npcService.createNpc(toData(dto, null));
|
||||
return ResponseEntity.ok(npcMapper.toDTO(created));
|
||||
}
|
||||
|
||||
@@ -47,10 +45,7 @@ public class NpcController {
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<NpcDTO> updateNpc(@PathVariable String id, @RequestBody NpcDTO dto) {
|
||||
Npc updated = npcService.updateNpc(
|
||||
id,
|
||||
new NpcService.NpcData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), dto.getOrder())
|
||||
);
|
||||
Npc updated = npcService.updateNpc(id, toData(dto, dto.getOrder()));
|
||||
return ResponseEntity.ok(npcMapper.toDTO(updated));
|
||||
}
|
||||
|
||||
@@ -59,4 +54,17 @@ public class NpcController {
|
||||
npcService.deleteNpc(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private NpcService.NpcData toData(NpcDTO dto, Integer order) {
|
||||
return new NpcService.NpcData(
|
||||
dto.getName(),
|
||||
dto.getPortraitImageId(),
|
||||
dto.getHeaderImageId(),
|
||||
dto.getValues(),
|
||||
dto.getImageValues(),
|
||||
dto.getKeyValueValues(),
|
||||
dto.getCampaignId(),
|
||||
order
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.lorecontext.TemplateService;
|
||||
import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.web.dto.lorecontext.TemplateDTO;
|
||||
import com.loremind.infrastructure.web.mapper.TemplateFieldMapper;
|
||||
import com.loremind.infrastructure.web.mapper.TemplateMapper;
|
||||
|
||||
@@ -2,15 +2,26 @@ package com.loremind.infrastructure.web.dto.campaigncontext;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* DTO pour les fiches de personnages (PJ) d'une campagne.
|
||||
* Reflete la refonte template-based : champs universels hard-codes (name,
|
||||
* portrait, header) + maps {@code values}/{@code imageValues} pour les
|
||||
* champs templates pilotes par le GameSystem.
|
||||
*/
|
||||
@Data
|
||||
public class CharacterDTO {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String markdownContent;
|
||||
private String portraitImageId;
|
||||
private String headerImageId;
|
||||
private Map<String, String> values = new HashMap<>();
|
||||
private Map<String, List<String>> imageValues = new HashMap<>();
|
||||
private Map<String, Map<String, String>> keyValueValues = new HashMap<>();
|
||||
private String campaignId;
|
||||
private int order;
|
||||
}
|
||||
|
||||
@@ -2,15 +2,23 @@ package com.loremind.infrastructure.web.dto.campaigncontext;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* DTO pour les fiches de PNJ d'une campagne.
|
||||
* DTO pour les fiches de PNJ d'une campagne. Meme structure que CharacterDTO.
|
||||
*/
|
||||
@Data
|
||||
public class NpcDTO {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String markdownContent;
|
||||
private String portraitImageId;
|
||||
private String headerImageId;
|
||||
private Map<String, String> values = new HashMap<>();
|
||||
private Map<String, List<String>> imageValues = new HashMap<>();
|
||||
private Map<String, Map<String, String>> keyValueValues = new HashMap<>();
|
||||
private String campaignId;
|
||||
private int order;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
package com.loremind.infrastructure.web.dto.gamesystemcontext;
|
||||
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* DTO pour l'entité GameSystem (système de JDR).
|
||||
* Expose les templates PJ/PNJ comme listes de TemplateFieldDTO pour le wire.
|
||||
*/
|
||||
@Data
|
||||
public class GameSystemDTO {
|
||||
@@ -12,6 +17,8 @@ public class GameSystemDTO {
|
||||
private String name;
|
||||
private String description;
|
||||
private String rulesMarkdown;
|
||||
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
|
||||
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
|
||||
private String author;
|
||||
private boolean isPublic;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.loremind.infrastructure.web.dto.lorecontext;
|
||||
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.loremind.infrastructure.web.dto.lorecontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* DTO pour un champ de Template.
|
||||
* <p>
|
||||
* Miroir wire-friendly de {@link com.loremind.domain.lorecontext.TemplateField}.
|
||||
* Le type est serialise en string (TEXT/IMAGE) pour interop facile avec Angular.
|
||||
* Le layout (null pour TEXT, ou GALLERY/HERO/MASONRY/CAROUSEL pour IMAGE) pilote
|
||||
* le rendu visuel des champs image cote front.
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TemplateFieldDTO {
|
||||
private String name;
|
||||
/** "TEXT" ou "IMAGE" (string pour serialisation JSON transparente). */
|
||||
private String type;
|
||||
/** "GALLERY" | "HERO" | "MASONRY" | "CAROUSEL", null si type=TEXT. */
|
||||
private String layout;
|
||||
|
||||
/** Retrocompat : constructeur sans layout. */
|
||||
public TemplateFieldDTO(String name, String type) {
|
||||
this(name, type, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.loremind.infrastructure.web.dto.shared;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* DTO pour un champ de Template.
|
||||
* <p>
|
||||
* Miroir wire-friendly de {@link com.loremind.domain.shared.template.TemplateField}.
|
||||
* Le type est serialise en string (TEXT/IMAGE) pour interop facile avec Angular.
|
||||
* Le layout (null pour TEXT, ou GALLERY/HERO/MASONRY/CAROUSEL pour IMAGE) pilote
|
||||
* le rendu visuel des champs image cote front.
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TemplateFieldDTO {
|
||||
private String name;
|
||||
/** "TEXT" | "IMAGE" | "NUMBER" | "KEY_VALUE_LIST". */
|
||||
private String type;
|
||||
/** "GALLERY" | "HERO" | "MASONRY" | "CAROUSEL", uniquement pour IMAGE. */
|
||||
private String layout;
|
||||
/** Labels predefinis pour KEY_VALUE_LIST (ordre significatif). */
|
||||
private List<String> labels;
|
||||
|
||||
/** Retrocompat : constructeur sans labels. */
|
||||
public TemplateFieldDTO(String name, String type, String layout) {
|
||||
this(name, type, layout, null);
|
||||
}
|
||||
|
||||
/** Retrocompat : constructeur sans layout ni labels. */
|
||||
public TemplateFieldDTO(String name, String type) {
|
||||
this(name, type, null, null);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.CharacterDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
@Component
|
||||
public class CharacterMapper {
|
||||
|
||||
@@ -12,7 +14,11 @@ public class CharacterMapper {
|
||||
CharacterDTO dto = new CharacterDTO();
|
||||
dto.setId(c.getId());
|
||||
dto.setName(c.getName());
|
||||
dto.setMarkdownContent(c.getMarkdownContent());
|
||||
dto.setPortraitImageId(c.getPortraitImageId());
|
||||
dto.setHeaderImageId(c.getHeaderImageId());
|
||||
dto.setValues(c.getValues() != null ? new HashMap<>(c.getValues()) : new HashMap<>());
|
||||
dto.setImageValues(c.getImageValues() != null ? new HashMap<>(c.getImageValues()) : new HashMap<>());
|
||||
dto.setKeyValueValues(c.getKeyValueValues() != null ? new HashMap<>(c.getKeyValueValues()) : new HashMap<>());
|
||||
dto.setCampaignId(c.getCampaignId());
|
||||
dto.setOrder(c.getOrder());
|
||||
return dto;
|
||||
@@ -23,7 +29,11 @@ public class CharacterMapper {
|
||||
return Character.builder()
|
||||
.id(dto.getId())
|
||||
.name(dto.getName())
|
||||
.markdownContent(dto.getMarkdownContent())
|
||||
.portraitImageId(dto.getPortraitImageId())
|
||||
.headerImageId(dto.getHeaderImageId())
|
||||
.values(dto.getValues() != null ? new HashMap<>(dto.getValues()) : new HashMap<>())
|
||||
.imageValues(dto.getImageValues() != null ? new HashMap<>(dto.getImageValues()) : new HashMap<>())
|
||||
.keyValueValues(dto.getKeyValueValues() != null ? new HashMap<>(dto.getKeyValueValues()) : new HashMap<>())
|
||||
.campaignId(dto.getCampaignId())
|
||||
.order(dto.getOrder())
|
||||
.build();
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
package com.loremind.infrastructure.web.mapper;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class GameSystemMapper {
|
||||
|
||||
private final TemplateFieldMapper fieldMapper;
|
||||
|
||||
public GameSystemMapper(TemplateFieldMapper fieldMapper) {
|
||||
this.fieldMapper = fieldMapper;
|
||||
}
|
||||
|
||||
public GameSystemDTO toDTO(GameSystem g) {
|
||||
if (g == null) return null;
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
@@ -14,6 +25,8 @@ public class GameSystemMapper {
|
||||
dto.setName(g.getName());
|
||||
dto.setDescription(g.getDescription());
|
||||
dto.setRulesMarkdown(g.getRulesMarkdown());
|
||||
dto.setCharacterTemplate(toDTOList(g.getCharacterTemplate()));
|
||||
dto.setNpcTemplate(toDTOList(g.getNpcTemplate()));
|
||||
dto.setAuthor(g.getAuthor());
|
||||
dto.setPublic(g.isPublic());
|
||||
return dto;
|
||||
@@ -26,8 +39,24 @@ public class GameSystemMapper {
|
||||
.name(dto.getName())
|
||||
.description(dto.getDescription())
|
||||
.rulesMarkdown(dto.getRulesMarkdown())
|
||||
.characterTemplate(toDomainList(dto.getCharacterTemplate()))
|
||||
.npcTemplate(toDomainList(dto.getNpcTemplate()))
|
||||
.author(dto.getAuthor())
|
||||
.isPublic(dto.isPublic())
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<TemplateFieldDTO> toDTOList(List<TemplateField> fields) {
|
||||
if (fields == null) return new ArrayList<>();
|
||||
List<TemplateFieldDTO> out = new ArrayList<>(fields.size());
|
||||
for (TemplateField f : fields) out.add(fieldMapper.toDTO(f));
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<TemplateField> toDomainList(List<TemplateFieldDTO> dtos) {
|
||||
if (dtos == null) return new ArrayList<>();
|
||||
List<TemplateField> out = new ArrayList<>(dtos.size());
|
||||
for (TemplateFieldDTO d : dtos) out.add(fieldMapper.toDomain(d));
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import com.loremind.domain.campaigncontext.Npc;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
@Component
|
||||
public class NpcMapper {
|
||||
|
||||
@@ -12,7 +14,11 @@ public class NpcMapper {
|
||||
NpcDTO dto = new NpcDTO();
|
||||
dto.setId(n.getId());
|
||||
dto.setName(n.getName());
|
||||
dto.setMarkdownContent(n.getMarkdownContent());
|
||||
dto.setPortraitImageId(n.getPortraitImageId());
|
||||
dto.setHeaderImageId(n.getHeaderImageId());
|
||||
dto.setValues(n.getValues() != null ? new HashMap<>(n.getValues()) : new HashMap<>());
|
||||
dto.setImageValues(n.getImageValues() != null ? new HashMap<>(n.getImageValues()) : new HashMap<>());
|
||||
dto.setKeyValueValues(n.getKeyValueValues() != null ? new HashMap<>(n.getKeyValueValues()) : new HashMap<>());
|
||||
dto.setCampaignId(n.getCampaignId());
|
||||
dto.setOrder(n.getOrder());
|
||||
return dto;
|
||||
@@ -23,7 +29,11 @@ public class NpcMapper {
|
||||
return Npc.builder()
|
||||
.id(dto.getId())
|
||||
.name(dto.getName())
|
||||
.markdownContent(dto.getMarkdownContent())
|
||||
.portraitImageId(dto.getPortraitImageId())
|
||||
.headerImageId(dto.getHeaderImageId())
|
||||
.values(dto.getValues() != null ? new HashMap<>(dto.getValues()) : new HashMap<>())
|
||||
.imageValues(dto.getImageValues() != null ? new HashMap<>(dto.getImageValues()) : new HashMap<>())
|
||||
.keyValueValues(dto.getKeyValueValues() != null ? new HashMap<>(dto.getKeyValueValues()) : new HashMap<>())
|
||||
.campaignId(dto.getCampaignId())
|
||||
.order(dto.getOrder())
|
||||
.build();
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
package com.loremind.infrastructure.web.mapper;
|
||||
|
||||
import com.loremind.domain.lorecontext.FieldType;
|
||||
import com.loremind.domain.lorecontext.ImageLayout;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.infrastructure.web.dto.lorecontext.TemplateFieldDTO;
|
||||
import com.loremind.domain.shared.template.FieldType;
|
||||
import com.loremind.domain.shared.template.ImageLayout;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Mapper pour convertir entre {@link TemplateField} (domaine) et
|
||||
* {@link TemplateFieldDTO} (wire).
|
||||
* <p>
|
||||
* Tolerance : un type inconnu recu du client est interprete comme TEXT
|
||||
* (plus safe que de rejeter la requete et d'interrompre la sauvegarde).
|
||||
* Tolerance : un type inconnu recu du client est interprete comme TEXT.
|
||||
* Un layout inconnu ou absent sur un champ IMAGE est interprete comme GALLERY.
|
||||
* Le layout est force a null pour les champs TEXT.
|
||||
* Layout/labels forces a null pour les types qui ne les utilisent pas.
|
||||
*/
|
||||
@Component
|
||||
public class TemplateFieldMapper {
|
||||
@@ -26,7 +28,11 @@ public class TemplateFieldMapper {
|
||||
ImageLayout layout = field.getLayout() != null ? field.getLayout() : ImageLayout.GALLERY;
|
||||
layoutStr = layout.name();
|
||||
}
|
||||
return new TemplateFieldDTO(field.getName(), typeStr, layoutStr);
|
||||
List<String> labels = null;
|
||||
if (field.getType() == FieldType.KEY_VALUE_LIST && field.getLabels() != null) {
|
||||
labels = new ArrayList<>(field.getLabels());
|
||||
}
|
||||
return new TemplateFieldDTO(field.getName(), typeStr, layoutStr, labels);
|
||||
}
|
||||
|
||||
public TemplateField toDomain(TemplateFieldDTO dto) {
|
||||
@@ -47,6 +53,10 @@ public class TemplateFieldMapper {
|
||||
layout = ImageLayout.GALLERY;
|
||||
}
|
||||
}
|
||||
return new TemplateField(dto.getName(), type, layout);
|
||||
List<String> labels = null;
|
||||
if (type == FieldType.KEY_VALUE_LIST && dto.getLabels() != null) {
|
||||
labels = new ArrayList<>(dto.getLabels());
|
||||
}
|
||||
return new TemplateField(dto.getName(), type, layout, labels);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package com.loremind.infrastructure.web.mapper;
|
||||
|
||||
import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.web.dto.lorecontext.TemplateDTO;
|
||||
import com.loremind.infrastructure.web.dto.lorecontext.TemplateFieldDTO;
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -38,7 +39,7 @@ public class NpcServiceTest {
|
||||
testNpc = Npc.builder()
|
||||
.id("npc-1")
|
||||
.name("Borin le forgeron")
|
||||
.markdownContent("# Borin\nForgeron nain")
|
||||
.values(new java.util.HashMap<>(Map.of("Notes", "Forgeron nain")))
|
||||
.campaignId("camp-1")
|
||||
.order(1)
|
||||
.build();
|
||||
@@ -49,7 +50,8 @@ public class NpcServiceTest {
|
||||
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
||||
|
||||
Npc result = npcService.createNpc(
|
||||
new NpcService.NpcData("Borin le forgeron", "# Borin", "camp-1", 5));
|
||||
new NpcService.NpcData("Borin le forgeron", null, null,
|
||||
Map.of("Notes", "Borin"), null, null, "camp-1", 5));
|
||||
|
||||
assertNotNull(result);
|
||||
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||
@@ -65,7 +67,7 @@ public class NpcServiceTest {
|
||||
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of(a, b));
|
||||
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
||||
|
||||
npcService.createNpc(new NpcService.NpcData("Nouveau", null, "camp-1", null));
|
||||
npcService.createNpc(new NpcService.NpcData("Nouveau", null, null, null, null, null, "camp-1", null));
|
||||
|
||||
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||
verify(npcRepository).save(captor.capture());
|
||||
@@ -77,7 +79,7 @@ public class NpcServiceTest {
|
||||
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of());
|
||||
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
||||
|
||||
npcService.createNpc(new NpcService.NpcData("Premier", null, "camp-1", null));
|
||||
npcService.createNpc(new NpcService.NpcData("Premier", null, null, null, null, null, "camp-1", null));
|
||||
|
||||
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||
verify(npcRepository).save(captor.capture());
|
||||
@@ -121,10 +123,11 @@ public class NpcServiceTest {
|
||||
when(npcRepository.save(any(Npc.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
Npc result = npcService.updateNpc("npc-1",
|
||||
new NpcService.NpcData("Borin renommé", "# v2", "camp-1", 7));
|
||||
new NpcService.NpcData("Borin renommé", null, null,
|
||||
Map.of("Notes", "v2"), null, null, "camp-1", 7));
|
||||
|
||||
assertEquals("Borin renommé", result.getName());
|
||||
assertEquals("# v2", result.getMarkdownContent());
|
||||
assertEquals("v2", result.getValues().get("Notes"));
|
||||
assertEquals(7, result.getOrder());
|
||||
}
|
||||
|
||||
@@ -134,7 +137,8 @@ public class NpcServiceTest {
|
||||
when(npcRepository.save(any(Npc.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
Npc result = npcService.updateNpc("npc-1",
|
||||
new NpcService.NpcData("Borin", "# txt", "camp-1", null));
|
||||
new NpcService.NpcData("Borin", null, null,
|
||||
Map.of("Notes", "txt"), null, null, "camp-1", null));
|
||||
|
||||
// testNpc avait order=1 → préservé
|
||||
assertEquals(1, result.getOrder());
|
||||
@@ -146,7 +150,7 @@ public class NpcServiceTest {
|
||||
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||
() -> npcService.updateNpc("missing",
|
||||
new NpcService.NpcData("x", null, "camp-1", null)));
|
||||
new NpcService.NpcData("x", null, null, null, null, null, "camp-1", null)));
|
||||
assertTrue(ex.getMessage().contains("missing"));
|
||||
verify(npcRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@@ -153,19 +153,19 @@ public class CampaignStructuralContextBuilderTest {
|
||||
void testBuild_ProjectsCharactersAndNpcsWithSnippets() {
|
||||
Character pj1 = Character.builder().id("c-1").campaignId("camp-1").order(1)
|
||||
.name("Aragorn")
|
||||
.markdownContent("# Aragorn\n\nRôdeur du Nord, héritier d'Isildur.")
|
||||
.values(new java.util.HashMap<>(java.util.Map.of("Histoire", "# Aragorn\n\nRôdeur du Nord, héritier d'Isildur.")))
|
||||
.build();
|
||||
Character pj2 = Character.builder().id("c-2").campaignId("camp-1").order(2)
|
||||
.name("Legolas")
|
||||
.markdownContent(null) // pas de snippet → string vide
|
||||
.values(null) // pas de snippet → string vide
|
||||
.build();
|
||||
Npc npc1 = Npc.builder().id("n-1").campaignId("camp-1").order(2)
|
||||
.name("Borin le forgeron")
|
||||
.markdownContent("# Borin\n\nNain barbu au regard perçant, ancien clan Feuillefer.")
|
||||
.values(new java.util.HashMap<>(java.util.Map.of("Histoire", "# Borin\n\nNain barbu au regard perçant, ancien clan Feuillefer.")))
|
||||
.build();
|
||||
Npc npc2 = Npc.builder().id("n-2").campaignId("camp-1").order(1)
|
||||
.name("Dame Elara")
|
||||
.markdownContent("")
|
||||
.values(new java.util.HashMap<>(java.util.Map.of("Histoire", "")))
|
||||
.build();
|
||||
|
||||
when(campaignRepository.findById("camp-1")).thenReturn(Optional.of(campaign));
|
||||
@@ -196,7 +196,7 @@ public class CampaignStructuralContextBuilderTest {
|
||||
// Snippet > 160 chars : doit être tronqué à 159 + "…"
|
||||
String longLine = "x".repeat(200);
|
||||
Npc longNpc = Npc.builder().id("n-1").campaignId("camp-1").order(1)
|
||||
.name("Verbeux").markdownContent(longLine).build();
|
||||
.name("Verbeux").values(new java.util.HashMap<>(java.util.Map.of("Histoire", longLine))).build();
|
||||
|
||||
when(campaignRepository.findById("camp-1")).thenReturn(Optional.of(campaign));
|
||||
when(arcRepository.findByCampaignId("camp-1")).thenReturn(List.of());
|
||||
|
||||
@@ -3,12 +3,12 @@ package com.loremind.application.generationcontext;
|
||||
import com.loremind.domain.generationcontext.GenerationContext;
|
||||
import com.loremind.domain.generationcontext.GenerationResult;
|
||||
import com.loremind.domain.generationcontext.ports.AiProvider;
|
||||
import com.loremind.domain.lorecontext.FieldType;
|
||||
import com.loremind.domain.shared.template.FieldType;
|
||||
import com.loremind.domain.lorecontext.Lore;
|
||||
import com.loremind.domain.lorecontext.LoreNode;
|
||||
import com.loremind.domain.lorecontext.Page;
|
||||
import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
||||
import com.loremind.domain.lorecontext.ports.LoreRepository;
|
||||
import com.loremind.domain.lorecontext.ports.PageRepository;
|
||||
|
||||
@@ -115,8 +115,13 @@ public class NarrativeEntityContextBuilderTest {
|
||||
|
||||
@Test
|
||||
void testBuild_Character_MarkdownProjected() {
|
||||
// Refonte 2026-04-30 : les valeurs templates sont projetees individuellement
|
||||
// dans la map fields (cle = nom du champ template).
|
||||
Character c = Character.builder()
|
||||
.id("c-1").name("Aragorn").markdownContent("# Aragorn\nRôdeur")
|
||||
.id("c-1").name("Aragorn")
|
||||
.values(new java.util.HashMap<>(java.util.Map.of(
|
||||
"Histoire", "# Aragorn\nRôdeur",
|
||||
"Race", "Humain")))
|
||||
.build();
|
||||
when(characterRepository.findById("c-1")).thenReturn(Optional.of(c));
|
||||
|
||||
@@ -124,14 +129,17 @@ public class NarrativeEntityContextBuilderTest {
|
||||
|
||||
assertEquals("character", ctx.entityType());
|
||||
assertEquals("Aragorn", ctx.title());
|
||||
assertEquals("# Aragorn\nRôdeur", ctx.fields().get("fiche complète (markdown)"));
|
||||
assertEquals("# Aragorn\nRôdeur", ctx.fields().get("Histoire"));
|
||||
assertEquals("Humain", ctx.fields().get("Race"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuild_Npc_MarkdownProjected() {
|
||||
Npc n = Npc.builder()
|
||||
.id("n-1").name("Borin le forgeron")
|
||||
.markdownContent("# Borin\n**Faction :** Clan Feuillefer")
|
||||
.values(new java.util.HashMap<>(java.util.Map.of(
|
||||
"Faction", "Clan Feuillefer",
|
||||
"Histoire", "# Borin")))
|
||||
.build();
|
||||
when(npcRepository.findById("n-1")).thenReturn(Optional.of(n));
|
||||
|
||||
@@ -139,13 +147,14 @@ public class NarrativeEntityContextBuilderTest {
|
||||
|
||||
assertEquals("npc", ctx.entityType());
|
||||
assertEquals("Borin le forgeron", ctx.title());
|
||||
assertEquals("# Borin\n**Faction :** Clan Feuillefer",
|
||||
ctx.fields().get("fiche complète (markdown)"));
|
||||
assertEquals("Clan Feuillefer", ctx.fields().get("Faction"));
|
||||
assertEquals("# Borin", ctx.fields().get("Histoire"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuild_Npc_NormalizesCase() {
|
||||
Npc n = Npc.builder().id("n-1").name("Elara").markdownContent("desc").build();
|
||||
Npc n = Npc.builder().id("n-1").name("Elara")
|
||||
.values(new java.util.HashMap<>(java.util.Map.of("Notes", "desc"))).build();
|
||||
when(npcRepository.findById("n-1")).thenReturn(Optional.of(n));
|
||||
|
||||
NarrativeEntityContext ctx = builder.build(" NPC ", "n-1");
|
||||
|
||||
@@ -5,10 +5,10 @@ import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||
import com.loremind.domain.lorecontext.FieldType;
|
||||
import com.loremind.domain.shared.template.FieldType;
|
||||
import com.loremind.domain.lorecontext.Page;
|
||||
import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.domain.lorecontext.ports.PageRepository;
|
||||
import com.loremind.domain.lorecontext.ports.TemplateRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.loremind.application.lorecontext;
|
||||
|
||||
import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.domain.lorecontext.ports.TemplateRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.loremind.domain.gamesystemcontext;
|
||||
|
||||
import com.loremind.domain.shared.template.FieldType;
|
||||
import com.loremind.domain.shared.template.ImageLayout;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Tests unitaires du domaine GameSystem ciblant la gestion des templates PJ/PNJ.
|
||||
* Le ruleset markdown est testé ailleurs via GameSystemContextSelector.
|
||||
*/
|
||||
class GameSystemTest {
|
||||
|
||||
// --- addCharacterField --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void addCharacterField_appendsField() {
|
||||
GameSystem gs = GameSystem.builder().build();
|
||||
|
||||
gs.addCharacterField(TemplateField.text("Histoire"));
|
||||
gs.addCharacterField(TemplateField.image("Portrait", ImageLayout.HERO));
|
||||
|
||||
assertEquals(2, gs.getCharacterTemplate().size());
|
||||
assertEquals("Histoire", gs.getCharacterTemplate().get(0).getName());
|
||||
assertEquals(FieldType.IMAGE, gs.getCharacterTemplate().get(1).getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addCharacterField_rejectsDuplicateNameCaseInsensitive() {
|
||||
GameSystem gs = GameSystem.builder().build();
|
||||
gs.addCharacterField(TemplateField.text("Histoire"));
|
||||
|
||||
// Doublon de cle dans Character.values garanti casse-insensible :
|
||||
// "Histoire" et "histoire" produiraient la meme cle JSON.
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> gs.addCharacterField(TemplateField.number("HISTOIRE")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addCharacterField_rejectsBlankName() {
|
||||
GameSystem gs = GameSystem.builder().build();
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> gs.addCharacterField(new TemplateField(" ", FieldType.TEXT)));
|
||||
}
|
||||
|
||||
// --- removeCharacterField ----------------------------------------------
|
||||
|
||||
@Test
|
||||
void removeCharacterField_removesByNameCaseInsensitive() {
|
||||
GameSystem gs = GameSystem.builder()
|
||||
.characterTemplate(new ArrayList<>(List.of(
|
||||
TemplateField.text("Histoire"),
|
||||
TemplateField.text("Notes")
|
||||
)))
|
||||
.build();
|
||||
|
||||
gs.removeCharacterField("HISTOIRE");
|
||||
|
||||
assertEquals(1, gs.getCharacterTemplate().size());
|
||||
assertEquals("Notes", gs.getCharacterTemplate().get(0).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeCharacterField_silentNoOpWhenMissing() {
|
||||
GameSystem gs = GameSystem.builder()
|
||||
.characterTemplate(new ArrayList<>(List.of(TemplateField.text("Histoire"))))
|
||||
.build();
|
||||
|
||||
gs.removeCharacterField("absent");
|
||||
|
||||
assertEquals(1, gs.getCharacterTemplate().size());
|
||||
}
|
||||
|
||||
// --- replaceCharacterTemplate ------------------------------------------
|
||||
|
||||
@Test
|
||||
void replaceCharacterTemplate_overwritesEntireList() {
|
||||
GameSystem gs = GameSystem.builder()
|
||||
.characterTemplate(new ArrayList<>(List.of(TemplateField.text("Old"))))
|
||||
.build();
|
||||
|
||||
gs.replaceCharacterTemplate(List.of(
|
||||
TemplateField.text("A"),
|
||||
TemplateField.number("B")));
|
||||
|
||||
assertEquals(2, gs.getCharacterTemplate().size());
|
||||
assertEquals("A", gs.getCharacterTemplate().get(0).getName());
|
||||
assertEquals("B", gs.getCharacterTemplate().get(1).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceCharacterTemplate_rejectsDuplicates() {
|
||||
GameSystem gs = GameSystem.builder().build();
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> gs.replaceCharacterTemplate(List.of(
|
||||
TemplateField.text("a"),
|
||||
TemplateField.text("A"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceCharacterTemplate_nullBecomesEmptyList() {
|
||||
GameSystem gs = GameSystem.builder().build();
|
||||
gs.replaceCharacterTemplate(null);
|
||||
assertTrue(gs.getCharacterTemplate().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceCharacterTemplate_isolatesInternalListFromCallerMutations() {
|
||||
// Garantie d'encapsulation : muter la liste passee ne doit pas affecter le GameSystem.
|
||||
List<TemplateField> external = new ArrayList<>(List.of(TemplateField.text("A")));
|
||||
GameSystem gs = GameSystem.builder().build();
|
||||
|
||||
gs.replaceCharacterTemplate(external);
|
||||
external.add(TemplateField.text("B"));
|
||||
|
||||
assertEquals(1, gs.getCharacterTemplate().size());
|
||||
}
|
||||
|
||||
// --- Templates NPC : meme logique, sanity check minimal ----------------
|
||||
|
||||
@Test
|
||||
void npcTemplate_followsSameRulesAsCharacterTemplate() {
|
||||
GameSystem gs = GameSystem.builder().build();
|
||||
|
||||
gs.addNpcField(TemplateField.text("Motivation"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> gs.addNpcField(TemplateField.text("motivation")));
|
||||
|
||||
gs.removeNpcField("Motivation");
|
||||
assertTrue(gs.getNpcTemplate().isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.loremind.domain.lorecontext;
|
||||
|
||||
import com.loremind.domain.shared.template.ImageLayout;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.loremind.domain.lorecontext;
|
||||
package com.loremind.domain.shared.template;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.loremind.infrastructure.persistence.converter;
|
||||
|
||||
import com.loremind.domain.lorecontext.FieldType;
|
||||
import com.loremind.domain.lorecontext.ImageLayout;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.FieldType;
|
||||
import com.loremind.domain.shared.template.ImageLayout;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.lorecontext.FieldType;
|
||||
import com.loremind.domain.lorecontext.ImageLayout;
|
||||
import com.loremind.domain.shared.template.FieldType;
|
||||
import com.loremind.domain.shared.template.ImageLayout;
|
||||
import com.loremind.domain.lorecontext.Lore;
|
||||
import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.domain.lorecontext.ports.LoreRepository;
|
||||
import com.loremind.domain.lorecontext.ports.TemplateRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration du GameSystemController centres sur la persistance
|
||||
* des templates PJ/PNJ via l'API REST. Le CRUD de base est suppose stable.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class GameSystemControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
|
||||
@Test
|
||||
void create_persistsCharacterAndNpcTemplates() throws Exception {
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
dto.setName("Nimble Test");
|
||||
dto.setRulesMarkdown("## Combat\n- d20");
|
||||
dto.setCharacterTemplate(List.of(
|
||||
new TemplateFieldDTO("Histoire", "TEXT", null),
|
||||
new TemplateFieldDTO("PV", "NUMBER", null),
|
||||
new TemplateFieldDTO("Portrait", "IMAGE", "HERO")));
|
||||
dto.setNpcTemplate(List.of(
|
||||
new TemplateFieldDTO("Motivation", "TEXT", null)));
|
||||
|
||||
mockMvc.perform(post("/api/game-systems")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").exists())
|
||||
.andExpect(jsonPath("$.characterTemplate.length()").value(3))
|
||||
.andExpect(jsonPath("$.characterTemplate[1].type").value("NUMBER"))
|
||||
.andExpect(jsonPath("$.characterTemplate[2].layout").value("HERO"))
|
||||
.andExpect(jsonPath("$.npcTemplate.length()").value(1))
|
||||
.andExpect(jsonPath("$.npcTemplate[0].name").value("Motivation"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_replacesTemplates() throws Exception {
|
||||
// Creation initiale avec un seul champ.
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
dto.setName("RuleSet");
|
||||
dto.setCharacterTemplate(List.of(new TemplateFieldDTO("Old", "TEXT", null)));
|
||||
|
||||
MvcResult posted = mockMvc.perform(post("/api/game-systems")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
|
||||
GameSystemDTO created = objectMapper.readValue(
|
||||
posted.getResponse().getContentAsString(), GameSystemDTO.class);
|
||||
|
||||
// Replace template integralement.
|
||||
created.setCharacterTemplate(List.of(
|
||||
new TemplateFieldDTO("Histoire", "TEXT", null),
|
||||
new TemplateFieldDTO("Niveau", "NUMBER", null)));
|
||||
|
||||
mockMvc.perform(put("/api/game-systems/{id}", created.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(created)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.characterTemplate.length()").value(2))
|
||||
.andExpect(jsonPath("$.characterTemplate[0].name").value("Histoire"))
|
||||
.andExpect(jsonPath("$.characterTemplate[1].type").value("NUMBER"));
|
||||
|
||||
// Verification que le GET independant retourne bien les nouveaux champs (pas de cache stale).
|
||||
mockMvc.perform(get("/api/game-systems/{id}", created.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.characterTemplate[?(@.name == 'Old')]").doesNotExist())
|
||||
.andExpect(jsonPath("$.characterTemplate[?(@.name == 'Histoire')]").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_rejectsDuplicateFieldNames() throws Exception {
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
dto.setName("BadRules");
|
||||
dto.setCharacterTemplate(List.of(
|
||||
new TemplateFieldDTO("Nom", "TEXT", null),
|
||||
new TemplateFieldDTO("nom", "NUMBER", null)));
|
||||
|
||||
mockMvc.perform(post("/api/game-systems")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().is4xxClientError());
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.ports.LoreRepository;
|
||||
import com.loremind.domain.lorecontext.ports.TemplateRepository;
|
||||
import com.loremind.infrastructure.web.dto.lorecontext.TemplateDTO;
|
||||
import com.loremind.infrastructure.web.dto.lorecontext.TemplateFieldDTO;
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
Auteur : ietm64
|
||||
Licence : AGPL-3.0
|
||||
Projet : LoreMindMJ - assistant pour Maitres de Jeu de JDR
|
||||
Version : 0.8.1
|
||||
Version : 0.8.3
|
||||
|
||||
.LINK
|
||||
https://github.com/IGMLcreation/LoreMind
|
||||
|
||||
@@ -355,3 +355,55 @@ export async function getTemplateById(
|
||||
expect(res.ok(), `GET /api/templates/${templateId} -> ${res.status()}`).toBeTruthy();
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// ─────────────── GameSystem ───────────────
|
||||
|
||||
export interface SeededGameSystem {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export async function seedGameSystem(
|
||||
request: APIRequestContext,
|
||||
opts: { name?: string; description?: string; author?: string; rulesMarkdown?: string } = {},
|
||||
): Promise<SeededGameSystem> {
|
||||
const name = opts.name ?? `E2E GameSystem ${Date.now()}-${Math.floor(Math.random() * 10000)}`;
|
||||
const res = await request.post('/api/game-systems', {
|
||||
data: {
|
||||
name,
|
||||
description: opts.description ?? null,
|
||||
author: opts.author ?? null,
|
||||
rulesMarkdown: opts.rulesMarkdown ?? null,
|
||||
characterTemplate: [],
|
||||
npcTemplate: [],
|
||||
isPublic: false,
|
||||
},
|
||||
});
|
||||
expect(res.ok(), `POST /api/game-systems -> ${res.status()}`).toBeTruthy();
|
||||
const gs = await res.json();
|
||||
return { id: gs.id, name };
|
||||
}
|
||||
|
||||
export async function deleteGameSystem(
|
||||
request: APIRequestContext,
|
||||
id: string,
|
||||
): Promise<void> {
|
||||
// Best-effort : ignore 404 si déjà supprimé par le test (ex: delete spec).
|
||||
await request.delete(`/api/game-systems/${id}`);
|
||||
}
|
||||
|
||||
export async function getGameSystemById(
|
||||
request: APIRequestContext,
|
||||
id: string,
|
||||
): Promise<{
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
author: string | null;
|
||||
rulesMarkdown: string | null;
|
||||
isPublic: boolean;
|
||||
}> {
|
||||
const res = await request.get(`/api/game-systems/${id}`);
|
||||
expect(res.ok(), `GET /api/game-systems/${id} -> ${res.status()}`).toBeTruthy();
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -24,10 +24,12 @@ test.describe('Arc delete', () => {
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
|
||||
await page.goto(`/campaigns/${campaign.id}/arcs/${arc.id}/edit`);
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).first().click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}$`));
|
||||
|
||||
@@ -36,10 +38,12 @@ test.describe('Arc delete', () => {
|
||||
});
|
||||
|
||||
test('keeps the arc when confirm is dismissed', async ({ page, request }) => {
|
||||
page.on('dialog', (dialog) => dialog.dismiss());
|
||||
|
||||
await page.goto(`/campaigns/${campaign.id}/arcs/${arc.id}/edit`);
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).first().click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Annuler$/i }).click();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}/arcs/${arc.id}/edit$`));
|
||||
|
||||
|
||||
@@ -38,6 +38,10 @@ test.describe('Arc edit', () => {
|
||||
};
|
||||
|
||||
await page.goto(`/campaigns/${campaign.id}/arcs/${arc.id}/edit`);
|
||||
// Attend que le formulaire soit prerempli par le ngOnInit (HTTP async) avant
|
||||
// de fill — sinon le patchValue du load arrive APRES nos fills et ecrase
|
||||
// les valeurs, le test echoue alors a la verif persisted.name.
|
||||
await expect(page.getByLabel(/Titre de l'arc/i)).toHaveValue(arc.name);
|
||||
|
||||
await page.getByLabel(/Titre de l'arc/i).fill(newName);
|
||||
await page.getByLabel(/Synopsis de l'arc/i).fill(values.description);
|
||||
|
||||
@@ -16,10 +16,12 @@ test.describe('Campaign delete', () => {
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
|
||||
await page.goto(`/campaigns/${campaign.id}`);
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).first().click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/campaigns$/);
|
||||
|
||||
@@ -28,10 +30,12 @@ test.describe('Campaign delete', () => {
|
||||
});
|
||||
|
||||
test('keeps the campaign when confirm is dismissed', async ({ page, request }) => {
|
||||
page.on('dialog', (dialog) => dialog.dismiss());
|
||||
|
||||
await page.goto(`/campaigns/${campaign.id}`);
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).first().click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Annuler$/i }).click();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}$`));
|
||||
|
||||
|
||||
@@ -17,20 +17,22 @@ test.describe('NPC creation', () => {
|
||||
if (campaign?.id) await deleteCampaign(request, campaign.id);
|
||||
});
|
||||
|
||||
test('creates an NPC and redirects back to the campaign', async ({ page, request }) => {
|
||||
test('creates an NPC and redirects to the NPC detail page', async ({ page, request }) => {
|
||||
// Note : depuis la refonte 2026-04-30 les fiches PNJ utilisent des champs
|
||||
// templates dynamiques pilotes par le GameSystem (plus de markdownContent
|
||||
// libre). La campagne seedee n'a pas de GameSystem donc on ne fill que le
|
||||
// nom — c'est suffisant pour valider la creation + la redirection.
|
||||
const npcName = `Borin le forgeron ${Date.now()}`;
|
||||
const markdown = '# Borin\n\n**Faction :** Clan Feuillefer\n\nNain barbu au regard perçant.';
|
||||
|
||||
await page.goto(`/campaigns/${campaign.id}/npcs/create`);
|
||||
await expect(page.getByRole('heading', { name: /Nouveau PNJ/i })).toBeVisible();
|
||||
|
||||
await page.getByLabel(/Nom du PNJ/i).fill(npcName);
|
||||
await page.getByLabel(/Fiche \(markdown\)/i).fill(markdown);
|
||||
|
||||
await page.getByRole('button', { name: /^Créer$/i }).click();
|
||||
|
||||
// Retour à la page campagne après création
|
||||
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}$`));
|
||||
// Redirection vers la fiche du PNJ après création
|
||||
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}/npcs/\\d+$`));
|
||||
|
||||
// Persistance vérifiée via API
|
||||
const npcs = await getNpcsByCampaign(request, campaign.id);
|
||||
@@ -58,7 +60,7 @@ test.describe('NPC creation', () => {
|
||||
await page.getByLabel(/Nom du PNJ/i).fill(npcName);
|
||||
await page.getByRole('button', { name: /^Créer$/i }).click();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}$`));
|
||||
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}/npcs/\\d+$`));
|
||||
|
||||
// Le nœud "PNJ" doit apparaître dans la sidebar avec le nouveau PNJ.
|
||||
// On clique sur le nœud PNJ pour le déplier au cas où il serait fermé,
|
||||
|
||||
@@ -14,19 +14,19 @@ test.describe('NPC edit', () => {
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
campaign = await seedCampaign(request);
|
||||
npc = await seedNpc(request, {
|
||||
campaignId: campaign.id,
|
||||
markdownContent: '# Initial\n\nFiche de départ.',
|
||||
});
|
||||
npc = await seedNpc(request, { campaignId: campaign.id });
|
||||
});
|
||||
|
||||
test.afterEach(async ({ request }) => {
|
||||
if (campaign?.id) await deleteCampaign(request, campaign.id);
|
||||
});
|
||||
|
||||
test('edits name + markdown content and persists via API', async ({ page, request }) => {
|
||||
test('edits name and persists via API', async ({ page, request }) => {
|
||||
// Note : depuis la refonte 2026-04-30 les fiches PNJ utilisent des champs
|
||||
// templates dynamiques pilotes par le GameSystem, plus le markdownContent
|
||||
// libre. La campagne seedee n'a pas de GameSystem donc pas de champs
|
||||
// dynamiques a tester ici — on se contente du nom (champ universel).
|
||||
const newName = `${npc.name} (renommé)`;
|
||||
const newMarkdown = '# Borin réécrit\n\n**Statut :** Disparu\n\nDes traces dans la neige...';
|
||||
|
||||
await page.goto(`/campaigns/${campaign.id}/npcs/${npc.id}/edit`);
|
||||
|
||||
@@ -34,7 +34,6 @@ test.describe('NPC edit', () => {
|
||||
await expect(page.getByLabel(/Nom du PNJ/i)).toHaveValue(npc.name);
|
||||
|
||||
await page.getByLabel(/Nom du PNJ/i).fill(newName);
|
||||
await page.getByLabel(/Fiche \(markdown\)/i).fill(newMarkdown);
|
||||
|
||||
await page.getByRole('button', { name: /^Enregistrer$/i }).click();
|
||||
|
||||
@@ -43,7 +42,6 @@ test.describe('NPC edit', () => {
|
||||
|
||||
const persisted = await getNpcById(request, npc.id);
|
||||
expect(persisted.name).toBe(newName);
|
||||
expect(persisted.markdownContent).toBe(newMarkdown);
|
||||
});
|
||||
|
||||
test('save button is disabled when name is cleared', async ({ page }) => {
|
||||
|
||||
74
web/e2e/tests/game-system/game-system-create.spec.ts
Normal file
74
web/e2e/tests/game-system/game-system-create.spec.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { deleteGameSystem } from '../../fixtures/api';
|
||||
|
||||
test.describe('GameSystem creation', () => {
|
||||
// Les game systems crees par les tests sont nettoyes via cet array — chaque
|
||||
// test pousse les IDs qu'il a crees pour qu'on les supprime en afterEach.
|
||||
const createdIds: string[] = [];
|
||||
|
||||
test.afterEach(async ({ request }) => {
|
||||
while (createdIds.length) {
|
||||
const id = createdIds.pop()!;
|
||||
await deleteGameSystem(request, id);
|
||||
}
|
||||
});
|
||||
|
||||
test('creates a game system and redirects to the list', async ({ page, request }) => {
|
||||
const gsName = `Système E2E ${Date.now()}`;
|
||||
const description = 'Système créé par les tests automatisés.';
|
||||
const author = 'Playwright';
|
||||
|
||||
await page.goto('/game-systems');
|
||||
await expect(page.getByRole('heading', { name: /Systèmes de JDR/i })).toBeVisible();
|
||||
|
||||
// Carte "Nouveau système" → ouvre l'editeur en mode creation.
|
||||
await page.locator('.gs-card.card-new').click();
|
||||
await expect(page).toHaveURL(/\/game-systems\/create$/);
|
||||
await expect(page.getByRole('heading', { name: /Nouveau système de JDR/i })).toBeVisible();
|
||||
|
||||
await page.getByLabel(/^Nom/i).fill(gsName);
|
||||
await page.getByLabel(/Description courte/i).fill(description);
|
||||
await page.getByLabel(/Auteur/i).fill(author);
|
||||
|
||||
await page.getByRole('button', { name: /^Créer$/i }).click();
|
||||
|
||||
// Redirection vers la liste apres creation.
|
||||
await expect(page).toHaveURL(/\/game-systems$/);
|
||||
// Et la carte du nouveau systeme est visible dans la grille.
|
||||
await expect(page.locator('.gs-card', { hasText: gsName })).toBeVisible();
|
||||
|
||||
// Verification API : le systeme est bien persistant.
|
||||
const all = await request.get('/api/game-systems').then((r) => r.json());
|
||||
const created = all.find((gs: { id: string; name: string }) => gs.name === gsName);
|
||||
expect(created).toBeDefined();
|
||||
expect(created.author).toBe(author);
|
||||
createdIds.push(created.id);
|
||||
});
|
||||
|
||||
test('submit button is disabled when name is empty', async ({ page }) => {
|
||||
await page.goto('/game-systems/create');
|
||||
|
||||
const submit = page.getByRole('button', { name: /^Créer$/i });
|
||||
await expect(submit).toBeDisabled();
|
||||
|
||||
await page.getByLabel(/^Nom/i).fill('Quelque chose');
|
||||
await expect(submit).toBeEnabled();
|
||||
|
||||
await page.getByLabel(/^Nom/i).fill(' ');
|
||||
await expect(submit).toBeDisabled();
|
||||
});
|
||||
|
||||
test('cancel returns to the list without creating', async ({ page, request }) => {
|
||||
const abandoned = `Système abandonné ${Date.now()}`;
|
||||
|
||||
await page.goto('/game-systems/create');
|
||||
await page.getByLabel(/^Nom/i).fill(abandoned);
|
||||
|
||||
await page.getByRole('button', { name: /^Annuler$/i }).click();
|
||||
await expect(page).toHaveURL(/\/game-systems$/);
|
||||
|
||||
// Rien n'a ete cree cote API.
|
||||
const all = await request.get('/api/game-systems').then((r) => r.json());
|
||||
expect(all.find((gs: { name: string }) => gs.name === abandoned)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
61
web/e2e/tests/game-system/game-system-delete.spec.ts
Normal file
61
web/e2e/tests/game-system/game-system-delete.spec.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import {
|
||||
seedGameSystem,
|
||||
deleteGameSystem,
|
||||
type SeededGameSystem,
|
||||
} from '../../fixtures/api';
|
||||
|
||||
test.describe('GameSystem delete', () => {
|
||||
let gs: SeededGameSystem;
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
gs = await seedGameSystem(request);
|
||||
});
|
||||
|
||||
test.afterEach(async ({ request }) => {
|
||||
// Best-effort cleanup — ne fait rien si deja supprime par le test.
|
||||
if (gs?.id) await deleteGameSystem(request, gs.id);
|
||||
});
|
||||
|
||||
test('deletes a game system after confirming and removes it from the list', async ({
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
await page.goto('/game-systems');
|
||||
|
||||
const card = page.locator('.gs-card', { hasText: gs.name });
|
||||
await expect(card).toBeVisible();
|
||||
|
||||
// Bouton corbeille dans le coin de la carte du systeme seede.
|
||||
await card.locator('.icon-btn').click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog).toContainText(gs.name);
|
||||
|
||||
await dialog.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
|
||||
// La carte disparait apres reload de la liste.
|
||||
await expect(page.locator('.gs-card', { hasText: gs.name })).toHaveCount(0);
|
||||
|
||||
const res = await request.get(`/api/game-systems/${gs.id}`);
|
||||
expect(res.status()).toBe(404);
|
||||
});
|
||||
|
||||
test('keeps the game system when cancel is clicked', async ({ page, request }) => {
|
||||
await page.goto('/game-systems');
|
||||
|
||||
const card = page.locator('.gs-card', { hasText: gs.name });
|
||||
await expect(card).toBeVisible();
|
||||
await card.locator('.icon-btn').click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Annuler$/i }).click();
|
||||
|
||||
// La carte est toujours la, le systeme est toujours en base.
|
||||
await expect(page.locator('.gs-card', { hasText: gs.name })).toBeVisible();
|
||||
const res = await request.get(`/api/game-systems/${gs.id}`);
|
||||
expect(res.ok()).toBeTruthy();
|
||||
});
|
||||
});
|
||||
68
web/e2e/tests/game-system/game-system-edit.spec.ts
Normal file
68
web/e2e/tests/game-system/game-system-edit.spec.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import {
|
||||
seedGameSystem,
|
||||
deleteGameSystem,
|
||||
getGameSystemById,
|
||||
type SeededGameSystem,
|
||||
} from '../../fixtures/api';
|
||||
|
||||
test.describe('GameSystem edit', () => {
|
||||
let gs: SeededGameSystem;
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
gs = await seedGameSystem(request, {
|
||||
description: 'Description initiale.',
|
||||
author: 'Auteur initial',
|
||||
});
|
||||
});
|
||||
|
||||
test.afterEach(async ({ request }) => {
|
||||
if (gs?.id) await deleteGameSystem(request, gs.id);
|
||||
});
|
||||
|
||||
test('form is prefilled with the game system data', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
|
||||
await expect(page.getByRole('heading', { name: /Éditer le système/i })).toBeVisible();
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
await expect(page.getByLabel(/Description courte/i)).toHaveValue('Description initiale.');
|
||||
await expect(page.getByLabel(/Auteur/i)).toHaveValue('Auteur initial');
|
||||
});
|
||||
|
||||
test('edits name and description and persists them to API', async ({ page, request }) => {
|
||||
const newName = `${gs.name} renamed`;
|
||||
const newDescription = 'Description mise à jour par le test.';
|
||||
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
|
||||
// Attente que le formulaire soit prerempli avant de fill — sinon le load
|
||||
// async ecrase les valeurs filled (cf. bug arc-edit corrige).
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
await page.getByLabel(/^Nom/i).fill(newName);
|
||||
await page.getByLabel(/Description courte/i).fill(newDescription);
|
||||
|
||||
await page.getByRole('button', { name: /^Enregistrer$/i }).click();
|
||||
|
||||
// Retour a la liste apres save.
|
||||
await expect(page).toHaveURL(/\/game-systems$/);
|
||||
|
||||
const persisted = await getGameSystemById(request, gs.id);
|
||||
expect(persisted.name).toBe(newName);
|
||||
expect(persisted.description).toBe(newDescription);
|
||||
});
|
||||
|
||||
test('save button is disabled when name is cleared', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
const nameField = page.getByLabel(/^Nom/i);
|
||||
const saveBtn = page.getByRole('button', { name: /^Enregistrer$/i });
|
||||
|
||||
await expect(saveBtn).toBeEnabled();
|
||||
await nameField.fill('');
|
||||
await expect(saveBtn).toBeDisabled();
|
||||
await nameField.fill('OK');
|
||||
await expect(saveBtn).toBeEnabled();
|
||||
});
|
||||
});
|
||||
111
web/e2e/tests/game-system/game-system-sections.spec.ts
Normal file
111
web/e2e/tests/game-system/game-system-sections.spec.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import {
|
||||
seedGameSystem,
|
||||
deleteGameSystem,
|
||||
type SeededGameSystem,
|
||||
} from '../../fixtures/api';
|
||||
|
||||
test.describe('GameSystem rule sections editor', () => {
|
||||
let gs: SeededGameSystem;
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
// On part d'un GameSystem vide (pas de regles seedees) — chaque test gere
|
||||
// ses propres ajouts pour eviter les couplages.
|
||||
gs = await seedGameSystem(request);
|
||||
});
|
||||
|
||||
test.afterEach(async ({ request }) => {
|
||||
if (gs?.id) await deleteGameSystem(request, gs.id);
|
||||
});
|
||||
|
||||
test('adds a suggested section, fills it, and persists it', async ({ page, request }) => {
|
||||
const sectionContent = 'Initiative à d20, action+bonus+mouvement, dégâts par dés.';
|
||||
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
// Attendre le chargement du form (nom prerempli).
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
// Empty state visible tant qu'aucune section n'est ajoutee.
|
||||
await expect(page.locator('.section-list .empty-hint')).toBeVisible();
|
||||
|
||||
// Ajout via la chip suggeree "Combat".
|
||||
await page.locator('.add-row .chip', { hasText: 'Combat' }).click();
|
||||
|
||||
// Une section-card est apparue avec titre "Combat" prerempli + textarea visible.
|
||||
const card = page.locator('.section-card').first();
|
||||
await expect(card).toBeVisible();
|
||||
await expect(card.locator('.section-title-input')).toHaveValue('Combat');
|
||||
await card.locator('.section-content').fill(sectionContent);
|
||||
|
||||
// Save + retour a la liste.
|
||||
await page.getByRole('button', { name: /^Enregistrer$/i }).click();
|
||||
await expect(page).toHaveURL(/\/game-systems$/);
|
||||
|
||||
// Verification cote API : le markdown contient bien la section + son contenu.
|
||||
const persisted = await request.get(`/api/game-systems/${gs.id}`).then((r) => r.json());
|
||||
expect(persisted.rulesMarkdown).toContain('## Combat');
|
||||
expect(persisted.rulesMarkdown).toContain(sectionContent);
|
||||
});
|
||||
|
||||
test('disables a suggested chip after it has been used', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
const combatChip = page.locator('.add-row .chip', { hasText: 'Combat' });
|
||||
await expect(combatChip).toBeEnabled();
|
||||
|
||||
await combatChip.click();
|
||||
|
||||
// Apres ajout, la chip "Combat" est desactivee (suggestion deja utilisee).
|
||||
await expect(combatChip).toBeDisabled();
|
||||
});
|
||||
|
||||
test('adds a custom blank section via "Autre…" and lets the user name it', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
await page.locator('.add-row .chip-custom', { hasText: /Autre/i }).click();
|
||||
|
||||
// Section vierge ajoutee : titre vide, prete a remplir.
|
||||
const card = page.locator('.section-card').first();
|
||||
await expect(card).toBeVisible();
|
||||
const titleInput = card.locator('.section-title-input');
|
||||
await expect(titleInput).toHaveValue('');
|
||||
await titleInput.fill('Sorts');
|
||||
await expect(titleInput).toHaveValue('Sorts');
|
||||
});
|
||||
|
||||
test('removes a section', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
await page.locator('.add-row .chip', { hasText: 'Combat' }).click();
|
||||
await page.locator('.add-row .chip', { hasText: 'Classes' }).click();
|
||||
|
||||
await expect(page.locator('.section-card')).toHaveCount(2);
|
||||
|
||||
// Supprime la premiere section (Combat).
|
||||
await page.locator('.section-card').first().locator('.btn-remove').click();
|
||||
await expect(page.locator('.section-card')).toHaveCount(1);
|
||||
await expect(page.locator('.section-card').first().locator('.section-title-input')).toHaveValue('Classes');
|
||||
});
|
||||
|
||||
test('collapses and expands a section', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
await page.locator('.add-row .chip', { hasText: 'Combat' }).click();
|
||||
const card = page.locator('.section-card').first();
|
||||
|
||||
// Par defaut deployee : textarea visible.
|
||||
await expect(card.locator('.section-content')).toBeVisible();
|
||||
|
||||
// Clic sur le bouton collapse → textarea masquee.
|
||||
await card.locator('.btn-collapse').click();
|
||||
await expect(card.locator('.section-content')).toHaveCount(0);
|
||||
|
||||
// Re-clic → re-deployee.
|
||||
await card.locator('.btn-collapse').click();
|
||||
await expect(card.locator('.section-content')).toBeVisible();
|
||||
});
|
||||
});
|
||||
151
web/e2e/tests/game-system/game-system-templates.spec.ts
Normal file
151
web/e2e/tests/game-system/game-system-templates.spec.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
import { test, expect, Page } from '@playwright/test';
|
||||
import {
|
||||
seedGameSystem,
|
||||
deleteGameSystem,
|
||||
type SeededGameSystem,
|
||||
} from '../../fixtures/api';
|
||||
|
||||
/**
|
||||
* Tests du composant <app-template-fields-editor> dans le contexte GameSystem.
|
||||
*
|
||||
* Le composant est instancie DEUX fois sur la page d'edition d'un GameSystem
|
||||
* (une fois pour PJ "characterTemplate", une fois pour PNJ "npcTemplate"), donc
|
||||
* les selecteurs doivent etre scopes a l'instance ciblee. On utilise un helper
|
||||
* `tfe(label)` qui renvoie le locator de l'editeur correspondant au titre.
|
||||
*/
|
||||
test.describe('GameSystem template fields editor (PJ / PNJ)', () => {
|
||||
let gs: SeededGameSystem;
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
gs = await seedGameSystem(request);
|
||||
});
|
||||
|
||||
test.afterEach(async ({ request }) => {
|
||||
if (gs?.id) await deleteGameSystem(request, gs.id);
|
||||
});
|
||||
|
||||
/** Helper : retourne le locator de l'editeur de templates par son label. */
|
||||
const tfe = (page: Page, label: 'PJ' | 'PNJ') =>
|
||||
page.locator('.tfe').filter({ hasText: `Champs de la fiche ${label}` });
|
||||
|
||||
test('adds a suggested field to the PJ template and persists it', async ({ page, request }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
const pjEditor = tfe(page, 'PJ');
|
||||
await expect(pjEditor).toBeVisible();
|
||||
|
||||
// Ajout de "Histoire" via la chip suggeree.
|
||||
await pjEditor.locator('.tfe-add .chip', { hasText: 'Histoire' }).click();
|
||||
|
||||
// Une row apparait avec le nom prerempli.
|
||||
const row = pjEditor.locator('.tfe-item').first();
|
||||
await expect(row).toBeVisible();
|
||||
await expect(row.locator('.tfe-name')).toHaveValue('Histoire');
|
||||
|
||||
// Save → retour a la liste.
|
||||
await page.getByRole('button', { name: /^Enregistrer$/i }).click();
|
||||
await expect(page).toHaveURL(/\/game-systems$/);
|
||||
|
||||
// Verification API : le champ est bien dans characterTemplate.
|
||||
const persisted = await request.get(`/api/game-systems/${gs.id}`).then((r) => r.json());
|
||||
expect(persisted.characterTemplate).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ name: 'Histoire' })]),
|
||||
);
|
||||
// npcTemplate non touche (toujours vide).
|
||||
expect(persisted.npcTemplate ?? []).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('adds a custom NUMBER field via "Nombre" chip', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
const pjEditor = tfe(page, 'PJ');
|
||||
await pjEditor.locator('.tfe-add .chip-custom', { hasText: 'Nombre' }).click();
|
||||
|
||||
const row = pjEditor.locator('.tfe-item').first();
|
||||
await expect(row).toBeVisible();
|
||||
// Champ vide, nom a remplir, type "NUMBER" pre-selectionne dans le select.
|
||||
await expect(row.locator('.tfe-name')).toHaveValue('');
|
||||
await expect(row.locator('.tfe-type')).toHaveValue('NUMBER');
|
||||
|
||||
await row.locator('.tfe-name').fill('Points de vie');
|
||||
await expect(row.locator('.tfe-name')).toHaveValue('Points de vie');
|
||||
});
|
||||
|
||||
test('PJ and PNJ editors are independent (adding to one does not affect the other)', async ({
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
await tfe(page, 'PJ').locator('.tfe-add .chip', { hasText: 'Histoire' }).click();
|
||||
await tfe(page, 'PNJ').locator('.tfe-add .chip', { hasText: 'Motivation' }).click();
|
||||
|
||||
await expect(tfe(page, 'PJ').locator('.tfe-item')).toHaveCount(1);
|
||||
await expect(tfe(page, 'PNJ').locator('.tfe-item')).toHaveCount(1);
|
||||
await expect(tfe(page, 'PJ').locator('.tfe-item').first().locator('.tfe-name')).toHaveValue('Histoire');
|
||||
await expect(tfe(page, 'PNJ').locator('.tfe-item').first().locator('.tfe-name')).toHaveValue('Motivation');
|
||||
|
||||
await page.getByRole('button', { name: /^Enregistrer$/i }).click();
|
||||
await expect(page).toHaveURL(/\/game-systems$/);
|
||||
|
||||
const persisted = await request.get(`/api/game-systems/${gs.id}`).then((r) => r.json());
|
||||
expect(persisted.characterTemplate).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ name: 'Histoire' })]),
|
||||
);
|
||||
expect(persisted.npcTemplate).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ name: 'Motivation' })]),
|
||||
);
|
||||
});
|
||||
|
||||
test('removes a field from the template', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
const pjEditor = tfe(page, 'PJ');
|
||||
await pjEditor.locator('.tfe-add .chip', { hasText: 'Histoire' }).click();
|
||||
await pjEditor.locator('.tfe-add .chip', { hasText: 'Apparence' }).click();
|
||||
|
||||
await expect(pjEditor.locator('.tfe-item')).toHaveCount(2);
|
||||
|
||||
// Supprime le premier champ (Histoire) via son btn-remove.
|
||||
await pjEditor.locator('.tfe-item').first().locator('.btn-remove').click();
|
||||
await expect(pjEditor.locator('.tfe-item')).toHaveCount(1);
|
||||
await expect(pjEditor.locator('.tfe-item').first().locator('.tfe-name')).toHaveValue('Apparence');
|
||||
});
|
||||
|
||||
test('reorders fields with the up arrow button', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
const pjEditor = tfe(page, 'PJ');
|
||||
await pjEditor.locator('.tfe-add .chip', { hasText: 'Histoire' }).click();
|
||||
await pjEditor.locator('.tfe-add .chip', { hasText: 'Apparence' }).click();
|
||||
|
||||
// Ordre initial : Histoire, Apparence.
|
||||
let rows = pjEditor.locator('.tfe-item');
|
||||
await expect(rows.nth(0).locator('.tfe-name')).toHaveValue('Histoire');
|
||||
await expect(rows.nth(1).locator('.tfe-name')).toHaveValue('Apparence');
|
||||
|
||||
// Monte Apparence d'un cran.
|
||||
await rows.nth(1).locator('.btn-arrow').first().click();
|
||||
|
||||
rows = pjEditor.locator('.tfe-item');
|
||||
await expect(rows.nth(0).locator('.tfe-name')).toHaveValue('Apparence');
|
||||
await expect(rows.nth(1).locator('.tfe-name')).toHaveValue('Histoire');
|
||||
});
|
||||
|
||||
test('disables a suggested chip after the field has been added', async ({ page }) => {
|
||||
await page.goto(`/game-systems/${gs.id}/edit`);
|
||||
await expect(page.getByLabel(/^Nom/i)).toHaveValue(gs.name);
|
||||
|
||||
const pjEditor = tfe(page, 'PJ');
|
||||
const histoireChip = pjEditor.locator('.tfe-add .chip', { hasText: 'Histoire' });
|
||||
|
||||
await expect(histoireChip).toBeEnabled();
|
||||
await histoireChip.click();
|
||||
await expect(histoireChip).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -17,32 +17,31 @@ test.describe('Lore delete', () => {
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
let confirmMessage = '';
|
||||
page.on('dialog', async (dialog) => {
|
||||
confirmMessage = dialog.message();
|
||||
await dialog.accept();
|
||||
});
|
||||
|
||||
await page.goto(`/lore/${seeded.id}`);
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).first().click();
|
||||
|
||||
// Attente du dialog et du retour sur la liste des lores.
|
||||
await expect(page).toHaveURL(/\/lore$/);
|
||||
expect(confirmMessage).toContain(seeded.name);
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog).toContainText(seeded.name);
|
||||
// Lore contient un dossier seedé : le récapitulatif doit l'indiquer.
|
||||
expect(confirmMessage).toMatch(/1 dossier/i);
|
||||
await expect(dialog).toContainText(/1 dossier/i);
|
||||
|
||||
await dialog.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
|
||||
// Attente du retour sur la liste des lores.
|
||||
await expect(page).toHaveURL(/\/lore$/);
|
||||
|
||||
const res = await request.get(`/api/lores/${seeded.id}`);
|
||||
expect(res.status()).toBe(404);
|
||||
});
|
||||
|
||||
test('keeps the lore when the confirm is dismissed', async ({ page, request }) => {
|
||||
page.on('dialog', async (dialog) => {
|
||||
await dialog.dismiss();
|
||||
});
|
||||
|
||||
await page.goto(`/lore/${seeded.id}`);
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).first().click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Annuler$/i }).click();
|
||||
|
||||
// On reste sur le détail, le titre du lore est toujours visible.
|
||||
await expect(page.locator('.detail-header h1')).toHaveText(seeded.name);
|
||||
|
||||
@@ -32,10 +32,12 @@ test.describe('Page delete', () => {
|
||||
});
|
||||
|
||||
test('deletes the page after accepting confirm', async ({ page, request }) => {
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
|
||||
await page.goto(`/lore/${seeded.id}/pages/${pageEntity.id}/edit`);
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).first().click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
|
||||
// Le composant redirige vers la racine du Lore après suppression.
|
||||
await expect(page).toHaveURL(new RegExp(`/lore/${seeded.id}$`));
|
||||
@@ -45,10 +47,12 @@ test.describe('Page delete', () => {
|
||||
});
|
||||
|
||||
test('keeps the page when confirm is dismissed', async ({ page, request }) => {
|
||||
page.on('dialog', (dialog) => dialog.dismiss());
|
||||
|
||||
await page.goto(`/lore/${seeded.id}/pages/${pageEntity.id}/edit`);
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
await page.getByRole('button', { name: /^Supprimer$/i }).first().click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Annuler$/i }).click();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/lore/${seeded.id}/pages/${pageEntity.id}/edit$`));
|
||||
|
||||
|
||||
@@ -25,11 +25,13 @@ test.describe('Template delete', () => {
|
||||
});
|
||||
|
||||
test('deletes the template after accepting confirm', async ({ page, request }) => {
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
|
||||
await page.goto(`/lore/${seeded.id}/templates/${template.id}`);
|
||||
await page.locator('.page-header .btn-danger').click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Supprimer$/i }).click();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/lore/${seeded.id}$`));
|
||||
|
||||
const templates = await getTemplatesForLore(request, seeded.id);
|
||||
@@ -37,11 +39,13 @@ test.describe('Template delete', () => {
|
||||
});
|
||||
|
||||
test('keeps the template when confirm is dismissed', async ({ page, request }) => {
|
||||
page.on('dialog', (dialog) => dialog.dismiss());
|
||||
|
||||
await page.goto(`/lore/${seeded.id}/templates/${template.id}`);
|
||||
await page.locator('.page-header .btn-danger').click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Annuler$/i }).click();
|
||||
|
||||
// On reste sur l'écran d'édition (l'URL ne change pas).
|
||||
await expect(page).toHaveURL(new RegExp(`/lore/${seeded.id}/templates/${template.id}$`));
|
||||
|
||||
|
||||
4
web/package-lock.json
generated
4
web/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "loremind-web",
|
||||
"version": "0.8.1",
|
||||
"version": "0.8.4-beta",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "loremind-web",
|
||||
"version": "0.8.1",
|
||||
"version": "0.8.4-beta",
|
||||
"dependencies": {
|
||||
"@angular/animations": "^17.0.0",
|
||||
"@angular/common": "^17.0.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "loremind-web",
|
||||
"version": "0.8.1",
|
||||
"version": "0.8.4-beta",
|
||||
"description": "LoreMind Frontend - Angular",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
const baseURL = process.env['E2E_BASE_URL'] || 'http://localhost:8081';
|
||||
// Par defaut on cible le serveur de dev Angular (ng serve) sur :4200 pour les
|
||||
// runs locaux — c'est ce qu'on veut quand on bosse en TDD/dev sur le front.
|
||||
// La CI (.gitea/workflows/e2e.yml) override avec `E2E_BASE_URL=http://web`
|
||||
// pour cibler l'instance Docker dans le reseau du runner. Pour tester
|
||||
// localement contre le container docker-compose, lancer :
|
||||
// E2E_BASE_URL=http://localhost:8081 npm run e2e
|
||||
const baseURL = process.env['E2E_BASE_URL'] || 'http://localhost:4200';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e/tests',
|
||||
|
||||
@@ -18,3 +18,4 @@
|
||||
</div>
|
||||
|
||||
<app-global-search></app-global-search>
|
||||
<app-confirm-dialog-host></app-confirm-dialog-host>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { SidebarComponent } from './sidebar/sidebar.component';
|
||||
import { SecondarySidebarComponent } from './shared/secondary-sidebar/secondary-sidebar.component';
|
||||
import { GlobalSearchComponent } from './shared/global-search/global-search.component';
|
||||
import { UpdateBannerComponent } from './shared/update-banner/update-banner.component';
|
||||
import { ConfirmDialogHostComponent } from './shared/confirm-dialog/confirm-dialog-host.component';
|
||||
import { LayoutService } from './services/layout.service';
|
||||
import { GlobalSearchService } from './services/global-search.service';
|
||||
import { VersionCheckerService } from './services/version-checker.service';
|
||||
@@ -18,6 +19,7 @@ import { VersionCheckerService } from './services/version-checker.service';
|
||||
SecondarySidebarComponent,
|
||||
GlobalSearchComponent,
|
||||
UpdateBannerComponent,
|
||||
ConfirmDialogHostComponent,
|
||||
AsyncPipe,
|
||||
NgIf,
|
||||
],
|
||||
|
||||
@@ -18,8 +18,10 @@ export const routes: Routes = [
|
||||
{ path: 'campaigns/:id', loadComponent: () => import('./campaigns/campaign/campaign-detail/campaign-detail.component').then(m => m.CampaignDetailComponent) },
|
||||
{ path: 'campaigns/:campaignId/characters/create', loadComponent: () => import('./campaigns/character/character-edit/character-edit.component').then(m => m.CharacterEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/characters/:characterId/edit', loadComponent: () => import('./campaigns/character/character-edit/character-edit.component').then(m => m.CharacterEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/characters/:characterId', loadComponent: () => import('./campaigns/character/character-view/character-view.component').then(m => m.CharacterViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/npcs/create', loadComponent: () => import('./campaigns/npc/npc-edit/npc-edit.component').then(m => m.NpcEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/npcs/:npcId/edit', loadComponent: () => import('./campaigns/npc/npc-edit/npc-edit.component').then(m => m.NpcEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/npcs/:npcId', loadComponent: () => import('./campaigns/npc/npc-view/npc-view.component').then(m => m.NpcViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/create', loadComponent: () => import('./campaigns/arc/arc-create/arc-create.component').then(m => m.ArcCreateComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId', loadComponent: () => import('./campaigns/arc/arc-view/arc-view.component').then(m => m.ArcViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId/edit', loadComponent: () => import('./campaigns/arc/arc-edit/arc-edit.component').then(m => m.ArcEditComponent) },
|
||||
|
||||
@@ -7,9 +7,8 @@ import { LucideAngularModule, BookOpen } from 'lucide-angular';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||
import { Campaign } from '../../../services/campaign.model';
|
||||
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||
import { LayoutService } from '../../../services/layout.service';
|
||||
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
|
||||
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
|
||||
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
|
||||
@@ -62,21 +61,7 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
}).subscribe(({ campaign, allCampaigns, treeData }) => {
|
||||
this.existingArcCount = treeData.arcs.length;
|
||||
|
||||
const globalItems: GlobalItem[] = allCampaigns.map((c: Campaign) => ({
|
||||
id: c.id!, name: c.name, route: `/campaigns/${c.id}`
|
||||
}));
|
||||
|
||||
this.layoutService.show({
|
||||
title: campaign.name,
|
||||
items: buildCampaignTree(this.campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${this.campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackRoute: '/campaigns'
|
||||
});
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -89,7 +74,7 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
order: this.existingArcCount + 1,
|
||||
icon: this.selectedIcon
|
||||
}).subscribe({
|
||||
next: (created) => this.router.navigate(['/campaigns', this.campaignId, 'arcs', created.id, 'edit']),
|
||||
next: (created) => this.router.navigate(['/campaigns', this.campaignId, 'arcs', created.id]),
|
||||
error: () => console.error('Erreur lors de la création de l\'arc')
|
||||
});
|
||||
}
|
||||
@@ -99,6 +84,9 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.layoutService.hide();
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,16 +9,17 @@ import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { PageService } from '../../../services/page.service';
|
||||
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||
import { LayoutService } from '../../../services/layout.service';
|
||||
import { PageTitleService } from '../../../services/page-title.service';
|
||||
import { Campaign, Arc } from '../../../services/campaign.model';
|
||||
import { Arc } from '../../../services/campaign.model';
|
||||
import { Page } from '../../../services/page.model';
|
||||
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
|
||||
import { LoreLinkPickerComponent } from '../../../shared/lore-link-picker/lore-link-picker.component';
|
||||
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
||||
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
||||
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
|
||||
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
|
||||
/**
|
||||
* Écran de détail/modification d'un Arc.
|
||||
@@ -78,7 +79,8 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
private npcService: NpcService,
|
||||
private pageService: PageService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
) {
|
||||
this.form = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
@@ -142,21 +144,7 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
resolution: arc.resolution ?? ''
|
||||
});
|
||||
|
||||
const globalItems: GlobalItem[] = allCampaigns.map((c: Campaign) => ({
|
||||
id: c.id!, name: c.name, route: `/campaigns/${c.id}`
|
||||
}));
|
||||
|
||||
this.layoutService.show({
|
||||
title: campaign.name,
|
||||
items: buildCampaignTree(this.campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${this.campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackRoute: '/campaigns'
|
||||
});
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -183,10 +171,18 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
delete(): void {
|
||||
if (!confirm(`Supprimer l'arc "${this.arc?.name}" ? Cette action est irréversible.`)) return;
|
||||
this.campaignService.deleteArc(this.arcId).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId]),
|
||||
error: () => console.error('Erreur lors de la suppression')
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer l\'arc',
|
||||
message: `Supprimer l'arc "${this.arc?.name}" ?`,
|
||||
details: ['Cette action est irréversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
this.campaignService.deleteArc(this.arcId).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId]),
|
||||
error: () => console.error('Erreur lors de la suppression')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -195,6 +191,9 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.layoutService.hide();
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,13 @@ import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { PageService } from '../../../services/page.service';
|
||||
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||
import { LayoutService } from '../../../services/layout.service';
|
||||
import { PageTitleService } from '../../../services/page-title.service';
|
||||
import { Campaign, Arc } from '../../../services/campaign.model';
|
||||
import { Arc } from '../../../services/campaign.model';
|
||||
import { Page } from '../../../services/page.model';
|
||||
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
|
||||
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
|
||||
/**
|
||||
* Écran de consultation d'un Arc narratif (lecture seule).
|
||||
@@ -50,7 +51,8 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
private npcService: NpcService,
|
||||
private pageService: PageService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -83,20 +85,7 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
this.availablePages = pages;
|
||||
this.pageTitleService.set(arc.name);
|
||||
|
||||
const globalItems: GlobalItem[] = allCampaigns.map((c: Campaign) => ({
|
||||
id: c.id!, name: c.name, route: `/campaigns/${c.id}`
|
||||
}));
|
||||
this.layoutService.show({
|
||||
title: campaign.name,
|
||||
items: buildCampaignTree(this.campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${this.campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackRoute: '/campaigns'
|
||||
});
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -122,18 +111,24 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
if (impact.chapters > 0) parts.push(`${impact.chapters} chapitre${impact.chapters > 1 ? 's' : ''}`);
|
||||
if (impact.scenes > 0) parts.push(`${impact.scenes} scène${impact.scenes > 1 ? 's' : ''}`);
|
||||
|
||||
const lines = [`Supprimer l'arc "${arc.name}" ?`];
|
||||
const details: string[] = [];
|
||||
if (parts.length) {
|
||||
lines.push('');
|
||||
lines.push(`Cette action supprimera aussi : ${parts.join(', ')}.`);
|
||||
details.push(`Cette action supprimera aussi : ${parts.join(', ')}.`);
|
||||
}
|
||||
lines.push('');
|
||||
lines.push('Cette action est irréversible.');
|
||||
details.push('Cette action est irréversible.');
|
||||
|
||||
if (!confirm(lines.join('\n'))) return;
|
||||
this.campaignService.deleteArc(arc.id!).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId]),
|
||||
error: () => console.error('Erreur lors de la suppression de l\'arc')
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer l\'arc',
|
||||
message: `Supprimer l'arc "${arc.name}" ?`,
|
||||
details,
|
||||
confirmLabel: 'Supprimer',
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
this.campaignService.deleteArc(arc.id!).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId]),
|
||||
error: () => console.error('Erreur lors de la suppression de l\'arc')
|
||||
});
|
||||
});
|
||||
},
|
||||
error: () => console.error('Impossible de récupérer les dépendances de l\'arc')
|
||||
@@ -141,6 +136,9 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.layoutService.hide();
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ import { switchMap, map } from 'rxjs/operators';
|
||||
import { CampaignService } from '../services/campaign.service';
|
||||
import { CharacterService } from '../services/character.service';
|
||||
import { NpcService } from '../services/npc.service';
|
||||
import { TreeItem } from '../services/layout.service';
|
||||
import { Arc, Chapter, Scene } from '../services/campaign.model';
|
||||
import { TreeItem, SecondarySidebarConfig, GlobalItem } from '../services/layout.service';
|
||||
import { Arc, Chapter, Scene, Campaign } from '../services/campaign.model';
|
||||
import { Character } from '../services/character.model';
|
||||
import { Npc } from '../services/npc.model';
|
||||
|
||||
@@ -83,7 +83,7 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
const characterItems: TreeItem[] = sortedCharacters.map(ch => ({
|
||||
id: `character-${ch.id}`,
|
||||
label: ch.name,
|
||||
route: `/campaigns/${campaignId}/characters/${ch.id}/edit`
|
||||
route: `/campaigns/${campaignId}/characters/${ch.id}`
|
||||
}));
|
||||
|
||||
const charactersNode: TreeItem = {
|
||||
@@ -107,7 +107,7 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
const npcItems: TreeItem[] = sortedNpcs.map(n => ({
|
||||
id: `npc-${n.id}`,
|
||||
label: n.name,
|
||||
route: `/campaigns/${campaignId}/npcs/${n.id}/edit`
|
||||
route: `/campaigns/${campaignId}/npcs/${n.id}`
|
||||
}));
|
||||
|
||||
const npcsNode: TreeItem = {
|
||||
@@ -172,3 +172,35 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
|
||||
return [...arcNodes, charactersNode, npcsNode];
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit la SecondarySidebarConfig complete d'une campagne a partir des
|
||||
* donnees deja chargees. A utiliser quand le composant fait deja un forkJoin
|
||||
* pour ses propres donnees (arc-view, scene-edit, etc.) et a deja `campaign`,
|
||||
* `allCampaigns` et `treeData` en main — evite de refaire les memes HTTP.
|
||||
*
|
||||
* Pour les composants qui n'ont pas d'autre fetch a faire (character-view,
|
||||
* npc-view...), preferer CampaignSidebarService.show(campaignId) qui orchestre
|
||||
* le forkJoin et appelle layoutService.show() en une seule ligne.
|
||||
*/
|
||||
export function buildCampaignSidebarConfig(
|
||||
campaign: Campaign,
|
||||
allCampaigns: Campaign[],
|
||||
treeData: CampaignTreeData,
|
||||
campaignId: string
|
||||
): SecondarySidebarConfig {
|
||||
const globalItems: GlobalItem[] = allCampaigns.map(c => ({
|
||||
id: c.id!, name: c.name, route: `/campaigns/${c.id}`
|
||||
}));
|
||||
return {
|
||||
title: campaign.name,
|
||||
items: buildCampaignTree(campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackRoute: '/campaigns'
|
||||
};
|
||||
}
|
||||
|
||||
@@ -50,14 +50,50 @@
|
||||
|
||||
<div class="field">
|
||||
<label for="campaign-game-system">Système de JDR</label>
|
||||
<select id="campaign-game-system" formControlName="gameSystemId">
|
||||
<select *ngIf="!creatingGameSystem" id="campaign-game-system" formControlName="gameSystemId">
|
||||
<option value="">— Aucun (campagne générique) —</option>
|
||||
<option *ngFor="let gs of availableGameSystems" [value]="gs.id">{{ gs.name }}</option>
|
||||
<option [value]="CREATE_GAMESYSTEM_SENTINEL">+ Créer un nouveau système…</option>
|
||||
</select>
|
||||
<p class="hint">
|
||||
|
||||
<!-- Mode creation inline : remplace temporairement le select. -->
|
||||
<div *ngIf="creatingGameSystem" class="inline-create">
|
||||
<input
|
||||
type="text"
|
||||
[(ngModel)]="newGameSystemName"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
placeholder="Nom du nouveau système (ex: D&D 5e, Nimble, Maison)"
|
||||
(keydown.enter)="$event.preventDefault(); submitCreateGameSystem()"
|
||||
(keydown.escape)="cancelCreateGameSystem()"
|
||||
autofocus
|
||||
/>
|
||||
<div class="inline-create-actions">
|
||||
<button type="button" class="btn-inline-primary"
|
||||
[disabled]="!newGameSystemName.trim() || creatingGameSystemInFlight"
|
||||
(click)="submitCreateGameSystem()">
|
||||
<lucide-icon [img]="Check" [size]="14"></lucide-icon>
|
||||
Créer
|
||||
</button>
|
||||
<button type="button" class="btn-inline-secondary" (click)="cancelCreateGameSystem()">
|
||||
Annuler
|
||||
</button>
|
||||
</div>
|
||||
<p class="hint">
|
||||
Création rapide — vous pourrez ajouter les règles, les templates de fiches PJ/PNJ
|
||||
et le reste depuis la section "Systèmes" plus tard.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p *ngIf="!creatingGameSystem" class="hint">
|
||||
Optionnel. Si défini, l'IA injectera les règles du système (classes, combat, lore...)
|
||||
dans ses suggestions pour respecter les mécaniques du JDR.
|
||||
</p>
|
||||
<p *ngIf="!creatingGameSystem" class="hint hint-warning">
|
||||
⚠️ Le système de jeu choisi détermine aussi le <strong>template des fiches de PJ et PNJ</strong>.
|
||||
Le changer plus tard rendra les champs des fiches existantes invisibles
|
||||
(les données restent stockées mais ne s'afficheront qu'en revenant à l'ancien système).
|
||||
Choisissez bien dès le départ si possible.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="info-box">
|
||||
|
||||
@@ -87,6 +87,81 @@ form {
|
||||
input[type="number"] { width: 120px; }
|
||||
}
|
||||
|
||||
.inline-create {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.875rem;
|
||||
background: #1a2233;
|
||||
border: 1px solid #2d3748;
|
||||
border-left: 3px solid #6c63ff;
|
||||
border-radius: 8px;
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
background: #1f2937;
|
||||
border: 1px solid #374151;
|
||||
border-radius: 6px;
|
||||
padding: 0.6rem 0.875rem;
|
||||
color: white;
|
||||
font-size: 0.9rem;
|
||||
outline: none;
|
||||
transition: border-color 0.2s;
|
||||
|
||||
&::placeholder { color: #4b5563; }
|
||||
&:focus { border-color: #6c63ff; }
|
||||
}
|
||||
}
|
||||
|
||||
.inline-create-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.btn-inline-primary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.5rem 0.875rem;
|
||||
background: #6c63ff;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
|
||||
&:hover:not(:disabled) { background: #5b52e0; }
|
||||
&:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
}
|
||||
|
||||
.btn-inline-secondary {
|
||||
padding: 0.5rem 0.875rem;
|
||||
background: transparent;
|
||||
color: #9ca3af;
|
||||
border: 1px solid #374151;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, color 0.2s;
|
||||
|
||||
&:hover { background: #1f2937; color: white; }
|
||||
}
|
||||
|
||||
.hint-warning {
|
||||
margin-top: 0.5rem;
|
||||
background: rgba(234, 179, 8, 0.08);
|
||||
border-left: 3px solid #eab308;
|
||||
border-radius: 4px;
|
||||
padding: 0.625rem 0.875rem;
|
||||
color: #fbbf24;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.5;
|
||||
|
||||
strong { color: #fde68a; }
|
||||
}
|
||||
|
||||
.info-box {
|
||||
background: #1f2937;
|
||||
border-radius: 8px;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { LucideAngularModule, BookCopy, X } from 'lucide-angular';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, BookCopy, X, Plus, Check } from 'lucide-angular';
|
||||
import { LoreService } from '../../../services/lore.service';
|
||||
import { Lore } from '../../../services/lore.model';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
@@ -22,7 +23,7 @@ export interface CampaignCreatePayload {
|
||||
@Component({
|
||||
selector: 'app-campaign-create',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, LucideAngularModule],
|
||||
imports: [CommonModule, ReactiveFormsModule, FormsModule, LucideAngularModule],
|
||||
templateUrl: './campaign-create.component.html',
|
||||
styleUrls: ['./campaign-create.component.scss']
|
||||
})
|
||||
@@ -32,6 +33,11 @@ export class CampaignCreateComponent implements OnInit {
|
||||
|
||||
readonly BookCopy = BookCopy;
|
||||
readonly X = X;
|
||||
readonly Plus = Plus;
|
||||
readonly Check = Check;
|
||||
|
||||
/** Valeur sentinelle de l'option "Creer un systeme" dans le <select>. */
|
||||
readonly CREATE_GAMESYSTEM_SENTINEL = '__create__';
|
||||
|
||||
form: FormGroup;
|
||||
/** Lores disponibles pour association. Chargés à l'ouverture de la modal. */
|
||||
@@ -39,6 +45,11 @@ export class CampaignCreateComponent implements OnInit {
|
||||
/** GameSystems disponibles pour association. */
|
||||
availableGameSystems: GameSystem[] = [];
|
||||
|
||||
/** Mode creation inline d'un GameSystem depuis le dropdown. */
|
||||
creatingGameSystem = false;
|
||||
newGameSystemName = '';
|
||||
creatingGameSystemInFlight = false;
|
||||
|
||||
constructor(
|
||||
private fb: FormBuilder,
|
||||
private loreService: LoreService,
|
||||
@@ -62,6 +73,47 @@ export class CampaignCreateComponent implements OnInit {
|
||||
next: (gs) => this.availableGameSystems = gs,
|
||||
error: () => this.availableGameSystems = []
|
||||
});
|
||||
|
||||
// Detecte la selection de l'option sentinelle "Creer un systeme" et bascule
|
||||
// en mode creation inline. On reinitialise immediatement le control a ''
|
||||
// pour que la sentinelle ne reste pas en valeur reelle du form.
|
||||
this.form.get('gameSystemId')?.valueChanges.subscribe(value => {
|
||||
if (value === this.CREATE_GAMESYSTEM_SENTINEL) {
|
||||
this.form.get('gameSystemId')?.setValue('', { emitEvent: false });
|
||||
this.startCreateGameSystem();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
startCreateGameSystem(): void {
|
||||
this.creatingGameSystem = true;
|
||||
this.newGameSystemName = '';
|
||||
}
|
||||
|
||||
cancelCreateGameSystem(): void {
|
||||
this.creatingGameSystem = false;
|
||||
this.newGameSystemName = '';
|
||||
}
|
||||
|
||||
submitCreateGameSystem(): void {
|
||||
const name = this.newGameSystemName.trim();
|
||||
if (!name || this.creatingGameSystemInFlight) return;
|
||||
this.creatingGameSystemInFlight = true;
|
||||
this.gameSystemService.create({ name, isPublic: false }).subscribe({
|
||||
next: (created) => {
|
||||
this.creatingGameSystemInFlight = false;
|
||||
this.availableGameSystems = [...this.availableGameSystems, created];
|
||||
if (created.id) {
|
||||
this.form.get('gameSystemId')?.setValue(created.id);
|
||||
}
|
||||
this.creatingGameSystem = false;
|
||||
this.newGameSystemName = '';
|
||||
},
|
||||
error: () => {
|
||||
this.creatingGameSystemInFlight = false;
|
||||
console.error('Erreur lors de la creation du systeme de jeu');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
submit(): void {
|
||||
|
||||
@@ -55,10 +55,37 @@
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Système de JDR</label>
|
||||
<select [(ngModel)]="editGameSystemId" name="editGameSystemId">
|
||||
<select *ngIf="!creatingGameSystem"
|
||||
[(ngModel)]="editGameSystemId"
|
||||
name="editGameSystemId"
|
||||
(ngModelChange)="onEditGameSystemChange($event)">
|
||||
<option value="">— Aucun (générique) —</option>
|
||||
<option *ngFor="let gs of availableGameSystems" [value]="gs.id">{{ gs.name }}</option>
|
||||
<option [value]="CREATE_GAMESYSTEM_SENTINEL">+ Créer un nouveau système…</option>
|
||||
</select>
|
||||
|
||||
<div *ngIf="creatingGameSystem" class="inline-create">
|
||||
<input
|
||||
type="text"
|
||||
[(ngModel)]="newGameSystemName"
|
||||
name="newGameSystemName"
|
||||
placeholder="Nom du nouveau système (ex: D&D 5e, Nimble, Maison)"
|
||||
(keydown.enter)="$event.preventDefault(); submitCreateGameSystem()"
|
||||
(keydown.escape)="cancelCreateGameSystem()"
|
||||
autofocus
|
||||
/>
|
||||
<div class="inline-create-actions">
|
||||
<button type="button" class="btn-inline-primary"
|
||||
[disabled]="!newGameSystemName.trim() || creatingGameSystemInFlight"
|
||||
(click)="submitCreateGameSystem()">
|
||||
<lucide-icon [img]="Check" [size]="14"></lucide-icon>
|
||||
Créer
|
||||
</button>
|
||||
<button type="button" class="btn-inline-secondary" (click)="cancelCreateGameSystem()">
|
||||
Annuler
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button type="button" class="btn-primary" (click)="saveEdit()" [disabled]="!editName.trim()">
|
||||
@@ -90,7 +117,7 @@
|
||||
</div>
|
||||
|
||||
<div class="characters-grid" *ngIf="characters.length > 0">
|
||||
<div class="character-card" *ngFor="let character of characters" (click)="editCharacter(character)">
|
||||
<div class="character-card" *ngFor="let character of characters" (click)="viewCharacter(character)">
|
||||
<lucide-icon [img]="User" [size]="20" class="character-icon"></lucide-icon>
|
||||
<div class="character-info">
|
||||
<span class="character-name">{{ character.name }}</span>
|
||||
@@ -123,7 +150,7 @@
|
||||
</div>
|
||||
|
||||
<div class="characters-grid" *ngIf="npcs.length > 0">
|
||||
<div class="character-card" *ngFor="let npc of npcs" (click)="editNpc(npc)">
|
||||
<div class="character-card" *ngFor="let npc of npcs" (click)="viewNpc(npc)">
|
||||
<lucide-icon [img]="Drama" [size]="20" class="character-icon character-icon--npc"></lucide-icon>
|
||||
<div class="character-info">
|
||||
<span class="character-name">{{ npc.name }}</span>
|
||||
|
||||
@@ -122,6 +122,64 @@
|
||||
textarea { resize: vertical; }
|
||||
}
|
||||
|
||||
.inline-create {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.875rem;
|
||||
background: #0f172a;
|
||||
border: 1px solid #1f2937;
|
||||
border-left: 3px solid #6c63ff;
|
||||
border-radius: 8px;
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
background: #0a1320;
|
||||
border: 1px solid #1f2937;
|
||||
border-radius: 6px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
color: white;
|
||||
font-size: 0.9rem;
|
||||
outline: none;
|
||||
|
||||
&::placeholder { color: #4b5563; }
|
||||
&:focus { border-color: #6c63ff; }
|
||||
}
|
||||
|
||||
.inline-create-actions { display: flex; gap: 0.5rem; }
|
||||
|
||||
.btn-inline-primary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.45rem 0.875rem;
|
||||
background: #6c63ff;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
|
||||
&:hover:not(:disabled) { background: #5b52e0; }
|
||||
&:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
}
|
||||
|
||||
.btn-inline-secondary {
|
||||
padding: 0.45rem 0.875rem;
|
||||
background: transparent;
|
||||
color: #9ca3af;
|
||||
border: 1px solid #374151;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, color 0.2s;
|
||||
|
||||
&:hover { background: #1f2937; color: white; }
|
||||
}
|
||||
}
|
||||
|
||||
.header-actions { justify-content: flex-end; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, User, Dices, Drama } from 'lucide-angular';
|
||||
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, User, Dices, Drama, Check } from 'lucide-angular';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
import { catchError, switchMap, filter, map } from 'rxjs/operators';
|
||||
@@ -14,11 +14,12 @@ import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { Character } from '../../../services/character.model';
|
||||
import { Npc } from '../../../services/npc.model';
|
||||
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||
import { LayoutService } from '../../../services/layout.service';
|
||||
import { PageTitleService } from '../../../services/page-title.service';
|
||||
import { Campaign, Arc } from '../../../services/campaign.model';
|
||||
import { Lore } from '../../../services/lore.model';
|
||||
import { loadCampaignTreeData, buildCampaignTree, CampaignTreeData } from '../../campaign-tree.helper';
|
||||
import { loadCampaignTreeData, buildCampaignSidebarConfig, CampaignTreeData } from '../../campaign-tree.helper';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-detail',
|
||||
@@ -36,6 +37,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
readonly User = User;
|
||||
readonly Dices = Dices;
|
||||
readonly Drama = Drama;
|
||||
readonly Check = Check;
|
||||
|
||||
campaign: Campaign | null = null;
|
||||
arcs: Arc[] = [];
|
||||
@@ -61,6 +63,13 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
editLoreId = '';
|
||||
editGameSystemId = '';
|
||||
|
||||
/** Valeur sentinelle de l'option "Creer un systeme" dans le <select>. */
|
||||
readonly CREATE_GAMESYSTEM_SENTINEL = '__create__';
|
||||
/** Mode creation inline d'un GameSystem depuis le dropdown d'edition. */
|
||||
creatingGameSystem = false;
|
||||
newGameSystemName = '';
|
||||
creatingGameSystemInFlight = false;
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
@@ -70,7 +79,8 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
private characterService: CharacterService,
|
||||
private npcService: NpcService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -194,6 +204,17 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
this.router.navigate(['/campaigns', this.campaign.id, 'characters', character.id, 'edit']);
|
||||
}
|
||||
|
||||
/** Ouvre la vue lecture seule (style WorldAnvil) — clic sur la carte. */
|
||||
viewCharacter(character: Character): void {
|
||||
if (!this.campaign || !character.id) return;
|
||||
this.router.navigate(['/campaigns', this.campaign.id, 'characters', character.id]);
|
||||
}
|
||||
|
||||
viewNpc(npc: Npc): void {
|
||||
if (!this.campaign || !npc.id) return;
|
||||
this.router.navigate(['/campaigns', this.campaign.id, 'npcs', npc.id]);
|
||||
}
|
||||
|
||||
createArc(): void {
|
||||
if (!this.campaign) return;
|
||||
this.router.navigate(['/campaigns', this.campaign.id, 'arcs', 'create']);
|
||||
@@ -205,19 +226,23 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extrait une ligne de résumé depuis le markdown (1re ligne non-vide, non-titre).
|
||||
* Générique : utilisé pour les fiches PJ comme PNJ (mêmes besoins d'aperçu carte).
|
||||
* Extrait une ligne de resume pour la fiche PJ/PNJ — 1re valeur de template
|
||||
* non-vide (apres refonte 2026-04-30, remplace l'ancien parsing markdown).
|
||||
*/
|
||||
personaSnippet(p: { markdownContent?: string | null }): string {
|
||||
if (!p.markdownContent) return '(Fiche vide)';
|
||||
const firstMeaningful = p.markdownContent
|
||||
.split('\n')
|
||||
.map(l => l.trim())
|
||||
.find(l => l && !l.startsWith('#'));
|
||||
if (!firstMeaningful) return '(Fiche vide)';
|
||||
return firstMeaningful.length > 80
|
||||
? firstMeaningful.substring(0, 77) + '…'
|
||||
: firstMeaningful;
|
||||
personaSnippet(p: { values?: Record<string, string> }): string {
|
||||
const values = p.values ?? {};
|
||||
for (const v of Object.values(values)) {
|
||||
if (!v) continue;
|
||||
const firstMeaningful = v
|
||||
.split('\n')
|
||||
.map(l => l.trim())
|
||||
.find(l => l && !l.startsWith('#'));
|
||||
if (!firstMeaningful) continue;
|
||||
return firstMeaningful.length > 80
|
||||
? firstMeaningful.substring(0, 77) + '…'
|
||||
: firstMeaningful;
|
||||
}
|
||||
return '(Fiche vide)';
|
||||
}
|
||||
|
||||
/** Alias gardé pour compatibilité avec les anciens templates. */
|
||||
@@ -226,24 +251,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private showLayout(allCampaigns: Campaign[], data: CampaignTreeData): void {
|
||||
const campaignId = this.campaign!.id!;
|
||||
const globalItems: GlobalItem[] = allCampaigns.map(c => ({
|
||||
id: c.id!,
|
||||
name: c.name,
|
||||
route: `/campaigns/${c.id}`
|
||||
}));
|
||||
|
||||
this.layoutService.show({
|
||||
title: this.campaign!.name,
|
||||
items: buildCampaignTree(campaignId, data),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackRoute: '/campaigns'
|
||||
});
|
||||
this.layoutService.show(buildCampaignSidebarConfig(this.campaign!, allCampaigns, data, this.campaign!.id!));
|
||||
}
|
||||
|
||||
// ─────────────── Édition / suppression de la Campagne ───────────────
|
||||
@@ -268,16 +276,83 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
|
||||
cancelEdit(): void {
|
||||
this.editing = false;
|
||||
this.creatingGameSystem = false;
|
||||
this.newGameSystemName = '';
|
||||
}
|
||||
|
||||
/** Detecte la selection de l'option sentinelle dans le <select> GameSystem. */
|
||||
onEditGameSystemChange(value: string): void {
|
||||
if (value === this.CREATE_GAMESYSTEM_SENTINEL) {
|
||||
this.editGameSystemId = '';
|
||||
this.startCreateGameSystem();
|
||||
}
|
||||
}
|
||||
|
||||
startCreateGameSystem(): void {
|
||||
this.creatingGameSystem = true;
|
||||
this.newGameSystemName = '';
|
||||
}
|
||||
|
||||
cancelCreateGameSystem(): void {
|
||||
this.creatingGameSystem = false;
|
||||
this.newGameSystemName = '';
|
||||
}
|
||||
|
||||
submitCreateGameSystem(): void {
|
||||
const name = this.newGameSystemName.trim();
|
||||
if (!name || this.creatingGameSystemInFlight) return;
|
||||
this.creatingGameSystemInFlight = true;
|
||||
this.gameSystemService.create({ name, isPublic: false }).subscribe({
|
||||
next: (created) => {
|
||||
this.creatingGameSystemInFlight = false;
|
||||
this.availableGameSystems = [...this.availableGameSystems, created];
|
||||
if (created.id) {
|
||||
this.editGameSystemId = created.id;
|
||||
}
|
||||
this.creatingGameSystem = false;
|
||||
this.newGameSystemName = '';
|
||||
},
|
||||
error: () => {
|
||||
this.creatingGameSystemInFlight = false;
|
||||
console.error('Erreur lors de la creation du systeme de jeu');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
saveEdit(): void {
|
||||
if (!this.campaign || !this.editName.trim()) return;
|
||||
const newGameSystemId = this.editGameSystemId ? this.editGameSystemId : null;
|
||||
const currentGameSystemId = this.campaign.gameSystemId ?? null;
|
||||
const gameSystemChanged = newGameSystemId !== currentGameSystemId;
|
||||
const hasSheets = this.characters.length > 0 || this.npcs.length > 0;
|
||||
if (gameSystemChanged && hasSheets) {
|
||||
const count = this.characters.length + this.npcs.length;
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Changer le systeme de jeu ?',
|
||||
message:
|
||||
`Vous etes sur le point de changer le systeme de jeu de cette campagne. ` +
|
||||
`Cela change egalement le template des fiches de PJ et PNJ.`,
|
||||
details: [
|
||||
`${count} fiche(s) existante(s) sont liees au template du systeme actuel.`,
|
||||
`Leurs champs ne s'afficheront plus avec le nouveau systeme.`,
|
||||
`Les donnees restent stockees : revenir a l'ancien systeme les rendra a nouveau visibles.`
|
||||
],
|
||||
confirmLabel: 'Changer quand meme',
|
||||
variant: 'warning'
|
||||
}).then(ok => { if (ok) this.persistEdit(newGameSystemId); });
|
||||
return;
|
||||
}
|
||||
this.persistEdit(newGameSystemId);
|
||||
}
|
||||
|
||||
private persistEdit(newGameSystemId: string | null): void {
|
||||
if (!this.campaign) return;
|
||||
this.campaignService.updateCampaign(this.campaign.id!, {
|
||||
name: this.editName.trim(),
|
||||
description: this.editDescription,
|
||||
playerCount: this.campaign.playerCount ?? 0,
|
||||
loreId: this.editLoreId ? this.editLoreId : null,
|
||||
gameSystemId: this.editGameSystemId ? this.editGameSystemId : null
|
||||
gameSystemId: newGameSystemId
|
||||
}).subscribe({
|
||||
next: (updated) => {
|
||||
this.campaign = updated;
|
||||
@@ -306,18 +381,22 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
if (impact.scenes > 0) parts.push(`${impact.scenes} scène${impact.scenes > 1 ? 's' : ''}`);
|
||||
if (impact.characters > 0) parts.push(`${impact.characters} personnage${impact.characters > 1 ? 's' : ''}`);
|
||||
|
||||
const lines = [`Supprimer définitivement la campagne "${campaign.name}" ?`];
|
||||
if (parts.length) {
|
||||
lines.push('');
|
||||
lines.push(`Cette action supprimera aussi : ${parts.join(', ')}.`);
|
||||
}
|
||||
lines.push('');
|
||||
lines.push('Cette action est irréversible.');
|
||||
const details: string[] = [];
|
||||
if (parts.length) details.push(`Sera aussi supprime : ${parts.join(', ')}.`);
|
||||
details.push('Cette action est irreversible.');
|
||||
|
||||
if (!confirm(lines.join('\n'))) return;
|
||||
this.campaignService.deleteCampaign(campaign.id!).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns']),
|
||||
error: () => console.error('Erreur lors de la suppression de la campagne')
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer la campagne ?',
|
||||
message: `Supprimer definitivement la campagne "${campaign.name}" ?`,
|
||||
details,
|
||||
confirmLabel: 'Supprimer',
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
this.campaignService.deleteCampaign(campaign.id!).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns']),
|
||||
error: () => console.error('Erreur lors de la suppression de la campagne')
|
||||
});
|
||||
});
|
||||
},
|
||||
error: () => console.error('Impossible de récupérer les dépendances de la campagne')
|
||||
|
||||
@@ -7,9 +7,8 @@ import { LucideAngularModule } from 'lucide-angular';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||
import { Campaign } from '../../../services/campaign.model';
|
||||
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||
import { LayoutService } from '../../../services/layout.service';
|
||||
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
|
||||
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
|
||||
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
|
||||
@@ -65,21 +64,7 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
|
||||
this.arcName = currentArc?.name ?? '';
|
||||
this.existingChapterCount = treeData.chaptersByArc[this.arcId]?.length ?? 0;
|
||||
|
||||
const globalItems: GlobalItem[] = allCampaigns.map((c: Campaign) => ({
|
||||
id: c.id!, name: c.name, route: `/campaigns/${c.id}`
|
||||
}));
|
||||
|
||||
this.layoutService.show({
|
||||
title: campaign.name,
|
||||
items: buildCampaignTree(this.campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${this.campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackRoute: '/campaigns'
|
||||
});
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -102,6 +87,9 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.layoutService.hide();
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,16 +9,17 @@ import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { PageService } from '../../../services/page.service';
|
||||
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||
import { LayoutService } from '../../../services/layout.service';
|
||||
import { PageTitleService } from '../../../services/page-title.service';
|
||||
import { Campaign, Chapter } from '../../../services/campaign.model';
|
||||
import { Chapter } from '../../../services/campaign.model';
|
||||
import { Page } from '../../../services/page.model';
|
||||
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
|
||||
import { LoreLinkPickerComponent } from '../../../shared/lore-link-picker/lore-link-picker.component';
|
||||
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
||||
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
||||
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
|
||||
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
|
||||
/**
|
||||
* Écran de détail/modification d'un Chapitre.
|
||||
@@ -71,7 +72,8 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
private npcService: NpcService,
|
||||
private pageService: PageService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
) {
|
||||
this.form = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
@@ -130,21 +132,7 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
narrativeStakes: chapter.narrativeStakes ?? ''
|
||||
});
|
||||
|
||||
const globalItems: GlobalItem[] = allCampaigns.map((c: Campaign) => ({
|
||||
id: c.id!, name: c.name, route: `/campaigns/${c.id}`
|
||||
}));
|
||||
|
||||
this.layoutService.show({
|
||||
title: campaign.name,
|
||||
items: buildCampaignTree(this.campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${this.campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackRoute: '/campaigns'
|
||||
});
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -169,10 +157,18 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
delete(): void {
|
||||
if (!confirm(`Supprimer le chapitre "${this.chapter?.name}" ? Cette action est irréversible.`)) return;
|
||||
this.campaignService.deleteChapter(this.chapterId).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId]),
|
||||
error: () => console.error('Erreur lors de la suppression')
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer le chapitre',
|
||||
message: `Supprimer le chapitre "${this.chapter?.name}" ?`,
|
||||
details: ['Cette action est irréversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
this.campaignService.deleteChapter(this.chapterId).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId]),
|
||||
error: () => console.error('Erreur lors de la suppression')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -181,6 +177,9 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.layoutService.hide();
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -371,6 +371,9 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.layoutService.hide();
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,13 @@ import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { PageService } from '../../../services/page.service';
|
||||
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||
import { LayoutService } from '../../../services/layout.service';
|
||||
import { PageTitleService } from '../../../services/page-title.service';
|
||||
import { Campaign, Chapter } from '../../../services/campaign.model';
|
||||
import { Chapter } from '../../../services/campaign.model';
|
||||
import { Page } from '../../../services/page.model';
|
||||
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
|
||||
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
|
||||
/**
|
||||
* Écran de consultation d'un Chapitre (lecture seule).
|
||||
@@ -49,7 +50,8 @@ export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
private npcService: NpcService,
|
||||
private pageService: PageService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -86,20 +88,7 @@ export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
this.availablePages = pages;
|
||||
this.pageTitleService.set(chapter.name);
|
||||
|
||||
const globalItems: GlobalItem[] = allCampaigns.map((c: Campaign) => ({
|
||||
id: c.id!, name: c.name, route: `/campaigns/${c.id}`
|
||||
}));
|
||||
this.layoutService.show({
|
||||
title: campaign.name,
|
||||
items: buildCampaignTree(this.campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${this.campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackRoute: '/campaigns'
|
||||
});
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -128,18 +117,24 @@ export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
const chapter = this.chapter;
|
||||
this.campaignService.getChapterDeletionImpact(chapter.id!).subscribe({
|
||||
next: impact => {
|
||||
const lines = [`Supprimer le chapitre "${chapter.name}" ?`];
|
||||
const details: string[] = [];
|
||||
if (impact.scenes > 0) {
|
||||
lines.push('');
|
||||
lines.push(`Cette action supprimera aussi : ${impact.scenes} scène${impact.scenes > 1 ? 's' : ''}.`);
|
||||
details.push(`Cette action supprimera aussi : ${impact.scenes} scène${impact.scenes > 1 ? 's' : ''}.`);
|
||||
}
|
||||
lines.push('');
|
||||
lines.push('Cette action est irréversible.');
|
||||
details.push('Cette action est irréversible.');
|
||||
|
||||
if (!confirm(lines.join('\n'))) return;
|
||||
this.campaignService.deleteChapter(chapter.id!).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId, 'arcs', this.arcId]),
|
||||
error: () => console.error('Erreur lors de la suppression du chapitre')
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer le chapitre',
|
||||
message: `Supprimer le chapitre "${chapter.name}" ?`,
|
||||
details,
|
||||
confirmLabel: 'Supprimer',
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
this.campaignService.deleteChapter(chapter.id!).subscribe({
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId, 'arcs', this.arcId]),
|
||||
error: () => console.error('Erreur lors de la suppression du chapitre')
|
||||
});
|
||||
});
|
||||
},
|
||||
error: () => console.error('Impossible de récupérer les dépendances du chapitre')
|
||||
@@ -147,6 +142,9 @@ export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.layoutService.hide();
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,8 +26,9 @@
|
||||
<div class="ce-form">
|
||||
|
||||
<div class="field">
|
||||
<label>Nom du personnage *</label>
|
||||
<label for="character-name">Nom du personnage *</label>
|
||||
<input
|
||||
id="character-name"
|
||||
type="text"
|
||||
[(ngModel)]="name"
|
||||
name="name"
|
||||
@@ -35,18 +36,37 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field content-field">
|
||||
<label>Fiche (markdown)</label>
|
||||
<p class="hint">
|
||||
Tout en markdown libre : stats, classe, backstory, équipement, objectifs personnels…
|
||||
L'IA lira ces infos pour rester cohérente quand vous générez des scènes impliquant ce PJ.
|
||||
</p>
|
||||
<textarea
|
||||
[(ngModel)]="markdownContent"
|
||||
name="markdownContent"
|
||||
rows="22"
|
||||
placeholder="# Thorin Grand-Hache **Race :** Nain **Classe :** Guerrier niveau 4 **PV :** 35 / 35 ## Stats - Force : 16 - Dextérité : 12 ... ## Backstory Originaire des montagnes du Nord, Thorin a fui son clan après..."
|
||||
></textarea>
|
||||
<div class="field-row image-row">
|
||||
<div class="field portrait-field">
|
||||
<label>Portrait</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="portraitImageId"
|
||||
aspectRatio="1 / 1"
|
||||
hint="Carre conseille (400×400)."
|
||||
(imageIdChange)="portraitImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
<div class="field header-field">
|
||||
<label>Bandeau / Header</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="headerImageId"
|
||||
aspectRatio="3 / 1"
|
||||
hint="Format paysage conseille (1200×400)."
|
||||
(imageIdChange)="headerImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="template-fields">
|
||||
<app-dynamic-fields-form
|
||||
[fields]="templateFields"
|
||||
[values]="values"
|
||||
[imageValues]="imageValues"
|
||||
[keyValueValues]="keyValueValues"
|
||||
(valuesChange)="values = $event"
|
||||
(imageValuesChange)="imageValues = $event"
|
||||
(keyValueValuesChange)="keyValueValues = $event">
|
||||
</app-dynamic-fields-form>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
|
||||
@@ -4,22 +4,30 @@ import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, Save, ArrowLeft, User, Trash2, Sparkles } from 'lucide-angular';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { Character } from '../../../services/character.model';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { TemplateField } from '../../../services/template.model';
|
||||
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
||||
import { DynamicFieldsFormComponent } from '../../../shared/dynamic-fields-form/dynamic-fields-form.component';
|
||||
import { SingleImagePickerComponent } from '../../../shared/single-image-picker/single-image-picker.component';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
|
||||
/**
|
||||
* Éditeur plein écran d'une fiche de personnage (PJ).
|
||||
* Double rôle création/édition :
|
||||
* - `/campaigns/:campaignId/characters/create` → POST
|
||||
* - `/campaigns/:campaignId/characters/:characterId/edit` → PUT
|
||||
* Editeur plein ecran d'une fiche de personnage (PJ).
|
||||
* Refonte 2026-04-30 : remplace le markdown libre par un formulaire dynamique
|
||||
* pilote par le characterTemplate du GameSystem associe a la campagne.
|
||||
*
|
||||
* MVP : name + markdown libre. Évolution prévue vers un template dérivé
|
||||
* du GameSystem de la campagne (stats structurées).
|
||||
* Comportements :
|
||||
* - Si la campagne n'a pas de GameSystem ou si son template est vide, affiche
|
||||
* uniquement les champs universels (nom, portrait, header).
|
||||
* - Le picker d'images dedie portrait/header est hors scope MVP — pour l'instant
|
||||
* saisie manuelle d'IDs d'images.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-character-edit',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, LucideAngularModule, AiChatDrawerComponent],
|
||||
imports: [CommonModule, FormsModule, LucideAngularModule, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent],
|
||||
templateUrl: './character-edit.component.html',
|
||||
styleUrls: ['./character-edit.component.scss']
|
||||
})
|
||||
@@ -30,12 +38,11 @@ export class CharacterEditComponent implements OnInit {
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Sparkles = Sparkles;
|
||||
|
||||
/** État drawer chat IA focalisé sur ce PJ. */
|
||||
chatOpen = false;
|
||||
readonly chatQuickSuggestions = [
|
||||
'Propose une backstory cohérente avec l\'univers',
|
||||
'Suggère 3 objectifs personnels pour ce personnage',
|
||||
'Aide-moi à équilibrer les stats de combat'
|
||||
'Propose une backstory coherente avec l\'univers',
|
||||
'Suggere 3 objectifs personnels pour ce personnage',
|
||||
'Aide-moi a equilibrer les stats de combat'
|
||||
];
|
||||
|
||||
toggleChat(): void { this.chatOpen = !this.chatOpen; }
|
||||
@@ -44,13 +51,22 @@ export class CharacterEditComponent implements OnInit {
|
||||
characterId: string | null = null;
|
||||
|
||||
name = '';
|
||||
markdownContent = '';
|
||||
portraitImageId: string | null = null;
|
||||
headerImageId: string | null = null;
|
||||
values: Record<string, string> = {};
|
||||
imageValues: Record<string, string[]> = {};
|
||||
keyValueValues: Record<string, Record<string, string>> = {};
|
||||
templateFields: TemplateField[] = [];
|
||||
private order = 0;
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private service: CharacterService
|
||||
private service: CharacterService,
|
||||
private campaignService: CampaignService,
|
||||
private gameSystemService: GameSystemService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -58,11 +74,20 @@ export class CharacterEditComponent implements OnInit {
|
||||
this.campaignId = params.get('campaignId');
|
||||
this.characterId = params.get('characterId');
|
||||
|
||||
if (this.campaignId) {
|
||||
this.loadTemplateForCampaign(this.campaignId);
|
||||
this.campaignSidebar.show(this.campaignId);
|
||||
}
|
||||
|
||||
if (this.characterId) {
|
||||
this.service.getById(this.characterId).subscribe({
|
||||
next: (c) => {
|
||||
this.name = c.name;
|
||||
this.markdownContent = c.markdownContent ?? '';
|
||||
this.portraitImageId = c.portraitImageId ?? null;
|
||||
this.headerImageId = c.headerImageId ?? null;
|
||||
this.values = c.values ?? {};
|
||||
this.imageValues = c.imageValues ?? {};
|
||||
this.keyValueValues = c.keyValueValues ?? {};
|
||||
this.order = c.order ?? 0;
|
||||
},
|
||||
error: () => this.back()
|
||||
@@ -70,33 +95,64 @@ export class CharacterEditComponent implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
private loadTemplateForCampaign(campaignId: string): void {
|
||||
this.campaignService.getCampaignById(campaignId).subscribe({
|
||||
next: (campaign) => {
|
||||
if (!campaign.gameSystemId) {
|
||||
this.templateFields = [];
|
||||
return;
|
||||
}
|
||||
this.gameSystemService.getById(campaign.gameSystemId).subscribe({
|
||||
next: (gs) => { this.templateFields = gs.characterTemplate ?? []; },
|
||||
error: () => { this.templateFields = []; }
|
||||
});
|
||||
},
|
||||
error: () => { this.templateFields = []; }
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
submit(): void {
|
||||
if (!this.name.trim() || !this.campaignId) return;
|
||||
const payload = {
|
||||
name: this.name.trim(),
|
||||
portraitImageId: this.portraitImageId,
|
||||
headerImageId: this.headerImageId,
|
||||
values: this.values,
|
||||
imageValues: this.imageValues,
|
||||
keyValueValues: this.keyValueValues,
|
||||
campaignId: this.campaignId
|
||||
};
|
||||
const isCreation = !this.characterId;
|
||||
const req = this.characterId
|
||||
? this.service.update(this.characterId, {
|
||||
id: this.characterId,
|
||||
name: this.name.trim(),
|
||||
markdownContent: this.markdownContent || null,
|
||||
campaignId: this.campaignId,
|
||||
order: this.order
|
||||
})
|
||||
: this.service.create({
|
||||
name: this.name.trim(),
|
||||
markdownContent: this.markdownContent || null,
|
||||
campaignId: this.campaignId
|
||||
});
|
||||
? this.service.update(this.characterId, { ...payload, id: this.characterId, order: this.order })
|
||||
: this.service.create(payload);
|
||||
req.subscribe({
|
||||
next: () => this.back(),
|
||||
next: (saved) => {
|
||||
if (isCreation && saved.id) {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'characters', saved.id]);
|
||||
} else {
|
||||
this.back();
|
||||
}
|
||||
},
|
||||
error: () => console.error('Erreur sauvegarde Character')
|
||||
});
|
||||
}
|
||||
|
||||
deleteCharacter(): void {
|
||||
if (!this.characterId) return;
|
||||
if (!confirm(`Supprimer la fiche de "${this.name}" ? Cette action est irréversible.`)) return;
|
||||
this.service.delete(this.characterId).subscribe({
|
||||
next: () => this.back(),
|
||||
error: () => console.error('Erreur suppression Character')
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer la fiche ?',
|
||||
message: `Supprimer la fiche de "${this.name}" ?`,
|
||||
details: ['Cette action est irreversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok || !this.characterId) return;
|
||||
this.service.delete(this.characterId).subscribe({
|
||||
next: () => this.back(),
|
||||
error: () => console.error('Erreur suppression Character')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<div class="cv-page">
|
||||
<div class="cv-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-ai" (click)="toggleChat()" [class.active]="chatOpen" *ngIf="characterId">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
</button>
|
||||
<button class="btn-edit" (click)="edit()">
|
||||
<lucide-icon [img]="Edit3" [size]="14"></lucide-icon>
|
||||
Editer
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<app-persona-view [persona]="character" [templateFields]="templateFields"></app-persona-view>
|
||||
</div>
|
||||
|
||||
<app-ai-chat-drawer
|
||||
*ngIf="characterId && campaignId"
|
||||
[campaignId]="campaignId"
|
||||
entityType="character"
|
||||
[entityId]="characterId"
|
||||
[isOpen]="chatOpen"
|
||||
(close)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
@@ -0,0 +1,53 @@
|
||||
.cv-page {
|
||||
padding: 16px 0 48px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.cv-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 0 32px 16px;
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
|
||||
.spacer { flex: 1; }
|
||||
}
|
||||
|
||||
.btn-back,
|
||||
.btn-edit,
|
||||
.btn-ai {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 12px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 4px;
|
||||
color: #d1d5db;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
transition: all 120ms;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
|
||||
.btn-edit {
|
||||
border-color: rgba(209, 168, 120, 0.4);
|
||||
color: #d1a878;
|
||||
|
||||
&:hover {
|
||||
background: rgba(209, 168, 120, 0.15);
|
||||
}
|
||||
}
|
||||
|
||||
.btn-ai {
|
||||
&.active {
|
||||
background: rgba(168, 85, 247, 0.2);
|
||||
border-color: rgba(168, 85, 247, 0.5);
|
||||
color: #d8b4fe;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LucideAngularModule, ArrowLeft, Edit3, Sparkles } from 'lucide-angular';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { TemplateField } from '../../../services/template.model';
|
||||
import { Character } from '../../../services/character.model';
|
||||
import { PersonaViewComponent } from '../../../shared/persona-view/persona-view.component';
|
||||
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
||||
|
||||
/**
|
||||
* Vue lecture seule "WorldAnvil" d'une fiche PJ.
|
||||
* Route : /campaigns/:campaignId/characters/:characterId
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-character-view',
|
||||
standalone: true,
|
||||
imports: [CommonModule, LucideAngularModule, PersonaViewComponent, AiChatDrawerComponent],
|
||||
templateUrl: './character-view.component.html',
|
||||
styleUrls: ['./character-view.component.scss']
|
||||
})
|
||||
export class CharacterViewComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly Edit3 = Edit3;
|
||||
readonly Sparkles = Sparkles;
|
||||
|
||||
campaignId: string | null = null;
|
||||
characterId: string | null = null;
|
||||
|
||||
character: Character | null = null;
|
||||
templateFields: TemplateField[] = [];
|
||||
|
||||
chatOpen = false;
|
||||
toggleChat(): void { this.chatOpen = !this.chatOpen; }
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private service: CharacterService,
|
||||
private campaignService: CampaignService,
|
||||
private gameSystemService: GameSystemService,
|
||||
private campaignSidebar: CampaignSidebarService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
const params = this.route.snapshot.paramMap;
|
||||
this.campaignId = params.get('campaignId');
|
||||
this.characterId = params.get('characterId');
|
||||
if (this.characterId) {
|
||||
this.service.getById(this.characterId).subscribe({
|
||||
next: c => { this.character = c; },
|
||||
error: () => this.back()
|
||||
});
|
||||
}
|
||||
if (this.campaignId) {
|
||||
this.campaignSidebar.show(this.campaignId);
|
||||
this.campaignService.getCampaignById(this.campaignId).subscribe(camp => {
|
||||
if (camp.gameSystemId) {
|
||||
this.gameSystemService.getById(camp.gameSystemId).subscribe(gs => {
|
||||
this.templateFields = gs.characterTemplate ?? [];
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
edit(): void {
|
||||
if (this.campaignId && this.characterId) {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'characters', this.characterId, 'edit']);
|
||||
}
|
||||
}
|
||||
|
||||
back(): void {
|
||||
if (this.campaignId) {
|
||||
this.router.navigate(['/campaigns', this.campaignId]);
|
||||
} else {
|
||||
this.router.navigate(['/campaigns']);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,9 @@
|
||||
<div class="ne-form">
|
||||
|
||||
<div class="field">
|
||||
<label>Nom du PNJ *</label>
|
||||
<label for="npc-name">Nom du PNJ *</label>
|
||||
<input
|
||||
id="npc-name"
|
||||
type="text"
|
||||
[(ngModel)]="name"
|
||||
name="name"
|
||||
@@ -35,18 +36,37 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field content-field">
|
||||
<label>Fiche (markdown)</label>
|
||||
<p class="hint">
|
||||
Tout en markdown libre : apparence, motivations, faction, secrets, stats, notes MJ…
|
||||
À terme, l'IA pourra exploiter ces infos pour incarner le PNJ avec cohérence dans les scènes.
|
||||
</p>
|
||||
<textarea
|
||||
[(ngModel)]="markdownContent"
|
||||
name="markdownContent"
|
||||
rows="22"
|
||||
placeholder="# Borin le forgeron **Race :** Nain **Faction :** Clan Feuillefer **Statut :** Vivant ## Apparence Barbe rousse tressée, tablier de cuir brûlé... ## Motivations Venger son clan décimé par les orcs il y a 10 hivers. ## Notes MJ (secret) Connaît l'emplacement du marteau de Durin..."
|
||||
></textarea>
|
||||
<div class="field-row image-row">
|
||||
<div class="field portrait-field">
|
||||
<label>Portrait</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="portraitImageId"
|
||||
aspectRatio="1 / 1"
|
||||
hint="Carre conseille (400×400)."
|
||||
(imageIdChange)="portraitImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
<div class="field header-field">
|
||||
<label>Bandeau / Header</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="headerImageId"
|
||||
aspectRatio="3 / 1"
|
||||
hint="Format paysage conseille (1200×400)."
|
||||
(imageIdChange)="headerImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="template-fields">
|
||||
<app-dynamic-fields-form
|
||||
[fields]="templateFields"
|
||||
[values]="values"
|
||||
[imageValues]="imageValues"
|
||||
[keyValueValues]="keyValueValues"
|
||||
(valuesChange)="values = $event"
|
||||
(imageValuesChange)="imageValues = $event"
|
||||
(keyValueValuesChange)="keyValueValues = $event">
|
||||
</app-dynamic-fields-form>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user