Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e3c8232e38 | |||
| a4df9fc759 | |||
| f1989c1d77 | |||
| 8efdf5d0e0 | |||
| 96bc5de942 | |||
| 84ccdd53ad | |||
| 29978058ee | |||
| e510f64336 | |||
| f189f67aaf | |||
| 8efa148739 | |||
| 8f4dd3e9d6 | |||
| bf38b6695f | |||
| 49a82d05f7 |
@@ -20,6 +20,8 @@ from app.domain.models import (
|
|||||||
CampaignStructuralContext,
|
CampaignStructuralContext,
|
||||||
ChatMessage,
|
ChatMessage,
|
||||||
ChapterSummary,
|
ChapterSummary,
|
||||||
|
CharacterSummary,
|
||||||
|
GameSystemContext,
|
||||||
LoreStructuralContext,
|
LoreStructuralContext,
|
||||||
NarrativeEntityContext,
|
NarrativeEntityContext,
|
||||||
PageContext,
|
PageContext,
|
||||||
@@ -63,16 +65,17 @@ class ChatUseCase:
|
|||||||
page_context: PageContext | None = None,
|
page_context: PageContext | None = None,
|
||||||
campaign_context: CampaignStructuralContext | None = None,
|
campaign_context: CampaignStructuralContext | None = None,
|
||||||
narrative_entity: NarrativeEntityContext | None = None,
|
narrative_entity: NarrativeEntityContext | None = None,
|
||||||
|
game_system_context: GameSystemContext | None = None,
|
||||||
) -> AsyncIterator[str]:
|
) -> AsyncIterator[str]:
|
||||||
"""Streame les tokens de la réponse assistant pour le dernier message user.
|
"""Streame les tokens de la réponse assistant pour le dernier message user.
|
||||||
|
|
||||||
Les 4 contextes sont tous optionnels, mais au moins l'un des deux
|
Les contextes sont tous optionnels, mais au moins l'un des deux
|
||||||
"niveaux haut" (lore_context ou campaign_context) doit être fourni
|
"niveaux haut" (lore_context ou campaign_context) doit être fourni
|
||||||
pour que le prompt ait du sens. Le controller (main.py) applique
|
pour que le prompt ait du sens. Le controller (main.py) applique
|
||||||
cette règle à la frontière HTTP.
|
cette règle à la frontière HTTP.
|
||||||
"""
|
"""
|
||||||
system_prompt = self._build_system_prompt(
|
system_prompt = self._build_system_prompt(
|
||||||
lore_context, page_context, campaign_context, narrative_entity
|
lore_context, page_context, campaign_context, narrative_entity, game_system_context
|
||||||
)
|
)
|
||||||
async for token in self._llm.stream_chat(
|
async for token in self._llm.stream_chat(
|
||||||
messages,
|
messages,
|
||||||
@@ -81,6 +84,21 @@ class ChatUseCase:
|
|||||||
):
|
):
|
||||||
yield token
|
yield token
|
||||||
|
|
||||||
|
def build_system_prompt(
|
||||||
|
self,
|
||||||
|
lore_context: LoreStructuralContext | None = None,
|
||||||
|
page_context: PageContext | None = None,
|
||||||
|
campaign_context: CampaignStructuralContext | None = None,
|
||||||
|
narrative_entity: NarrativeEntityContext | None = None,
|
||||||
|
game_system_context: GameSystemContext | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Version publique — utilisée par le controller HTTP pour compter
|
||||||
|
les tokens du system prompt avant de streamer (jauge de contexte).
|
||||||
|
"""
|
||||||
|
return self._build_system_prompt(
|
||||||
|
lore_context, page_context, campaign_context, narrative_entity, game_system_context
|
||||||
|
)
|
||||||
|
|
||||||
# --- Construction du system prompt --------------------------------------
|
# --- Construction du system prompt --------------------------------------
|
||||||
|
|
||||||
def _build_system_prompt(
|
def _build_system_prompt(
|
||||||
@@ -89,12 +107,15 @@ class ChatUseCase:
|
|||||||
page: PageContext | None,
|
page: PageContext | None,
|
||||||
campaign: CampaignStructuralContext | None,
|
campaign: CampaignStructuralContext | None,
|
||||||
narrative: NarrativeEntityContext | None,
|
narrative: NarrativeEntityContext | None,
|
||||||
|
game_system: GameSystemContext | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
sections = [_BASE_SYSTEM]
|
sections = [_BASE_SYSTEM]
|
||||||
if lore is not None:
|
if lore is not None:
|
||||||
sections.append(self._format_lore(lore))
|
sections.append(self._format_lore(lore))
|
||||||
if campaign is not None:
|
if campaign is not None:
|
||||||
sections.append(self._format_campaign(campaign, lore_present=lore is not None))
|
sections.append(self._format_campaign(campaign, lore_present=lore is not None))
|
||||||
|
if game_system is not None:
|
||||||
|
sections.append(self._format_game_system(game_system))
|
||||||
if page is not None:
|
if page is not None:
|
||||||
sections.append(self._format_page(page))
|
sections.append(self._format_page(page))
|
||||||
if narrative is not None:
|
if narrative is not None:
|
||||||
@@ -176,14 +197,40 @@ class ChatUseCase:
|
|||||||
if lore_present
|
if lore_present
|
||||||
else "\n(Cette campagne n'est associée à aucun univers — tu peux proposer des éléments d'ambiance libres.)"
|
else "\n(Cette campagne n'est associée à aucun univers — tu peux proposer des éléments d'ambiance libres.)"
|
||||||
)
|
)
|
||||||
|
characters_block = ChatUseCase._format_characters(ctx.characters)
|
||||||
return (
|
return (
|
||||||
"--- CAMPAGNE COURANTE ---\n"
|
"--- CAMPAGNE COURANTE ---\n"
|
||||||
f"Nom : {ctx.campaign_name}{desc}{lore_note}\n\n"
|
f"Nom : {ctx.campaign_name}{desc}{lore_note}\n"
|
||||||
|
f"{characters_block}\n"
|
||||||
"Structure narrative (les flèches → indiquent des transitions de scène "
|
"Structure narrative (les flèches → indiquent des transitions de scène "
|
||||||
"déclenchées par un choix des joueurs) :\n"
|
"déclenchées par un choix des joueurs) :\n"
|
||||||
f"{arcs_block}"
|
f"{arcs_block}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _format_characters(characters: list[CharacterSummary]) -> str:
|
||||||
|
"""Bloc PJ — liste nom + snippet. Rappel anti-hallucination IA.
|
||||||
|
|
||||||
|
Si la campagne n'a aucun PJ, on le signale explicitement : l'IA ne
|
||||||
|
doit pas inventer "les héros" ou leurs noms dans ses suggestions.
|
||||||
|
"""
|
||||||
|
if not characters:
|
||||||
|
return (
|
||||||
|
"\nPersonnages joueurs : aucune fiche pour l'instant. Ne suppose "
|
||||||
|
"ni noms ni classes pour les PJ tant que le MJ ne les a pas créés.\n"
|
||||||
|
)
|
||||||
|
lines = ["\nPersonnages joueurs (PJ) :"]
|
||||||
|
for c in characters:
|
||||||
|
if c.snippet:
|
||||||
|
lines.append(f"- **{c.name}** — {c.snippet}")
|
||||||
|
else:
|
||||||
|
lines.append(f"- **{c.name}** (fiche vide)")
|
||||||
|
lines.append(
|
||||||
|
"Pour une fiche complète (stats, backstory), n'invente rien : "
|
||||||
|
"demande au MJ d'ouvrir l'éditeur du PJ pour te donner les détails."
|
||||||
|
)
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _format_arcs(arcs: list[ArcSummary]) -> str:
|
def _format_arcs(arcs: list[ArcSummary]) -> str:
|
||||||
if not arcs:
|
if not arcs:
|
||||||
@@ -234,12 +281,46 @@ class ChatUseCase:
|
|||||||
noun = "illustration" if count == 1 else "illustrations"
|
noun = "illustration" if count == 1 else "illustrations"
|
||||||
return f" [{count} {noun}]"
|
return f" [{count} {noun}]"
|
||||||
|
|
||||||
|
# --- Bloc Système de JDR ------------------------------------------------
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _format_game_system(gs: GameSystemContext) -> str:
|
||||||
|
"""Bloc des règles du système de JDR de la campagne.
|
||||||
|
|
||||||
|
Les sections ont été filtrées côté Core selon l'intent (combat,
|
||||||
|
classes, lore...). Si aucune section n'a matché, on affiche juste
|
||||||
|
le nom du système comme rappel de cadre.
|
||||||
|
"""
|
||||||
|
desc = f"\nDescription : {gs.system_description}" if gs.system_description else ""
|
||||||
|
if not gs.sections:
|
||||||
|
return (
|
||||||
|
"--- SYSTÈME DE JDR ---\n"
|
||||||
|
f"Nom : {gs.system_name}{desc}\n"
|
||||||
|
"(Aucune section de règles pertinente pour ce type de génération — "
|
||||||
|
"reste cohérent avec l'univers et les conventions du système.)"
|
||||||
|
)
|
||||||
|
sections_block = "\n\n".join(
|
||||||
|
f"### {title}\n{content}" for title, content in gs.sections.items()
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
"--- SYSTÈME DE JDR ---\n"
|
||||||
|
f"Nom : {gs.system_name}{desc}\n\n"
|
||||||
|
"Respecte scrupuleusement les règles et conventions ci-dessous quand "
|
||||||
|
"tu proposes des stats, classes, rencontres, mécaniques ou éléments "
|
||||||
|
"d'ambiance. Les noms propres (classes, sorts, monstres) doivent "
|
||||||
|
"venir de ces règles — n'en invente pas d'autres.\n\n"
|
||||||
|
f"{sections_block}"
|
||||||
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _format_narrative_entity(ne: NarrativeEntityContext) -> str:
|
def _format_narrative_entity(ne: NarrativeEntityContext) -> str:
|
||||||
"""Bloc équivalent à _format_page mais pour Arc/Chapter/Scene."""
|
"""Bloc équivalent à _format_page mais pour Arc/Chapter/Scene."""
|
||||||
type_label = {"arc": "ARC", "chapter": "CHAPITRE", "scene": "SCÈNE"}.get(
|
type_label = {
|
||||||
ne.entity_type.lower(), ne.entity_type.upper()
|
"arc": "ARC",
|
||||||
)
|
"chapter": "CHAPITRE",
|
||||||
|
"scene": "SCÈNE",
|
||||||
|
"character": "FICHE DE PERSONNAGE",
|
||||||
|
}.get(ne.entity_type.lower(), ne.entity_type.upper())
|
||||||
if ne.fields:
|
if ne.fields:
|
||||||
fields_block = "\n".join(
|
fields_block = "\n".join(
|
||||||
f'- "{key}" : {value or "(vide)"}'
|
f'- "{key}" : {value or "(vide)"}'
|
||||||
|
|||||||
@@ -169,6 +169,20 @@ class CampaignStructuralContext:
|
|||||||
campaign_name: str
|
campaign_name: str
|
||||||
campaign_description: str | None
|
campaign_description: str | None
|
||||||
arcs: list[ArcSummary]
|
arcs: list[ArcSummary]
|
||||||
|
characters: list["CharacterSummary"] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CharacterSummary:
|
||||||
|
"""Résumé d'un PJ : nom + snippet court extrait du markdown de la fiche.
|
||||||
|
|
||||||
|
La fiche complète n'est JAMAIS dans ce résumé — elle n'arrive que si le PJ
|
||||||
|
est l'entité focus (via NarrativeEntityContext entity_type="character").
|
||||||
|
Ça plafonne le coût token à ~40 tokens/PJ quel que soit le détail des fiches.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
snippet: str
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -184,3 +198,20 @@ class NarrativeEntityContext:
|
|||||||
entity_type: str
|
entity_type: str
|
||||||
title: str
|
title: str
|
||||||
fields: dict[str, str]
|
fields: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class GameSystemContext:
|
||||||
|
"""Règles d'un système de JDR (D&D, Nimble, homebrew...) injectées
|
||||||
|
dans le system prompt pour que l'IA respecte les mécaniques du jeu.
|
||||||
|
|
||||||
|
Les sections ont été présélectionnées côté Core selon l'intent
|
||||||
|
(SCENE → combat/PNJ, CHAPTER → combat/classes, ARC → lore/factions,
|
||||||
|
GENERIC → toutes). Indexées par titre H2 original.
|
||||||
|
|
||||||
|
Campagne uniquement au MVP : jamais présent sur un chat Lore.
|
||||||
|
"""
|
||||||
|
|
||||||
|
system_name: str
|
||||||
|
system_description: str | None
|
||||||
|
sections: dict[str, str]
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from typing import Annotated, AsyncIterator, Literal
|
|||||||
|
|
||||||
import hmac
|
import hmac
|
||||||
import httpx
|
import httpx
|
||||||
|
import tiktoken
|
||||||
from fastapi import Depends, FastAPI, HTTPException, Request
|
from fastapi import Depends, FastAPI, HTTPException, Request
|
||||||
from fastapi.responses import JSONResponse, StreamingResponse
|
from fastapi.responses import JSONResponse, StreamingResponse
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
@@ -21,7 +22,9 @@ from app.domain.models import (
|
|||||||
ArcSummary,
|
ArcSummary,
|
||||||
CampaignStructuralContext,
|
CampaignStructuralContext,
|
||||||
ChapterSummary,
|
ChapterSummary,
|
||||||
|
CharacterSummary,
|
||||||
ChatMessage,
|
ChatMessage,
|
||||||
|
GameSystemContext,
|
||||||
LoreStructuralContext,
|
LoreStructuralContext,
|
||||||
NarrativeEntityContext,
|
NarrativeEntityContext,
|
||||||
PageContext,
|
PageContext,
|
||||||
@@ -37,10 +40,27 @@ from app.infrastructure.onemin_adapter import OneMinAiLLMProvider
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LoreMind Brain",
|
title="LoreMind Brain",
|
||||||
description="Backend IA pour la génération de contenu narratif.",
|
description="Backend IA pour la génération de contenu narratif.",
|
||||||
version="0.3.0",
|
version="0.6.1",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Encodeur tiktoken partagé — chargé une fois pour éviter le coût de lookup
|
||||||
|
# à chaque requête. On utilise cl100k_base (GPT-3.5/4) comme tokenizer
|
||||||
|
# universel approximatif : ±10% d'écart avec Llama/Gemma mais largement
|
||||||
|
# suffisant pour une jauge visuelle à l'utilisateur.
|
||||||
|
_TOKEN_ENCODER: tiktoken.Encoding | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _count_tokens(text: str | None) -> int:
|
||||||
|
"""Compte les tokens d'un texte via tiktoken. Null/empty → 0."""
|
||||||
|
if not text:
|
||||||
|
return 0
|
||||||
|
global _TOKEN_ENCODER
|
||||||
|
if _TOKEN_ENCODER is None:
|
||||||
|
_TOKEN_ENCODER = tiktoken.get_encoding("cl100k_base")
|
||||||
|
return len(_TOKEN_ENCODER.encode(text))
|
||||||
|
|
||||||
|
|
||||||
# Chemins exemptes d'auth inter-service : healthcheck docker + introspection
|
# Chemins exemptes d'auth inter-service : healthcheck docker + introspection
|
||||||
# FastAPI (docs uniquement utiles en dev ; en prod docker-compose, le Brain
|
# FastAPI (docs uniquement utiles en dev ; en prod docker-compose, le Brain
|
||||||
# n'est pas expose en dehors du reseau interne donc pas un risque).
|
# n'est pas expose en dehors du reseau interne donc pas un risque).
|
||||||
@@ -178,22 +198,42 @@ class ArcSummaryDTO(BaseModel):
|
|||||||
illustration_count: int = 0
|
illustration_count: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
class CharacterSummaryDTO(BaseModel):
|
||||||
|
"""Résumé d'un PJ : nom + snippet. Pas de fiche complète au niveau résumé."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
snippet: str = ""
|
||||||
|
|
||||||
|
|
||||||
class CampaignContextDTO(BaseModel):
|
class CampaignContextDTO(BaseModel):
|
||||||
"""Carte narrative enrichie : arcs → chapitres → scènes avec synopsis."""
|
"""Carte narrative enrichie : arcs → chapitres → scènes avec synopsis."""
|
||||||
|
|
||||||
campaign_name: str
|
campaign_name: str
|
||||||
campaign_description: str | None = None
|
campaign_description: str | None = None
|
||||||
arcs: list[ArcSummaryDTO] = Field(default_factory=list)
|
arcs: list[ArcSummaryDTO] = Field(default_factory=list)
|
||||||
|
characters: list[CharacterSummaryDTO] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
class NarrativeEntityDTO(BaseModel):
|
class NarrativeEntityDTO(BaseModel):
|
||||||
"""Entité narrative (arc/chapter/scene) en cours d'édition — focus optionnel."""
|
"""Entité narrative (arc/chapter/scene/character) en cours d'édition — focus optionnel."""
|
||||||
|
|
||||||
entity_type: str = Field(pattern="^(arc|chapter|scene)$")
|
entity_type: str = Field(pattern="^(arc|chapter|scene|character)$")
|
||||||
title: str
|
title: str
|
||||||
fields: dict[str, str] = Field(default_factory=dict)
|
fields: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class GameSystemContextDTO(BaseModel):
|
||||||
|
"""Règles de JDR présélectionnées par le Core (filtrées par intent).
|
||||||
|
|
||||||
|
Les sections sont un dict titre_H2 → contenu_markdown. Peuvent être
|
||||||
|
vides si aucune section ne matchait l'intent de génération courant.
|
||||||
|
"""
|
||||||
|
|
||||||
|
system_name: str
|
||||||
|
system_description: str | None = None
|
||||||
|
sections: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
class ChatStreamRequestDTO(BaseModel):
|
class ChatStreamRequestDTO(BaseModel):
|
||||||
"""Requête de chat streamé : historique + contextes structurels.
|
"""Requête de chat streamé : historique + contextes structurels.
|
||||||
|
|
||||||
@@ -208,6 +248,7 @@ class ChatStreamRequestDTO(BaseModel):
|
|||||||
page_context: PageContextDTO | None = None
|
page_context: PageContextDTO | None = None
|
||||||
campaign_context: CampaignContextDTO | None = None
|
campaign_context: CampaignContextDTO | None = None
|
||||||
narrative_entity: NarrativeEntityDTO | None = None
|
narrative_entity: NarrativeEntityDTO | None = None
|
||||||
|
game_system_context: GameSystemContextDTO | None = None
|
||||||
|
|
||||||
def has_scope(self) -> bool:
|
def has_scope(self) -> bool:
|
||||||
"""Vrai si au moins un contexte racine (Lore ou Campagne) est fourni."""
|
"""Vrai si au moins un contexte racine (Lore ou Campagne) est fourni."""
|
||||||
@@ -334,8 +375,35 @@ async def chat_stream(
|
|||||||
page_context = _to_page_context(body.page_context)
|
page_context = _to_page_context(body.page_context)
|
||||||
campaign_context = _to_campaign_context(body.campaign_context)
|
campaign_context = _to_campaign_context(body.campaign_context)
|
||||||
narrative_entity = _to_narrative_entity(body.narrative_entity)
|
narrative_entity = _to_narrative_entity(body.narrative_entity)
|
||||||
|
game_system_context = _to_game_system_context(body.game_system_context)
|
||||||
|
|
||||||
|
# --- Comptage tokens pour la jauge de contexte frontend ---
|
||||||
|
# On construit le system prompt une fois ici pour le compter — le use case
|
||||||
|
# le reconstruira à l'identique en interne (coût négligeable : concat de str).
|
||||||
|
# Cette duplication évite de complexifier le contrat stream() avec un
|
||||||
|
# paramètre optionnel system_prompt précalculé.
|
||||||
|
system_prompt_preview = use_case.build_system_prompt(
|
||||||
|
lore_context=lore_context,
|
||||||
|
page_context=page_context,
|
||||||
|
campaign_context=campaign_context,
|
||||||
|
narrative_entity=narrative_entity,
|
||||||
|
game_system_context=game_system_context,
|
||||||
|
)
|
||||||
|
# Dernier message = "current" (souvent user), le reste = historique accumulé.
|
||||||
|
current_msg = messages[-1] if messages else None
|
||||||
|
history_msgs = messages[:-1] if messages else []
|
||||||
|
settings = get_settings()
|
||||||
|
usage_payload = {
|
||||||
|
"system": _count_tokens(system_prompt_preview),
|
||||||
|
"history": sum(_count_tokens(m.content) for m in history_msgs),
|
||||||
|
"current": _count_tokens(current_msg.content) if current_msg else 0,
|
||||||
|
"max": settings.llm_num_ctx,
|
||||||
|
}
|
||||||
|
|
||||||
async def event_stream() -> AsyncIterator[str]:
|
async def event_stream() -> AsyncIterator[str]:
|
||||||
|
# Event 'usage' émis en tout premier : le frontend peut afficher la
|
||||||
|
# jauge avant même le premier token de réponse.
|
||||||
|
yield f"event: usage\ndata: {json.dumps(usage_payload, ensure_ascii=False)}\n\n"
|
||||||
try:
|
try:
|
||||||
async for token in use_case.stream(
|
async for token in use_case.stream(
|
||||||
messages,
|
messages,
|
||||||
@@ -343,6 +411,7 @@ async def chat_stream(
|
|||||||
page_context=page_context,
|
page_context=page_context,
|
||||||
campaign_context=campaign_context,
|
campaign_context=campaign_context,
|
||||||
narrative_entity=narrative_entity,
|
narrative_entity=narrative_entity,
|
||||||
|
game_system_context=game_system_context,
|
||||||
):
|
):
|
||||||
# json.dumps avec ensure_ascii=False pour préserver les accents
|
# json.dumps avec ensure_ascii=False pour préserver les accents
|
||||||
yield f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
yield f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
||||||
@@ -353,6 +422,60 @@ async def chat_stream(
|
|||||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||||
|
|
||||||
|
|
||||||
|
# --- Auto-titre d'une conversation persistee --------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class SummarizeTitleMessageDTO(BaseModel):
|
||||||
|
role: Literal["user", "assistant", "system"]
|
||||||
|
content: str
|
||||||
|
|
||||||
|
|
||||||
|
class SummarizeTitleRequestDTO(BaseModel):
|
||||||
|
"""Premiers messages d'une conversation pour auto-generer un titre court."""
|
||||||
|
|
||||||
|
messages: list[SummarizeTitleMessageDTO] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class SummarizeTitleResponseDTO(BaseModel):
|
||||||
|
title: str
|
||||||
|
|
||||||
|
|
||||||
|
_TITLE_SYSTEM_PROMPT = (
|
||||||
|
"Tu generes un titre court (4 a 7 mots max) qui resume le sujet de la "
|
||||||
|
"conversation ci-dessous. Reponds UNIQUEMENT par le titre, sans guillemets, "
|
||||||
|
"sans ponctuation finale, sans prefixe type 'Titre :'. Le titre doit etre "
|
||||||
|
"en francais et capturer le sujet metier (pas 'Conversation IA')."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/summarize/conversation-title", response_model=SummarizeTitleResponseDTO)
|
||||||
|
async def summarize_conversation_title(
|
||||||
|
body: SummarizeTitleRequestDTO,
|
||||||
|
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||||
|
) -> SummarizeTitleResponseDTO:
|
||||||
|
"""Genere un titre court a partir des premiers echanges de la conversation.
|
||||||
|
|
||||||
|
Appele par le core apres le 1er couple user/assistant, pour remplacer le
|
||||||
|
titre provisoire "Nouvelle conversation" par quelque chose de parlant.
|
||||||
|
"""
|
||||||
|
if not body.messages:
|
||||||
|
raise HTTPException(status_code=422, detail="Au moins un message requis")
|
||||||
|
|
||||||
|
transcript = "\n".join(f"{m.role.upper()}: {m.content}" for m in body.messages[:6])
|
||||||
|
prompt = f"{_TITLE_SYSTEM_PROMPT}\n\nConversation :\n{transcript}\n\nTitre :"
|
||||||
|
try:
|
||||||
|
raw = await llm.generate(prompt)
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
title = raw.strip().splitlines()[0].strip().strip('"').strip("'").rstrip(".")
|
||||||
|
if len(title) > 80:
|
||||||
|
title = title[:80].rstrip()
|
||||||
|
if not title:
|
||||||
|
title = "Nouvelle conversation"
|
||||||
|
return SummarizeTitleResponseDTO(title=title)
|
||||||
|
|
||||||
|
|
||||||
# --- Mapping DTO → domaine (frontière HTTP) ---------------------------------
|
# --- Mapping DTO → domaine (frontière HTTP) ---------------------------------
|
||||||
|
|
||||||
|
|
||||||
@@ -426,10 +549,15 @@ def _to_campaign_context(dto: CampaignContextDTO | None) -> CampaignStructuralCo
|
|||||||
)
|
)
|
||||||
for arc in dto.arcs
|
for arc in dto.arcs
|
||||||
]
|
]
|
||||||
|
characters = [
|
||||||
|
CharacterSummary(name=c.name, snippet=c.snippet)
|
||||||
|
for c in dto.characters
|
||||||
|
]
|
||||||
return CampaignStructuralContext(
|
return CampaignStructuralContext(
|
||||||
campaign_name=dto.campaign_name,
|
campaign_name=dto.campaign_name,
|
||||||
campaign_description=dto.campaign_description,
|
campaign_description=dto.campaign_description,
|
||||||
arcs=arcs,
|
arcs=arcs,
|
||||||
|
characters=characters,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -449,6 +577,9 @@ class SettingsDTO(BaseModel):
|
|||||||
onemin_model: str
|
onemin_model: str
|
||||||
# True si une cle 1min.ai est deja configuree — pas de leak de la cle elle-meme.
|
# True si une cle 1min.ai est deja configuree — pas de leak de la cle elle-meme.
|
||||||
onemin_api_key_set: bool
|
onemin_api_key_set: bool
|
||||||
|
# Fenetre de contexte effective passee au modele (num_ctx Ollama) — sert
|
||||||
|
# aussi de plafond a la jauge de contexte UI.
|
||||||
|
llm_num_ctx: int
|
||||||
|
|
||||||
|
|
||||||
class SettingsUpdateDTO(BaseModel):
|
class SettingsUpdateDTO(BaseModel):
|
||||||
@@ -460,6 +591,7 @@ class SettingsUpdateDTO(BaseModel):
|
|||||||
onemin_model: str | None = None
|
onemin_model: str | None = None
|
||||||
# Chaine vide => on efface la cle. None => pas de changement.
|
# Chaine vide => on efface la cle. None => pas de changement.
|
||||||
onemin_api_key: str | None = None
|
onemin_api_key: str | None = None
|
||||||
|
llm_num_ctx: int | None = None
|
||||||
|
|
||||||
|
|
||||||
def _to_settings_dto(s: Settings) -> SettingsDTO:
|
def _to_settings_dto(s: Settings) -> SettingsDTO:
|
||||||
@@ -469,6 +601,7 @@ def _to_settings_dto(s: Settings) -> SettingsDTO:
|
|||||||
llm_model=s.llm_model,
|
llm_model=s.llm_model,
|
||||||
onemin_model=s.onemin_model,
|
onemin_model=s.onemin_model,
|
||||||
onemin_api_key_set=bool(s.onemin_api_key),
|
onemin_api_key_set=bool(s.onemin_api_key),
|
||||||
|
llm_num_ctx=s.llm_num_ctx,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -512,6 +645,50 @@ async def list_ollama_models(
|
|||||||
return {"models": sorted(models)}
|
return {"models": sorted(models)}
|
||||||
|
|
||||||
|
|
||||||
|
class OllamaModelInfoDTO(BaseModel):
|
||||||
|
"""Info utile extraite de /api/show pour un modele Ollama donne.
|
||||||
|
|
||||||
|
`context_length` = fenetre de contexte max supportee par le modele
|
||||||
|
(extraite des metadonnees GGUF). 0 si inconnue. Le frontend s'en sert
|
||||||
|
pour borner le slider de num_ctx dans les Parametres.
|
||||||
|
"""
|
||||||
|
|
||||||
|
context_length: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/models/ollama/info", response_model=OllamaModelInfoDTO)
|
||||||
|
async def get_ollama_model_info(
|
||||||
|
body: dict[str, str],
|
||||||
|
settings: Annotated[Settings, Depends(get_settings)],
|
||||||
|
) -> OllamaModelInfoDTO:
|
||||||
|
"""Retourne les metadonnees d'un modele Ollama via /api/show.
|
||||||
|
|
||||||
|
On passe par POST (et pas GET /models/ollama/{name}) parce que les noms
|
||||||
|
Ollama contiennent souvent un `:` (ex: `gemma3:e2b`) qui se segmente
|
||||||
|
mal dans une URL — le body JSON evite le probleme d'escaping.
|
||||||
|
|
||||||
|
Le champ qui nous interesse est `model_info["<arch>.context_length"]`
|
||||||
|
(ex: `gemma3.context_length: 131072`). L'arch varie selon le modele, on
|
||||||
|
scanne donc tous les champs finissant par `.context_length`.
|
||||||
|
"""
|
||||||
|
name = (body.get("name") or "").strip()
|
||||||
|
if not name:
|
||||||
|
raise HTTPException(status_code=400, detail="name requis")
|
||||||
|
url = f"{settings.ollama_base_url}/api/show"
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=5) as client:
|
||||||
|
response = await client.post(url, json={"model": name})
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
except httpx.HTTPError:
|
||||||
|
return OllamaModelInfoDTO(context_length=0)
|
||||||
|
model_info = data.get("model_info") or {}
|
||||||
|
for key, value in model_info.items():
|
||||||
|
if key.endswith(".context_length") and isinstance(value, int):
|
||||||
|
return OllamaModelInfoDTO(context_length=value)
|
||||||
|
return OllamaModelInfoDTO(context_length=0)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/models/onemin")
|
@app.get("/models/onemin")
|
||||||
def list_onemin_models() -> dict[str, list[dict[str, object]]]:
|
def list_onemin_models() -> dict[str, list[dict[str, object]]]:
|
||||||
"""Catalogue statique des modeles 1min.ai, groupes par fournisseur.
|
"""Catalogue statique des modeles 1min.ai, groupes par fournisseur.
|
||||||
@@ -596,3 +773,13 @@ def _to_narrative_entity(dto: NarrativeEntityDTO | None) -> NarrativeEntityConte
|
|||||||
title=dto.title,
|
title=dto.title,
|
||||||
fields=dict(dto.fields),
|
fields=dict(dto.fields),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_game_system_context(dto: GameSystemContextDTO | None) -> GameSystemContext | None:
|
||||||
|
if dto is None:
|
||||||
|
return None
|
||||||
|
return GameSystemContext(
|
||||||
|
system_name=dto.system_name,
|
||||||
|
system_description=dto.system_description,
|
||||||
|
sections=dict(dto.sections),
|
||||||
|
)
|
||||||
|
|||||||
@@ -3,4 +3,10 @@ uvicorn[standard]==0.32.*
|
|||||||
httpx==0.27.*
|
httpx==0.27.*
|
||||||
pydantic-settings==2.6.*
|
pydantic-settings==2.6.*
|
||||||
|
|
||||||
pydantic
|
pydantic
|
||||||
|
|
||||||
|
# Comptage de tokens pour la jauge de contexte (UI chat drawer).
|
||||||
|
# L'encodage cl100k_base (GPT-4/3.5) donne une approximation correcte pour
|
||||||
|
# la plupart des modeles Llama/Gemma/Mistral (~5-10% d'ecart) — suffisant
|
||||||
|
# pour une jauge visuelle.
|
||||||
|
tiktoken==0.8.*
|
||||||
|
|||||||
11
core/lombok.config
Normal file
11
core/lombok.config
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
## LoreMind Core - Configuration Lombok
|
||||||
|
#
|
||||||
|
# addLombokGeneratedAnnotation : ajoute @lombok.Generated sur toutes les
|
||||||
|
# methodes generees par Lombok (equals, hashCode, toString, builders,
|
||||||
|
# getters/setters, etc.). JaCoCo 0.8.2+ reconnait cette annotation et
|
||||||
|
# exclut automatiquement ces methodes du rapport de couverture.
|
||||||
|
#
|
||||||
|
# Objectif : mesurer la couverture UNIQUEMENT sur le code que nous ecrivons,
|
||||||
|
# pas sur le bytecode auto-genere (qui fausse les metriques : branches et
|
||||||
|
# instructions gonflees par les equals/hashCode).
|
||||||
|
lombok.addLombokGeneratedAnnotation = true
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
<groupId>com.loremind</groupId>
|
<groupId>com.loremind</groupId>
|
||||||
<artifactId>loremind-core</artifactId>
|
<artifactId>loremind-core</artifactId>
|
||||||
<version>0.3.0</version>
|
<version>0.6.1</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Arc;
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import org.springframework.beans.BeanUtils;
|
import org.springframework.beans.BeanUtils;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -17,11 +21,20 @@ import java.util.Optional;
|
|||||||
public class ArcService {
|
public class ArcService {
|
||||||
|
|
||||||
private final ArcRepository arcRepository;
|
private final ArcRepository arcRepository;
|
||||||
|
private final ChapterRepository chapterRepository;
|
||||||
|
private final SceneRepository sceneRepository;
|
||||||
|
|
||||||
public ArcService(ArcRepository arcRepository) {
|
public ArcService(ArcRepository arcRepository,
|
||||||
|
ChapterRepository chapterRepository,
|
||||||
|
SceneRepository sceneRepository) {
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
|
this.chapterRepository = chapterRepository;
|
||||||
|
this.sceneRepository = sceneRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Compte des entités qui seront supprimées en cascade avec l'arc. */
|
||||||
|
public record DeletionImpact(int chapters, int scenes) {}
|
||||||
|
|
||||||
public Arc createArc(String name, String description, String campaignId, int order) {
|
public Arc createArc(String name, String description, String campaignId, int order) {
|
||||||
Arc arc = Arc.builder()
|
Arc arc = Arc.builder()
|
||||||
.name(name)
|
.name(name)
|
||||||
@@ -59,7 +72,31 @@ public class ArcService {
|
|||||||
return arcRepository.save(arc);
|
return arcRepository.save(arc);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calcule l'impact d'une suppression en cascade : chapitres + scènes
|
||||||
|
* qui disparaîtront avec l'arc.
|
||||||
|
*/
|
||||||
|
public DeletionImpact getDeletionImpact(String id) {
|
||||||
|
List<Chapter> chapters = chapterRepository.findByArcId(id);
|
||||||
|
int sceneTotal = 0;
|
||||||
|
for (Chapter chapter : chapters) {
|
||||||
|
sceneTotal += sceneRepository.findByChapterId(chapter.getId()).size();
|
||||||
|
}
|
||||||
|
return new DeletionImpact(chapters.size(), sceneTotal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Supprime l'arc et toutes ses entités dépendantes (chapitres → scènes).
|
||||||
|
* Transactionnel : atomique.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
public void deleteArc(String id) {
|
public void deleteArc(String id) {
|
||||||
|
for (Chapter chapter : chapterRepository.findByArcId(id)) {
|
||||||
|
for (var scene : sceneRepository.findByChapterId(chapter.getId())) {
|
||||||
|
sceneRepository.deleteById(scene.getId());
|
||||||
|
}
|
||||||
|
chapterRepository.deleteById(chapter.getId());
|
||||||
|
}
|
||||||
arcRepository.deleteById(id);
|
arcRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,15 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -16,9 +23,22 @@ import java.util.Optional;
|
|||||||
public class CampaignService {
|
public class CampaignService {
|
||||||
|
|
||||||
private final CampaignRepository campaignRepository;
|
private final CampaignRepository campaignRepository;
|
||||||
|
private final ArcRepository arcRepository;
|
||||||
|
private final ChapterRepository chapterRepository;
|
||||||
|
private final SceneRepository sceneRepository;
|
||||||
|
private final CharacterRepository characterRepository;
|
||||||
|
|
||||||
public CampaignService(CampaignRepository campaignRepository) {
|
public CampaignService(
|
||||||
|
CampaignRepository campaignRepository,
|
||||||
|
ArcRepository arcRepository,
|
||||||
|
ChapterRepository chapterRepository,
|
||||||
|
SceneRepository sceneRepository,
|
||||||
|
CharacterRepository characterRepository) {
|
||||||
this.campaignRepository = campaignRepository;
|
this.campaignRepository = campaignRepository;
|
||||||
|
this.arcRepository = arcRepository;
|
||||||
|
this.chapterRepository = chapterRepository;
|
||||||
|
this.sceneRepository = sceneRepository;
|
||||||
|
this.characterRepository = characterRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -28,13 +48,20 @@ public class CampaignService {
|
|||||||
*
|
*
|
||||||
* <p>{@code loreId} est nullable : une campagne peut exister sans univers associé.</p>
|
* <p>{@code loreId} est nullable : une campagne peut exister sans univers associé.</p>
|
||||||
*/
|
*/
|
||||||
public record CampaignData(String name, String description, String loreId) {}
|
public record CampaignData(String name, String description, String loreId, String gameSystemId) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compte des entités qui seront supprimées en cascade si la campagne est effacée.
|
||||||
|
* Utilisé par l'UI pour afficher un récapitulatif dans le dialogue de confirmation.
|
||||||
|
*/
|
||||||
|
public record DeletionImpact(int arcs, int chapters, int scenes, int characters) {}
|
||||||
|
|
||||||
public Campaign createCampaign(CampaignData data) {
|
public Campaign createCampaign(CampaignData data) {
|
||||||
Campaign campaign = Campaign.builder()
|
Campaign campaign = Campaign.builder()
|
||||||
.name(data.name())
|
.name(data.name())
|
||||||
.description(data.description())
|
.description(data.description())
|
||||||
.loreId(normalizeLoreId(data.loreId()))
|
.loreId(normalizeId(data.loreId()))
|
||||||
|
.gameSystemId(normalizeId(data.gameSystemId()))
|
||||||
.arcsCount(0)
|
.arcsCount(0)
|
||||||
.build();
|
.build();
|
||||||
return campaignRepository.save(campaign);
|
return campaignRepository.save(campaign);
|
||||||
@@ -57,19 +84,61 @@ public class CampaignService {
|
|||||||
Campaign campaign = existingCampaign.get();
|
Campaign campaign = existingCampaign.get();
|
||||||
campaign.setName(data.name());
|
campaign.setName(data.name());
|
||||||
campaign.setDescription(data.description());
|
campaign.setDescription(data.description());
|
||||||
campaign.setLoreId(normalizeLoreId(data.loreId()));
|
campaign.setLoreId(normalizeId(data.loreId()));
|
||||||
|
campaign.setGameSystemId(normalizeId(data.gameSystemId()));
|
||||||
return campaignRepository.save(campaign);
|
return campaignRepository.save(campaign);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalise un loreId entrant : une chaîne vide/blanche est traitée comme "pas de lien".
|
* Normalise un ID entrant : une chaîne vide/blanche est traitée comme "pas de lien".
|
||||||
* Utile car les payloads JSON peuvent envoyer "" au lieu de null.
|
* Utile car les payloads JSON peuvent envoyer "" au lieu de null.
|
||||||
*/
|
*/
|
||||||
private String normalizeLoreId(String loreId) {
|
private String normalizeId(String id) {
|
||||||
return (loreId == null || loreId.isBlank()) ? null : loreId;
|
return (id == null || id.isBlank()) ? null : id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calcule l'impact d'une suppression en cascade : nombre d'arcs, chapitres,
|
||||||
|
* scènes et personnages qui disparaîtront avec la campagne. Utilisé par l'UI
|
||||||
|
* pour afficher "X arcs, Y chapitres, Z scènes seront supprimés".
|
||||||
|
*/
|
||||||
|
public DeletionImpact getDeletionImpact(String id) {
|
||||||
|
List<Arc> arcs = arcRepository.findByCampaignId(id);
|
||||||
|
int chapterTotal = 0;
|
||||||
|
int sceneTotal = 0;
|
||||||
|
for (Arc arc : arcs) {
|
||||||
|
List<Chapter> chapters = chapterRepository.findByArcId(arc.getId());
|
||||||
|
chapterTotal += chapters.size();
|
||||||
|
for (Chapter chapter : chapters) {
|
||||||
|
sceneTotal += sceneRepository.findByChapterId(chapter.getId()).size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int characterTotal = characterRepository.findByCampaignId(id).size();
|
||||||
|
return new DeletionImpact(arcs.size(), chapterTotal, sceneTotal, characterTotal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Supprime la campagne et toutes ses entités dépendantes (arcs → chapitres →
|
||||||
|
* scènes, plus les personnages). L'opération est transactionnelle : soit
|
||||||
|
* tout disparaît, soit rien ne change. Les FKs applicatives n'ayant pas
|
||||||
|
* de contrainte CASCADE au niveau DB, on orchestre la cascade ici.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
public void deleteCampaign(String id) {
|
public void deleteCampaign(String id) {
|
||||||
|
List<Arc> arcs = arcRepository.findByCampaignId(id);
|
||||||
|
for (Arc arc : arcs) {
|
||||||
|
List<Chapter> chapters = chapterRepository.findByArcId(arc.getId());
|
||||||
|
for (Chapter chapter : chapters) {
|
||||||
|
for (var scene : sceneRepository.findByChapterId(chapter.getId())) {
|
||||||
|
sceneRepository.deleteById(scene.getId());
|
||||||
|
}
|
||||||
|
chapterRepository.deleteById(chapter.getId());
|
||||||
|
}
|
||||||
|
arcRepository.deleteById(arc.getId());
|
||||||
|
}
|
||||||
|
for (var character : characterRepository.findByCampaignId(id)) {
|
||||||
|
characterRepository.deleteById(character.getId());
|
||||||
|
}
|
||||||
campaignRepository.deleteById(id);
|
campaignRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package com.loremind.application.campaigncontext;
|
|||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Chapter;
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import org.springframework.beans.BeanUtils;
|
import org.springframework.beans.BeanUtils;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -17,11 +19,16 @@ import java.util.Optional;
|
|||||||
public class ChapterService {
|
public class ChapterService {
|
||||||
|
|
||||||
private final ChapterRepository chapterRepository;
|
private final ChapterRepository chapterRepository;
|
||||||
|
private final SceneRepository sceneRepository;
|
||||||
|
|
||||||
public ChapterService(ChapterRepository chapterRepository) {
|
public ChapterService(ChapterRepository chapterRepository, SceneRepository sceneRepository) {
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
|
this.sceneRepository = sceneRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Compte des scènes qui seront supprimées en cascade avec le chapitre. */
|
||||||
|
public record DeletionImpact(int scenes) {}
|
||||||
|
|
||||||
public Chapter createChapter(String name, String description, String arcId, int order) {
|
public Chapter createChapter(String name, String description, String arcId, int order) {
|
||||||
Chapter chapter = Chapter.builder()
|
Chapter chapter = Chapter.builder()
|
||||||
.name(name)
|
.name(name)
|
||||||
@@ -58,7 +65,17 @@ public class ChapterService {
|
|||||||
return chapterRepository.save(chapter);
|
return chapterRepository.save(chapter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Compte des scènes qui tomberont avec le chapitre. */
|
||||||
|
public DeletionImpact getDeletionImpact(String id) {
|
||||||
|
return new DeletionImpact(sceneRepository.findByChapterId(id).size());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Supprime le chapitre et toutes ses scènes. Transactionnel : atomique. */
|
||||||
|
@Transactional
|
||||||
public void deleteChapter(String id) {
|
public void deleteChapter(String id) {
|
||||||
|
for (var scene : sceneRepository.findByChapterId(id)) {
|
||||||
|
sceneRepository.deleteById(scene.getId());
|
||||||
|
}
|
||||||
chapterRepository.deleteById(id);
|
chapterRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service d'application pour les fiches de personnages (PJ).
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class CharacterService {
|
||||||
|
|
||||||
|
private final CharacterRepository characterRepository;
|
||||||
|
|
||||||
|
public CharacterService(CharacterRepository characterRepository) {
|
||||||
|
this.characterRepository = characterRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parameter Object pour la création / mise à jour d'un Character.
|
||||||
|
* `order` est fourni par le controller ; si absent, le service le calcule.
|
||||||
|
*/
|
||||||
|
public record CharacterData(String name, String markdownContent, String campaignId, Integer order) {}
|
||||||
|
|
||||||
|
public Character createCharacter(CharacterData data) {
|
||||||
|
int order = data.order() != null
|
||||||
|
? data.order()
|
||||||
|
: nextOrderFor(data.campaignId());
|
||||||
|
Character character = Character.builder()
|
||||||
|
.name(data.name())
|
||||||
|
.markdownContent(data.markdownContent())
|
||||||
|
.campaignId(data.campaignId())
|
||||||
|
.order(order)
|
||||||
|
.build();
|
||||||
|
return characterRepository.save(character);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Character> getCharacterById(String id) {
|
||||||
|
return characterRepository.findById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Character> getCharactersByCampaignId(String campaignId) {
|
||||||
|
return characterRepository.findByCampaignId(campaignId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Character updateCharacter(String id, CharacterData data) {
|
||||||
|
Character existing = characterRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Character non trouvé avec l'ID: " + id));
|
||||||
|
existing.setName(data.name());
|
||||||
|
existing.setMarkdownContent(data.markdownContent());
|
||||||
|
if (data.order() != null) {
|
||||||
|
existing.setOrder(data.order());
|
||||||
|
}
|
||||||
|
// campaignId n'est pas modifiable après création (cross-campagne move hors scope MVP).
|
||||||
|
return characterRepository.save(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteCharacter(String id) {
|
||||||
|
characterRepository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Renvoie la prochaine position libre — append en fin de liste. */
|
||||||
|
private int nextOrderFor(String campaignId) {
|
||||||
|
return characterRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.mapToInt(Character::getOrder)
|
||||||
|
.max()
|
||||||
|
.orElse(-1) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package com.loremind.application.conversationcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.conversationcontext.Conversation;
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
import com.loremind.domain.conversationcontext.ports.ConversationRepository;
|
||||||
|
import com.loremind.domain.conversationcontext.ports.ConversationTitleGenerator;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service d'application du contexte Conversation.
|
||||||
|
*
|
||||||
|
* Regroupe les cas d'usage CRUD + append message + rename. Un seul
|
||||||
|
* service suffit — le contexte est simple et les operations fortement
|
||||||
|
* liees (meme aggregat).
|
||||||
|
*
|
||||||
|
* Regles metier :
|
||||||
|
* - exactement un ancrage parent (loreId XOR campaignId) ;
|
||||||
|
* - entityType et entityId vont ensemble (tous deux null = niveau racine,
|
||||||
|
* tous deux non-null = niveau entite precise).
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class ConversationService {
|
||||||
|
|
||||||
|
private final ConversationRepository repository;
|
||||||
|
private final ConversationTitleGenerator titleGenerator;
|
||||||
|
|
||||||
|
public ConversationService(ConversationRepository repository,
|
||||||
|
ConversationTitleGenerator titleGenerator) {
|
||||||
|
this.repository = repository;
|
||||||
|
this.titleGenerator = titleGenerator;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Donnees de creation d'une conversation. Titre optionnel — sera auto-genere si absent. */
|
||||||
|
public record CreateData(
|
||||||
|
String title,
|
||||||
|
String loreId,
|
||||||
|
String campaignId,
|
||||||
|
String entityType,
|
||||||
|
String entityId) {}
|
||||||
|
|
||||||
|
public Conversation create(CreateData data) {
|
||||||
|
validateAnchor(data.loreId(), data.campaignId(), data.entityType(), data.entityId());
|
||||||
|
|
||||||
|
String title = (data.title() == null || data.title().isBlank())
|
||||||
|
? "Nouvelle conversation"
|
||||||
|
: data.title().trim();
|
||||||
|
|
||||||
|
Conversation conv = Conversation.builder()
|
||||||
|
.title(title)
|
||||||
|
.loreId(data.loreId())
|
||||||
|
.campaignId(data.campaignId())
|
||||||
|
.entityType(data.entityType())
|
||||||
|
.entityId(data.entityId())
|
||||||
|
.build();
|
||||||
|
return repository.save(conv);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Conversation> getById(String id) {
|
||||||
|
return repository.findById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Conversation> listByContext(String loreId, String campaignId, String entityType, String entityId) {
|
||||||
|
validateAnchor(loreId, campaignId, entityType, entityId);
|
||||||
|
return repository.findByContext(loreId, campaignId, entityType, entityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void rename(String id, String title) {
|
||||||
|
if (title == null || title.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("Le titre ne peut pas etre vide");
|
||||||
|
}
|
||||||
|
if (repository.findById(id).isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Conversation introuvable : " + id);
|
||||||
|
}
|
||||||
|
repository.updateTitle(id, title.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(String id) {
|
||||||
|
repository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auto-genere un titre a partir des premiers messages et le persiste.
|
||||||
|
* Appele typiquement apres le 1er couple user/assistant pour remplacer
|
||||||
|
* le titre provisoire. Echec silencieux (fallback dans l'adaptateur) —
|
||||||
|
* on n'empeche pas la conversation de fonctionner si le Brain est down.
|
||||||
|
*/
|
||||||
|
public String autoGenerateTitle(String conversationId) {
|
||||||
|
Conversation conv = repository.findById(conversationId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Conversation introuvable : " + conversationId));
|
||||||
|
List<ConversationMessage> seeds = conv.getMessages();
|
||||||
|
if (seeds == null || seeds.isEmpty()) {
|
||||||
|
return conv.getTitle();
|
||||||
|
}
|
||||||
|
String title = titleGenerator.generate(seeds);
|
||||||
|
repository.updateTitle(conversationId, title);
|
||||||
|
return title;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ajoute un message (user ou assistant) a une conversation existante.
|
||||||
|
* L'horodatage et l'id sont assignes par la couche persistance.
|
||||||
|
*/
|
||||||
|
public ConversationMessage appendMessage(String conversationId, String role, String content) {
|
||||||
|
if (role == null || (!role.equals("user") && !role.equals("assistant") && !role.equals("system"))) {
|
||||||
|
throw new IllegalArgumentException("Role invalide : " + role);
|
||||||
|
}
|
||||||
|
if (content == null || content.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Contenu vide interdit");
|
||||||
|
}
|
||||||
|
ConversationMessage msg = ConversationMessage.builder()
|
||||||
|
.role(role)
|
||||||
|
.content(content)
|
||||||
|
.build();
|
||||||
|
return repository.appendMessage(conversationId, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Validation ----------
|
||||||
|
|
||||||
|
private void validateAnchor(String loreId, String campaignId, String entityType, String entityId) {
|
||||||
|
boolean hasLore = loreId != null && !loreId.isBlank();
|
||||||
|
boolean hasCamp = campaignId != null && !campaignId.isBlank();
|
||||||
|
if (hasLore == hasCamp) {
|
||||||
|
throw new IllegalArgumentException("Exactement un parent attendu : loreId XOR campaignId");
|
||||||
|
}
|
||||||
|
boolean hasType = entityType != null && !entityType.isBlank();
|
||||||
|
boolean hasEntId = entityId != null && !entityId.isBlank();
|
||||||
|
if (hasType != hasEntId) {
|
||||||
|
throw new IllegalArgumentException("entityType et entityId doivent etre tous deux null ou tous deux non-null");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
|
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Construit un {@link GameSystemContext} à partir d'un gameSystemId et d'un intent.
|
||||||
|
* <p>
|
||||||
|
* Pipeline :
|
||||||
|
* 1. Charge le GameSystem (retourne Optional.empty si introuvable — dégradation gracieuse).
|
||||||
|
* 2. Parse le markdown par titres H2 (## Section) → Map<Titre, Contenu>.
|
||||||
|
* 3. Filtre les sections selon l'intent via les alias {@link GenerationIntent#getSectionAliases()}.
|
||||||
|
* GENERIC = pas de filtre.
|
||||||
|
* <p>
|
||||||
|
* Parsing à la volée (pas de cache) : les règles d'un système font
|
||||||
|
* typiquement 5-20kB, le coût de parsing est négligeable devant l'appel LLM.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class GameSystemContextBuilder {
|
||||||
|
|
||||||
|
/** Matche "## Titre" en début de ligne (multiline). Capture le titre en groupe 1. */
|
||||||
|
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(.+?)\\s*$");
|
||||||
|
|
||||||
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
|
||||||
|
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) {
|
||||||
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
||||||
|
if (gameSystemId == null || gameSystemId.isBlank()) return Optional.empty();
|
||||||
|
return gameSystemRepository.findById(gameSystemId)
|
||||||
|
.map(gs -> build(gs, intent));
|
||||||
|
}
|
||||||
|
|
||||||
|
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
||||||
|
Map<String, String> allSections = parseH2Sections(gs.getRulesMarkdown());
|
||||||
|
Map<String, String> filtered = filterByIntent(allSections, intent);
|
||||||
|
return GameSystemContext.builder()
|
||||||
|
.systemName(gs.getName())
|
||||||
|
.systemDescription(gs.getDescription())
|
||||||
|
.sections(filtered)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Découpe le markdown par titres H2. Préserve l'ordre d'apparition (LinkedHashMap).
|
||||||
|
* Le contenu avant le premier H2 est ignoré (préambule libre).
|
||||||
|
*/
|
||||||
|
Map<String, String> parseH2Sections(String markdown) {
|
||||||
|
Map<String, String> sections = new LinkedHashMap<>();
|
||||||
|
if (markdown == null || markdown.isBlank()) return sections;
|
||||||
|
|
||||||
|
Matcher m = H2_HEADER.matcher(markdown);
|
||||||
|
String currentTitle = null;
|
||||||
|
int currentContentStart = -1;
|
||||||
|
|
||||||
|
while (m.find()) {
|
||||||
|
if (currentTitle != null) {
|
||||||
|
sections.put(currentTitle, markdown.substring(currentContentStart, m.start()).strip());
|
||||||
|
}
|
||||||
|
currentTitle = m.group(1).trim();
|
||||||
|
currentContentStart = m.end();
|
||||||
|
}
|
||||||
|
if (currentTitle != null) {
|
||||||
|
sections.put(currentTitle, markdown.substring(currentContentStart).strip());
|
||||||
|
}
|
||||||
|
return sections;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> filterByIntent(Map<String, String> sections, GenerationIntent intent) {
|
||||||
|
if (intent.matchesAllSections()) return sections;
|
||||||
|
Map<String, String> filtered = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<String, String> e : sections.entrySet()) {
|
||||||
|
String titleLower = e.getKey().toLowerCase();
|
||||||
|
boolean match = intent.getSectionAliases().stream().anyMatch(titleLower::contains);
|
||||||
|
if (match) {
|
||||||
|
filtered.put(e.getKey(), e.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return filtered;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class GameSystemService {
|
||||||
|
|
||||||
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
|
||||||
|
public GameSystemService(GameSystemRepository gameSystemRepository) {
|
||||||
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parameter Object pour la création / mise à jour d'un GameSystem.
|
||||||
|
*/
|
||||||
|
public record GameSystemData(
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
String rulesMarkdown,
|
||||||
|
String author,
|
||||||
|
boolean isPublic
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public GameSystem createGameSystem(GameSystemData data) {
|
||||||
|
GameSystem gameSystem = GameSystem.builder()
|
||||||
|
.name(data.name())
|
||||||
|
.description(data.description())
|
||||||
|
.rulesMarkdown(data.rulesMarkdown())
|
||||||
|
.author(normalize(data.author()))
|
||||||
|
.isPublic(data.isPublic())
|
||||||
|
.build();
|
||||||
|
return gameSystemRepository.save(gameSystem);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<GameSystem> getGameSystemById(String id) {
|
||||||
|
return gameSystemRepository.findById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<GameSystem> getAllGameSystems() {
|
||||||
|
return gameSystemRepository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
public GameSystem updateGameSystem(String id, GameSystemData data) {
|
||||||
|
GameSystem existing = gameSystemRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("GameSystem non trouvé avec l'ID: " + id));
|
||||||
|
existing.setName(data.name());
|
||||||
|
existing.setDescription(data.description());
|
||||||
|
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||||
|
existing.setAuthor(normalize(data.author()));
|
||||||
|
existing.setPublic(data.isPublic());
|
||||||
|
return gameSystemRepository.save(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteGameSystem(String id) {
|
||||||
|
gameSystemRepository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean gameSystemExists(String id) {
|
||||||
|
return gameSystemRepository.existsById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<GameSystem> searchGameSystems(String query) {
|
||||||
|
if (query == null || query.isBlank()) return List.of();
|
||||||
|
return gameSystemRepository.searchByName(query.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalize(String value) {
|
||||||
|
return (value == null || value.isBlank()) ? null : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,15 +3,18 @@ package com.loremind.application.generationcontext;
|
|||||||
import com.loremind.domain.campaigncontext.Arc;
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
import com.loremind.domain.campaigncontext.Chapter;
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
import com.loremind.domain.campaigncontext.Scene;
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@@ -38,18 +41,24 @@ public class CampaignStructuralContextBuilder {
|
|||||||
private final ArcRepository arcRepository;
|
private final ArcRepository arcRepository;
|
||||||
private final ChapterRepository chapterRepository;
|
private final ChapterRepository chapterRepository;
|
||||||
private final SceneRepository sceneRepository;
|
private final SceneRepository sceneRepository;
|
||||||
|
private final CharacterRepository characterRepository;
|
||||||
|
|
||||||
public CampaignStructuralContextBuilder(
|
public CampaignStructuralContextBuilder(
|
||||||
CampaignRepository campaignRepository,
|
CampaignRepository campaignRepository,
|
||||||
ArcRepository arcRepository,
|
ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
SceneRepository sceneRepository) {
|
SceneRepository sceneRepository,
|
||||||
|
CharacterRepository characterRepository) {
|
||||||
this.campaignRepository = campaignRepository;
|
this.campaignRepository = campaignRepository;
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
|
this.characterRepository = characterRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Longueur max du snippet de PJ injecté dans le contexte (coût tokens maîtrisé). */
|
||||||
|
private static final int CHARACTER_SNIPPET_MAX_LEN = 160;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Construit la carte narrative d'une Campagne (arcs → chapitres → scènes,
|
* Construit la carte narrative d'une Campagne (arcs → chapitres → scènes,
|
||||||
* nom + description courte à chaque niveau).
|
* nom + description courte à chaque niveau).
|
||||||
@@ -65,13 +74,42 @@ public class CampaignStructuralContextBuilder {
|
|||||||
.map(this::toArcSummary)
|
.map(this::toArcSummary)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
List<CharacterSummary> characters = characterRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.sorted(Comparator.comparingInt(Character::getOrder))
|
||||||
|
.map(this::toCharacterSummary)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
return CampaignStructuralContext.builder()
|
return CampaignStructuralContext.builder()
|
||||||
.campaignName(campaign.getName())
|
.campaignName(campaign.getName())
|
||||||
.campaignDescription(campaign.getDescription())
|
.campaignDescription(campaign.getDescription())
|
||||||
.arcs(arcs)
|
.arcs(arcs)
|
||||||
|
.characters(characters)
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Projette un PJ vers un résumé court : nom + 1re ligne "signifiante" du
|
||||||
|
* markdown (ni vide, ni un titre). Permet à l'IA de savoir "qui est Thorin"
|
||||||
|
* sans injecter toute sa fiche.
|
||||||
|
*/
|
||||||
|
private CharacterSummary toCharacterSummary(Character c) {
|
||||||
|
return CharacterSummary.builder()
|
||||||
|
.name(c.getName())
|
||||||
|
.snippet(extractSnippet(c.getMarkdownContent()))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
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() + "…";
|
||||||
|
}
|
||||||
|
|
||||||
private ArcSummary toArcSummary(Arc arc) {
|
private ArcSummary toArcSummary(Arc arc) {
|
||||||
List<ChapterSummary> chapters = chapterRepository.findByArcId(arc.getId()).stream()
|
List<ChapterSummary> chapters = chapterRepository.findByArcId(arc.getId()).stream()
|
||||||
.sorted(Comparator.comparingInt(Chapter::getOrder))
|
.sorted(Comparator.comparingInt(Chapter::getOrder))
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ package com.loremind.application.generationcontext;
|
|||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Arc;
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Chapter;
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
import com.loremind.domain.campaigncontext.Scene;
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
@@ -26,20 +28,23 @@ public class NarrativeEntityContextBuilder {
|
|||||||
private final ArcRepository arcRepository;
|
private final ArcRepository arcRepository;
|
||||||
private final ChapterRepository chapterRepository;
|
private final ChapterRepository chapterRepository;
|
||||||
private final SceneRepository sceneRepository;
|
private final SceneRepository sceneRepository;
|
||||||
|
private final CharacterRepository characterRepository;
|
||||||
|
|
||||||
public NarrativeEntityContextBuilder(
|
public NarrativeEntityContextBuilder(
|
||||||
ArcRepository arcRepository,
|
ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
SceneRepository sceneRepository) {
|
SceneRepository sceneRepository,
|
||||||
|
CharacterRepository characterRepository) {
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
|
this.characterRepository = characterRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Charge l'entité narrative ciblée et la projette vers un VO du GenerationContext.
|
* Charge l'entité narrative ciblée et la projette vers un VO du GenerationContext.
|
||||||
*
|
*
|
||||||
* @param entityType "arc", "chapter" ou "scene" (insensible à la casse)
|
* @param entityType "arc", "chapter", "scene" ou "character" (insensible à la casse)
|
||||||
* @param entityId l'ID de l'entité
|
* @param entityId l'ID de l'entité
|
||||||
* @throws IllegalArgumentException si le type est inconnu ou l'entité introuvable
|
* @throws IllegalArgumentException si le type est inconnu ou l'entité introuvable
|
||||||
*/
|
*/
|
||||||
@@ -49,6 +54,7 @@ public class NarrativeEntityContextBuilder {
|
|||||||
case "arc" -> fromArc(loadArc(entityId));
|
case "arc" -> fromArc(loadArc(entityId));
|
||||||
case "chapter" -> fromChapter(loadChapter(entityId));
|
case "chapter" -> fromChapter(loadChapter(entityId));
|
||||||
case "scene" -> fromScene(loadScene(entityId));
|
case "scene" -> fromScene(loadScene(entityId));
|
||||||
|
case "character" -> fromCharacter(loadCharacter(entityId));
|
||||||
default -> throw new IllegalArgumentException("Type d'entité narrative inconnu: " + entityType);
|
default -> throw new IllegalArgumentException("Type d'entité narrative inconnu: " + entityType);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -70,6 +76,11 @@ public class NarrativeEntityContextBuilder {
|
|||||||
.orElseThrow(() -> new IllegalArgumentException("Scène non trouvée: " + id));
|
.orElseThrow(() -> new IllegalArgumentException("Scène non trouvée: " + id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Character loadCharacter(String id) {
|
||||||
|
return characterRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Personnage non trouvé: " + id));
|
||||||
|
}
|
||||||
|
|
||||||
// --- Mapping entité → VO ------------------------------------------------
|
// --- Mapping entité → VO ------------------------------------------------
|
||||||
|
|
||||||
private NarrativeEntityContext fromArc(Arc a) {
|
private NarrativeEntityContext fromArc(Arc a) {
|
||||||
@@ -118,6 +129,16 @@ public class NarrativeEntityContextBuilder {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private NarrativeEntityContext fromCharacter(Character c) {
|
||||||
|
Map<String, String> fields = new LinkedHashMap<>();
|
||||||
|
putField(fields, "fiche complète (markdown)", c.getMarkdownContent());
|
||||||
|
return NarrativeEntityContext.builder()
|
||||||
|
.entityType("character")
|
||||||
|
.title(c.getName())
|
||||||
|
.fields(fields)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
/** Null/blank devient chaîne vide — uniforme côté prompt, pas de NPE côté LLM. */
|
/** Null/blank devient chaîne vide — uniforme côté prompt, pas de NPE côté LLM. */
|
||||||
private static void putField(Map<String, String> target, String key, String value) {
|
private static void putField(Map<String, String> target, String key, String value) {
|
||||||
target.put(key, value == null ? "" : value);
|
target.put(key, value == null ? "" : value);
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
package com.loremind.application.generationcontext;
|
package com.loremind.application.generationcontext;
|
||||||
|
|
||||||
|
import com.loremind.application.gamesystemcontext.GameSystemContextBuilder;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.ChatMessage;
|
import com.loremind.domain.generationcontext.ChatMessage;
|
||||||
import com.loremind.domain.generationcontext.ChatRequest;
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
|
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||||
@@ -33,6 +37,7 @@ public class StreamChatForCampaignUseCase {
|
|||||||
private final CampaignStructuralContextBuilder campaignContextBuilder;
|
private final CampaignStructuralContextBuilder campaignContextBuilder;
|
||||||
private final LoreStructuralContextBuilder loreContextBuilder;
|
private final LoreStructuralContextBuilder loreContextBuilder;
|
||||||
private final NarrativeEntityContextBuilder narrativeEntityContextBuilder;
|
private final NarrativeEntityContextBuilder narrativeEntityContextBuilder;
|
||||||
|
private final GameSystemContextBuilder gameSystemContextBuilder;
|
||||||
private final AiChatProvider aiChatProvider;
|
private final AiChatProvider aiChatProvider;
|
||||||
|
|
||||||
public StreamChatForCampaignUseCase(
|
public StreamChatForCampaignUseCase(
|
||||||
@@ -40,11 +45,13 @@ public class StreamChatForCampaignUseCase {
|
|||||||
CampaignStructuralContextBuilder campaignContextBuilder,
|
CampaignStructuralContextBuilder campaignContextBuilder,
|
||||||
LoreStructuralContextBuilder loreContextBuilder,
|
LoreStructuralContextBuilder loreContextBuilder,
|
||||||
NarrativeEntityContextBuilder narrativeEntityContextBuilder,
|
NarrativeEntityContextBuilder narrativeEntityContextBuilder,
|
||||||
|
GameSystemContextBuilder gameSystemContextBuilder,
|
||||||
AiChatProvider aiChatProvider) {
|
AiChatProvider aiChatProvider) {
|
||||||
this.campaignRepository = campaignRepository;
|
this.campaignRepository = campaignRepository;
|
||||||
this.campaignContextBuilder = campaignContextBuilder;
|
this.campaignContextBuilder = campaignContextBuilder;
|
||||||
this.loreContextBuilder = loreContextBuilder;
|
this.loreContextBuilder = loreContextBuilder;
|
||||||
this.narrativeEntityContextBuilder = narrativeEntityContextBuilder;
|
this.narrativeEntityContextBuilder = narrativeEntityContextBuilder;
|
||||||
|
this.gameSystemContextBuilder = gameSystemContextBuilder;
|
||||||
this.aiChatProvider = aiChatProvider;
|
this.aiChatProvider = aiChatProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,6 +72,7 @@ public class StreamChatForCampaignUseCase {
|
|||||||
String entityType,
|
String entityType,
|
||||||
String entityId,
|
String entityId,
|
||||||
List<ChatMessage> messages,
|
List<ChatMessage> messages,
|
||||||
|
Consumer<ChatUsage> onUsage,
|
||||||
Consumer<String> onToken,
|
Consumer<String> onToken,
|
||||||
Runnable onComplete,
|
Runnable onComplete,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
@@ -76,15 +84,17 @@ public class StreamChatForCampaignUseCase {
|
|||||||
CampaignStructuralContext campaignContext = campaignContextBuilder.build(campaignId);
|
CampaignStructuralContext campaignContext = campaignContextBuilder.build(campaignId);
|
||||||
LoreStructuralContext loreContext = loadLinkedLoreContextOrNull(campaign);
|
LoreStructuralContext loreContext = loadLinkedLoreContextOrNull(campaign);
|
||||||
NarrativeEntityContext narrativeEntity = buildNarrativeEntityOrNull(entityType, entityId);
|
NarrativeEntityContext narrativeEntity = buildNarrativeEntityOrNull(entityType, entityId);
|
||||||
|
GameSystemContext gameSystemContext = loadGameSystemContextOrNull(campaign, entityType);
|
||||||
|
|
||||||
ChatRequest request = ChatRequest.builder()
|
ChatRequest request = ChatRequest.builder()
|
||||||
.messages(messages)
|
.messages(messages)
|
||||||
.loreContext(loreContext)
|
.loreContext(loreContext)
|
||||||
.campaignContext(campaignContext)
|
.campaignContext(campaignContext)
|
||||||
.narrativeEntity(narrativeEntity)
|
.narrativeEntity(narrativeEntity)
|
||||||
|
.gameSystemContext(gameSystemContext)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
aiChatProvider.streamChat(request, onToken, onComplete, onError);
|
aiChatProvider.streamChat(request, onUsage, onToken, onComplete, onError);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -102,4 +112,16 @@ public class StreamChatForCampaignUseCase {
|
|||||||
if (entityId == null || entityId.isBlank()) return null;
|
if (entityId == null || entityId.isBlank()) return null;
|
||||||
return narrativeEntityContextBuilder.build(entityType, entityId);
|
return narrativeEntityContextBuilder.build(entityType, entityId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Charge le GameSystemContext si la campagne est liée à un GameSystem.
|
||||||
|
* L'entityType détermine quelles sections de règles sont injectées
|
||||||
|
* (SCENE → combat/PNJ, CHAPTER → combat/classes, ARC → lore/factions, autre → toutes).
|
||||||
|
* Retourne null en cas de GameSystem introuvable (dégradation gracieuse).
|
||||||
|
*/
|
||||||
|
private GameSystemContext loadGameSystemContextOrNull(Campaign campaign, String entityType) {
|
||||||
|
if (!campaign.isLinkedToGameSystem()) return null;
|
||||||
|
GenerationIntent intent = GenerationIntent.fromNarrativeEntityType(entityType);
|
||||||
|
return gameSystemContextBuilder.buildOptional(campaign.getGameSystemId(), intent).orElse(null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.loremind.application.generationcontext;
|
|||||||
|
|
||||||
import com.loremind.domain.generationcontext.ChatMessage;
|
import com.loremind.domain.generationcontext.ChatMessage;
|
||||||
import com.loremind.domain.generationcontext.ChatRequest;
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.PageContext;
|
import com.loremind.domain.generationcontext.PageContext;
|
||||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||||
@@ -60,6 +61,7 @@ public class StreamChatForLoreUseCase {
|
|||||||
String loreId,
|
String loreId,
|
||||||
String pageId,
|
String pageId,
|
||||||
List<ChatMessage> messages,
|
List<ChatMessage> messages,
|
||||||
|
Consumer<ChatUsage> onUsage,
|
||||||
Consumer<String> onToken,
|
Consumer<String> onToken,
|
||||||
Runnable onComplete,
|
Runnable onComplete,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
@@ -75,7 +77,7 @@ public class StreamChatForLoreUseCase {
|
|||||||
.pageContext(pageContext)
|
.pageContext(pageContext)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
aiChatProvider.streamChat(request, onToken, onComplete, onError);
|
aiChatProvider.streamChat(request, onUsage, onToken, onComplete, onError);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
package com.loremind.application.lorecontext;
|
package com.loremind.application.lorecontext;
|
||||||
|
|
||||||
import com.loremind.domain.lorecontext.LoreNode;
|
import com.loremind.domain.lorecontext.LoreNode;
|
||||||
|
import com.loremind.domain.lorecontext.Page;
|
||||||
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
||||||
|
import com.loremind.domain.lorecontext.ports.PageRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@@ -16,11 +20,20 @@ import java.util.Optional;
|
|||||||
public class LoreNodeService {
|
public class LoreNodeService {
|
||||||
|
|
||||||
private final LoreNodeRepository loreNodeRepository;
|
private final LoreNodeRepository loreNodeRepository;
|
||||||
|
private final PageRepository pageRepository;
|
||||||
|
|
||||||
public LoreNodeService(LoreNodeRepository loreNodeRepository) {
|
public LoreNodeService(LoreNodeRepository loreNodeRepository, PageRepository pageRepository) {
|
||||||
this.loreNodeRepository = loreNodeRepository;
|
this.loreNodeRepository = loreNodeRepository;
|
||||||
|
this.pageRepository = pageRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compte des entités qui seront supprimées en cascade si le dossier est effacé :
|
||||||
|
* le dossier lui-même n'est pas compté, seuls les descendants (sous-dossiers
|
||||||
|
* récursifs + pages de l'ensemble du sous-arbre).
|
||||||
|
*/
|
||||||
|
public record DeletionImpact(int folders, int pages) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Crée un LoreNode (dossier) à partir d'un "objet changes" porteur des valeurs
|
* Crée un LoreNode (dossier) à partir d'un "objet changes" porteur des valeurs
|
||||||
* souhaitées (pattern Parameter Object) : évite les signatures qui gonflent
|
* souhaitées (pattern Parameter Object) : évite les signatures qui gonflent
|
||||||
@@ -68,7 +81,64 @@ public class LoreNodeService {
|
|||||||
return loreNodeRepository.save(existing);
|
return loreNodeRepository.save(existing);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calcule l'impact d'une suppression en cascade : nombre de sous-dossiers
|
||||||
|
* (récursif, sans compter la racine) et de pages dans l'ensemble du sous-arbre.
|
||||||
|
*/
|
||||||
|
public DeletionImpact getDeletionImpact(String id) {
|
||||||
|
List<LoreNode> descendants = collectDescendants(id);
|
||||||
|
int pageTotal = pageRepository.findByNodeId(id).size();
|
||||||
|
for (LoreNode descendant : descendants) {
|
||||||
|
pageTotal += pageRepository.findByNodeId(descendant.getId()).size();
|
||||||
|
}
|
||||||
|
return new DeletionImpact(descendants.size(), pageTotal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Supprime le dossier et tout son sous-arbre (sous-dossiers récursifs + pages).
|
||||||
|
* Suppression en profondeur d'abord (feuilles → racine) pour limiter les
|
||||||
|
* références orphelines en cours de transaction. Les FKs applicatives n'ayant
|
||||||
|
* pas de CASCADE en DB, on orchestre la descente ici.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
public void deleteLoreNode(String id) {
|
public void deleteLoreNode(String id) {
|
||||||
|
List<LoreNode> descendants = collectDescendants(id);
|
||||||
|
// Descendants retournés en ordre BFS (haut → bas) : on inverse pour
|
||||||
|
// supprimer les feuilles en premier, puis on finit par la racine.
|
||||||
|
for (int i = descendants.size() - 1; i >= 0; i--) {
|
||||||
|
String descendantId = descendants.get(i).getId();
|
||||||
|
deletePagesOfNode(descendantId);
|
||||||
|
loreNodeRepository.deleteById(descendantId);
|
||||||
|
}
|
||||||
|
deletePagesOfNode(id);
|
||||||
loreNodeRepository.deleteById(id);
|
loreNodeRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void deletePagesOfNode(String nodeId) {
|
||||||
|
for (Page page : pageRepository.findByNodeId(nodeId)) {
|
||||||
|
pageRepository.deleteById(page.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retourne tous les descendants (hors racine) d'un dossier, en ordre BFS.
|
||||||
|
* Parcours itératif pour éviter tout risque de débordement de pile sur
|
||||||
|
* une arborescence profonde malicieuse.
|
||||||
|
*/
|
||||||
|
private List<LoreNode> collectDescendants(String rootId) {
|
||||||
|
List<LoreNode> result = new ArrayList<>();
|
||||||
|
List<String> frontier = new ArrayList<>();
|
||||||
|
frontier.add(rootId);
|
||||||
|
while (!frontier.isEmpty()) {
|
||||||
|
List<String> nextFrontier = new ArrayList<>();
|
||||||
|
for (String parentId : frontier) {
|
||||||
|
for (LoreNode child : loreNodeRepository.findByParentId(parentId)) {
|
||||||
|
result.add(child);
|
||||||
|
nextFrontier.add(child.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
frontier = nextFrontier;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
package com.loremind.application.lorecontext;
|
package com.loremind.application.lorecontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.lorecontext.Lore;
|
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.ports.LoreNodeRepository;
|
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
||||||
import com.loremind.domain.lorecontext.ports.LoreRepository;
|
import com.loremind.domain.lorecontext.ports.LoreRepository;
|
||||||
import com.loremind.domain.lorecontext.ports.PageRepository;
|
import com.loremind.domain.lorecontext.ports.PageRepository;
|
||||||
|
import com.loremind.domain.lorecontext.ports.TemplateRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -26,15 +33,28 @@ public class LoreService {
|
|||||||
private final LoreRepository loreRepository;
|
private final LoreRepository loreRepository;
|
||||||
private final LoreNodeRepository loreNodeRepository;
|
private final LoreNodeRepository loreNodeRepository;
|
||||||
private final PageRepository pageRepository;
|
private final PageRepository pageRepository;
|
||||||
|
private final TemplateRepository templateRepository;
|
||||||
|
private final CampaignRepository campaignRepository;
|
||||||
|
|
||||||
public LoreService(LoreRepository loreRepository,
|
public LoreService(LoreRepository loreRepository,
|
||||||
LoreNodeRepository loreNodeRepository,
|
LoreNodeRepository loreNodeRepository,
|
||||||
PageRepository pageRepository) {
|
PageRepository pageRepository,
|
||||||
|
TemplateRepository templateRepository,
|
||||||
|
CampaignRepository campaignRepository) {
|
||||||
this.loreRepository = loreRepository;
|
this.loreRepository = loreRepository;
|
||||||
this.loreNodeRepository = loreNodeRepository;
|
this.loreNodeRepository = loreNodeRepository;
|
||||||
this.pageRepository = pageRepository;
|
this.pageRepository = pageRepository;
|
||||||
|
this.templateRepository = templateRepository;
|
||||||
|
this.campaignRepository = campaignRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compte des entités qui seront supprimées / détachées en cascade si le Lore
|
||||||
|
* est effacé. `detachedCampaigns` : campagnes qui perdront leur référence à
|
||||||
|
* ce Lore (leur loreId sera nullé) mais resteront présentes.
|
||||||
|
*/
|
||||||
|
public record DeletionImpact(int folders, int pages, int templates, int detachedCampaigns) {}
|
||||||
|
|
||||||
public Lore createLore(String name, String description) {
|
public Lore createLore(String name, String description) {
|
||||||
Lore lore = Lore.builder()
|
Lore lore = Lore.builder()
|
||||||
.name(name)
|
.name(name)
|
||||||
@@ -76,14 +96,61 @@ public class LoreService {
|
|||||||
if (existingLore.isEmpty()) {
|
if (existingLore.isEmpty()) {
|
||||||
throw new IllegalArgumentException("Lore non trouvé avec l'ID: " + id);
|
throw new IllegalArgumentException("Lore non trouvé avec l'ID: " + id);
|
||||||
}
|
}
|
||||||
|
|
||||||
Lore lore = existingLore.get();
|
Lore lore = existingLore.get();
|
||||||
lore.setName(name);
|
lore.setName(name);
|
||||||
lore.setDescription(description);
|
lore.setDescription(description);
|
||||||
return loreRepository.save(lore);
|
return loreRepository.save(lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calcule l'impact d'une suppression de Lore en cascade : dossiers + pages
|
||||||
|
* + templates supprimés, et campagnes qui seront détachées (loreId → null
|
||||||
|
* sans être supprimées, car une campagne peut vivre sans univers).
|
||||||
|
*/
|
||||||
|
public DeletionImpact getDeletionImpact(String id) {
|
||||||
|
int folders = (int) loreNodeRepository.countByLoreId(id);
|
||||||
|
int pages = (int) pageRepository.countByLoreId(id);
|
||||||
|
int templates = templateRepository.findByLoreId(id).size();
|
||||||
|
int detached = countCampaignsReferencingLore(id);
|
||||||
|
return new DeletionImpact(folders, pages, templates, detached);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Supprime le Lore et toutes ses entités dépendantes (dossiers, pages, templates).
|
||||||
|
* Les campagnes qui référençaient ce Lore sont conservées — leur loreId est
|
||||||
|
* mis à null (une campagne peut légitimement exister sans univers associé).
|
||||||
|
* Opération transactionnelle : atomique.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
public void deleteLore(String id) {
|
public void deleteLore(String id) {
|
||||||
|
// Pages d'abord : elles référencent nodeId ET loreId, on les supprime
|
||||||
|
// globalement via loreId pour éviter d'en rater une rattachée à un
|
||||||
|
// node orphelin (ne devrait pas arriver, mais ceinture+bretelles).
|
||||||
|
for (Page page : pageRepository.findByLoreId(id)) {
|
||||||
|
pageRepository.deleteById(page.getId());
|
||||||
|
}
|
||||||
|
for (LoreNode node : loreNodeRepository.findByLoreId(id)) {
|
||||||
|
loreNodeRepository.deleteById(node.getId());
|
||||||
|
}
|
||||||
|
for (Template template : templateRepository.findByLoreId(id)) {
|
||||||
|
templateRepository.deleteById(template.getId());
|
||||||
|
}
|
||||||
|
// Détache les campagnes : on garde la campagne, on nulle juste la référence.
|
||||||
|
for (Campaign campaign : campaignRepository.findAll()) {
|
||||||
|
if (id.equals(campaign.getLoreId())) {
|
||||||
|
campaign.setLoreId(null);
|
||||||
|
campaignRepository.save(campaign);
|
||||||
|
}
|
||||||
|
}
|
||||||
loreRepository.deleteById(id);
|
loreRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private int countCampaignsReferencingLore(String id) {
|
||||||
|
int count = 0;
|
||||||
|
for (Campaign campaign : campaignRepository.findAll()) {
|
||||||
|
if (id.equals(campaign.getLoreId())) count++;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,18 @@ public class Campaign {
|
|||||||
*/
|
*/
|
||||||
private String loreId;
|
private String loreId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Référence faible (weak reference) vers un GameSystem.
|
||||||
|
* Nullable : une campagne peut être "générique" (pas de système de JDR déclaré).
|
||||||
|
* Weak reference pour respecter la séparation des Bounded Contexts.
|
||||||
|
*/
|
||||||
|
private String gameSystemId;
|
||||||
|
|
||||||
public boolean isLinkedToLore() {
|
public boolean isLinkedToLore() {
|
||||||
return this.loreId != null && !this.loreId.isBlank();
|
return this.loreId != null && !this.loreId.isBlank();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isLinkedToGameSystem() {
|
||||||
|
return this.gameSystemId != null && !this.gameSystemId.isBlank();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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).
|
||||||
|
* <p>
|
||||||
|
* Scope strict PJ : les PNJ restent dans le Lore (pages templatées) ou
|
||||||
|
* dans les scènes elles-mêmes. Si le besoin de PNJ spécifiques à une
|
||||||
|
* campagne remonte, on étendra l'entité (ex: type enum PJ/PNJ).
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class Character {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contenu libre en markdown — stats + backstory + notes. Nullable à la création,
|
||||||
|
* renseigné progressivement par le MJ.
|
||||||
|
*/
|
||||||
|
private String markdownContent;
|
||||||
|
|
||||||
|
/** Référence vers la Campaign parente. */
|
||||||
|
private String campaignId;
|
||||||
|
|
||||||
|
/** Ordre d'affichage dans la liste des PJ de la campagne. */
|
||||||
|
private int order;
|
||||||
|
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie pour la persistance des fiches de personnages (PJ).
|
||||||
|
*/
|
||||||
|
public interface CharacterRepository {
|
||||||
|
|
||||||
|
Character save(Character character);
|
||||||
|
|
||||||
|
Optional<Character> findById(String id);
|
||||||
|
|
||||||
|
List<Character> findByCampaignId(String campaignId);
|
||||||
|
|
||||||
|
void deleteById(String id);
|
||||||
|
|
||||||
|
boolean existsById(String id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.loremind.domain.conversationcontext;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Agregat d'une conversation de chat IA persistee.
|
||||||
|
*
|
||||||
|
* Une conversation est ancree sur exactement un niveau de contexte :
|
||||||
|
* - un Lore (optionnellement une page precise)
|
||||||
|
* - une Campagne (optionnellement une entite narrative : arc/chapitre/scene)
|
||||||
|
*
|
||||||
|
* C'est cet ancrage qui permet au drawer de filtrer les conversations
|
||||||
|
* a afficher dans la sidebar selon l'ecran en cours.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class Conversation {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String title;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
/** Un seul des deux est non-null. */
|
||||||
|
private String loreId;
|
||||||
|
private String campaignId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Type d'entite focus, null si la conversation est ancree au niveau
|
||||||
|
* Lore/Campagne racine (pas sur une page/scene precise).
|
||||||
|
* Valeurs : "page", "arc", "chapter", "scene", "character".
|
||||||
|
*/
|
||||||
|
private String entityType;
|
||||||
|
private String entityId;
|
||||||
|
|
||||||
|
@Builder.Default
|
||||||
|
private List<ConversationMessage> messages = new ArrayList<>();
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.loremind.domain.conversationcontext;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un message persiste d'une conversation.
|
||||||
|
*
|
||||||
|
* Distinct de {@link com.loremind.domain.generationcontext.ChatMessage}
|
||||||
|
* qui reste un simple record role+content pour le streaming LLM. Ici
|
||||||
|
* on ajoute id et horodatage, necessaires pour l'affichage / l'ordre.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class ConversationMessage {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
/** "user" | "assistant" | "system". */
|
||||||
|
private String role;
|
||||||
|
private String content;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.loremind.domain.conversationcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.conversationcontext.Conversation;
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de persistance des conversations de chat IA.
|
||||||
|
*
|
||||||
|
* Les methodes de lecture par contexte acceptent des filtres nullables :
|
||||||
|
* - `loreId` OU `campaignId` doit etre non-null (mais pas les deux)
|
||||||
|
* - `entityType` + `entityId` : soit tous les deux null (niveau racine),
|
||||||
|
* soit tous les deux non-null (niveau entite precise).
|
||||||
|
*/
|
||||||
|
public interface ConversationRepository {
|
||||||
|
|
||||||
|
Conversation save(Conversation conversation);
|
||||||
|
|
||||||
|
Optional<Conversation> findById(String id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liste les conversations filtrees par contexte strict, triees par
|
||||||
|
* updatedAt desc. Les messages ne sont PAS chargees (liste vide) pour
|
||||||
|
* garder la payload legere — la sidebar n'affiche que les titres.
|
||||||
|
*/
|
||||||
|
List<Conversation> findByContext(
|
||||||
|
String loreId,
|
||||||
|
String campaignId,
|
||||||
|
String entityType,
|
||||||
|
String entityId);
|
||||||
|
|
||||||
|
void deleteById(String id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ajoute un message a une conversation existante. Met a jour updatedAt
|
||||||
|
* de la conversation parent. Renvoie le message persiste (avec id + ts).
|
||||||
|
*/
|
||||||
|
ConversationMessage appendMessage(String conversationId, ConversationMessage message);
|
||||||
|
|
||||||
|
/** Rename atomique — ne touche pas aux messages. */
|
||||||
|
void updateTitle(String conversationId, String title);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.loremind.domain.conversationcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port : generation d'un titre court a partir des premiers echanges d'une
|
||||||
|
* conversation. Implemente via un appel Brain /summarize/conversation-title.
|
||||||
|
*/
|
||||||
|
public interface ConversationTitleGenerator {
|
||||||
|
|
||||||
|
/** Renvoie un titre en francais (4-7 mots max). Jamais null ni vide. */
|
||||||
|
String generate(List<ConversationMessage> firstMessages);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entité de domaine représentant un GameSystem (système de JDR).
|
||||||
|
* <p>
|
||||||
|
* Porte les règles d'un système (D&D, Nimble, Pathfinder, homebrew...) sous forme
|
||||||
|
* 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>
|
||||||
|
* {@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.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class GameSystem {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String name;
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
||||||
|
private String rulesMarkdown;
|
||||||
|
|
||||||
|
/** Auteur déclaré — futur marketplace. Nullable. */
|
||||||
|
private String author;
|
||||||
|
|
||||||
|
/** Flag de partage — futur marketplace. False par défaut. */
|
||||||
|
private boolean isPublic;
|
||||||
|
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Intent de génération utilisé pour sélectionner les sections d'un GameSystem
|
||||||
|
* à injecter dans le prompt IA.
|
||||||
|
* <p>
|
||||||
|
* Chaque intent porte une liste d'alias (case-insensitive, comparaison par
|
||||||
|
* {@code contains}) utilisée pour matcher les titres H2 du markdown de règles.
|
||||||
|
* <p>
|
||||||
|
* MVP : mapping codé en dur. Évoluera vers un mapping configurable par
|
||||||
|
* l'utilisateur dans l'éditeur de GameSystem (futur marketplace).
|
||||||
|
*/
|
||||||
|
public enum GenerationIntent {
|
||||||
|
|
||||||
|
/** Scène (combat / rencontre) : règles de résolution + format de stat block. */
|
||||||
|
SCENE(Set.of("combat", "monstre", "monster")),
|
||||||
|
|
||||||
|
/** Chapitre (segment narratif) : règles de combat + archétypes pour PNJ. */
|
||||||
|
CHAPTER(Set.of("combat", "classe", "class")),
|
||||||
|
|
||||||
|
/** Arc (structure narrative longue) : pas de règles spécifiques — toutes. */
|
||||||
|
ARC(Set.of()),
|
||||||
|
|
||||||
|
/** Fallback : toutes les sections (intent inconnu). */
|
||||||
|
GENERIC(Set.of());
|
||||||
|
|
||||||
|
private final Set<String> sectionAliases;
|
||||||
|
|
||||||
|
GenerationIntent(Set<String> sectionAliases) {
|
||||||
|
this.sectionAliases = sectionAliases;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<String> getSectionAliases() {
|
||||||
|
return sectionAliases;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True si l'intent veut toutes les sections (pas de filtre). */
|
||||||
|
public boolean matchesAllSections() {
|
||||||
|
return sectionAliases.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mappe un entityType de NarrativeEntityContext ("arc"/"chapter"/"scene")
|
||||||
|
* vers l'intent correspondant. Tout le reste (null, inconnu) tombe sur GENERIC.
|
||||||
|
*/
|
||||||
|
public static GenerationIntent fromNarrativeEntityType(String entityType) {
|
||||||
|
if (entityType == null) return GENERIC;
|
||||||
|
return switch (entityType.toLowerCase()) {
|
||||||
|
case "scene" -> SCENE;
|
||||||
|
case "chapter" -> CHAPTER;
|
||||||
|
case "arc" -> ARC;
|
||||||
|
default -> GENERIC;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie pour la persistance des GameSystems.
|
||||||
|
*/
|
||||||
|
public interface GameSystemRepository {
|
||||||
|
|
||||||
|
GameSystem save(GameSystem gameSystem);
|
||||||
|
|
||||||
|
Optional<GameSystem> findById(String id);
|
||||||
|
|
||||||
|
List<GameSystem> findAll();
|
||||||
|
|
||||||
|
void deleteById(String id);
|
||||||
|
|
||||||
|
boolean existsById(String id);
|
||||||
|
|
||||||
|
List<GameSystem> searchByName(String query);
|
||||||
|
}
|
||||||
@@ -30,6 +30,22 @@ public class CampaignStructuralContext {
|
|||||||
String campaignName;
|
String campaignName;
|
||||||
String campaignDescription;
|
String campaignDescription;
|
||||||
@Singular List<ArcSummary> arcs;
|
@Singular List<ArcSummary> arcs;
|
||||||
|
/** Personnages joueurs (PJ) de la campagne. Vide si aucun. */
|
||||||
|
@Singular List<CharacterSummary> characters;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résumé d'un PJ : nom + snippet court du markdown.
|
||||||
|
* Pas le markdown complet pour maîtriser le coût token (chaque campagne
|
||||||
|
* peut avoir 4-6 PJ × potentiellement 1-2k tokens/fiche = trop lourd).
|
||||||
|
* La fiche complète n'est injectée que si le PJ est l'entité focus
|
||||||
|
* (via NarrativeEntityContext, entity_type="character").
|
||||||
|
*/
|
||||||
|
@Value
|
||||||
|
@Builder
|
||||||
|
public static class CharacterSummary {
|
||||||
|
String name;
|
||||||
|
String snippet;
|
||||||
|
}
|
||||||
|
|
||||||
/** Résumé d'un arc : nom + description courte + ses chapitres. */
|
/** Résumé d'un arc : nom + description courte + ses chapitres. */
|
||||||
@Value
|
@Value
|
||||||
|
|||||||
@@ -39,4 +39,10 @@ public class ChatRequest {
|
|||||||
|
|
||||||
/** Optionnel : entité narrative en cours d'édition (arc/chapter/scene). */
|
/** Optionnel : entité narrative en cours d'édition (arc/chapter/scene). */
|
||||||
NarrativeEntityContext narrativeEntity;
|
NarrativeEntityContext narrativeEntity;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optionnel : règles du système de JDR de la campagne (filtrées par intent).
|
||||||
|
* Null si la campagne n'a pas de GameSystem associé. Campagne uniquement au MVP.
|
||||||
|
*/
|
||||||
|
GameSystemContext gameSystemContext;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Instantané d'occupation de la fenêtre de contexte à l'instant t du chat.
|
||||||
|
* <p>
|
||||||
|
* Émis une fois par tour de chat (juste avant le streaming des tokens) pour
|
||||||
|
* alimenter la jauge de contexte côté frontend. Les unités sont des tokens
|
||||||
|
* (approximés via tiktoken côté Brain — ±10% vs le tokenizer réel du modèle).
|
||||||
|
*
|
||||||
|
* @param system tokens consommés par le system prompt (contextes Lore/campagne injectés)
|
||||||
|
* @param history tokens consommés par l'historique de la conversation (hors dernier message)
|
||||||
|
* @param current tokens du dernier message utilisateur en attente de réponse
|
||||||
|
* @param max taille maximale configurée de la fenêtre de contexte
|
||||||
|
*/
|
||||||
|
public record ChatUsage(int system, int history, int current, int max) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Value;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Value Object représentant les règles de JDR injectées dans un prompt IA.
|
||||||
|
* <p>
|
||||||
|
* Contient uniquement les sections pertinentes pour l'intent de génération
|
||||||
|
* en cours (sélection effectuée par GameSystemContextBuilder). Les sections
|
||||||
|
* sont indexées par leur titre H2 original (ex : "Combat", "Classes").
|
||||||
|
*/
|
||||||
|
@Value
|
||||||
|
@Builder
|
||||||
|
public class GameSystemContext {
|
||||||
|
|
||||||
|
/** Nom du système de JDR (ex : "Nimble", "D&D 5.1 SRD"). */
|
||||||
|
String systemName;
|
||||||
|
|
||||||
|
/** Description courte du système (nullable). */
|
||||||
|
String systemDescription;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections de règles pertinentes, indexées par titre H2.
|
||||||
|
* Vide si le GameSystem n'a aucune règle ou si aucune section ne matche l'intent.
|
||||||
|
*/
|
||||||
|
Map<String, String> sections;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.domain.generationcontext.ports;
|
package com.loremind.domain.generationcontext.ports;
|
||||||
|
|
||||||
import com.loremind.domain.generationcontext.ChatRequest;
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
@@ -26,6 +27,10 @@ public interface AiChatProvider {
|
|||||||
* HTTP côté controller SSE).
|
* HTTP côté controller SSE).
|
||||||
*
|
*
|
||||||
* @param request messages + contexte Lore
|
* @param request messages + contexte Lore
|
||||||
|
* @param onUsage invoqué une fois au début du stream avec le bilan
|
||||||
|
* d'occupation de la fenêtre de contexte (tokens system /
|
||||||
|
* history / current / max). Peut ne jamais être invoqué
|
||||||
|
* si le provider ne supporte pas le comptage.
|
||||||
* @param onToken invoqué à chaque token reçu du LLM (peut être appelé
|
* @param onToken invoqué à chaque token reçu du LLM (peut être appelé
|
||||||
* de nombreuses fois)
|
* de nombreuses fois)
|
||||||
* @param onComplete invoqué une fois le stream terminé avec succès
|
* @param onComplete invoqué une fois le stream terminé avec succès
|
||||||
@@ -34,6 +39,7 @@ public interface AiChatProvider {
|
|||||||
*/
|
*/
|
||||||
void streamChat(
|
void streamChat(
|
||||||
ChatRequest request,
|
ChatRequest request,
|
||||||
|
Consumer<ChatUsage> onUsage,
|
||||||
Consumer<String> onToken,
|
Consumer<String> onToken,
|
||||||
Runnable onComplete,
|
Runnable onComplete,
|
||||||
Consumer<Throwable> onError
|
Consumer<Throwable> onError
|
||||||
|
|||||||
@@ -1,16 +1,7 @@
|
|||||||
package com.loremind.infrastructure.ai;
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
|
||||||
import com.loremind.domain.generationcontext.ChatMessage;
|
|
||||||
import com.loremind.domain.generationcontext.ChatRequest;
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
import com.loremind.domain.generationcontext.LoreStructuralContext.PageSummary;
|
|
||||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
|
||||||
import com.loremind.domain.generationcontext.PageContext;
|
|
||||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||||
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
@@ -22,25 +13,21 @@ import org.springframework.web.reactive.function.client.WebClient;
|
|||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adapter de sortie (Architecture Hexagonale) : implémente AiChatProvider
|
* Adapter de sortie (Architecture Hexagonale) : implémente AiChatProvider
|
||||||
* en appelant le Brain Python via WebClient + SSE (Server-Sent Events).
|
* en appelant le Brain Python via WebClient + SSE (Server-Sent Events).
|
||||||
* <p>
|
* <p>
|
||||||
* Responsabilités :
|
* Responsabilités (après extraction) :
|
||||||
* 1. Traduire ChatRequest (domaine) -> JSON attendu par /chat/stream.
|
* 1. Transport HTTP + consommation du flux SSE.
|
||||||
* Sérialise lore_context, page_context, campaign_context et
|
* 2. Dispatch des évènements SSE (data / done / error / usage).
|
||||||
* narrative_entity de façon conditionnelle selon le scénario d'appel
|
* 3. Traduction des erreurs techniques en AiProviderException.
|
||||||
* (chat Lore / chat Lore focalisé page / chat Campagne / chat Campagne
|
* <p>
|
||||||
* focalisé arc-chapter-scene).
|
* Les responsabilités auxiliaires sont déléguées :
|
||||||
* 2. Consommer le flux SSE token par token.
|
* - Construction du payload JSON : {@link BrainChatPayloadBuilder}.
|
||||||
* 3. Invoquer onToken / onComplete / onError au bon moment.
|
* - Parsing des payloads SSE : {@link BrainSseParser}.
|
||||||
* 4. Traduire toute erreur technique en AiProviderException.
|
|
||||||
* <p>
|
* <p>
|
||||||
* Le domaine ne voit JAMAIS WebClient, Flux, ni la moindre URL.
|
* Le domaine ne voit JAMAIS WebClient, Flux, ni la moindre URL.
|
||||||
*/
|
*/
|
||||||
@@ -52,21 +39,28 @@ public class BrainAiChatClient implements AiChatProvider {
|
|||||||
new ParameterizedTypeReference<>() {};
|
new ParameterizedTypeReference<>() {};
|
||||||
|
|
||||||
private final WebClient webClient;
|
private final WebClient webClient;
|
||||||
|
private final BrainChatPayloadBuilder payloadBuilder;
|
||||||
|
private final BrainSseParser sseParser;
|
||||||
|
|
||||||
public BrainAiChatClient(
|
public BrainAiChatClient(
|
||||||
WebClient.Builder builder,
|
WebClient.Builder builder,
|
||||||
@Value("${brain.base-url}") String baseUrl) {
|
@Value("${brain.base-url}") String baseUrl,
|
||||||
|
BrainChatPayloadBuilder payloadBuilder,
|
||||||
|
BrainSseParser sseParser) {
|
||||||
this.webClient = builder.baseUrl(baseUrl).build();
|
this.webClient = builder.baseUrl(baseUrl).build();
|
||||||
|
this.payloadBuilder = payloadBuilder;
|
||||||
|
this.sseParser = sseParser;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void streamChat(
|
public void streamChat(
|
||||||
ChatRequest request,
|
ChatRequest request,
|
||||||
|
Consumer<ChatUsage> onUsage,
|
||||||
Consumer<String> onToken,
|
Consumer<String> onToken,
|
||||||
Runnable onComplete,
|
Runnable onComplete,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
|
|
||||||
Map<String, Object> payload = toPayload(request);
|
Map<String, Object> payload = payloadBuilder.build(request);
|
||||||
|
|
||||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||||
.uri(CHAT_STREAM_PATH)
|
.uri(CHAT_STREAM_PATH)
|
||||||
@@ -81,7 +75,7 @@ public class BrainAiChatClient implements AiChatProvider {
|
|||||||
// au contrat synchrone du port. L'appelant choisit le thread.
|
// au contrat synchrone du port. L'appelant choisit le thread.
|
||||||
flux
|
flux
|
||||||
.timeout(Duration.ofSeconds(120))
|
.timeout(Duration.ofSeconds(120))
|
||||||
.doOnNext(sse -> handleEvent(sse, onToken, onError))
|
.doOnNext(sse -> handleEvent(sse, onUsage, onToken, onError))
|
||||||
.blockLast();
|
.blockLast();
|
||||||
onComplete.run();
|
onComplete.run();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -90,12 +84,13 @@ public class BrainAiChatClient implements AiChatProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Dispatch selon le type d'événement SSE (data par défaut, done, error). */
|
/** Dispatch selon le type d'évènement SSE (data par défaut, done, error, usage). */
|
||||||
private void handleEvent(
|
private void handleEvent(
|
||||||
ServerSentEvent<String> sse,
|
ServerSentEvent<String> sse,
|
||||||
|
Consumer<ChatUsage> onUsage,
|
||||||
Consumer<String> onToken,
|
Consumer<String> onToken,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
String event = sse.event(); // null si pas d'event: xxx -> c'est un data par défaut
|
String event = sse.event(); // null si pas d'event: xxx -> data par défaut
|
||||||
String data = sse.data();
|
String data = sse.data();
|
||||||
|
|
||||||
if ("error".equals(event)) {
|
if ("error".equals(event)) {
|
||||||
@@ -104,197 +99,17 @@ public class BrainAiChatClient implements AiChatProvider {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("done".equals(event)) {
|
if ("done".equals(event)) {
|
||||||
return; // la fin est gérée par blockLast + onComplete
|
return; // fin gérée par blockLast + onComplete
|
||||||
}
|
}
|
||||||
// Défaut : événement data avec JSON {"token":"..."}.
|
if ("usage".equals(event)) {
|
||||||
String token = extractToken(data);
|
ChatUsage usage = sseParser.parseUsage(data);
|
||||||
|
if (usage != null) onUsage.accept(usage);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Défaut : évènement data avec JSON {"token":"..."}.
|
||||||
|
String token = sseParser.parseToken(data);
|
||||||
if (token != null && !token.isEmpty()) {
|
if (token != null && !token.isEmpty()) {
|
||||||
onToken.accept(token);
|
onToken.accept(token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse minimaliste du JSON {"token":"..."} sans pull Jackson ici.
|
|
||||||
* Si le format se complexifie, on remplacera par un DTO Jackson.
|
|
||||||
*/
|
|
||||||
private String extractToken(String json) {
|
|
||||||
if (json == null) return null;
|
|
||||||
int idx = json.indexOf("\"token\"");
|
|
||||||
if (idx < 0) return null;
|
|
||||||
int colon = json.indexOf(':', idx);
|
|
||||||
int firstQuote = json.indexOf('"', colon + 1);
|
|
||||||
int lastQuote = json.lastIndexOf('"');
|
|
||||||
if (firstQuote < 0 || lastQuote <= firstQuote) return null;
|
|
||||||
return json.substring(firstQuote + 1, lastQuote)
|
|
||||||
.replace("\\n", "\n")
|
|
||||||
.replace("\\\"", "\"")
|
|
||||||
.replace("\\\\", "\\");
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Construction du payload JSON vers le Brain -------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Construit le payload JSON. Chaque contexte optionnel est omis s'il est
|
|
||||||
* null, pour s'aligner sur le schéma Pydantic côté Brain (champs
|
|
||||||
* Optional qui restent absents du dict transmis au LLM).
|
|
||||||
*/
|
|
||||||
private Map<String, Object> toPayload(ChatRequest request) {
|
|
||||||
Map<String, Object> root = new LinkedHashMap<>();
|
|
||||||
root.put("messages", request.getMessages().stream()
|
|
||||||
.map(this::messageToMap)
|
|
||||||
.collect(Collectors.toList()));
|
|
||||||
|
|
||||||
if (request.getLoreContext() != null) {
|
|
||||||
root.put("lore_context", loreContextToMap(request.getLoreContext()));
|
|
||||||
}
|
|
||||||
if (request.getPageContext() != null) {
|
|
||||||
root.put("page_context", pageContextToMap(request.getPageContext()));
|
|
||||||
}
|
|
||||||
if (request.getCampaignContext() != null) {
|
|
||||||
root.put("campaign_context", campaignContextToMap(request.getCampaignContext()));
|
|
||||||
}
|
|
||||||
if (request.getNarrativeEntity() != null) {
|
|
||||||
root.put("narrative_entity", narrativeEntityToMap(request.getNarrativeEntity()));
|
|
||||||
}
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> messageToMap(ChatMessage m) {
|
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
|
||||||
map.put("role", m.role());
|
|
||||||
map.put("content", m.content());
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> loreContextToMap(LoreStructuralContext ctx) {
|
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
|
||||||
map.put("lore_name", ctx.getLoreName());
|
|
||||||
map.put("lore_description", ctx.getLoreDescription());
|
|
||||||
|
|
||||||
Map<String, Object> foldersMap = new LinkedHashMap<>();
|
|
||||||
for (Map.Entry<String, List<PageSummary>> e : ctx.getFolders().entrySet()) {
|
|
||||||
foldersMap.put(e.getKey(), e.getValue().stream()
|
|
||||||
.map(this::pageSummaryToMap)
|
|
||||||
.collect(Collectors.toList()));
|
|
||||||
}
|
|
||||||
map.put("folders", foldersMap);
|
|
||||||
map.put("tags", ctx.getTags());
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> pageSummaryToMap(PageSummary ps) {
|
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
|
||||||
map.put("title", ps.getTitle());
|
|
||||||
map.put("template_name", ps.getTemplateName());
|
|
||||||
// values/tags/related_page_titles ne sont sérialisés que s'ils contiennent
|
|
||||||
// de l'info — payload réseau plus léger quand la page est vierge.
|
|
||||||
if (ps.getValues() != null && !ps.getValues().isEmpty()) {
|
|
||||||
map.put("values", ps.getValues());
|
|
||||||
}
|
|
||||||
if (ps.getTags() != null && !ps.getTags().isEmpty()) {
|
|
||||||
map.put("tags", ps.getTags());
|
|
||||||
}
|
|
||||||
if (ps.getRelatedPageTitles() != null && !ps.getRelatedPageTitles().isEmpty()) {
|
|
||||||
map.put("related_page_titles", ps.getRelatedPageTitles());
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> pageContextToMap(PageContext pc) {
|
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
|
||||||
map.put("title", pc.getTitle());
|
|
||||||
map.put("template_name", pc.getTemplateName());
|
|
||||||
map.put("template_fields", pc.getTemplateFields());
|
|
||||||
map.put("values", pc.getValues());
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> campaignContextToMap(CampaignStructuralContext ctx) {
|
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
|
||||||
map.put("campaign_name", ctx.getCampaignName());
|
|
||||||
map.put("campaign_description", ctx.getCampaignDescription());
|
|
||||||
map.put("arcs", ctx.getArcs().stream()
|
|
||||||
.map(this::arcSummaryToMap)
|
|
||||||
.collect(Collectors.toList()));
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper generic pour serialiser les entites structurelles (Arc/Chapter/Scene)
|
|
||||||
* avec name, description et illustration_count conditionnel.
|
|
||||||
*/
|
|
||||||
private <T> Map<String, Object> structuralSummaryToMap(
|
|
||||||
T entity,
|
|
||||||
java.util.function.Function<T, String> nameExtractor,
|
|
||||||
java.util.function.Function<T, String> descriptionExtractor,
|
|
||||||
java.util.function.Function<T, Integer> illustrationCountExtractor,
|
|
||||||
java.util.function.BiConsumer<Map<String, Object>, T> childSerializer) {
|
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
|
||||||
map.put("name", nameExtractor.apply(entity));
|
|
||||||
map.put("description", descriptionExtractor.apply(entity));
|
|
||||||
// Envoye au Python pour enrichir le prompt ("N illustrations attachees").
|
|
||||||
// Serialise uniquement si > 0 pour economiser le payload sur les entites sans images.
|
|
||||||
if (illustrationCountExtractor.apply(entity) > 0) {
|
|
||||||
map.put("illustration_count", illustrationCountExtractor.apply(entity));
|
|
||||||
}
|
|
||||||
childSerializer.accept(map, entity);
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> arcSummaryToMap(ArcSummary a) {
|
|
||||||
return structuralSummaryToMap(
|
|
||||||
a,
|
|
||||||
ArcSummary::getName,
|
|
||||||
ArcSummary::getDescription,
|
|
||||||
ArcSummary::getIllustrationCount,
|
|
||||||
(map, arc) -> map.put("chapters", arc.getChapters().stream()
|
|
||||||
.map(this::chapterSummaryToMap)
|
|
||||||
.collect(Collectors.toList())));
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> chapterSummaryToMap(ChapterSummary c) {
|
|
||||||
return structuralSummaryToMap(
|
|
||||||
c,
|
|
||||||
ChapterSummary::getName,
|
|
||||||
ChapterSummary::getDescription,
|
|
||||||
ChapterSummary::getIllustrationCount,
|
|
||||||
(map, chapter) -> map.put("scenes", chapter.getScenes().stream()
|
|
||||||
.map(this::sceneSummaryToMap)
|
|
||||||
.collect(Collectors.toList())));
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> sceneSummaryToMap(SceneSummary s) {
|
|
||||||
return structuralSummaryToMap(
|
|
||||||
s,
|
|
||||||
SceneSummary::getName,
|
|
||||||
SceneSummary::getDescription,
|
|
||||||
SceneSummary::getIllustrationCount,
|
|
||||||
(map, scene) -> {
|
|
||||||
// Branches narratives : serialise uniquement si presentes, pour garder
|
|
||||||
// un payload leger sur les scenes lineaires classiques.
|
|
||||||
if (s.getBranches() != null && !s.getBranches().isEmpty()) {
|
|
||||||
map.put("branches", s.getBranches().stream()
|
|
||||||
.map(this::branchHintToMap)
|
|
||||||
.collect(Collectors.toList()));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> branchHintToMap(BranchHint b) {
|
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
|
||||||
map.put("label", b.getLabel());
|
|
||||||
map.put("target_scene_name", b.getTargetSceneName());
|
|
||||||
if (b.getCondition() != null && !b.getCondition().isBlank()) {
|
|
||||||
map.put("condition", b.getCondition());
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> narrativeEntityToMap(NarrativeEntityContext ne) {
|
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
|
||||||
map.put("entity_type", ne.getEntityType());
|
|
||||||
map.put("title", ne.getTitle());
|
|
||||||
map.put("fields", ne.getFields());
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,222 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||||
|
import com.loremind.domain.generationcontext.ChatMessage;
|
||||||
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
|
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||||
|
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||||
|
import com.loremind.domain.generationcontext.LoreStructuralContext.PageSummary;
|
||||||
|
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||||
|
import com.loremind.domain.generationcontext.PageContext;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.function.BiConsumer;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper d'infrastructure : traduit un ChatRequest (domaine) vers le dict JSON
|
||||||
|
* attendu par le Brain Python (/chat/stream).
|
||||||
|
* <p>
|
||||||
|
* Extrait de BrainAiChatClient pour isoler la responsabilité "sérialisation
|
||||||
|
* de payload" (SRP) — le client HTTP se concentre désormais uniquement sur le
|
||||||
|
* transport et le streaming SSE.
|
||||||
|
* <p>
|
||||||
|
* Chaque contexte optionnel (lore, page, campaign, entité narrative) est omis
|
||||||
|
* si null, pour s'aligner sur le schéma Pydantic (champs Optional absents).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainChatPayloadBuilder {
|
||||||
|
|
||||||
|
public Map<String, Object> build(ChatRequest request) {
|
||||||
|
Map<String, Object> root = new LinkedHashMap<>();
|
||||||
|
root.put("messages", request.getMessages().stream()
|
||||||
|
.map(this::messageToMap)
|
||||||
|
.collect(Collectors.toList()));
|
||||||
|
|
||||||
|
if (request.getLoreContext() != null) {
|
||||||
|
root.put("lore_context", loreContextToMap(request.getLoreContext()));
|
||||||
|
}
|
||||||
|
if (request.getPageContext() != null) {
|
||||||
|
root.put("page_context", pageContextToMap(request.getPageContext()));
|
||||||
|
}
|
||||||
|
if (request.getCampaignContext() != null) {
|
||||||
|
root.put("campaign_context", campaignContextToMap(request.getCampaignContext()));
|
||||||
|
}
|
||||||
|
if (request.getNarrativeEntity() != null) {
|
||||||
|
root.put("narrative_entity", narrativeEntityToMap(request.getNarrativeEntity()));
|
||||||
|
}
|
||||||
|
if (request.getGameSystemContext() != null) {
|
||||||
|
root.put("game_system_context", gameSystemContextToMap(request.getGameSystemContext()));
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> gameSystemContextToMap(GameSystemContext gs) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("system_name", gs.getSystemName());
|
||||||
|
if (gs.getSystemDescription() != null && !gs.getSystemDescription().isBlank()) {
|
||||||
|
map.put("system_description", gs.getSystemDescription());
|
||||||
|
}
|
||||||
|
map.put("sections", gs.getSections() != null ? gs.getSections() : Map.of());
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> messageToMap(ChatMessage m) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("role", m.role());
|
||||||
|
map.put("content", m.content());
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> loreContextToMap(LoreStructuralContext ctx) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("lore_name", ctx.getLoreName());
|
||||||
|
map.put("lore_description", ctx.getLoreDescription());
|
||||||
|
|
||||||
|
Map<String, Object> foldersMap = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<String, List<PageSummary>> e : ctx.getFolders().entrySet()) {
|
||||||
|
foldersMap.put(e.getKey(), e.getValue().stream()
|
||||||
|
.map(this::pageSummaryToMap)
|
||||||
|
.collect(Collectors.toList()));
|
||||||
|
}
|
||||||
|
map.put("folders", foldersMap);
|
||||||
|
map.put("tags", ctx.getTags());
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> pageSummaryToMap(PageSummary ps) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("title", ps.getTitle());
|
||||||
|
map.put("template_name", ps.getTemplateName());
|
||||||
|
// values/tags/related_page_titles : omis si vides pour alléger le payload.
|
||||||
|
if (ps.getValues() != null && !ps.getValues().isEmpty()) {
|
||||||
|
map.put("values", ps.getValues());
|
||||||
|
}
|
||||||
|
if (ps.getTags() != null && !ps.getTags().isEmpty()) {
|
||||||
|
map.put("tags", ps.getTags());
|
||||||
|
}
|
||||||
|
if (ps.getRelatedPageTitles() != null && !ps.getRelatedPageTitles().isEmpty()) {
|
||||||
|
map.put("related_page_titles", ps.getRelatedPageTitles());
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> pageContextToMap(PageContext pc) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("title", pc.getTitle());
|
||||||
|
map.put("template_name", pc.getTemplateName());
|
||||||
|
map.put("template_fields", pc.getTemplateFields());
|
||||||
|
map.put("values", pc.getValues());
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> campaignContextToMap(CampaignStructuralContext ctx) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("campaign_name", ctx.getCampaignName());
|
||||||
|
map.put("campaign_description", ctx.getCampaignDescription());
|
||||||
|
map.put("arcs", ctx.getArcs().stream()
|
||||||
|
.map(this::arcSummaryToMap)
|
||||||
|
.collect(Collectors.toList()));
|
||||||
|
// Liste des PJ : omise si aucun pour alléger le prompt des campagnes sans fiches.
|
||||||
|
if (ctx.getCharacters() != null && !ctx.getCharacters().isEmpty()) {
|
||||||
|
map.put("characters", ctx.getCharacters().stream()
|
||||||
|
.map(this::characterSummaryToMap)
|
||||||
|
.collect(Collectors.toList()));
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> characterSummaryToMap(CharacterSummary c) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("name", c.getName());
|
||||||
|
if (c.getSnippet() != null && !c.getSnippet().isBlank()) {
|
||||||
|
map.put("snippet", c.getSnippet());
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper générique pour sérialiser les entités structurelles (Arc/Chapter/Scene)
|
||||||
|
* avec name, description et illustration_count conditionnel.
|
||||||
|
*/
|
||||||
|
private <T> Map<String, Object> structuralSummaryToMap(
|
||||||
|
T entity,
|
||||||
|
Function<T, String> nameExtractor,
|
||||||
|
Function<T, String> descriptionExtractor,
|
||||||
|
Function<T, Integer> illustrationCountExtractor,
|
||||||
|
BiConsumer<Map<String, Object>, T> childSerializer) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("name", nameExtractor.apply(entity));
|
||||||
|
map.put("description", descriptionExtractor.apply(entity));
|
||||||
|
if (illustrationCountExtractor.apply(entity) > 0) {
|
||||||
|
map.put("illustration_count", illustrationCountExtractor.apply(entity));
|
||||||
|
}
|
||||||
|
childSerializer.accept(map, entity);
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> arcSummaryToMap(ArcSummary a) {
|
||||||
|
return structuralSummaryToMap(
|
||||||
|
a,
|
||||||
|
ArcSummary::getName,
|
||||||
|
ArcSummary::getDescription,
|
||||||
|
ArcSummary::getIllustrationCount,
|
||||||
|
(map, arc) -> map.put("chapters", arc.getChapters().stream()
|
||||||
|
.map(this::chapterSummaryToMap)
|
||||||
|
.collect(Collectors.toList())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> chapterSummaryToMap(ChapterSummary c) {
|
||||||
|
return structuralSummaryToMap(
|
||||||
|
c,
|
||||||
|
ChapterSummary::getName,
|
||||||
|
ChapterSummary::getDescription,
|
||||||
|
ChapterSummary::getIllustrationCount,
|
||||||
|
(map, chapter) -> map.put("scenes", chapter.getScenes().stream()
|
||||||
|
.map(this::sceneSummaryToMap)
|
||||||
|
.collect(Collectors.toList())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> sceneSummaryToMap(SceneSummary s) {
|
||||||
|
return structuralSummaryToMap(
|
||||||
|
s,
|
||||||
|
SceneSummary::getName,
|
||||||
|
SceneSummary::getDescription,
|
||||||
|
SceneSummary::getIllustrationCount,
|
||||||
|
(map, scene) -> {
|
||||||
|
// Branches narratives : omises si absentes (scènes linéaires classiques).
|
||||||
|
if (s.getBranches() != null && !s.getBranches().isEmpty()) {
|
||||||
|
map.put("branches", s.getBranches().stream()
|
||||||
|
.map(this::branchHintToMap)
|
||||||
|
.collect(Collectors.toList()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> branchHintToMap(BranchHint b) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("label", b.getLabel());
|
||||||
|
map.put("target_scene_name", b.getTargetSceneName());
|
||||||
|
if (b.getCondition() != null && !b.getCondition().isBlank()) {
|
||||||
|
map.put("condition", b.getCondition());
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> narrativeEntityToMap(NarrativeEntityContext ne) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("entity_type", ne.getEntityType());
|
||||||
|
map.put("title", ne.getTitle());
|
||||||
|
map.put("fields", ne.getFields());
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
import com.loremind.domain.conversationcontext.ports.ConversationTitleGenerator;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adaptateur : appelle le Brain POST /summarize/conversation-title pour
|
||||||
|
* obtenir un titre court a partir des premiers messages.
|
||||||
|
*
|
||||||
|
* Fallback volontairement silencieux : si le Brain est indisponible, on
|
||||||
|
* renvoie un titre par defaut plutot que de casser l'UX chat.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainConversationTitleClient implements ConversationTitleGenerator {
|
||||||
|
|
||||||
|
private static final String PATH = "/summarize/conversation-title";
|
||||||
|
private static final String FALLBACK = "Nouvelle conversation";
|
||||||
|
|
||||||
|
private final WebClient webClient;
|
||||||
|
|
||||||
|
public BrainConversationTitleClient(
|
||||||
|
WebClient.Builder builder,
|
||||||
|
@Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.webClient = builder.baseUrl(baseUrl).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String generate(List<ConversationMessage> firstMessages) {
|
||||||
|
if (firstMessages == null || firstMessages.isEmpty()) {
|
||||||
|
return FALLBACK;
|
||||||
|
}
|
||||||
|
Map<String, Object> payload = new LinkedHashMap<>();
|
||||||
|
payload.put("messages", firstMessages.stream()
|
||||||
|
.map(m -> Map.<String, Object>of(
|
||||||
|
"role", m.getRole(),
|
||||||
|
"content", m.getContent() == null ? "" : m.getContent()))
|
||||||
|
.collect(Collectors.toList()));
|
||||||
|
|
||||||
|
try {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> resp = webClient.post()
|
||||||
|
.uri(PATH)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(payload)
|
||||||
|
.retrieve()
|
||||||
|
.bodyToMono(Map.class)
|
||||||
|
.timeout(Duration.ofSeconds(20))
|
||||||
|
.block();
|
||||||
|
if (resp == null) return FALLBACK;
|
||||||
|
Object title = resp.get("title");
|
||||||
|
if (title == null) return FALLBACK;
|
||||||
|
String s = title.toString().trim();
|
||||||
|
return s.isEmpty() ? FALLBACK : s;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return FALLBACK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper d'infrastructure : parse les payloads JSON véhiculés dans les
|
||||||
|
* évènements SSE reçus du Brain Python.
|
||||||
|
* <p>
|
||||||
|
* Implémentation volontairement minimaliste (pas de Jackson ici) car les
|
||||||
|
* schémas attendus sont figés et simples : {"token":"..."} et
|
||||||
|
* {"system":N,"history":N,"current":N,"max":N}. Si la complexité augmente,
|
||||||
|
* remplacer par un ObjectMapper + DTOs.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainSseParser {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse un JSON {"system":N,"history":N,"current":N,"max":N} en ChatUsage.
|
||||||
|
* Renvoie null si le payload est illisible — l'appelant décidera de ne
|
||||||
|
* simplement pas propager l'usage (le stream token continue).
|
||||||
|
*/
|
||||||
|
public ChatUsage parseUsage(String json) {
|
||||||
|
if (json == null) return null;
|
||||||
|
try {
|
||||||
|
int system = extractIntField(json, "system");
|
||||||
|
int history = extractIntField(json, "history");
|
||||||
|
int current = extractIntField(json, "current");
|
||||||
|
int max = extractIntField(json, "max");
|
||||||
|
return new ChatUsage(system, history, current, max);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse {"token":"..."} et renvoie la valeur du champ token (chaîne vide
|
||||||
|
* ou null si introuvable).
|
||||||
|
*/
|
||||||
|
public String parseToken(String json) {
|
||||||
|
if (json == null) return null;
|
||||||
|
int idx = json.indexOf("\"token\"");
|
||||||
|
if (idx < 0) return null;
|
||||||
|
int colon = json.indexOf(':', idx);
|
||||||
|
int firstQuote = json.indexOf('"', colon + 1);
|
||||||
|
int lastQuote = json.lastIndexOf('"');
|
||||||
|
if (firstQuote < 0 || lastQuote <= firstQuote) return null;
|
||||||
|
return json.substring(firstQuote + 1, lastQuote)
|
||||||
|
.replace("\\n", "\n")
|
||||||
|
.replace("\\\"", "\"")
|
||||||
|
.replace("\\\\", "\\");
|
||||||
|
}
|
||||||
|
|
||||||
|
private int extractIntField(String json, String field) {
|
||||||
|
String needle = "\"" + field + "\"";
|
||||||
|
int idx = json.indexOf(needle);
|
||||||
|
if (idx < 0) return 0;
|
||||||
|
int colon = json.indexOf(':', idx);
|
||||||
|
if (colon < 0) return 0;
|
||||||
|
int start = colon + 1;
|
||||||
|
while (start < json.length() && Character.isWhitespace(json.charAt(start))) start++;
|
||||||
|
int end = start;
|
||||||
|
while (end < json.length() && (Character.isDigit(json.charAt(end)) || json.charAt(end) == '-')) end++;
|
||||||
|
if (end == start) return 0;
|
||||||
|
return Integer.parseInt(json.substring(start, end));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package com.loremind.infrastructure.persistence;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seed 3 rulesets libres au premier démarrage (si la table game_systems est vide).
|
||||||
|
* <p>
|
||||||
|
* Objectif : donner à l'utilisateur un point de départ pour comprendre le format
|
||||||
|
* attendu (markdown structuré par titres H2) et permettre une démo "out of the box"
|
||||||
|
* sans devoir taper ses propres règles.
|
||||||
|
* <p>
|
||||||
|
* Les rulesets fournis sont des <b>extraits libres</b> (Nimble, SRD 5.1 extrait,
|
||||||
|
* homebrew exemple) — pas des règles officielles complètes. L'utilisateur est
|
||||||
|
* libre de les éditer, supprimer, ou les utiliser comme template.
|
||||||
|
* <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).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class GameSystemSeeder {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(GameSystemSeeder.class);
|
||||||
|
|
||||||
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
|
||||||
|
public GameSystemSeeder(GameSystemRepository gameSystemRepository) {
|
||||||
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void seedIfEmpty() {
|
||||||
|
if (!gameSystemRepository.findAll().isEmpty()) {
|
||||||
|
log.debug("GameSystem seed skipped — table non vide.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log.info("Seed initial des GameSystems (table vide)...");
|
||||||
|
for (GameSystem gs : defaultSystems()) {
|
||||||
|
gameSystemRepository.save(gs);
|
||||||
|
}
|
||||||
|
log.info("GameSystems seedés : {}", defaultSystems().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<GameSystem> defaultSystems() {
|
||||||
|
return List.of(
|
||||||
|
GameSystem.builder()
|
||||||
|
.name("Nimble (extrait)")
|
||||||
|
.description("Système léger et narratif, résolution rapide des combats.")
|
||||||
|
.author("LoreMind seed")
|
||||||
|
.isPublic(false)
|
||||||
|
.rulesMarkdown(NIMBLE_RULES)
|
||||||
|
.build(),
|
||||||
|
GameSystem.builder()
|
||||||
|
.name("D&D 5e SRD (extrait)")
|
||||||
|
.description("Extrait libre des bases du System Reference Document 5.1.")
|
||||||
|
.author("LoreMind seed")
|
||||||
|
.isPublic(false)
|
||||||
|
.rulesMarkdown(DND_SRD_RULES)
|
||||||
|
.build(),
|
||||||
|
GameSystem.builder()
|
||||||
|
.name("Homebrew Exemple")
|
||||||
|
.description("Template minimaliste à dupliquer pour créer votre propre système.")
|
||||||
|
.author("LoreMind seed")
|
||||||
|
.isPublic(false)
|
||||||
|
.rulesMarkdown(HOMEBREW_EXAMPLE)
|
||||||
|
.build()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final String NIMBLE_RULES = """
|
||||||
|
Système Nimble — résolution rapide, narration fluide, peu de tableaux. Agnostique (aucun univers imposé).
|
||||||
|
|
||||||
|
## Combat
|
||||||
|
- Initiative libre : les joueurs décrivent leur action dans l'ordre qu'ils veulent, le MJ joue les ennemis quand la fiction l'exige.
|
||||||
|
- Résolution : 1d20 + mod, difficulté 10/15/20 (facile/normal/dur). 20 naturel = critique (double dégâts).
|
||||||
|
- Dégâts : arme légère 1d6, arme lourde 1d10, projectile 1d8. Pas de table d'armure, l'armure augmente la difficulté à toucher.
|
||||||
|
- Blessures : un PJ peut encaisser 3 blessures graves avant de tomber. Pas de PV fins — on raconte les coups.
|
||||||
|
|
||||||
|
## Classes
|
||||||
|
- **Guerrier** : +2 en combat, peut relancer un dé de dégât 1×/scène.
|
||||||
|
- **Explorateur** : +2 en perception/survie, ignore la première blessure d'une scène.
|
||||||
|
- **Mage** : peut lancer un effet de magie par scène, nécessite une composante racontée.
|
||||||
|
- **Barde** : +2 en social, peut inspirer un allié (relance de dé).
|
||||||
|
|
||||||
|
## Monstres
|
||||||
|
Les monstres ont 3 stats : Menace (difficulté à toucher), Dégâts (dé de dégât), Résistance (nombre de blessures).
|
||||||
|
Exemples : Gobelin (Menace 10, 1d6, 1), Ogre (Menace 13, 1d10, 3), Dragon adulte (Menace 18, 2d10, 6).
|
||||||
|
""";
|
||||||
|
|
||||||
|
private static final String DND_SRD_RULES = """
|
||||||
|
Extrait libre du SRD 5.1 (Open Game License). Pour les règles complètes, consulter le SRD officiel.
|
||||||
|
|
||||||
|
## Combat
|
||||||
|
- Initiative : 1d20 + mod Dex au début du combat, ordre fixe par round.
|
||||||
|
- Action par tour : une action, une action bonus (si classe le permet), une réaction, mouvement jusqu'à la vitesse.
|
||||||
|
- Attaque : 1d20 + mod caractéristique + bonus maîtrise vs CA de la cible.
|
||||||
|
- Dégâts : dé de l'arme + mod caractéristique. Critique sur 20 naturel (double les dés de dégâts).
|
||||||
|
- Avantage/Désavantage : lancer 2d20 et garder le meilleur / pire.
|
||||||
|
|
||||||
|
## Classes
|
||||||
|
- **Barbare** : d12 PV, rage (+dégâts, résistance). Caractéristique principale : Force.
|
||||||
|
- **Barde** : d8 PV, sorts + inspiration bardique. Caractéristique : Charisme.
|
||||||
|
- **Clerc** : d8 PV, sorts divins, canalise la divinité. Caractéristique : Sagesse.
|
||||||
|
- **Druide** : d8 PV, sorts nature + forme animale. Caractéristique : Sagesse.
|
||||||
|
- **Ensorceleur** : d6 PV, sorts innés + métamagie. Caractéristique : Charisme.
|
||||||
|
- **Guerrier** : d10 PV, maîtrise martiale, second souffle. Caractéristique : Force ou Dextérité.
|
||||||
|
- **Magicien** : d6 PV, livre de sorts, grande flexibilité. Caractéristique : Intelligence.
|
||||||
|
- **Moine** : d8 PV, arts martiaux + ki. Caractéristique : Dextérité + Sagesse.
|
||||||
|
- **Paladin** : d10 PV, sorts + serment + imposition des mains. Caractéristique : Force + Charisme.
|
||||||
|
- **Rôdeur** : d10 PV, ennemi juré + explorateur + sorts. Caractéristique : Dextérité + Sagesse.
|
||||||
|
- **Roublard** : d8 PV, attaque sournoise + expertise. Caractéristique : Dextérité.
|
||||||
|
|
||||||
|
## Monstres
|
||||||
|
Stat block standard : CA, PV, Vitesse, For/Dex/Con/Int/Sag/Cha, jets de sauvegarde, compétences, sens, langues, Facteur de Puissance (FP).
|
||||||
|
Exemples : Gobelin (FP 1/4, CA 15, 7 PV), Ogre (FP 2, CA 11, 59 PV), Dragon rouge adulte (FP 17, CA 19, 256 PV).
|
||||||
|
""";
|
||||||
|
|
||||||
|
private static final String HOMEBREW_EXAMPLE = """
|
||||||
|
Template vide à dupliquer et remplir pour créer votre propre système.
|
||||||
|
|
||||||
|
## Combat
|
||||||
|
(Décrivez ici comment se résout un combat : initiative, jet d'attaque, dégâts, points de vie, critiques...)
|
||||||
|
|
||||||
|
## Classes
|
||||||
|
(Listez les archétypes jouables : nom, stats de base, capacités signature.)
|
||||||
|
|
||||||
|
## Monstres
|
||||||
|
(Format de stat block pour vos créatures : stats, capacités spéciales, FP/niveau.)
|
||||||
|
|
||||||
|
## Magie
|
||||||
|
(Si votre système a un système de magie : écoles, coût, composantes, listes de sorts/pouvoirs.)
|
||||||
|
|
||||||
|
## Progression
|
||||||
|
(Comment les PJ montent en puissance : XP, niveaux, acquisitions par niveau.)
|
||||||
|
""";
|
||||||
|
}
|
||||||
@@ -45,6 +45,13 @@ public class CampaignJpaEntity {
|
|||||||
@Column(name = "lore_id")
|
@Column(name = "lore_id")
|
||||||
private String loreId;
|
private String loreId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ID du GameSystem associé (nullable).
|
||||||
|
* Weak reference inter-contexte — pas de @ManyToOne / pas de FK DB.
|
||||||
|
*/
|
||||||
|
@Column(name = "game_system_id")
|
||||||
|
private String gameSystemId;
|
||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
createdAt = LocalDateTime.now();
|
createdAt = LocalDateTime.now();
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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).
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "characters")
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class CharacterJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Column(name = "markdown_content", columnDefinition = "TEXT")
|
||||||
|
private String markdownContent;
|
||||||
|
|
||||||
|
@Column(name = "campaign_id", nullable = false)
|
||||||
|
private Long campaignId;
|
||||||
|
|
||||||
|
@Column(name = "\"order\"", nullable = false)
|
||||||
|
private int order;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at", nullable = false)
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
createdAt = LocalDateTime.now();
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.FetchType;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.Index;
|
||||||
|
import jakarta.persistence.OneToMany;
|
||||||
|
import jakarta.persistence.OrderBy;
|
||||||
|
import jakarta.persistence.PrePersist;
|
||||||
|
import jakarta.persistence.PreUpdate;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persistance d'une conversation de chat IA.
|
||||||
|
*
|
||||||
|
* Les refs loreId / campaignId / entityId sont des weak references (String,
|
||||||
|
* pas de FK) — coherent avec la politique inter-contexte du reste du code.
|
||||||
|
* Indexes compose pour accelerer le listing par contexte dans la sidebar.
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "conversations", indexes = {
|
||||||
|
@Index(name = "idx_conv_lore_entity", columnList = "lore_id,entity_type,entity_id,updated_at"),
|
||||||
|
@Index(name = "idx_conv_campaign_entity", columnList = "campaign_id,entity_type,entity_id,updated_at")
|
||||||
|
})
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class ConversationJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@Column(name = "lore_id")
|
||||||
|
private String loreId;
|
||||||
|
|
||||||
|
@Column(name = "campaign_id")
|
||||||
|
private String campaignId;
|
||||||
|
|
||||||
|
@Column(name = "entity_type")
|
||||||
|
private String entityType;
|
||||||
|
|
||||||
|
@Column(name = "entity_id")
|
||||||
|
private String entityId;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at", nullable = false)
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Messages enfants. Charges a la demande (fetch=LAZY) pour ne pas plomber
|
||||||
|
* le listing sidebar. Cascade ALL + orphanRemoval : la suppression d'une
|
||||||
|
* conversation efface ses messages.
|
||||||
|
*/
|
||||||
|
@OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||||
|
@OrderBy("createdAt ASC, id ASC")
|
||||||
|
@Builder.Default
|
||||||
|
private List<ConversationMessageJpaEntity> messages = new ArrayList<>();
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
createdAt = now;
|
||||||
|
updatedAt = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
import jakarta.persistence.PrePersist;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.ToString;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persistance d'un message appartenant a une {@link ConversationJpaEntity}.
|
||||||
|
* Les messages sont ordonnes par createdAt ASC (ordre d'ajout = ordre lu).
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "conversation_messages")
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class ConversationMessageJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/** "user" | "assistant" | "system". */
|
||||||
|
@Column(nullable = false, length = 16)
|
||||||
|
private String role;
|
||||||
|
|
||||||
|
@Column(nullable = false, columnDefinition = "TEXT")
|
||||||
|
private String content;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference vers la conversation parent. ToString exclu pour eviter une
|
||||||
|
* boucle infinie quand Lombok genere toString() (conv -> messages -> conv...).
|
||||||
|
*/
|
||||||
|
@ManyToOne(optional = false)
|
||||||
|
@JoinColumn(name = "conversation_id", nullable = false)
|
||||||
|
@ToString.Exclude
|
||||||
|
private ConversationJpaEntity conversation;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
createdAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entité JPA pour la persistance des GameSystems (systèmes de JDR).
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "game_systems")
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class GameSystemJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Column(columnDefinition = "TEXT")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
@Column(name = "rules_markdown", columnDefinition = "TEXT")
|
||||||
|
private String rulesMarkdown;
|
||||||
|
|
||||||
|
@Column
|
||||||
|
private String author;
|
||||||
|
|
||||||
|
@Column(name = "is_public", nullable = false)
|
||||||
|
private boolean isPublic;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at", nullable = false)
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
createdAt = LocalDateTime.now();
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.CharacterJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface CharacterJpaRepository extends JpaRepository<CharacterJpaEntity, Long> {
|
||||||
|
|
||||||
|
List<CharacterJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.ConversationJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repository Spring Data JPA pour ConversationJpaEntity.
|
||||||
|
*
|
||||||
|
* Les requetes de listing par contexte gerent explicitement les NULL parce
|
||||||
|
* que JPQL `=` ne matche pas NULL. On combine `IS NULL` / `=` selon si le
|
||||||
|
* filtre est fourni — plus simple qu'une Specification Criteria API.
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public interface ConversationJpaRepository extends JpaRepository<ConversationJpaEntity, Long> {
|
||||||
|
|
||||||
|
/** Listing Lore racine (entity_type IS NULL). */
|
||||||
|
@Query("""
|
||||||
|
SELECT c FROM ConversationJpaEntity c
|
||||||
|
WHERE c.loreId = :loreId
|
||||||
|
AND c.entityType IS NULL
|
||||||
|
ORDER BY c.updatedAt DESC
|
||||||
|
""")
|
||||||
|
List<ConversationJpaEntity> findByLoreRoot(@Param("loreId") String loreId);
|
||||||
|
|
||||||
|
/** Listing Lore + entite precise. */
|
||||||
|
@Query("""
|
||||||
|
SELECT c FROM ConversationJpaEntity c
|
||||||
|
WHERE c.loreId = :loreId
|
||||||
|
AND c.entityType = :entityType
|
||||||
|
AND c.entityId = :entityId
|
||||||
|
ORDER BY c.updatedAt DESC
|
||||||
|
""")
|
||||||
|
List<ConversationJpaEntity> findByLoreAndEntity(
|
||||||
|
@Param("loreId") String loreId,
|
||||||
|
@Param("entityType") String entityType,
|
||||||
|
@Param("entityId") String entityId);
|
||||||
|
|
||||||
|
/** Listing Campagne racine. */
|
||||||
|
@Query("""
|
||||||
|
SELECT c FROM ConversationJpaEntity c
|
||||||
|
WHERE c.campaignId = :campaignId
|
||||||
|
AND c.entityType IS NULL
|
||||||
|
ORDER BY c.updatedAt DESC
|
||||||
|
""")
|
||||||
|
List<ConversationJpaEntity> findByCampaignRoot(@Param("campaignId") String campaignId);
|
||||||
|
|
||||||
|
/** Listing Campagne + entite precise. */
|
||||||
|
@Query("""
|
||||||
|
SELECT c FROM ConversationJpaEntity c
|
||||||
|
WHERE c.campaignId = :campaignId
|
||||||
|
AND c.entityType = :entityType
|
||||||
|
AND c.entityId = :entityId
|
||||||
|
ORDER BY c.updatedAt DESC
|
||||||
|
""")
|
||||||
|
List<ConversationJpaEntity> findByCampaignAndEntity(
|
||||||
|
@Param("campaignId") String campaignId,
|
||||||
|
@Param("entityType") String entityType,
|
||||||
|
@Param("entityId") String entityId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.GameSystemJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface GameSystemJpaRepository extends JpaRepository<GameSystemJpaEntity, Long> {
|
||||||
|
|
||||||
|
@Query("SELECT g FROM GameSystemJpaEntity g WHERE LOWER(g.name) LIKE LOWER(CONCAT('%', :query, '%'))")
|
||||||
|
List<GameSystemJpaEntity> findByNameContainingIgnoreCase(@Param("query") String query);
|
||||||
|
}
|
||||||
@@ -71,6 +71,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
|||||||
.updatedAt(jpaEntity.getUpdatedAt())
|
.updatedAt(jpaEntity.getUpdatedAt())
|
||||||
.arcsCount(jpaEntity.getArcsCount())
|
.arcsCount(jpaEntity.getArcsCount())
|
||||||
.loreId(jpaEntity.getLoreId())
|
.loreId(jpaEntity.getLoreId())
|
||||||
|
.gameSystemId(jpaEntity.getGameSystemId())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +85,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
|||||||
.updatedAt(campaign.getUpdatedAt())
|
.updatedAt(campaign.getUpdatedAt())
|
||||||
.arcsCount(campaign.getArcsCount())
|
.arcsCount(campaign.getArcsCount())
|
||||||
.loreId(campaign.getLoreId())
|
.loreId(campaign.getLoreId())
|
||||||
|
.gameSystemId(campaign.getGameSystemId())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.CharacterJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.CharacterJpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class PostgresCharacterRepository implements CharacterRepository {
|
||||||
|
|
||||||
|
private final CharacterJpaRepository jpaRepository;
|
||||||
|
|
||||||
|
public PostgresCharacterRepository(CharacterJpaRepository jpaRepository) {
|
||||||
|
this.jpaRepository = jpaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Character save(Character character) {
|
||||||
|
CharacterJpaEntity entity = toJpaEntity(character);
|
||||||
|
CharacterJpaEntity saved = jpaRepository.save(entity);
|
||||||
|
return toDomainEntity(saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<Character> findById(String id) {
|
||||||
|
return jpaRepository.findById(Long.parseLong(id)).map(this::toDomainEntity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Character> findByCampaignId(String campaignId) {
|
||||||
|
return jpaRepository.findByCampaignIdOrderByOrderAsc(Long.parseLong(campaignId)).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteById(String id) {
|
||||||
|
jpaRepository.deleteById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean existsById(String id) {
|
||||||
|
return jpaRepository.existsById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Character toDomainEntity(CharacterJpaEntity e) {
|
||||||
|
return Character.builder()
|
||||||
|
.id(e.getId().toString())
|
||||||
|
.name(e.getName())
|
||||||
|
.markdownContent(e.getMarkdownContent())
|
||||||
|
.campaignId(e.getCampaignId().toString())
|
||||||
|
.order(e.getOrder())
|
||||||
|
.createdAt(e.getCreatedAt())
|
||||||
|
.updatedAt(e.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private CharacterJpaEntity toJpaEntity(Character c) {
|
||||||
|
Long id = c.getId() != null ? Long.parseLong(c.getId()) : null;
|
||||||
|
return CharacterJpaEntity.builder()
|
||||||
|
.id(id)
|
||||||
|
.name(c.getName())
|
||||||
|
.markdownContent(c.getMarkdownContent())
|
||||||
|
.campaignId(Long.parseLong(c.getCampaignId()))
|
||||||
|
.order(c.getOrder())
|
||||||
|
.createdAt(c.getCreatedAt())
|
||||||
|
.updatedAt(c.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.conversationcontext.Conversation;
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
import com.loremind.domain.conversationcontext.ports.ConversationRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.ConversationJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.ConversationMessageJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.ConversationJpaRepository;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adaptateur Postgres pour ConversationRepository.
|
||||||
|
*
|
||||||
|
* Les methodes de listing ne chargent PAS les messages (messages LAZY,
|
||||||
|
* liste vide renvoyee cote domaine) — la sidebar n'a besoin que des
|
||||||
|
* meta-donnees. findById charge les messages via fetch explicite de la
|
||||||
|
* collection dans une transaction.
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class PostgresConversationRepository implements ConversationRepository {
|
||||||
|
|
||||||
|
private final ConversationJpaRepository jpa;
|
||||||
|
|
||||||
|
public PostgresConversationRepository(ConversationJpaRepository jpa) {
|
||||||
|
this.jpa = jpa;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public Conversation save(Conversation conversation) {
|
||||||
|
ConversationJpaEntity entity = toJpaEntity(conversation);
|
||||||
|
ConversationJpaEntity saved = jpa.save(entity);
|
||||||
|
return toDomain(saved, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Optional<Conversation> findById(String id) {
|
||||||
|
return jpa.findById(Long.parseLong(id))
|
||||||
|
.map(e -> {
|
||||||
|
// Force l'initialisation LAZY avant de sortir de la transaction.
|
||||||
|
e.getMessages().size();
|
||||||
|
return toDomain(e, true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<Conversation> findByContext(String loreId, String campaignId, String entityType, String entityId) {
|
||||||
|
List<ConversationJpaEntity> rows;
|
||||||
|
if (loreId != null) {
|
||||||
|
rows = (entityType == null)
|
||||||
|
? jpa.findByLoreRoot(loreId)
|
||||||
|
: jpa.findByLoreAndEntity(loreId, entityType, entityId);
|
||||||
|
} else if (campaignId != null) {
|
||||||
|
rows = (entityType == null)
|
||||||
|
? jpa.findByCampaignRoot(campaignId)
|
||||||
|
: jpa.findByCampaignAndEntity(campaignId, entityType, entityId);
|
||||||
|
} else {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
return rows.stream().map(e -> toDomain(e, false)).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public void deleteById(String id) {
|
||||||
|
jpa.deleteById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public ConversationMessage appendMessage(String conversationId, ConversationMessage message) {
|
||||||
|
ConversationJpaEntity conv = jpa.findById(Long.parseLong(conversationId))
|
||||||
|
.orElseThrow(() -> new EntityNotFoundException("Conversation " + conversationId));
|
||||||
|
|
||||||
|
ConversationMessageJpaEntity msg = ConversationMessageJpaEntity.builder()
|
||||||
|
.role(message.getRole())
|
||||||
|
.content(message.getContent())
|
||||||
|
.conversation(conv)
|
||||||
|
.build();
|
||||||
|
conv.getMessages().add(msg);
|
||||||
|
// Force updatedAt via @PreUpdate en modifiant la conv (touch).
|
||||||
|
conv.setUpdatedAt(java.time.LocalDateTime.now());
|
||||||
|
|
||||||
|
ConversationJpaEntity saved = jpa.save(conv);
|
||||||
|
ConversationMessageJpaEntity persisted = saved.getMessages().get(saved.getMessages().size() - 1);
|
||||||
|
return toDomainMessage(persisted);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public void updateTitle(String conversationId, String title) {
|
||||||
|
ConversationJpaEntity conv = jpa.findById(Long.parseLong(conversationId))
|
||||||
|
.orElseThrow(() -> new EntityNotFoundException("Conversation " + conversationId));
|
||||||
|
conv.setTitle(title);
|
||||||
|
jpa.save(conv);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Mapping ----------
|
||||||
|
|
||||||
|
private ConversationJpaEntity toJpaEntity(Conversation c) {
|
||||||
|
Long id = c.getId() != null ? Long.parseLong(c.getId()) : null;
|
||||||
|
return ConversationJpaEntity.builder()
|
||||||
|
.id(id)
|
||||||
|
.title(c.getTitle())
|
||||||
|
.loreId(c.getLoreId())
|
||||||
|
.campaignId(c.getCampaignId())
|
||||||
|
.entityType(c.getEntityType())
|
||||||
|
.entityId(c.getEntityId())
|
||||||
|
.createdAt(c.getCreatedAt())
|
||||||
|
.updatedAt(c.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Conversation toDomain(ConversationJpaEntity e, boolean withMessages) {
|
||||||
|
List<ConversationMessage> msgs = withMessages
|
||||||
|
? e.getMessages().stream().map(this::toDomainMessage).collect(Collectors.toList())
|
||||||
|
: new java.util.ArrayList<>();
|
||||||
|
return Conversation.builder()
|
||||||
|
.id(e.getId().toString())
|
||||||
|
.title(e.getTitle())
|
||||||
|
.loreId(e.getLoreId())
|
||||||
|
.campaignId(e.getCampaignId())
|
||||||
|
.entityType(e.getEntityType())
|
||||||
|
.entityId(e.getEntityId())
|
||||||
|
.createdAt(e.getCreatedAt())
|
||||||
|
.updatedAt(e.getUpdatedAt())
|
||||||
|
.messages(msgs)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ConversationMessage toDomainMessage(ConversationMessageJpaEntity e) {
|
||||||
|
return ConversationMessage.builder()
|
||||||
|
.id(e.getId() != null ? e.getId().toString() : null)
|
||||||
|
.role(e.getRole())
|
||||||
|
.content(e.getContent())
|
||||||
|
.createdAt(e.getCreatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.GameSystemJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.GameSystemJpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class PostgresGameSystemRepository implements GameSystemRepository {
|
||||||
|
|
||||||
|
private final GameSystemJpaRepository jpaRepository;
|
||||||
|
|
||||||
|
public PostgresGameSystemRepository(GameSystemJpaRepository jpaRepository) {
|
||||||
|
this.jpaRepository = jpaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public GameSystem save(GameSystem gameSystem) {
|
||||||
|
GameSystemJpaEntity entity = toJpaEntity(gameSystem);
|
||||||
|
GameSystemJpaEntity saved = jpaRepository.save(entity);
|
||||||
|
return toDomainEntity(saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<GameSystem> findById(String id) {
|
||||||
|
return jpaRepository.findById(Long.parseLong(id)).map(this::toDomainEntity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<GameSystem> findAll() {
|
||||||
|
return jpaRepository.findAll().stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteById(String id) {
|
||||||
|
jpaRepository.deleteById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean existsById(String id) {
|
||||||
|
return jpaRepository.existsById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<GameSystem> searchByName(String query) {
|
||||||
|
return jpaRepository.findByNameContainingIgnoreCase(query).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private GameSystem toDomainEntity(GameSystemJpaEntity e) {
|
||||||
|
return GameSystem.builder()
|
||||||
|
.id(e.getId().toString())
|
||||||
|
.name(e.getName())
|
||||||
|
.description(e.getDescription())
|
||||||
|
.rulesMarkdown(e.getRulesMarkdown())
|
||||||
|
.author(e.getAuthor())
|
||||||
|
.isPublic(e.isPublic())
|
||||||
|
.createdAt(e.getCreatedAt())
|
||||||
|
.updatedAt(e.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private GameSystemJpaEntity toJpaEntity(GameSystem g) {
|
||||||
|
Long id = g.getId() != null ? Long.parseLong(g.getId()) : null;
|
||||||
|
return GameSystemJpaEntity.builder()
|
||||||
|
.id(id)
|
||||||
|
.name(g.getName())
|
||||||
|
.description(g.getDescription())
|
||||||
|
.rulesMarkdown(g.getRulesMarkdown())
|
||||||
|
.author(g.getAuthor())
|
||||||
|
.isPublic(g.isPublic())
|
||||||
|
.createdAt(g.getCreatedAt())
|
||||||
|
.updatedAt(g.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package com.loremind.infrastructure.web.controller;
|
|||||||
import com.loremind.application.generationcontext.StreamChatForCampaignUseCase;
|
import com.loremind.application.generationcontext.StreamChatForCampaignUseCase;
|
||||||
import com.loremind.application.generationcontext.StreamChatForLoreUseCase;
|
import com.loremind.application.generationcontext.StreamChatForLoreUseCase;
|
||||||
import com.loremind.domain.generationcontext.ChatMessage;
|
import com.loremind.domain.generationcontext.ChatMessage;
|
||||||
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatMessageDTO;
|
import com.loremind.infrastructure.web.dto.generationcontext.ChatMessageDTO;
|
||||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamCampaignRequestDTO;
|
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamCampaignRequestDTO;
|
||||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamRequestDTO;
|
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamRequestDTO;
|
||||||
@@ -80,6 +81,7 @@ public class AiChatController {
|
|||||||
try {
|
try {
|
||||||
streamChatForLoreUseCase.execute(
|
streamChatForLoreUseCase.execute(
|
||||||
loreId, pageId, messages,
|
loreId, pageId, messages,
|
||||||
|
usage -> sendUsage(emitter, usage),
|
||||||
token -> sendToken(emitter, token),
|
token -> sendToken(emitter, token),
|
||||||
() -> complete(emitter),
|
() -> complete(emitter),
|
||||||
error -> fail(emitter, error));
|
error -> fail(emitter, error));
|
||||||
@@ -100,6 +102,7 @@ public class AiChatController {
|
|||||||
try {
|
try {
|
||||||
streamChatForCampaignUseCase.execute(
|
streamChatForCampaignUseCase.execute(
|
||||||
campaignId, entityType, entityId, messages,
|
campaignId, entityType, entityId, messages,
|
||||||
|
usage -> sendUsage(emitter, usage),
|
||||||
token -> sendToken(emitter, token),
|
token -> sendToken(emitter, token),
|
||||||
() -> complete(emitter),
|
() -> complete(emitter),
|
||||||
error -> fail(emitter, error));
|
error -> fail(emitter, error));
|
||||||
@@ -110,6 +113,18 @@ public class AiChatController {
|
|||||||
|
|
||||||
// --- Helpers SSE (un seul point d'écriture par type d'événement) --------
|
// --- Helpers SSE (un seul point d'écriture par type d'événement) --------
|
||||||
|
|
||||||
|
private void sendUsage(SseEmitter emitter, ChatUsage usage) {
|
||||||
|
try {
|
||||||
|
String payload = "{\"system\":" + usage.system()
|
||||||
|
+ ",\"history\":" + usage.history()
|
||||||
|
+ ",\"current\":" + usage.current()
|
||||||
|
+ ",\"max\":" + usage.max() + "}";
|
||||||
|
emitter.send(SseEmitter.event().name("usage").data(payload));
|
||||||
|
} catch (IOException e) {
|
||||||
|
emitter.completeWithError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void sendToken(SseEmitter emitter, String token) {
|
private void sendToken(SseEmitter emitter, String token) {
|
||||||
try {
|
try {
|
||||||
emitter.send(SseEmitter.event()
|
emitter.send(SseEmitter.event()
|
||||||
|
|||||||
@@ -68,4 +68,12 @@ public class ArcController {
|
|||||||
arcService.deleteArc(id);
|
arcService.deleteArc(id);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}/deletion-impact")
|
||||||
|
public ResponseEntity<ArcService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||||
|
if (!arcService.arcExists(id)) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(arcService.getDeletionImpact(id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ public class CampaignController {
|
|||||||
public ResponseEntity<CampaignDTO> createCampaign(@RequestBody CampaignDTO campaignDTO) {
|
public ResponseEntity<CampaignDTO> createCampaign(@RequestBody CampaignDTO campaignDTO) {
|
||||||
Campaign campaign = campaignMapper.toDomain(campaignDTO);
|
Campaign campaign = campaignMapper.toDomain(campaignDTO);
|
||||||
Campaign createdCampaign = campaignService.createCampaign(
|
Campaign createdCampaign = campaignService.createCampaign(
|
||||||
new CampaignService.CampaignData(campaign.getName(), campaign.getDescription(), campaign.getLoreId())
|
new CampaignService.CampaignData(campaign.getName(), campaign.getDescription(), campaign.getLoreId(), campaign.getGameSystemId())
|
||||||
);
|
);
|
||||||
return ResponseEntity.ok(campaignMapper.toDTO(createdCampaign));
|
return ResponseEntity.ok(campaignMapper.toDTO(createdCampaign));
|
||||||
}
|
}
|
||||||
@@ -64,7 +64,7 @@ public class CampaignController {
|
|||||||
public ResponseEntity<CampaignDTO> updateCampaign(@PathVariable String id, @RequestBody CampaignDTO campaignDTO) {
|
public ResponseEntity<CampaignDTO> updateCampaign(@PathVariable String id, @RequestBody CampaignDTO campaignDTO) {
|
||||||
Campaign updatedCampaign = campaignService.updateCampaign(
|
Campaign updatedCampaign = campaignService.updateCampaign(
|
||||||
id,
|
id,
|
||||||
new CampaignService.CampaignData(campaignDTO.getName(), campaignDTO.getDescription(), campaignDTO.getLoreId())
|
new CampaignService.CampaignData(campaignDTO.getName(), campaignDTO.getDescription(), campaignDTO.getLoreId(), campaignDTO.getGameSystemId())
|
||||||
);
|
);
|
||||||
return ResponseEntity.ok(campaignMapper.toDTO(updatedCampaign));
|
return ResponseEntity.ok(campaignMapper.toDTO(updatedCampaign));
|
||||||
}
|
}
|
||||||
@@ -74,4 +74,16 @@ public class CampaignController {
|
|||||||
campaignService.deleteCampaign(id);
|
campaignService.deleteCampaign(id);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Récapitulatif des entités qui seront supprimées en cascade : utilisé par
|
||||||
|
* l'UI pour afficher "X arcs, Y chapitres, Z scènes..." dans la confirmation.
|
||||||
|
*/
|
||||||
|
@GetMapping("/{id}/deletion-impact")
|
||||||
|
public ResponseEntity<CampaignService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||||
|
if (!campaignService.campaignExists(id)) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(campaignService.getDeletionImpact(id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,4 +68,12 @@ public class ChapterController {
|
|||||||
chapterService.deleteChapter(id);
|
chapterService.deleteChapter(id);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}/deletion-impact")
|
||||||
|
public ResponseEntity<ChapterService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||||
|
if (!chapterService.chapterExists(id)) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(chapterService.getDeletionImpact(id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.campaigncontext.CharacterService;
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.infrastructure.web.dto.campaigncontext.CharacterDTO;
|
||||||
|
import com.loremind.infrastructure.web.mapper.CharacterMapper;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/characters")
|
||||||
|
public class CharacterController {
|
||||||
|
|
||||||
|
private final CharacterService characterService;
|
||||||
|
private final CharacterMapper characterMapper;
|
||||||
|
|
||||||
|
public CharacterController(CharacterService characterService, CharacterMapper characterMapper) {
|
||||||
|
this.characterService = characterService;
|
||||||
|
this.characterMapper = characterMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<CharacterDTO> createCharacter(@RequestBody CharacterDTO dto) {
|
||||||
|
Character created = characterService.createCharacter(
|
||||||
|
new CharacterService.CharacterData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), null)
|
||||||
|
);
|
||||||
|
return ResponseEntity.ok(characterMapper.toDTO(created));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ResponseEntity<CharacterDTO> getCharacterById(@PathVariable String id) {
|
||||||
|
return characterService.getCharacterById(id)
|
||||||
|
.map(c -> ResponseEntity.ok(characterMapper.toDTO(c)))
|
||||||
|
.orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/campaign/{campaignId}")
|
||||||
|
public ResponseEntity<List<CharacterDTO>> getCharactersByCampaign(@PathVariable String campaignId) {
|
||||||
|
List<CharacterDTO> dtos = characterService.getCharactersByCampaignId(campaignId).stream()
|
||||||
|
.map(characterMapper::toDTO)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return ResponseEntity.ok(dtos);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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())
|
||||||
|
);
|
||||||
|
return ResponseEntity.ok(characterMapper.toDTO(updated));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ResponseEntity<Void> deleteCharacter(@PathVariable String id) {
|
||||||
|
characterService.deleteCharacter(id);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.conversationcontext.ConversationService;
|
||||||
|
import com.loremind.domain.conversationcontext.Conversation;
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
import com.loremind.infrastructure.web.dto.conversationcontext.AppendMessageDTO;
|
||||||
|
import com.loremind.infrastructure.web.dto.conversationcontext.ConversationDTO;
|
||||||
|
import com.loremind.infrastructure.web.dto.conversationcontext.ConversationMessageDTO;
|
||||||
|
import com.loremind.infrastructure.web.dto.conversationcontext.CreateConversationDTO;
|
||||||
|
import com.loremind.infrastructure.web.dto.conversationcontext.RenameConversationDTO;
|
||||||
|
import com.loremind.infrastructure.web.mapper.ConversationMapper;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API REST des conversations persistees.
|
||||||
|
*
|
||||||
|
* GET /api/conversations?loreId=...&entityType=...&entityId=... (listing filtre)
|
||||||
|
* GET /api/conversations?campaignId=...&entityType=...&entityId=...
|
||||||
|
* GET /api/conversations/{id} (detail + messages)
|
||||||
|
* POST /api/conversations (create)
|
||||||
|
* PATCH /api/conversations/{id}/title (rename)
|
||||||
|
* DELETE /api/conversations/{id}
|
||||||
|
*
|
||||||
|
* L'ajout de messages est piloje cote chat stream (use case dedie),
|
||||||
|
* pas par ce controller.
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/conversations")
|
||||||
|
public class ConversationController {
|
||||||
|
|
||||||
|
private final ConversationService service;
|
||||||
|
private final ConversationMapper mapper;
|
||||||
|
|
||||||
|
public ConversationController(ConversationService service, ConversationMapper mapper) {
|
||||||
|
this.service = service;
|
||||||
|
this.mapper = mapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public ResponseEntity<List<ConversationDTO>> list(
|
||||||
|
@RequestParam(required = false) String loreId,
|
||||||
|
@RequestParam(required = false) String campaignId,
|
||||||
|
@RequestParam(required = false) String entityType,
|
||||||
|
@RequestParam(required = false) String entityId) {
|
||||||
|
List<Conversation> rows = service.listByContext(loreId, campaignId, entityType, entityId);
|
||||||
|
return ResponseEntity.ok(rows.stream().map(mapper::toListDTO).collect(Collectors.toList()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ResponseEntity<ConversationDTO> getById(@PathVariable String id) {
|
||||||
|
return service.getById(id)
|
||||||
|
.map(c -> ResponseEntity.ok(mapper.toDTO(c)))
|
||||||
|
.orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<ConversationDTO> create(@RequestBody CreateConversationDTO dto) {
|
||||||
|
Conversation created = service.create(new ConversationService.CreateData(
|
||||||
|
dto.getTitle(),
|
||||||
|
dto.getLoreId(),
|
||||||
|
dto.getCampaignId(),
|
||||||
|
dto.getEntityType(),
|
||||||
|
dto.getEntityId()));
|
||||||
|
return ResponseEntity.ok(mapper.toDTO(created));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PatchMapping("/{id}/title")
|
||||||
|
public ResponseEntity<Void> rename(@PathVariable String id, @RequestBody RenameConversationDTO dto) {
|
||||||
|
service.rename(id, dto.getTitle());
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ResponseEntity<Void> delete(@PathVariable String id) {
|
||||||
|
service.delete(id);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/{id}/messages")
|
||||||
|
public ResponseEntity<ConversationMessageDTO> appendMessage(
|
||||||
|
@PathVariable String id,
|
||||||
|
@RequestBody AppendMessageDTO dto) {
|
||||||
|
ConversationMessage saved = service.appendMessage(id, dto.getRole(), dto.getContent());
|
||||||
|
return ResponseEntity.ok(mapper.toMessageDTO(saved));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auto-genere et persiste un titre base sur les premiers messages.
|
||||||
|
* Appele par le front apres le 1er couple user/assistant.
|
||||||
|
*/
|
||||||
|
@PostMapping("/{id}/auto-title")
|
||||||
|
public ResponseEntity<RenameConversationDTO> autoTitle(@PathVariable String id) {
|
||||||
|
String title = service.autoGenerateTitle(id);
|
||||||
|
return ResponseEntity.ok(RenameConversationDTO.builder().title(title).build());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.gamesystemcontext.GameSystemService;
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||||
|
import com.loremind.infrastructure.web.mapper.GameSystemMapper;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/game-systems")
|
||||||
|
public class GameSystemController {
|
||||||
|
|
||||||
|
private final GameSystemService gameSystemService;
|
||||||
|
private final GameSystemMapper gameSystemMapper;
|
||||||
|
|
||||||
|
public GameSystemController(GameSystemService gameSystemService, GameSystemMapper gameSystemMapper) {
|
||||||
|
this.gameSystemService = gameSystemService;
|
||||||
|
this.gameSystemMapper = gameSystemMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<GameSystemDTO> createGameSystem(@RequestBody GameSystemDTO dto) {
|
||||||
|
GameSystem created = gameSystemService.createGameSystem(toData(dto));
|
||||||
|
return ResponseEntity.ok(gameSystemMapper.toDTO(created));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ResponseEntity<GameSystemDTO> getGameSystemById(@PathVariable String id) {
|
||||||
|
return gameSystemService.getGameSystemById(id)
|
||||||
|
.map(g -> ResponseEntity.ok(gameSystemMapper.toDTO(g)))
|
||||||
|
.orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public ResponseEntity<List<GameSystemDTO>> getAllGameSystems() {
|
||||||
|
List<GameSystemDTO> dtos = gameSystemService.getAllGameSystems().stream()
|
||||||
|
.map(gameSystemMapper::toDTO)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return ResponseEntity.ok(dtos);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/search")
|
||||||
|
public ResponseEntity<List<GameSystemDTO>> searchGameSystems(@RequestParam("q") String query) {
|
||||||
|
List<GameSystemDTO> dtos = gameSystemService.searchGameSystems(query).stream()
|
||||||
|
.map(gameSystemMapper::toDTO)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return ResponseEntity.ok(dtos);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public ResponseEntity<GameSystemDTO> updateGameSystem(@PathVariable String id, @RequestBody GameSystemDTO dto) {
|
||||||
|
GameSystem updated = gameSystemService.updateGameSystem(id, toData(dto));
|
||||||
|
return ResponseEntity.ok(gameSystemMapper.toDTO(updated));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ResponseEntity<Void> deleteGameSystem(@PathVariable String id) {
|
||||||
|
gameSystemService.deleteGameSystem(id);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private GameSystemService.GameSystemData toData(GameSystemDTO dto) {
|
||||||
|
return new GameSystemService.GameSystemData(
|
||||||
|
dto.getName(),
|
||||||
|
dto.getDescription(),
|
||||||
|
dto.getRulesMarkdown(),
|
||||||
|
dto.getAuthor(),
|
||||||
|
dto.isPublic()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,4 +69,17 @@ public class LoreController {
|
|||||||
loreService.deleteLore(id);
|
loreService.deleteLore(id);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Récapitulatif des entités qui seront supprimées / détachées en cascade.
|
||||||
|
* Utilisé par l'UI pour afficher "X dossiers, Y pages, Z templates,
|
||||||
|
* N campagne(s) détachée(s)" dans la confirmation.
|
||||||
|
*/
|
||||||
|
@GetMapping("/{id}/deletion-impact")
|
||||||
|
public ResponseEntity<LoreService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||||
|
if (loreService.getLoreById(id).isEmpty()) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(loreService.getDeletionImpact(id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,4 +97,16 @@ public class LoreNodeController {
|
|||||||
loreNodeService.deleteLoreNode(id);
|
loreNodeService.deleteLoreNode(id);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Récapitulatif des entités qui seront supprimées en cascade : utilisé par
|
||||||
|
* l'UI pour afficher "X sous-dossiers, Y pages..." dans la confirmation.
|
||||||
|
*/
|
||||||
|
@GetMapping("/{id}/deletion-impact")
|
||||||
|
public ResponseEntity<LoreNodeService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||||
|
if (loreNodeService.getLoreNodeById(id).isEmpty()) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(loreNodeService.getDeletionImpact(id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import org.springframework.http.HttpMethod;
|
|||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
@@ -53,6 +54,11 @@ public class SettingsController {
|
|||||||
return forward(HttpMethod.GET, "/models/ollama", null);
|
return forward(HttpMethod.GET, "/models/ollama", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/models/ollama/info")
|
||||||
|
public ResponseEntity<Map<String, Object>> getOllamaModelInfo(@RequestBody Map<String, Object> body) {
|
||||||
|
return forward(HttpMethod.POST, "/models/ollama/info", body);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/models/onemin")
|
@GetMapping("/models/onemin")
|
||||||
public ResponseEntity<Map<String, Object>> listOneMinModels() {
|
public ResponseEntity<Map<String, Object>> listOneMinModels() {
|
||||||
return forward(HttpMethod.GET, "/models/onemin", null);
|
return forward(HttpMethod.GET, "/models/onemin", null);
|
||||||
|
|||||||
@@ -15,4 +15,6 @@ public class CampaignDTO {
|
|||||||
private int arcsCount;
|
private int arcsCount;
|
||||||
/** Nullable : campagne sans univers associé. */
|
/** Nullable : campagne sans univers associé. */
|
||||||
private String loreId;
|
private String loreId;
|
||||||
|
/** Nullable : campagne sans système de JDR associé (générique). */
|
||||||
|
private String gameSystemId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.loremind.infrastructure.web.dto.campaigncontext;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DTO pour les fiches de personnages (PJ) d'une campagne.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class CharacterDTO {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String name;
|
||||||
|
private String markdownContent;
|
||||||
|
private String campaignId;
|
||||||
|
private int order;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class AppendMessageDTO {
|
||||||
|
/** "user" | "assistant" | "system". */
|
||||||
|
private String role;
|
||||||
|
private String content;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DTO d'une conversation. Les messages sont inclus uniquement sur GET /{id}
|
||||||
|
* (null pour les reponses de listing afin d'alleger la sidebar).
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class ConversationDTO {
|
||||||
|
private String id;
|
||||||
|
private String title;
|
||||||
|
private String loreId;
|
||||||
|
private String campaignId;
|
||||||
|
private String entityType;
|
||||||
|
private String entityId;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
private List<ConversationMessageDTO> messages;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class ConversationMessageDTO {
|
||||||
|
private String id;
|
||||||
|
private String role;
|
||||||
|
private String content;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Payload de creation. Le client fournit l'ancrage (lore ou campagne, +/-
|
||||||
|
* entite focus). Le titre est optionnel — sera auto-genere apres le 1er
|
||||||
|
* echange IA si absent.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class CreateConversationDTO {
|
||||||
|
private String title;
|
||||||
|
private String loreId;
|
||||||
|
private String campaignId;
|
||||||
|
private String entityType;
|
||||||
|
private String entityId;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class RenameConversationDTO {
|
||||||
|
private String title;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.loremind.infrastructure.web.dto.gamesystemcontext;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DTO pour l'entité GameSystem (système de JDR).
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class GameSystemDTO {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String name;
|
||||||
|
private String description;
|
||||||
|
private String rulesMarkdown;
|
||||||
|
private String author;
|
||||||
|
private boolean isPublic;
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ public class CampaignMapper {
|
|||||||
dto.setDescription(campaign.getDescription());
|
dto.setDescription(campaign.getDescription());
|
||||||
dto.setArcsCount(campaign.getArcsCount());
|
dto.setArcsCount(campaign.getArcsCount());
|
||||||
dto.setLoreId(campaign.getLoreId());
|
dto.setLoreId(campaign.getLoreId());
|
||||||
|
dto.setGameSystemId(campaign.getGameSystemId());
|
||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,6 +36,7 @@ public class CampaignMapper {
|
|||||||
.description(dto.getDescription())
|
.description(dto.getDescription())
|
||||||
.arcsCount(dto.getArcsCount())
|
.arcsCount(dto.getArcsCount())
|
||||||
.loreId(dto.getLoreId())
|
.loreId(dto.getLoreId())
|
||||||
|
.gameSystemId(dto.getGameSystemId())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.loremind.infrastructure.web.mapper;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.infrastructure.web.dto.campaigncontext.CharacterDTO;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class CharacterMapper {
|
||||||
|
|
||||||
|
public CharacterDTO toDTO(Character c) {
|
||||||
|
if (c == null) return null;
|
||||||
|
CharacterDTO dto = new CharacterDTO();
|
||||||
|
dto.setId(c.getId());
|
||||||
|
dto.setName(c.getName());
|
||||||
|
dto.setMarkdownContent(c.getMarkdownContent());
|
||||||
|
dto.setCampaignId(c.getCampaignId());
|
||||||
|
dto.setOrder(c.getOrder());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Character toDomain(CharacterDTO dto) {
|
||||||
|
if (dto == null) return null;
|
||||||
|
return Character.builder()
|
||||||
|
.id(dto.getId())
|
||||||
|
.name(dto.getName())
|
||||||
|
.markdownContent(dto.getMarkdownContent())
|
||||||
|
.campaignId(dto.getCampaignId())
|
||||||
|
.order(dto.getOrder())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package com.loremind.infrastructure.web.mapper;
|
||||||
|
|
||||||
|
import com.loremind.domain.conversationcontext.Conversation;
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
import com.loremind.infrastructure.web.dto.conversationcontext.ConversationDTO;
|
||||||
|
import com.loremind.infrastructure.web.dto.conversationcontext.ConversationMessageDTO;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Conversion Domaine <-> DTO pour le contexte Conversation.
|
||||||
|
*
|
||||||
|
* {@link #toListDTO(Conversation)} omet les messages — utilise pour le
|
||||||
|
* listing sidebar ou on n'expose que les metadonnees.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class ConversationMapper {
|
||||||
|
|
||||||
|
public ConversationDTO toDTO(Conversation c) {
|
||||||
|
List<ConversationMessageDTO> msgs = c.getMessages() == null
|
||||||
|
? List.of()
|
||||||
|
: c.getMessages().stream().map(this::toMessageDTO).collect(Collectors.toList());
|
||||||
|
return ConversationDTO.builder()
|
||||||
|
.id(c.getId())
|
||||||
|
.title(c.getTitle())
|
||||||
|
.loreId(c.getLoreId())
|
||||||
|
.campaignId(c.getCampaignId())
|
||||||
|
.entityType(c.getEntityType())
|
||||||
|
.entityId(c.getEntityId())
|
||||||
|
.createdAt(c.getCreatedAt())
|
||||||
|
.updatedAt(c.getUpdatedAt())
|
||||||
|
.messages(msgs)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Variante listing : pas de messages pour alleger la payload. */
|
||||||
|
public ConversationDTO toListDTO(Conversation c) {
|
||||||
|
return ConversationDTO.builder()
|
||||||
|
.id(c.getId())
|
||||||
|
.title(c.getTitle())
|
||||||
|
.loreId(c.getLoreId())
|
||||||
|
.campaignId(c.getCampaignId())
|
||||||
|
.entityType(c.getEntityType())
|
||||||
|
.entityId(c.getEntityId())
|
||||||
|
.createdAt(c.getCreatedAt())
|
||||||
|
.updatedAt(c.getUpdatedAt())
|
||||||
|
.messages(null)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ConversationMessageDTO toMessageDTO(ConversationMessage m) {
|
||||||
|
return ConversationMessageDTO.builder()
|
||||||
|
.id(m.getId())
|
||||||
|
.role(m.getRole())
|
||||||
|
.content(m.getContent())
|
||||||
|
.createdAt(m.getCreatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.loremind.infrastructure.web.mapper;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class GameSystemMapper {
|
||||||
|
|
||||||
|
public GameSystemDTO toDTO(GameSystem g) {
|
||||||
|
if (g == null) return null;
|
||||||
|
GameSystemDTO dto = new GameSystemDTO();
|
||||||
|
dto.setId(g.getId());
|
||||||
|
dto.setName(g.getName());
|
||||||
|
dto.setDescription(g.getDescription());
|
||||||
|
dto.setRulesMarkdown(g.getRulesMarkdown());
|
||||||
|
dto.setAuthor(g.getAuthor());
|
||||||
|
dto.setPublic(g.isPublic());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GameSystem toDomain(GameSystemDTO dto) {
|
||||||
|
if (dto == null) return null;
|
||||||
|
return GameSystem.builder()
|
||||||
|
.id(dto.getId())
|
||||||
|
.name(dto.getName())
|
||||||
|
.description(dto.getDescription())
|
||||||
|
.rulesMarkdown(dto.getRulesMarkdown())
|
||||||
|
.author(dto.getAuthor())
|
||||||
|
.isPublic(dto.isPublic())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Arc;
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
@@ -14,6 +18,7 @@ import java.util.Optional;
|
|||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,6 +31,10 @@ public class ArcServiceTest {
|
|||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private ArcRepository arcRepository;
|
private ArcRepository arcRepository;
|
||||||
|
@Mock
|
||||||
|
private ChapterRepository chapterRepository;
|
||||||
|
@Mock
|
||||||
|
private SceneRepository sceneRepository;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private ArcService arcService;
|
private ArcService arcService;
|
||||||
@@ -159,15 +168,48 @@ public class ArcServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testDeleteArc() {
|
void testDeleteArc_EmptyArc() {
|
||||||
// Arrange
|
// Aucun chapitre : Mockito renvoie List.of() par défaut.
|
||||||
doNothing().when(arcRepository).deleteById("arc-1");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
arcService.deleteArc("arc-1");
|
arcService.deleteArc("arc-1");
|
||||||
|
|
||||||
// Assert
|
verify(arcRepository).deleteById("arc-1");
|
||||||
verify(arcRepository, times(1)).deleteById("arc-1");
|
verify(chapterRepository, never()).deleteById(anyString());
|
||||||
|
verify(sceneRepository, never()).deleteById(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteArc_CascadesChaptersAndScenes() {
|
||||||
|
Chapter chapter = Chapter.builder().id("chap-1").arcId("arc-1").name("C").build();
|
||||||
|
Scene s1 = Scene.builder().id("s-1").chapterId("chap-1").name("S1").build();
|
||||||
|
Scene s2 = Scene.builder().id("s-2").chapterId("chap-1").name("S2").build();
|
||||||
|
|
||||||
|
when(chapterRepository.findByArcId("arc-1")).thenReturn(List.of(chapter));
|
||||||
|
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of(s1, s2));
|
||||||
|
|
||||||
|
arcService.deleteArc("arc-1");
|
||||||
|
|
||||||
|
verify(sceneRepository).deleteById("s-1");
|
||||||
|
verify(sceneRepository).deleteById("s-2");
|
||||||
|
verify(chapterRepository).deleteById("chap-1");
|
||||||
|
verify(arcRepository).deleteById("arc-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetDeletionImpact() {
|
||||||
|
Chapter c1 = Chapter.builder().id("chap-1").arcId("arc-1").name("C1").build();
|
||||||
|
Chapter c2 = Chapter.builder().id("chap-2").arcId("arc-1").name("C2").build();
|
||||||
|
Scene s1 = Scene.builder().id("s-1").chapterId("chap-1").name("S1").build();
|
||||||
|
Scene s2 = Scene.builder().id("s-2").chapterId("chap-2").name("S2").build();
|
||||||
|
Scene s3 = Scene.builder().id("s-3").chapterId("chap-2").name("S3").build();
|
||||||
|
|
||||||
|
when(chapterRepository.findByArcId("arc-1")).thenReturn(List.of(c1, c2));
|
||||||
|
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of(s1));
|
||||||
|
when(sceneRepository.findByChapterId("chap-2")).thenReturn(List.of(s2, s3));
|
||||||
|
|
||||||
|
ArcService.DeletionImpact impact = arcService.getDeletionImpact("arc-1");
|
||||||
|
|
||||||
|
assertEquals(2, impact.chapters());
|
||||||
|
assertEquals(3, impact.scenes());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -1,7 +1,15 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
@@ -27,6 +35,14 @@ public class CampaignServiceTest {
|
|||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private CampaignRepository campaignRepository;
|
private CampaignRepository campaignRepository;
|
||||||
|
@Mock
|
||||||
|
private ArcRepository arcRepository;
|
||||||
|
@Mock
|
||||||
|
private ChapterRepository chapterRepository;
|
||||||
|
@Mock
|
||||||
|
private SceneRepository sceneRepository;
|
||||||
|
@Mock
|
||||||
|
private CharacterRepository characterRepository;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private CampaignService campaignService;
|
private CampaignService campaignService;
|
||||||
@@ -50,9 +66,13 @@ public class CampaignServiceTest {
|
|||||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||||
"New Campaign",
|
"New Campaign",
|
||||||
"Description",
|
"Description",
|
||||||
"lore-123"
|
"lore-123",
|
||||||
|
null
|
||||||
);
|
);
|
||||||
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
// Le repo renvoie la Campaign telle que passée — on teste la normalisation
|
||||||
|
// du loreId dans le service, pas le comportement du repo.
|
||||||
|
when(campaignRepository.save(any(Campaign.class)))
|
||||||
|
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Campaign result = campaignService.createCampaign(data);
|
Campaign result = campaignService.createCampaign(data);
|
||||||
@@ -69,9 +89,11 @@ public class CampaignServiceTest {
|
|||||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||||
"New Campaign",
|
"New Campaign",
|
||||||
"Description",
|
"Description",
|
||||||
|
null,
|
||||||
null
|
null
|
||||||
);
|
);
|
||||||
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
when(campaignRepository.save(any(Campaign.class)))
|
||||||
|
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Campaign result = campaignService.createCampaign(data);
|
Campaign result = campaignService.createCampaign(data);
|
||||||
@@ -88,9 +110,11 @@ public class CampaignServiceTest {
|
|||||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||||
"New Campaign",
|
"New Campaign",
|
||||||
"Description",
|
"Description",
|
||||||
" "
|
" ",
|
||||||
|
null
|
||||||
);
|
);
|
||||||
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
when(campaignRepository.save(any(Campaign.class)))
|
||||||
|
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Campaign result = campaignService.createCampaign(data);
|
Campaign result = campaignService.createCampaign(data);
|
||||||
@@ -151,7 +175,8 @@ public class CampaignServiceTest {
|
|||||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||||
"Updated Campaign",
|
"Updated Campaign",
|
||||||
"Updated Description",
|
"Updated Description",
|
||||||
"lore-456"
|
"lore-456",
|
||||||
|
null
|
||||||
);
|
);
|
||||||
when(campaignRepository.findById("campaign-1")).thenReturn(Optional.of(testCampaign));
|
when(campaignRepository.findById("campaign-1")).thenReturn(Optional.of(testCampaign));
|
||||||
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
||||||
@@ -171,7 +196,8 @@ public class CampaignServiceTest {
|
|||||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||||
"Updated Campaign",
|
"Updated Campaign",
|
||||||
"Updated Description",
|
"Updated Description",
|
||||||
"lore-456"
|
"lore-456",
|
||||||
|
null
|
||||||
);
|
);
|
||||||
when(campaignRepository.findById("invalid-id")).thenReturn(Optional.empty());
|
when(campaignRepository.findById("invalid-id")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
@@ -186,15 +212,75 @@ public class CampaignServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testDeleteCampaign() {
|
void testDeleteCampaign_EmptyCampaign() {
|
||||||
// Arrange
|
// Arrange : aucune dépendance ; Mockito renvoie List.of() par défaut.
|
||||||
doNothing().when(campaignRepository).deleteById("campaign-1");
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
campaignService.deleteCampaign("campaign-1");
|
campaignService.deleteCampaign("campaign-1");
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
verify(campaignRepository, times(1)).deleteById("campaign-1");
|
verify(campaignRepository, times(1)).deleteById("campaign-1");
|
||||||
|
verify(arcRepository, never()).deleteById(anyString());
|
||||||
|
verify(chapterRepository, never()).deleteById(anyString());
|
||||||
|
verify(sceneRepository, never()).deleteById(anyString());
|
||||||
|
verify(characterRepository, never()).deleteById(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteCampaign_CascadesArcsChaptersScenes() {
|
||||||
|
// Arrange : campagne avec 1 arc → 1 chapitre → 2 scènes.
|
||||||
|
Arc arc = Arc.builder().id("arc-1").campaignId("campaign-1").name("Arc 1").build();
|
||||||
|
Chapter chapter = Chapter.builder().id("chap-1").arcId("arc-1").name("Chap 1").build();
|
||||||
|
Scene scene1 = Scene.builder().id("scene-1").chapterId("chap-1").name("Scene 1").build();
|
||||||
|
Scene scene2 = Scene.builder().id("scene-2").chapterId("chap-1").name("Scene 2").build();
|
||||||
|
|
||||||
|
when(arcRepository.findByCampaignId("campaign-1")).thenReturn(List.of(arc));
|
||||||
|
when(chapterRepository.findByArcId("arc-1")).thenReturn(List.of(chapter));
|
||||||
|
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of(scene1, scene2));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
campaignService.deleteCampaign("campaign-1");
|
||||||
|
|
||||||
|
// Assert : tout disparaît, dans l'ordre feuilles → racine.
|
||||||
|
verify(sceneRepository).deleteById("scene-1");
|
||||||
|
verify(sceneRepository).deleteById("scene-2");
|
||||||
|
verify(chapterRepository).deleteById("chap-1");
|
||||||
|
verify(arcRepository).deleteById("arc-1");
|
||||||
|
verify(campaignRepository).deleteById("campaign-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteCampaign_CascadesCharacters() {
|
||||||
|
Character pc = Character.builder().id("char-1").campaignId("campaign-1").name("Alric").build();
|
||||||
|
when(characterRepository.findByCampaignId("campaign-1")).thenReturn(List.of(pc));
|
||||||
|
|
||||||
|
campaignService.deleteCampaign("campaign-1");
|
||||||
|
|
||||||
|
verify(characterRepository).deleteById("char-1");
|
||||||
|
verify(campaignRepository).deleteById("campaign-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetDeletionImpact() {
|
||||||
|
Arc arc = Arc.builder().id("arc-1").campaignId("campaign-1").name("Arc 1").build();
|
||||||
|
Chapter c1 = Chapter.builder().id("chap-1").arcId("arc-1").name("C1").build();
|
||||||
|
Chapter c2 = Chapter.builder().id("chap-2").arcId("arc-1").name("C2").build();
|
||||||
|
Scene s1 = Scene.builder().id("s-1").chapterId("chap-1").name("S1").build();
|
||||||
|
Scene s2 = Scene.builder().id("s-2").chapterId("chap-2").name("S2").build();
|
||||||
|
Scene s3 = Scene.builder().id("s-3").chapterId("chap-2").name("S3").build();
|
||||||
|
Character pc = Character.builder().id("char-1").campaignId("campaign-1").name("Alric").build();
|
||||||
|
|
||||||
|
when(arcRepository.findByCampaignId("campaign-1")).thenReturn(List.of(arc));
|
||||||
|
when(chapterRepository.findByArcId("arc-1")).thenReturn(List.of(c1, c2));
|
||||||
|
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of(s1));
|
||||||
|
when(sceneRepository.findByChapterId("chap-2")).thenReturn(List.of(s2, s3));
|
||||||
|
when(characterRepository.findByCampaignId("campaign-1")).thenReturn(List.of(pc));
|
||||||
|
|
||||||
|
CampaignService.DeletionImpact impact = campaignService.getDeletionImpact("campaign-1");
|
||||||
|
|
||||||
|
assertEquals(1, impact.arcs());
|
||||||
|
assertEquals(2, impact.chapters());
|
||||||
|
assertEquals(3, impact.scenes());
|
||||||
|
assertEquals(1, impact.characters());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Chapter;
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
@@ -14,6 +16,7 @@ import java.util.Optional;
|
|||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,6 +29,8 @@ public class ChapterServiceTest {
|
|||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private ChapterRepository chapterRepository;
|
private ChapterRepository chapterRepository;
|
||||||
|
@Mock
|
||||||
|
private SceneRepository sceneRepository;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private ChapterService chapterService;
|
private ChapterService chapterService;
|
||||||
@@ -157,15 +162,36 @@ public class ChapterServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testDeleteChapter() {
|
void testDeleteChapter_EmptyChapter() {
|
||||||
// Arrange
|
// Aucune scène : Mockito renvoie List.of() par défaut.
|
||||||
doNothing().when(chapterRepository).deleteById("chapter-1");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
chapterService.deleteChapter("chapter-1");
|
chapterService.deleteChapter("chapter-1");
|
||||||
|
|
||||||
// Assert
|
verify(chapterRepository).deleteById("chapter-1");
|
||||||
verify(chapterRepository, times(1)).deleteById("chapter-1");
|
verify(sceneRepository, never()).deleteById(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteChapter_CascadesScenes() {
|
||||||
|
Scene s1 = Scene.builder().id("s-1").chapterId("chapter-1").name("S1").build();
|
||||||
|
Scene s2 = Scene.builder().id("s-2").chapterId("chapter-1").name("S2").build();
|
||||||
|
when(sceneRepository.findByChapterId("chapter-1")).thenReturn(List.of(s1, s2));
|
||||||
|
|
||||||
|
chapterService.deleteChapter("chapter-1");
|
||||||
|
|
||||||
|
verify(sceneRepository).deleteById("s-1");
|
||||||
|
verify(sceneRepository).deleteById("s-2");
|
||||||
|
verify(chapterRepository).deleteById("chapter-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetDeletionImpact() {
|
||||||
|
Scene s1 = Scene.builder().id("s-1").chapterId("chapter-1").name("S1").build();
|
||||||
|
Scene s2 = Scene.builder().id("s-2").chapterId("chapter-1").name("S2").build();
|
||||||
|
when(sceneRepository.findByChapterId("chapter-1")).thenReturn(List.of(s1, s2));
|
||||||
|
|
||||||
|
ChapterService.DeletionImpact impact = chapterService.getDeletionImpact("chapter-1");
|
||||||
|
|
||||||
|
assertEquals(2, impact.scenes());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -0,0 +1,323 @@
|
|||||||
|
package com.loremind.application.conversationcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.conversationcontext.Conversation;
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
import com.loremind.domain.conversationcontext.ports.ConversationRepository;
|
||||||
|
import com.loremind.domain.conversationcontext.ports.ConversationTitleGenerator;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires de ConversationService.
|
||||||
|
* Focus sur :
|
||||||
|
* - la validation XOR de l'ancrage (loreId XOR campaignId),
|
||||||
|
* - la coherence entityType/entityId (tous deux null ou tous deux non-null),
|
||||||
|
* - le fallback du titre a la creation,
|
||||||
|
* - la validation des roles et contenus de message,
|
||||||
|
* - l'auto-generation de titre (cas succes + court-circuit si pas de messages).
|
||||||
|
*/
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class ConversationServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ConversationRepository repository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ConversationTitleGenerator titleGenerator;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private ConversationService service;
|
||||||
|
|
||||||
|
// ---------- create : validation XOR de l'ancrage -----------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_rejectsBothAnchorsNull() {
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
"t", null, null, null, null);
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||||
|
assertEquals("Exactement un parent attendu : loreId XOR campaignId", ex.getMessage());
|
||||||
|
verifyNoInteractions(repository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_rejectsBothAnchorsPresent() {
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
"t", "lore-1", "camp-1", null, null);
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||||
|
verifyNoInteractions(repository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_rejectsBlankLoreIdAsAbsent() {
|
||||||
|
// Blank (espaces) = absent : c'est la regle du service.
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
"t", " ", " ", null, null);
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_rejectsEntityTypeWithoutEntityId() {
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
"t", "lore-1", null, "page", null);
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||||
|
assertEquals("entityType et entityId doivent etre tous deux null ou tous deux non-null", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_rejectsEntityIdWithoutEntityType() {
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
"t", "lore-1", null, null, "page-42");
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- create : cas nominaux --------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_withLoreAnchor_persistsBuiltConversation() {
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
"Discussion Thorin", "lore-1", null, "page", "page-42");
|
||||||
|
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
Conversation result = service.create(data);
|
||||||
|
|
||||||
|
ArgumentCaptor<Conversation> captor = ArgumentCaptor.forClass(Conversation.class);
|
||||||
|
verify(repository).save(captor.capture());
|
||||||
|
Conversation saved = captor.getValue();
|
||||||
|
assertEquals("Discussion Thorin", saved.getTitle());
|
||||||
|
assertEquals("lore-1", saved.getLoreId());
|
||||||
|
assertEquals("page", saved.getEntityType());
|
||||||
|
assertEquals("page-42", saved.getEntityId());
|
||||||
|
assertEquals(saved, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_withCampaignAnchor_andNoEntityFocus_persistsRootLevel() {
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
null, null, "camp-1", null, null);
|
||||||
|
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
service.create(data);
|
||||||
|
|
||||||
|
ArgumentCaptor<Conversation> captor = ArgumentCaptor.forClass(Conversation.class);
|
||||||
|
verify(repository).save(captor.capture());
|
||||||
|
assertEquals("Nouvelle conversation", captor.getValue().getTitle(),
|
||||||
|
"Titre absent -> fallback par defaut");
|
||||||
|
assertEquals("camp-1", captor.getValue().getCampaignId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_trimsProvidedTitle() {
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
" Mon titre ", "lore-1", null, null, null);
|
||||||
|
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
service.create(data);
|
||||||
|
|
||||||
|
ArgumentCaptor<Conversation> captor = ArgumentCaptor.forClass(Conversation.class);
|
||||||
|
verify(repository).save(captor.capture());
|
||||||
|
assertEquals("Mon titre", captor.getValue().getTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_blankTitle_fallsBackToDefault() {
|
||||||
|
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||||
|
" ", "lore-1", null, null, null);
|
||||||
|
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
service.create(data);
|
||||||
|
|
||||||
|
ArgumentCaptor<Conversation> captor = ArgumentCaptor.forClass(Conversation.class);
|
||||||
|
verify(repository).save(captor.capture());
|
||||||
|
assertEquals("Nouvelle conversation", captor.getValue().getTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- getById / listByContext / delete --------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getById_delegatesToRepository() {
|
||||||
|
Conversation conv = Conversation.builder().id("c-1").build();
|
||||||
|
when(repository.findById("c-1")).thenReturn(Optional.of(conv));
|
||||||
|
|
||||||
|
assertEquals(Optional.of(conv), service.getById("c-1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listByContext_validatesAnchorBeforeQuerying() {
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> service.listByContext(null, null, null, null));
|
||||||
|
verifyNoInteractions(repository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listByContext_delegates_whenAnchorValid() {
|
||||||
|
Conversation c = Conversation.builder().id("c-1").build();
|
||||||
|
when(repository.findByContext("lore-1", null, null, null)).thenReturn(List.of(c));
|
||||||
|
|
||||||
|
List<Conversation> result = service.listByContext("lore-1", null, null, null);
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void delete_delegatesToRepository() {
|
||||||
|
service.delete("c-1");
|
||||||
|
verify(repository).deleteById("c-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- rename -----------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rename_rejectsNullTitle() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.rename("c-1", null));
|
||||||
|
verify(repository, never()).updateTitle(anyString(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rename_rejectsBlankTitle() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.rename("c-1", " "));
|
||||||
|
verify(repository, never()).updateTitle(anyString(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rename_rejectsUnknownConversation() {
|
||||||
|
when(repository.findById("unknown")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> service.rename("unknown", "Nouveau titre"));
|
||||||
|
assertEquals("Conversation introuvable : unknown", ex.getMessage());
|
||||||
|
verify(repository, never()).updateTitle(anyString(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rename_trimsTitleBeforePersist() {
|
||||||
|
when(repository.findById("c-1")).thenReturn(Optional.of(Conversation.builder().id("c-1").build()));
|
||||||
|
|
||||||
|
service.rename("c-1", " Nouveau titre ");
|
||||||
|
|
||||||
|
verify(repository).updateTitle("c-1", "Nouveau titre");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- appendMessage ----------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void appendMessage_rejectsInvalidRole() {
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> service.appendMessage("c-1", "admin", "hello"));
|
||||||
|
assertEquals("Role invalide : admin", ex.getMessage());
|
||||||
|
verifyNoInteractions(repository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void appendMessage_rejectsNullRole() {
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> service.appendMessage("c-1", null, "hello"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void appendMessage_rejectsNullContent() {
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> service.appendMessage("c-1", "user", null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void appendMessage_rejectsEmptyContent() {
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> service.appendMessage("c-1", "user", ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void appendMessage_acceptsAllThreeCanonicalRoles() {
|
||||||
|
ConversationMessage returned = ConversationMessage.builder().id("m").build();
|
||||||
|
when(repository.appendMessage(eq("c-1"), any())).thenReturn(returned);
|
||||||
|
|
||||||
|
for (String role : new String[]{"user", "assistant", "system"}) {
|
||||||
|
service.appendMessage("c-1", role, "contenu");
|
||||||
|
}
|
||||||
|
|
||||||
|
ArgumentCaptor<ConversationMessage> captor = ArgumentCaptor.forClass(ConversationMessage.class);
|
||||||
|
verify(repository, times(3)).appendMessage(eq("c-1"), captor.capture());
|
||||||
|
assertEquals("user", captor.getAllValues().get(0).getRole());
|
||||||
|
assertEquals("assistant", captor.getAllValues().get(1).getRole());
|
||||||
|
assertEquals("system", captor.getAllValues().get(2).getRole());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void appendMessage_passesContentVerbatim() {
|
||||||
|
ConversationMessage returned = ConversationMessage.builder().id("m-1").build();
|
||||||
|
when(repository.appendMessage(eq("c-1"), any())).thenReturn(returned);
|
||||||
|
|
||||||
|
service.appendMessage("c-1", "user", " hello avec espaces ");
|
||||||
|
|
||||||
|
ArgumentCaptor<ConversationMessage> captor = ArgumentCaptor.forClass(ConversationMessage.class);
|
||||||
|
verify(repository).appendMessage(eq("c-1"), captor.capture());
|
||||||
|
// Le service NE trim PAS le contenu — seul le titre est trim.
|
||||||
|
assertEquals(" hello avec espaces ", captor.getValue().getContent());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- autoGenerateTitle ------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void autoGenerateTitle_throws_whenConversationNotFound() {
|
||||||
|
when(repository.findById("unknown")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.autoGenerateTitle("unknown"));
|
||||||
|
verifyNoInteractions(titleGenerator);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void autoGenerateTitle_shortCircuits_whenNoMessages() {
|
||||||
|
Conversation conv = Conversation.builder().id("c-1").title("Titre existant").messages(List.of()).build();
|
||||||
|
when(repository.findById("c-1")).thenReturn(Optional.of(conv));
|
||||||
|
|
||||||
|
String result = service.autoGenerateTitle("c-1");
|
||||||
|
|
||||||
|
assertEquals("Titre existant", result);
|
||||||
|
verifyNoInteractions(titleGenerator);
|
||||||
|
verify(repository, never()).updateTitle(anyString(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void autoGenerateTitle_shortCircuits_whenMessagesIsNull() {
|
||||||
|
Conversation conv = new Conversation(); // @NoArgsConstructor -> messages == null
|
||||||
|
conv.setId("c-1");
|
||||||
|
conv.setTitle("Titre");
|
||||||
|
when(repository.findById("c-1")).thenReturn(Optional.of(conv));
|
||||||
|
|
||||||
|
assertEquals("Titre", service.autoGenerateTitle("c-1"));
|
||||||
|
verifyNoInteractions(titleGenerator);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void autoGenerateTitle_generatesAndPersists_whenMessagesPresent() {
|
||||||
|
List<ConversationMessage> seeds = List.of(
|
||||||
|
ConversationMessage.builder().role("user").content("bonjour").build(),
|
||||||
|
ConversationMessage.builder().role("assistant").content("salut").build());
|
||||||
|
Conversation conv = Conversation.builder().id("c-1").title("Ancien").messages(seeds).build();
|
||||||
|
|
||||||
|
when(repository.findById("c-1")).thenReturn(Optional.of(conv));
|
||||||
|
when(titleGenerator.generate(seeds)).thenReturn("Premier echange poli");
|
||||||
|
|
||||||
|
String result = service.autoGenerateTitle("c-1");
|
||||||
|
|
||||||
|
assertEquals("Premier echange poli", result);
|
||||||
|
verify(repository).updateTitle("c-1", "Premier echange poli");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import com.loremind.domain.campaigncontext.SceneBranch;
|
|||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -40,6 +41,8 @@ public class CampaignStructuralContextBuilderTest {
|
|||||||
private ChapterRepository chapterRepository;
|
private ChapterRepository chapterRepository;
|
||||||
@Mock
|
@Mock
|
||||||
private SceneRepository sceneRepository;
|
private SceneRepository sceneRepository;
|
||||||
|
@Mock
|
||||||
|
private CharacterRepository characterRepository;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private CampaignStructuralContextBuilder builder;
|
private CampaignStructuralContextBuilder builder;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
|||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.ChatMessage;
|
import com.loremind.domain.generationcontext.ChatMessage;
|
||||||
import com.loremind.domain.generationcontext.ChatRequest;
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||||
@@ -46,6 +47,7 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
|
|
||||||
private CampaignStructuralContext campaignCtx;
|
private CampaignStructuralContext campaignCtx;
|
||||||
private List<ChatMessage> messages;
|
private List<ChatMessage> messages;
|
||||||
|
private Consumer<ChatUsage> onUsage;
|
||||||
private Consumer<String> onToken;
|
private Consumer<String> onToken;
|
||||||
private Runnable onComplete;
|
private Runnable onComplete;
|
||||||
private Consumer<Throwable> onError;
|
private Consumer<Throwable> onError;
|
||||||
@@ -57,6 +59,7 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
.campaignName("X").campaignDescription("d")
|
.campaignName("X").campaignDescription("d")
|
||||||
.build();
|
.build();
|
||||||
messages = List.of();
|
messages = List.of();
|
||||||
|
onUsage = mock(Consumer.class);
|
||||||
onToken = mock(Consumer.class);
|
onToken = mock(Consumer.class);
|
||||||
onComplete = mock(Runnable.class);
|
onComplete = mock(Runnable.class);
|
||||||
onError = mock(Consumer.class);
|
onError = mock(Consumer.class);
|
||||||
@@ -67,7 +70,7 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
when(campaignRepository.findById("missing")).thenReturn(Optional.empty());
|
when(campaignRepository.findById("missing")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
assertThrows(IllegalArgumentException.class,
|
assertThrows(IllegalArgumentException.class,
|
||||||
() -> useCase.execute("missing", null, null, messages, onToken, onComplete, onError));
|
() -> useCase.execute("missing", null, null, messages, onUsage, onToken, onComplete, onError));
|
||||||
verifyNoInteractions(aiChatProvider);
|
verifyNoInteractions(aiChatProvider);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,10 +80,10 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
when(campaignRepository.findById("c-1")).thenReturn(Optional.of(standalone));
|
when(campaignRepository.findById("c-1")).thenReturn(Optional.of(standalone));
|
||||||
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
||||||
|
|
||||||
useCase.execute("c-1", null, null, messages, onToken, onComplete, onError);
|
useCase.execute("c-1", null, null, messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), eq(onToken), eq(onComplete), eq(onError));
|
verify(aiChatProvider).streamChat(captor.capture(), eq(onUsage), eq(onToken), eq(onComplete), eq(onError));
|
||||||
ChatRequest req = captor.getValue();
|
ChatRequest req = captor.getValue();
|
||||||
assertSame(campaignCtx, req.getCampaignContext());
|
assertSame(campaignCtx, req.getCampaignContext());
|
||||||
assertNull(req.getLoreContext());
|
assertNull(req.getLoreContext());
|
||||||
@@ -100,10 +103,10 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
||||||
when(loreContextBuilder.buildOptional("lore-1")).thenReturn(Optional.of(loreCtx));
|
when(loreContextBuilder.buildOptional("lore-1")).thenReturn(Optional.of(loreCtx));
|
||||||
|
|
||||||
useCase.execute("c-1", null, null, messages, onToken, onComplete, onError);
|
useCase.execute("c-1", null, null, messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any());
|
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any(), any());
|
||||||
assertSame(loreCtx, captor.getValue().getLoreContext());
|
assertSame(loreCtx, captor.getValue().getLoreContext());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,10 +118,10 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
||||||
when(loreContextBuilder.buildOptional("lore-ghost")).thenReturn(Optional.empty());
|
when(loreContextBuilder.buildOptional("lore-ghost")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
useCase.execute("c-1", null, null, messages, onToken, onComplete, onError);
|
useCase.execute("c-1", null, null, messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any());
|
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any(), any());
|
||||||
assertNull(captor.getValue().getLoreContext());
|
assertNull(captor.getValue().getLoreContext());
|
||||||
// La requete doit tout de meme partir (pas d'exception).
|
// La requete doit tout de meme partir (pas d'exception).
|
||||||
}
|
}
|
||||||
@@ -133,10 +136,10 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
||||||
when(narrativeEntityContextBuilder.build("scene", "s-1")).thenReturn(entity);
|
when(narrativeEntityContextBuilder.build("scene", "s-1")).thenReturn(entity);
|
||||||
|
|
||||||
useCase.execute("c-1", "scene", "s-1", messages, onToken, onComplete, onError);
|
useCase.execute("c-1", "scene", "s-1", messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any());
|
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any(), any());
|
||||||
assertSame(entity, captor.getValue().getNarrativeEntity());
|
assertSame(entity, captor.getValue().getNarrativeEntity());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,10 +149,10 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
when(campaignRepository.findById("c-1")).thenReturn(Optional.of(standalone));
|
when(campaignRepository.findById("c-1")).thenReturn(Optional.of(standalone));
|
||||||
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
when(campaignContextBuilder.build("c-1")).thenReturn(campaignCtx);
|
||||||
|
|
||||||
useCase.execute("c-1", "scene", " ", messages, onToken, onComplete, onError);
|
useCase.execute("c-1", "scene", " ", messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any());
|
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any(), any());
|
||||||
assertNull(captor.getValue().getNarrativeEntity());
|
assertNull(captor.getValue().getNarrativeEntity());
|
||||||
verifyNoInteractions(narrativeEntityContextBuilder);
|
verifyNoInteractions(narrativeEntityContextBuilder);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.loremind.application.generationcontext;
|
|||||||
|
|
||||||
import com.loremind.domain.generationcontext.ChatMessage;
|
import com.loremind.domain.generationcontext.ChatMessage;
|
||||||
import com.loremind.domain.generationcontext.ChatRequest;
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||||
import com.loremind.domain.lorecontext.FieldType;
|
import com.loremind.domain.lorecontext.FieldType;
|
||||||
@@ -46,6 +47,7 @@ public class StreamChatForLoreUseCaseTest {
|
|||||||
|
|
||||||
private LoreStructuralContext loreCtx;
|
private LoreStructuralContext loreCtx;
|
||||||
private List<ChatMessage> messages;
|
private List<ChatMessage> messages;
|
||||||
|
private Consumer<ChatUsage> onUsage;
|
||||||
private Consumer<String> onToken;
|
private Consumer<String> onToken;
|
||||||
private Runnable onComplete;
|
private Runnable onComplete;
|
||||||
private Consumer<Throwable> onError;
|
private Consumer<Throwable> onError;
|
||||||
@@ -58,6 +60,7 @@ public class StreamChatForLoreUseCaseTest {
|
|||||||
.folders(Collections.emptyMap())
|
.folders(Collections.emptyMap())
|
||||||
.build();
|
.build();
|
||||||
messages = List.of();
|
messages = List.of();
|
||||||
|
onUsage = mock(Consumer.class);
|
||||||
onToken = mock(Consumer.class);
|
onToken = mock(Consumer.class);
|
||||||
onComplete = mock(Runnable.class);
|
onComplete = mock(Runnable.class);
|
||||||
onError = mock(Consumer.class);
|
onError = mock(Consumer.class);
|
||||||
@@ -67,10 +70,10 @@ public class StreamChatForLoreUseCaseTest {
|
|||||||
void testExecute_NoPageId_SendsRequestWithoutPageContext() {
|
void testExecute_NoPageId_SendsRequestWithoutPageContext() {
|
||||||
when(loreContextBuilder.build("lore-1")).thenReturn(loreCtx);
|
when(loreContextBuilder.build("lore-1")).thenReturn(loreCtx);
|
||||||
|
|
||||||
useCase.execute("lore-1", null, messages, onToken, onComplete, onError);
|
useCase.execute("lore-1", null, messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), eq(onToken), eq(onComplete), eq(onError));
|
verify(aiChatProvider).streamChat(captor.capture(), eq(onUsage), eq(onToken), eq(onComplete), eq(onError));
|
||||||
ChatRequest req = captor.getValue();
|
ChatRequest req = captor.getValue();
|
||||||
assertSame(loreCtx, req.getLoreContext());
|
assertSame(loreCtx, req.getLoreContext());
|
||||||
assertNull(req.getPageContext());
|
assertNull(req.getPageContext());
|
||||||
@@ -81,10 +84,10 @@ public class StreamChatForLoreUseCaseTest {
|
|||||||
void testExecute_BlankPageId_TreatedAsNoPage() {
|
void testExecute_BlankPageId_TreatedAsNoPage() {
|
||||||
when(loreContextBuilder.build("lore-1")).thenReturn(loreCtx);
|
when(loreContextBuilder.build("lore-1")).thenReturn(loreCtx);
|
||||||
|
|
||||||
useCase.execute("lore-1", " ", messages, onToken, onComplete, onError);
|
useCase.execute("lore-1", " ", messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any());
|
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any(), any());
|
||||||
assertNull(captor.getValue().getPageContext());
|
assertNull(captor.getValue().getPageContext());
|
||||||
verifyNoInteractions(pageRepository);
|
verifyNoInteractions(pageRepository);
|
||||||
}
|
}
|
||||||
@@ -108,10 +111,10 @@ public class StreamChatForLoreUseCaseTest {
|
|||||||
when(pageRepository.findById("p-1")).thenReturn(Optional.of(page));
|
when(pageRepository.findById("p-1")).thenReturn(Optional.of(page));
|
||||||
when(templateRepository.findById("tpl-1")).thenReturn(Optional.of(tpl));
|
when(templateRepository.findById("tpl-1")).thenReturn(Optional.of(tpl));
|
||||||
|
|
||||||
useCase.execute("lore-1", "p-1", messages, onToken, onComplete, onError);
|
useCase.execute("lore-1", "p-1", messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any());
|
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any(), any());
|
||||||
ChatRequest req = captor.getValue();
|
ChatRequest req = captor.getValue();
|
||||||
assertNotNull(req.getPageContext());
|
assertNotNull(req.getPageContext());
|
||||||
assertEquals("Alice", req.getPageContext().getTitle());
|
assertEquals("Alice", req.getPageContext().getTitle());
|
||||||
@@ -130,10 +133,10 @@ public class StreamChatForLoreUseCaseTest {
|
|||||||
when(loreContextBuilder.build("lore-1")).thenReturn(loreCtx);
|
when(loreContextBuilder.build("lore-1")).thenReturn(loreCtx);
|
||||||
when(pageRepository.findById("p-1")).thenReturn(Optional.of(page));
|
when(pageRepository.findById("p-1")).thenReturn(Optional.of(page));
|
||||||
|
|
||||||
useCase.execute("lore-1", "p-1", messages, onToken, onComplete, onError);
|
useCase.execute("lore-1", "p-1", messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any());
|
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any(), any());
|
||||||
var pageCtx = captor.getValue().getPageContext();
|
var pageCtx = captor.getValue().getPageContext();
|
||||||
assertNotNull(pageCtx);
|
assertNotNull(pageCtx);
|
||||||
assertEquals("Orphan", pageCtx.getTitle());
|
assertEquals("Orphan", pageCtx.getTitle());
|
||||||
@@ -153,10 +156,10 @@ public class StreamChatForLoreUseCaseTest {
|
|||||||
when(pageRepository.findById("p-1")).thenReturn(Optional.of(page));
|
when(pageRepository.findById("p-1")).thenReturn(Optional.of(page));
|
||||||
when(templateRepository.findById("tpl-ghost")).thenReturn(Optional.empty());
|
when(templateRepository.findById("tpl-ghost")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
useCase.execute("lore-1", "p-1", messages, onToken, onComplete, onError);
|
useCase.execute("lore-1", "p-1", messages, onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
ArgumentCaptor<ChatRequest> captor = ArgumentCaptor.forClass(ChatRequest.class);
|
||||||
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any());
|
verify(aiChatProvider).streamChat(captor.capture(), any(), any(), any(), any());
|
||||||
var pageCtx = captor.getValue().getPageContext();
|
var pageCtx = captor.getValue().getPageContext();
|
||||||
assertEquals("?", pageCtx.getTemplateName());
|
assertEquals("?", pageCtx.getTemplateName());
|
||||||
assertTrue(pageCtx.getTemplateFields().isEmpty());
|
assertTrue(pageCtx.getTemplateFields().isEmpty());
|
||||||
@@ -168,7 +171,7 @@ public class StreamChatForLoreUseCaseTest {
|
|||||||
when(pageRepository.findById("missing")).thenReturn(Optional.empty());
|
when(pageRepository.findById("missing")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
assertThrows(IllegalArgumentException.class,
|
assertThrows(IllegalArgumentException.class,
|
||||||
() -> useCase.execute("lore-1", "missing", messages, onToken, onComplete, onError));
|
() -> useCase.execute("lore-1", "missing", messages, onUsage, onToken, onComplete, onError));
|
||||||
verifyNoInteractions(aiChatProvider);
|
verifyNoInteractions(aiChatProvider);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package com.loremind.application.lorecontext;
|
package com.loremind.application.lorecontext;
|
||||||
|
|
||||||
import com.loremind.domain.lorecontext.LoreNode;
|
import com.loremind.domain.lorecontext.LoreNode;
|
||||||
|
import com.loremind.domain.lorecontext.Page;
|
||||||
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
||||||
|
import com.loremind.domain.lorecontext.ports.PageRepository;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
@@ -15,6 +17,7 @@ import java.util.Optional;
|
|||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,6 +29,7 @@ import static org.mockito.Mockito.*;
|
|||||||
public class LoreNodeServiceTest {
|
public class LoreNodeServiceTest {
|
||||||
|
|
||||||
@Mock private LoreNodeRepository loreNodeRepository;
|
@Mock private LoreNodeRepository loreNodeRepository;
|
||||||
|
@Mock private PageRepository pageRepository;
|
||||||
|
|
||||||
@InjectMocks private LoreNodeService loreNodeService;
|
@InjectMocks private LoreNodeService loreNodeService;
|
||||||
|
|
||||||
@@ -118,8 +122,66 @@ public class LoreNodeServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testDelete() {
|
void testDelete_LeafFolder() {
|
||||||
|
// Aucun descendant, aucune page : seul le dossier est supprimé.
|
||||||
loreNodeService.deleteLoreNode("n-1");
|
loreNodeService.deleteLoreNode("n-1");
|
||||||
verify(loreNodeRepository).deleteById("n-1");
|
verify(loreNodeRepository).deleteById("n-1");
|
||||||
|
verify(pageRepository, never()).deleteById(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDelete_CascadesPagesOfRoot() {
|
||||||
|
Page p1 = Page.builder().id("p-1").nodeId("n-1").title("P1").build();
|
||||||
|
Page p2 = Page.builder().id("p-2").nodeId("n-1").title("P2").build();
|
||||||
|
when(pageRepository.findByNodeId("n-1")).thenReturn(List.of(p1, p2));
|
||||||
|
|
||||||
|
loreNodeService.deleteLoreNode("n-1");
|
||||||
|
|
||||||
|
verify(pageRepository).deleteById("p-1");
|
||||||
|
verify(pageRepository).deleteById("p-2");
|
||||||
|
verify(loreNodeRepository).deleteById("n-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDelete_CascadesSubfoldersRecursive() {
|
||||||
|
// n-1 → n-1a → n-1a1 ; chaque feuille a une page.
|
||||||
|
LoreNode mid = LoreNode.builder().id("n-1a").parentId("n-1").loreId("lore-1").name("mid").build();
|
||||||
|
LoreNode leaf = LoreNode.builder().id("n-1a1").parentId("n-1a").loreId("lore-1").name("leaf").build();
|
||||||
|
Page pageOnLeaf = Page.builder().id("p-leaf").nodeId("n-1a1").title("P").build();
|
||||||
|
|
||||||
|
when(loreNodeRepository.findByParentId("n-1")).thenReturn(List.of(mid));
|
||||||
|
when(loreNodeRepository.findByParentId("n-1a")).thenReturn(List.of(leaf));
|
||||||
|
when(pageRepository.findByNodeId("n-1a1")).thenReturn(List.of(pageOnLeaf));
|
||||||
|
|
||||||
|
loreNodeService.deleteLoreNode("n-1");
|
||||||
|
|
||||||
|
// Feuilles d'abord (pages puis dossier leaf), puis mid, puis la racine.
|
||||||
|
verify(pageRepository).deleteById("p-leaf");
|
||||||
|
verify(loreNodeRepository).deleteById("n-1a1");
|
||||||
|
verify(loreNodeRepository).deleteById("n-1a");
|
||||||
|
verify(loreNodeRepository).deleteById("n-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetDeletionImpact_CountsSubfoldersAndPages() {
|
||||||
|
LoreNode sub1 = LoreNode.builder().id("s-1").parentId("n-1").loreId("lore-1").name("s1").build();
|
||||||
|
LoreNode sub2 = LoreNode.builder().id("s-2").parentId("n-1").loreId("lore-1").name("s2").build();
|
||||||
|
LoreNode subsub = LoreNode.builder().id("s-1a").parentId("s-1").loreId("lore-1").name("s1a").build();
|
||||||
|
Page p1 = Page.builder().id("p-1").nodeId("n-1").title("P1").build();
|
||||||
|
Page p2 = Page.builder().id("p-2").nodeId("s-1").title("P2").build();
|
||||||
|
Page p3 = Page.builder().id("p-3").nodeId("s-1a").title("P3").build();
|
||||||
|
|
||||||
|
when(loreNodeRepository.findByParentId("n-1")).thenReturn(List.of(sub1, sub2));
|
||||||
|
when(loreNodeRepository.findByParentId("s-1")).thenReturn(List.of(subsub));
|
||||||
|
when(pageRepository.findByNodeId("n-1")).thenReturn(List.of(p1));
|
||||||
|
when(pageRepository.findByNodeId("s-1")).thenReturn(List.of(p2));
|
||||||
|
when(pageRepository.findByNodeId("s-2")).thenReturn(List.of());
|
||||||
|
when(pageRepository.findByNodeId("s-1a")).thenReturn(List.of(p3));
|
||||||
|
|
||||||
|
LoreNodeService.DeletionImpact impact = loreNodeService.getDeletionImpact("n-1");
|
||||||
|
|
||||||
|
// 3 sous-dossiers (sub1, sub2, subsub) — on ne compte pas la racine n-1.
|
||||||
|
assertEquals(3, impact.folders());
|
||||||
|
assertEquals(3, impact.pages());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
package com.loremind.application.lorecontext;
|
package com.loremind.application.lorecontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.lorecontext.Lore;
|
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.ports.LoreNodeRepository;
|
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
||||||
import com.loremind.domain.lorecontext.ports.LoreRepository;
|
import com.loremind.domain.lorecontext.ports.LoreRepository;
|
||||||
import com.loremind.domain.lorecontext.ports.PageRepository;
|
import com.loremind.domain.lorecontext.ports.PageRepository;
|
||||||
|
import com.loremind.domain.lorecontext.ports.TemplateRepository;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
@@ -17,6 +23,7 @@ import java.util.Optional;
|
|||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -30,6 +37,8 @@ public class LoreServiceTest {
|
|||||||
@Mock private LoreRepository loreRepository;
|
@Mock private LoreRepository loreRepository;
|
||||||
@Mock private LoreNodeRepository loreNodeRepository;
|
@Mock private LoreNodeRepository loreNodeRepository;
|
||||||
@Mock private PageRepository pageRepository;
|
@Mock private PageRepository pageRepository;
|
||||||
|
@Mock private TemplateRepository templateRepository;
|
||||||
|
@Mock private CampaignRepository campaignRepository;
|
||||||
|
|
||||||
@InjectMocks private LoreService loreService;
|
@InjectMocks private LoreService loreService;
|
||||||
|
|
||||||
@@ -134,8 +143,67 @@ public class LoreServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testDeleteLore_DelegatesToRepository() {
|
void testDeleteLore_EmptyLore() {
|
||||||
|
// Aucun dossier / page / template / campagne : seul le Lore est supprimé.
|
||||||
loreService.deleteLore("lore-1");
|
loreService.deleteLore("lore-1");
|
||||||
verify(loreRepository).deleteById("lore-1");
|
verify(loreRepository).deleteById("lore-1");
|
||||||
|
verify(loreNodeRepository, never()).deleteById(anyString());
|
||||||
|
verify(pageRepository, never()).deleteById(anyString());
|
||||||
|
verify(templateRepository, never()).deleteById(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteLore_CascadesFoldersPagesTemplates() {
|
||||||
|
LoreNode node = LoreNode.builder().id("n-1").loreId("lore-1").name("F").build();
|
||||||
|
Page page = Page.builder().id("p-1").loreId("lore-1").nodeId("n-1").title("P").build();
|
||||||
|
Template template = Template.builder().id("t-1").loreId("lore-1").name("T").build();
|
||||||
|
|
||||||
|
when(pageRepository.findByLoreId("lore-1")).thenReturn(List.of(page));
|
||||||
|
when(loreNodeRepository.findByLoreId("lore-1")).thenReturn(List.of(node));
|
||||||
|
when(templateRepository.findByLoreId("lore-1")).thenReturn(List.of(template));
|
||||||
|
|
||||||
|
loreService.deleteLore("lore-1");
|
||||||
|
|
||||||
|
verify(pageRepository).deleteById("p-1");
|
||||||
|
verify(loreNodeRepository).deleteById("n-1");
|
||||||
|
verify(templateRepository).deleteById("t-1");
|
||||||
|
verify(loreRepository).deleteById("lore-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteLore_DetachesCampaignsInsteadOfDeleting() {
|
||||||
|
Campaign attached = Campaign.builder().id("c-1").loreId("lore-1").name("C1").build();
|
||||||
|
Campaign other = Campaign.builder().id("c-2").loreId("lore-other").name("C2").build();
|
||||||
|
Campaign orphan = Campaign.builder().id("c-3").loreId(null).name("C3").build();
|
||||||
|
when(campaignRepository.findAll()).thenReturn(List.of(attached, other, orphan));
|
||||||
|
when(campaignRepository.save(any(Campaign.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
loreService.deleteLore("lore-1");
|
||||||
|
|
||||||
|
// Seule la campagne attachée est re-sauvegardée (avec loreId=null).
|
||||||
|
ArgumentCaptor<Campaign> captor = ArgumentCaptor.forClass(Campaign.class);
|
||||||
|
verify(campaignRepository, times(1)).save(captor.capture());
|
||||||
|
assertEquals("c-1", captor.getValue().getId());
|
||||||
|
assertNull(captor.getValue().getLoreId());
|
||||||
|
// Aucune campagne n'est supprimée.
|
||||||
|
verify(campaignRepository, never()).deleteById(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetDeletionImpact() {
|
||||||
|
Template t1 = Template.builder().id("t-1").loreId("lore-1").name("T").build();
|
||||||
|
Campaign attached = Campaign.builder().id("c-1").loreId("lore-1").name("C").build();
|
||||||
|
Campaign unrelated = Campaign.builder().id("c-2").loreId("lore-other").name("C2").build();
|
||||||
|
when(loreNodeRepository.countByLoreId("lore-1")).thenReturn(4L);
|
||||||
|
when(pageRepository.countByLoreId("lore-1")).thenReturn(12L);
|
||||||
|
when(templateRepository.findByLoreId("lore-1")).thenReturn(List.of(t1));
|
||||||
|
when(campaignRepository.findAll()).thenReturn(List.of(attached, unrelated));
|
||||||
|
|
||||||
|
LoreService.DeletionImpact impact = loreService.getDeletionImpact("lore-1");
|
||||||
|
|
||||||
|
assertEquals(4, impact.folders());
|
||||||
|
assertEquals(12, impact.pages());
|
||||||
|
assertEquals(1, impact.templates());
|
||||||
|
assertEquals(1, impact.detachedCampaigns());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires du domaine pour Arc.
|
||||||
|
* Focus sur les @Builder.Default des collections : la moindre omission
|
||||||
|
* renverrait {@code null} et propagerait des NPE dans toute la pile.
|
||||||
|
*/
|
||||||
|
class ArcTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_initializesAllCollectionsToEmptyList_whenNotSet() {
|
||||||
|
Arc arc = Arc.builder()
|
||||||
|
.id("arc-1")
|
||||||
|
.name("Acte I")
|
||||||
|
.campaignId("camp-1")
|
||||||
|
.order(0)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNotNull(arc.getRelatedPageIds(), "relatedPageIds ne doit jamais etre null");
|
||||||
|
assertNotNull(arc.getIllustrationImageIds(), "illustrationImageIds ne doit jamais etre null");
|
||||||
|
assertNotNull(arc.getMapImageIds(), "mapImageIds ne doit jamais etre null");
|
||||||
|
assertTrue(arc.getRelatedPageIds().isEmpty());
|
||||||
|
assertTrue(arc.getIllustrationImageIds().isEmpty());
|
||||||
|
assertTrue(arc.getMapImageIds().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesProvidedCollections() {
|
||||||
|
Arc arc = Arc.builder()
|
||||||
|
.relatedPageIds(List.of("page-a", "page-b"))
|
||||||
|
.illustrationImageIds(List.of("img-1"))
|
||||||
|
.mapImageIds(List.of("map-1", "map-2", "map-3"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(2, arc.getRelatedPageIds().size());
|
||||||
|
assertEquals(1, arc.getIllustrationImageIds().size());
|
||||||
|
assertEquals(3, arc.getMapImageIds().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesNarrativeEnrichmentFields() {
|
||||||
|
Arc arc = Arc.builder()
|
||||||
|
.themes("trahison, vengeance")
|
||||||
|
.stakes("la survie du royaume")
|
||||||
|
.gmNotes("secret : le roi est un imposteur")
|
||||||
|
.rewards("artefact ancien")
|
||||||
|
.resolution("couronnement du legitime heritier")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("trahison, vengeance", arc.getThemes());
|
||||||
|
assertEquals("la survie du royaume", arc.getStakes());
|
||||||
|
assertEquals("secret : le roi est un imposteur", arc.getGmNotes());
|
||||||
|
assertEquals("artefact ancien", arc.getRewards());
|
||||||
|
assertEquals("couronnement du legitime heritier", arc.getResolution());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires du domaine pour Campaign.
|
||||||
|
* Valide la seule methode metier ({@code isLinkedToLore}) et les invariants
|
||||||
|
* de construction du builder Lombok (defaults).
|
||||||
|
*/
|
||||||
|
class CampaignTest {
|
||||||
|
|
||||||
|
// --- isLinkedToLore : regle metier du Bounded Context --------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isLinkedToLore_returnsFalse_whenLoreIdIsNull() {
|
||||||
|
Campaign campaign = Campaign.builder()
|
||||||
|
.id("c1")
|
||||||
|
.name("One-shot")
|
||||||
|
.loreId(null)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertFalse(campaign.isLinkedToLore());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isLinkedToLore_returnsFalse_whenLoreIdIsEmpty() {
|
||||||
|
Campaign campaign = Campaign.builder().loreId("").build();
|
||||||
|
assertFalse(campaign.isLinkedToLore());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isLinkedToLore_returnsFalse_whenLoreIdIsBlank() {
|
||||||
|
// Blank = espaces / tabulations uniquement → ne doit pas compter comme un lien valide.
|
||||||
|
Campaign campaign = Campaign.builder().loreId(" ").build();
|
||||||
|
assertFalse(campaign.isLinkedToLore());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isLinkedToLore_returnsTrue_whenLoreIdIsPresent() {
|
||||||
|
Campaign campaign = Campaign.builder().loreId("lore-42").build();
|
||||||
|
assertTrue(campaign.isLinkedToLore());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Invariants de construction -----------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesAllScalarFields() {
|
||||||
|
Campaign campaign = Campaign.builder()
|
||||||
|
.id("c-1")
|
||||||
|
.name("Les Ombres d'Ithoril")
|
||||||
|
.description("Une campagne de faction dans un royaume en decadence.")
|
||||||
|
.loreId("lore-1")
|
||||||
|
.arcsCount(3)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("c-1", campaign.getId());
|
||||||
|
assertEquals("Les Ombres d'Ithoril", campaign.getName());
|
||||||
|
assertEquals("Une campagne de faction dans un royaume en decadence.", campaign.getDescription());
|
||||||
|
assertEquals("lore-1", campaign.getLoreId());
|
||||||
|
assertEquals(3, campaign.getArcsCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_allowsNoArgs_forFlexibility() {
|
||||||
|
// Un Campaign peut etre cree sans champ rempli (cas pre-hydratation depuis DB).
|
||||||
|
Campaign campaign = Campaign.builder().build();
|
||||||
|
assertNotNull(campaign);
|
||||||
|
assertFalse(campaign.isLinkedToLore());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires du domaine pour Chapter.
|
||||||
|
* Verifie l'initialisation des collections via @Builder.Default et la
|
||||||
|
* preservation des champs narratifs enrichis.
|
||||||
|
*/
|
||||||
|
class ChapterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_initializesAllCollectionsToEmptyList_whenNotSet() {
|
||||||
|
Chapter chapter = Chapter.builder()
|
||||||
|
.id("ch-1")
|
||||||
|
.name("L'arrivee")
|
||||||
|
.arcId("arc-1")
|
||||||
|
.order(0)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNotNull(chapter.getRelatedPageIds());
|
||||||
|
assertNotNull(chapter.getIllustrationImageIds());
|
||||||
|
assertNotNull(chapter.getMapImageIds());
|
||||||
|
assertTrue(chapter.getRelatedPageIds().isEmpty());
|
||||||
|
assertTrue(chapter.getIllustrationImageIds().isEmpty());
|
||||||
|
assertTrue(chapter.getMapImageIds().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesProvidedCollections() {
|
||||||
|
Chapter chapter = Chapter.builder()
|
||||||
|
.relatedPageIds(List.of("page-x"))
|
||||||
|
.illustrationImageIds(List.of("img-1", "img-2"))
|
||||||
|
.mapImageIds(List.of("map-dungeon"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(1, chapter.getRelatedPageIds().size());
|
||||||
|
assertEquals(2, chapter.getIllustrationImageIds().size());
|
||||||
|
assertEquals(1, chapter.getMapImageIds().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesNarrativeEnrichmentFields() {
|
||||||
|
Chapter chapter = Chapter.builder()
|
||||||
|
.gmNotes("les joueurs doivent decouvrir la trahison")
|
||||||
|
.playerObjectives("trouver l'indice dans la bibliotheque")
|
||||||
|
.narrativeStakes("si echec, l'allie meurt")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("les joueurs doivent decouvrir la trahison", chapter.getGmNotes());
|
||||||
|
assertEquals("trouver l'indice dans la bibliotheque", chapter.getPlayerObjectives());
|
||||||
|
assertEquals("si echec, l'allie meurt", chapter.getNarrativeStakes());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour SceneBranch (Value Object).
|
||||||
|
* Verifie :
|
||||||
|
* - l'immuabilite (pas de setters : seul le builder permet la construction),
|
||||||
|
* - l'egalite structurelle generee par @Value (equals/hashCode sur tous les
|
||||||
|
* champs) — deux branches aux memes champs sont strictement egales,
|
||||||
|
* - le support du champ optionnel {@code condition}.
|
||||||
|
*/
|
||||||
|
class SceneBranchTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_exposesAllFields() {
|
||||||
|
SceneBranch branch = SceneBranch.builder()
|
||||||
|
.label("Si les joueurs attaquent le garde")
|
||||||
|
.targetSceneId("sc-combat")
|
||||||
|
.condition("initiative > 15")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("Si les joueurs attaquent le garde", branch.getLabel());
|
||||||
|
assertEquals("sc-combat", branch.getTargetSceneId());
|
||||||
|
assertEquals("initiative > 15", branch.getCondition());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void condition_isOptional() {
|
||||||
|
SceneBranch branch = SceneBranch.builder()
|
||||||
|
.label("sortie par la porte")
|
||||||
|
.targetSceneId("sc-corridor")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNull(branch.getCondition());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoBranches_withSameFields_areEqual() {
|
||||||
|
SceneBranch a = SceneBranch.builder()
|
||||||
|
.label("fuite")
|
||||||
|
.targetSceneId("sc-2")
|
||||||
|
.condition(null)
|
||||||
|
.build();
|
||||||
|
SceneBranch b = SceneBranch.builder()
|
||||||
|
.label("fuite")
|
||||||
|
.targetSceneId("sc-2")
|
||||||
|
.condition(null)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(a, b);
|
||||||
|
assertEquals(a.hashCode(), b.hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoBranches_differingOnTargetSceneId_areNotEqual() {
|
||||||
|
SceneBranch a = SceneBranch.builder().label("X").targetSceneId("sc-1").build();
|
||||||
|
SceneBranch b = SceneBranch.builder().label("X").targetSceneId("sc-2").build();
|
||||||
|
|
||||||
|
assertNotEquals(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoBranches_differingOnCondition_areNotEqual() {
|
||||||
|
SceneBranch a = SceneBranch.builder().label("X").targetSceneId("sc-1").condition("A").build();
|
||||||
|
SceneBranch b = SceneBranch.builder().label("X").targetSceneId("sc-1").condition("B").build();
|
||||||
|
|
||||||
|
assertNotEquals(a, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires du domaine pour Scene.
|
||||||
|
* Scene est la plus riche en champs : on valide les quatre collections
|
||||||
|
* @Builder.Default (relatedPageIds, illustrationImageIds, mapImageIds, branches)
|
||||||
|
* et la preservation de l'ensemble des champs narratifs.
|
||||||
|
*/
|
||||||
|
class SceneTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_initializesAllCollectionsToEmptyList_whenNotSet() {
|
||||||
|
Scene scene = Scene.builder()
|
||||||
|
.id("sc-1")
|
||||||
|
.name("L'auberge")
|
||||||
|
.chapterId("ch-1")
|
||||||
|
.order(0)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNotNull(scene.getRelatedPageIds());
|
||||||
|
assertNotNull(scene.getIllustrationImageIds());
|
||||||
|
assertNotNull(scene.getMapImageIds());
|
||||||
|
assertNotNull(scene.getBranches(), "branches ne doit jamais etre null — une scene sans branche est une feuille");
|
||||||
|
assertTrue(scene.getRelatedPageIds().isEmpty());
|
||||||
|
assertTrue(scene.getIllustrationImageIds().isEmpty());
|
||||||
|
assertTrue(scene.getMapImageIds().isEmpty());
|
||||||
|
assertTrue(scene.getBranches().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesAllNarrativeFields() {
|
||||||
|
Scene scene = Scene.builder()
|
||||||
|
.location("Taverne du Dragon d'Or")
|
||||||
|
.timing("Soir, a la tombee de la nuit")
|
||||||
|
.atmosphere("fumee, rires rauques, odeur de biere")
|
||||||
|
.playerNarration("Vous poussez la porte et entrez dans...")
|
||||||
|
.gmSecretNotes("l'aubergiste est un espion de la guilde")
|
||||||
|
.choicesConsequences("si les PJ parlent fort, ils attirent les gardes")
|
||||||
|
.combatDifficulty("facile (CR 1/2)")
|
||||||
|
.enemies("3 brigands armes de gourdins")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("Taverne du Dragon d'Or", scene.getLocation());
|
||||||
|
assertEquals("Soir, a la tombee de la nuit", scene.getTiming());
|
||||||
|
assertEquals("fumee, rires rauques, odeur de biere", scene.getAtmosphere());
|
||||||
|
assertEquals("Vous poussez la porte et entrez dans...", scene.getPlayerNarration());
|
||||||
|
assertEquals("l'aubergiste est un espion de la guilde", scene.getGmSecretNotes());
|
||||||
|
assertEquals("si les PJ parlent fort, ils attirent les gardes", scene.getChoicesConsequences());
|
||||||
|
assertEquals("facile (CR 1/2)", scene.getCombatDifficulty());
|
||||||
|
assertEquals("3 brigands armes de gourdins", scene.getEnemies());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesBranches_whenProvided() {
|
||||||
|
SceneBranch b1 = SceneBranch.builder().label("fuite").targetSceneId("sc-2").build();
|
||||||
|
SceneBranch b2 = SceneBranch.builder().label("combat").targetSceneId("sc-3").build();
|
||||||
|
|
||||||
|
Scene scene = Scene.builder()
|
||||||
|
.branches(List.of(b1, b2))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(2, scene.getBranches().size());
|
||||||
|
assertEquals("fuite", scene.getBranches().get(0).getLabel());
|
||||||
|
assertEquals("sc-3", scene.getBranches().get(1).getTargetSceneId());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.loremind.domain.conversationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour ConversationMessage.
|
||||||
|
* Entite persistee (@Data mutable) : distinct du record ChatMessage du
|
||||||
|
* generationcontext — ici on ajoute id et horodatage pour l'affichage.
|
||||||
|
*/
|
||||||
|
class ConversationMessageTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesAllFields() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
ConversationMessage msg = ConversationMessage.builder()
|
||||||
|
.id("msg-1")
|
||||||
|
.role("user")
|
||||||
|
.content("Salut")
|
||||||
|
.createdAt(now)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("msg-1", msg.getId());
|
||||||
|
assertEquals("user", msg.getRole());
|
||||||
|
assertEquals("Salut", msg.getContent());
|
||||||
|
assertEquals(now, msg.getCreatedAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noArgsConstructor_yieldsEmptyMessage() {
|
||||||
|
ConversationMessage msg = new ConversationMessage();
|
||||||
|
assertNull(msg.getId());
|
||||||
|
assertNull(msg.getRole());
|
||||||
|
assertNull(msg.getContent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void allArgsConstructor_populatesEveryField() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
ConversationMessage msg = new ConversationMessage("m-1", "assistant", "Reponse", now);
|
||||||
|
assertNotNull(msg);
|
||||||
|
assertEquals("assistant", msg.getRole());
|
||||||
|
assertEquals("Reponse", msg.getContent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setters_mutateFields() {
|
||||||
|
// @Data genere les setters : verifier la mutabilite attendue.
|
||||||
|
ConversationMessage msg = new ConversationMessage();
|
||||||
|
msg.setRole("system");
|
||||||
|
msg.setContent("system prompt");
|
||||||
|
assertEquals("system", msg.getRole());
|
||||||
|
assertEquals("system prompt", msg.getContent());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package com.loremind.domain.conversationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires du domaine pour Conversation (agregat).
|
||||||
|
* Valide :
|
||||||
|
* - le @Builder.Default sur la liste des messages (jamais null),
|
||||||
|
* - la preservation des deux modes d'ancrage (Lore XOR Campaign),
|
||||||
|
* - la preservation du focus entite optionnel (page / arc / chapter / scene).
|
||||||
|
* <p>
|
||||||
|
* NB : la contrainte XOR (un seul de loreId/campaignId non-null) est portee
|
||||||
|
* par ConversationService cote application, pas par le domaine — le test
|
||||||
|
* verifie donc juste que les deux champs sont exposes independamment.
|
||||||
|
*/
|
||||||
|
class ConversationTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_initializesMessagesToEmptyList_whenNotSet() {
|
||||||
|
Conversation conv = Conversation.builder()
|
||||||
|
.id("conv-1")
|
||||||
|
.title("Discussion autour de Thorin")
|
||||||
|
.loreId("lore-1")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNotNull(conv.getMessages(), "messages ne doit jamais etre null");
|
||||||
|
assertTrue(conv.getMessages().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_anchorsToLore_withOptionalEntityFocus() {
|
||||||
|
Conversation conv = Conversation.builder()
|
||||||
|
.loreId("lore-1")
|
||||||
|
.entityType("page")
|
||||||
|
.entityId("page-42")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("lore-1", conv.getLoreId());
|
||||||
|
assertEquals("page", conv.getEntityType());
|
||||||
|
assertEquals("page-42", conv.getEntityId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_anchorsToCampaign_withSceneFocus() {
|
||||||
|
Conversation conv = Conversation.builder()
|
||||||
|
.campaignId("camp-1")
|
||||||
|
.entityType("scene")
|
||||||
|
.entityId("sc-7")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("camp-1", conv.getCampaignId());
|
||||||
|
assertEquals("scene", conv.getEntityType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesProvidedMessages() {
|
||||||
|
ConversationMessage m1 = ConversationMessage.builder().role("user").content("hello").build();
|
||||||
|
ConversationMessage m2 = ConversationMessage.builder().role("assistant").content("hi").build();
|
||||||
|
|
||||||
|
Conversation conv = Conversation.builder()
|
||||||
|
.messages(List.of(m1, m2))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(2, conv.getMessages().size());
|
||||||
|
assertEquals("user", conv.getMessages().get(0).getRole());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noArgsConstructor_createsConversationWithNullMessages() {
|
||||||
|
// @NoArgsConstructor bypass le builder → on accepte que messages soit null
|
||||||
|
// dans ce cas (cas de reconstruction JPA avant hydratation).
|
||||||
|
Conversation conv = new Conversation();
|
||||||
|
assertEquals(null, conv.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour CampaignStructuralContext et ses types imbriques.
|
||||||
|
* Focus sur les annotations @Singular (chapters/scenes/branches/arcs) qui
|
||||||
|
* permettent une construction incrementale du graphe narratif.
|
||||||
|
*/
|
||||||
|
class CampaignStructuralContextTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_constructsFullNarrativeTree() {
|
||||||
|
BranchHint branch = BranchHint.builder()
|
||||||
|
.label("si les PJ fuient")
|
||||||
|
.targetSceneName("La poursuite")
|
||||||
|
.condition("PJ < moitie des HP")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
SceneSummary scene = SceneSummary.builder()
|
||||||
|
.name("L'auberge")
|
||||||
|
.description("Rencontre tendue avec le tavernier")
|
||||||
|
.illustrationCount(2)
|
||||||
|
.branch(branch)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
ChapterSummary chapter = ChapterSummary.builder()
|
||||||
|
.name("L'arrivee")
|
||||||
|
.description("Les PJ decouvrent la ville")
|
||||||
|
.scene(scene)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
ArcSummary arc = ArcSummary.builder()
|
||||||
|
.name("Acte I")
|
||||||
|
.description("Mise en place")
|
||||||
|
.illustrationCount(1)
|
||||||
|
.chapter(chapter)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
CampaignStructuralContext ctx = CampaignStructuralContext.builder()
|
||||||
|
.campaignName("Les Ombres")
|
||||||
|
.campaignDescription("Une campagne dark fantasy")
|
||||||
|
.arc(arc)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("Les Ombres", ctx.getCampaignName());
|
||||||
|
assertEquals(1, ctx.getArcs().size());
|
||||||
|
assertEquals(1, ctx.getArcs().get(0).getChapters().size());
|
||||||
|
assertEquals(1, ctx.getArcs().get(0).getChapters().get(0).getScenes().size());
|
||||||
|
assertEquals(1, ctx.getArcs().get(0).getChapters().get(0).getScenes().get(0).getBranches().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- BranchHint ---------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void branchHint_preservesAllFields() {
|
||||||
|
BranchHint b = BranchHint.builder()
|
||||||
|
.label("combat")
|
||||||
|
.targetSceneName("La confrontation")
|
||||||
|
.condition("initiative > 15")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("combat", b.getLabel());
|
||||||
|
assertEquals("La confrontation", b.getTargetSceneName());
|
||||||
|
assertEquals("initiative > 15", b.getCondition());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void branchHint_conditionIsOptional() {
|
||||||
|
BranchHint b = BranchHint.builder()
|
||||||
|
.label("suite normale")
|
||||||
|
.targetSceneName("Scene 2")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNull(b.getCondition());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- illustrationCount --------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void illustrationCount_defaultsToZero_onAllSummaryTypes() {
|
||||||
|
ArcSummary arc = ArcSummary.builder().name("X").build();
|
||||||
|
ChapterSummary chapter = ChapterSummary.builder().name("X").build();
|
||||||
|
SceneSummary scene = SceneSummary.builder().name("X").build();
|
||||||
|
|
||||||
|
assertEquals(0, arc.getIllustrationCount());
|
||||||
|
assertEquals(0, chapter.getIllustrationCount());
|
||||||
|
assertEquals(0, scene.getIllustrationCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- @Singular : accumulation incrementale -----------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void singular_accumulatesMultipleCalls() {
|
||||||
|
ArcSummary arc = ArcSummary.builder()
|
||||||
|
.name("Acte I")
|
||||||
|
.chapter(ChapterSummary.builder().name("Ch1").build())
|
||||||
|
.chapter(ChapterSummary.builder().name("Ch2").build())
|
||||||
|
.chapter(ChapterSummary.builder().name("Ch3").build())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(3, arc.getChapters().size());
|
||||||
|
assertTrue(arc.getChapters().stream().anyMatch(c -> "Ch2".equals(c.getName())));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour le record ChatMessage.
|
||||||
|
* Role est une chaine libre cote domaine (les roles acceptes "user"/"assistant"/
|
||||||
|
* "system" sont une convention — le domaine ne l'impose pas, c'est la
|
||||||
|
* couche application qui valide au besoin).
|
||||||
|
*/
|
||||||
|
class ChatMessageTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void accessors_exposeRoleAndContent() {
|
||||||
|
ChatMessage msg = new ChatMessage("user", "Que se passe-t-il dans la taverne ?");
|
||||||
|
assertEquals("user", msg.role());
|
||||||
|
assertEquals("Que se passe-t-il dans la taverne ?", msg.content());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoMessages_withSameContent_areEqual() {
|
||||||
|
ChatMessage a = new ChatMessage("assistant", "Il y a 3 clients au bar.");
|
||||||
|
ChatMessage b = new ChatMessage("assistant", "Il y a 3 clients au bar.");
|
||||||
|
assertEquals(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoMessages_differingOnRole_areNotEqual() {
|
||||||
|
ChatMessage a = new ChatMessage("user", "hello");
|
||||||
|
ChatMessage b = new ChatMessage("assistant", "hello");
|
||||||
|
assertNotEquals(a, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour ChatRequest (Value Object).
|
||||||
|
* Valide les combinaisons supportees par le metier :
|
||||||
|
* - chat Lore pur (loreContext seul),
|
||||||
|
* - chat Lore focalise (loreContext + pageContext),
|
||||||
|
* - chat Campagne (campaignContext),
|
||||||
|
* - chat Campagne focalise (campaignContext + narrativeEntity).
|
||||||
|
*/
|
||||||
|
class ChatRequestTest {
|
||||||
|
|
||||||
|
private final List<ChatMessage> sampleMessages = List.of(
|
||||||
|
new ChatMessage("user", "Bonjour")
|
||||||
|
);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void buildLoreOnly_leavesCampaignAndEntityNull() {
|
||||||
|
ChatRequest request = ChatRequest.builder()
|
||||||
|
.messages(sampleMessages)
|
||||||
|
.loreContext(LoreStructuralContext.builder()
|
||||||
|
.loreName("Ithoril")
|
||||||
|
.loreDescription("Royaume sombre")
|
||||||
|
.folders(java.util.Map.of())
|
||||||
|
.build())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(1, request.getMessages().size());
|
||||||
|
assertNotNull(request.getLoreContext());
|
||||||
|
assertEquals("Ithoril", request.getLoreContext().getLoreName());
|
||||||
|
assertNull(request.getPageContext());
|
||||||
|
assertNull(request.getCampaignContext());
|
||||||
|
assertNull(request.getNarrativeEntity());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void buildLoreWithPageFocus_hasBothContexts() {
|
||||||
|
ChatRequest request = ChatRequest.builder()
|
||||||
|
.messages(sampleMessages)
|
||||||
|
.loreContext(LoreStructuralContext.builder().folders(java.util.Map.of()).build())
|
||||||
|
.pageContext(PageContext.builder()
|
||||||
|
.title("Thorin")
|
||||||
|
.templateName("PNJ")
|
||||||
|
.build())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNotNull(request.getLoreContext());
|
||||||
|
assertNotNull(request.getPageContext());
|
||||||
|
assertEquals("Thorin", request.getPageContext().getTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void buildCampaignWithNarrativeEntity_hasBothContexts() {
|
||||||
|
ChatRequest request = ChatRequest.builder()
|
||||||
|
.messages(sampleMessages)
|
||||||
|
.campaignContext(CampaignStructuralContext.builder()
|
||||||
|
.campaignName("Les Ombres")
|
||||||
|
.campaignDescription("...")
|
||||||
|
.build())
|
||||||
|
.narrativeEntity(NarrativeEntityContext.builder()
|
||||||
|
.entityType("scene")
|
||||||
|
.title("L'auberge")
|
||||||
|
.fields(java.util.Map.of("location", "Taverne"))
|
||||||
|
.build())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNotNull(request.getCampaignContext());
|
||||||
|
assertNotNull(request.getNarrativeEntity());
|
||||||
|
assertEquals("scene", request.getNarrativeEntity().getEntityType());
|
||||||
|
assertNull(request.getLoreContext());
|
||||||
|
assertNull(request.getPageContext());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void buildMinimal_onlyRequiresMessages() {
|
||||||
|
// Cas degenere supporte : aucun contexte, juste l'historique.
|
||||||
|
ChatRequest request = ChatRequest.builder()
|
||||||
|
.messages(sampleMessages)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals(1, request.getMessages().size());
|
||||||
|
assertNull(request.getLoreContext());
|
||||||
|
assertNull(request.getPageContext());
|
||||||
|
assertNull(request.getCampaignContext());
|
||||||
|
assertNull(request.getNarrativeEntity());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour le record ChatUsage.
|
||||||
|
* Verifie l'immuabilite (acces via accesseurs generes) et l'egalite
|
||||||
|
* structurelle (equals/hashCode generes par le record).
|
||||||
|
*/
|
||||||
|
class ChatUsageTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void accessors_exposeAllComponents() {
|
||||||
|
ChatUsage usage = new ChatUsage(1200, 3400, 150, 8192);
|
||||||
|
assertEquals(1200, usage.system());
|
||||||
|
assertEquals(3400, usage.history());
|
||||||
|
assertEquals(150, usage.current());
|
||||||
|
assertEquals(8192, usage.max());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoUsages_withSameComponents_areEqual() {
|
||||||
|
ChatUsage a = new ChatUsage(100, 200, 50, 4096);
|
||||||
|
ChatUsage b = new ChatUsage(100, 200, 50, 4096);
|
||||||
|
assertEquals(a, b);
|
||||||
|
assertEquals(a.hashCode(), b.hashCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoUsages_differingOnAnyComponent_areNotEqual() {
|
||||||
|
ChatUsage base = new ChatUsage(100, 200, 50, 4096);
|
||||||
|
assertNotEquals(base, new ChatUsage(101, 200, 50, 4096));
|
||||||
|
assertNotEquals(base, new ChatUsage(100, 201, 50, 4096));
|
||||||
|
assertNotEquals(base, new ChatUsage(100, 200, 51, 4096));
|
||||||
|
assertNotEquals(base, new ChatUsage(100, 200, 50, 4097));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour GenerationContext (Value Object pour la generation one-shot).
|
||||||
|
* Verifie la construction via builder et l'egalite structurelle.
|
||||||
|
*/
|
||||||
|
class GenerationContextTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesAllFields() {
|
||||||
|
GenerationContext ctx = GenerationContext.builder()
|
||||||
|
.loreName("Ithoril")
|
||||||
|
.loreDescription("Royaume sombre")
|
||||||
|
.folderName("PNJ")
|
||||||
|
.templateName("Fiche PNJ")
|
||||||
|
.templateFields(List.of("histoire", "motto", "apparence"))
|
||||||
|
.pageTitle("Thorin")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("Ithoril", ctx.getLoreName());
|
||||||
|
assertEquals("PNJ", ctx.getFolderName());
|
||||||
|
assertEquals("Fiche PNJ", ctx.getTemplateName());
|
||||||
|
assertEquals(3, ctx.getTemplateFields().size());
|
||||||
|
assertEquals("Thorin", ctx.getPageTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoContexts_withSameFields_areEqual() {
|
||||||
|
GenerationContext a = GenerationContext.builder()
|
||||||
|
.loreName("X").pageTitle("A").templateFields(List.of("f1")).build();
|
||||||
|
GenerationContext b = GenerationContext.builder()
|
||||||
|
.loreName("X").pageTitle("A").templateFields(List.of("f1")).build();
|
||||||
|
assertEquals(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoContexts_differingOnPageTitle_areNotEqual() {
|
||||||
|
GenerationContext a = GenerationContext.builder().pageTitle("A").build();
|
||||||
|
GenerationContext b = GenerationContext.builder().pageTitle("B").build();
|
||||||
|
assertNotEquals(a, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour le record GenerationResult.
|
||||||
|
* Structure triviale (map name -> value) — on verifie juste l'acces et
|
||||||
|
* l'egalite structurelle.
|
||||||
|
*/
|
||||||
|
class GenerationResultTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void accessor_exposesValuesMap() {
|
||||||
|
GenerationResult result = new GenerationResult(Map.of(
|
||||||
|
"histoire", "Nee sous une etoile rouge...",
|
||||||
|
"motto", "Jamais genou en terre"
|
||||||
|
));
|
||||||
|
|
||||||
|
assertEquals(2, result.values().size());
|
||||||
|
assertEquals("Jamais genou en terre", result.values().get("motto"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoResults_withSameMap_areEqual() {
|
||||||
|
GenerationResult a = new GenerationResult(Map.of("f", "v"));
|
||||||
|
GenerationResult b = new GenerationResult(Map.of("f", "v"));
|
||||||
|
assertEquals(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoResults_withDifferentMaps_areNotEqual() {
|
||||||
|
GenerationResult a = new GenerationResult(Map.of("f", "v1"));
|
||||||
|
GenerationResult b = new GenerationResult(Map.of("f", "v2"));
|
||||||
|
assertNotEquals(a, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.generationcontext.LoreStructuralContext.PageSummary;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour LoreStructuralContext et son type imbrique PageSummary.
|
||||||
|
* Valide le @Singular de Lombok sur {@code tags} (alimentation incrementale via
|
||||||
|
* {@code tag(...)} vs initialisation groupee via {@code tags(...)}).
|
||||||
|
*/
|
||||||
|
class LoreStructuralContextTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesFoldersAndTags() {
|
||||||
|
PageSummary pnj = PageSummary.builder()
|
||||||
|
.title("Thorin")
|
||||||
|
.templateName("PNJ")
|
||||||
|
.values(Map.of("histoire", "Nee sous une etoile rouge"))
|
||||||
|
.tags(List.of("pnj", "allie"))
|
||||||
|
.relatedPageTitles(List.of("Taverne du Dragon d'Or"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
LoreStructuralContext ctx = LoreStructuralContext.builder()
|
||||||
|
.loreName("Ithoril")
|
||||||
|
.loreDescription("Royaume sombre")
|
||||||
|
.folders(Map.of("PNJ", List.of(pnj)))
|
||||||
|
.tag("royaume")
|
||||||
|
.tag("dark-fantasy")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("Ithoril", ctx.getLoreName());
|
||||||
|
assertEquals(1, ctx.getFolders().size());
|
||||||
|
assertEquals(1, ctx.getFolders().get("PNJ").size());
|
||||||
|
assertEquals(2, ctx.getTags().size(), "@Singular doit accumuler les appels tag()");
|
||||||
|
assertTrue(ctx.getTags().contains("royaume"));
|
||||||
|
assertTrue(ctx.getTags().contains("dark-fantasy"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void emptyFolders_areAllowed() {
|
||||||
|
// Dossier vide : legitime (ex: dossier "Lieux" cree mais pas encore peuple).
|
||||||
|
LoreStructuralContext ctx = LoreStructuralContext.builder()
|
||||||
|
.loreName("Vide")
|
||||||
|
.loreDescription("")
|
||||||
|
.folders(Map.of("Lieux", List.of()))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNotNull(ctx.getFolders().get("Lieux"));
|
||||||
|
assertTrue(ctx.getFolders().get("Lieux").isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- PageSummary --------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void pageSummary_preservesAllFields() {
|
||||||
|
PageSummary ps = PageSummary.builder()
|
||||||
|
.title("Le Donjon du Chaos")
|
||||||
|
.templateName("Lieu")
|
||||||
|
.values(Map.of("histoire", "Bati il y a 1000 ans..."))
|
||||||
|
.tags(List.of("donjon", "ancien"))
|
||||||
|
.relatedPageTitles(List.of("Thorin", "Garde royale"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("Le Donjon du Chaos", ps.getTitle());
|
||||||
|
assertEquals("Lieu", ps.getTemplateName());
|
||||||
|
assertEquals(1, ps.getValues().size());
|
||||||
|
assertEquals(2, ps.getTags().size());
|
||||||
|
assertEquals(2, ps.getRelatedPageTitles().size());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour NarrativeEntityContext.
|
||||||
|
* Trois types attendus : "arc", "chapter", "scene" — mais le domaine ne
|
||||||
|
* restreint pas la chaine (validation cote application layer).
|
||||||
|
*/
|
||||||
|
class NarrativeEntityContextTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesAllFields() {
|
||||||
|
Map<String, String> fields = new LinkedHashMap<>();
|
||||||
|
fields.put("themes", "trahison");
|
||||||
|
fields.put("stakes", "la survie du royaume");
|
||||||
|
|
||||||
|
NarrativeEntityContext ctx = NarrativeEntityContext.builder()
|
||||||
|
.entityType("arc")
|
||||||
|
.title("Acte I")
|
||||||
|
.fields(fields)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("arc", ctx.getEntityType());
|
||||||
|
assertEquals("Acte I", ctx.getTitle());
|
||||||
|
assertEquals(2, ctx.getFields().size());
|
||||||
|
assertEquals("trahison", ctx.getFields().get("themes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fieldsOrder_isPreserved_whenUsingLinkedHashMap() {
|
||||||
|
// L'ordre des champs est significatif : le prompt doit etre lisible.
|
||||||
|
Map<String, String> fields = new LinkedHashMap<>();
|
||||||
|
fields.put("location", "Taverne");
|
||||||
|
fields.put("timing", "Soir");
|
||||||
|
fields.put("atmosphere", "fumee");
|
||||||
|
|
||||||
|
NarrativeEntityContext ctx = NarrativeEntityContext.builder()
|
||||||
|
.entityType("scene")
|
||||||
|
.title("L'auberge")
|
||||||
|
.fields(fields)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("[location, timing, atmosphere]", ctx.getFields().keySet().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoContexts_differingOnEntityType_areNotEqual() {
|
||||||
|
NarrativeEntityContext a = NarrativeEntityContext.builder().entityType("arc").title("X").build();
|
||||||
|
NarrativeEntityContext b = NarrativeEntityContext.builder().entityType("scene").title("X").build();
|
||||||
|
assertNotEquals(a, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.loremind.domain.generationcontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires pour PageContext (Value Object : focus IA sur une page).
|
||||||
|
*/
|
||||||
|
class PageContextTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesAllFields() {
|
||||||
|
PageContext ctx = PageContext.builder()
|
||||||
|
.title("Thorin")
|
||||||
|
.templateName("PNJ")
|
||||||
|
.templateFields(List.of("histoire", "apparence", "motto"))
|
||||||
|
.values(Map.of("histoire", "Nee sous une etoile rouge"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("Thorin", ctx.getTitle());
|
||||||
|
assertEquals("PNJ", ctx.getTemplateName());
|
||||||
|
assertEquals(3, ctx.getTemplateFields().size());
|
||||||
|
assertEquals(1, ctx.getValues().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void emptyValues_areAllowed() {
|
||||||
|
// Page vierge : template defini mais aucun champ rempli (cas generation ex-nihilo).
|
||||||
|
PageContext ctx = PageContext.builder()
|
||||||
|
.title("Nouveau PNJ")
|
||||||
|
.templateName("PNJ")
|
||||||
|
.templateFields(List.of("histoire", "apparence"))
|
||||||
|
.values(Map.of())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertTrue(ctx.getValues().isEmpty());
|
||||||
|
assertEquals(2, ctx.getTemplateFields().size());
|
||||||
|
}
|
||||||
|
}
|
||||||
45
core/src/test/java/com/loremind/domain/images/ImageTest.java
Normal file
45
core/src/test/java/com/loremind/domain/images/ImageTest.java
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package com.loremind.domain.images;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires du domaine pour Image (Shared Kernel).
|
||||||
|
* Entite pure : metadata + cle opaque vers l'object storage.
|
||||||
|
* On verifie juste la preservation des champs — aucune logique metier.
|
||||||
|
*/
|
||||||
|
class ImageTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesAllFields() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
Image image = Image.builder()
|
||||||
|
.id("img-1")
|
||||||
|
.filename("portrait-elfe.jpg")
|
||||||
|
.contentType("image/jpeg")
|
||||||
|
.sizeBytes(125_000L)
|
||||||
|
.storageKey("images/abc123.jpg")
|
||||||
|
.uploadedAt(now)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("img-1", image.getId());
|
||||||
|
assertEquals("portrait-elfe.jpg", image.getFilename());
|
||||||
|
assertEquals("image/jpeg", image.getContentType());
|
||||||
|
assertEquals(125_000L, image.getSizeBytes());
|
||||||
|
assertEquals("images/abc123.jpg", image.getStorageKey());
|
||||||
|
assertEquals(now, image.getUploadedAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_supportsCommonMimeTypes() {
|
||||||
|
// Verifie que n'importe quelle chaine MIME passe : la validation se fait
|
||||||
|
// cote application (ImageService) pas dans le domaine.
|
||||||
|
for (String mime : new String[]{"image/jpeg", "image/png", "image/webp", "image/gif"}) {
|
||||||
|
Image image = Image.builder().contentType(mime).build();
|
||||||
|
assertEquals(mime, image.getContentType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package com.loremind.domain.lorecontext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires du domaine pour LoreNode.
|
||||||
|
* Verifie la preservation des champs et l'absence de parent (racine de l'arbre).
|
||||||
|
*/
|
||||||
|
class LoreNodeTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builder_preservesAllFields() {
|
||||||
|
LoreNode node = LoreNode.builder()
|
||||||
|
.id("n-1")
|
||||||
|
.name("Personnages")
|
||||||
|
.icon("users")
|
||||||
|
.parentId("n-root")
|
||||||
|
.loreId("lore-1")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertEquals("n-1", node.getId());
|
||||||
|
assertEquals("Personnages", node.getName());
|
||||||
|
assertEquals("users", node.getIcon());
|
||||||
|
assertEquals("n-root", node.getParentId());
|
||||||
|
assertEquals("lore-1", node.getLoreId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parentId_isNull_forRootNodes() {
|
||||||
|
// Un node racine a parentId == null : invariant de l'arborescence.
|
||||||
|
LoreNode root = LoreNode.builder()
|
||||||
|
.id("n-root")
|
||||||
|
.name("Racine")
|
||||||
|
.loreId("lore-1")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertNull(root.getParentId());
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user