Compare commits
11 Commits
v0.12.2-be
...
af3a6d443c
| Author | SHA1 | Date | |
|---|---|---|---|
| af3a6d443c | |||
| 6e75326779 | |||
| d0b53bb15a | |||
| bbcb5ee34e | |||
| c77c0bc994 | |||
| 6035df262d | |||
| 809e00ce49 | |||
| bc0cbb0f7b | |||
| 6740ed2177 | |||
| 8cc90bd24d | |||
| 14fc1c28fe |
@@ -14,6 +14,11 @@ import asyncio
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from app.application.chunking import chunk_text, split_in_half
|
from app.application.chunking import chunk_text, split_in_half
|
||||||
|
from app.application.import_status import (
|
||||||
|
notify_status,
|
||||||
|
reset_status_queue,
|
||||||
|
set_status_queue,
|
||||||
|
)
|
||||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.streaming import with_heartbeat
|
from app.application.streaming import with_heartbeat
|
||||||
@@ -510,6 +515,11 @@ class ImportCampaignUseCase:
|
|||||||
skipped = 0
|
skipped = 0
|
||||||
last_error: str | None = None
|
last_error: str | None = None
|
||||||
done_count = 0
|
done_count = 0
|
||||||
|
# Canal de statut : les couches profondes (retry LLM, re-découpage) y
|
||||||
|
# publient des messages destinés à l'UI — cf. import_status.notify_status.
|
||||||
|
status_queue: asyncio.Queue = asyncio.Queue()
|
||||||
|
status_token = set_status_queue(status_queue)
|
||||||
|
try:
|
||||||
# PARALLÉLISME : les morceaux sont traités par VAGUES de `map_concurrency`
|
# PARALLÉLISME : les morceaux sont traités par VAGUES de `map_concurrency`
|
||||||
# appels simultanés. L'ordre narratif est préservé : la fusion se fait
|
# appels simultanés. L'ordre narratif est préservé : la fusion se fait
|
||||||
# vague par vague, dans l'ordre du livre.
|
# vague par vague, dans l'ordre du livre.
|
||||||
@@ -526,9 +536,12 @@ class ImportCampaignUseCase:
|
|||||||
return_exceptions=True,
|
return_exceptions=True,
|
||||||
)
|
)
|
||||||
results: list | None = None
|
results: list | None = None
|
||||||
async for kind, payload in with_heartbeat(gathered):
|
async for kind, payload in with_heartbeat(gathered, status_queue=status_queue):
|
||||||
if kind == "heartbeat":
|
if kind == "heartbeat":
|
||||||
yield {"type": "heartbeat", "current": done_count + 1, "total": total}
|
yield {"type": "heartbeat", "current": done_count + 1, "total": total}
|
||||||
|
elif kind == "status":
|
||||||
|
yield {"type": "status", "message": payload,
|
||||||
|
"current": done_count + 1, "total": total}
|
||||||
else:
|
else:
|
||||||
results = payload
|
results = payload
|
||||||
for (i, _), res in zip(wave, results or []):
|
for (i, _), res in zip(wave, results or []):
|
||||||
@@ -578,9 +591,14 @@ class ImportCampaignUseCase:
|
|||||||
# (best-effort, voir _consolidate). Inutile sur un import mono-morceau.
|
# (best-effort, voir _consolidate). Inutile sur un import mono-morceau.
|
||||||
if total > 1:
|
if total > 1:
|
||||||
yield {"type": "consolidating", "total": total}
|
yield {"type": "consolidating", "total": total}
|
||||||
async for kind, _ in with_heartbeat(self._consolidate(merger)):
|
async for kind, payload in with_heartbeat(
|
||||||
|
self._consolidate(merger), status_queue=status_queue
|
||||||
|
):
|
||||||
if kind == "heartbeat":
|
if kind == "heartbeat":
|
||||||
yield {"type": "heartbeat", "current": total, "total": total}
|
yield {"type": "heartbeat", "current": total, "total": total}
|
||||||
|
elif kind == "status":
|
||||||
|
yield {"type": "status", "message": payload,
|
||||||
|
"current": total, "total": total}
|
||||||
|
|
||||||
yield {
|
yield {
|
||||||
"type": "done",
|
"type": "done",
|
||||||
@@ -590,6 +608,8 @@ class ImportCampaignUseCase:
|
|||||||
"ocr_page_count": doc.ocr_page_count,
|
"ocr_page_count": doc.ocr_page_count,
|
||||||
"skipped": skipped,
|
"skipped": skipped,
|
||||||
}
|
}
|
||||||
|
finally:
|
||||||
|
reset_status_queue(status_token)
|
||||||
|
|
||||||
# --- Consolidation finale (fusion des quasi-doublons) ---------------------
|
# --- Consolidation finale (fusion des quasi-doublons) ---------------------
|
||||||
|
|
||||||
@@ -666,6 +686,9 @@ class ImportCampaignUseCase:
|
|||||||
logger.info(
|
logger.info(
|
||||||
"Morceau %s : timeout de génération → re-découpage en 2 moitiés (niveau %s).",
|
"Morceau %s : timeout de génération → re-découpage en 2 moitiés (niveau %s).",
|
||||||
index, depth + 1)
|
index, depth + 1)
|
||||||
|
notify_status(
|
||||||
|
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
||||||
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_payload(
|
a = await self._extract_payload(
|
||||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||||
b = await self._extract_payload(
|
b = await self._extract_payload(
|
||||||
@@ -679,6 +702,9 @@ class ImportCampaignUseCase:
|
|||||||
logger.info(
|
logger.info(
|
||||||
"Morceau %s : sortie tronquée → re-découpage en 2 moitiés (niveau %s).",
|
"Morceau %s : sortie tronquée → re-découpage en 2 moitiés (niveau %s).",
|
||||||
index, depth + 1)
|
index, depth + 1)
|
||||||
|
notify_status(
|
||||||
|
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
||||||
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_payload(
|
a = await self._extract_payload(
|
||||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||||
b = await self._extract_payload(
|
b = await self._extract_payload(
|
||||||
|
|||||||
@@ -15,7 +15,14 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
from app.application.chunking import CHUNK_TARGET_TOKENS, chunk_text, split_in_half
|
from app.application.chunking import CHUNK_TARGET_TOKENS, chunk_text, split_in_half
|
||||||
|
from app.application.import_status import (
|
||||||
|
notify_status,
|
||||||
|
reset_status_queue,
|
||||||
|
set_status_queue,
|
||||||
|
)
|
||||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.streaming import with_heartbeat
|
from app.application.streaming import with_heartbeat
|
||||||
@@ -332,6 +339,11 @@ class ImportRulesUseCase:
|
|||||||
merger = _SectionMerger()
|
merger = _SectionMerger()
|
||||||
skipped = 0
|
skipped = 0
|
||||||
last_error: str | None = None
|
last_error: str | None = None
|
||||||
|
# Canal de statut : les couches profondes (retry LLM, re-découpage) y
|
||||||
|
# publient des messages destinés à l'UI — cf. import_status.notify_status.
|
||||||
|
status_queue: asyncio.Queue = asyncio.Queue()
|
||||||
|
status_token = set_status_queue(status_queue)
|
||||||
|
try:
|
||||||
for i, chunk in enumerate(chunks):
|
for i, chunk in enumerate(chunks):
|
||||||
# RÉSILIENCE : un morceau qui échoue est SAUTÉ, l'import continue.
|
# RÉSILIENCE : un morceau qui échoue est SAUTÉ, l'import continue.
|
||||||
# Abandon seulement si AUCUN morceau ne passe (cf. après la boucle).
|
# Abandon seulement si AUCUN morceau ne passe (cf. après la boucle).
|
||||||
@@ -341,10 +353,14 @@ class ImportRulesUseCase:
|
|||||||
try:
|
try:
|
||||||
sections: dict[str, str] | None = None
|
sections: dict[str, str] | None = None
|
||||||
async for kind, payload in with_heartbeat(
|
async for kind, payload in with_heartbeat(
|
||||||
self._map_chunk(chunk, index=i, total=total)
|
self._map_chunk(chunk, index=i, total=total),
|
||||||
|
status_queue=status_queue,
|
||||||
):
|
):
|
||||||
if kind == "heartbeat":
|
if kind == "heartbeat":
|
||||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||||
|
elif kind == "status":
|
||||||
|
yield {"type": "status", "message": payload,
|
||||||
|
"current": i + 1, "total": total}
|
||||||
else:
|
else:
|
||||||
sections = payload
|
sections = payload
|
||||||
new_titles = merger.add(sections or {})
|
new_titles = merger.add(sections or {})
|
||||||
@@ -361,6 +377,8 @@ class ImportRulesUseCase:
|
|||||||
"new_sections": new_titles,
|
"new_sections": new_titles,
|
||||||
"skipped": skipped,
|
"skipped": skipped,
|
||||||
}
|
}
|
||||||
|
finally:
|
||||||
|
reset_status_queue(status_token)
|
||||||
|
|
||||||
if total > 0 and skipped == total:
|
if total > 0 and skipped == total:
|
||||||
yield {"type": "error",
|
yield {"type": "error",
|
||||||
@@ -423,6 +441,9 @@ class ImportRulesUseCase:
|
|||||||
logger.info(
|
logger.info(
|
||||||
"Morceau %s : timeout de génération → re-découpage en 2 moitiés (niveau %s).",
|
"Morceau %s : timeout de génération → re-découpage en 2 moitiés (niveau %s).",
|
||||||
index, depth + 1)
|
index, depth + 1)
|
||||||
|
notify_status(
|
||||||
|
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
||||||
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_sections(left, index=index, total=total, depth=depth + 1)
|
a = await self._extract_sections(left, index=index, total=total, depth=depth + 1)
|
||||||
b = await self._extract_sections(right, index=index, total=total, depth=depth + 1)
|
b = await self._extract_sections(right, index=index, total=total, depth=depth + 1)
|
||||||
return _combine_sections(a, b)
|
return _combine_sections(a, b)
|
||||||
@@ -437,6 +458,9 @@ class ImportRulesUseCase:
|
|||||||
logger.info(
|
logger.info(
|
||||||
"Morceau %s : sortie tronquée → re-découpage en 2 moitiés (niveau %s).",
|
"Morceau %s : sortie tronquée → re-découpage en 2 moitiés (niveau %s).",
|
||||||
index, depth + 1)
|
index, depth + 1)
|
||||||
|
notify_status(
|
||||||
|
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
||||||
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_sections(left, index=index, total=total, depth=depth + 1)
|
a = await self._extract_sections(left, index=index, total=total, depth=depth + 1)
|
||||||
b = await self._extract_sections(right, index=index, total=total, depth=depth + 1)
|
b = await self._extract_sections(right, index=index, total=total, depth=depth + 1)
|
||||||
return _combine_sections(a, b)
|
return _combine_sections(a, b)
|
||||||
|
|||||||
39
brain/app/application/import_status.py
Normal file
39
brain/app/application/import_status.py
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
"""Canal de statut des imports : remonte à l'UI ce qui n'existait qu'en logs.
|
||||||
|
|
||||||
|
Problème résolu : pendant un import, les événements internes (retry parce que
|
||||||
|
le fournisseur IA est saturé, re-découpage d'un morceau trop gros…) n'étaient
|
||||||
|
visibles que dans les logs Docker. L'utilisateur voyait une barre de
|
||||||
|
progression figée sans explication.
|
||||||
|
|
||||||
|
Mécanisme : le flux d'import (use case `stream()`) installe une Queue dans une
|
||||||
|
ContextVar ; les couches profondes (retry LLM, re-découpage) y publient des
|
||||||
|
messages via `notify_status()` sans connaître le flux SSE. La ContextVar est
|
||||||
|
propagée automatiquement aux tâches asyncio enfants → chaque import concurrent
|
||||||
|
a SA queue, sans couplage ni paramètre à faire transiter partout.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from contextvars import ContextVar, Token
|
||||||
|
|
||||||
|
_QUEUE: ContextVar[asyncio.Queue | None] = ContextVar("import_status_queue", default=None)
|
||||||
|
|
||||||
|
|
||||||
|
def set_status_queue(queue: asyncio.Queue | None) -> Token:
|
||||||
|
"""Installe la queue de statut pour le contexte courant (et ses tâches filles).
|
||||||
|
|
||||||
|
Renvoie le token à passer à `reset_status_queue` en fin d'import.
|
||||||
|
"""
|
||||||
|
return _QUEUE.set(queue)
|
||||||
|
|
||||||
|
|
||||||
|
def reset_status_queue(token: Token) -> None:
|
||||||
|
_QUEUE.reset(token)
|
||||||
|
|
||||||
|
|
||||||
|
def notify_status(message: str) -> None:
|
||||||
|
"""Publie un message de statut si un import écoute. No-op sinon (appels
|
||||||
|
LLM hors import : chat, génération de page…)."""
|
||||||
|
queue = _QUEUE.get()
|
||||||
|
if queue is not None:
|
||||||
|
queue.put_nowait(message)
|
||||||
@@ -14,6 +14,7 @@ import asyncio
|
|||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
from app.application.import_status import notify_status
|
||||||
from app.domain.ports import LLMGenerationTimeout, LLMProvider, LLMProviderError
|
from app.domain.ports import LLMGenerationTimeout, LLMProvider, LLMProviderError
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -103,6 +104,14 @@ async def generate_with_retry(
|
|||||||
attempt + 1, _ATTEMPTS, " [rate limit]" if _is_rate_limit(exc) else "",
|
attempt + 1, _ATTEMPTS, " [rate limit]" if _is_rate_limit(exc) else "",
|
||||||
exc, wait,
|
exc, wait,
|
||||||
)
|
)
|
||||||
|
# Remonte aussi l'info à l'UI (flux d'import) : sans ça l'utilisateur
|
||||||
|
# voit une barre figée sans savoir que le fournisseur est saturé.
|
||||||
|
notify_status(
|
||||||
|
("Fournisseur IA saturé (rate limit)" if _is_rate_limit(exc)
|
||||||
|
else "Appel IA échoué")
|
||||||
|
+ f" — tentative {attempt + 1}/{_ATTEMPTS}, nouvel essai dans {int(wait)}s. "
|
||||||
|
+ str(exc)[:160]
|
||||||
|
)
|
||||||
await asyncio.sleep(wait)
|
await asyncio.sleep(wait)
|
||||||
assert last_error is not None
|
assert last_error is not None
|
||||||
raise last_error
|
raise last_error
|
||||||
|
|||||||
@@ -34,23 +34,59 @@ Règles :
|
|||||||
|
|
||||||
PROPOSITIONS D'INTÉGRATION (IMPORTANT) :
|
PROPOSITIONS D'INTÉGRATION (IMPORTANT) :
|
||||||
Quand l'utilisateur veut CRÉER ou ADAPTER un élément concret pour sa campagne (un PNJ,
|
Quand l'utilisateur veut CRÉER ou ADAPTER un élément concret pour sa campagne (un PNJ,
|
||||||
une scène, un chapitre, un arc, une table aléatoire), termine ta réponse par un ou
|
une scène, un chapitre, une quête, un arc, une table aléatoire), termine ta réponse par
|
||||||
plusieurs BLOCS D'ACTION — un objet JSON par bloc, dans une clôture ```loremind-action.
|
un ou plusieurs BLOCS D'ACTION — un objet JSON par bloc, dans une clôture
|
||||||
L'interface les transformera en boutons « Créer dans la campagne ». N'en mets que si
|
```loremind-action. L'interface les transformera en boutons « Créer dans la campagne ».
|
||||||
c'est pertinent et explicitement souhaité. Formats acceptés :
|
Si l'utilisateur demande PLUSIEURS éléments (« propose-moi 3 quêtes »), produis UN bloc
|
||||||
|
par élément. N'en mets pas si l'utilisateur pose une simple question.
|
||||||
|
|
||||||
|
VOCABULAIRE DE LA CAMPAGNE : une « quête » n'est PAS un type à part — c'est un CHAPITRE
|
||||||
|
rangé dans un arc de type HUB (quêtes parallèles, sans ordre imposé), tandis qu'un arc
|
||||||
|
LINEAR contient des chapitres joués en séquence. Donc :
|
||||||
|
- demande de QUÊTE → action "chapter" (l'utilisateur la placera dans son arc HUB) ;
|
||||||
|
s'il n'a aucun arc HUB dans sa campagne, propose AUSSI une action "arc" avec
|
||||||
|
"arcType": "HUB" pour les accueillir.
|
||||||
|
- demande de CHAPITRE → action "chapter" (destinée plutôt à un arc LINEAR).
|
||||||
|
|
||||||
|
RÈGLE CLÉ : remplis TOUS les champs pour lesquels tu as de la matière — pas seulement
|
||||||
|
le résumé ou les notes MJ. Chaque champ rempli atterrit au bon endroit de la fiche ;
|
||||||
|
un champ laissé vide est une fiche que l'utilisateur devra compléter à la main. Vise
|
||||||
|
2 à 5 phrases concrètes par champ narratif, tirées de la source et de la campagne.
|
||||||
|
Omets simplement un champ si tu n'as rien de précis à y mettre. Formats acceptés :
|
||||||
|
|
||||||
```loremind-action
|
```loremind-action
|
||||||
{{"type": "npc", "name": "Nom", "description": "Fiche en quelques phrases."}}
|
{{"type": "npc", "name": "Nom",
|
||||||
|
"description": "Résumé du PNJ (rôle, apparence, motivation).",
|
||||||
|
"values": {{"<champ de la fiche PNJ>": "contenu", "<autre champ>": "contenu"}}}}
|
||||||
|
```
|
||||||
|
(`values` : utilise comme clés les CHAMPS DE LA FICHE PNJ listés dans le contexte
|
||||||
|
campagne s'ils y figurent — ex. "Histoire", "Apparence" — sinon omets `values`.)
|
||||||
|
|
||||||
|
```loremind-action
|
||||||
|
{{"type": "scene", "name": "Nom",
|
||||||
|
"description": "Résumé court de la scène.",
|
||||||
|
"location": "Lieu précis", "timing": "Quand elle survient",
|
||||||
|
"atmosphere": "Ambiance sensorielle (sons, odeurs, lumière…)",
|
||||||
|
"playerNarration": "Texte d'ambiance À LIRE AUX JOUEURS, immersif, à la 2e personne.",
|
||||||
|
"gmSecretNotes": "Secrets, vérités cachées, notes pour le MJ uniquement.",
|
||||||
|
"choicesConsequences": "Choix offerts aux joueurs et leurs conséquences.",
|
||||||
|
"combatDifficulty": "Difficulté du combat éventuel", "enemies": "Ennemis présents (effectifs, tactiques)"}}
|
||||||
```
|
```
|
||||||
```loremind-action
|
```loremind-action
|
||||||
{{"type": "scene", "name": "Nom", "description": "Résumé", "content": "Déroulé détaillé."}}
|
{{"type": "chapter", "name": "Nom",
|
||||||
|
"description": "Résumé du chapitre (ou de la quête).",
|
||||||
|
"playerObjectives": "Objectifs tels que les joueurs les perçoivent.",
|
||||||
|
"narrativeStakes": "Enjeux narratifs (ce qui se joue vraiment).",
|
||||||
|
"gmNotes": "Notes MJ : fils à tirer, points d'attention."}}
|
||||||
```
|
```
|
||||||
```loremind-action
|
```loremind-action
|
||||||
{{"type": "chapter", "name": "Nom", "description": "Résumé du chapitre."}}
|
{{"type": "arc", "name": "Nom", "description": "Résumé", "arcType": "LINEAR",
|
||||||
```
|
"themes": "Thèmes de l'arc", "stakes": "Enjeux",
|
||||||
```loremind-action
|
"rewards": "Récompenses attendues", "resolution": "Issues possibles",
|
||||||
{{"type": "arc", "name": "Nom", "description": "Résumé", "arcType": "LINEAR"}}
|
"gmNotes": "Notes MJ."}}
|
||||||
```
|
```
|
||||||
|
(`arcType` : "LINEAR" pour des chapitres en séquence, "HUB" pour un recueil de
|
||||||
|
quêtes parallèles.)
|
||||||
```loremind-action
|
```loremind-action
|
||||||
{{"type": "table", "name": "Nom", "diceFormula": "1d8", "entries": [{{"minRoll":1,"maxRoll":4,"label":"...","detail":"..."}}]}}
|
{{"type": "table", "name": "Nom", "diceFormula": "1d8", "entries": [{{"minRoll":1,"maxRoll":4,"label":"...","detail":"..."}}]}}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -25,21 +25,43 @@ async def with_heartbeat(
|
|||||||
coro: Awaitable[Any],
|
coro: Awaitable[Any],
|
||||||
*,
|
*,
|
||||||
interval: float = HEARTBEAT_INTERVAL_SECONDS,
|
interval: float = HEARTBEAT_INTERVAL_SECONDS,
|
||||||
|
status_queue: "asyncio.Queue | None" = None,
|
||||||
) -> AsyncIterator[tuple[str, Any]]:
|
) -> AsyncIterator[tuple[str, Any]]:
|
||||||
"""Exécute `coro` en émettant ('heartbeat', None) toutes les `interval`s tant
|
"""Exécute `coro` en émettant ('heartbeat', None) toutes les `interval`s tant
|
||||||
qu'elle n'est pas terminée, puis ('result', valeur).
|
qu'elle n'est pas terminée, puis ('result', valeur).
|
||||||
|
|
||||||
|
Si `status_queue` est fournie, les messages qui y sont publiés pendant
|
||||||
|
l'exécution (cf. import_status.notify_status : retry LLM, re-découpage…)
|
||||||
|
sont émis AU FIL DE L'EAU sous forme ('status', message) — c'est ce qui
|
||||||
|
permet à l'UI d'expliquer une attente au lieu d'une barre figée.
|
||||||
|
|
||||||
L'exception éventuelle de `coro` est propagée (re-levée par `task.result()`),
|
L'exception éventuelle de `coro` est propagée (re-levée par `task.result()`),
|
||||||
donc l'appelant peut l'attraper normalement. Si l'itération est abandonnée
|
donc l'appelant peut l'attraper normalement. Si l'itération est abandonnée
|
||||||
(client déconnecté), la tâche sous-jacente est annulée.
|
(client déconnecté), la tâche sous-jacente est annulée.
|
||||||
"""
|
"""
|
||||||
task: asyncio.Task = asyncio.ensure_future(coro)
|
task: asyncio.Task = asyncio.ensure_future(coro)
|
||||||
|
getter: asyncio.Task | None = None
|
||||||
try:
|
try:
|
||||||
while not task.done():
|
while not task.done():
|
||||||
done, _ = await asyncio.wait({task}, timeout=interval)
|
waiters: set[asyncio.Task] = {task}
|
||||||
|
if status_queue is not None and getter is None:
|
||||||
|
getter = asyncio.ensure_future(status_queue.get())
|
||||||
|
if getter is not None:
|
||||||
|
waiters.add(getter)
|
||||||
|
done, _ = await asyncio.wait(
|
||||||
|
waiters, timeout=interval, return_when=asyncio.FIRST_COMPLETED)
|
||||||
|
if getter is not None and getter in done:
|
||||||
|
yield ("status", getter.result())
|
||||||
|
getter = None # un nouveau get() sera créé au tour suivant
|
||||||
if not done:
|
if not done:
|
||||||
yield ("heartbeat", None)
|
yield ("heartbeat", None)
|
||||||
|
# Vide les statuts restés en file (publiés juste avant la fin de la tâche).
|
||||||
|
if status_queue is not None:
|
||||||
|
while not status_queue.empty():
|
||||||
|
yield ("status", status_queue.get_nowait())
|
||||||
yield ("result", task.result())
|
yield ("result", task.result())
|
||||||
finally:
|
finally:
|
||||||
|
if getter is not None and not getter.done():
|
||||||
|
getter.cancel()
|
||||||
if not task.done():
|
if not task.done():
|
||||||
task.cancel()
|
task.cancel()
|
||||||
|
|||||||
@@ -144,6 +144,16 @@ class GeminiLLMProvider:
|
|||||||
) as response:
|
) as response:
|
||||||
if response.status_code >= 400:
|
if response.status_code >= 400:
|
||||||
detail = (await response.aread()).decode("utf-8", "replace").strip()
|
detail = (await response.aread()).decode("utf-8", "replace").strip()
|
||||||
|
# 401/403 = clé rejetée par GOOGLE (pas un problème LoreMind) :
|
||||||
|
# message actionnable plutôt que le JSON brut de l'API.
|
||||||
|
if response.status_code in (401, 403):
|
||||||
|
raise LLMProviderError(
|
||||||
|
"Erreur Gemini : clé API refusée par Google "
|
||||||
|
f"(HTTP {response.status_code}). Vérifiez que la clé vient bien "
|
||||||
|
"de aistudio.google.com (« Get API key ») et qu'elle n'a pas de "
|
||||||
|
"restrictions (API ou adresse IP) dans la Google Cloud Console. "
|
||||||
|
f"Détail : {detail[:300]}"
|
||||||
|
)
|
||||||
raise LLMProviderError(
|
raise LLMProviderError(
|
||||||
f"Erreur Gemini (HTTP {response.status_code})"
|
f"Erreur Gemini (HTTP {response.status_code})"
|
||||||
+ (f" : {detail[:500]}" if detail else "")
|
+ (f" : {detail[:500]}" if detail else "")
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LoreMind Brain",
|
title="LoreMind Brain",
|
||||||
description="Backend IA pour la génération de contenu narratif.",
|
description="Backend IA pour la génération de contenu narratif.",
|
||||||
version="0.12.2-beta",
|
version="0.13.0-beta",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
<groupId>com.loremind</groupId>
|
<groupId>com.loremind</groupId>
|
||||||
<artifactId>loremind-core</artifactId>
|
<artifactId>loremind-core</artifactId>
|
||||||
<version>0.12.2-beta</version>
|
<version>0.13.0-beta</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
|
|||||||
@@ -42,15 +42,17 @@ public class CampaignBriefBuilder {
|
|||||||
if (notBlank(cc.campaignDescription())) sb.append(cc.campaignDescription()).append("\n");
|
if (notBlank(cc.campaignDescription())) sb.append(cc.campaignDescription()).append("\n");
|
||||||
|
|
||||||
sb.append("\n## Structure (arcs → chapitres → scènes)\n");
|
sb.append("\n## Structure (arcs → chapitres → scènes)\n");
|
||||||
|
sb.append("_Un arc HUB contient des chapitres parallèles appelés « quêtes » ; ")
|
||||||
|
.append("un arc LINEAR contient des chapitres en séquence._\n");
|
||||||
if (cc.arcs().isEmpty()) {
|
if (cc.arcs().isEmpty()) {
|
||||||
sb.append("_(aucun arc pour le moment)_\n");
|
sb.append("_(aucun arc pour le moment)_\n");
|
||||||
}
|
}
|
||||||
for (ArcSummary arc : cc.arcs()) {
|
for (ArcSummary arc : cc.arcs()) {
|
||||||
sb.append("### Arc : ").append(arc.name());
|
sb.append(arc.hub() ? "### Arc HUB (à quêtes) : " : "### Arc : ").append(arc.name());
|
||||||
if (notBlank(arc.description())) sb.append(" — ").append(arc.description());
|
if (notBlank(arc.description())) sb.append(" — ").append(arc.description());
|
||||||
sb.append("\n");
|
sb.append("\n");
|
||||||
for (ChapterSummary ch : arc.chapters()) {
|
for (ChapterSummary ch : arc.chapters()) {
|
||||||
sb.append("- Chapitre : ").append(ch.name());
|
sb.append(arc.hub() ? "- Quête : " : "- Chapitre : ").append(ch.name());
|
||||||
if (notBlank(ch.description())) sb.append(" — ").append(ch.description());
|
if (notBlank(ch.description())) sb.append(" — ").append(ch.description());
|
||||||
sb.append("\n");
|
sb.append("\n");
|
||||||
for (SceneSummary sc : ch.scenes()) {
|
for (SceneSummary sc : ch.scenes()) {
|
||||||
|
|||||||
@@ -65,10 +65,11 @@ public class CampaignImportService {
|
|||||||
String filename,
|
String filename,
|
||||||
Consumer<CampaignImportProgress> onProgress,
|
Consumer<CampaignImportProgress> onProgress,
|
||||||
Runnable onHeartbeat,
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
Consumer<CampaignImportProposal> onDone,
|
Consumer<CampaignImportProposal> onDone,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
campaignPdfImporter.importCampaignStreaming(
|
campaignPdfImporter.importCampaignStreaming(
|
||||||
pdfBytes, filename, onProgress, onHeartbeat, onDone, onError);
|
pdfBytes, filename, onProgress, onHeartbeat, onStatus, onDone, onError);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -163,7 +164,7 @@ public class CampaignImportService {
|
|||||||
isBlank(p.description())
|
isBlank(p.description())
|
||||||
? java.util.Map.of()
|
? java.util.Map.of()
|
||||||
: java.util.Map.of("Description", p.description().trim()),
|
: java.util.Map.of("Description", p.description().trim()),
|
||||||
null, null, campaignId, null, null));
|
null, null, campaignId, null, null, null));
|
||||||
created++;
|
created++;
|
||||||
}
|
}
|
||||||
return created;
|
return created;
|
||||||
|
|||||||
@@ -78,6 +78,11 @@ public class CharacterService {
|
|||||||
characterRepository.deleteById(id);
|
characterRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<Character> searchCharacters(String query) {
|
||||||
|
if (query == null || query.isBlank()) return List.of();
|
||||||
|
return characterRepository.searchByName(query.trim());
|
||||||
|
}
|
||||||
|
|
||||||
private int nextOrderFor(String playthroughId) {
|
private int nextOrderFor(String playthroughId) {
|
||||||
return characterRepository.findByPlaythroughId(playthroughId).stream()
|
return characterRepository.findByPlaythroughId(playthroughId).stream()
|
||||||
.mapToInt(Character::getOrder)
|
.mapToInt(Character::getOrder)
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Enemy;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service d'application pour les fiches d'ennemis (bestiaire de campagne).
|
||||||
|
* Miroir de {@link NpcService} : fiche pilotée par le template ENNEMI du GameSystem.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class EnemyService {
|
||||||
|
|
||||||
|
private final EnemyRepository enemyRepository;
|
||||||
|
|
||||||
|
public EnemyService(EnemyRepository enemyRepository) {
|
||||||
|
this.enemyRepository = enemyRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public record EnemyData(
|
||||||
|
String name,
|
||||||
|
String level,
|
||||||
|
String folder,
|
||||||
|
String portraitImageId,
|
||||||
|
String headerImageId,
|
||||||
|
Map<String, String> values,
|
||||||
|
Map<String, List<String>> imageValues,
|
||||||
|
Map<String, Map<String, String>> keyValueValues,
|
||||||
|
String campaignId,
|
||||||
|
Integer order
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public Enemy createEnemy(EnemyData data) {
|
||||||
|
int order = data.order() != null ? data.order() : nextOrderFor(data.campaignId());
|
||||||
|
Enemy enemy = Enemy.builder()
|
||||||
|
.name(data.name())
|
||||||
|
.level(normalize(data.level()))
|
||||||
|
.folder(normalize(data.folder()))
|
||||||
|
.portraitImageId(data.portraitImageId())
|
||||||
|
.headerImageId(data.headerImageId())
|
||||||
|
.values(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>())
|
||||||
|
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
|
||||||
|
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
|
||||||
|
.campaignId(data.campaignId())
|
||||||
|
.order(order)
|
||||||
|
.build();
|
||||||
|
return enemyRepository.save(enemy);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Enemy> getEnemyById(String id) {
|
||||||
|
return enemyRepository.findById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Enemy> getEnemiesByCampaignId(String campaignId) {
|
||||||
|
return enemyRepository.findByCampaignId(campaignId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Enemy updateEnemy(String id, EnemyData data) {
|
||||||
|
Enemy existing = enemyRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Enemy non trouvé avec l'ID: " + id));
|
||||||
|
existing.setName(data.name());
|
||||||
|
existing.setLevel(normalize(data.level()));
|
||||||
|
existing.setFolder(normalize(data.folder()));
|
||||||
|
existing.setPortraitImageId(data.portraitImageId());
|
||||||
|
existing.setHeaderImageId(data.headerImageId());
|
||||||
|
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
|
||||||
|
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
|
||||||
|
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||||
|
if (data.order() != null) {
|
||||||
|
existing.setOrder(data.order());
|
||||||
|
}
|
||||||
|
return enemyRepository.save(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteEnemy(String id) {
|
||||||
|
enemyRepository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Enemy> searchEnemies(String query) {
|
||||||
|
if (query == null || query.isBlank()) return List.of();
|
||||||
|
return enemyRepository.searchByName(query.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Trim ; chaîne vide → null (= non renseigné / non classé). */
|
||||||
|
private static String normalize(String value) {
|
||||||
|
if (value == null) return null;
|
||||||
|
String trimmed = value.trim();
|
||||||
|
return trimmed.isEmpty() ? null : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int nextOrderFor(String campaignId) {
|
||||||
|
return enemyRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.mapToInt(Enemy::getOrder)
|
||||||
|
.max()
|
||||||
|
.orElse(-1) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -82,6 +82,11 @@ public class ItemCatalogService {
|
|||||||
repository.deleteById(id);
|
repository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<ItemCatalog> searchCatalogs(String query) {
|
||||||
|
if (query == null || query.isBlank()) return List.of();
|
||||||
|
return repository.searchByName(query.trim());
|
||||||
|
}
|
||||||
|
|
||||||
/** Génère une PROPOSITION de catalogue (non persistée) via l'IA, contextualisée campagne. */
|
/** Génère une PROPOSITION de catalogue (non persistée) via l'IA, contextualisée campagne. */
|
||||||
public ItemCatalog generateProposal(String campaignId, String description) {
|
public ItemCatalog generateProposal(String campaignId, String description) {
|
||||||
ItemCatalogGenerator.GeneratedCatalog g = generator.generate(description, buildContext(campaignId));
|
ItemCatalogGenerator.GeneratedCatalog g = generator.generate(description, buildContext(campaignId));
|
||||||
|
|||||||
@@ -22,16 +22,19 @@ public class NotebookService {
|
|||||||
private final NotebookIndexer indexer;
|
private final NotebookIndexer indexer;
|
||||||
private final CampaignRepository campaignRepository;
|
private final CampaignRepository campaignRepository;
|
||||||
private final CampaignBriefBuilder briefBuilder;
|
private final CampaignBriefBuilder briefBuilder;
|
||||||
|
private final com.loremind.domain.gamesystemcontext.ports.GameSystemRepository gameSystemRepository;
|
||||||
|
|
||||||
public NotebookService(
|
public NotebookService(
|
||||||
NotebookRepository repository,
|
NotebookRepository repository,
|
||||||
NotebookIndexer indexer,
|
NotebookIndexer indexer,
|
||||||
CampaignRepository campaignRepository,
|
CampaignRepository campaignRepository,
|
||||||
CampaignBriefBuilder briefBuilder) {
|
CampaignBriefBuilder briefBuilder,
|
||||||
|
com.loremind.domain.gamesystemcontext.ports.GameSystemRepository gameSystemRepository) {
|
||||||
this.repository = repository;
|
this.repository = repository;
|
||||||
this.indexer = indexer;
|
this.indexer = indexer;
|
||||||
this.campaignRepository = campaignRepository;
|
this.campaignRepository = campaignRepository;
|
||||||
this.briefBuilder = briefBuilder;
|
this.briefBuilder = briefBuilder;
|
||||||
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Notebooks ---
|
// --- Notebooks ---
|
||||||
@@ -119,6 +122,58 @@ public class NotebookService {
|
|||||||
.notebookId(notebookId).role(role).content(content).build());
|
.notebookId(notebookId).role(role).content(content).build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** « Vider la conversation » : archive le fil actif (rien n'est supprimé). */
|
||||||
|
public void clearChat(String notebookId) {
|
||||||
|
repository.archiveMessagesByNotebookId(notebookId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Messages archivés, chronologiques — l'appelant regroupe par {@code archivedAt}. */
|
||||||
|
public List<NotebookMessage> getArchivedMessages(String notebookId) {
|
||||||
|
return repository.findArchivedMessagesByNotebookId(notebookId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Budget total (caractères ≈ tokens/4) des archives injectées en référence :
|
||||||
|
// borne le prompt même si l'utilisateur coche plusieurs longues conversations.
|
||||||
|
private static final int ARCHIVE_CONTEXT_MAX_CHARS = 16000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bloc de contexte construit à partir des archives COCHÉES par l'utilisateur
|
||||||
|
* (clés = {@code archivedAt.toString()}). Injecté dans le prompt du chat pour
|
||||||
|
* que l'IA puisse s'appuyer sur d'anciennes conversations. Chaîne vide si
|
||||||
|
* aucune clé valide. Chaque archive est tronquée PAR LE DÉBUT au-delà de son
|
||||||
|
* budget : la fin d'une conversation (conclusions) est la partie utile.
|
||||||
|
*/
|
||||||
|
public String buildArchiveContext(String notebookId, List<String> archivedAtKeys) {
|
||||||
|
if (archivedAtKeys == null || archivedAtKeys.isEmpty()) return "";
|
||||||
|
var wanted = new java.util.HashSet<>(archivedAtKeys);
|
||||||
|
var groups = new java.util.LinkedHashMap<java.time.LocalDateTime, List<NotebookMessage>>();
|
||||||
|
for (NotebookMessage m : repository.findArchivedMessagesByNotebookId(notebookId)) {
|
||||||
|
if (m.getArchivedAt() != null && wanted.contains(m.getArchivedAt().toString())) {
|
||||||
|
groups.computeIfAbsent(m.getArchivedAt(), k -> new java.util.ArrayList<>()).add(m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (groups.isEmpty()) return "";
|
||||||
|
|
||||||
|
int budgetPerArchive = Math.max(2000, ARCHIVE_CONTEXT_MAX_CHARS / groups.size());
|
||||||
|
StringBuilder out = new StringBuilder(
|
||||||
|
"--- ANCIENNES CONVERSATIONS DE CET ATELIER (références choisies par le MJ : "
|
||||||
|
+ "tu peux t'appuyer sur leurs conclusions) ---\n");
|
||||||
|
groups.forEach((archivedAt, messages) -> {
|
||||||
|
StringBuilder convo = new StringBuilder();
|
||||||
|
for (NotebookMessage m : messages) {
|
||||||
|
convo.append("user".equals(m.getRole()) ? "MJ : " : "IA : ")
|
||||||
|
.append(m.getContent()).append('\n');
|
||||||
|
}
|
||||||
|
String text = convo.toString();
|
||||||
|
if (text.length() > budgetPerArchive) {
|
||||||
|
text = "[…début tronqué…]\n" + text.substring(text.length() - budgetPerArchive);
|
||||||
|
}
|
||||||
|
out.append("[Archive du ").append(archivedAt).append("]\n").append(text).append('\n');
|
||||||
|
});
|
||||||
|
out.append("--- FIN DES ANCIENNES CONVERSATIONS ---");
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
// --- Contexte campagne (oriente l'IA) ---
|
// --- Contexte campagne (oriente l'IA) ---
|
||||||
|
|
||||||
/** Brief COMPLET de la campagne (structure arcs/chapitres/scènes + PNJ + lore) :
|
/** Brief COMPLET de la campagne (structure arcs/chapitres/scènes + PNJ + lore) :
|
||||||
@@ -127,6 +182,25 @@ public class NotebookService {
|
|||||||
if (campaignId == null) return "";
|
if (campaignId == null) return "";
|
||||||
Campaign campaign = campaignRepository.findById(campaignId).orElse(null);
|
Campaign campaign = campaignRepository.findById(campaignId).orElse(null);
|
||||||
if (campaign == null) return "";
|
if (campaign == null) return "";
|
||||||
return briefBuilder.build(campaign);
|
String brief = briefBuilder.build(campaign);
|
||||||
|
// Champs TEXT de la fiche PNJ du système de jeu : permet à l'IA de remplir
|
||||||
|
// `values` des actions "npc" avec les BONS noms de champs (Histoire,
|
||||||
|
// Apparence…) au lieu de tout entasser dans une description générique.
|
||||||
|
String npcFields = npcSheetFields(campaign.getGameSystemId());
|
||||||
|
return npcFields.isEmpty() ? brief : brief + "\n\n" + npcFields;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String npcSheetFields(String gameSystemId) {
|
||||||
|
if (gameSystemId == null || gameSystemId.isBlank()) return "";
|
||||||
|
var gameSystem = gameSystemRepository.findById(gameSystemId).orElse(null);
|
||||||
|
if (gameSystem == null || gameSystem.getNpcTemplate() == null) return "";
|
||||||
|
var names = gameSystem.getNpcTemplate().stream()
|
||||||
|
.filter(f -> f.getType() == com.loremind.domain.shared.template.FieldType.TEXT)
|
||||||
|
.map(com.loremind.domain.shared.template.TemplateField::getName)
|
||||||
|
.filter(n -> n != null && !n.isBlank())
|
||||||
|
.toList();
|
||||||
|
if (names.isEmpty()) return "";
|
||||||
|
return "FICHE PNJ — champs texte disponibles (clés à utiliser dans `values` "
|
||||||
|
+ "d'une action npc) : " + String.join(", ", names);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
import com.loremind.domain.campaigncontext.Npc;
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -16,9 +19,11 @@ import java.util.Optional;
|
|||||||
public class NpcService {
|
public class NpcService {
|
||||||
|
|
||||||
private final NpcRepository npcRepository;
|
private final NpcRepository npcRepository;
|
||||||
|
private final CampaignRepository campaignRepository;
|
||||||
|
|
||||||
public NpcService(NpcRepository npcRepository) {
|
public NpcService(NpcRepository npcRepository, CampaignRepository campaignRepository) {
|
||||||
this.npcRepository = npcRepository;
|
this.npcRepository = npcRepository;
|
||||||
|
this.campaignRepository = campaignRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public record NpcData(
|
public record NpcData(
|
||||||
@@ -29,6 +34,7 @@ public class NpcService {
|
|||||||
Map<String, List<String>> imageValues,
|
Map<String, List<String>> imageValues,
|
||||||
Map<String, Map<String, String>> keyValueValues,
|
Map<String, Map<String, String>> keyValueValues,
|
||||||
String campaignId,
|
String campaignId,
|
||||||
|
List<String> relatedPageIds,
|
||||||
String folder,
|
String folder,
|
||||||
Integer order
|
Integer order
|
||||||
) {}
|
) {}
|
||||||
@@ -45,6 +51,7 @@ public class NpcService {
|
|||||||
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
|
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
|
||||||
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
|
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
|
||||||
.campaignId(data.campaignId())
|
.campaignId(data.campaignId())
|
||||||
|
.relatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>())
|
||||||
.folder(normalizeFolder(data.folder()))
|
.folder(normalizeFolder(data.folder()))
|
||||||
.order(order)
|
.order(order)
|
||||||
.build();
|
.build();
|
||||||
@@ -59,6 +66,21 @@ public class NpcService {
|
|||||||
return npcRepository.findByCampaignId(campaignId);
|
return npcRepository.findByCampaignId(campaignId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PNJ de TOUTES les campagnes liées au Lore donné (via {@code campaign.loreId}).
|
||||||
|
* Sert au graphe du Lore : relier les PNJ aux pages qu'ils référencent.
|
||||||
|
* Volume faible (usage mono-utilisateur) → filtrage en mémoire assumé.
|
||||||
|
*/
|
||||||
|
public List<Npc> getNpcsByLoreId(String loreId) {
|
||||||
|
List<Npc> out = new ArrayList<>();
|
||||||
|
for (Campaign campaign : campaignRepository.findAll()) {
|
||||||
|
if (campaign.isLinkedToLore() && campaign.getLoreId().equals(loreId)) {
|
||||||
|
out.addAll(npcRepository.findByCampaignId(campaign.getId()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
public Npc updateNpc(String id, NpcData data) {
|
public Npc updateNpc(String id, NpcData data) {
|
||||||
Npc existing = npcRepository.findById(id)
|
Npc existing = npcRepository.findById(id)
|
||||||
.orElseThrow(() -> new IllegalArgumentException("Npc non trouvé avec l'ID: " + id));
|
.orElseThrow(() -> new IllegalArgumentException("Npc non trouvé avec l'ID: " + id));
|
||||||
@@ -68,6 +90,7 @@ public class NpcService {
|
|||||||
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
|
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
|
||||||
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
|
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
|
||||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||||
|
existing.setRelatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>());
|
||||||
existing.setFolder(normalizeFolder(data.folder()));
|
existing.setFolder(normalizeFolder(data.folder()));
|
||||||
if (data.order() != null) {
|
if (data.order() != null) {
|
||||||
existing.setOrder(data.order());
|
existing.setOrder(data.order());
|
||||||
@@ -79,6 +102,11 @@ public class NpcService {
|
|||||||
npcRepository.deleteById(id);
|
npcRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<Npc> searchNpcs(String query) {
|
||||||
|
if (query == null || query.isBlank()) return List.of();
|
||||||
|
return npcRepository.searchByName(query.trim());
|
||||||
|
}
|
||||||
|
|
||||||
/** Trim le dossier ; chaîne vide → null (= non classé). */
|
/** Trim le dossier ; chaîne vide → null (= non classé). */
|
||||||
private static String normalizeFolder(String folder) {
|
private static String normalizeFolder(String folder) {
|
||||||
if (folder == null) return null;
|
if (folder == null) return null;
|
||||||
|
|||||||
@@ -85,6 +85,11 @@ public class RandomTableService {
|
|||||||
repository.deleteById(id);
|
repository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<RandomTable> searchTables(String query) {
|
||||||
|
if (query == null || query.isBlank()) return List.of();
|
||||||
|
return repository.searchByName(query.trim());
|
||||||
|
}
|
||||||
|
|
||||||
/** Génère une PROPOSITION de table (non persistée) via l'IA, contextualisée campagne. */
|
/** Génère une PROPOSITION de table (non persistée) via l'IA, contextualisée campagne. */
|
||||||
public RandomTable generateProposal(String campaignId, String description, String diceFormula) {
|
public RandomTable generateProposal(String campaignId, String description, String diceFormula) {
|
||||||
String formula = (diceFormula == null || diceFormula.isBlank()) ? "1d20" : diceFormula;
|
String formula = (diceFormula == null || diceFormula.isBlank()) ? "1d20" : diceFormula;
|
||||||
|
|||||||
@@ -40,10 +40,11 @@ public class GameSystemService {
|
|||||||
String filename,
|
String filename,
|
||||||
java.util.function.Consumer<com.loremind.domain.gamesystemcontext.RulesImportProgress> onProgress,
|
java.util.function.Consumer<com.loremind.domain.gamesystemcontext.RulesImportProgress> onProgress,
|
||||||
Runnable onHeartbeat,
|
Runnable onHeartbeat,
|
||||||
|
java.util.function.Consumer<String> onStatus,
|
||||||
java.util.function.Consumer<RulesImportResult> onDone,
|
java.util.function.Consumer<RulesImportResult> onDone,
|
||||||
java.util.function.Consumer<Throwable> onError) {
|
java.util.function.Consumer<Throwable> onError) {
|
||||||
rulesPdfImporter.importRulesStreaming(
|
rulesPdfImporter.importRulesStreaming(
|
||||||
pdfBytes, filename, onProgress, onHeartbeat, onDone, onError);
|
pdfBytes, filename, onProgress, onHeartbeat, onStatus, onDone, onError);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -56,6 +57,7 @@ public class GameSystemService {
|
|||||||
String rulesMarkdown,
|
String rulesMarkdown,
|
||||||
List<TemplateField> characterTemplate,
|
List<TemplateField> characterTemplate,
|
||||||
List<TemplateField> npcTemplate,
|
List<TemplateField> npcTemplate,
|
||||||
|
List<TemplateField> enemyTemplate,
|
||||||
String author,
|
String author,
|
||||||
boolean isPublic
|
boolean isPublic
|
||||||
) {}
|
) {}
|
||||||
@@ -70,6 +72,7 @@ public class GameSystemService {
|
|||||||
.build();
|
.build();
|
||||||
gameSystem.replaceCharacterTemplate(data.characterTemplate());
|
gameSystem.replaceCharacterTemplate(data.characterTemplate());
|
||||||
gameSystem.replaceNpcTemplate(data.npcTemplate());
|
gameSystem.replaceNpcTemplate(data.npcTemplate());
|
||||||
|
gameSystem.replaceEnemyTemplate(data.enemyTemplate());
|
||||||
return gameSystemRepository.save(gameSystem);
|
return gameSystemRepository.save(gameSystem);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +92,7 @@ public class GameSystemService {
|
|||||||
existing.setRulesMarkdown(data.rulesMarkdown());
|
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||||
existing.replaceCharacterTemplate(data.characterTemplate());
|
existing.replaceCharacterTemplate(data.characterTemplate());
|
||||||
existing.replaceNpcTemplate(data.npcTemplate());
|
existing.replaceNpcTemplate(data.npcTemplate());
|
||||||
|
existing.replaceEnemyTemplate(data.enemyTemplate());
|
||||||
existing.setAuthor(normalize(data.author()));
|
existing.setAuthor(normalize(data.author()));
|
||||||
existing.setPublic(data.isPublic());
|
existing.setPublic(data.isPublic());
|
||||||
return gameSystemRepository.save(existing);
|
return gameSystemRepository.save(existing);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.application.generationcontext;
|
package com.loremind.application.generationcontext;
|
||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Arc;
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
|
import com.loremind.domain.campaigncontext.ArcType;
|
||||||
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.Character;
|
||||||
@@ -10,6 +11,7 @@ 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.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
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;
|
||||||
@@ -48,6 +50,7 @@ public class CampaignStructuralContextBuilder {
|
|||||||
private final SceneRepository sceneRepository;
|
private final SceneRepository sceneRepository;
|
||||||
private final CharacterRepository characterRepository;
|
private final CharacterRepository characterRepository;
|
||||||
private final NpcRepository npcRepository;
|
private final NpcRepository npcRepository;
|
||||||
|
private final EnemyRepository enemyRepository;
|
||||||
|
|
||||||
public CampaignStructuralContextBuilder(
|
public CampaignStructuralContextBuilder(
|
||||||
CampaignRepository campaignRepository,
|
CampaignRepository campaignRepository,
|
||||||
@@ -55,13 +58,15 @@ public class CampaignStructuralContextBuilder {
|
|||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
SceneRepository sceneRepository,
|
SceneRepository sceneRepository,
|
||||||
CharacterRepository characterRepository,
|
CharacterRepository characterRepository,
|
||||||
NpcRepository npcRepository) {
|
NpcRepository npcRepository,
|
||||||
|
EnemyRepository enemyRepository) {
|
||||||
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;
|
this.characterRepository = characterRepository;
|
||||||
this.npcRepository = npcRepository;
|
this.npcRepository = npcRepository;
|
||||||
|
this.enemyRepository = enemyRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Longueur max du snippet de PJ/PNJ injecté dans le contexte (coût tokens maîtrisé). */
|
/** Longueur max du snippet de PJ/PNJ injecté dans le contexte (coût tokens maîtrisé). */
|
||||||
@@ -84,9 +89,17 @@ public class CampaignStructuralContextBuilder {
|
|||||||
.orElseThrow(() -> new IllegalArgumentException(
|
.orElseThrow(() -> new IllegalArgumentException(
|
||||||
"Campagne non trouvée avec l'ID: " + campaignId));
|
"Campagne non trouvée avec l'ID: " + campaignId));
|
||||||
|
|
||||||
|
// Libellés du bestiaire (« Nom (niveau) ») chargés UNE fois pour résoudre
|
||||||
|
// les enemyIds des pièces sans N+1 sur le repo.
|
||||||
|
Map<String, String> enemyLabelById = enemyRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.collect(Collectors.toMap(
|
||||||
|
com.loremind.domain.campaigncontext.Enemy::getId,
|
||||||
|
CampaignStructuralContextBuilder::enemyLabel,
|
||||||
|
(a, b) -> a));
|
||||||
|
|
||||||
List<ArcSummary> arcs = arcRepository.findByCampaignId(campaignId).stream()
|
List<ArcSummary> arcs = arcRepository.findByCampaignId(campaignId).stream()
|
||||||
.sorted(Comparator.comparingInt(Arc::getOrder))
|
.sorted(Comparator.comparingInt(Arc::getOrder))
|
||||||
.map(this::toArcSummary)
|
.map(arc -> toArcSummary(arc, enemyLabelById))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
List<CharacterSummary> characters = (playthroughId == null || playthroughId.isBlank())
|
List<CharacterSummary> characters = (playthroughId == null || playthroughId.isBlank())
|
||||||
@@ -143,19 +156,20 @@ public class CampaignStructuralContextBuilder {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
private ArcSummary toArcSummary(Arc arc) {
|
private ArcSummary toArcSummary(Arc arc, Map<String, String> enemyLabelById) {
|
||||||
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))
|
||||||
.map(this::toChapterSummary)
|
.map(chapter -> toChapterSummary(chapter, enemyLabelById))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
return new ArcSummary(
|
return new ArcSummary(
|
||||||
arc.getName(),
|
arc.getName(),
|
||||||
arc.getDescription(),
|
arc.getDescription(),
|
||||||
|
arc.getType() == ArcType.HUB,
|
||||||
countImages(arc.getIllustrationImageIds()),
|
countImages(arc.getIllustrationImageIds()),
|
||||||
chapters);
|
chapters);
|
||||||
}
|
}
|
||||||
|
|
||||||
private ChapterSummary toChapterSummary(Chapter chapter) {
|
private ChapterSummary toChapterSummary(Chapter chapter, Map<String, String> enemyLabelById) {
|
||||||
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId()).stream()
|
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId()).stream()
|
||||||
.sorted(Comparator.comparingInt(Scene::getOrder))
|
.sorted(Comparator.comparingInt(Scene::getOrder))
|
||||||
.toList();
|
.toList();
|
||||||
@@ -166,7 +180,7 @@ public class CampaignStructuralContextBuilder {
|
|||||||
.collect(Collectors.toMap(Scene::getId, Scene::getName));
|
.collect(Collectors.toMap(Scene::getId, Scene::getName));
|
||||||
|
|
||||||
List<SceneSummary> summaries = scenes.stream()
|
List<SceneSummary> summaries = scenes.stream()
|
||||||
.map(s -> toSceneSummary(s, nameById))
|
.map(s -> toSceneSummary(s, nameById, enemyLabelById))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
return new ChapterSummary(
|
return new ChapterSummary(
|
||||||
@@ -176,7 +190,8 @@ public class CampaignStructuralContextBuilder {
|
|||||||
summaries);
|
summaries);
|
||||||
}
|
}
|
||||||
|
|
||||||
private SceneSummary toSceneSummary(Scene scene, Map<String, String> nameById) {
|
private SceneSummary toSceneSummary(
|
||||||
|
Scene scene, Map<String, String> nameById, Map<String, String> enemyLabelById) {
|
||||||
List<BranchHint> hints = scene.getBranches() == null
|
List<BranchHint> hints = scene.getBranches() == null
|
||||||
? List.of()
|
? List.of()
|
||||||
: scene.getBranches().stream()
|
: scene.getBranches().stream()
|
||||||
@@ -186,7 +201,7 @@ public class CampaignStructuralContextBuilder {
|
|||||||
b.condition()))
|
b.condition()))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
List<RoomSummary> rooms = toRoomSummaries(scene);
|
List<RoomSummary> rooms = toRoomSummaries(scene, enemyLabelById);
|
||||||
|
|
||||||
return new SceneSummary(
|
return new SceneSummary(
|
||||||
scene.getName(),
|
scene.getName(),
|
||||||
@@ -202,7 +217,7 @@ public class CampaignStructuralContextBuilder {
|
|||||||
* connaît la structure du lieu (nom des pièces, ennemis, sorties) — c'est
|
* connaît la structure du lieu (nom des pièces, ennemis, sorties) — c'est
|
||||||
* suffisant pour proposer de la narration ou anticiper les choix.
|
* suffisant pour proposer de la narration ou anticiper les choix.
|
||||||
*/
|
*/
|
||||||
private List<RoomSummary> toRoomSummaries(Scene scene) {
|
private List<RoomSummary> toRoomSummaries(Scene scene, Map<String, String> enemyLabelById) {
|
||||||
if (scene.getRooms() == null || scene.getRooms().isEmpty()) return List.of();
|
if (scene.getRooms() == null || scene.getRooms().isEmpty()) return List.of();
|
||||||
Map<String, String> nameById = scene.getRooms().stream()
|
Map<String, String> nameById = scene.getRooms().stream()
|
||||||
.collect(Collectors.toMap(
|
.collect(Collectors.toMap(
|
||||||
@@ -219,11 +234,36 @@ public class CampaignStructuralContextBuilder {
|
|||||||
nameById.getOrDefault(b.targetRoomId(), "(pièce inconnue)"),
|
nameById.getOrDefault(b.targetRoomId(), "(pièce inconnue)"),
|
||||||
b.condition()))
|
b.condition()))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
return new RoomSummary(r.getName(), r.getFloor(), r.getDescription(), r.getEnemies(), hints);
|
return new RoomSummary(
|
||||||
|
r.getName(), r.getFloor(), r.getDescription(),
|
||||||
|
roomEnemiesText(r, enemyLabelById), hints);
|
||||||
})
|
})
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Texte « ennemis » d'une pièce pour le prompt : fiches du bestiaire
|
||||||
|
* référencées (libellés résolus, IDs orphelins ignorés) suivies du texte
|
||||||
|
* libre. L'un ou l'autre peut être vide.
|
||||||
|
*/
|
||||||
|
private static String roomEnemiesText(
|
||||||
|
com.loremind.domain.campaigncontext.Room room, Map<String, String> enemyLabelById) {
|
||||||
|
String linked = room.getEnemyIds() == null ? "" : room.getEnemyIds().stream()
|
||||||
|
.map(enemyLabelById::get)
|
||||||
|
.filter(l -> l != null && !l.isBlank())
|
||||||
|
.collect(Collectors.joining(", "));
|
||||||
|
String freeText = room.getEnemies() == null ? "" : room.getEnemies().strip();
|
||||||
|
if (linked.isEmpty()) return freeText;
|
||||||
|
if (freeText.isEmpty()) return linked;
|
||||||
|
return linked + " — " + freeText;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Libellé court d'une fiche du bestiaire : « Nom (niveau) » ou « Nom ». */
|
||||||
|
private static String enemyLabel(com.loremind.domain.campaigncontext.Enemy enemy) {
|
||||||
|
String level = enemy.getLevel() == null ? "" : enemy.getLevel().strip();
|
||||||
|
return level.isEmpty() ? enemy.getName() : enemy.getName() + " (" + level + ")";
|
||||||
|
}
|
||||||
|
|
||||||
/** Helper defensif : compte les illustrations attachees (null-safe). */
|
/** Helper defensif : compte les illustrations attachees (null-safe). */
|
||||||
private static int countImages(List<String> ids) {
|
private static int countImages(List<String> ids) {
|
||||||
return ids == null ? 0 : ids.size();
|
return ids == null ? 0 : ids.size();
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ 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.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
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;
|
||||||
@@ -32,18 +33,21 @@ public class NarrativeEntityContextBuilder {
|
|||||||
private final SceneRepository sceneRepository;
|
private final SceneRepository sceneRepository;
|
||||||
private final CharacterRepository characterRepository;
|
private final CharacterRepository characterRepository;
|
||||||
private final NpcRepository npcRepository;
|
private final NpcRepository npcRepository;
|
||||||
|
private final EnemyRepository enemyRepository;
|
||||||
|
|
||||||
public NarrativeEntityContextBuilder(
|
public NarrativeEntityContextBuilder(
|
||||||
ArcRepository arcRepository,
|
ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
SceneRepository sceneRepository,
|
SceneRepository sceneRepository,
|
||||||
CharacterRepository characterRepository,
|
CharacterRepository characterRepository,
|
||||||
NpcRepository npcRepository) {
|
NpcRepository npcRepository,
|
||||||
|
EnemyRepository enemyRepository) {
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
this.characterRepository = characterRepository;
|
this.characterRepository = characterRepository;
|
||||||
this.npcRepository = npcRepository;
|
this.npcRepository = npcRepository;
|
||||||
|
this.enemyRepository = enemyRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -124,10 +128,41 @@ public class NarrativeEntityContextBuilder {
|
|||||||
putField(fields, "choicesConsequences", s.getChoicesConsequences());
|
putField(fields, "choicesConsequences", s.getChoicesConsequences());
|
||||||
putField(fields, "combatDifficulty", s.getCombatDifficulty());
|
putField(fields, "combatDifficulty", s.getCombatDifficulty());
|
||||||
putField(fields, "enemies", s.getEnemies());
|
putField(fields, "enemies", s.getEnemies());
|
||||||
|
putField(fields, "linkedEnemies", resolveLinkedEnemies(s));
|
||||||
putField(fields, "gmSecretNotes", s.getGmSecretNotes());
|
putField(fields, "gmSecretNotes", s.getGmSecretNotes());
|
||||||
return new NarrativeEntityContext("scene", s.getName(), fields);
|
return new NarrativeEntityContext("scene", s.getName(), fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résout les fiches du bestiaire référencées par la scène en une ligne par
|
||||||
|
* ennemi : « Nom (niveau) — champ: valeur ; … ». Valeurs tronquées : le
|
||||||
|
* contexte focus doit camper la rencontre, pas embarquer la fiche complète.
|
||||||
|
* Les IDs orphelins (fiche supprimée) sont ignorés silencieusement.
|
||||||
|
*/
|
||||||
|
private String resolveLinkedEnemies(Scene s) {
|
||||||
|
if (s.getEnemyIds() == null || s.getEnemyIds().isEmpty()) return "";
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (String enemyId : s.getEnemyIds()) {
|
||||||
|
enemyRepository.findById(enemyId).ifPresent(e -> {
|
||||||
|
if (sb.length() > 0) sb.append("\n");
|
||||||
|
sb.append("- ").append(e.getName());
|
||||||
|
if (e.getLevel() != null && !e.getLevel().isBlank()) {
|
||||||
|
sb.append(" (").append(e.getLevel().trim()).append(")");
|
||||||
|
}
|
||||||
|
String stats = e.getValues().entrySet().stream()
|
||||||
|
.filter(en -> en.getValue() != null && !en.getValue().isBlank())
|
||||||
|
.map(en -> en.getKey() + ": " + truncate(en.getValue().trim(), 100))
|
||||||
|
.collect(java.util.stream.Collectors.joining(" ; "));
|
||||||
|
if (!stats.isEmpty()) sb.append(" — ").append(stats);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String truncate(String value, int maxLen) {
|
||||||
|
return value.length() <= maxLen ? value : value.substring(0, maxLen - 1).stripTrailing() + "…";
|
||||||
|
}
|
||||||
|
|
||||||
private NarrativeEntityContext fromCharacter(Character c) {
|
private NarrativeEntityContext fromCharacter(Character c) {
|
||||||
Map<String, String> fields = new LinkedHashMap<>();
|
Map<String, String> fields = new LinkedHashMap<>();
|
||||||
if (c.getValues() != null) {
|
if (c.getValues() != null) {
|
||||||
|
|||||||
@@ -76,6 +76,8 @@ public class PageService {
|
|||||||
existing.setNodeId(changes.getNodeId());
|
existing.setNodeId(changes.getNodeId());
|
||||||
existing.setValues(CollectionUtils.copyMap(changes.getValues()));
|
existing.setValues(CollectionUtils.copyMap(changes.getValues()));
|
||||||
existing.setImageValues(CollectionUtils.copyMap(changes.getImageValues()));
|
existing.setImageValues(CollectionUtils.copyMap(changes.getImageValues()));
|
||||||
|
existing.setKeyValueValues(CollectionUtils.copyMap(changes.getKeyValueValues()));
|
||||||
|
existing.setTableValues(CollectionUtils.copyMap(changes.getTableValues()));
|
||||||
existing.setNotes(changes.getNotes());
|
existing.setNotes(changes.getNotes());
|
||||||
existing.setTags(CollectionUtils.copyList(changes.getTags()));
|
existing.setTags(CollectionUtils.copyList(changes.getTags()));
|
||||||
existing.setRelatedPageIds(CollectionUtils.copyList(changes.getRelatedPageIds()));
|
existing.setRelatedPageIds(CollectionUtils.copyList(changes.getRelatedPageIds()));
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche d'ennemi (monstre/créature) d'une campagne — le bestiaire du MJ.
|
||||||
|
* <p>
|
||||||
|
* Même principe de templating que {@link Npc} : champs universels hard-codés
|
||||||
|
* (nom, niveau, dossier, portrait, bandeau) + champs pilotés par le template
|
||||||
|
* ENNEMI du GameSystem ({@code GameSystem.enemyTemplate} : CA, PV, attaques…).
|
||||||
|
* Classement libre par dossier (« Démons », « Humanoïdes »…).
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class Enemy {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** Niveau / FP / dangerosité — texte libre (« 5 », « FP 8 », « Boss »). Nullable. */
|
||||||
|
private String level;
|
||||||
|
|
||||||
|
/** Dossier de classement (texte libre). Null = non classé. */
|
||||||
|
private String folder;
|
||||||
|
|
||||||
|
/** ID de l'image portrait (champ universel hard-codé). Nullable. */
|
||||||
|
private String portraitImageId;
|
||||||
|
|
||||||
|
/** ID de l'image header/bannière (champ universel hard-codé). Nullable. */
|
||||||
|
private String headerImageId;
|
||||||
|
|
||||||
|
/** Valeurs TEXT/NUMBER du template ennemi. Jamais null après construction. */
|
||||||
|
private Map<String, String> values;
|
||||||
|
|
||||||
|
/** Valeurs IMAGE du template ennemi (listes d'IDs ordonnées par champ). Jamais null. */
|
||||||
|
private Map<String, List<String>> imageValues;
|
||||||
|
|
||||||
|
/** Valeurs KEY_VALUE_LIST : fieldName -> label -> value. Jamais null. */
|
||||||
|
private Map<String, Map<String, String>> keyValueValues;
|
||||||
|
|
||||||
|
/** Référence vers la Campaign parente (cross-aggregate via ID). */
|
||||||
|
private String campaignId;
|
||||||
|
|
||||||
|
/** Ordre d'affichage dans la liste. */
|
||||||
|
private int order;
|
||||||
|
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
public Map<String, String> getValues() {
|
||||||
|
if (values == null) values = new HashMap<>();
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, List<String>> getImageValues() {
|
||||||
|
if (imageValues == null) imageValues = new HashMap<>();
|
||||||
|
return imageValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Map<String, String>> getKeyValueValues() {
|
||||||
|
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||||
|
return keyValueValues;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,4 +17,6 @@ public class NotebookMessage {
|
|||||||
private String role;
|
private String role;
|
||||||
private String content;
|
private String content;
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
/** Null = conversation active ; sinon horodatage du « vider » (lot d'archive). */
|
||||||
|
private LocalDateTime archivedAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import lombok.Builder;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -46,6 +47,13 @@ public class Npc {
|
|||||||
/** Référence vers la Campaign parente (cross-aggregate via ID). */
|
/** Référence vers la Campaign parente (cross-aggregate via ID). */
|
||||||
private String campaignId;
|
private String campaignId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IDs de Pages de Lore référencées par ce PNJ (sa ville, sa faction, sa
|
||||||
|
* région…). Référence faible cross-context, même principe que sur
|
||||||
|
* Arc/Chapter/Scene — alimente notamment le graphe du Lore.
|
||||||
|
*/
|
||||||
|
private List<String> relatedPageIds;
|
||||||
|
|
||||||
/** Dossier de classement (texte libre, ex. « Bard's Gate »). Nullable = non classé. */
|
/** Dossier de classement (texte libre, ex. « Bard's Gate »). Nullable = non classé. */
|
||||||
private String folder;
|
private String folder;
|
||||||
|
|
||||||
@@ -69,4 +77,9 @@ public class Npc {
|
|||||||
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||||
return keyValueValues;
|
return keyValueValues;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<String> getRelatedPageIds() {
|
||||||
|
if (relatedPageIds == null) relatedPageIds = new ArrayList<>();
|
||||||
|
return relatedPageIds;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,13 @@ public class Room {
|
|||||||
/** Énemis, créatures, boss éventuels (markdown libre). */
|
/** Énemis, créatures, boss éventuels (markdown libre). */
|
||||||
private String enemies;
|
private String enemies;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IDs des fiches du bestiaire ({@link Enemy}) présentes dans la pièce
|
||||||
|
* (weak refs). Complète le texte libre {@code enemies}, comme sur Scene.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private List<String> enemyIds = new ArrayList<>();
|
||||||
|
|
||||||
/** Loot / récompenses présentes dans la pièce. */
|
/** Loot / récompenses présentes dans la pièce. */
|
||||||
private String loot;
|
private String loot;
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,15 @@ public class Scene {
|
|||||||
|
|
||||||
// === Combat ou rencontre ===
|
// === Combat ou rencontre ===
|
||||||
private String combatDifficulty; // Difficulté estimée
|
private String combatDifficulty; // Difficulté estimée
|
||||||
private String enemies; // Liste des ennemis et créatures
|
private String enemies; // Liste des ennemis et créatures (texte libre)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IDs des fiches du bestiaire ({@link Enemy}) engagées dans cette rencontre
|
||||||
|
* (weak cross-aggregate references). Complète le texte libre `enemies` :
|
||||||
|
* l'utilisateur peut référencer ses fiches, ou tout écrire à la main, ou les deux.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private List<String> enemyIds = new ArrayList<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IDs des pages du Lore associées à cette scène (weak cross-context references).
|
* IDs des pages du Lore associées à cette scène (weak cross-context references).
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ public interface CampaignPdfImporter {
|
|||||||
* @param onHeartbeat invoqué périodiquement pendant un appel LLM long (aucune
|
* @param onHeartbeat invoqué périodiquement pendant un appel LLM long (aucune
|
||||||
* avancée à afficher, mais le canal SSE vers le navigateur
|
* avancée à afficher, mais le canal SSE vers le navigateur
|
||||||
* doit rester actif — sinon un proxy intermédiaire le coupe).
|
* doit rester actif — sinon un proxy intermédiaire le coupe).
|
||||||
|
* @param onStatus invoqué avec un message lisible quand quelque chose se
|
||||||
|
* passe pendant l'attente (fournisseur saturé → retry,
|
||||||
|
* morceau re-découpé, morceau ignoré…) — affiché par l'UI
|
||||||
|
* pour que l'utilisateur n'ait pas à lire les logs.
|
||||||
* @param onDone invoqué une fois avec l'arbre proposé (non persisté).
|
* @param onDone invoqué une fois avec l'arbre proposé (non persisté).
|
||||||
* @param onError invoqué si l'extraction/structuration échoue.
|
* @param onError invoqué si l'extraction/structuration échoue.
|
||||||
*/
|
*/
|
||||||
@@ -27,6 +31,7 @@ public interface CampaignPdfImporter {
|
|||||||
String filename,
|
String filename,
|
||||||
Consumer<CampaignImportProgress> onProgress,
|
Consumer<CampaignImportProgress> onProgress,
|
||||||
Runnable onHeartbeat,
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
Consumer<CampaignImportProposal> onDone,
|
Consumer<CampaignImportProposal> onDone,
|
||||||
Consumer<Throwable> onError);
|
Consumer<Throwable> onError);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,4 +19,7 @@ public interface CharacterRepository {
|
|||||||
void deleteById(String id);
|
void deleteById(String id);
|
||||||
|
|
||||||
boolean existsById(String id);
|
boolean existsById(String id);
|
||||||
|
|
||||||
|
/** Recherche par nom (insensible à la casse) — alimente la recherche globale. */
|
||||||
|
List<Character> searchByName(String query);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Enemy;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie pour la persistance des fiches d'ennemis (bestiaire de campagne).
|
||||||
|
*/
|
||||||
|
public interface EnemyRepository {
|
||||||
|
|
||||||
|
Enemy save(Enemy enemy);
|
||||||
|
|
||||||
|
Optional<Enemy> findById(String id);
|
||||||
|
|
||||||
|
List<Enemy> findByCampaignId(String campaignId);
|
||||||
|
|
||||||
|
void deleteById(String id);
|
||||||
|
|
||||||
|
/** Recherche par nom (insensible à la casse) — alimente la recherche globale. */
|
||||||
|
List<Enemy> searchByName(String query);
|
||||||
|
}
|
||||||
@@ -19,4 +19,7 @@ public interface ItemCatalogRepository {
|
|||||||
void deleteById(String id);
|
void deleteById(String id);
|
||||||
|
|
||||||
boolean existsById(String id);
|
boolean existsById(String id);
|
||||||
|
|
||||||
|
/** Recherche par nom (insensible à la casse) — alimente la recherche globale. */
|
||||||
|
List<ItemCatalog> searchByName(String query);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,5 +28,10 @@ public interface NotebookRepository {
|
|||||||
|
|
||||||
// --- Messages (conversation) ---
|
// --- Messages (conversation) ---
|
||||||
NotebookMessage saveMessage(NotebookMessage message);
|
NotebookMessage saveMessage(NotebookMessage message);
|
||||||
|
/** Messages de la conversation ACTIVE (les archives sont exclues). */
|
||||||
List<NotebookMessage> findMessagesByNotebookId(String notebookId);
|
List<NotebookMessage> findMessagesByNotebookId(String notebookId);
|
||||||
|
/** « Vider » : archive le fil actif en un lot horodaté (rien n'est supprimé). */
|
||||||
|
void archiveMessagesByNotebookId(String notebookId);
|
||||||
|
/** Messages archivés, chronologiques (regroupables par {@code archivedAt}). */
|
||||||
|
List<NotebookMessage> findArchivedMessagesByNotebookId(String notebookId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,4 +19,7 @@ public interface NpcRepository {
|
|||||||
void deleteById(String id);
|
void deleteById(String id);
|
||||||
|
|
||||||
boolean existsById(String id);
|
boolean existsById(String id);
|
||||||
|
|
||||||
|
/** Recherche par nom (insensible à la casse) — alimente la recherche globale. */
|
||||||
|
List<Npc> searchByName(String query);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,4 +19,7 @@ public interface RandomTableRepository {
|
|||||||
void deleteById(String id);
|
void deleteById(String id);
|
||||||
|
|
||||||
boolean existsById(String id);
|
boolean existsById(String id);
|
||||||
|
|
||||||
|
/** Recherche par nom (insensible à la casse) — alimente la recherche globale. */
|
||||||
|
List<RandomTable> searchByName(String query);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,6 +50,14 @@ public class GameSystem {
|
|||||||
*/
|
*/
|
||||||
private List<TemplateField> npcTemplate;
|
private List<TemplateField> npcTemplate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Template de fiche ENNEMI (monstres/créatures du bestiaire de campagne).
|
||||||
|
* Mêmes règles que {@link #characterTemplate} — distinct du template PNJ :
|
||||||
|
* un ennemi porte des stats de combat (CA, PV, attaques…), pas une
|
||||||
|
* caractérisation narrative.
|
||||||
|
*/
|
||||||
|
private List<TemplateField> enemyTemplate;
|
||||||
|
|
||||||
/** Auteur déclaré — futur marketplace. Nullable. */
|
/** Auteur déclaré — futur marketplace. Nullable. */
|
||||||
private String author;
|
private String author;
|
||||||
|
|
||||||
@@ -98,6 +106,10 @@ public class GameSystem {
|
|||||||
npcTemplate = validateAndCopy(fields);
|
npcTemplate = validateAndCopy(fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void replaceEnemyTemplate(List<TemplateField> fields) {
|
||||||
|
enemyTemplate = validateAndCopy(fields);
|
||||||
|
}
|
||||||
|
|
||||||
// --- Helpers privés ----------------------------------------------------
|
// --- Helpers privés ----------------------------------------------------
|
||||||
|
|
||||||
private static List<TemplateField> appendField(List<TemplateField> current, TemplateField field) {
|
private static List<TemplateField> appendField(List<TemplateField> current, TemplateField field) {
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ public interface RulesPdfImporter {
|
|||||||
* @param onHeartbeat invoqué périodiquement pendant un appel LLM long (aucune
|
* @param onHeartbeat invoqué périodiquement pendant un appel LLM long (aucune
|
||||||
* avancée à afficher, mais le canal SSE vers le navigateur
|
* avancée à afficher, mais le canal SSE vers le navigateur
|
||||||
* doit rester actif — sinon un proxy intermédiaire le coupe).
|
* doit rester actif — sinon un proxy intermédiaire le coupe).
|
||||||
|
* @param onStatus invoqué avec un message lisible quand quelque chose se
|
||||||
|
* passe pendant l'attente (fournisseur saturé → retry,
|
||||||
|
* morceau re-découpé, morceau ignoré…) — affiché par l'UI
|
||||||
|
* pour que l'utilisateur n'ait pas à lire les logs.
|
||||||
* @param onDone invoqué une fois avec le résultat final.
|
* @param onDone invoqué une fois avec le résultat final.
|
||||||
* @param onError invoqué si l'extraction/structuration échoue.
|
* @param onError invoqué si l'extraction/structuration échoue.
|
||||||
*/
|
*/
|
||||||
@@ -38,6 +42,7 @@ public interface RulesPdfImporter {
|
|||||||
String filename,
|
String filename,
|
||||||
Consumer<RulesImportProgress> onProgress,
|
Consumer<RulesImportProgress> onProgress,
|
||||||
Runnable onHeartbeat,
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
Consumer<RulesImportResult> onDone,
|
Consumer<RulesImportResult> onDone,
|
||||||
Consumer<Throwable> onError);
|
Consumer<Throwable> onError);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,11 +52,15 @@ public record CampaignStructuralContext(
|
|||||||
/**
|
/**
|
||||||
* Résumé d'un arc : nom + description courte + ses chapitres.
|
* Résumé d'un arc : nom + description courte + ses chapitres.
|
||||||
*
|
*
|
||||||
|
* @param hub true si l'arc est de type HUB : ses chapitres sont des
|
||||||
|
* « quêtes » parallèles (vocabulaire UI). L'IA doit le savoir
|
||||||
|
* pour parler de quêtes et cibler le bon arc.
|
||||||
* @param illustrationCount Nombre d'illustrations attachees a cet arc (pour hint dans le prompt IA).
|
* @param illustrationCount Nombre d'illustrations attachees a cet arc (pour hint dans le prompt IA).
|
||||||
*/
|
*/
|
||||||
public record ArcSummary(
|
public record ArcSummary(
|
||||||
String name,
|
String name,
|
||||||
String description,
|
String description,
|
||||||
|
boolean hub,
|
||||||
int illustrationCount,
|
int illustrationCount,
|
||||||
List<ChapterSummary> chapters) {
|
List<ChapterSummary> chapters) {
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,20 @@ public class Page {
|
|||||||
*/
|
*/
|
||||||
private Map<String, List<String>> imageValues;
|
private Map<String, List<String>> imageValues;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valeurs des champs KEY_VALUE_LIST (tableau libelle → valeur, comme sur les
|
||||||
|
* fiches de personnage) : fieldName → (label → valeur). Les labels sont
|
||||||
|
* definis par le Template ; seules les valeurs vivent sur la page.
|
||||||
|
*/
|
||||||
|
private Map<String, Map<String, String>> keyValueValues;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valeurs des champs TABLE (colonnes figees au template, lignes libres) :
|
||||||
|
* fieldName → liste ordonnee de lignes, chaque ligne = colonne → cellule.
|
||||||
|
* Usage type : inventaire de boutique, table d'objets.
|
||||||
|
*/
|
||||||
|
private Map<String, List<Map<String, String>>> tableValues;
|
||||||
|
|
||||||
/** Notes privées du MJ (non exportées vers FoundryVTT). */
|
/** Notes privées du MJ (non exportées vers FoundryVTT). */
|
||||||
private String notes;
|
private String notes;
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,11 @@ package com.loremind.domain.shared.template;
|
|||||||
* - KEY_VALUE_LIST : liste de paires {label, value} avec labels figes au template
|
* - KEY_VALUE_LIST : liste de paires {label, value} avec labels figes au template
|
||||||
* (Map<String, Map<String, String>> : fieldName -> label -> value).
|
* (Map<String, Map<String, String>> : fieldName -> label -> value).
|
||||||
* Usage : stat blocks, listes de competences, traits.
|
* Usage : stat blocks, listes de competences, traits.
|
||||||
|
* - TABLE : tableau a colonnes figees au template (TemplateField.labels =
|
||||||
|
* noms de colonnes) et lignes LIBRES ajoutees au remplissage
|
||||||
|
* (Map<String, List<Map<String, String>>> : fieldName -> lignes,
|
||||||
|
* chaque ligne = colonne -> cellule).
|
||||||
|
* Usage : inventaire de boutique, tables d'objets, listes de prix.
|
||||||
* <p>
|
* <p>
|
||||||
* Extension future possible : RICH_TEXT, DATE, BOOLEAN, REFERENCE...
|
* Extension future possible : RICH_TEXT, DATE, BOOLEAN, REFERENCE...
|
||||||
*/
|
*/
|
||||||
@@ -16,5 +21,6 @@ public enum FieldType {
|
|||||||
TEXT,
|
TEXT,
|
||||||
IMAGE,
|
IMAGE,
|
||||||
NUMBER,
|
NUMBER,
|
||||||
KEY_VALUE_LIST
|
KEY_VALUE_LIST,
|
||||||
|
TABLE
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,8 +30,9 @@ public class TemplateField {
|
|||||||
/** Variante de rendu pour les champs IMAGE. Null = GALLERY. */
|
/** Variante de rendu pour les champs IMAGE. Null = GALLERY. */
|
||||||
private ImageLayout layout;
|
private ImageLayout layout;
|
||||||
/**
|
/**
|
||||||
* Labels predefinis pour les champs KEY_VALUE_LIST (ordre significatif).
|
* Labels predefinis (ordre significatif), selon le type :
|
||||||
* Ex: ["FOR","DEX","CON","INT","SAG","CHA"] pour un champ "Caracteristiques".
|
* - KEY_VALUE_LIST : libelles des lignes. Ex: ["FOR","DEX","CON","INT","SAG","CHA"].
|
||||||
|
* - TABLE : noms des COLONNES. Ex: ["Objet","Prix","Description"].
|
||||||
* Null/vide pour les autres types.
|
* Null/vide pour les autres types.
|
||||||
*/
|
*/
|
||||||
private List<String> labels;
|
private List<String> labels;
|
||||||
@@ -70,4 +71,9 @@ public class TemplateField {
|
|||||||
public static TemplateField keyValueList(String name, List<String> labels) {
|
public static TemplateField keyValueList(String name, List<String> labels) {
|
||||||
return new TemplateField(name, FieldType.KEY_VALUE_LIST, null, labels);
|
return new TemplateField(name, FieldType.KEY_VALUE_LIST, null, labels);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Raccourci : construit un champ TABLE avec ses noms de colonnes. */
|
||||||
|
public static TemplateField table(String name, List<String> columns) {
|
||||||
|
return new TemplateField(name, FieldType.TABLE, null, columns);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
String filename,
|
String filename,
|
||||||
Consumer<CampaignImportProgress> onProgress,
|
Consumer<CampaignImportProgress> onProgress,
|
||||||
Runnable onHeartbeat,
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
Consumer<CampaignImportProposal> onDone,
|
Consumer<CampaignImportProposal> onDone,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
|
|
||||||
@@ -85,7 +86,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
.timeout(Duration.ofSeconds(importTimeoutSeconds))
|
.timeout(Duration.ofSeconds(importTimeoutSeconds))
|
||||||
.doOnNext(sse -> handleEvent(
|
.doOnNext(sse -> handleEvent(
|
||||||
sse, pageCount, ocrPageCount, terminated,
|
sse, pageCount, ocrPageCount, terminated,
|
||||||
onProgress, onHeartbeat, onDone, onError))
|
onProgress, onHeartbeat, onStatus, onDone, onError))
|
||||||
.blockLast();
|
.blockLast();
|
||||||
if (!terminated[0]) {
|
if (!terminated[0]) {
|
||||||
onError.accept(new CampaignImportException(
|
onError.accept(new CampaignImportException(
|
||||||
@@ -110,6 +111,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
boolean[] terminated,
|
boolean[] terminated,
|
||||||
Consumer<CampaignImportProgress> onProgress,
|
Consumer<CampaignImportProgress> onProgress,
|
||||||
Runnable onHeartbeat,
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
Consumer<CampaignImportProposal> onDone,
|
Consumer<CampaignImportProposal> onDone,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
|
|
||||||
@@ -122,6 +124,22 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
onHeartbeat.run();
|
onHeartbeat.run();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if ("status".equals(event)) {
|
||||||
|
// Message d'attente lisible (retry sur fournisseur saturé, morceau
|
||||||
|
// re-découpé…) : affiché par l'UI au lieu de n'exister qu'en logs.
|
||||||
|
onStatus.accept(readMessage(data));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("chunk_failed".equals(event)) {
|
||||||
|
JsonNode node = readJson(data);
|
||||||
|
String msg = node != null && node.hasNonNull("message")
|
||||||
|
? node.get("message").asText() : "";
|
||||||
|
int current = node != null ? node.path("current").asInt() : 0;
|
||||||
|
int total = node != null ? node.path("total").asInt() : 0;
|
||||||
|
onStatus.accept("Morceau " + current + "/" + total + " ignoré"
|
||||||
|
+ (msg.isEmpty() ? "." : " : " + msg));
|
||||||
|
return;
|
||||||
|
}
|
||||||
if ("error".equals(event)) {
|
if ("error".equals(event)) {
|
||||||
terminated[0] = true;
|
terminated[0] = true;
|
||||||
onError.accept(new CampaignImportException(
|
onError.accept(new CampaignImportException(
|
||||||
|
|||||||
@@ -252,9 +252,15 @@ public class BrainChatPayloadBuilder {
|
|||||||
ArcSummary::name,
|
ArcSummary::name,
|
||||||
ArcSummary::description,
|
ArcSummary::description,
|
||||||
ArcSummary::illustrationCount,
|
ArcSummary::illustrationCount,
|
||||||
(map, arc) -> map.put("chapters", arc.chapters().stream()
|
(map, arc) -> {
|
||||||
|
// Vocabulaire UI : les chapitres d'un arc HUB sont des « quêtes ».
|
||||||
|
if (arc.hub()) {
|
||||||
|
map.put("arc_type", "HUB");
|
||||||
|
}
|
||||||
|
map.put("chapters", arc.chapters().stream()
|
||||||
.map(this::chapterSummaryToMap)
|
.map(this::chapterSummaryToMap)
|
||||||
.collect(Collectors.toList())));
|
.collect(Collectors.toList()));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> chapterSummaryToMap(ChapterSummary c) {
|
private Map<String, Object> chapterSummaryToMap(ChapterSummary c) {
|
||||||
|
|||||||
@@ -115,6 +115,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
String filename,
|
String filename,
|
||||||
Consumer<RulesImportProgress> onProgress,
|
Consumer<RulesImportProgress> onProgress,
|
||||||
Runnable onHeartbeat,
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
Consumer<RulesImportResult> onDone,
|
Consumer<RulesImportResult> onDone,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
|
|
||||||
@@ -141,7 +142,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
.timeout(Duration.ofSeconds(importTimeoutSeconds))
|
.timeout(Duration.ofSeconds(importTimeoutSeconds))
|
||||||
.doOnNext(sse -> handleEvent(
|
.doOnNext(sse -> handleEvent(
|
||||||
sse, pageCount, ocrPageCount, terminated,
|
sse, pageCount, ocrPageCount, terminated,
|
||||||
onProgress, onHeartbeat, onDone, onError))
|
onProgress, onHeartbeat, onStatus, onDone, onError))
|
||||||
.blockLast();
|
.blockLast();
|
||||||
// Flux terminé sans event done/error (ex: connexion coupée) → on signale.
|
// Flux terminé sans event done/error (ex: connexion coupée) → on signale.
|
||||||
if (!terminated[0]) {
|
if (!terminated[0]) {
|
||||||
@@ -168,6 +169,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
boolean[] terminated,
|
boolean[] terminated,
|
||||||
Consumer<RulesImportProgress> onProgress,
|
Consumer<RulesImportProgress> onProgress,
|
||||||
Runnable onHeartbeat,
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
Consumer<RulesImportResult> onDone,
|
Consumer<RulesImportResult> onDone,
|
||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
|
|
||||||
@@ -181,6 +183,22 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
onHeartbeat.run();
|
onHeartbeat.run();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if ("status".equals(event)) {
|
||||||
|
// Message d'attente lisible (retry sur fournisseur saturé, morceau
|
||||||
|
// re-découpé…) : affiché par l'UI au lieu de n'exister qu'en logs.
|
||||||
|
onStatus.accept(readMessage(data));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("chunk_failed".equals(event)) {
|
||||||
|
JsonNode node = readJson(data);
|
||||||
|
String msg = node != null && node.hasNonNull("message")
|
||||||
|
? node.get("message").asText() : "";
|
||||||
|
int current = node != null ? node.path("current").asInt() : 0;
|
||||||
|
int total = node != null ? node.path("total").asInt() : 0;
|
||||||
|
onStatus.accept("Morceau " + current + "/" + total + " ignoré"
|
||||||
|
+ (msg.isEmpty() ? "." : " : " + msg));
|
||||||
|
return;
|
||||||
|
}
|
||||||
if ("error".equals(event)) {
|
if ("error".equals(event)) {
|
||||||
terminated[0] = true;
|
terminated[0] = true;
|
||||||
onError.accept(new RulesImportException(
|
onError.accept(new RulesImportException(
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.converter;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import jakarta.persistence.AttributeConverter;
|
||||||
|
import jakarta.persistence.Converter;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convertit une Map<String, List<Map<String, String>>> en JSON et inversement.
|
||||||
|
* <p>
|
||||||
|
* Utilise pour Page.tableValues : pour chaque champ TABLE du template, stocke
|
||||||
|
* la liste ordonnee des LIGNES du tableau, chaque ligne etant une map
|
||||||
|
* colonne -> cellule. Exemple :
|
||||||
|
* {"Inventaire": [{"Objet":"Potion","Prix":"50 po"}, {"Objet":"Corde","Prix":"1 po"}]}
|
||||||
|
* <p>
|
||||||
|
* Adaptateur technique pur : le domaine ignore ce converter.
|
||||||
|
*/
|
||||||
|
@Converter
|
||||||
|
public class StringRowListMapJsonConverter
|
||||||
|
implements AttributeConverter<Map<String, List<Map<String, String>>>, String> {
|
||||||
|
|
||||||
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||||
|
private static final TypeReference<Map<String, List<Map<String, String>>>> TYPE_REF =
|
||||||
|
new TypeReference<>() {};
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String convertToDatabaseColumn(Map<String, List<Map<String, String>>> attribute) {
|
||||||
|
if (attribute == null || attribute.isEmpty()) return "{}";
|
||||||
|
try {
|
||||||
|
return MAPPER.writeValueAsString(attribute);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"Erreur serialisation Map<String, List<Map<String,String>>> -> JSON", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, List<Map<String, String>>> convertToEntityAttribute(String dbData) {
|
||||||
|
if (dbData == null || dbData.isBlank()) return Collections.emptyMap();
|
||||||
|
try {
|
||||||
|
return MAPPER.readValue(dbData, TYPE_REF);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"Erreur deserialisation JSON -> Map<String, List<Map<String,String>>>", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -86,7 +86,7 @@ public class TemplateFieldListJsonConverter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
List<String> labels = null;
|
List<String> labels = null;
|
||||||
if (type == FieldType.KEY_VALUE_LIST) {
|
if (type == FieldType.KEY_VALUE_LIST || type == FieldType.TABLE) {
|
||||||
JsonNode labelsNode = item.path("labels");
|
JsonNode labelsNode = item.path("labels");
|
||||||
if (labelsNode.isArray()) {
|
if (labelsNode.isArray()) {
|
||||||
labels = new ArrayList<>();
|
labels = new ArrayList<>();
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringListMapJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapMapJsonConverter;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entité JPA des fiches d'ennemis (bestiaire). Mêmes règles que NpcJpaEntity.
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "enemies", indexes = {
|
||||||
|
@Index(name = "idx_enemies_campaign_id", columnList = "campaign_id")
|
||||||
|
})
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class EnemyJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** Niveau / FP — texte libre. Nullable. */
|
||||||
|
@Column(name = "level")
|
||||||
|
private String level;
|
||||||
|
|
||||||
|
/** Dossier de classement (« Démons », « Humanoïdes »…). Nullable = non classé. */
|
||||||
|
@Column(name = "folder")
|
||||||
|
private String folder;
|
||||||
|
|
||||||
|
@Column(name = "portrait_image_id")
|
||||||
|
private String portraitImageId;
|
||||||
|
|
||||||
|
@Column(name = "header_image_id")
|
||||||
|
private String headerImageId;
|
||||||
|
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Column(name = "field_values", columnDefinition = "TEXT")
|
||||||
|
private Map<String, String> values;
|
||||||
|
|
||||||
|
@Convert(converter = StringListMapJsonConverter.class)
|
||||||
|
@Column(name = "image_values", columnDefinition = "TEXT")
|
||||||
|
private Map<String, List<String>> imageValues;
|
||||||
|
|
||||||
|
@Convert(converter = StringMapMapJsonConverter.class)
|
||||||
|
@Column(name = "key_value_values", columnDefinition = "TEXT")
|
||||||
|
private Map<String, Map<String, String>> keyValueValues;
|
||||||
|
|
||||||
|
@Column(name = "campaign_id", nullable = false)
|
||||||
|
private Long campaignId;
|
||||||
|
|
||||||
|
@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();
|
||||||
|
if (values == null) values = new HashMap<>();
|
||||||
|
if (imageValues == null) imageValues = new HashMap<>();
|
||||||
|
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -46,6 +46,11 @@ public class GameSystemJpaEntity {
|
|||||||
@Column(name = "npc_template", columnDefinition = "TEXT")
|
@Column(name = "npc_template", columnDefinition = "TEXT")
|
||||||
private List<TemplateField> npcTemplate;
|
private List<TemplateField> npcTemplate;
|
||||||
|
|
||||||
|
/** Template ENNEMI (bestiaire) serialise en JSON. */
|
||||||
|
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||||
|
@Column(name = "enemy_template", columnDefinition = "TEXT")
|
||||||
|
private List<TemplateField> enemyTemplate;
|
||||||
|
|
||||||
@Column
|
@Column
|
||||||
private String author;
|
private String author;
|
||||||
|
|
||||||
@@ -64,6 +69,7 @@ public class GameSystemJpaEntity {
|
|||||||
updatedAt = LocalDateTime.now();
|
updatedAt = LocalDateTime.now();
|
||||||
if (characterTemplate == null) characterTemplate = new ArrayList<>();
|
if (characterTemplate == null) characterTemplate = new ArrayList<>();
|
||||||
if (npcTemplate == null) npcTemplate = new ArrayList<>();
|
if (npcTemplate == null) npcTemplate = new ArrayList<>();
|
||||||
|
if (enemyTemplate == null) enemyTemplate = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreUpdate
|
@PreUpdate
|
||||||
|
|||||||
@@ -34,6 +34,14 @@ public class NotebookMessageJpaEntity {
|
|||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Null = message de la conversation ACTIVE. Non-null = message archivé lors
|
||||||
|
* d'un « vider la conversation » ; tous les messages d'un même clear portent
|
||||||
|
* le même horodatage, qui sert d'identifiant de lot d'archive.
|
||||||
|
*/
|
||||||
|
@Column(name = "archived_at")
|
||||||
|
private LocalDateTime archivedAt;
|
||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
if (createdAt == null) createdAt = LocalDateTime.now();
|
if (createdAt == null) createdAt = LocalDateTime.now();
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.infrastructure.persistence.entity;
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListMapJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListMapJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringMapMapJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringMapMapJsonConverter;
|
||||||
@@ -54,6 +55,11 @@ public class NpcJpaEntity {
|
|||||||
@Column(name = "campaign_id", nullable = false)
|
@Column(name = "campaign_id", nullable = false)
|
||||||
private Long campaignId;
|
private Long campaignId;
|
||||||
|
|
||||||
|
/** IDs de Pages de Lore référencées (référence faible cross-context). JSON TEXT. */
|
||||||
|
@Convert(converter = StringListJsonConverter.class)
|
||||||
|
@Column(name = "related_page_ids", columnDefinition = "TEXT")
|
||||||
|
private List<String> relatedPageIds;
|
||||||
|
|
||||||
@Column(name = "folder")
|
@Column(name = "folder")
|
||||||
private String folder;
|
private String folder;
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package com.loremind.infrastructure.persistence.entity;
|
|||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListMapJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListMapJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapMapJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringRowListMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -52,6 +54,16 @@ public class PageJpaEntity {
|
|||||||
@Convert(converter = StringListMapJsonConverter.class)
|
@Convert(converter = StringListMapJsonConverter.class)
|
||||||
private Map<String, List<String>> imageValues;
|
private Map<String, List<String>> imageValues;
|
||||||
|
|
||||||
|
/** Valeurs des champs KEY_VALUE_LIST : fieldName → (label → valeur). JSON TEXT. */
|
||||||
|
@Column(name = "key_value_values", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapMapJsonConverter.class)
|
||||||
|
private Map<String, Map<String, String>> keyValueValues;
|
||||||
|
|
||||||
|
/** Valeurs des champs TABLE : fieldName → lignes (colonne → cellule). JSON TEXT. */
|
||||||
|
@Column(name = "table_values", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringRowListMapJsonConverter.class)
|
||||||
|
private Map<String, List<Map<String, String>>> tableValues;
|
||||||
|
|
||||||
@Column(columnDefinition = "TEXT")
|
@Column(columnDefinition = "TEXT")
|
||||||
private String notes;
|
private String notes;
|
||||||
|
|
||||||
|
|||||||
@@ -75,6 +75,12 @@ public class SceneJpaEntity {
|
|||||||
@Column(columnDefinition = "TEXT")
|
@Column(columnDefinition = "TEXT")
|
||||||
private String enemies;
|
private String enemies;
|
||||||
|
|
||||||
|
/** IDs des fiches du bestiaire liées à la rencontre (JSON, weak refs). */
|
||||||
|
@Column(name = "enemy_ids", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringListJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private List<String> enemyIds = new ArrayList<>();
|
||||||
|
|
||||||
@Column(name = "related_page_ids", columnDefinition = "TEXT")
|
@Column(name = "related_page_ids", columnDefinition = "TEXT")
|
||||||
@Convert(converter = StringListJsonConverter.class)
|
@Convert(converter = StringListJsonConverter.class)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
|
|||||||
@@ -10,4 +10,7 @@ import java.util.List;
|
|||||||
public interface CharacterJpaRepository extends JpaRepository<CharacterJpaEntity, Long> {
|
public interface CharacterJpaRepository extends JpaRepository<CharacterJpaEntity, Long> {
|
||||||
|
|
||||||
List<CharacterJpaEntity> findByPlaythroughIdOrderByOrderAsc(Long playthroughId);
|
List<CharacterJpaEntity> findByPlaythroughIdOrderByOrderAsc(Long playthroughId);
|
||||||
|
|
||||||
|
/** Recherche globale : bornée pour ne jamais inonder la palette de résultats. */
|
||||||
|
List<CharacterJpaEntity> findTop20ByNameContainingIgnoreCaseOrderByNameAsc(String name);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.EnemyJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface EnemyJpaRepository extends JpaRepository<EnemyJpaEntity, Long> {
|
||||||
|
|
||||||
|
List<EnemyJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
||||||
|
|
||||||
|
/** Recherche globale : bornée pour ne jamais inonder la palette de résultats. */
|
||||||
|
List<EnemyJpaEntity> findTop20ByNameContainingIgnoreCaseOrderByNameAsc(String name);
|
||||||
|
}
|
||||||
@@ -10,4 +10,7 @@ import java.util.List;
|
|||||||
public interface ItemCatalogJpaRepository extends JpaRepository<ItemCatalogJpaEntity, Long> {
|
public interface ItemCatalogJpaRepository extends JpaRepository<ItemCatalogJpaEntity, Long> {
|
||||||
|
|
||||||
List<ItemCatalogJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
List<ItemCatalogJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
||||||
|
|
||||||
|
/** Recherche globale : bornée pour ne jamais inonder la palette de résultats. */
|
||||||
|
List<ItemCatalogJpaEntity> findTop20ByNameContainingIgnoreCaseOrderByNameAsc(String name);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,27 @@ package com.loremind.infrastructure.persistence.jpa;
|
|||||||
|
|
||||||
import com.loremind.infrastructure.persistence.entity.NotebookMessageJpaEntity;
|
import com.loremind.infrastructure.persistence.entity.NotebookMessageJpaEntity;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Modifying;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface NotebookMessageJpaRepository extends JpaRepository<NotebookMessageJpaEntity, Long> {
|
public interface NotebookMessageJpaRepository extends JpaRepository<NotebookMessageJpaEntity, Long> {
|
||||||
List<NotebookMessageJpaEntity> findByNotebookIdOrderByCreatedAtAsc(Long notebookId);
|
/** Messages de la conversation ACTIVE (les archives sont exclues). */
|
||||||
|
List<NotebookMessageJpaEntity> findByNotebookIdAndArchivedAtIsNullOrderByCreatedAtAsc(Long notebookId);
|
||||||
|
|
||||||
|
/** Messages archivés (tous lots confondus, l'appelant regroupe par archivedAt). */
|
||||||
|
List<NotebookMessageJpaEntity> findByNotebookIdAndArchivedAtIsNotNullOrderByCreatedAtAsc(Long notebookId);
|
||||||
|
|
||||||
void deleteByNotebookId(Long notebookId);
|
void deleteByNotebookId(Long notebookId);
|
||||||
|
|
||||||
|
/** « Vider la conversation » : archive le fil actif en un lot horodaté. */
|
||||||
|
@Modifying
|
||||||
|
@Query("update NotebookMessageJpaEntity m set m.archivedAt = :now "
|
||||||
|
+ "where m.notebookId = :notebookId and m.archivedAt is null")
|
||||||
|
int archiveActiveMessages(@Param("notebookId") Long notebookId, @Param("now") LocalDateTime now);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,4 +10,7 @@ import java.util.List;
|
|||||||
public interface NpcJpaRepository extends JpaRepository<NpcJpaEntity, Long> {
|
public interface NpcJpaRepository extends JpaRepository<NpcJpaEntity, Long> {
|
||||||
|
|
||||||
List<NpcJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
List<NpcJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
||||||
|
|
||||||
|
/** Recherche globale : bornée pour ne jamais inonder la palette de résultats. */
|
||||||
|
List<NpcJpaEntity> findTop20ByNameContainingIgnoreCaseOrderByNameAsc(String name);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,4 +10,7 @@ import java.util.List;
|
|||||||
public interface RandomTableJpaRepository extends JpaRepository<RandomTableJpaEntity, Long> {
|
public interface RandomTableJpaRepository extends JpaRepository<RandomTableJpaEntity, Long> {
|
||||||
|
|
||||||
List<RandomTableJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
List<RandomTableJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
||||||
|
|
||||||
|
/** Recherche globale : bornée pour ne jamais inonder la palette de résultats. */
|
||||||
|
List<RandomTableJpaEntity> findTop20ByNameContainingIgnoreCaseOrderByNameAsc(String name);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,13 @@ public class PostgresCharacterRepository implements CharacterRepository {
|
|||||||
return jpaRepository.existsById(Long.parseLong(id));
|
return jpaRepository.existsById(Long.parseLong(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Character> searchByName(String query) {
|
||||||
|
return jpaRepository.findTop20ByNameContainingIgnoreCaseOrderByNameAsc(query).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
private Character toDomainEntity(CharacterJpaEntity e) {
|
private Character toDomainEntity(CharacterJpaEntity e) {
|
||||||
return Character.builder()
|
return Character.builder()
|
||||||
.id(e.getId().toString())
|
.id(e.getId().toString())
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Enemy;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.EnemyJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.EnemyJpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class PostgresEnemyRepository implements EnemyRepository {
|
||||||
|
|
||||||
|
private final EnemyJpaRepository jpaRepository;
|
||||||
|
|
||||||
|
public PostgresEnemyRepository(EnemyJpaRepository jpaRepository) {
|
||||||
|
this.jpaRepository = jpaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Enemy save(Enemy enemy) {
|
||||||
|
return toDomainEntity(jpaRepository.save(toJpaEntity(enemy)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<Enemy> findById(String id) {
|
||||||
|
return jpaRepository.findById(Long.parseLong(id)).map(this::toDomainEntity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Enemy> 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 List<Enemy> searchByName(String query) {
|
||||||
|
return jpaRepository.findTop20ByNameContainingIgnoreCaseOrderByNameAsc(query).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Enemy toDomainEntity(EnemyJpaEntity e) {
|
||||||
|
return Enemy.builder()
|
||||||
|
.id(e.getId().toString())
|
||||||
|
.name(e.getName())
|
||||||
|
.level(e.getLevel())
|
||||||
|
.folder(e.getFolder())
|
||||||
|
.portraitImageId(e.getPortraitImageId())
|
||||||
|
.headerImageId(e.getHeaderImageId())
|
||||||
|
.values(e.getValues() != null ? new HashMap<>(e.getValues()) : new HashMap<>())
|
||||||
|
.imageValues(e.getImageValues() != null ? new HashMap<>(e.getImageValues()) : new HashMap<>())
|
||||||
|
.keyValueValues(e.getKeyValueValues() != null ? new HashMap<>(e.getKeyValueValues()) : new HashMap<>())
|
||||||
|
.campaignId(e.getCampaignId().toString())
|
||||||
|
.order(e.getOrder())
|
||||||
|
.createdAt(e.getCreatedAt())
|
||||||
|
.updatedAt(e.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private EnemyJpaEntity toJpaEntity(Enemy n) {
|
||||||
|
return EnemyJpaEntity.builder()
|
||||||
|
.id(n.getId() != null ? Long.parseLong(n.getId()) : null)
|
||||||
|
.name(n.getName())
|
||||||
|
.level(n.getLevel())
|
||||||
|
.folder(n.getFolder())
|
||||||
|
.portraitImageId(n.getPortraitImageId())
|
||||||
|
.headerImageId(n.getHeaderImageId())
|
||||||
|
.values(n.getValues() != null ? new HashMap<>(n.getValues()) : new HashMap<>())
|
||||||
|
.imageValues(n.getImageValues() != null ? new HashMap<>(n.getImageValues()) : new HashMap<>())
|
||||||
|
.keyValueValues(n.getKeyValueValues() != null ? new HashMap<>(n.getKeyValueValues()) : new HashMap<>())
|
||||||
|
.campaignId(Long.parseLong(n.getCampaignId()))
|
||||||
|
.order(n.getOrder())
|
||||||
|
.createdAt(n.getCreatedAt())
|
||||||
|
.updatedAt(n.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -67,6 +67,9 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.npcTemplate(e.getNpcTemplate() != null
|
.npcTemplate(e.getNpcTemplate() != null
|
||||||
? new java.util.ArrayList<>(e.getNpcTemplate())
|
? new java.util.ArrayList<>(e.getNpcTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
|
.enemyTemplate(e.getEnemyTemplate() != null
|
||||||
|
? new java.util.ArrayList<>(e.getEnemyTemplate())
|
||||||
|
: new java.util.ArrayList<>())
|
||||||
.author(e.getAuthor())
|
.author(e.getAuthor())
|
||||||
.isPublic(e.isPublic())
|
.isPublic(e.isPublic())
|
||||||
.createdAt(e.getCreatedAt())
|
.createdAt(e.getCreatedAt())
|
||||||
@@ -87,6 +90,9 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.npcTemplate(g.getNpcTemplate() != null
|
.npcTemplate(g.getNpcTemplate() != null
|
||||||
? new java.util.ArrayList<>(g.getNpcTemplate())
|
? new java.util.ArrayList<>(g.getNpcTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
|
.enemyTemplate(g.getEnemyTemplate() != null
|
||||||
|
? new java.util.ArrayList<>(g.getEnemyTemplate())
|
||||||
|
: new java.util.ArrayList<>())
|
||||||
.author(g.getAuthor())
|
.author(g.getAuthor())
|
||||||
.isPublic(g.isPublic())
|
.isPublic(g.isPublic())
|
||||||
.createdAt(g.getCreatedAt())
|
.createdAt(g.getCreatedAt())
|
||||||
|
|||||||
@@ -77,6 +77,14 @@ public class PostgresItemCatalogRepository implements ItemCatalogRepository {
|
|||||||
return jpaRepository.existsById(Long.parseLong(id));
|
return jpaRepository.existsById(Long.parseLong(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<ItemCatalog> searchByName(String query) {
|
||||||
|
return jpaRepository.findTop20ByNameContainingIgnoreCaseOrderByNameAsc(query).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
private ItemCatalog toDomainEntity(ItemCatalogJpaEntity e) {
|
private ItemCatalog toDomainEntity(ItemCatalogJpaEntity e) {
|
||||||
List<CatalogItem> items = e.getItems().stream()
|
List<CatalogItem> items = e.getItems().stream()
|
||||||
.map(c -> CatalogItem.builder()
|
.map(c -> CatalogItem.builder()
|
||||||
|
|||||||
@@ -115,7 +115,19 @@ public class PostgresNotebookRepository implements NotebookRepository {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<NotebookMessage> findMessagesByNotebookId(String notebookId) {
|
public List<NotebookMessage> findMessagesByNotebookId(String notebookId) {
|
||||||
return messageJpa.findByNotebookIdOrderByCreatedAtAsc(Long.parseLong(notebookId)).stream()
|
return messageJpa.findByNotebookIdAndArchivedAtIsNullOrderByCreatedAtAsc(Long.parseLong(notebookId)).stream()
|
||||||
|
.map(this::toMessage).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public void archiveMessagesByNotebookId(String notebookId) {
|
||||||
|
messageJpa.archiveActiveMessages(Long.parseLong(notebookId), java.time.LocalDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<NotebookMessage> findArchivedMessagesByNotebookId(String notebookId) {
|
||||||
|
return messageJpa.findByNotebookIdAndArchivedAtIsNotNullOrderByCreatedAtAsc(Long.parseLong(notebookId)).stream()
|
||||||
.map(this::toMessage).collect(Collectors.toList());
|
.map(this::toMessage).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,6 +162,7 @@ public class PostgresNotebookRepository implements NotebookRepository {
|
|||||||
.role(e.getRole())
|
.role(e.getRole())
|
||||||
.content(e.getContent())
|
.content(e.getContent())
|
||||||
.createdAt(e.getCreatedAt())
|
.createdAt(e.getCreatedAt())
|
||||||
|
.archivedAt(e.getArchivedAt())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import com.loremind.infrastructure.persistence.entity.NpcJpaEntity;
|
|||||||
import com.loremind.infrastructure.persistence.jpa.NpcJpaRepository;
|
import com.loremind.infrastructure.persistence.jpa.NpcJpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -49,6 +50,13 @@ public class PostgresNpcRepository implements NpcRepository {
|
|||||||
return jpaRepository.existsById(Long.parseLong(id));
|
return jpaRepository.existsById(Long.parseLong(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Npc> searchByName(String query) {
|
||||||
|
return jpaRepository.findTop20ByNameContainingIgnoreCaseOrderByNameAsc(query).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
private Npc toDomainEntity(NpcJpaEntity e) {
|
private Npc toDomainEntity(NpcJpaEntity e) {
|
||||||
return Npc.builder()
|
return Npc.builder()
|
||||||
.id(e.getId().toString())
|
.id(e.getId().toString())
|
||||||
@@ -59,6 +67,7 @@ public class PostgresNpcRepository implements NpcRepository {
|
|||||||
.imageValues(e.getImageValues() != null ? new HashMap<>(e.getImageValues()) : new HashMap<>())
|
.imageValues(e.getImageValues() != null ? new HashMap<>(e.getImageValues()) : new HashMap<>())
|
||||||
.keyValueValues(e.getKeyValueValues() != null ? new HashMap<>(e.getKeyValueValues()) : new HashMap<>())
|
.keyValueValues(e.getKeyValueValues() != null ? new HashMap<>(e.getKeyValueValues()) : new HashMap<>())
|
||||||
.campaignId(e.getCampaignId().toString())
|
.campaignId(e.getCampaignId().toString())
|
||||||
|
.relatedPageIds(e.getRelatedPageIds() != null ? new ArrayList<>(e.getRelatedPageIds()) : new ArrayList<>())
|
||||||
.folder(e.getFolder())
|
.folder(e.getFolder())
|
||||||
.order(e.getOrder())
|
.order(e.getOrder())
|
||||||
.createdAt(e.getCreatedAt())
|
.createdAt(e.getCreatedAt())
|
||||||
@@ -77,6 +86,7 @@ public class PostgresNpcRepository implements NpcRepository {
|
|||||||
.imageValues(n.getImageValues() != null ? new HashMap<>(n.getImageValues()) : new HashMap<>())
|
.imageValues(n.getImageValues() != null ? new HashMap<>(n.getImageValues()) : new HashMap<>())
|
||||||
.keyValueValues(n.getKeyValueValues() != null ? new HashMap<>(n.getKeyValueValues()) : new HashMap<>())
|
.keyValueValues(n.getKeyValueValues() != null ? new HashMap<>(n.getKeyValueValues()) : new HashMap<>())
|
||||||
.campaignId(Long.parseLong(n.getCampaignId()))
|
.campaignId(Long.parseLong(n.getCampaignId()))
|
||||||
|
.relatedPageIds(n.getRelatedPageIds() != null ? new ArrayList<>(n.getRelatedPageIds()) : new ArrayList<>())
|
||||||
.folder(n.getFolder())
|
.folder(n.getFolder())
|
||||||
.order(n.getOrder())
|
.order(n.getOrder())
|
||||||
.createdAt(n.getCreatedAt())
|
.createdAt(n.getCreatedAt())
|
||||||
|
|||||||
@@ -93,6 +93,8 @@ public class PostgresPageRepository implements PageRepository {
|
|||||||
.title(e.getTitle())
|
.title(e.getTitle())
|
||||||
.values(e.getValues() != null ? new HashMap<>(e.getValues()) : new HashMap<>())
|
.values(e.getValues() != null ? new HashMap<>(e.getValues()) : new HashMap<>())
|
||||||
.imageValues(e.getImageValues() != null ? new HashMap<>(e.getImageValues()) : new HashMap<>())
|
.imageValues(e.getImageValues() != null ? new HashMap<>(e.getImageValues()) : new HashMap<>())
|
||||||
|
.keyValueValues(e.getKeyValueValues() != null ? new HashMap<>(e.getKeyValueValues()) : new HashMap<>())
|
||||||
|
.tableValues(e.getTableValues() != null ? new HashMap<>(e.getTableValues()) : new HashMap<>())
|
||||||
.notes(e.getNotes())
|
.notes(e.getNotes())
|
||||||
.tags(e.getTags() != null ? new ArrayList<>(e.getTags()) : new ArrayList<>())
|
.tags(e.getTags() != null ? new ArrayList<>(e.getTags()) : new ArrayList<>())
|
||||||
.relatedPageIds(e.getRelatedPageIds() != null ? new ArrayList<>(e.getRelatedPageIds()) : new ArrayList<>())
|
.relatedPageIds(e.getRelatedPageIds() != null ? new ArrayList<>(e.getRelatedPageIds()) : new ArrayList<>())
|
||||||
@@ -111,6 +113,8 @@ public class PostgresPageRepository implements PageRepository {
|
|||||||
.title(p.getTitle())
|
.title(p.getTitle())
|
||||||
.values(p.getValues() != null ? new HashMap<>(p.getValues()) : new HashMap<>())
|
.values(p.getValues() != null ? new HashMap<>(p.getValues()) : new HashMap<>())
|
||||||
.imageValues(p.getImageValues() != null ? new HashMap<>(p.getImageValues()) : new HashMap<>())
|
.imageValues(p.getImageValues() != null ? new HashMap<>(p.getImageValues()) : new HashMap<>())
|
||||||
|
.keyValueValues(p.getKeyValueValues() != null ? new HashMap<>(p.getKeyValueValues()) : new HashMap<>())
|
||||||
|
.tableValues(p.getTableValues() != null ? new HashMap<>(p.getTableValues()) : new HashMap<>())
|
||||||
.notes(p.getNotes())
|
.notes(p.getNotes())
|
||||||
.tags(p.getTags() != null ? new ArrayList<>(p.getTags()) : new ArrayList<>())
|
.tags(p.getTags() != null ? new ArrayList<>(p.getTags()) : new ArrayList<>())
|
||||||
.relatedPageIds(p.getRelatedPageIds() != null ? new ArrayList<>(p.getRelatedPageIds()) : new ArrayList<>())
|
.relatedPageIds(p.getRelatedPageIds() != null ? new ArrayList<>(p.getRelatedPageIds()) : new ArrayList<>())
|
||||||
|
|||||||
@@ -81,6 +81,14 @@ public class PostgresRandomTableRepository implements RandomTableRepository {
|
|||||||
return jpaRepository.existsById(Long.parseLong(id));
|
return jpaRepository.existsById(Long.parseLong(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<RandomTable> searchByName(String query) {
|
||||||
|
return jpaRepository.findTop20ByNameContainingIgnoreCaseOrderByNameAsc(query).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
private RandomTable toDomainEntity(RandomTableJpaEntity e) {
|
private RandomTable toDomainEntity(RandomTableJpaEntity e) {
|
||||||
List<RandomTableEntry> entries = e.getEntries().stream()
|
List<RandomTableEntry> entries = e.getEntries().stream()
|
||||||
.map(c -> RandomTableEntry.builder()
|
.map(c -> RandomTableEntry.builder()
|
||||||
|
|||||||
@@ -80,6 +80,9 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.choicesConsequences(jpaEntity.getChoicesConsequences())
|
.choicesConsequences(jpaEntity.getChoicesConsequences())
|
||||||
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
||||||
.enemies(jpaEntity.getEnemies())
|
.enemies(jpaEntity.getEnemies())
|
||||||
|
.enemyIds(jpaEntity.getEnemyIds() != null
|
||||||
|
? new ArrayList<>(jpaEntity.getEnemyIds())
|
||||||
|
: new ArrayList<>())
|
||||||
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
@@ -117,6 +120,9 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.choicesConsequences(scene.getChoicesConsequences())
|
.choicesConsequences(scene.getChoicesConsequences())
|
||||||
.combatDifficulty(scene.getCombatDifficulty())
|
.combatDifficulty(scene.getCombatDifficulty())
|
||||||
.enemies(scene.getEnemies())
|
.enemies(scene.getEnemies())
|
||||||
|
.enemyIds(scene.getEnemyIds() != null
|
||||||
|
? new ArrayList<>(scene.getEnemyIds())
|
||||||
|
: new ArrayList<>())
|
||||||
.relatedPageIds(scene.getRelatedPageIds() != null
|
.relatedPageIds(scene.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(scene.getRelatedPageIds())
|
? new ArrayList<>(scene.getRelatedPageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import org.springframework.web.bind.MethodArgumentNotValidException;
|
|||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
import org.springframework.web.context.request.async.AsyncRequestNotUsableException;
|
import org.springframework.web.context.request.async.AsyncRequestNotUsableException;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -71,6 +72,21 @@ public class GlobalExceptionHandler {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Statut HTTP explicitement choisi par un controller via {@link ResponseStatusException}
|
||||||
|
* (ex: {@code NotebookController} -> 404 si notebook introuvable, 502 si Brain injoignable).
|
||||||
|
* <p>
|
||||||
|
* SANS ce handler, le fallback {@code @ExceptionHandler(Throwable.class)} ci-dessous
|
||||||
|
* interceptait ces exceptions et renvoyait 500 — ecrasant le statut voulu (le
|
||||||
|
* resolver natif de Spring est court-circuite des qu'un advice gere Throwable).
|
||||||
|
*/
|
||||||
|
@ExceptionHandler(ResponseStatusException.class)
|
||||||
|
public ResponseEntity<Map<String, String>> handleResponseStatus(ResponseStatusException ex) {
|
||||||
|
String reason = ex.getReason();
|
||||||
|
return ResponseEntity.status(ex.getStatusCode())
|
||||||
|
.body(Map.of("error", reason != null ? reason : ex.getStatusCode().toString()));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Client HTTP parti pendant une reponse asynchrone (SSE) : le navigateur a ferme
|
* Client HTTP parti pendant une reponse asynchrone (SSE) : le navigateur a ferme
|
||||||
* la connexion (onglet ferme, proxy coupe...), la reponse n'est plus utilisable.
|
* la connexion (onglet ferme, proxy coupe...), la reponse n'est plus utilisable.
|
||||||
|
|||||||
@@ -88,6 +88,8 @@ public class CampaignImportController {
|
|||||||
bytes, filename,
|
bytes, filename,
|
||||||
progress -> sendEvent(emitter, clientGone, "progress", progress),
|
progress -> sendEvent(emitter, clientGone, "progress", progress),
|
||||||
() -> sendHeartbeat(emitter, clientGone),
|
() -> sendHeartbeat(emitter, clientGone),
|
||||||
|
status -> sendEvent(emitter, clientGone, "status",
|
||||||
|
Map.of("message", status != null ? status : "")),
|
||||||
proposal -> {
|
proposal -> {
|
||||||
sendEvent(emitter, clientGone, "done", proposal);
|
sendEvent(emitter, clientGone, "done", proposal);
|
||||||
emitter.complete();
|
emitter.complete();
|
||||||
|
|||||||
@@ -16,10 +16,13 @@ public class CharacterController {
|
|||||||
|
|
||||||
private final CharacterService characterService;
|
private final CharacterService characterService;
|
||||||
private final CharacterMapper characterMapper;
|
private final CharacterMapper characterMapper;
|
||||||
|
private final com.loremind.domain.playcontext.ports.PlaythroughRepository playthroughRepository;
|
||||||
|
|
||||||
public CharacterController(CharacterService characterService, CharacterMapper characterMapper) {
|
public CharacterController(CharacterService characterService, CharacterMapper characterMapper,
|
||||||
|
com.loremind.domain.playcontext.ports.PlaythroughRepository playthroughRepository) {
|
||||||
this.characterService = characterService;
|
this.characterService = characterService;
|
||||||
this.characterMapper = characterMapper;
|
this.characterMapper = characterMapper;
|
||||||
|
this.playthroughRepository = playthroughRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
@@ -43,6 +46,31 @@ public class CharacterController {
|
|||||||
return ResponseEntity.ok(dtos);
|
return ResponseEntity.ok(dtos);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recherche par nom — alimente la recherche globale (Ctrl+K). Le résultat est
|
||||||
|
* enrichi du campaignId (résolu via le Playthrough) pour que le front puisse
|
||||||
|
* construire la route /campaigns/{c}/playthroughs/{p}/characters/{id}.
|
||||||
|
*/
|
||||||
|
@GetMapping("/search")
|
||||||
|
public ResponseEntity<List<CharacterSearchDTO>> search(@RequestParam("q") String query) {
|
||||||
|
List<CharacterSearchDTO> out = characterService.searchCharacters(query).stream()
|
||||||
|
.map(c -> new CharacterSearchDTO(
|
||||||
|
c.getId(),
|
||||||
|
c.getName(),
|
||||||
|
c.getPlaythroughId(),
|
||||||
|
c.getPlaythroughId() != null
|
||||||
|
? playthroughRepository.findById(c.getPlaythroughId())
|
||||||
|
.map(com.loremind.domain.playcontext.Playthrough::getCampaignId)
|
||||||
|
.orElse(null)
|
||||||
|
: null))
|
||||||
|
.filter(r -> r.campaignId() != null) // PJ orphelin (legacy) : non navigable → exclu
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return ResponseEntity.ok(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Résultat de recherche d'un PJ, enrichi pour la navigation. */
|
||||||
|
public record CharacterSearchDTO(String id, String name, String playthroughId, String campaignId) {}
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
@PutMapping("/{id}")
|
||||||
public ResponseEntity<CharacterDTO> updateCharacter(@PathVariable String id, @RequestBody CharacterDTO dto) {
|
public ResponseEntity<CharacterDTO> updateCharacter(@PathVariable String id, @RequestBody CharacterDTO dto) {
|
||||||
Character updated = characterService.updateCharacter(id, toData(dto, dto.getOrder()));
|
Character updated = characterService.updateCharacter(id, toData(dto, dto.getOrder()));
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.campaigncontext.EnemyService;
|
||||||
|
import com.loremind.domain.campaigncontext.Enemy;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* REST Controller des fiches d'ennemis (bestiaire de campagne).
|
||||||
|
* Réponses = domaine {@link Enemy} sérialisé tel quel (Lombok @Data) ;
|
||||||
|
* requêtes = record dédié (le domaine n'a pas de constructeur no-args).
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/enemies")
|
||||||
|
public class EnemyController {
|
||||||
|
|
||||||
|
private final EnemyService enemyService;
|
||||||
|
|
||||||
|
public EnemyController(EnemyService enemyService) {
|
||||||
|
this.enemyService = enemyService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<Enemy> create(@RequestBody EnemyRequest req) {
|
||||||
|
return ResponseEntity.ok(enemyService.createEnemy(toData(req)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ResponseEntity<Enemy> getById(@PathVariable String id) {
|
||||||
|
return enemyService.getEnemyById(id)
|
||||||
|
.map(ResponseEntity::ok)
|
||||||
|
.orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/campaign/{campaignId}")
|
||||||
|
public ResponseEntity<List<Enemy>> getByCampaign(@PathVariable String campaignId) {
|
||||||
|
return ResponseEntity.ok(enemyService.getEnemiesByCampaignId(campaignId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recherche par nom — alimente la recherche globale (Ctrl+K). */
|
||||||
|
@GetMapping("/search")
|
||||||
|
public ResponseEntity<List<Enemy>> search(@RequestParam("q") String query) {
|
||||||
|
return ResponseEntity.ok(enemyService.searchEnemies(query));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public ResponseEntity<Enemy> update(@PathVariable String id, @RequestBody EnemyRequest req) {
|
||||||
|
return ResponseEntity.ok(enemyService.updateEnemy(id, toData(req)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ResponseEntity<Void> delete(@PathVariable String id) {
|
||||||
|
enemyService.deleteEnemy(id);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private EnemyService.EnemyData toData(EnemyRequest req) {
|
||||||
|
return new EnemyService.EnemyData(
|
||||||
|
req.name(), req.level(), req.folder(),
|
||||||
|
req.portraitImageId(), req.headerImageId(),
|
||||||
|
req.values(), req.imageValues(), req.keyValueValues(),
|
||||||
|
req.campaignId(), req.order());
|
||||||
|
}
|
||||||
|
|
||||||
|
public record EnemyRequest(
|
||||||
|
String name,
|
||||||
|
String level,
|
||||||
|
String folder,
|
||||||
|
String portraitImageId,
|
||||||
|
String headerImageId,
|
||||||
|
Map<String, String> values,
|
||||||
|
Map<String, List<String>> imageValues,
|
||||||
|
Map<String, Map<String, String>> keyValueValues,
|
||||||
|
String campaignId,
|
||||||
|
Integer order) {}
|
||||||
|
}
|
||||||
@@ -170,6 +170,8 @@ public class GameSystemController {
|
|||||||
bytes, filename,
|
bytes, filename,
|
||||||
progress -> sendImportEvent(emitter, clientGone, "progress", progress),
|
progress -> sendImportEvent(emitter, clientGone, "progress", progress),
|
||||||
() -> sendImportHeartbeat(emitter, clientGone),
|
() -> sendImportHeartbeat(emitter, clientGone),
|
||||||
|
status -> sendImportEvent(emitter, clientGone, "status",
|
||||||
|
Map.of("message", status != null ? status : "")),
|
||||||
result -> {
|
result -> {
|
||||||
sendImportEvent(emitter, clientGone, "done", result);
|
sendImportEvent(emitter, clientGone, "done", result);
|
||||||
emitter.complete();
|
emitter.complete();
|
||||||
@@ -261,6 +263,7 @@ public class GameSystemController {
|
|||||||
dto.getRulesMarkdown(),
|
dto.getRulesMarkdown(),
|
||||||
toDomainFields(dto.getCharacterTemplate()),
|
toDomainFields(dto.getCharacterTemplate()),
|
||||||
toDomainFields(dto.getNpcTemplate()),
|
toDomainFields(dto.getNpcTemplate()),
|
||||||
|
toDomainFields(dto.getEnemyTemplate()),
|
||||||
dto.getAuthor(),
|
dto.getAuthor(),
|
||||||
dto.isPublic()
|
dto.isPublic()
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -58,6 +58,14 @@ public class ItemCatalogController {
|
|||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Recherche par nom — alimente la recherche globale (Ctrl+K). */
|
||||||
|
@GetMapping("/search")
|
||||||
|
public ResponseEntity<List<ItemCatalogDTO>> search(@RequestParam("q") String query) {
|
||||||
|
return ResponseEntity.ok(service.searchCatalogs(query).stream()
|
||||||
|
.map(mapper::toDTO)
|
||||||
|
.collect(java.util.stream.Collectors.toList()));
|
||||||
|
}
|
||||||
|
|
||||||
/** Génère une PROPOSITION de catalogue via l'IA (non persistée) — l'UI préremplit le formulaire. */
|
/** Génère une PROPOSITION de catalogue via l'IA (non persistée) — l'UI préremplit le formulaire. */
|
||||||
@PostMapping("/generate")
|
@PostMapping("/generate")
|
||||||
public ResponseEntity<ItemCatalogDTO> generate(@RequestBody GenerateRequest req) {
|
public ResponseEntity<ItemCatalogDTO> generate(@RequestBody GenerateRequest req) {
|
||||||
|
|||||||
@@ -105,6 +105,43 @@ public class NotebookController {
|
|||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Conversation : vider (= archiver) et consulter les archives ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* « Vider la conversation » : le fil actif est ARCHIVÉ en un lot horodaté,
|
||||||
|
* jamais supprimé — consultable ensuite via {@link #listArchives}.
|
||||||
|
*/
|
||||||
|
@PostMapping("/{id}/chat/clear")
|
||||||
|
public ResponseEntity<Void> clearChat(@PathVariable String id) {
|
||||||
|
if (service.getNotebook(id).isEmpty()) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Notebook introuvable");
|
||||||
|
}
|
||||||
|
service.clearChat(id);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Archives de conversation, plus récentes d'abord : [{archivedAt, messages:[…]}]. */
|
||||||
|
@GetMapping("/{id}/chat/archives")
|
||||||
|
public ResponseEntity<List<Map<String, Object>>> listArchives(@PathVariable String id) {
|
||||||
|
var grouped = new java.util.TreeMap<java.time.LocalDateTime, List<Map<String, Object>>>(
|
||||||
|
java.util.Comparator.reverseOrder());
|
||||||
|
for (var m : service.getArchivedMessages(id)) {
|
||||||
|
grouped.computeIfAbsent(m.getArchivedAt(), k -> new java.util.ArrayList<>())
|
||||||
|
.add(Map.of(
|
||||||
|
"role", m.getRole(),
|
||||||
|
"content", m.getContent(),
|
||||||
|
"createdAt", m.getCreatedAt().toString()));
|
||||||
|
}
|
||||||
|
List<Map<String, Object>> out = new java.util.ArrayList<>();
|
||||||
|
grouped.forEach((archivedAt, messages) -> {
|
||||||
|
Map<String, Object> archive = new LinkedHashMap<>();
|
||||||
|
archive.put("archivedAt", archivedAt.toString());
|
||||||
|
archive.put("messages", messages);
|
||||||
|
out.add(archive);
|
||||||
|
});
|
||||||
|
return ResponseEntity.ok(out);
|
||||||
|
}
|
||||||
|
|
||||||
// --- Chat ancré streamé ---
|
// --- Chat ancré streamé ---
|
||||||
|
|
||||||
@PostMapping(value = "/{id}/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
@PostMapping(value = "/{id}/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
@@ -124,8 +161,26 @@ public class NotebookController {
|
|||||||
List<NotebookChatStreamer.Msg> history = service.getMessages(id).stream()
|
List<NotebookChatStreamer.Msg> history = service.getMessages(id).stream()
|
||||||
.map(m -> new NotebookChatStreamer.Msg(m.getRole(), m.getContent()))
|
.map(m -> new NotebookChatStreamer.Msg(m.getRole(), m.getContent()))
|
||||||
.toList();
|
.toList();
|
||||||
List<String> sourceIds = service.readySourceIds(id);
|
// Sélection de l'UI (cases cochées) : on ne garde que les sources qui
|
||||||
String context = service.buildContext(nb.getCampaignId());
|
// appartiennent bien à CE notebook et sont prêtes — un id étranger est
|
||||||
|
// ignoré. Limite le coût (ex. analyse approfondie sur 1 PDF au lieu de 5).
|
||||||
|
// Variable finale : elle est capturée par la lambda du taskExecutor.
|
||||||
|
List<String> readyIds = service.readySourceIds(id);
|
||||||
|
final List<String> sourceIds;
|
||||||
|
if (req.sourceIds() != null) {
|
||||||
|
var wanted = new java.util.HashSet<>(req.sourceIds());
|
||||||
|
sourceIds = readyIds.stream().filter(wanted::contains).toList();
|
||||||
|
} else {
|
||||||
|
sourceIds = readyIds;
|
||||||
|
}
|
||||||
|
// Contexte = brief de campagne + archives cochées en référence (le tout
|
||||||
|
// dans une variable finale : capturée par la lambda du taskExecutor).
|
||||||
|
String campaignContext = service.buildContext(nb.getCampaignId());
|
||||||
|
String archiveContext = service.buildArchiveContext(id, req.archiveIds());
|
||||||
|
final String context = archiveContext.isEmpty()
|
||||||
|
? campaignContext
|
||||||
|
: (campaignContext.isEmpty() ? archiveContext
|
||||||
|
: campaignContext + "\n\n" + archiveContext);
|
||||||
|
|
||||||
boolean deep = req.deep() != null && req.deep();
|
boolean deep = req.deep() != null && req.deep();
|
||||||
taskExecutor.execute(() -> {
|
taskExecutor.execute(() -> {
|
||||||
@@ -220,5 +275,14 @@ public class NotebookController {
|
|||||||
|
|
||||||
public record CreateRequest(String campaignId, String name) {}
|
public record CreateRequest(String campaignId, String name) {}
|
||||||
public record RenameRequest(String name) {}
|
public record RenameRequest(String name) {}
|
||||||
public record ChatRequest(String message, Boolean deep) {}
|
/**
|
||||||
|
* @param sourceIds Optionnel : sous-ensemble de sources à utiliser pour ce tour
|
||||||
|
* (cases cochées dans l'UI). Null = toutes les sources prêtes.
|
||||||
|
* Toujours intersecté avec les sources du notebook (sécurité).
|
||||||
|
* @param archiveIds Optionnel : archives de conversation cochées comme RÉFÉRENCE
|
||||||
|
* (clés = archivedAt). Leur contenu est injecté dans le contexte
|
||||||
|
* du prompt — toujours résolu dans CE notebook (sécurité).
|
||||||
|
*/
|
||||||
|
public record ChatRequest(String message, Boolean deep, List<String> sourceIds,
|
||||||
|
List<String> archiveIds) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,6 +43,24 @@ public class NpcController {
|
|||||||
return ResponseEntity.ok(dtos);
|
return ResponseEntity.ok(dtos);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Recherche par nom — alimente la recherche globale (Ctrl+K). */
|
||||||
|
@GetMapping("/search")
|
||||||
|
public ResponseEntity<List<NpcDTO>> search(@RequestParam("q") String query) {
|
||||||
|
List<NpcDTO> dtos = npcService.searchNpcs(query).stream()
|
||||||
|
.map(npcMapper::toDTO)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return ResponseEntity.ok(dtos);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PNJ de toutes les campagnes liées au Lore donné — alimente le graphe du Lore. */
|
||||||
|
@GetMapping("/lore/{loreId}")
|
||||||
|
public ResponseEntity<List<NpcDTO>> getNpcsByLore(@PathVariable String loreId) {
|
||||||
|
List<NpcDTO> dtos = npcService.getNpcsByLoreId(loreId).stream()
|
||||||
|
.map(npcMapper::toDTO)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return ResponseEntity.ok(dtos);
|
||||||
|
}
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
@PutMapping("/{id}")
|
||||||
public ResponseEntity<NpcDTO> updateNpc(@PathVariable String id, @RequestBody NpcDTO dto) {
|
public ResponseEntity<NpcDTO> updateNpc(@PathVariable String id, @RequestBody NpcDTO dto) {
|
||||||
Npc updated = npcService.updateNpc(id, toData(dto, dto.getOrder()));
|
Npc updated = npcService.updateNpc(id, toData(dto, dto.getOrder()));
|
||||||
@@ -64,6 +82,7 @@ public class NpcController {
|
|||||||
dto.getImageValues(),
|
dto.getImageValues(),
|
||||||
dto.getKeyValueValues(),
|
dto.getKeyValueValues(),
|
||||||
dto.getCampaignId(),
|
dto.getCampaignId(),
|
||||||
|
dto.getRelatedPageIds(),
|
||||||
dto.getFolder(),
|
dto.getFolder(),
|
||||||
order
|
order
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -59,6 +59,14 @@ public class RandomTableController {
|
|||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Recherche par nom — alimente la recherche globale (Ctrl+K). */
|
||||||
|
@GetMapping("/search")
|
||||||
|
public ResponseEntity<List<RandomTableDTO>> search(@RequestParam("q") String query) {
|
||||||
|
return ResponseEntity.ok(service.searchTables(query).stream()
|
||||||
|
.map(mapper::toDTO)
|
||||||
|
.collect(java.util.stream.Collectors.toList()));
|
||||||
|
}
|
||||||
|
|
||||||
/** Génère une PROPOSITION de table via l'IA (non persistée) — l'UI préremplit le formulaire. */
|
/** Génère une PROPOSITION de table via l'IA (non persistée) — l'UI préremplit le formulaire. */
|
||||||
@PostMapping("/generate")
|
@PostMapping("/generate")
|
||||||
public ResponseEntity<RandomTableDTO> generate(@RequestBody GenerateRequest req) {
|
public ResponseEntity<RandomTableDTO> generate(@RequestBody GenerateRequest req) {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.loremind.infrastructure.web.dto.campaigncontext;
|
|||||||
|
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -20,6 +21,8 @@ public class NpcDTO {
|
|||||||
private Map<String, List<String>> imageValues = new HashMap<>();
|
private Map<String, List<String>> imageValues = new HashMap<>();
|
||||||
private Map<String, Map<String, String>> keyValueValues = new HashMap<>();
|
private Map<String, Map<String, String>> keyValueValues = new HashMap<>();
|
||||||
private String campaignId;
|
private String campaignId;
|
||||||
|
/** IDs de Pages de Lore référencées par ce PNJ (référence faible cross-context). */
|
||||||
|
private List<String> relatedPageIds = new ArrayList<>();
|
||||||
private String folder;
|
private String folder;
|
||||||
private int order;
|
private int order;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ public class RoomDTO {
|
|||||||
private String name;
|
private String name;
|
||||||
private String description;
|
private String description;
|
||||||
private String enemies;
|
private String enemies;
|
||||||
|
/** IDs des fiches du bestiaire présentes dans la pièce (weak refs). */
|
||||||
|
private List<String> enemyIds = new ArrayList<>();
|
||||||
private String loot;
|
private String loot;
|
||||||
private String traps;
|
private String traps;
|
||||||
private String gmNotes;
|
private String gmNotes;
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ public class SceneDTO {
|
|||||||
private String combatDifficulty;
|
private String combatDifficulty;
|
||||||
private String enemies;
|
private String enemies;
|
||||||
|
|
||||||
|
/** IDs des fiches du bestiaire engagées dans la rencontre (weak refs). */
|
||||||
|
private List<String> enemyIds = new ArrayList<>();
|
||||||
|
|
||||||
/** IDs des pages du Lore liées (weak cross-context references). */
|
/** IDs des pages du Lore liées (weak cross-context references). */
|
||||||
private List<String> relatedPageIds = new ArrayList<>();
|
private List<String> relatedPageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ public class GameSystemDTO {
|
|||||||
private String rulesMarkdown;
|
private String rulesMarkdown;
|
||||||
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
|
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
|
||||||
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
|
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
|
||||||
|
private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>();
|
||||||
private String author;
|
private String author;
|
||||||
private boolean isPublic;
|
private boolean isPublic;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ public class PageDTO {
|
|||||||
private Map<String, String> values;
|
private Map<String, String> values;
|
||||||
/** Pour chaque champ IMAGE du template, la liste ordonnee des IDs d'images. */
|
/** Pour chaque champ IMAGE du template, la liste ordonnee des IDs d'images. */
|
||||||
private Map<String, List<String>> imageValues;
|
private Map<String, List<String>> imageValues;
|
||||||
|
/** Pour chaque champ KEY_VALUE_LIST du template : label → valeur. */
|
||||||
|
private Map<String, Map<String, String>> keyValueValues;
|
||||||
|
/** Pour chaque champ TABLE du template : lignes (colonne → cellule). */
|
||||||
|
private Map<String, List<Map<String, String>>> tableValues;
|
||||||
private String notes;
|
private String notes;
|
||||||
private List<String> tags;
|
private List<String> tags;
|
||||||
private List<String> relatedPageIds;
|
private List<String> relatedPageIds;
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ public class GameSystemMapper {
|
|||||||
dto.setRulesMarkdown(g.getRulesMarkdown());
|
dto.setRulesMarkdown(g.getRulesMarkdown());
|
||||||
dto.setCharacterTemplate(toDTOList(g.getCharacterTemplate()));
|
dto.setCharacterTemplate(toDTOList(g.getCharacterTemplate()));
|
||||||
dto.setNpcTemplate(toDTOList(g.getNpcTemplate()));
|
dto.setNpcTemplate(toDTOList(g.getNpcTemplate()));
|
||||||
|
dto.setEnemyTemplate(toDTOList(g.getEnemyTemplate()));
|
||||||
dto.setAuthor(g.getAuthor());
|
dto.setAuthor(g.getAuthor());
|
||||||
dto.setPublic(g.isPublic());
|
dto.setPublic(g.isPublic());
|
||||||
return dto;
|
return dto;
|
||||||
@@ -41,6 +42,7 @@ public class GameSystemMapper {
|
|||||||
.rulesMarkdown(dto.getRulesMarkdown())
|
.rulesMarkdown(dto.getRulesMarkdown())
|
||||||
.characterTemplate(toDomainList(dto.getCharacterTemplate()))
|
.characterTemplate(toDomainList(dto.getCharacterTemplate()))
|
||||||
.npcTemplate(toDomainList(dto.getNpcTemplate()))
|
.npcTemplate(toDomainList(dto.getNpcTemplate()))
|
||||||
|
.enemyTemplate(toDomainList(dto.getEnemyTemplate()))
|
||||||
.author(dto.getAuthor())
|
.author(dto.getAuthor())
|
||||||
.isPublic(dto.isPublic())
|
.isPublic(dto.isPublic())
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.loremind.domain.campaigncontext.Npc;
|
|||||||
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@@ -20,6 +21,7 @@ public class NpcMapper {
|
|||||||
dto.setImageValues(n.getImageValues() != null ? new HashMap<>(n.getImageValues()) : new HashMap<>());
|
dto.setImageValues(n.getImageValues() != null ? new HashMap<>(n.getImageValues()) : new HashMap<>());
|
||||||
dto.setKeyValueValues(n.getKeyValueValues() != null ? new HashMap<>(n.getKeyValueValues()) : new HashMap<>());
|
dto.setKeyValueValues(n.getKeyValueValues() != null ? new HashMap<>(n.getKeyValueValues()) : new HashMap<>());
|
||||||
dto.setCampaignId(n.getCampaignId());
|
dto.setCampaignId(n.getCampaignId());
|
||||||
|
dto.setRelatedPageIds(n.getRelatedPageIds() != null ? new ArrayList<>(n.getRelatedPageIds()) : new ArrayList<>());
|
||||||
dto.setFolder(n.getFolder());
|
dto.setFolder(n.getFolder());
|
||||||
dto.setOrder(n.getOrder());
|
dto.setOrder(n.getOrder());
|
||||||
return dto;
|
return dto;
|
||||||
@@ -36,6 +38,7 @@ public class NpcMapper {
|
|||||||
.imageValues(dto.getImageValues() != null ? new HashMap<>(dto.getImageValues()) : new HashMap<>())
|
.imageValues(dto.getImageValues() != null ? new HashMap<>(dto.getImageValues()) : new HashMap<>())
|
||||||
.keyValueValues(dto.getKeyValueValues() != null ? new HashMap<>(dto.getKeyValueValues()) : new HashMap<>())
|
.keyValueValues(dto.getKeyValueValues() != null ? new HashMap<>(dto.getKeyValueValues()) : new HashMap<>())
|
||||||
.campaignId(dto.getCampaignId())
|
.campaignId(dto.getCampaignId())
|
||||||
|
.relatedPageIds(dto.getRelatedPageIds() != null ? new ArrayList<>(dto.getRelatedPageIds()) : new ArrayList<>())
|
||||||
.folder(dto.getFolder())
|
.folder(dto.getFolder())
|
||||||
.order(dto.getOrder())
|
.order(dto.getOrder())
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ public class PageMapper {
|
|||||||
dto.setTitle(page.getTitle());
|
dto.setTitle(page.getTitle());
|
||||||
dto.setValues(CollectionUtils.copyMap(page.getValues()));
|
dto.setValues(CollectionUtils.copyMap(page.getValues()));
|
||||||
dto.setImageValues(CollectionUtils.copyMap(page.getImageValues()));
|
dto.setImageValues(CollectionUtils.copyMap(page.getImageValues()));
|
||||||
|
dto.setKeyValueValues(CollectionUtils.copyMap(page.getKeyValueValues()));
|
||||||
|
dto.setTableValues(CollectionUtils.copyMap(page.getTableValues()));
|
||||||
dto.setNotes(page.getNotes());
|
dto.setNotes(page.getNotes());
|
||||||
dto.setTags(CollectionUtils.copyList(page.getTags()));
|
dto.setTags(CollectionUtils.copyList(page.getTags()));
|
||||||
dto.setRelatedPageIds(CollectionUtils.copyList(page.getRelatedPageIds()));
|
dto.setRelatedPageIds(CollectionUtils.copyList(page.getRelatedPageIds()));
|
||||||
@@ -41,6 +43,8 @@ public class PageMapper {
|
|||||||
.title(dto.getTitle())
|
.title(dto.getTitle())
|
||||||
.values(CollectionUtils.copyMap(dto.getValues()))
|
.values(CollectionUtils.copyMap(dto.getValues()))
|
||||||
.imageValues(CollectionUtils.copyMap(dto.getImageValues()))
|
.imageValues(CollectionUtils.copyMap(dto.getImageValues()))
|
||||||
|
.keyValueValues(CollectionUtils.copyMap(dto.getKeyValueValues()))
|
||||||
|
.tableValues(CollectionUtils.copyMap(dto.getTableValues()))
|
||||||
.notes(dto.getNotes())
|
.notes(dto.getNotes())
|
||||||
.tags(CollectionUtils.copyList(dto.getTags()))
|
.tags(CollectionUtils.copyList(dto.getTags()))
|
||||||
.relatedPageIds(CollectionUtils.copyList(dto.getRelatedPageIds()))
|
.relatedPageIds(CollectionUtils.copyList(dto.getRelatedPageIds()))
|
||||||
|
|||||||
@@ -40,6 +40,9 @@ public class SceneMapper {
|
|||||||
dto.setChoicesConsequences(scene.getChoicesConsequences());
|
dto.setChoicesConsequences(scene.getChoicesConsequences());
|
||||||
dto.setCombatDifficulty(scene.getCombatDifficulty());
|
dto.setCombatDifficulty(scene.getCombatDifficulty());
|
||||||
dto.setEnemies(scene.getEnemies());
|
dto.setEnemies(scene.getEnemies());
|
||||||
|
dto.setEnemyIds(scene.getEnemyIds() != null
|
||||||
|
? new ArrayList<>(scene.getEnemyIds())
|
||||||
|
: new ArrayList<>());
|
||||||
dto.setRelatedPageIds(scene.getRelatedPageIds() != null
|
dto.setRelatedPageIds(scene.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(scene.getRelatedPageIds())
|
? new ArrayList<>(scene.getRelatedPageIds())
|
||||||
: new ArrayList<>());
|
: new ArrayList<>());
|
||||||
@@ -74,6 +77,9 @@ public class SceneMapper {
|
|||||||
.choicesConsequences(dto.getChoicesConsequences())
|
.choicesConsequences(dto.getChoicesConsequences())
|
||||||
.combatDifficulty(dto.getCombatDifficulty())
|
.combatDifficulty(dto.getCombatDifficulty())
|
||||||
.enemies(dto.getEnemies())
|
.enemies(dto.getEnemies())
|
||||||
|
.enemyIds(dto.getEnemyIds() != null
|
||||||
|
? new ArrayList<>(dto.getEnemyIds())
|
||||||
|
: new ArrayList<>())
|
||||||
.relatedPageIds(dto.getRelatedPageIds() != null
|
.relatedPageIds(dto.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(dto.getRelatedPageIds())
|
? new ArrayList<>(dto.getRelatedPageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
@@ -117,6 +123,9 @@ public class SceneMapper {
|
|||||||
dto.setName(r.getName());
|
dto.setName(r.getName());
|
||||||
dto.setDescription(r.getDescription());
|
dto.setDescription(r.getDescription());
|
||||||
dto.setEnemies(r.getEnemies());
|
dto.setEnemies(r.getEnemies());
|
||||||
|
dto.setEnemyIds(r.getEnemyIds() != null
|
||||||
|
? new ArrayList<>(r.getEnemyIds())
|
||||||
|
: new ArrayList<>());
|
||||||
dto.setLoot(r.getLoot());
|
dto.setLoot(r.getLoot());
|
||||||
dto.setTraps(r.getTraps());
|
dto.setTraps(r.getTraps());
|
||||||
dto.setGmNotes(r.getGmNotes());
|
dto.setGmNotes(r.getGmNotes());
|
||||||
@@ -145,6 +154,9 @@ public class SceneMapper {
|
|||||||
.name(d.getName())
|
.name(d.getName())
|
||||||
.description(d.getDescription())
|
.description(d.getDescription())
|
||||||
.enemies(d.getEnemies())
|
.enemies(d.getEnemies())
|
||||||
|
.enemyIds(d.getEnemyIds() != null
|
||||||
|
? new ArrayList<>(d.getEnemyIds())
|
||||||
|
: new ArrayList<>())
|
||||||
.loot(d.getLoot())
|
.loot(d.getLoot())
|
||||||
.traps(d.getTraps())
|
.traps(d.getTraps())
|
||||||
.gmNotes(d.getGmNotes())
|
.gmNotes(d.getGmNotes())
|
||||||
|
|||||||
@@ -29,7 +29,8 @@ public class TemplateFieldMapper {
|
|||||||
layoutStr = layout.name();
|
layoutStr = layout.name();
|
||||||
}
|
}
|
||||||
List<String> labels = null;
|
List<String> labels = null;
|
||||||
if (field.getType() == FieldType.KEY_VALUE_LIST && field.getLabels() != null) {
|
if ((field.getType() == FieldType.KEY_VALUE_LIST || field.getType() == FieldType.TABLE)
|
||||||
|
&& field.getLabels() != null) {
|
||||||
labels = new ArrayList<>(field.getLabels());
|
labels = new ArrayList<>(field.getLabels());
|
||||||
}
|
}
|
||||||
return new TemplateFieldDTO(field.getName(), typeStr, layoutStr, labels);
|
return new TemplateFieldDTO(field.getName(), typeStr, layoutStr, labels);
|
||||||
@@ -54,7 +55,7 @@ public class TemplateFieldMapper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
List<String> labels = null;
|
List<String> labels = null;
|
||||||
if (type == FieldType.KEY_VALUE_LIST && dto.getLabels() != null) {
|
if ((type == FieldType.KEY_VALUE_LIST || type == FieldType.TABLE) && dto.getLabels() != null) {
|
||||||
labels = new ArrayList<>(dto.getLabels());
|
labels = new ArrayList<>(dto.getLabels());
|
||||||
}
|
}
|
||||||
return new TemplateField(dto.getName(), type, layout, labels);
|
return new TemplateField(dto.getName(), type, layout, labels);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Npc;
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -29,6 +30,9 @@ public class NpcServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private NpcRepository npcRepository;
|
private NpcRepository npcRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private CampaignRepository campaignRepository;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private NpcService npcService;
|
private NpcService npcService;
|
||||||
|
|
||||||
@@ -51,7 +55,7 @@ public class NpcServiceTest {
|
|||||||
|
|
||||||
Npc result = npcService.createNpc(
|
Npc result = npcService.createNpc(
|
||||||
new NpcService.NpcData("Borin le forgeron", null, null,
|
new NpcService.NpcData("Borin le forgeron", null, null,
|
||||||
Map.of("Notes", "Borin"), null, null, "camp-1", null,5));
|
Map.of("Notes", "Borin"), null, null, "camp-1", null, null, 5));
|
||||||
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||||
@@ -67,7 +71,7 @@ public class NpcServiceTest {
|
|||||||
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of(a, b));
|
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of(a, b));
|
||||||
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
||||||
|
|
||||||
npcService.createNpc(new NpcService.NpcData("Nouveau", null, null, null, null, null, "camp-1", null,null));
|
npcService.createNpc(new NpcService.NpcData("Nouveau", null, null, null, null, null, "camp-1", null, null, null));
|
||||||
|
|
||||||
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||||
verify(npcRepository).save(captor.capture());
|
verify(npcRepository).save(captor.capture());
|
||||||
@@ -79,7 +83,7 @@ public class NpcServiceTest {
|
|||||||
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of());
|
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of());
|
||||||
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
||||||
|
|
||||||
npcService.createNpc(new NpcService.NpcData("Premier", null, null, null, null, null, "camp-1", null,null));
|
npcService.createNpc(new NpcService.NpcData("Premier", null, null, null, null, null, "camp-1", null, null, null));
|
||||||
|
|
||||||
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||||
verify(npcRepository).save(captor.capture());
|
verify(npcRepository).save(captor.capture());
|
||||||
@@ -124,7 +128,7 @@ public class NpcServiceTest {
|
|||||||
|
|
||||||
Npc result = npcService.updateNpc("npc-1",
|
Npc result = npcService.updateNpc("npc-1",
|
||||||
new NpcService.NpcData("Borin renommé", null, null,
|
new NpcService.NpcData("Borin renommé", null, null,
|
||||||
Map.of("Notes", "v2"), null, null, "camp-1", null,7));
|
Map.of("Notes", "v2"), null, null, "camp-1", null, null, 7));
|
||||||
|
|
||||||
assertEquals("Borin renommé", result.getName());
|
assertEquals("Borin renommé", result.getName());
|
||||||
assertEquals("v2", result.getValues().get("Notes"));
|
assertEquals("v2", result.getValues().get("Notes"));
|
||||||
@@ -138,7 +142,7 @@ public class NpcServiceTest {
|
|||||||
|
|
||||||
Npc result = npcService.updateNpc("npc-1",
|
Npc result = npcService.updateNpc("npc-1",
|
||||||
new NpcService.NpcData("Borin", null, null,
|
new NpcService.NpcData("Borin", null, null,
|
||||||
Map.of("Notes", "txt"), null, null, "camp-1", null,null));
|
Map.of("Notes", "txt"), null, null, "camp-1", null, null, null));
|
||||||
|
|
||||||
// testNpc avait order=1 → préservé
|
// testNpc avait order=1 → préservé
|
||||||
assertEquals(1, result.getOrder());
|
assertEquals(1, result.getOrder());
|
||||||
@@ -150,7 +154,7 @@ public class NpcServiceTest {
|
|||||||
|
|
||||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
() -> npcService.updateNpc("missing",
|
() -> npcService.updateNpc("missing",
|
||||||
new NpcService.NpcData("x", null, null, null, null, null, "camp-1", null,null)));
|
new NpcService.NpcData("x", null, null, null, null, null, "camp-1", null, null, null)));
|
||||||
assertTrue(ex.getMessage().contains("missing"));
|
assertTrue(ex.getMessage().contains("missing"));
|
||||||
verify(npcRepository, never()).save(any());
|
verify(npcRepository, never()).save(any());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ 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.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
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;
|
||||||
@@ -48,6 +49,8 @@ public class CampaignStructuralContextBuilderTest {
|
|||||||
private CharacterRepository characterRepository;
|
private CharacterRepository characterRepository;
|
||||||
@Mock
|
@Mock
|
||||||
private NpcRepository npcRepository;
|
private NpcRepository npcRepository;
|
||||||
|
@Mock
|
||||||
|
private EnemyRepository enemyRepository;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private CampaignStructuralContextBuilder builder;
|
private CampaignStructuralContextBuilder builder;
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ class CampaignStructuralContextTest {
|
|||||||
ArcSummary arc = new ArcSummary(
|
ArcSummary arc = new ArcSummary(
|
||||||
"Acte I",
|
"Acte I",
|
||||||
"Mise en place",
|
"Mise en place",
|
||||||
|
false,
|
||||||
1,
|
1,
|
||||||
List.of(chapter));
|
List.of(chapter));
|
||||||
|
|
||||||
@@ -76,7 +77,7 @@ class CampaignStructuralContextTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void illustrationCount_defaultsToZero_onAllSummaryTypes() {
|
void illustrationCount_defaultsToZero_onAllSummaryTypes() {
|
||||||
ArcSummary arc = new ArcSummary("X", null, 0, List.of());
|
ArcSummary arc = new ArcSummary("X", null, false, 0, List.of());
|
||||||
ChapterSummary chapter = new ChapterSummary("X", null, 0, List.of());
|
ChapterSummary chapter = new ChapterSummary("X", null, 0, List.of());
|
||||||
SceneSummary scene = new SceneSummary("X", null, 0, List.of(), List.of());
|
SceneSummary scene = new SceneSummary("X", null, 0, List.of(), List.of());
|
||||||
|
|
||||||
@@ -92,6 +93,7 @@ class CampaignStructuralContextTest {
|
|||||||
ArcSummary arc = new ArcSummary(
|
ArcSummary arc = new ArcSummary(
|
||||||
"Acte I",
|
"Acte I",
|
||||||
null,
|
null,
|
||||||
|
false,
|
||||||
0,
|
0,
|
||||||
List.of(
|
List.of(
|
||||||
new ChapterSummary("Ch1", null, 0, List.of()),
|
new ChapterSummary("Ch1", null, 0, List.of()),
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
|
import com.loremind.domain.generationcontext.ChatUsage;
|
||||||
|
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring, sans réseau) de
|
||||||
|
* {@link BrainAiChatClient}.
|
||||||
|
*
|
||||||
|
* Principe : WebClient.Builder préconfiguré avec une ExchangeFunction mock
|
||||||
|
* renvoyant un flux SSE canned. Le payloadBuilder est mocké ; le sseParser est
|
||||||
|
* une instance réelle (simple parseur sans dépendance).
|
||||||
|
*/
|
||||||
|
class BrainAiChatClientTest {
|
||||||
|
|
||||||
|
/** ChatRequest minimal valide : messages vide suffit (payloadBuilder mocké). */
|
||||||
|
private ChatRequest minimalRequest() {
|
||||||
|
return ChatRequest.builder().messages(List.of()).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Construit un client dont le WebClient renvoie le corps SSE fourni. */
|
||||||
|
private BrainAiChatClient clientWithSse(String sseBody) {
|
||||||
|
ExchangeFunction ef = req -> Mono.just(
|
||||||
|
ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sseBody)
|
||||||
|
.build());
|
||||||
|
return buildClient(ef);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Construit un client dont le WebClient émet une erreur transport. */
|
||||||
|
private BrainAiChatClient clientErroring() {
|
||||||
|
ExchangeFunction ef = req -> Mono.error(new RuntimeException("boom"));
|
||||||
|
return buildClient(ef);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BrainAiChatClient buildClient(ExchangeFunction ef) {
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
BrainChatPayloadBuilder payloadBuilder = mock(BrainChatPayloadBuilder.class);
|
||||||
|
when(payloadBuilder.build(org.mockito.ArgumentMatchers.any())).thenReturn(Map.of());
|
||||||
|
return new BrainAiChatClient(builder, "http://brain", payloadBuilder, new BrainSseParser());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Collecteurs partagés pour les callbacks ---
|
||||||
|
private final List<ChatUsage> usages = new ArrayList<>();
|
||||||
|
private final List<String> tokens = new ArrayList<>();
|
||||||
|
private final AtomicBoolean completed = new AtomicBoolean(false);
|
||||||
|
private final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||||
|
|
||||||
|
private final Consumer<ChatUsage> onUsage = usages::add;
|
||||||
|
private final Consumer<String> onToken = tokens::add;
|
||||||
|
private final Runnable onComplete = () -> completed.set(true);
|
||||||
|
private final Consumer<Throwable> onError = error::set;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void flux_complet_parse_usage_et_token_puis_complete() {
|
||||||
|
String sse =
|
||||||
|
"event:usage\ndata:{\"system\":1,\"history\":2,\"current\":3,\"max\":100}\n\n" +
|
||||||
|
"data:{\"token\":\"Bonjour\"}\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
BrainAiChatClient client = clientWithSse(sse);
|
||||||
|
|
||||||
|
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
|
// usage parsé et propagé
|
||||||
|
assertThat(usages).hasSize(1);
|
||||||
|
assertThat(usages.get(0)).isEqualTo(new ChatUsage(1, 2, 3, 100));
|
||||||
|
// token propagé
|
||||||
|
assertThat(tokens).containsExactly("Bonjour");
|
||||||
|
// event done ignoré (pas de token/usage supplémentaire)
|
||||||
|
// complétion appelée, pas d'erreur
|
||||||
|
assertThat(completed).isTrue();
|
||||||
|
assertThat(error.get()).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void plusieurs_tokens_propages_dans_l_ordre() {
|
||||||
|
String sse =
|
||||||
|
"data:{\"token\":\"Bon\"}\n\n" +
|
||||||
|
"data:{\"token\":\"jour\"}\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
BrainAiChatClient client = clientWithSse(sse);
|
||||||
|
|
||||||
|
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
|
assertThat(tokens).containsExactly("Bon", "jour");
|
||||||
|
assertThat(completed).isTrue();
|
||||||
|
assertThat(error.get()).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_error_declenche_onError_avec_AiProviderException() {
|
||||||
|
String sse =
|
||||||
|
"event:error\ndata:boom\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
BrainAiChatClient client = clientWithSse(sse);
|
||||||
|
|
||||||
|
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
|
assertThat(error.get())
|
||||||
|
.isInstanceOf(AiProviderException.class)
|
||||||
|
.hasMessageContaining("boom");
|
||||||
|
// Aucun token émis sur ce flux.
|
||||||
|
assertThat(tokens).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void token_vide_n_est_pas_propage() {
|
||||||
|
String sse =
|
||||||
|
"data:{\"token\":\"\"}\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
BrainAiChatClient client = clientWithSse(sse);
|
||||||
|
|
||||||
|
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
|
assertThat(tokens).isEmpty();
|
||||||
|
assertThat(completed).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void usage_illisible_n_est_pas_propage() {
|
||||||
|
// data usage sans champs numériques -> parser renvoie ChatUsage(0,0,0,0),
|
||||||
|
// donc propagé ; ici on teste un usage avec data non-null mais vide d'entiers.
|
||||||
|
String sse =
|
||||||
|
"event:usage\ndata:{\"system\":5}\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
BrainAiChatClient client = clientWithSse(sse);
|
||||||
|
|
||||||
|
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
|
// Les champs absents tombent à 0 (parser tolérant).
|
||||||
|
assertThat(usages).containsExactly(new ChatUsage(5, 0, 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur_transport_declenche_onError_avec_AiProviderException() {
|
||||||
|
BrainAiChatClient client = clientErroring();
|
||||||
|
|
||||||
|
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
|
assertThat(error.get())
|
||||||
|
.isInstanceOf(AiProviderException.class)
|
||||||
|
.hasMessageContaining("streaming chat");
|
||||||
|
// onComplete NON appelé puisqu'une exception a interrompu blockLast().
|
||||||
|
assertThat(completed).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void flux_vide_appelle_seulement_onComplete() {
|
||||||
|
// Flux SSE vide : aucun évènement, blockLast renvoie null, onComplete appelé.
|
||||||
|
BrainAiChatClient client = clientWithSse("");
|
||||||
|
|
||||||
|
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||||
|
|
||||||
|
assertThat(tokens).isEmpty();
|
||||||
|
assertThat(usages).isEmpty();
|
||||||
|
assertThat(completed).isTrue();
|
||||||
|
assertThat(error.get()).isNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.generationcontext.GenerationContext;
|
||||||
|
import com.loremind.domain.generationcontext.GenerationResult;
|
||||||
|
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.client.HttpServerErrorException;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires PURS (JUnit 5 + Mockito, sans Spring, sans reseau) pour
|
||||||
|
* BrainAiClient. Le RestTemplate est mocke ; on couvre toutes les branches
|
||||||
|
* de callBrain ainsi que la traduction domaine -> wire -> domaine.
|
||||||
|
*/
|
||||||
|
class BrainAiClientTest {
|
||||||
|
|
||||||
|
private static final String BASE_URL = "http://brain";
|
||||||
|
private static final String EXPECTED_URL = "http://brain/generate-page";
|
||||||
|
|
||||||
|
private GenerationContext sampleContext() {
|
||||||
|
return new GenerationContext(
|
||||||
|
"Aetheria",
|
||||||
|
"Un monde de cendres",
|
||||||
|
"PNJ",
|
||||||
|
"Fiche personnage",
|
||||||
|
List.of("histoire", "motto"),
|
||||||
|
"Garde rouge"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BrainGeneratePageResponse responseWith(Map<String, String> values) {
|
||||||
|
BrainGeneratePageResponse r = new BrainGeneratePageResponse();
|
||||||
|
r.setValues(values);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Branche succes ------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatePage_succes_traduitReponseWireEnResultatDomaine() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||||
|
|
||||||
|
BrainGeneratePageResponse wire = responseWith(Map.of(
|
||||||
|
"histoire", "Nee sous une etoile rouge",
|
||||||
|
"motto", "Jamais genou en terre"
|
||||||
|
));
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||||
|
.thenReturn(wire);
|
||||||
|
|
||||||
|
GenerationResult result = client.generatePage(sampleContext());
|
||||||
|
|
||||||
|
assertEquals(2, result.values().size());
|
||||||
|
assertEquals("Jamais genou en terre", result.values().get("motto"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatePage_appelleBonneUrlEtContentTypeJson_avecCorpsTraduit() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||||
|
.thenReturn(responseWith(Map.of("histoire", "v")));
|
||||||
|
|
||||||
|
client.generatePage(sampleContext());
|
||||||
|
|
||||||
|
// Capture de l'URL et de l'HttpEntity envoyes au RestTemplate
|
||||||
|
ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
ArgumentCaptor<HttpEntity<BrainGeneratePageRequest>> entityCaptor =
|
||||||
|
ArgumentCaptor.forClass(HttpEntity.class);
|
||||||
|
|
||||||
|
org.mockito.Mockito.verify(rt).postForObject(
|
||||||
|
urlCaptor.capture(),
|
||||||
|
entityCaptor.capture(),
|
||||||
|
eq(BrainGeneratePageResponse.class));
|
||||||
|
|
||||||
|
assertEquals(EXPECTED_URL, urlCaptor.getValue());
|
||||||
|
|
||||||
|
HttpEntity<BrainGeneratePageRequest> entity = entityCaptor.getValue();
|
||||||
|
HttpHeaders headers = entity.getHeaders();
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, headers.getContentType());
|
||||||
|
|
||||||
|
// Verifie la traduction domaine -> wire (exerce les getters du record)
|
||||||
|
BrainGeneratePageRequest body = entity.getBody();
|
||||||
|
assertEquals("Aetheria", body.loreName());
|
||||||
|
assertEquals("Un monde de cendres", body.loreDescription());
|
||||||
|
assertEquals("PNJ", body.folderName());
|
||||||
|
assertEquals("Fiche personnage", body.templateName());
|
||||||
|
assertEquals(List.of("histoire", "motto"), body.templateFields());
|
||||||
|
assertEquals("Garde rouge", body.pageTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Branche reponse null ------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatePage_reponseNull_leveAiProviderException() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||||
|
.thenReturn(null);
|
||||||
|
|
||||||
|
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||||
|
() -> client.generatePage(sampleContext()));
|
||||||
|
assertTrue(ex.getMessage().contains("reponse vide")
|
||||||
|
|| ex.getMessage().contains("réponse vide"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Branche values null -------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatePage_valuesNull_leveAiProviderException() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||||
|
|
||||||
|
// Reponse non null mais avec values == null
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||||
|
.thenReturn(responseWith(null));
|
||||||
|
|
||||||
|
assertThrows(AiProviderException.class,
|
||||||
|
() -> client.generatePage(sampleContext()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Branche ResourceAccessException (Brain injoignable) -----------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatePage_brainInjoignable_leveAiProviderException() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||||
|
|
||||||
|
ResourceAccessException cause = new ResourceAccessException("down");
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||||
|
.thenThrow(cause);
|
||||||
|
|
||||||
|
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||||
|
() -> client.generatePage(sampleContext()));
|
||||||
|
assertTrue(ex.getMessage().contains("injoignable"));
|
||||||
|
assertSame(cause, ex.getCause());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Branche RestClientResponseException (HTTP 4xx/5xx) ------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatePage_erreurHttp_leveAiProviderExceptionAvecCode() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||||
|
|
||||||
|
HttpServerErrorException cause = HttpServerErrorException.create(
|
||||||
|
HttpStatus.BAD_GATEWAY, "Bad Gateway",
|
||||||
|
new HttpHeaders(), new byte[0], null);
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||||
|
.thenThrow(cause);
|
||||||
|
|
||||||
|
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||||
|
() -> client.generatePage(sampleContext()));
|
||||||
|
assertTrue(ex.getMessage().contains("502"));
|
||||||
|
assertSame(cause, ex.getCause());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Branche AiProviderException deja traduite : re-levee telle quelle ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatePage_aiProviderExceptionDejaTraduite_estRelancee() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||||
|
|
||||||
|
AiProviderException original = new AiProviderException("deja traduite");
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||||
|
.thenThrow(original);
|
||||||
|
|
||||||
|
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||||
|
() -> client.generatePage(sampleContext()));
|
||||||
|
// Pas de re-enveloppement : c'est exactement la meme instance
|
||||||
|
assertSame(original, ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Branche Exception generique (filet de securite) ---------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatePage_exceptionGenerique_leveAiProviderException() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||||
|
|
||||||
|
RuntimeException cause = new IllegalStateException("JSON invalide");
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||||
|
.thenThrow(cause);
|
||||||
|
|
||||||
|
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||||
|
() -> client.generatePage(sampleContext()));
|
||||||
|
assertTrue(ex.getMessage().contains("inattendue"));
|
||||||
|
assertSame(cause, ex.getCause());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires PURS (JUnit 5, sans Spring ni réseau) pour {@link BrainCampaignAdaptClient}.
|
||||||
|
* Le WebClient.Builder injecté embarque une ExchangeFunction qui renvoie un corps SSE canned.
|
||||||
|
*/
|
||||||
|
class BrainCampaignAdaptClientTest {
|
||||||
|
|
||||||
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
|
private BrainCampaignAdaptClient clientReturning(String sseBody) {
|
||||||
|
ExchangeFunction ef = req -> Mono.just(
|
||||||
|
ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sseBody)
|
||||||
|
.build());
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainCampaignAdaptClient(builder, MAPPER, "http://brain", 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BrainCampaignAdaptClient clientFailingWith(Throwable boom) {
|
||||||
|
ExchangeFunction ef = req -> Mono.error(boom);
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainCampaignAdaptClient(builder, MAPPER, "http://brain", 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Collecteur de callbacks + déclenchement de adviseStreaming. */
|
||||||
|
private static final class Collector {
|
||||||
|
final StringBuilder tokens = new StringBuilder();
|
||||||
|
final AtomicBoolean complete = new AtomicBoolean(false);
|
||||||
|
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||||
|
|
||||||
|
void invoke(BrainCampaignAdaptClient client, String filename, String brief, String messagesJson) {
|
||||||
|
client.adviseStreaming(
|
||||||
|
new byte[]{1, 2, 3},
|
||||||
|
filename,
|
||||||
|
brief,
|
||||||
|
messagesJson,
|
||||||
|
tokens::append,
|
||||||
|
() -> complete.set(true),
|
||||||
|
error::set);
|
||||||
|
}
|
||||||
|
|
||||||
|
void invoke(BrainCampaignAdaptClient client) {
|
||||||
|
invoke(client, "camp.pdf", "brief", "[]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streame_tokens_puis_done() {
|
||||||
|
String sse =
|
||||||
|
"event:token\ndata:{\"token\":\"Conseil\"}\n\n" +
|
||||||
|
"event:token\ndata:{\"token\":\" final\"}\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals("Conseil final", c.tokens.toString());
|
||||||
|
assertTrue(c.complete.get(), "onComplete appelé via event done");
|
||||||
|
assertNull(c.error.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void token_vide_ou_absent_ignore() {
|
||||||
|
// token "" -> non émis ; champ token absent -> readField renvoie data (non vide)
|
||||||
|
// donc émis tel quel : on vérifie ce comportement réel.
|
||||||
|
String sse =
|
||||||
|
"event:token\ndata:{\"token\":\"\"}\n\n" +
|
||||||
|
"event:token\ndata:{\"token\":\"OK\"}\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals("OK", c.tokens.toString());
|
||||||
|
assertTrue(c.complete.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_error_appelle_onError_avec_runtimeexception() {
|
||||||
|
String sse =
|
||||||
|
"event:token\ndata:{\"token\":\"avant\"}\n\n" +
|
||||||
|
"event:error\ndata:{\"message\":\"PDF illisible\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertInstanceOf(RuntimeException.class, c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("PDF illisible"));
|
||||||
|
assertFalse(c.complete.get(), "onComplete non appelé après error terminal");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_error_data_non_json_relaie_data_brut() {
|
||||||
|
// readField : data non parsable -> catch -> renvoie data brut.
|
||||||
|
String sse = "event:error\ndata:panne-brute\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("panne-brute"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void flux_clos_sans_done_appelle_onComplete() {
|
||||||
|
// Pas de done/error -> terminated false -> onComplete de secours.
|
||||||
|
String sse = "event:token\ndata:{\"token\":\"x\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals("x", c.tokens.toString());
|
||||||
|
assertTrue(c.complete.get());
|
||||||
|
assertNull(c.error.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur_transport_traduite_en_runtimeexception() {
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientFailingWith(new RuntimeException("boom")));
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertInstanceOf(RuntimeException.class, c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("adaptation"));
|
||||||
|
assertFalse(c.complete.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filename_null_et_brief_null_et_messages_null_acceptes() {
|
||||||
|
// Couvre les branches : filename blank -> "campaign.pdf", brief null -> "",
|
||||||
|
// messagesJson null/blank -> "[]".
|
||||||
|
String sse = "event:done\ndata:{}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse), null, null, null);
|
||||||
|
|
||||||
|
assertTrue(c.complete.get());
|
||||||
|
assertNull(c.error.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void messages_blank_remplace_par_tableau_vide() {
|
||||||
|
String sse = "event:done\ndata:{}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse), " ", " ", " ");
|
||||||
|
|
||||||
|
assertTrue(c.complete.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,429 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignImportException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires PURS (JUnit 5, sans Spring ni réseau) pour {@link BrainCampaignImportClient}.
|
||||||
|
* <p>
|
||||||
|
* NB : contrairement à la consigne initiale, ce client est entièrement WebClient + SSE
|
||||||
|
* (POST /import/campaign/stream) — il n'y a PAS de RestTemplate ni d'appel one-shot.
|
||||||
|
* On injecte donc un WebClient.Builder dont l'ExchangeFunction renvoie un corps SSE
|
||||||
|
* canned (ou échoue), ce qui couvre {@code handleEvent} et tous les helpers de parsing.
|
||||||
|
*/
|
||||||
|
class BrainCampaignImportClientTest {
|
||||||
|
|
||||||
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
|
/** Construit un client dont le WebClient renvoie le corps SSE fourni. */
|
||||||
|
private BrainCampaignImportClient clientReturning(String sseBody) {
|
||||||
|
ExchangeFunction ef = req -> Mono.just(
|
||||||
|
ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sseBody)
|
||||||
|
.build());
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainCampaignImportClient(builder, MAPPER, "http://brain", 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Construit un client dont le transport échoue immédiatement (Mono.error). */
|
||||||
|
private BrainCampaignImportClient clientFailingWith(Throwable boom) {
|
||||||
|
ExchangeFunction ef = req -> Mono.error(boom);
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainCampaignImportClient(builder, MAPPER, "http://brain", 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Collecteur mutable réunissant tous les callbacks de l'import streamé. */
|
||||||
|
private static final class Collector {
|
||||||
|
final List<CampaignImportProgress> progresses = new ArrayList<>();
|
||||||
|
final AtomicInteger heartbeats = new AtomicInteger(0);
|
||||||
|
final List<String> statuses = new ArrayList<>();
|
||||||
|
final AtomicReference<CampaignImportProposal> done = new AtomicReference<>();
|
||||||
|
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||||
|
|
||||||
|
void invoke(BrainCampaignImportClient client) {
|
||||||
|
invoke(client, "campaign.pdf");
|
||||||
|
}
|
||||||
|
|
||||||
|
void invoke(BrainCampaignImportClient client, String filename) {
|
||||||
|
client.importCampaignStreaming(
|
||||||
|
new byte[]{1, 2, 3},
|
||||||
|
filename,
|
||||||
|
progresses::add,
|
||||||
|
heartbeats::incrementAndGet,
|
||||||
|
statuses::add,
|
||||||
|
done::set,
|
||||||
|
error::set);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- flux nominal : start -> progress -> done --------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streame_start_progress_done_construit_la_proposition() {
|
||||||
|
// SSE déclenchant start (page/ocr counts), progress (compteurs), puis done (arbre complet).
|
||||||
|
String sse =
|
||||||
|
"event:start\ndata:{\"total\":5,\"page_count\":12,\"ocr_page_count\":3}\n\n" +
|
||||||
|
"event:progress\ndata:{\"current\":2,\"total\":5,\"arc_count\":1,\"chapter_count\":2,\"scene_count\":4,\"npc_count\":6}\n\n" +
|
||||||
|
"event:done\ndata:" + doneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
// start : current=0, total=5, pageCount=12, ocrPageCount=3, reste 0.
|
||||||
|
assertEquals(2, c.progresses.size());
|
||||||
|
CampaignImportProgress start = c.progresses.get(0);
|
||||||
|
assertEquals(0, start.current());
|
||||||
|
assertEquals(5, start.total());
|
||||||
|
assertEquals(12, start.pageCount());
|
||||||
|
assertEquals(3, start.ocrPageCount());
|
||||||
|
|
||||||
|
// progress : compteurs propagés + pageCount/ocr mémorisés depuis start.
|
||||||
|
CampaignImportProgress prog = c.progresses.get(1);
|
||||||
|
assertEquals(2, prog.current());
|
||||||
|
assertEquals(5, prog.total());
|
||||||
|
assertEquals(12, prog.pageCount());
|
||||||
|
assertEquals(3, prog.ocrPageCount());
|
||||||
|
assertEquals(1, prog.arcCount());
|
||||||
|
assertEquals(2, prog.chapterCount());
|
||||||
|
assertEquals(4, prog.sceneCount());
|
||||||
|
assertEquals(6, prog.npcCount());
|
||||||
|
|
||||||
|
// done : arbre désérialisé (arcs/chapters/scenes/rooms + npcs).
|
||||||
|
CampaignImportProposal proposal = c.done.get();
|
||||||
|
assertNotNull(proposal);
|
||||||
|
assertEquals(1, proposal.arcs().size());
|
||||||
|
var arc = proposal.arcs().get(0);
|
||||||
|
assertEquals("Acte I", arc.name());
|
||||||
|
assertEquals("Mise en place", arc.description());
|
||||||
|
assertEquals("LINEAR", arc.type());
|
||||||
|
assertEquals(1, arc.chapters().size());
|
||||||
|
var chapter = arc.chapters().get(0);
|
||||||
|
assertEquals("Chapitre 1", chapter.name());
|
||||||
|
assertEquals(1, chapter.scenes().size());
|
||||||
|
var scene = chapter.scenes().get(0);
|
||||||
|
assertEquals("L'auberge", scene.name());
|
||||||
|
assertEquals("Lisez ceci", scene.playerNarration());
|
||||||
|
assertEquals("Secret MJ", scene.gmNotes());
|
||||||
|
assertEquals(1, scene.rooms().size());
|
||||||
|
var room = scene.rooms().get(0);
|
||||||
|
assertEquals("Cave", room.name());
|
||||||
|
assertEquals("2 gobelins", room.enemies());
|
||||||
|
assertEquals("50 po", room.loot());
|
||||||
|
assertEquals(1, proposal.npcs().size());
|
||||||
|
assertEquals("Thorin", proposal.npcs().get(0).name());
|
||||||
|
assertEquals("Nain bougon", proposal.npcs().get(0).description());
|
||||||
|
|
||||||
|
assertNull(c.error.get(), "aucune erreur sur un flux terminé par done");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String doneJson() {
|
||||||
|
return "{"
|
||||||
|
+ "\"arcs\":[{"
|
||||||
|
+ " \"name\":\"Acte I\",\"description\":\"Mise en place\",\"type\":\"LINEAR\","
|
||||||
|
+ " \"chapters\":[{"
|
||||||
|
+ " \"name\":\"Chapitre 1\",\"description\":\"intro\","
|
||||||
|
+ " \"scenes\":[{"
|
||||||
|
+ " \"name\":\"L'auberge\",\"description\":\"tendue\","
|
||||||
|
+ " \"player_narration\":\"Lisez ceci\",\"gm_notes\":\"Secret MJ\","
|
||||||
|
+ " \"rooms\":[{\"name\":\"Cave\",\"description\":\"sombre\",\"enemies\":\"2 gobelins\",\"loot\":\"50 po\"}]"
|
||||||
|
+ " }]"
|
||||||
|
+ " }]"
|
||||||
|
+ "}],"
|
||||||
|
+ "\"npcs\":[{\"name\":\"Thorin\",\"description\":\"Nain bougon\"}]"
|
||||||
|
+ "}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- events simples : heartbeat / status / chunk_failed / extracting
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_heartbeat_propage_le_keepalive() {
|
||||||
|
String sse =
|
||||||
|
"event:heartbeat\ndata:\n\n" +
|
||||||
|
"event:heartbeat\ndata:\n\n" +
|
||||||
|
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals(2, c.heartbeats.get());
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_status_relaie_le_message_lisible() {
|
||||||
|
String sse =
|
||||||
|
"event:status\ndata:{\"message\":\"Fournisseur saturé, nouvelle tentative\"}\n\n" +
|
||||||
|
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals(1, c.statuses.size());
|
||||||
|
assertEquals("Fournisseur saturé, nouvelle tentative", c.statuses.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_status_sans_champ_message_relaie_data_brut() {
|
||||||
|
// readMessage : pas de champ "message" -> renvoie la data brute.
|
||||||
|
String sse =
|
||||||
|
"event:status\ndata:texte-brut\n\n" +
|
||||||
|
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals("texte-brut", c.statuses.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_chunk_failed_compose_un_status_avec_compteurs_et_message() {
|
||||||
|
String sse =
|
||||||
|
"event:chunk_failed\ndata:{\"current\":3,\"total\":10,\"message\":\"timeout LLM\"}\n\n" +
|
||||||
|
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals("Morceau 3/10 ignoré : timeout LLM", c.statuses.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_chunk_failed_sans_message_termine_par_un_point() {
|
||||||
|
// Branche msg.isEmpty() -> suffixe "." au lieu de " : <msg>".
|
||||||
|
String sse =
|
||||||
|
"event:chunk_failed\ndata:{\"current\":1,\"total\":4}\n\n" +
|
||||||
|
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals("Morceau 1/4 ignoré.", c.statuses.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_chunk_failed_avec_json_invalide_donne_zero_zero() {
|
||||||
|
// data non-JSON -> readJson renvoie null -> current/total à 0, suffixe ".".
|
||||||
|
String sse =
|
||||||
|
"event:chunk_failed\ndata:pas-du-json\n\n" +
|
||||||
|
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals("Morceau 0/0 ignoré.", c.statuses.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_extracting_emet_un_progress_neutre() {
|
||||||
|
String sse =
|
||||||
|
"event:extracting\ndata:\n\n" +
|
||||||
|
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals(1, c.progresses.size());
|
||||||
|
CampaignImportProgress p = c.progresses.get(0);
|
||||||
|
assertEquals(0, p.current());
|
||||||
|
assertEquals(0, p.total());
|
||||||
|
assertEquals(0, p.pageCount());
|
||||||
|
assertEquals(0, p.npcCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String emptyDoneJson() {
|
||||||
|
return "{\"arcs\":[],\"npcs\":[]}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- event error (terminal) -------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_error_appelle_onError_et_n_appelle_pas_onDone() {
|
||||||
|
String sse =
|
||||||
|
"event:start\ndata:{\"total\":2,\"page_count\":1,\"ocr_page_count\":0}\n\n" +
|
||||||
|
"event:error\ndata:{\"message\":\"PDF illisible\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertInstanceOf(CampaignImportException.class, c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("PDF illisible"));
|
||||||
|
assertNull(c.done.get(), "onDone non appelé après un error terminal");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_error_sans_message_relaie_data_brut() {
|
||||||
|
String sse = "event:error\ndata:erreur-brute\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("erreur-brute"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- branches de robustesse du parsing --------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_inconnu_avec_data_non_json_est_ignore() {
|
||||||
|
// event non géré + data non-JSON -> readJson null -> return sans effet ;
|
||||||
|
// flux clos sans done -> branche d'interruption (onError).
|
||||||
|
String sse = "event:mystere\ndata:pas-du-json\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertTrue(c.progresses.isEmpty());
|
||||||
|
assertTrue(c.statuses.isEmpty());
|
||||||
|
assertNull(c.done.get());
|
||||||
|
assertNotNull(c.error.get(), "flux interrompu sans done/error -> onError");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void start_avec_champs_absents_utilise_les_valeurs_par_defaut() {
|
||||||
|
// JSON valide mais sans page_count/ocr/total -> path().asInt() == 0.
|
||||||
|
String sse =
|
||||||
|
"event:start\ndata:{}\n\n" +
|
||||||
|
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
CampaignImportProgress p = c.progresses.get(0);
|
||||||
|
assertEquals(0, p.total());
|
||||||
|
assertEquals(0, p.pageCount());
|
||||||
|
assertEquals(0, p.ocrPageCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void done_avec_arbre_vide_donne_une_proposition_vide() {
|
||||||
|
// Couvre toArcs/toNpcs sur des tableaux vides + text() sur champs absents.
|
||||||
|
String sse = "event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
assertTrue(c.done.get().arcs().isEmpty());
|
||||||
|
assertTrue(c.done.get().npcs().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void done_avec_arc_sans_chapitres_et_npc_sans_description() {
|
||||||
|
// toChapters sur noeud absent (path -> MissingNode, non-array) -> liste vide ;
|
||||||
|
// text() sur "description" absent -> "".
|
||||||
|
String sse = "event:done\ndata:{"
|
||||||
|
+ "\"arcs\":[{\"name\":\"Solo\"}],"
|
||||||
|
+ "\"npcs\":[{\"name\":\"Anon\"}]"
|
||||||
|
+ "}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
var proposal = c.done.get();
|
||||||
|
assertNotNull(proposal);
|
||||||
|
var arc = proposal.arcs().get(0);
|
||||||
|
assertEquals("Solo", arc.name());
|
||||||
|
assertEquals("", arc.description());
|
||||||
|
assertEquals("", arc.type());
|
||||||
|
assertTrue(arc.chapters().isEmpty());
|
||||||
|
assertEquals("Anon", proposal.npcs().get(0).name());
|
||||||
|
assertEquals("", proposal.npcs().get(0).description());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void done_avec_champ_explicitement_null_donne_chaine_vide() {
|
||||||
|
// text() : valeur JSON null -> "" (branche v.isNull()).
|
||||||
|
String sse = "event:done\ndata:{"
|
||||||
|
+ "\"arcs\":[{\"name\":null,\"description\":\"d\"}],"
|
||||||
|
+ "\"npcs\":[]"
|
||||||
|
+ "}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertEquals("", c.done.get().arcs().get(0).name());
|
||||||
|
assertEquals("d", c.done.get().arcs().get(0).description());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- fin de flux sans terminaison -------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void flux_clos_sans_done_ni_error_appelle_onError() {
|
||||||
|
// terminated reste false -> branche "Le flux d'import s'est interrompu...".
|
||||||
|
String sse = "event:progress\ndata:{\"current\":1,\"total\":3}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNull(c.done.get());
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertInstanceOf(CampaignImportException.class, c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("interrompu"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- erreur de transport ----------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur_transport_traduite_en_CampaignImportException() {
|
||||||
|
// Mono.error -> blockLast lève -> branche catch, expose type + message de la cause.
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientFailingWith(new RuntimeException("connexion coupée")));
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertInstanceOf(CampaignImportException.class, c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("streaming d'import"));
|
||||||
|
assertTrue(c.error.get().getMessage().contains("connexion coupée"));
|
||||||
|
assertNull(c.done.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur_transport_sans_message_reste_geree() {
|
||||||
|
// Cause sans message -> branche getMessage() == null (pas de " — ...").
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientFailingWith(new RuntimeException()));
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertInstanceOf(CampaignImportException.class, c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("streaming d'import"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur_transport_apres_event_error_ne_double_pas_le_callback() {
|
||||||
|
// error terminal puis le flux se clôt : terminated[0]==true -> pas de second onError.
|
||||||
|
// (vérifie que le callback n'est appelé qu'une fois via le message attendu.)
|
||||||
|
String sse = "event:error\ndata:{\"message\":\"stop\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("stop"));
|
||||||
|
assertFalse(c.error.get().getMessage().contains("interrompu"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- nom de fichier ---------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filename_null_ou_blanc_est_accepte() {
|
||||||
|
// Couvre la branche de repli "campaign.pdf" dans filePart + part().filename().
|
||||||
|
String sse = "event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||||
|
Collector c1 = new Collector();
|
||||||
|
c1.invoke(clientReturning(sse), null);
|
||||||
|
assertNotNull(c1.done.get());
|
||||||
|
|
||||||
|
Collector c2 = new Collector();
|
||||||
|
c2.invoke(clientReturning(sse), " ");
|
||||||
|
assertNotNull(c2.done.get());
|
||||||
|
|
||||||
|
Collector c3 = new Collector();
|
||||||
|
c3.invoke(clientReturning(sse), "mon-livre.pdf");
|
||||||
|
assertNotNull(c3.done.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,12 +7,21 @@ import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSu
|
|||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||||
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.CampaignStructuralContext.CharacterSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.NpcSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.RoomBranchHint;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.RoomSummary;
|
||||||
|
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.LoreStructuralContext.PageSummary;
|
import com.loremind.domain.generationcontext.LoreStructuralContext.PageSummary;
|
||||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||||
import com.loremind.domain.generationcontext.PageContext;
|
import com.loremind.domain.generationcontext.PageContext;
|
||||||
|
import com.loremind.domain.generationcontext.SessionContext;
|
||||||
|
import com.loremind.domain.generationcontext.SessionContext.JournalEntrySummary;
|
||||||
|
import com.loremind.domain.generationcontext.SessionContext.QuestSummary;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -165,7 +174,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
BranchHint branch = new BranchHint("fuite", "La poursuite", "HP < 50%");
|
BranchHint branch = new BranchHint("fuite", "La poursuite", "HP < 50%");
|
||||||
SceneSummary scene = new SceneSummary("L'auberge", "Rencontre tendue", 3, List.of(branch), List.of());
|
SceneSummary scene = new SceneSummary("L'auberge", "Rencontre tendue", 3, List.of(branch), List.of());
|
||||||
ChapterSummary chapter = new ChapterSummary("L'arrivee", "...", 0, List.of(scene));
|
ChapterSummary chapter = new ChapterSummary("L'arrivee", "...", 0, List.of(scene));
|
||||||
ArcSummary arc = new ArcSummary("Acte I", "Mise en place", 1, List.of(chapter));
|
ArcSummary arc = new ArcSummary("Acte I", "Mise en place", false, 1, List.of(chapter));
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"Les Ombres", "dark fantasy", List.of(arc), List.of(), List.of());
|
"Les Ombres", "dark fantasy", List.of(arc), List.of(), List.of());
|
||||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
@@ -198,7 +207,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
@Test
|
@Test
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
void build_arcSummary_omitsIllustrationCount_whenZero() {
|
void build_arcSummary_omitsIllustrationCount_whenZero() {
|
||||||
ArcSummary arc = new ArcSummary("A", "", 0, List.of());
|
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of());
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"X", "", List.of(arc), List.of(), List.of());
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
@@ -215,7 +224,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
void build_sceneSummary_omitsBranches_whenEmpty() {
|
void build_sceneSummary_omitsBranches_whenEmpty() {
|
||||||
SceneSummary scene = new SceneSummary("S", "", 0, List.of(), List.of());
|
SceneSummary scene = new SceneSummary("S", "", 0, List.of(), List.of());
|
||||||
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||||
ArcSummary arc = new ArcSummary("A", "", 0, List.of(chapter));
|
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of(chapter));
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"X", "", List.of(arc), List.of(), List.of());
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
@@ -234,7 +243,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
BranchHint branch = new BranchHint("X", "Y", " ");
|
BranchHint branch = new BranchHint("X", "Y", " ");
|
||||||
SceneSummary scene = new SceneSummary("S", "", 0, List.of(branch), List.of());
|
SceneSummary scene = new SceneSummary("S", "", 0, List.of(branch), List.of());
|
||||||
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||||
ArcSummary arc = new ArcSummary("A", "", 0, List.of(chapter));
|
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of(chapter));
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"X", "", List.of(arc), List.of(), List.of());
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
@@ -284,4 +293,252 @@ class BrainChatPayloadBuilderTest {
|
|||||||
assertFalse(payload.containsKey("lore_context"));
|
assertFalse(payload.containsKey("lore_context"));
|
||||||
assertFalse(payload.containsKey("page_context"));
|
assertFalse(payload.containsKey("page_context"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- arc HUB + characters/npcs ----------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_arcHub_injecteArcTypeHub() {
|
||||||
|
// arc.hub() == true -> ajoute "arc_type":"HUB" (vocabulaire « quêtes »).
|
||||||
|
ArcSummary arc = new ArcSummary("Hub central", "", true, 0, List.of());
|
||||||
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
|
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||||
|
assertEquals("HUB", arcMap.get("arc_type"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_arcLineaire_n_injectePasArcType() {
|
||||||
|
ArcSummary arc = new ArcSummary("Lineaire", "", false, 0, List.of());
|
||||||
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
|
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||||
|
assertFalse(arcMap.containsKey("arc_type"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_campaignContext_serialiseCharactersEtNpcs_avecOmissionSnippetBlank() {
|
||||||
|
// snippet renseigné -> présent ; snippet blank/null -> omis.
|
||||||
|
CharacterSummary pj1 = new CharacterSummary("Aria", "Magicienne elfe");
|
||||||
|
CharacterSummary pj2 = new CharacterSummary("Bran", " ");
|
||||||
|
NpcSummary pnj1 = new NpcSummary("Garde", "Sentinelle bourrue");
|
||||||
|
NpcSummary pnj2 = new NpcSummary("Mendiant", null);
|
||||||
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
|
"X", "", List.of(), List.of(pj1, pj2), List.of(pnj1, pnj2));
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
|
Map<String, Object> cctx = asMap(builder.build(req).get("campaign_context"));
|
||||||
|
List<Map<String, Object>> chars = (List<Map<String, Object>>) cctx.get("characters");
|
||||||
|
assertEquals("Aria", chars.get(0).get("name"));
|
||||||
|
assertTrue(chars.get(0).containsKey("snippet"));
|
||||||
|
assertFalse(chars.get(1).containsKey("snippet"), "snippet blank omis");
|
||||||
|
|
||||||
|
List<Map<String, Object>> npcs = (List<Map<String, Object>>) cctx.get("npcs");
|
||||||
|
assertEquals("Garde", npcs.get(0).get("name"));
|
||||||
|
assertTrue(npcs.get(0).containsKey("snippet"));
|
||||||
|
assertFalse(npcs.get(1).containsKey("snippet"), "snippet null omis");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- rooms d'une scène ------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_sceneRooms_serialiseTousLesChampsEtBranchesEntrePieces() {
|
||||||
|
RoomBranchHint exit = new RoomBranchHint("porte nord", "Salle du trone", "clé en main");
|
||||||
|
RoomSummary room = new RoomSummary("Hall", 1, "Vaste entrée", "Spectres", List.of(exit));
|
||||||
|
SceneSummary scene = new SceneSummary("Donjon", "", 0, List.of(), List.of(room));
|
||||||
|
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||||
|
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of(chapter));
|
||||||
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
|
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||||
|
Map<String, Object> sceneMap = firstOf(firstOf(arcMap, "chapters"), "scenes");
|
||||||
|
Map<String, Object> roomMap = firstOf(sceneMap, "rooms");
|
||||||
|
|
||||||
|
assertEquals("Hall", roomMap.get("name"));
|
||||||
|
assertEquals(1, roomMap.get("floor"));
|
||||||
|
assertEquals("Vaste entrée", roomMap.get("description"));
|
||||||
|
assertEquals("Spectres", roomMap.get("enemies"));
|
||||||
|
Map<String, Object> branchMap = firstOf(roomMap, "branches");
|
||||||
|
assertEquals("porte nord", branchMap.get("label"));
|
||||||
|
assertEquals("Salle du trone", branchMap.get("target_room_name"));
|
||||||
|
assertEquals("clé en main", branchMap.get("condition"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_sceneRooms_ometLesChampsOptionnelsVides() {
|
||||||
|
// floor null, description/enemies blank, condition blank, branches non vides.
|
||||||
|
RoomBranchHint exit = new RoomBranchHint("sortie", "Autre", " ");
|
||||||
|
RoomSummary room = new RoomSummary("Cellule", null, " ", " ", List.of(exit));
|
||||||
|
SceneSummary scene = new SceneSummary("Donjon", "", 0, List.of(), List.of(room));
|
||||||
|
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||||
|
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of(chapter));
|
||||||
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
|
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||||
|
Map<String, Object> sceneMap = firstOf(firstOf(arcMap, "chapters"), "scenes");
|
||||||
|
Map<String, Object> roomMap = firstOf(sceneMap, "rooms");
|
||||||
|
|
||||||
|
assertFalse(roomMap.containsKey("floor"));
|
||||||
|
assertFalse(roomMap.containsKey("description"));
|
||||||
|
assertFalse(roomMap.containsKey("enemies"));
|
||||||
|
Map<String, Object> branchMap = firstOf(roomMap, "branches");
|
||||||
|
assertFalse(branchMap.containsKey("condition"), "condition blank omise");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_sceneRooms_omisesSiListeVide() {
|
||||||
|
// s.rooms() vide -> clé "rooms" absente.
|
||||||
|
SceneSummary scene = new SceneSummary("Lineaire", "", 0, List.of(), List.of());
|
||||||
|
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||||
|
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of(chapter));
|
||||||
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
|
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||||
|
Map<String, Object> sceneMap = firstOf(firstOf(arcMap, "chapters"), "scenes");
|
||||||
|
assertFalse(sceneMap.containsKey("rooms"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- game_system_context ----------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_gameSystemContext_completInclutDescriptionEtSections() {
|
||||||
|
GameSystemContext gs = new GameSystemContext(
|
||||||
|
"Nimble", "JDR rapide", Map.of("Combat", "Lancez 1d20"));
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).gameSystemContext(gs).build();
|
||||||
|
|
||||||
|
Map<String, Object> gsm = asMap(builder.build(req).get("game_system_context"));
|
||||||
|
assertEquals("Nimble", gsm.get("system_name"));
|
||||||
|
assertEquals("JDR rapide", gsm.get("system_description"));
|
||||||
|
assertEquals(Map.of("Combat", "Lancez 1d20"), gsm.get("sections"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_gameSystemContext_descriptionBlankEtSectionsNull() {
|
||||||
|
// systemDescription blank -> omis ; sections null -> Map.of() de repli.
|
||||||
|
GameSystemContext gs = new GameSystemContext("D&D 5.1", " ", null);
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).gameSystemContext(gs).build();
|
||||||
|
|
||||||
|
Map<String, Object> gsm = asMap(builder.build(req).get("game_system_context"));
|
||||||
|
assertEquals("D&D 5.1", gsm.get("system_name"));
|
||||||
|
assertFalse(gsm.containsKey("system_description"));
|
||||||
|
assertEquals(Map.of(), gsm.get("sections"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- session_context --------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_sessionContext_complet_inclutToutesLesListesPeuplees() {
|
||||||
|
LocalDateTime now = LocalDateTime.of(2026, 6, 14, 20, 0);
|
||||||
|
JournalEntrySummary entry = new JournalEntrySummary(
|
||||||
|
"combat", "Le dragon attaque", now, null);
|
||||||
|
JournalEntrySummary prev = new JournalEntrySummary(
|
||||||
|
"info", "Le roi est mort", now, "Session 1");
|
||||||
|
QuestSummary avail = new QuestSummary("Sauver le village", "Acte I", "Urgence");
|
||||||
|
QuestSummary inProg = new QuestSummary("Trouver l'épée", "Acte II", " ");
|
||||||
|
SessionContext sc = new SessionContext(
|
||||||
|
"Session 2", true, now,
|
||||||
|
List.of(entry), List.of(prev),
|
||||||
|
List.of(avail), List.of(inProg),
|
||||||
|
List.of("Quête secrète"), List.of("porte_ouverte"));
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).sessionContext(sc).build();
|
||||||
|
|
||||||
|
Map<String, Object> scm = asMap(builder.build(req).get("session_context"));
|
||||||
|
assertEquals("Session 2", scm.get("session_name"));
|
||||||
|
assertEquals(true, scm.get("active"));
|
||||||
|
assertEquals(now.toString(), scm.get("started_at"));
|
||||||
|
|
||||||
|
// entries : type/content/occurredAt présents, source omis (null) sur l'entrée courante.
|
||||||
|
Map<String, Object> entryMap = firstOf(scm, "entries");
|
||||||
|
assertEquals("combat", entryMap.get("type"));
|
||||||
|
assertEquals("Le dragon attaque", entryMap.get("content"));
|
||||||
|
assertEquals(now.toString(), entryMap.get("occurred_at"));
|
||||||
|
assertFalse(entryMap.containsKey("source_session_name"));
|
||||||
|
|
||||||
|
// previous_events : source renseignée.
|
||||||
|
Map<String, Object> prevMap = firstOf(scm, "previous_events");
|
||||||
|
assertEquals("Session 1", prevMap.get("source_session_name"));
|
||||||
|
|
||||||
|
// available_quests : description renseignée ; in_progress : description blank omise.
|
||||||
|
Map<String, Object> availMap = firstOf(scm, "available_quests");
|
||||||
|
assertEquals("Sauver le village", availMap.get("name"));
|
||||||
|
assertEquals("Acte I", availMap.get("arc_name"));
|
||||||
|
assertEquals("Urgence", availMap.get("description"));
|
||||||
|
Map<String, Object> inProgMap = firstOf(scm, "in_progress_quests");
|
||||||
|
assertFalse(inProgMap.containsKey("description"), "description blank omise");
|
||||||
|
|
||||||
|
assertEquals(List.of("Quête secrète"), scm.get("locked_quest_titles"));
|
||||||
|
assertEquals(List.of("porte_ouverte"), scm.get("active_flags"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void build_sessionContext_minimal_ometListesVidesEtChampsNull() {
|
||||||
|
// startedAt null -> omis ; entries null -> List.of() ; toutes les autres listes
|
||||||
|
// vides/null -> clés absentes.
|
||||||
|
SessionContext sc = new SessionContext(
|
||||||
|
"Session vide", false, null,
|
||||||
|
null, List.of(),
|
||||||
|
List.of(), List.of(),
|
||||||
|
List.of(), List.of());
|
||||||
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).sessionContext(sc).build();
|
||||||
|
|
||||||
|
Map<String, Object> scm = asMap(builder.build(req).get("session_context"));
|
||||||
|
assertEquals("Session vide", scm.get("session_name"));
|
||||||
|
assertEquals(false, scm.get("active"));
|
||||||
|
assertFalse(scm.containsKey("started_at"));
|
||||||
|
assertEquals(List.of(), scm.get("entries"));
|
||||||
|
assertFalse(scm.containsKey("previous_events"));
|
||||||
|
assertFalse(scm.containsKey("available_quests"));
|
||||||
|
assertFalse(scm.containsKey("in_progress_quests"));
|
||||||
|
assertFalse(scm.containsKey("locked_quest_titles"));
|
||||||
|
assertFalse(scm.containsKey("active_flags"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- tous les contextes présents simultanément ------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void build_tousLesContextes_sontTousPresents() {
|
||||||
|
LoreStructuralContext lore = new LoreStructuralContext("L", "", Map.of(), List.of());
|
||||||
|
PageContext page = new PageContext("P", "T", List.of(), Map.of());
|
||||||
|
CampaignStructuralContext camp = new CampaignStructuralContext("C", "", List.of(), List.of(), List.of());
|
||||||
|
NarrativeEntityContext entity = new NarrativeEntityContext("scene", "S", Map.of());
|
||||||
|
GameSystemContext gs = new GameSystemContext("G", null, Map.of());
|
||||||
|
SessionContext sc = new SessionContext("Sess", true, null, List.of(), List.of(),
|
||||||
|
List.of(), List.of(), List.of(), List.of());
|
||||||
|
ChatRequest req = ChatRequest.builder()
|
||||||
|
.messages(sampleMessages)
|
||||||
|
.loreContext(lore)
|
||||||
|
.pageContext(page)
|
||||||
|
.campaignContext(camp)
|
||||||
|
.narrativeEntity(entity)
|
||||||
|
.gameSystemContext(gs)
|
||||||
|
.sessionContext(sc)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Map<String, Object> payload = builder.build(req);
|
||||||
|
assertTrue(payload.containsKey("lore_context"));
|
||||||
|
assertTrue(payload.containsKey("page_context"));
|
||||||
|
assertTrue(payload.containsKey("campaign_context"));
|
||||||
|
assertTrue(payload.containsKey("narrative_entity"));
|
||||||
|
assertTrue(payload.containsKey("game_system_context"));
|
||||||
|
assertTrue(payload.containsKey("session_context"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires purs (JUnit 5, sans Spring, sans réseau) de
|
||||||
|
* {@link BrainConversationTitleClient}.
|
||||||
|
*
|
||||||
|
* Principe : on injecte un WebClient.Builder préconfiguré avec une
|
||||||
|
* ExchangeFunction mock qui renvoie des réponses canned -> aucun appel réseau.
|
||||||
|
*/
|
||||||
|
class BrainConversationTitleClientTest {
|
||||||
|
|
||||||
|
private static final String FALLBACK = "Nouvelle conversation";
|
||||||
|
|
||||||
|
/** Construit un client dont le WebClient répond avec la réponse fournie. */
|
||||||
|
private BrainConversationTitleClient clientReturning(ClientResponse response) {
|
||||||
|
ExchangeFunction ef = req -> Mono.just(response);
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainConversationTitleClient(builder, "http://brain");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Construit un client dont le WebClient émet une erreur transport. */
|
||||||
|
private BrainConversationTitleClient clientErroring() {
|
||||||
|
ExchangeFunction ef = req -> Mono.error(new RuntimeException("boom"));
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainConversationTitleClient(builder, "http://brain");
|
||||||
|
}
|
||||||
|
|
||||||
|
private ClientResponse jsonOk(String body) {
|
||||||
|
return ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
.body(body)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ConversationMessage msg(String role, String content) {
|
||||||
|
return ConversationMessage.builder().role(role).content(content).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void liste_null_renvoie_fallback() {
|
||||||
|
// Pas besoin d'appel réseau : court-circuit sur entrée null.
|
||||||
|
BrainConversationTitleClient client = clientErroring();
|
||||||
|
assertThat(client.generate(null)).isEqualTo(FALLBACK);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void liste_vide_renvoie_fallback() {
|
||||||
|
BrainConversationTitleClient client = clientErroring();
|
||||||
|
assertThat(client.generate(List.of())).isEqualTo(FALLBACK);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reponse_ok_avec_titre_renvoie_le_titre() {
|
||||||
|
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\"Mon titre\"}"));
|
||||||
|
String result = client.generate(List.of(msg("user", "Salut")));
|
||||||
|
assertThat(result).isEqualTo("Mon titre");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void titre_avec_espaces_est_trimme() {
|
||||||
|
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\" Espacé \"}"));
|
||||||
|
String result = client.generate(List.of(msg("user", "Bonjour")));
|
||||||
|
assertThat(result).isEqualTo("Espacé");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void contenu_message_null_traite_sans_npe() {
|
||||||
|
// content null -> mappé en "" dans le payload, ne doit pas lever.
|
||||||
|
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\"Ok\"}"));
|
||||||
|
String result = client.generate(List.of(msg("assistant", null)));
|
||||||
|
assertThat(result).isEqualTo("Ok");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void titre_absent_renvoie_fallback() {
|
||||||
|
BrainConversationTitleClient client = clientReturning(jsonOk("{\"autre\":\"x\"}"));
|
||||||
|
String result = client.generate(List.of(msg("user", "Hello")));
|
||||||
|
assertThat(result).isEqualTo(FALLBACK);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void titre_vide_renvoie_fallback() {
|
||||||
|
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\"\"}"));
|
||||||
|
String result = client.generate(List.of(msg("user", "Hello")));
|
||||||
|
assertThat(result).isEqualTo(FALLBACK);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void titre_blanc_renvoie_fallback() {
|
||||||
|
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\" \"}"));
|
||||||
|
String result = client.generate(List.of(msg("user", "Hello")));
|
||||||
|
assertThat(result).isEqualTo(FALLBACK);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void corps_json_vide_renvoie_fallback() {
|
||||||
|
// Map décodée non null mais sans clé "title".
|
||||||
|
BrainConversationTitleClient client = clientReturning(jsonOk("{}"));
|
||||||
|
String result = client.generate(List.of(msg("user", "Hello")));
|
||||||
|
assertThat(result).isEqualTo(FALLBACK);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur_transport_renvoie_fallback() {
|
||||||
|
BrainConversationTitleClient client = clientErroring();
|
||||||
|
String result = client.generate(List.of(msg("user", "Hello")));
|
||||||
|
assertThat(result).isEqualTo(FALLBACK);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reponse_500_renvoie_fallback() {
|
||||||
|
ClientResponse err = ClientResponse.create(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
.body("{\"error\":\"down\"}")
|
||||||
|
.build();
|
||||||
|
BrainConversationTitleClient client = clientReturning(err);
|
||||||
|
String result = client.generate(List.of(msg("user", "Hello")));
|
||||||
|
assertThat(result).isEqualTo(FALLBACK);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
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.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires des DTOs wire de l'Adapter IA :
|
||||||
|
* - BrainGeneratePageRequest (record envoye au Brain) ;
|
||||||
|
* - BrainGeneratePageResponse (@Data/@NoArgsConstructor recu du Brain).
|
||||||
|
* On instancie et on appelle les accesseurs pour couvrir le code genere.
|
||||||
|
*/
|
||||||
|
class BrainGeneratePageRequestTest {
|
||||||
|
|
||||||
|
// --- BrainGeneratePageRequest -------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void request_accesseursExposentLesChamps() {
|
||||||
|
BrainGeneratePageRequest req = new BrainGeneratePageRequest(
|
||||||
|
"Aetheria",
|
||||||
|
"Un monde de cendres",
|
||||||
|
"PNJ",
|
||||||
|
"Fiche personnage",
|
||||||
|
List.of("histoire", "motto"),
|
||||||
|
"Garde rouge"
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals("Aetheria", req.loreName());
|
||||||
|
assertEquals("Un monde de cendres", req.loreDescription());
|
||||||
|
assertEquals("PNJ", req.folderName());
|
||||||
|
assertEquals("Fiche personnage", req.templateName());
|
||||||
|
assertEquals(List.of("histoire", "motto"), req.templateFields());
|
||||||
|
assertEquals("Garde rouge", req.pageTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void request_egaliteStructurelleEtToString() {
|
||||||
|
BrainGeneratePageRequest a = new BrainGeneratePageRequest(
|
||||||
|
"n", "d", "f", "t", List.of("x"), "p");
|
||||||
|
BrainGeneratePageRequest b = new BrainGeneratePageRequest(
|
||||||
|
"n", "d", "f", "t", List.of("x"), "p");
|
||||||
|
BrainGeneratePageRequest c = new BrainGeneratePageRequest(
|
||||||
|
"AUTRE", "d", "f", "t", List.of("x"), "p");
|
||||||
|
|
||||||
|
assertEquals(a, b);
|
||||||
|
assertEquals(a.hashCode(), b.hashCode());
|
||||||
|
assertNotEquals(a, c);
|
||||||
|
// toString genere : on verifie juste qu'il est non vide et contient un champ
|
||||||
|
org.junit.jupiter.api.Assertions.assertTrue(a.toString().contains("n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- BrainGeneratePageResponse ------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void response_setterEtGetterValues() {
|
||||||
|
BrainGeneratePageResponse resp = new BrainGeneratePageResponse();
|
||||||
|
assertNull(resp.getValues());
|
||||||
|
|
||||||
|
Map<String, String> values = Map.of("histoire", "Nee sous une etoile rouge");
|
||||||
|
resp.setValues(values);
|
||||||
|
|
||||||
|
assertEquals(values, resp.getValues());
|
||||||
|
assertEquals("Nee sous une etoile rouge", resp.getValues().get("histoire"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void response_egaliteEtToStringGeneresParLombok() {
|
||||||
|
BrainGeneratePageResponse a = new BrainGeneratePageResponse();
|
||||||
|
a.setValues(Map.of("f", "v"));
|
||||||
|
BrainGeneratePageResponse b = new BrainGeneratePageResponse();
|
||||||
|
b.setValues(Map.of("f", "v"));
|
||||||
|
BrainGeneratePageResponse c = new BrainGeneratePageResponse();
|
||||||
|
c.setValues(Map.of("f", "AUTRE"));
|
||||||
|
|
||||||
|
assertEquals(a, b);
|
||||||
|
assertEquals(a.hashCode(), b.hashCode());
|
||||||
|
assertNotEquals(a, c);
|
||||||
|
org.junit.jupiter.api.Assertions.assertTrue(a.toString().contains("values"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerationException;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerator.GeneratedCatalog;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.client.HttpServerErrorException;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring) de {@link BrainItemCatalogClient}.
|
||||||
|
* Le RestTemplate est mocké : {@code postForObject(url, entity, Map.class)}.
|
||||||
|
*/
|
||||||
|
class BrainItemCatalogClientTest {
|
||||||
|
|
||||||
|
private RestTemplate rt;
|
||||||
|
private BrainItemCatalogClient client;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
rt = mock(RestTemplate.class);
|
||||||
|
client = new BrainItemCatalogClient(rt, "http://brain");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Construit une map d'objet pour le payload "items". */
|
||||||
|
private static Map<String, Object> item(Object name, Object price, Object category, Object description) {
|
||||||
|
Map<String, Object> m = new LinkedHashMap<>();
|
||||||
|
m.put("name", name);
|
||||||
|
m.put("price", price);
|
||||||
|
m.put("category", category);
|
||||||
|
m.put("description", description);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- generate : cas nominal et mapping ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_reponseValide_mappeItems_etIgnoreInvalides() {
|
||||||
|
List<Object> items = new ArrayList<>();
|
||||||
|
items.add(item("Épée longue", "15 po", "Armes", "Tranchante")); // valide
|
||||||
|
items.add(item("Potion", null, null, null)); // valide, champs null
|
||||||
|
items.add(item(null, "1 po", "x", "y")); // ignoré : name null
|
||||||
|
items.add(item(" ", "1 po", "x", "y")); // ignoré : name blank
|
||||||
|
items.add("pas une map"); // ignoré : item non-Map
|
||||||
|
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("name", "Boutique du forgeron");
|
||||||
|
resp.put("description", "Au village");
|
||||||
|
resp.put("items", items);
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
GeneratedCatalog cat = client.generate("desc", "ctx");
|
||||||
|
|
||||||
|
assertEquals("Boutique du forgeron", cat.name());
|
||||||
|
assertEquals("Au village", cat.description());
|
||||||
|
assertEquals(2, cat.items().size());
|
||||||
|
|
||||||
|
CatalogItem i0 = cat.items().get(0);
|
||||||
|
assertEquals("Épée longue", i0.getName());
|
||||||
|
assertEquals("15 po", i0.getPrice());
|
||||||
|
assertEquals("Armes", i0.getCategory());
|
||||||
|
assertEquals("Tranchante", i0.getDescription());
|
||||||
|
|
||||||
|
CatalogItem i1 = cat.items().get(1);
|
||||||
|
assertEquals("Potion", i1.getName());
|
||||||
|
assertNull(i1.getPrice());
|
||||||
|
assertNull(i1.getCategory());
|
||||||
|
assertNull(i1.getDescription());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_nameAbsent_fallbackSurDescription() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("items", List.of(item("Objet", null, null, null)));
|
||||||
|
// pas de "name" -> fallback description
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
GeneratedCatalog cat = client.generate("MaDescription", "ctx");
|
||||||
|
assertEquals("MaDescription", cat.name());
|
||||||
|
assertNull(cat.description());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_nameBlank_fallbackSurDescription() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("name", " ");
|
||||||
|
resp.put("items", List.of(item("Objet", null, null, null)));
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
GeneratedCatalog cat = client.generate("Fallback", "ctx");
|
||||||
|
assertEquals("Fallback", cat.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_argumentsNull_remplisParDefauts() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("name", "Cat");
|
||||||
|
resp.put("items", List.of(item("Objet", null, null, null)));
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
GeneratedCatalog cat = client.generate(null, null);
|
||||||
|
assertEquals("Cat", cat.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- generate : réponse vide / pas d'items ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_reponseNull_leveException() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(null);
|
||||||
|
|
||||||
|
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||||
|
() -> client.generate("d", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("réponse vide"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_itemsAbsents_leveException() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("name", "Cat"); // pas de "items"
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||||
|
() -> client.generate("d", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("Aucun objet"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_itemsVide_leveException() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("items", new ArrayList<>());
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
assertThrows(ItemCatalogGenerationException.class, () -> client.generate("d", "c"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_tousItemsInvalides_leveException() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("items", List.of(item(null, null, null, null)));
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
assertThrows(ItemCatalogGenerationException.class, () -> client.generate("d", "c"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- generate : branches du catch ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_brainInjoignable_resourceAccess() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||||
|
.thenThrow(new ResourceAccessException("down"));
|
||||||
|
|
||||||
|
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||||
|
() -> client.generate("d", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("injoignable"));
|
||||||
|
assertInstanceOf(ResourceAccessException.class, ex.getCause());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_erreurHttp_restClientResponse() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||||
|
.thenThrow(HttpServerErrorException.create(
|
||||||
|
HttpStatus.BAD_GATEWAY, "Bad Gateway", new HttpHeaders(), new byte[0], null));
|
||||||
|
|
||||||
|
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||||
|
() -> client.generate("d", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("HTTP 502"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_erreurInattendue_exceptionGenerique() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||||
|
.thenThrow(new IllegalStateException("boom"));
|
||||||
|
|
||||||
|
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||||
|
() -> client.generate("d", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("inattendue"));
|
||||||
|
assertInstanceOf(IllegalStateException.class, ex.getCause());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.mock.http.client.reactive.MockClientHttpRequest;
|
||||||
|
import org.springframework.util.MultiValueMap;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeStrategies;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Couvre les sous-classes anonymes {@code new ByteArrayResource(){ getFilename() }}
|
||||||
|
* des clients d'upload multipart : leur {@code getFilename()} (nom par défaut si
|
||||||
|
* absent/vide) n'est appelé que lors de la SÉRIALISATION du corps, qui n'a pas lieu
|
||||||
|
* quand le transport est mocké. On la déclenche donc explicitement :
|
||||||
|
* <ul>
|
||||||
|
* <li>clients RestTemplate : on capture le {@link HttpEntity} envoyé et on lit la
|
||||||
|
* ressource « file » pour appeler {@code getFilename()} ;</li>
|
||||||
|
* <li>clients WebClient : l'{@link ExchangeFunction} sérialise réellement le corps
|
||||||
|
* multipart dans un {@link MockClientHttpRequest} (ce qui invoque getFilename).</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
class BrainMultipartFilenameTest {
|
||||||
|
|
||||||
|
// --- Helpers ------------------------------------------------------------
|
||||||
|
|
||||||
|
/** ExchangeFunction qui sérialise le corps de la requête (déclenche getFilename) puis renvoie un SSE 'done'. */
|
||||||
|
private static ExchangeFunction serializingExchange(String sse) {
|
||||||
|
return request -> {
|
||||||
|
MockClientHttpRequest mock = new MockClientHttpRequest(request.method(), request.url());
|
||||||
|
// Le write-handler par défaut ne souscrit pas au corps : on draine donc le
|
||||||
|
// flux nous-mêmes pour forcer l'écriture des parts (et l'appel à getFilename).
|
||||||
|
mock.setWriteHandler(body -> DataBufferUtils.join(body)
|
||||||
|
.doOnNext(DataBufferUtils::release).then());
|
||||||
|
request.writeTo(mock, ExchangeStrategies.withDefaults()).block();
|
||||||
|
return Mono.just(ClientResponse.create(org.springframework.http.HttpStatus.OK)
|
||||||
|
.header(org.springframework.http.HttpHeaders.CONTENT_TYPE,
|
||||||
|
org.springframework.http.MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sse)
|
||||||
|
.build());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static String capturedFilename(RestTemplate rt) {
|
||||||
|
ArgumentCaptor<HttpEntity> cap = ArgumentCaptor.forClass(HttpEntity.class);
|
||||||
|
verify(rt).postForObject(anyString(), cap.capture(), any());
|
||||||
|
MultiValueMap<String, Object> body = (MultiValueMap<String, Object>) cap.getValue().getBody();
|
||||||
|
return ((Resource) body.getFirst("file")).getFilename();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- BrainNotebookIndexClient (RestTemplate) ----------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void notebookIndex_filePart_usesGivenFilename_elseDefault() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainNotebookIndexClient client = new BrainNotebookIndexClient(rt, "http://brain");
|
||||||
|
|
||||||
|
try { client.index("src-1", new byte[]{1, 2}, "doc.pdf"); } catch (RuntimeException ignored) { }
|
||||||
|
assertEquals("doc.pdf", capturedFilename(rt));
|
||||||
|
|
||||||
|
RestTemplate rt2 = mock(RestTemplate.class);
|
||||||
|
BrainNotebookIndexClient client2 = new BrainNotebookIndexClient(rt2, "http://brain");
|
||||||
|
try { client2.index("src-1", new byte[]{1, 2}, null); } catch (RuntimeException ignored) { }
|
||||||
|
assertEquals("source.pdf", capturedFilename(rt2));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- BrainRulesImportClient (RestTemplate one-shot) ---------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rulesImport_filePart_usesGivenFilename_elseDefault() {
|
||||||
|
RestTemplate rt = mock(RestTemplate.class);
|
||||||
|
BrainRulesImportClient client = new BrainRulesImportClient(
|
||||||
|
rt, WebClient.builder(), new ObjectMapper(), "http://brain", 600);
|
||||||
|
|
||||||
|
try { client.importRules(new byte[]{1, 2}, "regles.pdf"); } catch (RuntimeException ignored) { }
|
||||||
|
assertEquals("regles.pdf", capturedFilename(rt));
|
||||||
|
|
||||||
|
RestTemplate rt2 = mock(RestTemplate.class);
|
||||||
|
BrainRulesImportClient client2 = new BrainRulesImportClient(
|
||||||
|
rt2, WebClient.builder(), new ObjectMapper(), "http://brain", 600);
|
||||||
|
try { client2.importRules(new byte[]{1, 2}, " "); } catch (RuntimeException ignored) { }
|
||||||
|
assertEquals("rules.pdf", capturedFilename(rt2));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- BrainCampaignAdaptClient (WebClient multipart) ---------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void campaignAdapt_filePart_serializedFilename() {
|
||||||
|
ExchangeFunction ef = serializingExchange("event:done\ndata:{}\n\n");
|
||||||
|
BrainCampaignAdaptClient client = new BrainCampaignAdaptClient(
|
||||||
|
WebClient.builder().exchangeFunction(ef), new ObjectMapper(), "http://brain", 30);
|
||||||
|
|
||||||
|
// filename présent puis null : les deux branches de getFilename sont sérialisées.
|
||||||
|
client.adviseStreaming(new byte[]{1, 2}, "doc.pdf", "brief", "[]",
|
||||||
|
t -> { }, () -> { }, e -> { });
|
||||||
|
client.adviseStreaming(new byte[]{1, 2}, null, null, null,
|
||||||
|
t -> { }, () -> { }, e -> { });
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- BrainCampaignImportClient (WebClient multipart) --------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void campaignImport_filePart_serializedFilename() {
|
||||||
|
ExchangeFunction ef = serializingExchange("event:done\ndata:{\"sections\":{}}\n\n");
|
||||||
|
BrainCampaignImportClient client = new BrainCampaignImportClient(
|
||||||
|
WebClient.builder().exchangeFunction(ef), new ObjectMapper(), "http://brain", 30);
|
||||||
|
|
||||||
|
client.importCampaignStreaming(new byte[]{1, 2}, "doc.pdf",
|
||||||
|
p -> { }, () -> { }, s -> { }, r -> { }, e -> { });
|
||||||
|
client.importCampaignStreaming(new byte[]{1, 2}, null,
|
||||||
|
p -> { }, () -> { }, s -> { }, r -> { }, e -> { });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NotebookChatStreamer.Msg;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NotebookChatStreamer.Progress;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NotebookException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires PURS (JUnit 5 + Mockito-less) pour {@link BrainNotebookChatClient}.
|
||||||
|
* On injecte un WebClient.Builder dont l'ExchangeFunction renvoie un corps SSE canned :
|
||||||
|
* aucun réseau n'est sollicité.
|
||||||
|
*/
|
||||||
|
class BrainNotebookChatClientTest {
|
||||||
|
|
||||||
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
|
/** Construit un client dont le WebClient renvoie le corps SSE fourni. */
|
||||||
|
private BrainNotebookChatClient clientReturning(String sseBody) {
|
||||||
|
ExchangeFunction ef = req -> Mono.just(
|
||||||
|
ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sseBody)
|
||||||
|
.build());
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainNotebookChatClient(builder, MAPPER, "http://brain", 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Construit un client dont le transport échoue immédiatement. */
|
||||||
|
private BrainNotebookChatClient clientFailingWith(Throwable boom) {
|
||||||
|
ExchangeFunction ef = req -> Mono.error(boom);
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainNotebookChatClient(builder, MAPPER, "http://brain", 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Collecteur réutilisable pour les callbacks. */
|
||||||
|
private static final class Collector {
|
||||||
|
final AtomicReference<String> sources = new AtomicReference<>();
|
||||||
|
final StringBuilder tokens = new StringBuilder();
|
||||||
|
final List<Progress> progresses = new ArrayList<>();
|
||||||
|
final AtomicBoolean done = new AtomicBoolean(false);
|
||||||
|
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||||
|
|
||||||
|
void invoke(BrainNotebookChatClient client, boolean deep) {
|
||||||
|
client.stream(
|
||||||
|
List.of("s1", "s2"),
|
||||||
|
List.of(new Msg("user", "Bonjour")),
|
||||||
|
"ctx",
|
||||||
|
deep,
|
||||||
|
sources::set,
|
||||||
|
tokens::append,
|
||||||
|
progresses::add,
|
||||||
|
() -> done.set(true),
|
||||||
|
error::set);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streame_tous_les_events_token_sources_progress_done() {
|
||||||
|
// SSE déclenchant chaque branche de handleEvent : sources, progress, token, done.
|
||||||
|
String sse =
|
||||||
|
"event:sources\ndata:{\"passages\":[1,2]}\n\n" +
|
||||||
|
"event:progress\ndata:{\"current\":2,\"total\":5}\n\n" +
|
||||||
|
"event:token\ndata:{\"token\":\"Salut\"}\n\n" +
|
||||||
|
"event:token\ndata:{\"token\":\" toi\"}\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse), true);
|
||||||
|
|
||||||
|
assertEquals("{\"passages\":[1,2]}", c.sources.get(), "JSON sources relayé brut");
|
||||||
|
assertEquals("Salut toi", c.tokens.toString(), "tokens concaténés dans l'ordre");
|
||||||
|
assertEquals(1, c.progresses.size());
|
||||||
|
assertEquals(2, c.progresses.get(0).current());
|
||||||
|
assertEquals(5, c.progresses.get(0).total());
|
||||||
|
assertTrue(c.done.get(), "onDone appelé via event done");
|
||||||
|
assertNull(c.error.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void token_vide_ou_absent_ignore() {
|
||||||
|
// token vide -> non émis ; token absent -> readField null -> non émis.
|
||||||
|
String sse =
|
||||||
|
"event:token\ndata:{\"token\":\"\"}\n\n" +
|
||||||
|
"event:token\ndata:{\"foo\":\"bar\"}\n\n" +
|
||||||
|
"event:token\ndata:{\"token\":\"X\"}\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse), false);
|
||||||
|
|
||||||
|
assertEquals("X", c.tokens.toString(), "seul le token non vide est émis");
|
||||||
|
assertTrue(c.done.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void progress_avec_json_invalide_donne_zero() {
|
||||||
|
// data non-JSON -> readInt catch -> 0/0 (couvre la branche d'exception).
|
||||||
|
String sse =
|
||||||
|
"event:progress\ndata:pas-du-json\n\n" +
|
||||||
|
"event:done\ndata:{}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse), true);
|
||||||
|
|
||||||
|
assertEquals(1, c.progresses.size());
|
||||||
|
assertEquals(0, c.progresses.get(0).current());
|
||||||
|
assertEquals(0, c.progresses.get(0).total());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_error_appelle_onError_avec_NotebookException() {
|
||||||
|
String sse =
|
||||||
|
"event:token\ndata:{\"token\":\"avant\"}\n\n" +
|
||||||
|
"event:error\ndata:{\"message\":\"oups modèle\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse), false);
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertInstanceOf(NotebookException.class, c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("oups modèle"));
|
||||||
|
assertFalse(c.done.get(), "onDone non appelé après un error terminal");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void event_error_sans_message_relaie_data_brut() {
|
||||||
|
// readMessage : pas de champ message -> renvoie data brut.
|
||||||
|
String sse = "event:error\ndata:erreur-brute\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse), false);
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("erreur-brute"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void flux_termine_sans_done_appelle_onDone() {
|
||||||
|
// Aucun event done/error -> terminated reste false -> onDone() de secours.
|
||||||
|
String sse = "event:token\ndata:{\"token\":\"fin\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse), false);
|
||||||
|
|
||||||
|
assertEquals("fin", c.tokens.toString());
|
||||||
|
assertTrue(c.done.get(), "onDone de secours appelé pour flux clos sans done");
|
||||||
|
assertNull(c.error.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur_transport_traduite_en_NotebookException() {
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientFailingWith(new RuntimeException("boom")), false);
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertInstanceOf(NotebookException.class, c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("boom"));
|
||||||
|
assertFalse(c.done.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void context_null_est_accepte() {
|
||||||
|
// Couvre la branche context == null -> "" lors de la construction du payload.
|
||||||
|
String sse = "event:done\ndata:{}\n\n";
|
||||||
|
ExchangeFunction ef = req -> Mono.just(
|
||||||
|
ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sse)
|
||||||
|
.build());
|
||||||
|
BrainNotebookChatClient client =
|
||||||
|
new BrainNotebookChatClient(WebClient.builder().exchangeFunction(ef), MAPPER, "http://brain", 30);
|
||||||
|
|
||||||
|
AtomicBoolean done = new AtomicBoolean(false);
|
||||||
|
client.stream(
|
||||||
|
List.of("s1"),
|
||||||
|
List.of(new Msg("user", "hi")),
|
||||||
|
null,
|
||||||
|
false,
|
||||||
|
json -> {},
|
||||||
|
tok -> {},
|
||||||
|
p -> {},
|
||||||
|
() -> done.set(true),
|
||||||
|
err -> {});
|
||||||
|
|
||||||
|
assertTrue(done.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NotebookException;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NotebookIndexer.IndexResult;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.client.HttpServerErrorException;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.doReturn;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring/réseau) de
|
||||||
|
* {@link BrainNotebookIndexClient} : indexation multipart one-shot (RestTemplate)
|
||||||
|
* et suppression best-effort.
|
||||||
|
* <p>
|
||||||
|
* {@code IndexResponse} étant une classe privée de l'adapter, on l'instancie par
|
||||||
|
* réflexion pour piloter la valeur renvoyée par le mock RestTemplate.
|
||||||
|
*/
|
||||||
|
class BrainNotebookIndexClientTest {
|
||||||
|
|
||||||
|
private static final String BASE_URL = "http://brain";
|
||||||
|
|
||||||
|
private RestTemplate restTemplate;
|
||||||
|
private BrainNotebookIndexClient client;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
restTemplate = mock(RestTemplate.class);
|
||||||
|
client = new BrainNotebookIndexClient(restTemplate, BASE_URL);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Récupère la Class<?> de l'IndexResponse privée (telle qu'attendue par postForObject). */
|
||||||
|
private Class<?> indexResponseClass() throws ClassNotFoundException {
|
||||||
|
return Class.forName("com.loremind.infrastructure.ai.BrainNotebookIndexClient$IndexResponse");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Instancie l'IndexResponse privée et remplit ses champs par réflexion. */
|
||||||
|
private Object newIndexResponse(int chunks, int pageCount, int ocrPageCount) throws Exception {
|
||||||
|
Class<?> cls = indexResponseClass();
|
||||||
|
Constructor<?> ctor = cls.getDeclaredConstructor();
|
||||||
|
ctor.setAccessible(true);
|
||||||
|
Object resp = ctor.newInstance();
|
||||||
|
setField(resp, "chunks", chunks);
|
||||||
|
setField(resp, "pageCount", pageCount);
|
||||||
|
setField(resp, "ocrPageCount", ocrPageCount);
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setField(Object target, String name, int value) throws Exception {
|
||||||
|
Field f = target.getClass().getDeclaredField(name);
|
||||||
|
f.setAccessible(true);
|
||||||
|
f.setInt(target, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- index() -------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void index_succes_retourneIndexResult() throws Exception {
|
||||||
|
Object wire = newIndexResponse(42, 100, 7);
|
||||||
|
// doReturn évite l'inférence générique (Class<?> -> wildcard) qui casse thenReturn.
|
||||||
|
doReturn(wire).when(restTemplate)
|
||||||
|
.postForObject(anyString(), any(), eq(indexResponseClass()));
|
||||||
|
|
||||||
|
IndexResult result = client.index("src-1", new byte[]{1, 2, 3}, "livre.pdf");
|
||||||
|
|
||||||
|
assertEquals(42, result.chunks());
|
||||||
|
assertEquals(100, result.pageCount());
|
||||||
|
assertEquals(7, result.ocrPageCount());
|
||||||
|
|
||||||
|
// L'URL appelée concatène baseUrl + INDEX_PATH.
|
||||||
|
ArgumentCaptor<String> url = ArgumentCaptor.forClass(String.class);
|
||||||
|
verify(restTemplate).postForObject(url.capture(), any(), eq(indexResponseClass()));
|
||||||
|
assertEquals(BASE_URL + "/index/notebook-source", url.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void index_filenameNull_utiliseNomParDefaut() throws Exception {
|
||||||
|
Object wire = newIndexResponse(1, 1, 0);
|
||||||
|
doReturn(wire).when(restTemplate)
|
||||||
|
.postForObject(anyString(), any(), eq(indexResponseClass()));
|
||||||
|
|
||||||
|
// filename null/blank -> branche "source.pdf" du filePart.
|
||||||
|
IndexResult result = client.index("src-1", new byte[]{9}, null);
|
||||||
|
assertEquals(1, result.chunks());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void index_reponseNull_leveNotebookException() {
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), any(Class.class)))
|
||||||
|
.thenReturn(null);
|
||||||
|
|
||||||
|
NotebookException ex = assertThrows(NotebookException.class,
|
||||||
|
() -> client.index("src-1", new byte[]{1}, "f.pdf"));
|
||||||
|
assertTrue(ex.getMessage().contains("vide"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void index_resourceAccess_leveNotebookException() {
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), any(Class.class)))
|
||||||
|
.thenThrow(new ResourceAccessException("timeout"));
|
||||||
|
|
||||||
|
NotebookException ex = assertThrows(NotebookException.class,
|
||||||
|
() -> client.index("src-1", new byte[]{1}, "f.pdf"));
|
||||||
|
assertTrue(ex.getMessage().contains("injoignable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void index_httpServerError_leveNotebookExceptionAvecStatut() {
|
||||||
|
HttpServerErrorException http = HttpServerErrorException.create(
|
||||||
|
HttpStatus.BAD_GATEWAY, "Bad Gateway", new HttpHeaders(), new byte[0], null);
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), any(Class.class)))
|
||||||
|
.thenThrow(http);
|
||||||
|
|
||||||
|
NotebookException ex = assertThrows(NotebookException.class,
|
||||||
|
() -> client.index("src-1", new byte[]{1}, "f.pdf"));
|
||||||
|
assertTrue(ex.getMessage().contains("502"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void index_erreurInattendue_leveNotebookException() {
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), any(Class.class)))
|
||||||
|
.thenThrow(new IllegalStateException("boom"));
|
||||||
|
|
||||||
|
NotebookException ex = assertThrows(NotebookException.class,
|
||||||
|
() -> client.index("src-1", new byte[]{1}, "f.pdf"));
|
||||||
|
assertTrue(ex.getMessage().contains("inattendue"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- delete() ------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void delete_appelleRestTemplateAvecBonneUrl() {
|
||||||
|
client.delete("src-99");
|
||||||
|
verify(restTemplate).delete(BASE_URL + "/index/notebook-source/src-99");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void delete_erreurIgnoree_neRelancePas() {
|
||||||
|
// Best-effort : une exception du RestTemplate est avalée (log warn).
|
||||||
|
doThrow(new ResourceAccessException("down"))
|
||||||
|
.when(restTemplate).delete(anyString());
|
||||||
|
|
||||||
|
// Ne doit pas lever.
|
||||||
|
client.delete("src-99");
|
||||||
|
verify(restTemplate).delete(BASE_URL + "/index/notebook-source/src-99");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.RandomTableEntry;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.RandomTableGenerationException;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.RandomTableGenerator.GeneratedTable;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.client.HttpServerErrorException;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring) de {@link BrainRandomTableClient}.
|
||||||
|
* Le RestTemplate est mocké : {@code postForObject(url, entity, Map.class)}.
|
||||||
|
*/
|
||||||
|
class BrainRandomTableClientTest {
|
||||||
|
|
||||||
|
private RestTemplate rt;
|
||||||
|
private BrainRandomTableClient client;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
rt = mock(RestTemplate.class);
|
||||||
|
client = new BrainRandomTableClient(rt, "http://brain");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Construit une map d'entrée pour le payload "entries". */
|
||||||
|
private static Map<String, Object> entry(Object min, Object max, Object label, Object detail) {
|
||||||
|
Map<String, Object> m = new LinkedHashMap<>();
|
||||||
|
m.put("min_roll", min);
|
||||||
|
m.put("max_roll", max);
|
||||||
|
m.put("label", label);
|
||||||
|
m.put("detail", detail);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- generate : cas nominal et branches de parsing ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_reponseValide_plusieursEntrees_avecEntreesInvalidesIgnorees() {
|
||||||
|
List<Object> entries = new ArrayList<>();
|
||||||
|
entries.add(entry(1, 5, "Embuscade", "des gobelins")); // valide (Number)
|
||||||
|
entries.add(entry("6", "10", "Trésor", null)); // valide (String -> asInt)
|
||||||
|
entries.add(entry(null, 3, "min null", "x")); // ignorée : min null
|
||||||
|
entries.add(entry(3, null, "max null", "x")); // ignorée : max null
|
||||||
|
entries.add(entry(1, 2, null, "x")); // ignorée : label null
|
||||||
|
entries.add(entry(1, 2, " ", "x")); // ignorée : label blank
|
||||||
|
entries.add(entry("abc", 2, "min non-num", "x")); // ignorée : asInt String non-numérique
|
||||||
|
entries.add("pas une map"); // ignorée : item non-Map
|
||||||
|
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("name", "Table des rencontres");
|
||||||
|
resp.put("description", "En forêt");
|
||||||
|
resp.put("entries", entries);
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
GeneratedTable table = client.generate("desc", "1d10", "ctx");
|
||||||
|
|
||||||
|
assertEquals("Table des rencontres", table.name());
|
||||||
|
assertEquals("En forêt", table.description());
|
||||||
|
assertEquals(2, table.entries().size());
|
||||||
|
|
||||||
|
RandomTableEntry e0 = table.entries().get(0);
|
||||||
|
assertEquals(1, e0.getMinRoll());
|
||||||
|
assertEquals(5, e0.getMaxRoll());
|
||||||
|
assertEquals("Embuscade", e0.getLabel());
|
||||||
|
assertEquals("des gobelins", e0.getDetail());
|
||||||
|
|
||||||
|
RandomTableEntry e1 = table.entries().get(1);
|
||||||
|
assertEquals(6, e1.getMinRoll());
|
||||||
|
assertEquals(10, e1.getMaxRoll());
|
||||||
|
assertEquals("Trésor", e1.getLabel());
|
||||||
|
assertNull(e1.getDetail()); // detail null -> asString(null) == null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_maxInferieurAMin_estCorrigeParMathMax() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("entries", List.of(entry(8, 3, "Inversé", null)));
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
GeneratedTable table = client.generate("d", "1d8", "c");
|
||||||
|
RandomTableEntry e = table.entries().get(0);
|
||||||
|
assertEquals(8, e.getMinRoll());
|
||||||
|
assertEquals(8, e.getMaxRoll()); // Math.max(8,3) == 8
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_nameAbsent_fallbackSurDescription() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("entries", List.of(entry(1, 1, "Ok", null)));
|
||||||
|
// pas de "name" -> asString(null) == null -> fallback description
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
GeneratedTable table = client.generate("MaDescription", "1d20", "c");
|
||||||
|
assertEquals("MaDescription", table.name());
|
||||||
|
assertNull(table.description()); // description absente
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_nameBlank_fallbackSurDescription() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("name", " ");
|
||||||
|
resp.put("entries", List.of(entry(1, 1, "Ok", null)));
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
GeneratedTable table = client.generate("Fallback", "1d20", "c");
|
||||||
|
assertEquals("Fallback", table.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_argumentsNull_remplisParDefauts_etAppelle() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("name", "T");
|
||||||
|
resp.put("entries", List.of(entry(1, 1, "Ok", null)));
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
// description/diceFormula/context null -> branches de défaut couvertes
|
||||||
|
GeneratedTable table = client.generate(null, null, null);
|
||||||
|
assertEquals("T", table.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_reponseNull_leveException() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(null);
|
||||||
|
|
||||||
|
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||||
|
() -> client.generate("d", "1d20", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("réponse vide"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_entriesAbsentes_aucuneEntree_leveException() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("name", "T");
|
||||||
|
// pas de "entries" -> rawEntries null, pas un List<?>
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||||
|
() -> client.generate("d", "1d20", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("Aucune entrée"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_entriesVide_leveException() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("entries", new ArrayList<>()); // List mais vide
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||||
|
() -> client.generate("d", "1d20", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("Aucune entrée"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_toutesEntreesInvalides_leveException() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("entries", List.of(entry(null, null, null, null)));
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
assertThrows(RandomTableGenerationException.class,
|
||||||
|
() -> client.generate("d", "1d20", "c"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- generate : branches du catch ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_brainInjoignable_resourceAccess() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||||
|
.thenThrow(new ResourceAccessException("down"));
|
||||||
|
|
||||||
|
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||||
|
() -> client.generate("d", "1d20", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("injoignable"));
|
||||||
|
assertInstanceOf(ResourceAccessException.class, ex.getCause());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_erreurHttp_restClientResponse() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||||
|
.thenThrow(HttpServerErrorException.create(
|
||||||
|
HttpStatus.BAD_GATEWAY, "Bad Gateway", new HttpHeaders(), new byte[0], null));
|
||||||
|
|
||||||
|
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||||
|
() -> client.generate("d", "1d20", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("HTTP 502"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generate_erreurInattendue_exceptionGenerique() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||||
|
.thenThrow(new IllegalStateException("boom"));
|
||||||
|
|
||||||
|
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||||
|
() -> client.generate("d", "1d20", "c"));
|
||||||
|
assertTrue(ex.getMessage().contains("inattendue"));
|
||||||
|
assertInstanceOf(IllegalStateException.class, ex.getCause());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- improvise ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void improvise_narrationPresente_retourneNarration() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("narration", "Les gobelins surgissent des fourrés.");
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
String out = client.improvise("Table", "Embuscade", "détail", "ctx");
|
||||||
|
assertEquals("Les gobelins surgissent des fourrés.", out);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void improvise_argumentsNull_remplisParDefauts() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>();
|
||||||
|
resp.put("narration", "ok");
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
assertEquals("ok", client.improvise(null, null, null, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void improvise_reponseNull_retourneChaineVide() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(null);
|
||||||
|
|
||||||
|
assertEquals("", client.improvise("T", "L", "D", "C"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void improvise_narrationAbsente_retourneChaineVide() {
|
||||||
|
Map<String, Object> resp = new LinkedHashMap<>(); // pas de "narration"
|
||||||
|
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||||
|
|
||||||
|
assertEquals("", client.improvise("T", "L", "D", "C"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void improvise_brainInjoignable_propageException() {
|
||||||
|
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||||
|
.thenThrow(new ResourceAccessException("down"));
|
||||||
|
|
||||||
|
assertThrows(RandomTableGenerationException.class,
|
||||||
|
() -> client.improvise("T", "L", "D", "C"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RulesImportProgress;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RulesImportResult;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RulesImportException;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.client.HttpServerErrorException;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring/réseau) de
|
||||||
|
* {@link BrainRulesImportClient} :
|
||||||
|
* - one-shot via RestTemplate (importRules) ;
|
||||||
|
* - streaming SSE via WebClient + ExchangeFunction (importRulesStreaming).
|
||||||
|
* Couvre aussi indirectement les getters du DTO {@link BrainRulesImportResponse}.
|
||||||
|
*/
|
||||||
|
class BrainRulesImportClientTest {
|
||||||
|
|
||||||
|
private static final String BASE_URL = "http://brain";
|
||||||
|
|
||||||
|
private RestTemplate restTemplate;
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
restTemplate = mock(RestTemplate.class);
|
||||||
|
objectMapper = new ObjectMapper();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Construit le client avec un WebClient câblé sur l'ExchangeFunction fournie. */
|
||||||
|
private BrainRulesImportClient client(ExchangeFunction ef) {
|
||||||
|
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||||
|
return new BrainRulesImportClient(restTemplate, builder, objectMapper, BASE_URL, 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Client one-shot : l'ExchangeFunction n'est jamais utilisée. */
|
||||||
|
private BrainRulesImportClient oneShotClient() {
|
||||||
|
return client(req -> Mono.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- One-shot (RestTemplate) --------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void importRules_succes_retourneResultatEtCouvreGettersDuDto() {
|
||||||
|
BrainRulesImportResponse wire = new BrainRulesImportResponse();
|
||||||
|
wire.setSections(Map.of("Combat", "## Combat"));
|
||||||
|
wire.setPageCount(12);
|
||||||
|
wire.setOcrPageCount(3);
|
||||||
|
// Couvre aussi les getters Lombok du DTO.
|
||||||
|
assertEquals(Map.of("Combat", "## Combat"), wire.getSections());
|
||||||
|
assertEquals(12, wire.getPageCount());
|
||||||
|
assertEquals(3, wire.getOcrPageCount());
|
||||||
|
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||||
|
.thenReturn(wire);
|
||||||
|
|
||||||
|
RulesImportResult result = oneShotClient().importRules(new byte[]{1, 2, 3}, "regles.pdf");
|
||||||
|
|
||||||
|
assertEquals(Map.of("Combat", "## Combat"), result.sections());
|
||||||
|
assertEquals(12, result.pageCount());
|
||||||
|
assertEquals(3, result.ocrPageCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void importRules_filenameNull_utiliseNomParDefaut() {
|
||||||
|
BrainRulesImportResponse wire = new BrainRulesImportResponse();
|
||||||
|
wire.setSections(Map.of("A", "x"));
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||||
|
.thenReturn(wire);
|
||||||
|
|
||||||
|
// filename null -> branche du filePart anonyme (getFilename par défaut).
|
||||||
|
RulesImportResult result = oneShotClient().importRules(new byte[]{9}, null);
|
||||||
|
assertEquals(1, result.sections().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void importRules_reponseNull_leveRulesImportException() {
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||||
|
.thenReturn(null);
|
||||||
|
|
||||||
|
RulesImportException ex = assertThrows(RulesImportException.class,
|
||||||
|
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||||
|
assertTrue(ex.getMessage().contains("vide"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void importRules_sectionsNull_leveRulesImportException() {
|
||||||
|
BrainRulesImportResponse wire = new BrainRulesImportResponse();
|
||||||
|
wire.setSections(null);
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||||
|
.thenReturn(wire);
|
||||||
|
|
||||||
|
assertThrows(RulesImportException.class,
|
||||||
|
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void importRules_resourceAccess_leveRulesImportException() {
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||||
|
.thenThrow(new ResourceAccessException("timeout"));
|
||||||
|
|
||||||
|
RulesImportException ex = assertThrows(RulesImportException.class,
|
||||||
|
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||||
|
assertTrue(ex.getMessage().contains("injoignable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void importRules_httpServerError_leveRulesImportExceptionAvecStatut() {
|
||||||
|
HttpServerErrorException http = HttpServerErrorException.create(
|
||||||
|
HttpStatus.BAD_GATEWAY, "Bad Gateway", new HttpHeaders(), new byte[0], null);
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||||
|
.thenThrow(http);
|
||||||
|
|
||||||
|
RulesImportException ex = assertThrows(RulesImportException.class,
|
||||||
|
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||||
|
assertTrue(ex.getMessage().contains("502"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void importRules_erreurInattendue_leveRulesImportException() {
|
||||||
|
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||||
|
.thenThrow(new IllegalStateException("boom"));
|
||||||
|
|
||||||
|
RulesImportException ex = assertThrows(RulesImportException.class,
|
||||||
|
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||||
|
assertTrue(ex.getMessage().contains("inattendue"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Collecteur de callbacks pour le streaming --------------------------
|
||||||
|
|
||||||
|
private static final class Collector {
|
||||||
|
final List<RulesImportProgress> progress = new ArrayList<>();
|
||||||
|
final AtomicInteger heartbeats = new AtomicInteger();
|
||||||
|
final List<String> statuses = new ArrayList<>();
|
||||||
|
final AtomicReference<RulesImportResult> done = new AtomicReference<>();
|
||||||
|
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void runStreaming(String sse, Collector c) {
|
||||||
|
ExchangeFunction ef = req -> Mono.just(
|
||||||
|
ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sse)
|
||||||
|
.build());
|
||||||
|
client(ef).importRulesStreaming(
|
||||||
|
new byte[]{1, 2}, "r.pdf",
|
||||||
|
c.progress::add,
|
||||||
|
c.heartbeats::incrementAndGet,
|
||||||
|
c.statuses::add,
|
||||||
|
c.done::set,
|
||||||
|
c.error::set);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Streaming (WebClient + SSE) ----------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_tousLesEvenements_declenchentLesBonsCallbacks() {
|
||||||
|
String sse =
|
||||||
|
"event:extracting\ndata:{}\n\n" +
|
||||||
|
"event:start\ndata:{\"total\":2,\"page_count\":10,\"ocr_page_count\":1}\n\n" +
|
||||||
|
"event:progress\ndata:{\"current\":1,\"total\":2,\"new_sections\":[\"Combat\"]}\n\n" +
|
||||||
|
"event:heartbeat\ndata:{}\n\n" +
|
||||||
|
"event:status\ndata:{\"message\":\"retry\"}\n\n" +
|
||||||
|
"event:chunk_failed\ndata:{\"current\":2,\"total\":2,\"message\":\"timeout\"}\n\n" +
|
||||||
|
"event:done\ndata:{\"sections\":{\"Combat\":\"## Combat\"},\"page_count\":10,\"ocr_page_count\":1}\n\n";
|
||||||
|
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(sse, c);
|
||||||
|
|
||||||
|
// extracting -> progress(0,0,0,0,[]) ; start -> progress(0,2,10,1,[]) ; progress -> progress(1,2,10,1,[Combat])
|
||||||
|
assertEquals(3, c.progress.size());
|
||||||
|
|
||||||
|
RulesImportProgress extracting = c.progress.get(0);
|
||||||
|
assertEquals(0, extracting.total());
|
||||||
|
assertTrue(extracting.newSectionTitles().isEmpty());
|
||||||
|
|
||||||
|
RulesImportProgress start = c.progress.get(1);
|
||||||
|
assertEquals(0, start.current());
|
||||||
|
assertEquals(2, start.total());
|
||||||
|
assertEquals(10, start.pageCount());
|
||||||
|
assertEquals(1, start.ocrPageCount());
|
||||||
|
|
||||||
|
RulesImportProgress prog = c.progress.get(2);
|
||||||
|
assertEquals(1, prog.current());
|
||||||
|
assertEquals(2, prog.total());
|
||||||
|
assertEquals(10, prog.pageCount());
|
||||||
|
assertEquals(1, prog.ocrPageCount());
|
||||||
|
assertEquals(List.of("Combat"), prog.newSectionTitles());
|
||||||
|
|
||||||
|
assertEquals(1, c.heartbeats.get());
|
||||||
|
|
||||||
|
// status (readMessage -> "retry") + chunk_failed (statut formaté).
|
||||||
|
assertEquals(2, c.statuses.size());
|
||||||
|
assertEquals("retry", c.statuses.get(0));
|
||||||
|
assertTrue(c.statuses.get(1).contains("Morceau 2/2"));
|
||||||
|
assertTrue(c.statuses.get(1).contains("timeout"));
|
||||||
|
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
assertEquals(Map.of("Combat", "## Combat"), c.done.get().sections());
|
||||||
|
assertEquals(10, c.done.get().pageCount());
|
||||||
|
assertEquals(1, c.done.get().ocrPageCount());
|
||||||
|
|
||||||
|
// done a positionné terminated -> pas d'onError.
|
||||||
|
assertEquals(null, c.error.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_evenementError_appelleOnError() {
|
||||||
|
String sse = "event:error\ndata:{\"message\":\"LLM saturé\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(sse, c);
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get() instanceof RulesImportException);
|
||||||
|
assertTrue(c.error.get().getMessage().contains("LLM saturé"));
|
||||||
|
assertNull(c.done.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_chunkFailedSansMessage_statutAvecPoint() {
|
||||||
|
// node sans champ "message" -> branche "." finale.
|
||||||
|
String sse = "event:chunk_failed\ndata:{\"current\":1,\"total\":3}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(sse, c);
|
||||||
|
|
||||||
|
assertEquals(1, c.statuses.size());
|
||||||
|
assertTrue(c.statuses.get(0).contains("Morceau 1/3 ignoré."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_statusDataNonJson_readMessageRenvoieDataBrut() {
|
||||||
|
// data non-JSON -> readJson renvoie null -> readMessage retourne le data brut.
|
||||||
|
String sse = "event:status\ndata:texte brut\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(sse, c);
|
||||||
|
|
||||||
|
assertEquals(1, c.statuses.size());
|
||||||
|
assertEquals("texte brut", c.statuses.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_evenementInconnuAvecDataNonJson_estIgnore() {
|
||||||
|
// Pas heartbeat/status/chunk_failed/error/extracting, et readJson==null -> return.
|
||||||
|
String sse = "event:mystere\ndata:pas du json\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(sse, c);
|
||||||
|
|
||||||
|
assertTrue(c.progress.isEmpty());
|
||||||
|
assertTrue(c.statuses.isEmpty());
|
||||||
|
// Aucun done/error -> flux interrompu -> onError.
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("interrompu"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_finSansDoneNiError_signaleFluxInterrompu() {
|
||||||
|
// Que des heartbeats : pas de done/error -> branche "flux interrompu".
|
||||||
|
String sse = "event:heartbeat\ndata:{}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(sse, c);
|
||||||
|
|
||||||
|
assertEquals(1, c.heartbeats.get());
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get() instanceof RulesImportException);
|
||||||
|
assertTrue(c.error.get().getMessage().contains("interrompu"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_erreurTransport_appelleOnErrorAvecCauseExposee() {
|
||||||
|
ExchangeFunction ef = req -> Mono.error(new RuntimeException("boom"));
|
||||||
|
Collector c = new Collector();
|
||||||
|
client(ef).importRulesStreaming(
|
||||||
|
new byte[]{1}, "r.pdf",
|
||||||
|
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add,
|
||||||
|
c.done::set, c.error::set);
|
||||||
|
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get() instanceof RulesImportException);
|
||||||
|
// La cause réelle (type + message) est exposée dans le message.
|
||||||
|
assertTrue(c.error.get().getMessage().contains("boom"));
|
||||||
|
assertNotNull(c.error.get().getCause());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_filenameVide_utiliseNomParDefautSansErreur() {
|
||||||
|
// filename vide -> branches "rules.pdf" du filePart et du part().filename().
|
||||||
|
String sse = "event:done\ndata:{\"sections\":{},\"page_count\":0,\"ocr_page_count\":0}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
ExchangeFunction ef = req -> Mono.just(
|
||||||
|
ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sse)
|
||||||
|
.build());
|
||||||
|
client(ef).importRulesStreaming(
|
||||||
|
new byte[]{1}, " ",
|
||||||
|
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add,
|
||||||
|
c.done::set, c.error::set);
|
||||||
|
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
assertTrue(c.done.get().sections().isEmpty());
|
||||||
|
assertNull(c.error.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
// petits helpers d'assertion null/non-null (évite import statique supplémentaire)
|
||||||
|
private static void assertNull(Object o) {
|
||||||
|
assertTrue(o == null, "attendu null");
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user