Compare commits
18 Commits
c77c0bc994
...
v0.16.0
| Author | SHA1 | Date | |
|---|---|---|---|
| f04ecf1021 | |||
| 72fe5e6215 | |||
| 7dfa9c3655 | |||
| 7aa174d75a | |||
| 48baa08cfb | |||
| f1c68634f7 | |||
| 1e501e03a4 | |||
| 9d4e72af26 | |||
| 1fb4563557 | |||
| 84025911f8 | |||
| bf871852b8 | |||
| 78e735c959 | |||
| c734de447f | |||
| 914767f793 | |||
| af3a6d443c | |||
| 6e75326779 | |||
| d0b53bb15a | |||
| bbcb5ee34e |
120
.github/workflows/desktop-release.yml
vendored
Normal file
120
.github/workflows/desktop-release.yml
vendored
Normal file
@@ -0,0 +1,120 @@
|
||||
name: Desktop installers
|
||||
|
||||
# Produit les installeurs de BUREAU (.msi Windows pour l'instant) et les publie
|
||||
# en tant qu'assets d'une GitHub Release, sur tag `v*`.
|
||||
#
|
||||
# Complementaire au pipeline Gitea Actions (.gitea/workflows/release.yml) qui,
|
||||
# lui, build et pousse les IMAGES Docker. Ici on est sur GitHub car jpackage et
|
||||
# PyInstaller ne savent PAS cross-compiler : le .msi DOIT etre construit sur un
|
||||
# runner Windows, et GitHub en fournit gratuitement (windows-latest).
|
||||
#
|
||||
# Prerequis : le depot Gitea doit etre mirrore vers GitHub (push mirror, tags
|
||||
# inclus) pour que le tag declenche ce workflow.
|
||||
#
|
||||
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
|
||||
# Tag beta vX.Y.Z-beta* -> AUCUNE publication publique. Le .msi est depose en
|
||||
# ARTEFACT PRIVE du run (telechargeable seulement par
|
||||
# toi via l'onglet Actions) ; tu le joins ensuite a un
|
||||
# post Patreon reserve a un palier. Patreon = la
|
||||
# barriere d'acces (equivalent du registry prive +
|
||||
# relais pour les images Docker beta).
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
# Declenchement MANUEL depuis l'onglet Actions ("Run workflow"). Utile quand un
|
||||
# tag a ete pousse AVANT que le workflow existe sur GitHub (ne se redeclenche
|
||||
# pas tout seul), ou pour rejouer un build. Saisir la version SANS le "v".
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Version a builder (doit correspondre a un tag existant, ex: 0.15.0 ou 0.15.0-beta)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: write # requis pour creer la Release et y attacher le .msi
|
||||
|
||||
jobs:
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
# En declenchement manuel, on checkout le TAG correspondant a la version
|
||||
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
||||
# on prend la ref poussee.
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('v{0}', inputs.version) || github.ref }}
|
||||
|
||||
# Apporte jpackage (lanceur d'empaquetage natif) dans le PATH.
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
# Python 3.12 = meme version que l'image Docker du Brain (coherence runtime).
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
# jpackage genere le MSI via WiX Toolset v3 (candle.exe/light.exe). WiX 4+
|
||||
# ne convient pas (outils renommes). Le paquet choco `wixtoolset` est la
|
||||
# ligne 3.x et s'ajoute au PATH.
|
||||
- name: Install WiX Toolset 3
|
||||
shell: pwsh
|
||||
run: choco install wixtoolset -y --no-progress
|
||||
|
||||
# Version de l'installeur = version du tag (push) OU de l'input (manuel).
|
||||
# Sorties : version (numerique X.Y.Z pour le MSI), tag (vX.Y.Z[-beta]),
|
||||
# isbeta (true/false) — independant du nom de ref (qui est une branche en manuel).
|
||||
- name: Derive version
|
||||
id: ver
|
||||
shell: pwsh
|
||||
run: |
|
||||
if ('${{ github.event_name }}' -eq 'workflow_dispatch') {
|
||||
$raw = '${{ inputs.version }}'
|
||||
} else {
|
||||
$raw = '${{ github.ref_name }}'
|
||||
}
|
||||
$raw = $raw -replace '^v','' # 0.15.0 ou 0.15.0-beta
|
||||
$num = ($raw -split '-')[0] # 0.15.0
|
||||
$isbeta = if ($raw -like '*-beta*') { 'true' } else { 'false' }
|
||||
"version=$num" >> $env:GITHUB_OUTPUT
|
||||
"tag=v$raw" >> $env:GITHUB_OUTPUT
|
||||
"isbeta=$isbeta" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: Build Windows installer
|
||||
shell: pwsh
|
||||
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||
|
||||
# STABLE uniquement : Release GitHub publique avec le .msi.
|
||||
# tag_name explicite : en declenchement manuel, github.ref est une branche,
|
||||
# donc on cible le tag derive (la release est attachee au bon tag).
|
||||
- name: Publish installer to GitHub Release (stable)
|
||||
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.ver.outputs.tag }}
|
||||
files: core/target/dist-out/*.msi
|
||||
fail_on_unmatched_files: true
|
||||
generate_release_notes: true
|
||||
|
||||
# BETA uniquement : artefact PRIVE (pas de release publique). A recuperer
|
||||
# via l'onglet Actions puis a joindre a un post Patreon gate par palier.
|
||||
- name: Upload installer as private artifact (beta)
|
||||
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: loremind-beta-${{ steps.ver.outputs.version }}-msi
|
||||
path: core/target/dist-out/*.msi
|
||||
retention-days: 90
|
||||
|
||||
# TODO (plus tard) : job `linux` sur ubuntu-latest produisant un AppImage
|
||||
# (jpackage --type app-image + appimagetool) + PyInstaller Linux du Brain,
|
||||
# attache a la MEME release. Reutilise la meme matrice / les memes etapes.
|
||||
14
.gitignore
vendored
14
.gitignore
vendored
@@ -45,6 +45,12 @@ env/
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# Artefacts du build bureau (cf. installers/desktop)
|
||||
.venv-build/
|
||||
brain/build/
|
||||
brain/dist-embed/
|
||||
*.spec
|
||||
|
||||
# ============================================================================
|
||||
# Angular / Node (Web)
|
||||
# ============================================================================
|
||||
@@ -109,3 +115,11 @@ docker-compose.override.yml
|
||||
relay/
|
||||
scripts/bump-version.mjs
|
||||
brain/data/notebooks/5.json
|
||||
|
||||
# ============================================================================
|
||||
# Documentation reservee aux patrons (repo Gitea PRIVE separe, clone
|
||||
# localement). NE DOIT JAMAIS partir dans le repo LoreMind public.
|
||||
# Contient le site premium (sources) + son Worker de gate dans gate/.
|
||||
# ============================================================================
|
||||
docusaurus/loremind-patreon/
|
||||
installers/desktop/README.md
|
||||
|
||||
68
README.fr.md
Normal file
68
README.fr.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# LoreMind
|
||||
|
||||
[English](README.md) · **Français**
|
||||
|
||||
> Application web auto-hébergeable pour MJ qui veulent centraliser leur univers, leurs campagnes et leurs personnages — avec un assistant IA contextuel.
|
||||
|
||||
[](LICENSE)
|
||||
[](https://loremind-docs.igmlcreation.fr/)
|
||||
[](https://loremind-demo.igmlcreation.fr/)
|
||||
[](https://www.patreon.com/c/IGMLCreation)
|
||||
[](https://discord.gg/cPpFzCjEzQ)
|
||||
|
||||
## Découvrir LoreMind en vidéo
|
||||
|
||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||
|
||||

|
||||
|
||||
## Ce que ça fait
|
||||
|
||||
LoreMind regroupe ce qu'un MJ utilise habituellement éparpillé entre plusieurs outils. L'application s'articule autour de trois modules principaux, augmentés par un assistant IA qui exploite tout votre contenu.
|
||||
|
||||
### Lore
|
||||
|
||||
Construire votre univers avec une arborescence de pages templatées : lieux, factions, PNJ, événements, organisations... Chaque type de page suit un template configurable, ce qui garantit la cohérence et facilite la navigation dans des univers riches.
|
||||
|
||||
### Game System
|
||||
|
||||
Stocker les règles de votre système de jeu (D&D, Nimble, créations maison...) et définir les modèles de fiches de personnages associés. Les règles indexées peuvent être injectées dans le contexte de l'IA pour des réponses fidèles à votre système.
|
||||
|
||||
### Campaign
|
||||
|
||||
Structurer vos campagnes en Arcs → Chapitres → Scènes avec séparation claire du contenu MJ et du contenu joueurs. Gérer les PJ et PNJ via des fiches dynamiques basées sur les templates du game system retenu.
|
||||
|
||||
### Assistant IA
|
||||
|
||||
Un assistant contextuel qui pioche dans votre Lore, vos règles et vos campagnes pour répondre à vos questions, suggérer du contenu cohérent, ou rebondir sur une situation improvisée en table.
|
||||
|
||||
L'IA s'exécute **en local via [Ollama](https://ollama.com/)** ou via **[1min.ai](https://1min.ai/)**. D'autres moteurs seront supportés à l'avenir.
|
||||
|
||||
## Documentation
|
||||
|
||||
Toute la documentation (installation, configuration, prise en main) est sur **[loremind-docs.igmlcreation.fr](https://loremind-docs.igmlcreation.fr/)**.
|
||||
|
||||
## Démo en ligne
|
||||
|
||||
Une instance de démonstration est disponible sur **[loremind-demo.igmlcreation.fr](https://loremind-demo.igmlcreation.fr/)**.
|
||||
|
||||
Quelques limites à connaître :
|
||||
- 10 utilisateurs maximum simultanés (instances isolées)
|
||||
- Session limitée à 20 minutes avant réinitialisation
|
||||
- Partie IA non incluse dans la démo (nécessite Ollama ou 1min.ai côté serveur)
|
||||
|
||||
## Soutenir le projet
|
||||
|
||||
LoreMind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||
|
||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
||||
|
||||
## Licence
|
||||
|
||||
LoreMind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
||||
|
||||
En pratique :
|
||||
- Vous pouvez l'utiliser gratuitement, l'héberger, la modifier, la redistribuer.
|
||||
- Si vous modifiez le code et que vous exposez l'application modifiée sur un réseau (même en SaaS privé), vous devez rendre vos modifications publiques sous la même licence.
|
||||
- Les univers (Lore) et campagnes que vous créez avec LoreMind **vous appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
||||
70
README.md
70
README.md
@@ -1,66 +1,68 @@
|
||||
# LoreMind
|
||||
|
||||
> Application web auto-hébergeable pour MJ qui veulent centraliser leur univers, leurs campagnes et leurs personnages — avec un assistant IA contextuel.
|
||||
**English** · [Français](README.fr.md)
|
||||
|
||||
[](LICENSE)
|
||||
[](https://loremind-docs.igmlcreation.fr/)
|
||||
[](https://loremind-demo.igmlcreation.fr/)
|
||||
[](https://www.patreon.com/c/IGMLCreation)
|
||||
[](https://discord.gg/cPpFzCjEzQ)
|
||||
> A self-hostable web app for game masters who want to centralize their world, campaigns and characters — with a context-aware AI assistant.
|
||||
|
||||
## Découvrir LoreMind en vidéo
|
||||
[](LICENSE)
|
||||
[](https://loremind-docs.igmlcreation.fr/en/)
|
||||
[](https://loremind-demo.igmlcreation.fr/)
|
||||
[](https://www.patreon.com/c/IGMLCreation)
|
||||
[](https://discord.gg/cPpFzCjEzQ)
|
||||
|
||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||
## See LoreMind in action
|
||||
|
||||

|
||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||
|
||||
## Ce que ça fait
|
||||

|
||||
|
||||
LoreMind regroupe ce qu'un MJ utilise habituellement éparpillé entre plusieurs outils. L'application s'articule autour de trois modules principaux, augmentés par un assistant IA qui exploite tout votre contenu.
|
||||
## What it does
|
||||
|
||||
LoreMind brings together what a game master usually scatters across several tools. The app is built around three core modules, augmented by an AI assistant that draws on all of your content.
|
||||
|
||||
### Lore
|
||||
|
||||
Construire votre univers avec une arborescence de pages templatées : lieux, factions, PNJ, événements, organisations... Chaque type de page suit un template configurable, ce qui garantit la cohérence et facilite la navigation dans des univers riches.
|
||||
Build your world with a tree of templated pages: locations, factions, NPCs, events, organizations... Each page type follows a configurable template, which keeps things consistent and makes navigating rich worlds easy.
|
||||
|
||||
### Game System
|
||||
|
||||
Stocker les règles de votre système de jeu (D&D, Nimble, créations maison...) et définir les modèles de fiches de personnages associés. Les règles indexées peuvent être injectées dans le contexte de l'IA pour des réponses fidèles à votre système.
|
||||
Store the rules of your game system (D&D, Nimble, homebrew...) and define the matching character sheet templates. Indexed rules can be injected into the AI's context for answers that stay true to your system.
|
||||
|
||||
### Campaign
|
||||
|
||||
Structurer vos campagnes en Arcs → Chapitres → Scènes avec séparation claire du contenu MJ et du contenu joueurs. Gérer les PJ et PNJ via des fiches dynamiques basées sur les templates du game system retenu.
|
||||
Structure your campaigns as Arcs → Chapters → Scenes, with a clear split between GM-only and player-facing content. Manage PCs and NPCs through dynamic sheets based on your chosen game system's templates.
|
||||
|
||||
### Assistant IA
|
||||
### AI Assistant
|
||||
|
||||
Un assistant contextuel qui pioche dans votre Lore, vos règles et vos campagnes pour répondre à vos questions, suggérer du contenu cohérent, ou rebondir sur une situation improvisée en table.
|
||||
A context-aware assistant that pulls from your Lore, rules and campaigns to answer your questions, suggest consistent content, or improvise around an unexpected situation at the table.
|
||||
|
||||
L'IA s'exécute **en local via [Ollama](https://ollama.com/)** ou via **[1min.ai](https://1min.ai/)**. D'autres moteurs seront supportés à l'avenir.
|
||||
The AI runs **locally via [Ollama](https://ollama.com/)** or via **[1min.ai](https://1min.ai/)**. More engines will be supported in the future.
|
||||
|
||||
## Documentation
|
||||
|
||||
Toute la documentation (installation, configuration, prise en main) est sur **[loremind-docs.igmlcreation.fr](https://loremind-docs.igmlcreation.fr/)**.
|
||||
The full documentation (installation, configuration, getting started) lives at **[loremind-docs.igmlcreation.fr/en](https://loremind-docs.igmlcreation.fr/en/)**.
|
||||
|
||||
## Démo en ligne
|
||||
## Live demo
|
||||
|
||||
Une instance de démonstration est disponible sur **[loremind-demo.igmlcreation.fr](https://loremind-demo.igmlcreation.fr/)**.
|
||||
A demo instance is available at **[loremind-demo.igmlcreation.fr](https://loremind-demo.igmlcreation.fr/)**.
|
||||
|
||||
Quelques limites à connaître :
|
||||
- 10 utilisateurs maximum simultanés (instances isolées)
|
||||
- Session limitée à 20 minutes avant réinitialisation
|
||||
- Partie IA non incluse dans la démo (nécessite Ollama ou 1min.ai côté serveur)
|
||||
A few limitations to be aware of:
|
||||
- 10 concurrent users maximum (isolated instances)
|
||||
- Sessions limited to 20 minutes before reset
|
||||
- The AI part is not included in the demo (requires Ollama or 1min.ai server-side)
|
||||
|
||||
## Soutenir le projet
|
||||
## Support the project
|
||||
|
||||
LoreMind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||
LoreMind is **and will remain free when self-hosted**. Development moves faster with your support:
|
||||
|
||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — early access to features, roadmap voting, exclusive devlogs
|
||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
|
||||
|
||||
## Licence
|
||||
## License
|
||||
|
||||
LoreMind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
||||
LoreMind is distributed under the **[GNU AGPL v3](LICENSE)** license.
|
||||
|
||||
En pratique :
|
||||
- Vous pouvez l'utiliser gratuitement, l'héberger, la modifier, la redistribuer.
|
||||
- Si vous modifiez le code et que vous exposez l'application modifiée sur un réseau (même en SaaS privé), vous devez rendre vos modifications publiques sous la même licence.
|
||||
- Les univers (Lore) et campagnes que vous créez avec LoreMind **vous appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
||||
In practice:
|
||||
- You can use it for free, host it, modify it, and redistribute it.
|
||||
- If you modify the code and expose the modified app over a network (even as a private SaaS), you must make your changes public under the same license.
|
||||
- The worlds (Lore) and campaigns you create with LoreMind **belong entirely to you** — the license only covers the application's code.
|
||||
|
||||
@@ -18,6 +18,7 @@ from app.api.chat_mapping import (
|
||||
from app.api.deps import get_chat_use_case
|
||||
from app.application.chat import ChatUseCase
|
||||
from app.core.config import get_settings
|
||||
from app.core.language import get_user_language
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError
|
||||
|
||||
@@ -44,6 +45,7 @@ def _count_tokens(text: str | None) -> int:
|
||||
async def chat_stream(
|
||||
body: ChatStreamRequestDTO,
|
||||
use_case: Annotated[ChatUseCase, Depends(get_chat_use_case)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> StreamingResponse:
|
||||
"""Chat streamé (Server-Sent Events) avec Structural Context.
|
||||
|
||||
@@ -82,6 +84,7 @@ async def chat_stream(
|
||||
narrative_entity=narrative_entity,
|
||||
game_system_context=game_system_context,
|
||||
session_context=session_context,
|
||||
language=language,
|
||||
)
|
||||
# Dernier message = "current" (souvent user), le reste = historique accumulé.
|
||||
current_msg = messages[-1] if messages else None
|
||||
@@ -109,6 +112,7 @@ async def chat_stream(
|
||||
narrative_entity=narrative_entity,
|
||||
game_system_context=game_system_context,
|
||||
session_context=session_context,
|
||||
language=language,
|
||||
):
|
||||
# json.dumps avec ensure_ascii=False pour préserver les accents
|
||||
yield f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
||||
|
||||
@@ -6,7 +6,9 @@ from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.deps import get_generate_page_use_case, get_llm_provider
|
||||
from app.application.generate_page import GeneratePageUseCase
|
||||
from app.application.prompts import conversation_title as title_prompts
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.core.language import get_user_language
|
||||
from app.domain.models import PageGenerationContext
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
@@ -60,6 +62,7 @@ async def generate_page(
|
||||
use_case: Annotated[
|
||||
GeneratePageUseCase, Depends(get_generate_page_use_case)
|
||||
],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> GeneratePageResponseDTO:
|
||||
"""Endpoint métier : contexte LoreMind → valeurs structurées par champ.
|
||||
|
||||
@@ -76,7 +79,7 @@ async def generate_page(
|
||||
)
|
||||
|
||||
try:
|
||||
result = await use_case.execute(context)
|
||||
result = await use_case.execute(context, language=language)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
@@ -101,18 +104,11 @@ class SummarizeTitleResponseDTO(BaseModel):
|
||||
title: str
|
||||
|
||||
|
||||
_TITLE_SYSTEM_PROMPT = (
|
||||
"Tu generes un titre court (4 a 7 mots max) qui resume le sujet de la "
|
||||
"conversation ci-dessous. Reponds UNIQUEMENT par le titre, sans guillemets, "
|
||||
"sans ponctuation finale, sans prefixe type 'Titre :'. Le titre doit etre "
|
||||
"en francais et capturer le sujet metier (pas 'Conversation IA')."
|
||||
)
|
||||
|
||||
|
||||
@router.post("/summarize/conversation-title", response_model=SummarizeTitleResponseDTO)
|
||||
async def summarize_conversation_title(
|
||||
body: SummarizeTitleRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> SummarizeTitleResponseDTO:
|
||||
"""Genere un titre court a partir des premiers echanges de la conversation.
|
||||
|
||||
@@ -123,7 +119,7 @@ async def summarize_conversation_title(
|
||||
raise HTTPException(status_code=422, detail="Au moins un message requis")
|
||||
|
||||
transcript = "\n".join(f"{m.role.upper()}: {m.content}" for m in body.messages[:6])
|
||||
prompt = f"{_TITLE_SYSTEM_PROMPT}\n\nConversation :\n{transcript}\n\nTitre :"
|
||||
prompt = f"{title_prompts.title_system_prompt(language)}\n\nConversation :\n{transcript}\n\nTitre :"
|
||||
try:
|
||||
raw = await llm.generate(prompt)
|
||||
except LLMProviderError as exc:
|
||||
@@ -133,5 +129,5 @@ async def summarize_conversation_title(
|
||||
if len(title) > 80:
|
||||
title = title[:80].rstrip()
|
||||
if not title:
|
||||
title = "Nouvelle conversation"
|
||||
title = title_prompts.TITLE_FALLBACK.get(language, title_prompts.TITLE_FALLBACK["fr"])
|
||||
return SummarizeTitleResponseDTO(title=title)
|
||||
|
||||
@@ -16,6 +16,7 @@ from app.api.deps import (
|
||||
from app.application.adapt_campaign import AdaptCampaignUseCase
|
||||
from app.application.import_campaign import ImportCampaignUseCase
|
||||
from app.application.import_rules import ImportRulesUseCase
|
||||
from app.core.language import get_user_language
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError, PdfExtractionError
|
||||
|
||||
@@ -40,6 +41,7 @@ class RulesImportResponseDTO(BaseModel):
|
||||
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
||||
async def import_rules(
|
||||
use_case: Annotated[ImportRulesUseCase, Depends(get_import_rules_use_case)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
file: UploadFile = File(...),
|
||||
) -> RulesImportResponseDTO:
|
||||
"""Import d'un PDF de règles → sections markdown structurées (proposition).
|
||||
@@ -58,7 +60,7 @@ async def import_rules(
|
||||
)
|
||||
|
||||
try:
|
||||
result = await use_case.execute(content)
|
||||
result = await use_case.execute(content, language=language)
|
||||
except PdfExtractionError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except LLMProviderError as exc:
|
||||
@@ -74,6 +76,7 @@ async def import_rules(
|
||||
@router.post("/import/rules/stream")
|
||||
async def import_rules_stream(
|
||||
use_case: Annotated[ImportRulesUseCase, Depends(get_import_rules_use_case)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
file: UploadFile = File(...),
|
||||
) -> StreamingResponse:
|
||||
"""Import streamé : émet l'avancement (SSE) puis le résultat final.
|
||||
@@ -93,7 +96,7 @@ async def import_rules_stream(
|
||||
yield sse_event("error", {"message": upload_error})
|
||||
return
|
||||
try:
|
||||
async for ev in use_case.stream(content):
|
||||
async for ev in use_case.stream(content, language=language):
|
||||
event_type = ev.pop("type")
|
||||
yield sse_event(event_type, ev)
|
||||
except PdfExtractionError as exc:
|
||||
@@ -146,6 +149,7 @@ async def import_campaign_stream(
|
||||
@router.post("/adapt/campaign/stream")
|
||||
async def adapt_campaign_stream(
|
||||
use_case: Annotated[AdaptCampaignUseCase, Depends(get_adapt_campaign_use_case)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
file: UploadFile = File(...),
|
||||
brief: str = Form(""),
|
||||
messages: str = Form("[]"),
|
||||
@@ -173,7 +177,7 @@ async def adapt_campaign_stream(
|
||||
yield sse_event("error", {"message": upload_error})
|
||||
return
|
||||
try:
|
||||
async for token in use_case.stream(content, brief, convo):
|
||||
async for token in use_case.stream(content, brief, convo, language=language):
|
||||
yield sse_event("token", {"token": token})
|
||||
yield sse_event("done", {})
|
||||
except PdfExtractionError as exc:
|
||||
|
||||
@@ -17,6 +17,7 @@ from app.application.notebook_chat import NotebookChatUseCase
|
||||
from app.application.notebook_deep import NotebookDeepUseCase
|
||||
from app.application.notebook_rag import NotebookRagUseCase
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.core.language import get_user_language
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError, PdfExtractionError
|
||||
from app.infrastructure import vector_store
|
||||
@@ -77,6 +78,7 @@ async def chat_notebook_stream(
|
||||
body: NotebookChatRequestDTO,
|
||||
use_case: Annotated[NotebookChatUseCase, Depends(get_notebook_chat_use_case)],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> StreamingResponse:
|
||||
"""Chat ANCRÉ sur les sources (RAG) : récupère les passages pertinents puis
|
||||
streame la réponse. Évènements SSE : `token` {token}, `done` {}, `error` {message}."""
|
||||
@@ -85,7 +87,7 @@ async def chat_notebook_stream(
|
||||
|
||||
async def event_stream() -> AsyncIterator[str]:
|
||||
try:
|
||||
async for ev in use_case.stream(body.source_ids, messages, context=body.context, top_k=top_k):
|
||||
async for ev in use_case.stream(body.source_ids, messages, context=body.context, top_k=top_k, language=language):
|
||||
if ev["type"] == "token":
|
||||
if ev.get("token"):
|
||||
yield sse_event("token", {"token": ev["token"]})
|
||||
@@ -107,6 +109,7 @@ async def chat_notebook_stream(
|
||||
async def chat_notebook_deep_stream(
|
||||
body: NotebookChatRequestDTO,
|
||||
use_case: Annotated[NotebookDeepUseCase, Depends(get_notebook_deep_use_case)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> StreamingResponse:
|
||||
"""Analyse APPROFONDIE (map-reduce sur tout le document). Évènements SSE :
|
||||
`progress` {current,total} pendant la lecture, puis `token` {token}, puis `done`."""
|
||||
@@ -118,7 +121,7 @@ async def chat_notebook_deep_stream(
|
||||
yield sse_event("error", {"message": "Question vide."})
|
||||
return
|
||||
try:
|
||||
async for ev in use_case.stream(body.source_ids, messages, context=body.context):
|
||||
async for ev in use_case.stream(body.source_ids, messages, context=body.context, language=language):
|
||||
ev_type = ev.pop("type")
|
||||
yield sse_event(ev_type, ev)
|
||||
except (LLMProviderError, EmbeddingError) as exc:
|
||||
|
||||
@@ -8,6 +8,8 @@ from pydantic import BaseModel, Field
|
||||
from app.api.deps import get_llm_provider
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.prompts import tables as prompts
|
||||
from app.core.language import get_user_language
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
router = APIRouter()
|
||||
@@ -51,28 +53,15 @@ class GenerateTableResponseDTO(BaseModel):
|
||||
async def generate_random_table(
|
||||
body: GenerateTableRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> GenerateTableResponseDTO:
|
||||
"""Génère une table aléatoire (entrées par plage) couvrant la formule de dé."""
|
||||
rng = _dice_total_range(body.dice_formula)
|
||||
if rng is None:
|
||||
raise HTTPException(status_code=422, detail="Formule de dé invalide (ex. 1d20, 2d6, d100).")
|
||||
lo, hi = rng
|
||||
context_block = f"\nContexte de la campagne :\n{body.context.strip()}\n" if body.context.strip() else ""
|
||||
prompt = (
|
||||
"Tu es un assistant de jeu de rôle. Génère une TABLE ALÉATOIRE évocatrice.\n"
|
||||
f"Dé : {body.dice_formula} (résultats possibles de {lo} à {hi}).\n"
|
||||
f"Sujet : {body.description.strip()}\n"
|
||||
f"{context_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format : {"name": "...", "description": "...", "entries": '
|
||||
'[{"min_roll": N, "max_roll": M, "label": "résultat court", "detail": "1-2 phrases"}]}\n'
|
||||
f"- Les plages (min_roll..max_roll) doivent COUVRIR EXACTEMENT {lo}..{hi}, "
|
||||
"sans trou ni chevauchement, dans l'ordre croissant.\n"
|
||||
"- Des résultats variés, cohérents avec le sujet (et le contexte s'il est fourni).\n"
|
||||
"- En français. 'label' = résultat bref ; 'detail' = description/effet concret.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
prompt = prompts.random_table_prompt(
|
||||
body.description, body.dice_formula, lo, hi, body.context, language)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.7)
|
||||
except LLMProviderError as exc:
|
||||
@@ -124,17 +113,11 @@ class ImproviseRollResponseDTO(BaseModel):
|
||||
async def improvise_table_roll(
|
||||
body: ImproviseRollRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> ImproviseRollResponseDTO:
|
||||
"""Brode un court récit (2-3 phrases) sur un résultat tiré, pour lancer la scène."""
|
||||
detail = f" ({body.result_detail.strip()})" if body.result_detail.strip() else ""
|
||||
context_block = f"\nContexte : {body.context.strip()}" if body.context.strip() else ""
|
||||
prompt = (
|
||||
"Tu es le Maître du Jeu. Les joueurs viennent de tirer sur la table "
|
||||
f"« {body.table_name.strip()} » et ont obtenu : « {body.result_label.strip()} »{detail}."
|
||||
f"{context_block}\n\n"
|
||||
"Décris en 2-3 phrases vivantes et immédiates ce qui se passe, pour lancer la scène. "
|
||||
"Pas de méta, pas d'options : juste la narration, en français."
|
||||
)
|
||||
prompt = prompts.improvise_roll_prompt(
|
||||
body.table_name, body.result_label, body.result_detail, body.context, language)
|
||||
try:
|
||||
raw = await llm.generate(prompt, temperature=0.8)
|
||||
except LLMProviderError as exc:
|
||||
@@ -167,22 +150,10 @@ class GenerateCatalogResponseDTO(BaseModel):
|
||||
async def generate_item_catalog(
|
||||
body: GenerateCatalogRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> GenerateCatalogResponseDTO:
|
||||
"""Génère un catalogue d'objets (boutique, butin…) — nom, prix, catégorie, description."""
|
||||
context_block = f"\nContexte de la campagne :\n{body.context.strip()}\n" if body.context.strip() else ""
|
||||
prompt = (
|
||||
"Tu es un assistant de jeu de rôle. Génère un CATALOGUE D'OBJETS (boutique, butin, trésor…).\n"
|
||||
f"Sujet : {body.description.strip()}\n"
|
||||
f"{context_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format : {"name": "...", "description": "...", "items": '
|
||||
'[{"name": "Objet", "price": "ex. 50 po", "category": "ex. Armes", "description": "effet/détails"}]}\n'
|
||||
"- Des objets variés et cohérents avec le sujet (et le contexte s'il est fourni).\n"
|
||||
"- 'price' = prix court dans la monnaie du jeu ; 'category' = regroupement (Armes, Potions…) ; "
|
||||
"'description' = effet/détails en une phrase. En français.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
prompt = prompts.item_catalog_prompt(body.description, body.context, language)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.7)
|
||||
except LLMProviderError as exc:
|
||||
|
||||
@@ -13,6 +13,8 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import AsyncIterator
|
||||
|
||||
from app.application.prompts import adapt_campaign as prompts
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMChatProvider, PdfExtractionError, PdfTextExtractor
|
||||
|
||||
@@ -21,27 +23,6 @@ logger = logging.getLogger(__name__)
|
||||
# Plus créatif que l'import (tâche de structuration) : ici on conseille/adapte.
|
||||
_TEMPERATURE = 0.7
|
||||
|
||||
_SYSTEM_PREFIX = (
|
||||
"Tu es un assistant pour Maître de Jeu de jeu de rôle. L'utilisateur a une "
|
||||
"campagne EXISTANTE (décrite plus bas) et souhaite ADAPTER et INTÉGRER le "
|
||||
"contenu d'un PDF (aventure, donjon, supplément) à CETTE campagne précise."
|
||||
)
|
||||
|
||||
_SYSTEM_SUFFIX = (
|
||||
"Produis des CONSEILS D'ADAPTATION concrets, actionnables et en FRANÇAIS, "
|
||||
"en markdown structuré (titres ##, listes). Couvre notamment :\n"
|
||||
"- **Où l'insérer** : à quel(s) arc(s)/chapitre(s) EXISTANT(s) rattacher ce "
|
||||
"contenu, dans quel ordre, et — si l'arc est un hub — sous quelles conditions de déblocage.\n"
|
||||
"- **Reskins / liens PNJ** : quels PNJ EXISTANTS de la campagne peuvent incarner "
|
||||
"ou remplacer les personnages clés du PDF.\n"
|
||||
"- **Adaptation à l'univers** : comment transposer lieux, factions, noms propres et "
|
||||
"ton vers l'univers de l'utilisateur plutôt que le cadre d'origine du PDF.\n"
|
||||
"- **Doublons / conflits** : ce qui recoupe l'existant et comment le réconcilier.\n"
|
||||
"- **Ajustements de ton et de difficulté**.\n\n"
|
||||
"Réfère-toi TOUJOURS aux éléments existants par leur NOM. Ne réécris PAS le PDF en "
|
||||
"entier : donne des recommandations. Si une information manque, propose des options."
|
||||
)
|
||||
|
||||
|
||||
class AdaptCampaignUseCase:
|
||||
"""Génère (en streaming) des conseils d'adaptation d'un PDF à une campagne."""
|
||||
@@ -64,6 +45,7 @@ class AdaptCampaignUseCase:
|
||||
pdf_bytes: bytes,
|
||||
brief: str,
|
||||
messages: list[ChatMessage],
|
||||
language: str = _DEFAULT_LANG,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Conversationnel : le PDF + la campagne sont le CONTEXTE (system prompt),
|
||||
`messages` est l'échange (demande initiale, puis feedbacks de l'utilisateur)."""
|
||||
@@ -87,12 +69,12 @@ class AdaptCampaignUseCase:
|
||||
)
|
||||
# Concaténation (pas .format) : brief/PDF peuvent contenir des { } littéraux.
|
||||
system_prompt = (
|
||||
f"{_SYSTEM_PREFIX}\n\n"
|
||||
f"{prompts.SYSTEM_PREFIX}\n\n"
|
||||
"--- CAMPAGNE EXISTANTE DE L'UTILISATEUR ---\n"
|
||||
f"{brief.strip() or '(campagne encore vide)'}\n\n"
|
||||
"--- CONTENU DU PDF À ADAPTER ---\n"
|
||||
f"{pdf_text}{trunc_note}\n\n"
|
||||
f"{_SYSTEM_SUFFIX}\n\n"
|
||||
f"{prompts.system_suffix(language)}\n\n"
|
||||
"Tu es en CONVERSATION : à chaque message de l'utilisateur, ajuste, corrige "
|
||||
"ou propose des alternatives en gardant tout ce contexte à l'esprit."
|
||||
)
|
||||
|
||||
@@ -31,6 +31,8 @@ from app.domain.models import (
|
||||
QuestSummary,
|
||||
SessionContext,
|
||||
)
|
||||
from app.application.prompts import chat as prompts
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG
|
||||
from app.domain.ports import LLMChatProvider
|
||||
|
||||
|
||||
@@ -40,21 +42,6 @@ from app.domain.ports import LLMChatProvider
|
||||
_DEFAULT_TEMPERATURE = 0.7
|
||||
|
||||
|
||||
_BASE_SYSTEM = """Tu es un assistant d'écriture pour un Maître de Jeu de JDR.
|
||||
Tu dialogues avec le MJ pour l'aider à enrichir son univers et ses campagnes.
|
||||
|
||||
Règles de ton :
|
||||
- Réponds en français, ton chaleureux et créatif.
|
||||
- Sois concis : listes à puces courtes plutôt que longs paragraphes.
|
||||
- Propose des idées qui s'intègrent dans le contexte existant ci-dessous.
|
||||
|
||||
Règles de cohérence (IMPORTANT) :
|
||||
- Tu PEUX et DOIS inventer des éléments originaux (personnages, lieux, objets, intrigues, créatures, scènes) — c'est ton rôle d'assistant créatif.
|
||||
- Tu ne peux PAS faire référence à un élément du MJ (du Lore, des arcs, chapitres ou scènes) comme s'il existait déjà, SAUF s'il apparaît EXACTEMENT (même orthographe) dans l'une des sections de contexte ci-dessous.
|
||||
- Si l'utilisateur mentionne un nom que tu ne vois pas dans le contexte, ne fais surtout pas semblant de le connaître : dis clairement "Je ne vois pas [nom] dans le contexte actuel, veux-tu qu'on le crée ?" plutôt que d'inventer des détails à son sujet.
|
||||
- Évite les précisions inventées qu'on ne peut pas vérifier : dates exactes, chiffres de population, hiérarchies politiques complexes, généalogies détaillées. Préfère des formulations ouvertes que le MJ validera ("il y a longtemps", "de nombreux", "la haute noblesse")."""
|
||||
|
||||
|
||||
class ChatUseCase:
|
||||
"""Orchestre un tour de conversation avec le LLM + contextes structurels."""
|
||||
|
||||
@@ -71,16 +58,18 @@ class ChatUseCase:
|
||||
narrative_entity: NarrativeEntityContext | None = None,
|
||||
game_system_context: GameSystemContext | None = None,
|
||||
session_context: SessionContext | None = None,
|
||||
language: str = _DEFAULT_LANG,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Streame les tokens de la réponse assistant pour le dernier message user.
|
||||
|
||||
Les contextes sont tous optionnels, mais au moins l'un des deux
|
||||
"niveaux haut" (lore_context ou campaign_context) doit être fourni
|
||||
pour que le prompt ait du sens. Le controller (main.py) applique
|
||||
cette règle à la frontière HTTP.
|
||||
cette règle à la frontière HTTP. `language` pilote la langue de réponse.
|
||||
"""
|
||||
system_prompt = self._build_system_prompt(
|
||||
lore_context, page_context, campaign_context, narrative_entity, game_system_context, session_context
|
||||
lore_context, page_context, campaign_context, narrative_entity,
|
||||
game_system_context, session_context, language,
|
||||
)
|
||||
async for token in self._llm.stream_chat(
|
||||
messages,
|
||||
@@ -97,12 +86,14 @@ class ChatUseCase:
|
||||
narrative_entity: NarrativeEntityContext | None = None,
|
||||
game_system_context: GameSystemContext | None = None,
|
||||
session_context: SessionContext | None = None,
|
||||
language: str = _DEFAULT_LANG,
|
||||
) -> str:
|
||||
"""Version publique — utilisée par le controller HTTP pour compter
|
||||
les tokens du system prompt avant de streamer (jauge de contexte).
|
||||
"""
|
||||
return self._build_system_prompt(
|
||||
lore_context, page_context, campaign_context, narrative_entity, game_system_context, session_context
|
||||
lore_context, page_context, campaign_context, narrative_entity,
|
||||
game_system_context, session_context, language,
|
||||
)
|
||||
|
||||
# --- Construction du system prompt --------------------------------------
|
||||
@@ -115,8 +106,9 @@ class ChatUseCase:
|
||||
narrative: NarrativeEntityContext | None,
|
||||
game_system: GameSystemContext | None = None,
|
||||
session: SessionContext | None = None,
|
||||
language: str = _DEFAULT_LANG,
|
||||
) -> str:
|
||||
sections = [_BASE_SYSTEM]
|
||||
sections = [prompts.base_system(language)]
|
||||
if lore is not None:
|
||||
sections.append(self._format_lore(lore))
|
||||
if campaign is not None:
|
||||
|
||||
@@ -8,9 +8,13 @@ permet de tester ce use case avec un FakeLLMProvider, sans Ollama qui tourne.
|
||||
"""
|
||||
import json
|
||||
|
||||
from app.application.prompts import generate_page as prompts
|
||||
from app.domain.models import PageGenerationContext, PageGenerationResult
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
# Langue de repli quand le router n'en fournit pas (appel direct / vieux client).
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG
|
||||
|
||||
|
||||
# Température basse : remplissage de champs = tâche factuelle, peu créative.
|
||||
# Une valeur trop haute (par défaut Ollama = 0.8) encourage l'IA à broder
|
||||
@@ -18,21 +22,6 @@ from app.domain.ports import LLMProvider, LLMProviderError
|
||||
_DEFAULT_TEMPERATURE = 0.4
|
||||
|
||||
|
||||
_SYSTEM_INSTRUCTIONS = """Tu es un assistant d'écriture pour un Maître de Jeu de JDR.
|
||||
Tu vas générer le contenu d'une page appartenant à un univers fictionnel.
|
||||
|
||||
Règles impératives de ta réponse :
|
||||
- Tu réponds UNIQUEMENT par un objet JSON valide.
|
||||
- Les clés du JSON correspondent EXACTEMENT aux noms de champs demandés.
|
||||
- Les valeurs sont des chaînes de texte en français, riches et évocatrices.
|
||||
- Aucun markdown, aucune explication, aucun commentaire autour du JSON.
|
||||
|
||||
Règles de cohérence (IMPORTANT) :
|
||||
- Tu PEUX inventer des détails originaux pour CETTE page : apparence, traits de caractère, anecdotes, histoire personnelle.
|
||||
- Tu ne dois PAS faire référence à d'autres personnages, lieux, organisations ou événements comme s'ils existaient déjà dans l'univers, sauf si le contexte ci-dessous les mentionne explicitement.
|
||||
- Si un champ appelle une précision externe (date, nom d'un roi, ville voisine, guerre passée), reste volontairement vague : "il y a de nombreuses années", "un bourg voisin", "une époque troublée". Le MJ préfère combler lui-même les blancs plutôt que trouver des faits inventés contradictoires avec son univers."""
|
||||
|
||||
|
||||
class GeneratePageUseCase:
|
||||
"""Orchestre la génération d'une page LoreMind via un LLM."""
|
||||
|
||||
@@ -42,8 +31,9 @@ class GeneratePageUseCase:
|
||||
async def execute(
|
||||
self,
|
||||
context: PageGenerationContext,
|
||||
language: str = _DEFAULT_LANG,
|
||||
) -> PageGenerationResult:
|
||||
prompt = self._build_prompt(context)
|
||||
prompt = self._build_prompt(context, language)
|
||||
raw = await self._llm.generate(
|
||||
prompt,
|
||||
output_format="json",
|
||||
@@ -53,7 +43,7 @@ class GeneratePageUseCase:
|
||||
return PageGenerationResult(values=values)
|
||||
|
||||
@staticmethod
|
||||
def _build_prompt(context: PageGenerationContext) -> str:
|
||||
def _build_prompt(context: PageGenerationContext, language: str = _DEFAULT_LANG) -> str:
|
||||
fields_block = "\n".join(f'- "{field}"' for field in context.template_fields)
|
||||
lore_desc_line = (
|
||||
f"\nDescription de l'univers : {context.lore_description}"
|
||||
@@ -62,7 +52,7 @@ class GeneratePageUseCase:
|
||||
)
|
||||
|
||||
return (
|
||||
f"{_SYSTEM_INSTRUCTIONS}\n\n"
|
||||
f"{prompts.system_instructions(language)}\n\n"
|
||||
f"Univers : {context.lore_name}"
|
||||
f"{lore_desc_line}\n"
|
||||
f"Catégorie (dossier) : {context.folder_name}\n"
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.application.import_status import (
|
||||
)
|
||||
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.prompts import import_campaign as prompts
|
||||
from app.application.streaming import with_heartbeat
|
||||
|
||||
# Repli anti-troncature : si la sortie d'un morceau est coupée, on le retraite en
|
||||
@@ -47,76 +48,11 @@ logger = logging.getLogger(__name__)
|
||||
# Plus la valeur est haute, plus le modèle "brode" (invente du contenu absent).
|
||||
_TEMPERATURE = 0.1
|
||||
|
||||
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
||||
_DEFAULT_ARC_NAME = "Aventure principale"
|
||||
|
||||
# Morceaux PLUS GROS que pour les règles : l'IA voit une quête/un chapitre entier
|
||||
# d'un coup et le structure de façon cohérente (1 scène par lieu) au lieu de le
|
||||
# fragmenter en dizaines de scènes. Adapté aux providers à grand contexte (1min.ai).
|
||||
_CHUNK_TARGET_TOKENS = 10000
|
||||
|
||||
_MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
||||
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
||||
|
||||
Ta tâche : en dégager une ARBORESCENCE narrative à GROS GRAIN : arcs → chapitres → scènes,
|
||||
et — pour les lieux explorables — leurs PIÈCES (rooms).
|
||||
- Un ARC = un acte / une grande partie de la campagne (souvent un seul pour une aventure courte).
|
||||
- Un CHAPITRE = une étape majeure du récit : un chapitre du livre, OU — dans une
|
||||
campagne "hub" / bac-à-sable — UNE QUÊTE ou UN LIEU principal débloqué depuis le
|
||||
point central (ex : Dragon of Icespire Peak → chaque quête/lieu = un chapitre).
|
||||
- Une SCÈNE = un temps fort jouable du chapitre : un lieu, une rencontre clé, un moment pivot.
|
||||
- Une PIÈCE (room) = une salle d'un lieu explorable (donjon, crypte, manoir...).
|
||||
|
||||
TYPE D'ARC ("type") :
|
||||
- "HUB" si la campagne est un bac-à-sable : des quêtes/lieux optionnels, parallèles,
|
||||
débloqués depuis un point central, SANS ordre fixe imposé (ex : Dragon of Icespire Peak).
|
||||
- "LINEAR" si les chapitres se jouent dans un ordre séquentiel imposé.
|
||||
- Dans le doute : "LINEAR".
|
||||
|
||||
GRANULARITÉ (évite la sur-détection) :
|
||||
- Vise PEU de scènes : typiquement 1 à 6 par chapitre. PAS des dizaines.
|
||||
- Un LIEU EXPLORABLE (donjon, crypte, manoir, grotte à plusieurs salles) = UNE SEULE
|
||||
scène. Ses salles vont dans le tableau "rooms" de cette scène — JAMAIS en scènes séparées.
|
||||
- NE crée PAS une scène par rencontre isolée, par PNJ, par monstre ou par paragraphe.
|
||||
- IGNORE : blocs de stats, listes de monstres, encarts de règles, légendes de cartes,
|
||||
pieds de page, sommaires, crédits.
|
||||
|
||||
CONTENU D'UNE SCÈNE (fidélité au livre — important) :
|
||||
- `description` = synopsis de la scène, 2 à 4 phrases (plus que 1 ligne, mais pas le texte intégral).
|
||||
- `player_narration` = le texte d'AMBIANCE « à lire aux joueurs » (encadrés / boxed text /
|
||||
« lecture à voix haute »), recopié FIDÈLEMENT s'il existe dans l'extrait. Vide sinon.
|
||||
- `gm_notes` = les informations pour le MJ : secrets, développement, ce qui se passe,
|
||||
conséquences, indices cachés. Vide si rien de tel.
|
||||
- Ne RÉSUME pas abusivement player_narration et gm_notes : recopie le contenu utile du livre.
|
||||
|
||||
PIÈCES (rooms) — uniquement pour les scènes qui sont des lieux explorables :
|
||||
- Une entrée par salle numérotée/nommée du donjon (ex : "1. Entrée", "2. Salle des gardes").
|
||||
- `enemies` = créatures/boss de la salle (vide si aucune). `loot` = trésor/récompense (vide si aucun).
|
||||
- Pour une scène narrative classique (pas un donjon), "rooms" est un tableau vide [].
|
||||
|
||||
PNJ ET CRÉATURES NOTABLES ("npcs", tableau au niveau racine) :
|
||||
- Recense les PNJ NOMMÉS (alliés, marchands, antagonistes) et les créatures UNIQUES
|
||||
(boss, monstre récurrent) présents dans l'extrait.
|
||||
- `description` = courte fiche utile au MJ : rôle dans l'histoire, apparence,
|
||||
motivations, où on le rencontre. 2 à 4 phrases, fidèles au livre.
|
||||
- N'inclus PAS les monstres génériques sans nom (« 3 gobelins », « un loup »).
|
||||
- Aucun PNJ nommé dans l'extrait → "npcs": [].
|
||||
|
||||
Format de réponse :
|
||||
- Tu réponds UNIQUEMENT par un objet JSON valide, sans markdown ni commentaire autour.
|
||||
- Schéma EXACT :
|
||||
{{"arcs": [{{"name": "...", "description": "...", "type": "LINEAR",
|
||||
"chapters": [{{"name": "...", "description": "...", "scenes": [
|
||||
{{"name": "...", "description": "...", "player_narration": "...", "gm_notes": "...",
|
||||
"rooms": [{{"name": "...", "description": "...", "enemies": "...", "loot": "..."}}]}}
|
||||
]}}]}}
|
||||
],
|
||||
"npcs": [{{"name": "...", "description": "..."}}]}}
|
||||
- Utilise les VRAIS titres du livre pour les noms (pas de paraphrase).
|
||||
- Si le livre n'est PAS découpé en actes/parties, regroupe tout sous un seul arc nommé "{default_arc}".
|
||||
- N'invente pas de contenu : tu réorganises et recopies ce qui est présent dans l'extrait.
|
||||
- Si l'extrait ne contient aucune matière narrative, renvoie {{"arcs": []}}."""
|
||||
|
||||
# Schéma de l'arbre attendu, passé aux providers à sorties structurées (Ollama
|
||||
# contraint la grammaire : un modèle local ne PEUT plus produire de clés
|
||||
# inventées, d'objets bavards type "thought" ni de texte hors JSON). Les
|
||||
@@ -195,47 +131,12 @@ _TREE_SCHEMA: dict = {
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
# Bloc TOC injecté quand le PDF a des bookmarks : les morceaux étant traités
|
||||
# séparément, c'est CE référentiel commun qui garantit que tous nomment les
|
||||
# mêmes chapitres à l'identique → la fusion par nom du _TreeMerger recolle
|
||||
# les chapitres coupés au lieu de créer des doublons.
|
||||
_TOC_BLOCK = """
|
||||
|
||||
--- STRUCTURE OFFICIELLE DU LIVRE (table des matières du PDF) ---
|
||||
{toc}
|
||||
--- FIN DE LA STRUCTURE ---
|
||||
IMPORTANT : pour nommer les arcs et chapitres, reprends EXACTEMENT les titres
|
||||
de cette structure (caractère pour caractère). Rattache le contenu de l'extrait
|
||||
au bon chapitre de la structure, même si son titre n'apparaît pas dans l'extrait."""
|
||||
|
||||
# Garde-fou prompt : une TOC de gros livre peut compter des centaines d'entrées
|
||||
# (sous-sous-sections). On la limite aux niveaux hauts et à un nombre raisonnable.
|
||||
_TOC_MAX_LEVEL = 2
|
||||
_TOC_MAX_ENTRIES = 80
|
||||
|
||||
|
||||
# Consolidation finale : le squelette (noms seuls) est minuscule, donc l'appel
|
||||
# est quasi gratuit comparé aux MAP. Température 0 et consigne CONSERVATRICE :
|
||||
# ne fusionner que les doublons évidents, jamais des entités distinctes.
|
||||
_CONSOLIDATE_PROMPT = """Voici le squelette d'une arborescence arc → chapitre → scène issue d'une
|
||||
fusion AUTOMATIQUE de morceaux d'un livre de campagne de jeu de rôle. La fusion par nom exact
|
||||
peut avoir laissé des QUASI-DOUBLONS : le même chapitre ou la même scène sous deux libellés
|
||||
légèrement différents (ex: "La Crypte" et "Crypte de Karrak", "3. Salle des gardes" et
|
||||
"Salle des gardes").
|
||||
|
||||
{skeleton}
|
||||
|
||||
Identifie UNIQUEMENT les fusions ÉVIDENTES (même entité du livre sous deux noms). Sois
|
||||
CONSERVATEUR : dans le doute, ne fusionne PAS. Deux lieux/évènements distincts ne doivent
|
||||
JAMAIS être fusionnés.
|
||||
|
||||
Réponds UNIQUEMENT par un objet JSON valide :
|
||||
{{"chapter_merges": [{{"into": "nom du chapitre à garder", "merge": ["nom à fusionner", ...]}}],
|
||||
"scene_merges": [{{"chapter": "nom du chapitre", "into": "nom de la scène à garder",
|
||||
"merge": ["nom à fusionner", ...]}}]}}
|
||||
S'il n'y a RIEN à fusionner (cas le plus fréquent) : {{"chapter_merges": [], "scene_merges": []}}"""
|
||||
|
||||
|
||||
def _format_toc(toc) -> str:
|
||||
"""Formate la TOC du PDF en liste indentée, bornée (niveaux hauts d'abord)."""
|
||||
entries = [e for e in toc if e.level <= _TOC_MAX_LEVEL][:_TOC_MAX_ENTRIES]
|
||||
@@ -626,7 +527,7 @@ class ImportCampaignUseCase:
|
||||
skeleton = merger.skeleton_text()
|
||||
try:
|
||||
raw = await generate_with_retry(
|
||||
self._llm, _CONSOLIDATE_PROMPT.format(skeleton=skeleton),
|
||||
self._llm, prompts.CONSOLIDATE_PROMPT.format(skeleton=skeleton),
|
||||
output_format="json", temperature=0.0)
|
||||
except Exception as exc: # noqa: BLE001 — best-effort STRICT : une erreur ici
|
||||
# (LLM, réseau, bug) ne doit JAMAIS faire perdre un import terminé.
|
||||
@@ -664,9 +565,9 @@ class ImportCampaignUseCase:
|
||||
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
||||
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
||||
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
||||
toc_section = _TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||
prompt = (
|
||||
_MAP_SYSTEM.format(default_arc=_DEFAULT_ARC_NAME)
|
||||
prompts.MAP_SYSTEM.format(default_arc=prompts.DEFAULT_ARC_NAME)
|
||||
+ toc_section
|
||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||
"Renvoie maintenant le JSON de l'arborescence."
|
||||
|
||||
@@ -25,7 +25,9 @@ from app.application.import_status import (
|
||||
)
|
||||
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.prompts import import_rules as prompts
|
||||
from app.application.streaming import with_heartbeat
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||
|
||||
# Repli anti-troncature : si la SORTIE d'un morceau est coupée (le modèle ne peut
|
||||
# pas tout réécrire en une réponse), on retraite ce morceau en 2 moitiés. Borné en
|
||||
@@ -57,43 +59,6 @@ _SECTIONS_SCHEMA: dict = {
|
||||
"additionalProperties": {"type": "string"},
|
||||
}
|
||||
|
||||
# Taxonomie canonique suggérée au modèle pour homogénéiser les titres entre
|
||||
# morceaux (sinon "Combat" / "Le combat" / "Règles de combat" se dispersent).
|
||||
# Le modèle reste libre d'en créer d'autres si rien ne correspond.
|
||||
_CANONICAL_SECTIONS = [
|
||||
"Règles générales",
|
||||
"Création de personnage",
|
||||
"Caractéristiques et tests",
|
||||
"Compétences",
|
||||
"Combat",
|
||||
"Magie et sorts",
|
||||
"Équipement et objets",
|
||||
"États et conditions",
|
||||
"Repos et récupération",
|
||||
"Progression et niveaux",
|
||||
"Conseils au Maître de Jeu",
|
||||
]
|
||||
|
||||
_MAP_SYSTEM = """Tu es un assistant qui réorganise un livre de règles de jeu de rôle.
|
||||
On te donne un EXTRAIT brut d'un PDF de règles (texte parfois mal coupé par la mise en page).
|
||||
|
||||
Ta tâche : répartir le contenu de cet extrait dans des SECTIONS THÉMATIQUES.
|
||||
|
||||
Format EXACT attendu — un objet JSON plat {{titre de section: contenu markdown}} :
|
||||
{{"Combat": "## Initiative\\n\\nChaque participant lance 1d20...", "Magie et sorts": "## Sorts\\n\\n..."}}
|
||||
|
||||
Règles impératives :
|
||||
- Tu réponds UNIQUEMENT par cet objet JSON, sans texte avant ni après.
|
||||
- Les CLÉS sont des titres de section (texte court). Les VALEURS sont le contenu de la règle en markdown (chaîne de caractères, jamais un objet ou une liste).
|
||||
- INTERDIT : des clés génériques comme "title", "content", "sections", "thought" ou "notes" ; des objets imbriqués ; tout commentaire sur ta démarche ou ton raisonnement.
|
||||
- Utilise EN PRIORITÉ ces titres canoniques quand le contenu y correspond :
|
||||
{canonical}
|
||||
- Si un contenu ne rentre dans aucun, crée un titre clair et concis (en français).
|
||||
- Reproduis FIDÈLEMENT les règles : tu peux nettoyer la coupure des lignes, recoller les mots coupés
|
||||
par un tiret en fin de ligne, retirer les en-têtes/pieds de page et numéros de page parasites.
|
||||
- N'INVENTE AUCUNE règle, ne résume pas abusivement : tu réorganises, tu ne réécris pas le fond.
|
||||
- Ignore les pages de garde, sommaires, crédits, pages vides (renvoie {{}} si l'extrait n'a aucune règle)."""
|
||||
|
||||
# --- Mode SEGMENTATION (modèles locaux) --------------------------------------
|
||||
# Réécrire tout le texte en JSON impose une SORTIE ≈ taille de l'ENTRÉE : à
|
||||
# ~100 tokens/s en local, un livre = des dizaines de minutes et des troncatures
|
||||
@@ -102,25 +67,6 @@ Règles impératives :
|
||||
# qui découpons le texte original. ~50× plus rapide, fidélité parfaite du
|
||||
# contenu (texte source intact), plus de troncature possible.
|
||||
|
||||
_SEGMENT_SYSTEM = """Tu analyses un EXTRAIT brut d'un livre de règles de jeu de rôle.
|
||||
Ta tâche : repérer où COMMENCENT les sections thématiques. Tu ne réécris RIEN.
|
||||
|
||||
Format EXACT attendu :
|
||||
{{"sections": [{{"titre": "Combat", "debut": "Le combat se déroule en tours de"}}, ...]}}
|
||||
|
||||
Règles impératives :
|
||||
- "debut" = les 5 à 10 PREMIERS MOTS du passage où la section commence, COPIÉS À L'IDENTIQUE
|
||||
depuis l'extrait (même orthographe, même ponctuation, même langue). JAMAIS un résumé.
|
||||
- La PREMIÈRE entrée commence aux tout premiers mots de l'extrait (même si le contenu
|
||||
poursuit une section entamée avant cet extrait).
|
||||
- Les entrées suivent l'ordre du texte. Vise des sections LARGES (un thème), pas un titre
|
||||
par paragraphe : un extrait contient typiquement 1 à 6 sections.
|
||||
- Titres : EN PRIORITÉ parmi :
|
||||
{canonical}
|
||||
sinon un titre court et clair en français.
|
||||
- Pages de garde, sommaires, crédits : n'en fais pas des sections. Si l'extrait n'est que ça,
|
||||
renvoie {{"sections": []}}."""
|
||||
|
||||
# Schéma passé à Ollama (structured outputs) : un objet {"sections": [...]}.
|
||||
# Racine objet (pas tableau) car l'extraction côté Brain repère le premier {…}.
|
||||
_ANCHORS_SCHEMA: dict = {
|
||||
@@ -293,7 +239,7 @@ class ImportRulesUseCase:
|
||||
self._chunk_target_tokens = chunk_target_tokens
|
||||
self._segment_only = segment_only
|
||||
|
||||
async def execute(self, pdf_bytes: bytes) -> RulesImportResult:
|
||||
async def execute(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG) -> RulesImportResult:
|
||||
"""Variante non-streamée : traite tout puis renvoie le résultat complet."""
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
@@ -303,14 +249,14 @@ class ImportRulesUseCase:
|
||||
)
|
||||
merger = _SectionMerger()
|
||||
for i, chunk in enumerate(chunks):
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks)))
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||
return RulesImportResult(
|
||||
sections=merger.result(),
|
||||
page_count=doc.page_count,
|
||||
ocr_page_count=doc.ocr_page_count,
|
||||
)
|
||||
|
||||
async def stream(self, pdf_bytes: bytes):
|
||||
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
|
||||
"""Variante streamée : yield des évènements d'avancement au fil de l'eau.
|
||||
|
||||
Évènements (dicts) : {"type": "extracting"}, puis
|
||||
@@ -353,7 +299,7 @@ class ImportRulesUseCase:
|
||||
try:
|
||||
sections: dict[str, str] | None = None
|
||||
async for kind, payload in with_heartbeat(
|
||||
self._map_chunk(chunk, index=i, total=total),
|
||||
self._map_chunk(chunk, index=i, total=total, language=language),
|
||||
status_queue=status_queue,
|
||||
):
|
||||
if kind == "heartbeat":
|
||||
@@ -408,20 +354,24 @@ class ImportRulesUseCase:
|
||||
|
||||
# --- MAP : un morceau → sections -----------------------------------------
|
||||
|
||||
async def _map_chunk(self, chunk: str, *, index: int, total: int) -> dict[str, str]:
|
||||
return await self._extract_sections(chunk, index=index, total=total, depth=0)
|
||||
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
||||
language: str = _DEFAULT_LANG) -> dict[str, str]:
|
||||
return await self._extract_sections(
|
||||
chunk, index=index, total=total, depth=0, language=language)
|
||||
|
||||
async def _extract_sections(
|
||||
self, text: str, *, index: int, total: int, depth: int
|
||||
self, text: str, *, index: int, total: int, depth: int,
|
||||
language: str = _DEFAULT_LANG,
|
||||
) -> dict[str, str]:
|
||||
"""Extrait les sections d'un texte. Si la SORTIE est tronquée, retraite le
|
||||
texte en DEUX moitiés (chacune produit une réponse complète) et fusionne —
|
||||
ainsi aucune section n'est perdue, quel que soit le plafond de sortie."""
|
||||
system = _SEGMENT_SYSTEM if self._segment_only else _MAP_SYSTEM
|
||||
system = prompts.SEGMENT_SYSTEM if self._segment_only else prompts.MAP_SYSTEM
|
||||
schema = _ANCHORS_SCHEMA if self._segment_only else _SECTIONS_SCHEMA
|
||||
prompt = (
|
||||
system.format(
|
||||
canonical="\n".join(f" - {s}" for s in _CANONICAL_SECTIONS)
|
||||
canonical="\n".join(f" - {s}" for s in prompts.CANONICAL_SECTIONS),
|
||||
language_name=language_name(language),
|
||||
)
|
||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||
"Renvoie maintenant le JSON des sections."
|
||||
@@ -444,8 +394,8 @@ class ImportRulesUseCase:
|
||||
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)
|
||||
b = await self._extract_sections(right, index=index, total=total, depth=depth + 1)
|
||||
a = await self._extract_sections(left, index=index, total=total, depth=depth + 1, language=language)
|
||||
b = await self._extract_sections(right, index=index, total=total, depth=depth + 1, language=language)
|
||||
return _combine_sections(a, b)
|
||||
if self._segment_only:
|
||||
sections, truncated = self._parse_anchors(raw, text, index=index)
|
||||
@@ -461,8 +411,8 @@ class ImportRulesUseCase:
|
||||
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)
|
||||
b = await self._extract_sections(right, index=index, total=total, depth=depth + 1)
|
||||
a = await self._extract_sections(left, index=index, total=total, depth=depth + 1, language=language)
|
||||
b = await self._extract_sections(right, index=index, total=total, depth=depth + 1, language=language)
|
||||
return _combine_sections(a, b)
|
||||
if truncated:
|
||||
logger.warning(
|
||||
|
||||
@@ -9,90 +9,13 @@ from __future__ import annotations
|
||||
from typing import AsyncIterator
|
||||
|
||||
from app.application.notebook_rag import NotebookRagUseCase
|
||||
from app.application.prompts import notebook as prompts
|
||||
from app.application.query_rewrite import standalone_question
|
||||
from app.application.rerank import pool_size, rerank
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMChatProvider
|
||||
|
||||
_SYSTEM_PROMPT = """Tu es un assistant de jeu de rôle qui aide à ADAPTER une source (PDF) à la CAMPAGNE de l'utilisateur.
|
||||
|
||||
Tu disposes de DEUX connaissances, toutes deux ci-dessous :
|
||||
1) LA CAMPAGNE de l'utilisateur (sa structure arcs/chapitres/scènes, ses PNJ, son univers) ;
|
||||
2) LA SOURCE (extraits pertinents du PDF).
|
||||
|
||||
Règles :
|
||||
- Pour une question sur SA CAMPAGNE (ex. « mon chapitre 3 », « mes PNJ »), appuie-toi sur la section CAMPAGNE.
|
||||
- Pour une question sur le livre, appuie-toi sur les EXTRAITS DE LA SOURCE.
|
||||
- CROISE les deux pour proposer des adaptations cohérentes avec sa campagne existante.
|
||||
- N'invente pas ce qui ne figure ni dans la campagne ni dans la source ; si tu ne sais pas, dis-le.
|
||||
- Quand un extrait porte un numéro de page (« (p. 12) »), cite-le (« d'après la p. 12 »).
|
||||
|
||||
{context_block}
|
||||
--- EXTRAITS PERTINENTS DE LA SOURCE ---
|
||||
{sources_block}
|
||||
--- FIN DES EXTRAITS ---
|
||||
|
||||
PROPOSITIONS D'INTÉGRATION (IMPORTANT) :
|
||||
Quand l'utilisateur veut CRÉER ou ADAPTER un élément concret pour sa campagne (un PNJ,
|
||||
une scène, un chapitre, une quête, un arc, une table aléatoire), termine ta réponse par
|
||||
un ou plusieurs BLOCS D'ACTION — un objet JSON par bloc, dans une clôture
|
||||
```loremind-action. L'interface les transformera en boutons « Créer dans la campagne ».
|
||||
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
|
||||
{{"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
|
||||
{{"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
|
||||
{{"type": "arc", "name": "Nom", "description": "Résumé", "arcType": "LINEAR",
|
||||
"themes": "Thèmes de l'arc", "stakes": "Enjeux",
|
||||
"rewards": "Récompenses attendues", "resolution": "Issues possibles",
|
||||
"gmNotes": "Notes MJ."}}
|
||||
```
|
||||
(`arcType` : "LINEAR" pour des chapitres en séquence, "HUB" pour un recueil de
|
||||
quêtes parallèles.)
|
||||
```loremind-action
|
||||
{{"type": "table", "name": "Nom", "diceFormula": "1d8", "entries": [{{"minRoll":1,"maxRoll":4,"label":"...","detail":"..."}}]}}
|
||||
```
|
||||
|
||||
Réponds en français, de façon utile et concise. Mets le texte explicatif AVANT les blocs d'action."""
|
||||
|
||||
|
||||
class NotebookChatUseCase:
|
||||
def __init__(
|
||||
@@ -109,6 +32,7 @@ class NotebookChatUseCase:
|
||||
messages: list[ChatMessage],
|
||||
context: str = "",
|
||||
top_k: int = 6,
|
||||
language: str = _DEFAULT_LANG,
|
||||
) -> AsyncIterator[dict]:
|
||||
"""Yield des évènements : {type:'sources', sources:[…]} (une fois, avant la
|
||||
réponse — transparence sur les passages utilisés), puis {type:'token', token}."""
|
||||
@@ -143,8 +67,9 @@ class NotebookChatUseCase:
|
||||
f"--- TA CAMPAGNE ---\n{context.strip()}\n--- FIN CAMPAGNE ---\n\n"
|
||||
if context.strip() else "--- TA CAMPAGNE ---\n(aucune donnée de campagne)\n--- FIN CAMPAGNE ---\n\n"
|
||||
)
|
||||
system_prompt = _SYSTEM_PROMPT.format(
|
||||
context_block=context_block, sources_block=sources_block)
|
||||
system_prompt = prompts.CHAT_SYSTEM.format(
|
||||
context_block=context_block, sources_block=sources_block,
|
||||
language_name=language_name(language))
|
||||
async for token in self._llm.stream_chat(messages, system_prompt=system_prompt):
|
||||
yield {"type": "token", "token": token}
|
||||
|
||||
|
||||
@@ -20,7 +20,9 @@ from typing import AsyncIterator
|
||||
import tiktoken
|
||||
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.prompts import notebook as prompts
|
||||
from app.application.query_rewrite import standalone_question
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMChatProvider, LLMProvider, LLMProviderError
|
||||
from app.infrastructure import vector_store
|
||||
@@ -36,15 +38,6 @@ _MAP_TEMPERATURE = 0.2
|
||||
# à la question par embedding, et seuls les lots plausiblement pertinents sont
|
||||
# relus. Sélection volontairement CONSERVATRICE (on préfère relire un lot de
|
||||
# trop que rater une mention) ; désactivable via deep_summary_filter=False.
|
||||
_SUMMARY_PROMPT = """Résume l'EXTRAIT ci-dessous en 4 à 8 puces factuelles : lieux, PNJ et
|
||||
créatures nommés, objets notables, évènements, règles particulières. Pas d'analyse, pas
|
||||
d'introduction — uniquement les puces, pour servir d'index de recherche.
|
||||
|
||||
--- EXTRAIT ---
|
||||
{excerpt}
|
||||
--- FIN EXTRAIT ---
|
||||
|
||||
Résumé :"""
|
||||
|
||||
# Un lot est gardé si son score est proche du meilleur (marge) OU bon dans
|
||||
# l'absolu ; et on garde toujours au moins _MIN_KEPT lots.
|
||||
@@ -52,38 +45,6 @@ _SELECT_MARGIN = 0.10
|
||||
_SELECT_FLOOR = 0.5
|
||||
_MIN_KEPT = 3
|
||||
|
||||
_MAP_PROMPT = """Voici un EXTRAIT d'un document. Extrais UNIQUEMENT les informations
|
||||
pertinentes pour répondre à la question ci-dessous. Conserve les détails utiles et
|
||||
indique les numéros de page (format « p. X »). Si l'extrait ne contient RIEN de
|
||||
pertinent, réponds EXACTEMENT « {no_match} » et rien d'autre.
|
||||
|
||||
QUESTION : {question}
|
||||
|
||||
--- EXTRAIT ---
|
||||
{excerpt}
|
||||
--- FIN EXTRAIT ---
|
||||
|
||||
Informations pertinentes (ou « {no_match} ») :"""
|
||||
|
||||
_REDUCE_SYSTEM = """Tu es l'assistant-MJ d'un jeu de rôle. Tu réponds à la demande du MJ en
|
||||
t'appuyant sur TROIS sources : (1) des NOTES extraites de l'ENSEMBLE du document source (vue
|
||||
complète — mais POSSIBLEMENT VIDE si rien d'utile n'y figure), (2) le contexte de sa CAMPAGNE,
|
||||
(3) la conversation ci-dessous.
|
||||
|
||||
- Si les notes contiennent des éléments utiles : exploite-les et CITE les pages (« p. X »).
|
||||
- Si les notes sont VIDES ou pauvres (cas fréquent d'une demande CRÉATIVE portant sur des
|
||||
éléments INVENTÉS par le MJ) : ne te bloque surtout PAS. Aide-le quand même en t'appuyant
|
||||
sur sa CAMPAGNE, la CONVERSATION et ta connaissance du genre — propose des adaptations
|
||||
concrètes (arcs, chapitres, scènes, PNJ), structurées et jouables.
|
||||
- Sois concret et utile. N'affirme rien de FAUX sur le contenu du document.
|
||||
|
||||
{context_block}
|
||||
--- NOTES EXTRAITES DE TOUT LE DOCUMENT ---
|
||||
{notes_block}
|
||||
--- FIN DES NOTES ---
|
||||
|
||||
Réponds en français."""
|
||||
|
||||
|
||||
class NotebookDeepUseCase:
|
||||
def __init__(
|
||||
@@ -109,6 +70,7 @@ class NotebookDeepUseCase:
|
||||
messages: list[ChatMessage],
|
||||
context: str = "",
|
||||
history_limit: int = 8,
|
||||
language: str = _DEFAULT_LANG,
|
||||
) -> AsyncIterator[dict]:
|
||||
"""Yield des évènements : {type:'progress',current,total}, {type:'token',token},
|
||||
{type:'done'}. (Les erreurs LLM des lots sont tolérées : lot ignoré.)
|
||||
@@ -175,7 +137,9 @@ class NotebookDeepUseCase:
|
||||
f"--- TA CAMPAGNE (structure, PNJ, univers) ---\n{context.strip()}\n--- FIN CAMPAGNE ---\n\n"
|
||||
if context.strip() else ""
|
||||
)
|
||||
system_prompt = _REDUCE_SYSTEM.format(context_block=context_block, notes_block=notes_block)
|
||||
system_prompt = prompts.REDUCE_SYSTEM.format(
|
||||
context_block=context_block, notes_block=notes_block,
|
||||
language_name=language_name(language))
|
||||
# Historique récent pour la cohérence des relances ; on garantit que le
|
||||
# dernier message est bien la question courante.
|
||||
reduce_messages = messages[-history_limit:] if messages else [ChatMessage(role="user", content=question)]
|
||||
@@ -251,7 +215,7 @@ class NotebookDeepUseCase:
|
||||
async def _summarize_batch(self, batch: list[dict]) -> str:
|
||||
excerpt = "\n\n".join(c.get("text", "").strip() for c in batch)
|
||||
raw = await generate_with_retry(
|
||||
self._llm, _SUMMARY_PROMPT.format(excerpt=excerpt), temperature=_MAP_TEMPERATURE)
|
||||
self._llm, prompts.SUMMARY_PROMPT.format(excerpt=excerpt), temperature=_MAP_TEMPERATURE)
|
||||
return (raw or "").strip()
|
||||
|
||||
async def _map_batch(self, question: str, batch: list[dict]) -> str:
|
||||
@@ -260,7 +224,7 @@ class NotebookDeepUseCase:
|
||||
f"(p. {c['page']}) {c['text'].strip()}" if c.get("page") else c["text"].strip()
|
||||
for c in batch
|
||||
)
|
||||
prompt = _MAP_PROMPT.format(no_match=_NO_MATCH, question=question, excerpt=excerpt)
|
||||
prompt = prompts.MAP_PROMPT.format(no_match=_NO_MATCH, question=question, excerpt=excerpt)
|
||||
raw = await generate_with_retry(self._llm, prompt, temperature=_MAP_TEMPERATURE)
|
||||
answer = raw.strip()
|
||||
if answer and answer.upper().rstrip(".") != _NO_MATCH:
|
||||
|
||||
12
brain/app/application/prompts/__init__.py
Normal file
12
brain/app/application/prompts/__init__.py
Normal file
@@ -0,0 +1,12 @@
|
||||
"""Prompts LLM, regroupés hors de la logique des use cases.
|
||||
|
||||
Un prompt est du code (couplé à son schéma de sortie et à son parsing), mais
|
||||
le mêler à la logique d'orchestration rend les use cases illisibles. Ce package
|
||||
isole le TEXTE des prompts : un module par domaine fonctionnel, miroir des
|
||||
modules de `app.application` / des routers.
|
||||
|
||||
Convention : les use cases importent depuis ici et gardent la logique (chunking,
|
||||
parsing, fusion, schémas de sortie JSON, températures, sentinelles). Les prompts
|
||||
restent en français (langue de travail) — seule la langue de SORTIE est
|
||||
paramétrée, cf. `app.core.language`.
|
||||
"""
|
||||
26
brain/app/application/prompts/adapt_campaign.py
Normal file
26
brain/app/application/prompts/adapt_campaign.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""Prompts des conseils d'adaptation d'un PDF à une campagne (cf. adapt_campaign.py)."""
|
||||
from app.core.language import language_name
|
||||
|
||||
SYSTEM_PREFIX = (
|
||||
"Tu es un assistant pour Maître de Jeu de jeu de rôle. L'utilisateur a une "
|
||||
"campagne EXISTANTE (décrite plus bas) et souhaite ADAPTER et INTÉGRER le "
|
||||
"contenu d'un PDF (aventure, donjon, supplément) à CETTE campagne précise."
|
||||
)
|
||||
|
||||
|
||||
def system_suffix(language: str) -> str:
|
||||
"""Consignes de sortie, avec la langue des conseils pilotée par l'utilisateur."""
|
||||
return (
|
||||
f"Produis des CONSEILS D'ADAPTATION concrets, actionnables et en {language_name(language).upper()}, "
|
||||
"en markdown structuré (titres ##, listes). Couvre notamment :\n"
|
||||
"- **Où l'insérer** : à quel(s) arc(s)/chapitre(s) EXISTANT(s) rattacher ce "
|
||||
"contenu, dans quel ordre, et — si l'arc est un hub — sous quelles conditions de déblocage.\n"
|
||||
"- **Reskins / liens PNJ** : quels PNJ EXISTANTS de la campagne peuvent incarner "
|
||||
"ou remplacer les personnages clés du PDF.\n"
|
||||
"- **Adaptation à l'univers** : comment transposer lieux, factions, noms propres et "
|
||||
"ton vers l'univers de l'utilisateur plutôt que le cadre d'origine du PDF.\n"
|
||||
"- **Doublons / conflits** : ce qui recoupe l'existant et comment le réconcilier.\n"
|
||||
"- **Ajustements de ton et de difficulté**.\n\n"
|
||||
"Réfère-toi TOUJOURS aux éléments existants par leur NOM. Ne réécris PAS le PDF en "
|
||||
"entier : donne des recommandations. Si une information manque, propose des options."
|
||||
)
|
||||
23
brain/app/application/prompts/chat.py
Normal file
23
brain/app/application/prompts/chat.py
Normal file
@@ -0,0 +1,23 @@
|
||||
"""Prompt système de base du chat contextuel (cf. chat.py).
|
||||
|
||||
Les blocs de contexte (Lore, page, campagne, session…) sont sérialisés par les
|
||||
méthodes `_format_*` du use case ; seul le SYSTEM de base vit ici.
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
|
||||
def base_system(language: str) -> str:
|
||||
"""System prompt de base, avec la langue de réponse pilotée par l'utilisateur."""
|
||||
return f"""Tu es un assistant d'écriture pour un Maître de Jeu de JDR.
|
||||
Tu dialogues avec le MJ pour l'aider à enrichir son univers et ses campagnes.
|
||||
|
||||
Règles de ton :
|
||||
- Réponds en {language_name(language)}, ton chaleureux et créatif.
|
||||
- Sois concis : listes à puces courtes plutôt que longs paragraphes.
|
||||
- Propose des idées qui s'intègrent dans le contexte existant ci-dessous.
|
||||
|
||||
Règles de cohérence (IMPORTANT) :
|
||||
- Tu PEUX et DOIS inventer des éléments originaux (personnages, lieux, objets, intrigues, créatures, scènes) — c'est ton rôle d'assistant créatif.
|
||||
- Tu ne peux PAS faire référence à un élément du MJ (du Lore, des arcs, chapitres ou scènes) comme s'il existait déjà, SAUF s'il apparaît EXACTEMENT (même orthographe) dans l'une des sections de contexte ci-dessous.
|
||||
- Si l'utilisateur mentionne un nom que tu ne vois pas dans le contexte, ne fais surtout pas semblant de le connaître : dis clairement "Je ne vois pas [nom] dans le contexte actuel, veux-tu qu'on le crée ?" plutôt que d'inventer des détails à son sujet.
|
||||
- Évite les précisions inventées qu'on ne peut pas vérifier : dates exactes, chiffres de population, hiérarchies politiques complexes, généalogies détaillées. Préfère des formulations ouvertes que le MJ validera ("il y a longtemps", "de nombreux", "la haute noblesse")."""
|
||||
15
brain/app/application/prompts/conversation_title.py
Normal file
15
brain/app/application/prompts/conversation_title.py
Normal file
@@ -0,0 +1,15 @@
|
||||
"""Prompt & repli de l'auto-titre de conversation (cf. router generation.py)."""
|
||||
from app.core.language import language_name
|
||||
|
||||
# Titre de repli (LLM injoignable / réponse vide), localisé selon la langue UI.
|
||||
TITLE_FALLBACK = {"fr": "Nouvelle conversation", "en": "New conversation"}
|
||||
|
||||
|
||||
def title_system_prompt(language: str) -> str:
|
||||
"""Consigne d'auto-titre, avec la langue du titre pilotée par l'utilisateur."""
|
||||
return (
|
||||
"Tu generes un titre court (4 a 7 mots max) qui resume le sujet de la "
|
||||
"conversation ci-dessous. Reponds UNIQUEMENT par le titre, sans guillemets, "
|
||||
"sans ponctuation finale, sans prefixe type 'Titre :'. Le titre doit etre "
|
||||
f"en {language_name(language)} et capturer le sujet metier (pas 'Conversation IA')."
|
||||
)
|
||||
19
brain/app/application/prompts/generate_page.py
Normal file
19
brain/app/application/prompts/generate_page.py
Normal file
@@ -0,0 +1,19 @@
|
||||
"""Consignes système de la génération de page (cf. generate_page.py)."""
|
||||
from app.core.language import language_name
|
||||
|
||||
|
||||
def system_instructions(language: str) -> str:
|
||||
"""Consignes système, avec la langue des valeurs générées pilotée par l'utilisateur."""
|
||||
return f"""Tu es un assistant d'écriture pour un Maître de Jeu de JDR.
|
||||
Tu vas générer le contenu d'une page appartenant à un univers fictionnel.
|
||||
|
||||
Règles impératives de ta réponse :
|
||||
- Tu réponds UNIQUEMENT par un objet JSON valide.
|
||||
- Les clés du JSON correspondent EXACTEMENT aux noms de champs demandés.
|
||||
- Les valeurs sont des chaînes de texte en {language_name(language)}, riches et évocatrices.
|
||||
- Aucun markdown, aucune explication, aucun commentaire autour du JSON.
|
||||
|
||||
Règles de cohérence (IMPORTANT) :
|
||||
- Tu PEUX inventer des détails originaux pour CETTE page : apparence, traits de caractère, anecdotes, histoire personnelle.
|
||||
- Tu ne dois PAS faire référence à d'autres personnages, lieux, organisations ou événements comme s'ils existaient déjà dans l'univers, sauf si le contexte ci-dessous les mentionne explicitement.
|
||||
- Si un champ appelle une précision externe (date, nom d'un roi, ville voisine, guerre passée), reste volontairement vague : "il y a de nombreuses années", "un bourg voisin", "une époque troublée". Le MJ préfère combler lui-même les blancs plutôt que trouver des faits inventés contradictoires avec son univers."""
|
||||
100
brain/app/application/prompts/import_campaign.py
Normal file
100
brain/app/application/prompts/import_campaign.py
Normal file
@@ -0,0 +1,100 @@
|
||||
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
||||
|
||||
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
||||
DEFAULT_ARC_NAME = "Aventure principale"
|
||||
|
||||
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
||||
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
||||
|
||||
Ta tâche : en dégager une ARBORESCENCE narrative à GROS GRAIN : arcs → chapitres → scènes,
|
||||
et — pour les lieux explorables — leurs PIÈCES (rooms).
|
||||
- Un ARC = un acte / une grande partie de la campagne (souvent un seul pour une aventure courte).
|
||||
- Un CHAPITRE = une étape majeure du récit : un chapitre du livre, OU — dans une
|
||||
campagne "hub" / bac-à-sable — UNE QUÊTE ou UN LIEU principal débloqué depuis le
|
||||
point central (ex : Dragon of Icespire Peak → chaque quête/lieu = un chapitre).
|
||||
- Une SCÈNE = un temps fort jouable du chapitre : un lieu, une rencontre clé, un moment pivot.
|
||||
- Une PIÈCE (room) = une salle d'un lieu explorable (donjon, crypte, manoir...).
|
||||
|
||||
TYPE D'ARC ("type") :
|
||||
- "HUB" si la campagne est un bac-à-sable : des quêtes/lieux optionnels, parallèles,
|
||||
débloqués depuis un point central, SANS ordre fixe imposé (ex : Dragon of Icespire Peak).
|
||||
- "LINEAR" si les chapitres se jouent dans un ordre séquentiel imposé.
|
||||
- Dans le doute : "LINEAR".
|
||||
|
||||
GRANULARITÉ (évite la sur-détection) :
|
||||
- Vise PEU de scènes : typiquement 1 à 6 par chapitre. PAS des dizaines.
|
||||
- Un LIEU EXPLORABLE (donjon, crypte, manoir, grotte à plusieurs salles) = UNE SEULE
|
||||
scène. Ses salles vont dans le tableau "rooms" de cette scène — JAMAIS en scènes séparées.
|
||||
- NE crée PAS une scène par rencontre isolée, par PNJ, par monstre ou par paragraphe.
|
||||
- IGNORE : blocs de stats, listes de monstres, encarts de règles, légendes de cartes,
|
||||
pieds de page, sommaires, crédits.
|
||||
|
||||
CONTENU D'UNE SCÈNE (fidélité au livre — important) :
|
||||
- `description` = synopsis de la scène, 2 à 4 phrases (plus que 1 ligne, mais pas le texte intégral).
|
||||
- `player_narration` = le texte d'AMBIANCE « à lire aux joueurs » (encadrés / boxed text /
|
||||
« lecture à voix haute »), recopié FIDÈLEMENT s'il existe dans l'extrait. Vide sinon.
|
||||
- `gm_notes` = les informations pour le MJ : secrets, développement, ce qui se passe,
|
||||
conséquences, indices cachés. Vide si rien de tel.
|
||||
- Ne RÉSUME pas abusivement player_narration et gm_notes : recopie le contenu utile du livre.
|
||||
|
||||
PIÈCES (rooms) — uniquement pour les scènes qui sont des lieux explorables :
|
||||
- Une entrée par salle numérotée/nommée du donjon (ex : "1. Entrée", "2. Salle des gardes").
|
||||
- `enemies` = créatures/boss de la salle (vide si aucune). `loot` = trésor/récompense (vide si aucun).
|
||||
- Pour une scène narrative classique (pas un donjon), "rooms" est un tableau vide [].
|
||||
|
||||
PNJ ET CRÉATURES NOTABLES ("npcs", tableau au niveau racine) :
|
||||
- Recense les PNJ NOMMÉS (alliés, marchands, antagonistes) et les créatures UNIQUES
|
||||
(boss, monstre récurrent) présents dans l'extrait.
|
||||
- `description` = courte fiche utile au MJ : rôle dans l'histoire, apparence,
|
||||
motivations, où on le rencontre. 2 à 4 phrases, fidèles au livre.
|
||||
- N'inclus PAS les monstres génériques sans nom (« 3 gobelins », « un loup »).
|
||||
- Aucun PNJ nommé dans l'extrait → "npcs": [].
|
||||
|
||||
Format de réponse :
|
||||
- Tu réponds UNIQUEMENT par un objet JSON valide, sans markdown ni commentaire autour.
|
||||
- Schéma EXACT :
|
||||
{{"arcs": [{{"name": "...", "description": "...", "type": "LINEAR",
|
||||
"chapters": [{{"name": "...", "description": "...", "scenes": [
|
||||
{{"name": "...", "description": "...", "player_narration": "...", "gm_notes": "...",
|
||||
"rooms": [{{"name": "...", "description": "...", "enemies": "...", "loot": "..."}}]}}
|
||||
]}}]}}
|
||||
],
|
||||
"npcs": [{{"name": "...", "description": "..."}}]}}
|
||||
- Utilise les VRAIS titres du livre pour les noms (pas de paraphrase).
|
||||
- Si le livre n'est PAS découpé en actes/parties, regroupe tout sous un seul arc nommé "{default_arc}".
|
||||
- N'invente pas de contenu : tu réorganises et recopies ce qui est présent dans l'extrait.
|
||||
- Si l'extrait ne contient aucune matière narrative, renvoie {{"arcs": []}}."""
|
||||
|
||||
# Bloc TOC injecté quand le PDF a des bookmarks : les morceaux étant traités
|
||||
# séparément, c'est CE référentiel commun qui garantit que tous nomment les
|
||||
# mêmes chapitres à l'identique → la fusion par nom du _TreeMerger recolle
|
||||
# les chapitres coupés au lieu de créer des doublons.
|
||||
TOC_BLOCK = """
|
||||
|
||||
--- STRUCTURE OFFICIELLE DU LIVRE (table des matières du PDF) ---
|
||||
{toc}
|
||||
--- FIN DE LA STRUCTURE ---
|
||||
IMPORTANT : pour nommer les arcs et chapitres, reprends EXACTEMENT les titres
|
||||
de cette structure (caractère pour caractère). Rattache le contenu de l'extrait
|
||||
au bon chapitre de la structure, même si son titre n'apparaît pas dans l'extrait."""
|
||||
|
||||
# Consolidation finale : le squelette (noms seuls) est minuscule, donc l'appel
|
||||
# est quasi gratuit comparé aux MAP. Température 0 et consigne CONSERVATRICE :
|
||||
# ne fusionner que les doublons évidents, jamais des entités distinctes.
|
||||
CONSOLIDATE_PROMPT = """Voici le squelette d'une arborescence arc → chapitre → scène issue d'une
|
||||
fusion AUTOMATIQUE de morceaux d'un livre de campagne de jeu de rôle. La fusion par nom exact
|
||||
peut avoir laissé des QUASI-DOUBLONS : le même chapitre ou la même scène sous deux libellés
|
||||
légèrement différents (ex: "La Crypte" et "Crypte de Karrak", "3. Salle des gardes" et
|
||||
"Salle des gardes").
|
||||
|
||||
{skeleton}
|
||||
|
||||
Identifie UNIQUEMENT les fusions ÉVIDENTES (même entité du livre sous deux noms). Sois
|
||||
CONSERVATEUR : dans le doute, ne fusionne PAS. Deux lieux/évènements distincts ne doivent
|
||||
JAMAIS être fusionnés.
|
||||
|
||||
Réponds UNIQUEMENT par un objet JSON valide :
|
||||
{{"chapter_merges": [{{"into": "nom du chapitre à garder", "merge": ["nom à fusionner", ...]}}],
|
||||
"scene_merges": [{{"chapter": "nom du chapitre", "into": "nom de la scène à garder",
|
||||
"merge": ["nom à fusionner", ...]}}]}}
|
||||
S'il n'y a RIEN à fusionner (cas le plus fréquent) : {{"chapter_merges": [], "scene_merges": []}}"""
|
||||
62
brain/app/application/prompts/import_rules.py
Normal file
62
brain/app/application/prompts/import_rules.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""Prompts de l'import de règles PDF (cf. import_rules.py).
|
||||
|
||||
Deux modes : MAP_SYSTEM (cloud, réécrit le contenu en sections markdown) et
|
||||
SEGMENT_SYSTEM (local, ne renvoie que les frontières des sections). Les deux
|
||||
templates attendent `.format(canonical=..., language_name=...)`.
|
||||
"""
|
||||
|
||||
# Taxonomie canonique suggérée au modèle pour homogénéiser les titres entre
|
||||
# morceaux (sinon "Combat" / "Le combat" / "Règles de combat" se dispersent).
|
||||
# Le modèle reste libre d'en créer d'autres si rien ne correspond.
|
||||
CANONICAL_SECTIONS = [
|
||||
"Règles générales",
|
||||
"Création de personnage",
|
||||
"Caractéristiques et tests",
|
||||
"Compétences",
|
||||
"Combat",
|
||||
"Magie et sorts",
|
||||
"Équipement et objets",
|
||||
"États et conditions",
|
||||
"Repos et récupération",
|
||||
"Progression et niveaux",
|
||||
"Conseils au Maître de Jeu",
|
||||
]
|
||||
|
||||
MAP_SYSTEM = """Tu es un assistant qui réorganise un livre de règles de jeu de rôle.
|
||||
On te donne un EXTRAIT brut d'un PDF de règles (texte parfois mal coupé par la mise en page).
|
||||
|
||||
Ta tâche : répartir le contenu de cet extrait dans des SECTIONS THÉMATIQUES.
|
||||
|
||||
Format EXACT attendu — un objet JSON plat {{titre de section: contenu markdown}} :
|
||||
{{"Combat": "## Initiative\\n\\nChaque participant lance 1d20...", "Magie et sorts": "## Sorts\\n\\n..."}}
|
||||
|
||||
Règles impératives :
|
||||
- Tu réponds UNIQUEMENT par cet objet JSON, sans texte avant ni après.
|
||||
- Les CLÉS sont des titres de section (texte court). Les VALEURS sont le contenu de la règle en markdown (chaîne de caractères, jamais un objet ou une liste).
|
||||
- INTERDIT : des clés génériques comme "title", "content", "sections", "thought" ou "notes" ; des objets imbriqués ; tout commentaire sur ta démarche ou ton raisonnement.
|
||||
- Utilise EN PRIORITÉ ces titres canoniques quand le contenu y correspond :
|
||||
{canonical}
|
||||
- Si un contenu ne rentre dans aucun, crée un titre clair et concis (en {language_name}).
|
||||
- Reproduis FIDÈLEMENT les règles : tu peux nettoyer la coupure des lignes, recoller les mots coupés
|
||||
par un tiret en fin de ligne, retirer les en-têtes/pieds de page et numéros de page parasites.
|
||||
- N'INVENTE AUCUNE règle, ne résume pas abusivement : tu réorganises, tu ne réécris pas le fond.
|
||||
- Ignore les pages de garde, sommaires, crédits, pages vides (renvoie {{}} si l'extrait n'a aucune règle)."""
|
||||
|
||||
SEGMENT_SYSTEM = """Tu analyses un EXTRAIT brut d'un livre de règles de jeu de rôle.
|
||||
Ta tâche : repérer où COMMENCENT les sections thématiques. Tu ne réécris RIEN.
|
||||
|
||||
Format EXACT attendu :
|
||||
{{"sections": [{{"titre": "Combat", "debut": "Le combat se déroule en tours de"}}, ...]}}
|
||||
|
||||
Règles impératives :
|
||||
- "debut" = les 5 à 10 PREMIERS MOTS du passage où la section commence, COPIÉS À L'IDENTIQUE
|
||||
depuis l'extrait (même orthographe, même ponctuation, même langue). JAMAIS un résumé.
|
||||
- La PREMIÈRE entrée commence aux tout premiers mots de l'extrait (même si le contenu
|
||||
poursuit une section entamée avant cet extrait).
|
||||
- Les entrées suivent l'ordre du texte. Vise des sections LARGES (un thème), pas un titre
|
||||
par paragraphe : un extrait contient typiquement 1 à 6 sections.
|
||||
- Titres : EN PRIORITÉ parmi :
|
||||
{canonical}
|
||||
sinon un titre court et clair en {language_name}.
|
||||
- Pages de garde, sommaires, crédits : n'en fais pas des sections. Si l'extrait n'est que ça,
|
||||
renvoie {{"sections": []}}."""
|
||||
134
brain/app/application/prompts/notebook.py
Normal file
134
brain/app/application/prompts/notebook.py
Normal file
@@ -0,0 +1,134 @@
|
||||
"""Prompts des notebooks (atelier RAG) : chat ancré (cf. notebook_chat.py) et
|
||||
analyse approfondie map-reduce (cf. notebook_deep.py).
|
||||
|
||||
CHAT_SYSTEM attend `.format(context_block=..., sources_block=..., language_name=...)`.
|
||||
REDUCE_SYSTEM attend `.format(context_block=..., notes_block=..., language_name=...)`.
|
||||
MAP_PROMPT attend `.format(no_match=..., question=..., excerpt=...)`.
|
||||
SUMMARY_PROMPT attend `.format(excerpt=...)`.
|
||||
"""
|
||||
|
||||
# --- Chat ancré (RAG) --------------------------------------------------------
|
||||
|
||||
CHAT_SYSTEM = """Tu es un assistant de jeu de rôle qui aide à ADAPTER une source (PDF) à la CAMPAGNE de l'utilisateur.
|
||||
|
||||
Tu disposes de DEUX connaissances, toutes deux ci-dessous :
|
||||
1) LA CAMPAGNE de l'utilisateur (sa structure arcs/chapitres/scènes, ses PNJ, son univers) ;
|
||||
2) LA SOURCE (extraits pertinents du PDF).
|
||||
|
||||
Règles :
|
||||
- Pour une question sur SA CAMPAGNE (ex. « mon chapitre 3 », « mes PNJ »), appuie-toi sur la section CAMPAGNE.
|
||||
- Pour une question sur le livre, appuie-toi sur les EXTRAITS DE LA SOURCE.
|
||||
- CROISE les deux pour proposer des adaptations cohérentes avec sa campagne existante.
|
||||
- N'invente pas ce qui ne figure ni dans la campagne ni dans la source ; si tu ne sais pas, dis-le.
|
||||
- Quand un extrait porte un numéro de page (« (p. 12) »), cite-le (« d'après la p. 12 »).
|
||||
|
||||
{context_block}
|
||||
--- EXTRAITS PERTINENTS DE LA SOURCE ---
|
||||
{sources_block}
|
||||
--- FIN DES EXTRAITS ---
|
||||
|
||||
PROPOSITIONS D'INTÉGRATION (IMPORTANT) :
|
||||
Quand l'utilisateur veut CRÉER ou ADAPTER un élément concret pour sa campagne (un PNJ,
|
||||
une scène, un chapitre, une quête, un arc, une table aléatoire), termine ta réponse par
|
||||
un ou plusieurs BLOCS D'ACTION — un objet JSON par bloc, dans une clôture
|
||||
```loremind-action. L'interface les transformera en boutons « Créer dans la campagne ».
|
||||
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
|
||||
{{"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
|
||||
{{"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
|
||||
{{"type": "arc", "name": "Nom", "description": "Résumé", "arcType": "LINEAR",
|
||||
"themes": "Thèmes de l'arc", "stakes": "Enjeux",
|
||||
"rewards": "Récompenses attendues", "resolution": "Issues possibles",
|
||||
"gmNotes": "Notes MJ."}}
|
||||
```
|
||||
(`arcType` : "LINEAR" pour des chapitres en séquence, "HUB" pour un recueil de
|
||||
quêtes parallèles.)
|
||||
```loremind-action
|
||||
{{"type": "table", "name": "Nom", "diceFormula": "1d8", "entries": [{{"minRoll":1,"maxRoll":4,"label":"...","detail":"..."}}]}}
|
||||
```
|
||||
|
||||
Réponds en {language_name}, de façon utile et concise. Mets le texte explicatif AVANT les blocs d'action."""
|
||||
|
||||
|
||||
# --- Analyse approfondie (map-reduce) ----------------------------------------
|
||||
|
||||
SUMMARY_PROMPT = """Résume l'EXTRAIT ci-dessous en 4 à 8 puces factuelles : lieux, PNJ et
|
||||
créatures nommés, objets notables, évènements, règles particulières. Pas d'analyse, pas
|
||||
d'introduction — uniquement les puces, pour servir d'index de recherche.
|
||||
|
||||
--- EXTRAIT ---
|
||||
{excerpt}
|
||||
--- FIN EXTRAIT ---
|
||||
|
||||
Résumé :"""
|
||||
|
||||
MAP_PROMPT = """Voici un EXTRAIT d'un document. Extrais UNIQUEMENT les informations
|
||||
pertinentes pour répondre à la question ci-dessous. Conserve les détails utiles et
|
||||
indique les numéros de page (format « p. X »). Si l'extrait ne contient RIEN de
|
||||
pertinent, réponds EXACTEMENT « {no_match} » et rien d'autre.
|
||||
|
||||
QUESTION : {question}
|
||||
|
||||
--- EXTRAIT ---
|
||||
{excerpt}
|
||||
--- FIN EXTRAIT ---
|
||||
|
||||
Informations pertinentes (ou « {no_match} ») :"""
|
||||
|
||||
REDUCE_SYSTEM = """Tu es l'assistant-MJ d'un jeu de rôle. Tu réponds à la demande du MJ en
|
||||
t'appuyant sur TROIS sources : (1) des NOTES extraites de l'ENSEMBLE du document source (vue
|
||||
complète — mais POSSIBLEMENT VIDE si rien d'utile n'y figure), (2) le contexte de sa CAMPAGNE,
|
||||
(3) la conversation ci-dessous.
|
||||
|
||||
- Si les notes contiennent des éléments utiles : exploite-les et CITE les pages (« p. X »).
|
||||
- Si les notes sont VIDES ou pauvres (cas fréquent d'une demande CRÉATIVE portant sur des
|
||||
éléments INVENTÉS par le MJ) : ne te bloque surtout PAS. Aide-le quand même en t'appuyant
|
||||
sur sa CAMPAGNE, la CONVERSATION et ta connaissance du genre — propose des adaptations
|
||||
concrètes (arcs, chapitres, scènes, PNJ), structurées et jouables.
|
||||
- Sois concret et utile. N'affirme rien de FAUX sur le contenu du document.
|
||||
|
||||
{context_block}
|
||||
--- NOTES EXTRAITES DE TOUT LE DOCUMENT ---
|
||||
{notes_block}
|
||||
--- FIN DES NOTES ---
|
||||
|
||||
Réponds en {language_name}."""
|
||||
20
brain/app/application/prompts/query_rewrite.py
Normal file
20
brain/app/application/prompts/query_rewrite.py
Normal file
@@ -0,0 +1,20 @@
|
||||
"""Prompt de réécriture en question autonome (cf. query_rewrite.py).
|
||||
|
||||
Attend `.format(conversation=...)`.
|
||||
"""
|
||||
|
||||
REWRITE_PROMPT = """Voici la fin d'une conversation entre un Maître de Jeu et son assistant.
|
||||
Réécris le DERNIER message de l'utilisateur en une question AUTONOME et complète :
|
||||
remplace les pronoms et références implicites (« il », « ses », « ce lieu », « et pour
|
||||
les autres ? ») par ce qu'ils désignent dans la conversation.
|
||||
|
||||
Règles :
|
||||
- Réponds UNIQUEMENT par la question réécrite, sans guillemets ni préfixe.
|
||||
- Conserve la langue et l'intention d'origine. N'ajoute RIEN qui n'est pas demandé.
|
||||
- Si le dernier message est déjà autonome, recopie-le tel quel.
|
||||
|
||||
--- CONVERSATION ---
|
||||
{conversation}
|
||||
--- FIN ---
|
||||
|
||||
Question autonome :"""
|
||||
14
brain/app/application/prompts/rerank.py
Normal file
14
brain/app/application/prompts/rerank.py
Normal file
@@ -0,0 +1,14 @@
|
||||
"""Prompt de reranking LLM des passages RAG (cf. rerank.py).
|
||||
|
||||
Attend `.format(question=..., passages=..., count=...)`.
|
||||
"""
|
||||
|
||||
RERANK_PROMPT = """Tu évalues la PERTINENCE d'extraits d'un document pour répondre à une question.
|
||||
Note chaque extrait de 0 (sans rapport) à 10 (répond directement), indépendamment des autres.
|
||||
|
||||
QUESTION : {question}
|
||||
|
||||
{passages}
|
||||
|
||||
Réponds UNIQUEMENT par un objet JSON : {{"scores": [note_extrait_1, note_extrait_2, ...]}}
|
||||
Le tableau doit contenir EXACTEMENT {count} notes, dans l'ordre des extraits."""
|
||||
60
brain/app/application/prompts/tables.py
Normal file
60
brain/app/application/prompts/tables.py
Normal file
@@ -0,0 +1,60 @@
|
||||
"""Prompts des outils de table (tables aléatoires, improvisation, catalogues).
|
||||
|
||||
Ces prompts étaient auparavant construits en ligne dans le router `tables.py` ;
|
||||
isolés ici pour garder la frontière HTTP fine. Le router calcule les plages de
|
||||
dés et passe les champs bruts ; ces fonctions façonnent le texte.
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
|
||||
def random_table_prompt(description: str, dice_formula: str, lo: int, hi: int,
|
||||
context: str, language: str) -> str:
|
||||
"""Prompt de génération d'une table aléatoire couvrant lo..hi."""
|
||||
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context.strip() else ""
|
||||
return (
|
||||
"Tu es un assistant de jeu de rôle. Génère une TABLE ALÉATOIRE évocatrice.\n"
|
||||
f"Dé : {dice_formula} (résultats possibles de {lo} à {hi}).\n"
|
||||
f"Sujet : {description.strip()}\n"
|
||||
f"{context_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format : {"name": "...", "description": "...", "entries": '
|
||||
'[{"min_roll": N, "max_roll": M, "label": "résultat court", "detail": "1-2 phrases"}]}\n'
|
||||
f"- Les plages (min_roll..max_roll) doivent COUVRIR EXACTEMENT {lo}..{hi}, "
|
||||
"sans trou ni chevauchement, dans l'ordre croissant.\n"
|
||||
"- Des résultats variés, cohérents avec le sujet (et le contexte s'il est fourni).\n"
|
||||
f"- En {language_name(language)}. 'label' = résultat bref ; 'detail' = description/effet concret.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
|
||||
|
||||
def improvise_roll_prompt(table_name: str, result_label: str, result_detail: str,
|
||||
context: str, language: str) -> str:
|
||||
"""Prompt de narration brodée sur un résultat tiré."""
|
||||
detail = f" ({result_detail.strip()})" if result_detail.strip() else ""
|
||||
context_block = f"\nContexte : {context.strip()}" if context.strip() else ""
|
||||
return (
|
||||
"Tu es le Maître du Jeu. Les joueurs viennent de tirer sur la table "
|
||||
f"« {table_name.strip()} » et ont obtenu : « {result_label.strip()} »{detail}."
|
||||
f"{context_block}\n\n"
|
||||
"Décris en 2-3 phrases vivantes et immédiates ce qui se passe, pour lancer la scène. "
|
||||
f"Pas de méta, pas d'options : juste la narration, en {language_name(language)}."
|
||||
)
|
||||
|
||||
|
||||
def item_catalog_prompt(description: str, context: str, language: str) -> str:
|
||||
"""Prompt de génération d'un catalogue d'objets (boutique, butin…)."""
|
||||
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context.strip() else ""
|
||||
return (
|
||||
"Tu es un assistant de jeu de rôle. Génère un CATALOGUE D'OBJETS (boutique, butin, trésor…).\n"
|
||||
f"Sujet : {description.strip()}\n"
|
||||
f"{context_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format : {"name": "...", "description": "...", "items": '
|
||||
'[{"name": "Objet", "price": "ex. 50 po", "category": "ex. Armes", "description": "effet/détails"}]}\n'
|
||||
"- Des objets variés et cohérents avec le sujet (et le contexte s'il est fourni).\n"
|
||||
"- 'price' = prix court dans la monnaie du jeu ; 'category' = regroupement (Armes, Potions…) ; "
|
||||
f"'description' = effet/détails en une phrase. En {language_name(language)}.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from app.application.prompts import query_rewrite as prompts
|
||||
from app.domain.models import ChatMessage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -23,22 +24,6 @@ _MAX_HISTORY = 6
|
||||
# modèle a divagué) → on retombe sur la question brute.
|
||||
_MAX_REWRITE_CHARS = 400
|
||||
|
||||
_REWRITE_PROMPT = """Voici la fin d'une conversation entre un Maître de Jeu et son assistant.
|
||||
Réécris le DERNIER message de l'utilisateur en une question AUTONOME et complète :
|
||||
remplace les pronoms et références implicites (« il », « ses », « ce lieu », « et pour
|
||||
les autres ? ») par ce qu'ils désignent dans la conversation.
|
||||
|
||||
Règles :
|
||||
- Réponds UNIQUEMENT par la question réécrite, sans guillemets ni préfixe.
|
||||
- Conserve la langue et l'intention d'origine. N'ajoute RIEN qui n'est pas demandé.
|
||||
- Si le dernier message est déjà autonome, recopie-le tel quel.
|
||||
|
||||
--- CONVERSATION ---
|
||||
{conversation}
|
||||
--- FIN ---
|
||||
|
||||
Question autonome :"""
|
||||
|
||||
|
||||
async def standalone_question(llm, messages: list[ChatMessage]) -> str:
|
||||
"""Condense `messages` en une question autonome pour la RECHERCHE.
|
||||
@@ -56,7 +41,7 @@ async def standalone_question(llm, messages: list[ChatMessage]) -> str:
|
||||
conversation = "\n".join(f"{m.role.upper()}: {m.content.strip()}" for m in recent)
|
||||
try:
|
||||
raw = await llm.generate(
|
||||
_REWRITE_PROMPT.format(conversation=conversation), temperature=0.0)
|
||||
prompts.REWRITE_PROMPT.format(conversation=conversation), temperature=0.0)
|
||||
except Exception as exc: # noqa: BLE001 — la recherche dégradée vaut mieux que pas de réponse
|
||||
logger.warning("Réécriture de question ignorée (échec LLM) : %s", exc)
|
||||
return last_user
|
||||
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.prompts import rerank as prompts
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -23,16 +24,6 @@ POOL_MAX = 24
|
||||
# prompt sans changer le jugement de pertinence.
|
||||
_EXCERPT_CHARS = 600
|
||||
|
||||
_RERANK_PROMPT = """Tu évalues la PERTINENCE d'extraits d'un document pour répondre à une question.
|
||||
Note chaque extrait de 0 (sans rapport) à 10 (répond directement), indépendamment des autres.
|
||||
|
||||
QUESTION : {question}
|
||||
|
||||
{passages}
|
||||
|
||||
Réponds UNIQUEMENT par un objet JSON : {{"scores": [note_extrait_1, note_extrait_2, ...]}}
|
||||
Le tableau doit contenir EXACTEMENT {count} notes, dans l'ordre des extraits."""
|
||||
|
||||
|
||||
def pool_size(top_k: int) -> int:
|
||||
"""Taille du pool à récupérer avant reranking."""
|
||||
@@ -52,7 +43,7 @@ async def rerank(llm, question: str, passages: list[dict], top_k: int) -> list[d
|
||||
f"--- EXTRAIT {i + 1} ---\n{(p.get('text') or '')[:_EXCERPT_CHARS]}"
|
||||
for i, p in enumerate(passages)
|
||||
)
|
||||
prompt = _RERANK_PROMPT.format(
|
||||
prompt = prompts.RERANK_PROMPT.format(
|
||||
question=question, passages=numbered, count=len(passages))
|
||||
try:
|
||||
raw = await llm.generate(prompt, temperature=0.0)
|
||||
|
||||
61
brain/app/core/language.py
Normal file
61
brain/app/core/language.py
Normal file
@@ -0,0 +1,61 @@
|
||||
"""Langue de sortie de l'IA, pilotée par l'utilisateur (et non plus figée en FR).
|
||||
|
||||
Le Core relaie la langue choisie dans l'UI via l'entête HTTP `X-User-Language`
|
||||
(`fr`/`en`). Ce module centralise :
|
||||
- la normalisation du code reçu (tolérante : `en-US`, `EN`, un `Accept-Language`
|
||||
brut… → `en`) avec repli sur le français ;
|
||||
- la fabrique de la directive de langue injectée dans les prompts ;
|
||||
- la dépendance FastAPI qui lit l'entête côté router.
|
||||
|
||||
Ajouter une langue = une entrée dans `NAMES`. Aucun autre branchement n'est requis.
|
||||
"""
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Header
|
||||
|
||||
# Nom (en français, langue de travail des prompts) de chaque langue supportée.
|
||||
# La clé est le code court ISO 639-1 utilisé par l'UI (cf. LanguageService Angular).
|
||||
NAMES: dict[str, str] = {
|
||||
"fr": "français",
|
||||
"en": "anglais",
|
||||
}
|
||||
|
||||
DEFAULT = "fr"
|
||||
|
||||
|
||||
def normalize(raw: str | None) -> str:
|
||||
"""Réduit un code/entête langue arbitraire à un code supporté (`fr`/`en`).
|
||||
|
||||
Tolère les variantes régionales (`en-GB`), la casse, et un `Accept-Language`
|
||||
complet (`fr-FR,fr;q=0.9,en;q=0.8`) dont on ne garde que la 1re préférence.
|
||||
Repli systématique sur `DEFAULT` si rien ne matche.
|
||||
"""
|
||||
if not raw:
|
||||
return DEFAULT
|
||||
# 1re préférence d'un éventuel Accept-Language, puis base avant le tiret régional.
|
||||
primary = raw.split(",")[0].split(";")[0].strip().lower()
|
||||
base = primary.split("-")[0]
|
||||
return base if base in NAMES else DEFAULT
|
||||
|
||||
|
||||
def language_name(lang: str) -> str:
|
||||
"""Nom de la langue (pour insertion inline dans un prompt)."""
|
||||
return NAMES.get(lang, NAMES[DEFAULT])
|
||||
|
||||
|
||||
def instruction(lang: str) -> str:
|
||||
"""Directive forte à injecter dans un prompt pour imposer la langue de sortie."""
|
||||
return (
|
||||
f"IMPORTANT : rédige l'INTÉGRALITÉ de ta réponse en {language_name(lang)}, "
|
||||
"quelle que soit la langue du contexte ou des documents fournis."
|
||||
)
|
||||
|
||||
|
||||
def get_user_language(
|
||||
x_user_language: Annotated[str | None, Header()] = None,
|
||||
) -> str:
|
||||
"""Dépendance FastAPI : langue de l'utilisateur lue depuis l'entête `X-User-Language`.
|
||||
|
||||
Absente (appel direct, vieux client) → français par défaut.
|
||||
"""
|
||||
return normalize(x_user_language)
|
||||
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
||||
app = FastAPI(
|
||||
title="LoreMind Brain",
|
||||
description="Backend IA pour la génération de contenu narratif.",
|
||||
version="0.13.0-beta",
|
||||
version="0.16.0",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
27
brain/run_local.py
Normal file
27
brain/run_local.py
Normal file
@@ -0,0 +1,27 @@
|
||||
"""Point d'entree LOCAL du Brain (hors Docker).
|
||||
|
||||
Lance le serveur uvicorn sur 127.0.0.1:8000 — l'equivalent autonome de la
|
||||
commande Docker `uvicorn app.main:app --host 0.0.0.0 --port 8000`, mais en
|
||||
n'ecoutant QUE sur la boucle locale (mono-utilisateur, jamais expose au reseau).
|
||||
|
||||
Empaquete avec le Python *embeddable* officiel (signe par la PSF) dans
|
||||
l'application de bureau : on evite ainsi tout executable "gele" type PyInstaller
|
||||
que les antivirus prennent souvent pour un trojan (bootloader packe).
|
||||
Le Core le lance via : python\\python.exe run_local.py
|
||||
|
||||
On insere le dossier de CE fichier dans sys.path pour que le package `app`
|
||||
soit importable quel que soit le repertoire de travail (le Core fixe le cwd
|
||||
ailleurs, sous ~/.loremind/brain, pour y ecrire le dossier data/).
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import uvicorn # noqa: E402
|
||||
|
||||
from app.main import app # noqa: E402
|
||||
|
||||
if __name__ == "__main__":
|
||||
# host 127.0.0.1 : accessible uniquement depuis le Core sur la meme machine.
|
||||
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
|
||||
72
core/pom.xml
72
core/pom.xml
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>0.13.0-beta</version>
|
||||
<version>0.16.0</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
@@ -60,11 +60,31 @@
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- H2 Database pour les tests -->
|
||||
<!-- Flyway : migrations de schema versionnees (remplace ddl-auto=update).
|
||||
Un SEUL jeu de migrations en SQL PostgreSQL sert les deux bases :
|
||||
- Postgres (Docker/serveur) nativement ;
|
||||
- H2 (mode local-first) via MODE=PostgreSQL dans l'URL JDBC.
|
||||
flyway-database-postgresql : module requis depuis Flyway 10 (DBs
|
||||
externalisees du core). H2 reste supporte par flyway-core. -->
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- H2 Database :
|
||||
- tests (toujours) ;
|
||||
- RUNTIME du profil "local" (mode local-first / jpackage) : base
|
||||
fichier embarquee a la place de Postgres, donc le driver doit etre
|
||||
sur le classpath d'execution. Scope runtime (jamais compile contre)
|
||||
=> present a l'execution + tests, ~2,5 Mo inutilises cote Docker. -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Lombok (réduit le code boilerplate) -->
|
||||
@@ -179,4 +199,50 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<!-- =================================================================
|
||||
Profil "desktop" : build local-first (application de bureau).
|
||||
Active avec : mvn -Pdesktop package
|
||||
Embarque le build Angular dans le jar (classpath:/static/) pour que
|
||||
le Core serve lui-meme le front (cf. LocalWebConfig, profil Spring
|
||||
"local"). Le build Docker normal (sans ce profil) reste une API pure :
|
||||
le front y est servi par le conteneur nginx, donc rien n'est copie.
|
||||
================================================================= -->
|
||||
<profile>
|
||||
<id>desktop</id>
|
||||
<properties>
|
||||
<!-- Sortie du `ng build` (builder browser) : web/dist/web. -->
|
||||
<frontend.dist>${project.basedir}/../web/dist/web</frontend.dist>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-frontend</id>
|
||||
<!-- Avant le repackage Spring Boot : on injecte le
|
||||
front dans les classes compilees -> embarque
|
||||
dans le fat jar sous /static. -->
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-resources</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.outputDirectory}/static</outputDirectory>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>${frontend.dist}</directory>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.loremind;
|
||||
|
||||
import com.loremind.infrastructure.desktop.DesktopSingleInstance;
|
||||
import com.loremind.infrastructure.desktop.DesktopUserConfig;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
@@ -13,6 +15,29 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
public class LoreMindApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LoreMindApplication.class, args);
|
||||
// Mode bureau (profil "local") : garde-fou instance unique. Si l'app
|
||||
// tourne deja, on ouvre juste le navigateur et on sort proprement (code 0)
|
||||
// au lieu de demarrer un 2e serveur qui echouerait sur le verrou H2 — ce
|
||||
// qui evite le trompeur « Failed to launch JVM » du launcher jpackage.
|
||||
boolean local = DesktopSingleInstance.isLocalProfile(args);
|
||||
if (local && !DesktopSingleInstance.tryAcquire()) {
|
||||
DesktopSingleInstance.openAppInBrowser();
|
||||
return;
|
||||
}
|
||||
SpringApplication app = new SpringApplication(LoreMindApplication.class);
|
||||
if (local) {
|
||||
// Mode bureau : on a besoin d'AWT (icone de la zone de notification,
|
||||
// cf. SystemTrayManager). Spring Boot force headless=true par defaut,
|
||||
// ce qui leverait HeadlessException — on le desactive ici. En mode
|
||||
// serveur/Docker, on reste en headless (defaut), aucun impact.
|
||||
app.setHeadless(false);
|
||||
// Config utilisateur editable (~/.loremind/loremind.properties) : creee
|
||||
// au 1er lancement (port + identifiants admin). Puis resolution du port :
|
||||
// celui configure s'il est libre, sinon un port libre (evite l'echec de
|
||||
// demarrage si 8080 est deja pris). Publie server.port + ~/.loremind/.port.
|
||||
DesktopUserConfig.ensureExists();
|
||||
DesktopUserConfig.resolveAndPublishPort();
|
||||
}
|
||||
app.run(args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,26 +40,33 @@ public class LicenseService {
|
||||
private final LicenseRelay relay;
|
||||
private final long gracePeriodSeconds;
|
||||
private final long refreshBeforeExpirySeconds;
|
||||
private final boolean licensingEnabled;
|
||||
|
||||
public LicenseService(
|
||||
LicenseRepository repository,
|
||||
JwtVerifier jwtVerifier,
|
||||
LicenseRelay relay,
|
||||
@Value("${licensing.grace-period-days:14}") int gracePeriodDays,
|
||||
@Value("${licensing.refresh-before-expiry-days:2}") int refreshBeforeExpiryDays) {
|
||||
@Value("${licensing.refresh-before-expiry-days:2}") int refreshBeforeExpiryDays,
|
||||
@Value("${licensing.enabled:true}") boolean licensingEnabled) {
|
||||
this.repository = repository;
|
||||
this.jwtVerifier = jwtVerifier;
|
||||
this.relay = relay;
|
||||
this.gracePeriodSeconds = (long) gracePeriodDays * 86_400L;
|
||||
this.refreshBeforeExpirySeconds = (long) refreshBeforeExpiryDays * 86_400L;
|
||||
this.licensingEnabled = licensingEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true si le verifier est configure (cle publique presente).
|
||||
* L'UI peut masquer toute la section Patreon si false.
|
||||
* @return true si le licensing Patreon est actif : il faut a la fois que la
|
||||
* feature soit activee ({@code licensing.enabled}, faux en mode
|
||||
* bureau/local ou le gating par image Docker n'a aucun sens) ET que
|
||||
* le verifier soit configure (cle publique presente). Faux => l'UI
|
||||
* masque toute la section Patreon, le daemon de refresh est no-op,
|
||||
* et le canal beta est desactive.
|
||||
*/
|
||||
public boolean isLicensingEnabled() {
|
||||
return jwtVerifier.isConfigured();
|
||||
return licensingEnabled && jwtVerifier.isConfigured();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,6 +10,9 @@ import java.util.List;
|
||||
*/
|
||||
public interface ConversationTitleGenerator {
|
||||
|
||||
/** Renvoie un titre en francais (4-7 mots max). Jamais null ni vide. */
|
||||
/**
|
||||
* Renvoie un titre court (4-7 mots max), dans la langue de l'utilisateur
|
||||
* (relayee au Brain via l'entete X-User-Language). Jamais null ni vide.
|
||||
*/
|
||||
String generate(List<ConversationMessage> firstMessages);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,21 @@ public interface ImageStorage {
|
||||
*/
|
||||
String upload(String filename, String contentType, InputStream data, long sizeBytes);
|
||||
|
||||
/**
|
||||
* Stocke un flux binaire SOUS UNE CLE IMPOSEE (pas de generation).
|
||||
* <p>
|
||||
* Utilise par l'import de contenu pour reinjecter une image sous sa cle
|
||||
* d'origine, garantissant que les references {@code storageKey} portees par
|
||||
* les entites restent valides apres un transfert inter-instance.
|
||||
* Ecrase si la cle existe deja.
|
||||
*
|
||||
* @param storageKey cle opaque exacte sous laquelle stocker (ex: images/UUID.ext)
|
||||
* @param contentType MIME type
|
||||
* @param data flux binaire a stocker
|
||||
* @param sizeBytes taille en octets (requis par certains backends comme S3)
|
||||
*/
|
||||
void store(String storageKey, String contentType, InputStream data, long sizeBytes);
|
||||
|
||||
/** Recupere le flux binaire associe a une cle, ou null si inexistante. */
|
||||
InputStream download(String storageKey);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -64,6 +65,7 @@ public class BrainAiChatClient implements AiChatProvider {
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(CHAT_STREAM_PATH)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
.bodyValue(payload)
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.loremind.infrastructure.ai;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignPdfAdvisor;
|
||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
@@ -65,6 +66,7 @@ public class BrainCampaignAdaptClient implements CampaignPdfAdvisor {
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(ADAPT_PATH)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
.body(BodyInserters.fromMultipartData(parts.build()))
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.loremind.domain.campaigncontext.CampaignImportProposal.RoomProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.SceneProposal;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignImportException;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignPdfImporter;
|
||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
@@ -71,6 +72,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(IMPORT_CAMPAIGN_STREAM_PATH)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
.body(BodyInserters.fromMultipartData(parts.build()))
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
import com.loremind.domain.conversationcontext.ports.ConversationTitleGenerator;
|
||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -50,6 +51,7 @@ public class BrainConversationTitleClient implements ConversationTitleGenerator
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> resp = webClient.post()
|
||||
.uri(PATH)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.bodyValue(payload)
|
||||
.retrieve()
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookChatStreamer;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookException;
|
||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -66,6 +67,7 @@ public class BrainNotebookChatClient implements NotebookChatStreamer {
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(deep ? DEEP_PATH : PATH)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
.bodyValue(payload)
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.loremind.domain.gamesystemcontext.RulesImportProgress;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportResult;
|
||||
import com.loremind.domain.gamesystemcontext.ports.RulesImportException;
|
||||
import com.loremind.domain.gamesystemcontext.ports.RulesPdfImporter;
|
||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -125,6 +126,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(IMPORT_RULES_STREAM_PATH)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
.body(BodyInserters.fromMultipartData(parts.build()))
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Lance le Brain (service IA Python) comme SOUS-PROCESSUS du Core, en mode
|
||||
* local-first (application de bureau empaquetee, sans Docker).
|
||||
* <p>
|
||||
* Cycle de vie calque sur celui du Core :
|
||||
* <ul>
|
||||
* <li>demarrage : a {@link ApplicationReadyEvent} (le serveur HTTP du Core
|
||||
* est deja pret) ;</li>
|
||||
* <li>arret : a {@link PreDestroy} (fermeture du contexte Spring) — on arrete
|
||||
* proprement le Brain pour ne pas laisser de process orphelin.</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* Tolerance aux pannes : si le Brain ne peut pas etre lance (exe absent,
|
||||
* commande non configuree...), on LOGGUE sans faire echouer le Core. L'app
|
||||
* reste utilisable (Lore, Campagnes, Systeme de jeu) ; seules les fonctions IA
|
||||
* sont indisponibles jusqu'a correction.
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class BrainSidecar {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BrainSidecar.class);
|
||||
|
||||
private final BrainSidecarProperties props;
|
||||
private final String internalSecret;
|
||||
|
||||
private volatile Process process;
|
||||
|
||||
public BrainSidecar(BrainSidecarProperties props,
|
||||
@Value("${brain.internal-secret:}") String internalSecret) {
|
||||
this.props = props;
|
||||
this.internalSecret = internalSecret;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void start() {
|
||||
if (!props.isEnabled()) {
|
||||
log.info("[Brain] Sidecar desactive (brain.sidecar.enabled=false).");
|
||||
return;
|
||||
}
|
||||
if (props.getCommand() == null || props.getCommand().isEmpty()) {
|
||||
log.warn("[Brain] Aucune commande configuree (brain.sidecar.command) : "
|
||||
+ "le Brain n'est pas lance. Les fonctions IA seront indisponibles.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder(props.getCommand());
|
||||
pb.redirectErrorStream(true);
|
||||
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
|
||||
|
||||
File workingDir = resolveWorkingDir();
|
||||
if (workingDir != null) {
|
||||
pb.directory(workingDir);
|
||||
}
|
||||
|
||||
// Secret partage Core <-> Brain : le Brain est fail-closed sans lui.
|
||||
// (cf. Settings.internal_shared_secret cote Python -> env INTERNAL_SHARED_SECRET)
|
||||
pb.environment().put("INTERNAL_SHARED_SECRET", internalSecret);
|
||||
|
||||
this.process = pb.start();
|
||||
log.info("[Brain] Sidecar demarre (pid={}, cwd={}).",
|
||||
process.pid(), workingDir != null ? workingDir : "<heritee>");
|
||||
} catch (IOException e) {
|
||||
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
||||
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
||||
props.getCommand(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void stop() {
|
||||
Process p = this.process;
|
||||
if (p == null || !p.isAlive()) {
|
||||
return;
|
||||
}
|
||||
log.info("[Brain] Arret du sidecar (pid={})...", p.pid());
|
||||
p.destroy();
|
||||
try {
|
||||
if (!p.waitFor(10, TimeUnit.SECONDS)) {
|
||||
log.warn("[Brain] Arret propre depasse (10s) : kill force.");
|
||||
p.destroyForcibly();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
p.destroyForcibly();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resout (et cree au besoin) le repertoire de travail du Brain. Le Brain y
|
||||
* ecrit son dossier {@code data/} (index vectoriel, settings.json).
|
||||
*/
|
||||
private File resolveWorkingDir() {
|
||||
String dir = props.getWorkingDir();
|
||||
if (dir == null || dir.isBlank()) {
|
||||
return null; // herite du cwd du Core
|
||||
}
|
||||
Path path = Path.of(dir).toAbsolutePath().normalize();
|
||||
try {
|
||||
Files.createDirectories(path);
|
||||
} catch (IOException e) {
|
||||
log.warn("[Brain] Impossible de creer le repertoire de travail {} : {}. "
|
||||
+ "Lancement avec le cwd herite.", path, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
return path.toFile();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Configuration du lancement du Brain (service IA Python) en SIDECAR, c.-a-d.
|
||||
* comme sous-processus du Core, en mode local-first.
|
||||
* <p>
|
||||
* En deploiement Docker, le Brain est un conteneur independant : ce mecanisme
|
||||
* est inactif (profil {@code local} uniquement). En application de bureau
|
||||
* empaquetee, il n'y a pas de Docker : le Core demarre lui-meme le Brain.
|
||||
*
|
||||
* @see BrainSidecar
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
@ConfigurationProperties(prefix = "brain.sidecar")
|
||||
public class BrainSidecarProperties {
|
||||
|
||||
/** Active le lancement du Brain par le Core. */
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* Commande de lancement (programme + arguments). Vide = ne rien lancer
|
||||
* (cas du dev qui demarre le Brain a la main).
|
||||
* <ul>
|
||||
* <li>Mode empaquete (jpackage) : chemin de l'exe PyInstaller, ex.
|
||||
* {@code C:\Program Files\LoreMind\brain\loremind-brain.exe}</li>
|
||||
* <li>Dev : {@code python,-m,uvicorn,app.main:app,--host,127.0.0.1,--port,8000}</li>
|
||||
* </ul>
|
||||
*/
|
||||
private List<String> command = List.of();
|
||||
|
||||
/**
|
||||
* Repertoire de travail du process Brain. Le Brain ecrit ses donnees (index
|
||||
* vectoriel, settings.json) sous {@code data/} RELATIF a ce dossier : on le
|
||||
* place donc sous loremind.home pour que tout vive au meme endroit.
|
||||
*/
|
||||
private String workingDir;
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||
|
||||
public List<String> getCommand() { return command; }
|
||||
public void setCommand(List<String> command) { this.command = command; }
|
||||
|
||||
public String getWorkingDir() { return workingDir; }
|
||||
public void setWorkingDir(String workingDir) { this.workingDir = workingDir; }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer;
|
||||
@@ -17,6 +18,12 @@ import java.time.Duration;
|
||||
* <p>
|
||||
* Sans cette entete, le Brain refuse la requete (401) — defense contre
|
||||
* l'acces direct au Brain depuis un attaquant qui atteindrait son port.
|
||||
* <p>
|
||||
* Relaie aussi l'entete X-User-Language (langue choisie dans l'UI, capturee par
|
||||
* {@link com.loremind.infrastructure.web.config.UserLanguageFilter}) pour que le
|
||||
* Brain redige ses reponses IA dans la langue de l'utilisateur. Lu depuis le
|
||||
* ThreadLocal au moment de l'execution de la requete (thread servlet) — d'ou
|
||||
* l'usage d'un interceptor (et non d'un defaultHeader fige au demarrage).
|
||||
*/
|
||||
@Configuration
|
||||
public class RestTemplateConfig {
|
||||
@@ -36,6 +43,7 @@ public class RestTemplateConfig {
|
||||
if (internalSecret != null && !internalSecret.isBlank()) {
|
||||
request.getHeaders().set(INTERNAL_SECRET_HEADER, internalSecret);
|
||||
}
|
||||
request.getHeaders().set(UserLanguageHolder.HEADER, UserLanguageHolder.get());
|
||||
return execution.execute(request, body);
|
||||
})
|
||||
.build();
|
||||
@@ -59,6 +67,7 @@ public class RestTemplateConfig {
|
||||
if (internalSecret != null && !internalSecret.isBlank()) {
|
||||
request.getHeaders().set(INTERNAL_SECRET_HEADER, internalSecret);
|
||||
}
|
||||
request.getHeaders().set(UserLanguageHolder.HEADER, UserLanguageHolder.get());
|
||||
return execution.execute(request, body);
|
||||
})
|
||||
.build();
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* En mode bureau (profil "local"), ouvre le navigateur par defaut sur
|
||||
* l'application des que le serveur est pret. L'app n'ayant pas de fenetre
|
||||
* native, c'est ce qui donne a l'utilisateur un retour visuel immediat apres
|
||||
* le double-clic.
|
||||
* <p>
|
||||
* Concerne uniquement l'instance qui a effectivement demarre le serveur :
|
||||
* l'instance « perdante » du verrou unique ouvre le navigateur des le {@code main}
|
||||
* puis sort (cf. {@link DesktopSingleInstance}).
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class DesktopBrowserOpener {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DesktopBrowserOpener.class);
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void onReady() {
|
||||
log.info("[Desktop] Application prete — ouverture du navigateur.");
|
||||
DesktopSingleInstance.openAppInBrowser();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
/**
|
||||
* Utilitaires du mode BUREAU (profil "local", application empaquetee jpackage).
|
||||
* <p>
|
||||
* Resout deux problemes specifiques au lancement par double-clic :
|
||||
* <ol>
|
||||
* <li><b>Instance unique</b> : un serveur web n'ouvre pas de fenetre. Un
|
||||
* utilisateur qui ne voit rien re-double-clique souvent — la 2e instance
|
||||
* trouvait la base H2 verrouillee et sortait en erreur, ce que le launcher
|
||||
* jpackage traduit par un trompeur « Failed to launch JVM ». On detecte
|
||||
* donc tres tot (avant Spring) qu'une instance tourne deja, et on se
|
||||
* contente d'ouvrir le navigateur puis de sortir proprement (code 0).</li>
|
||||
* <li><b>Ouverture du navigateur</b> : l'app n'ayant pas de fenetre native,
|
||||
* on ouvre le navigateur par defaut sur l'URL locale pour que l'utilisateur
|
||||
* voie l'application immediatement.</li>
|
||||
* </ol>
|
||||
* Volontairement sans dependance a {@code java.awt.Desktop} : ce module
|
||||
* ({@code java.desktop}) pourrait etre absent du runtime reduit par jlink.
|
||||
* On passe donc par la commande systeme d'ouverture d'URL.
|
||||
*/
|
||||
public final class DesktopSingleInstance {
|
||||
|
||||
/** Conserve le verrou ouvert pour TOUTE la duree de vie du process (sinon GC = relache). */
|
||||
@SuppressWarnings("unused")
|
||||
private static FileChannel lockChannel;
|
||||
private static FileLock lock;
|
||||
|
||||
private DesktopSingleInstance() {}
|
||||
|
||||
/** Vrai si le profil Spring actif inclut "local" (cas de l'app de bureau). */
|
||||
public static boolean isLocalProfile(String[] args) {
|
||||
String prop = System.getProperty("spring.profiles.active", "");
|
||||
String env = System.getenv().getOrDefault("SPRING_PROFILES_ACTIVE", "");
|
||||
if (containsLocal(prop) || containsLocal(env)) return true;
|
||||
if (args != null) {
|
||||
for (String a : args) {
|
||||
if (a.startsWith("--spring.profiles.active=") && containsLocal(a)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean containsLocal(String s) {
|
||||
for (String p : s.split("[,=]")) {
|
||||
if (p.trim().equals("local")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tente de prendre le verrou d'instance unique (fichier {@code .instance.lock}
|
||||
* sous loremind.home). Retourne {@code true} si on est la PREMIERE instance
|
||||
* (verrou obtenu, on doit demarrer le serveur), {@code false} si une autre
|
||||
* instance le detient deja.
|
||||
* <p>
|
||||
* En cas d'erreur d'E/S inattendue, on retourne {@code true} (degradation
|
||||
* prudente : mieux vaut tenter de demarrer que bloquer l'app).
|
||||
*/
|
||||
public static boolean tryAcquire() {
|
||||
try {
|
||||
Path dir = loremindHome();
|
||||
Files.createDirectories(dir);
|
||||
Path lockFile = dir.resolve(".instance.lock");
|
||||
lockChannel = FileChannel.open(lockFile,
|
||||
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
||||
lock = lockChannel.tryLock();
|
||||
return lock != null; // null = deja verrouille par une autre instance
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Verrou d'instance indisponible (" + e.getMessage()
|
||||
+ ") — on tente de demarrer quand meme.");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ouvre le navigateur par defaut sur l'URL de l'application locale (port reel). */
|
||||
public static void openAppInBrowser() {
|
||||
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
||||
}
|
||||
|
||||
/** Ouvre le navigateur par defaut sur une URL quelconque (sans dependance AWT). */
|
||||
public static void openUrl(String url) {
|
||||
try {
|
||||
String os = System.getProperty("os.name", "").toLowerCase();
|
||||
ProcessBuilder pb;
|
||||
if (os.contains("win")) {
|
||||
// rundll32 : ouverture d'URL fiable sans dependance graphique Java.
|
||||
pb = new ProcessBuilder("rundll32", "url.dll,FileProtocolHandler", url);
|
||||
} else if (os.contains("mac")) {
|
||||
pb = new ProcessBuilder("open", url);
|
||||
} else {
|
||||
pb = new ProcessBuilder("xdg-open", url);
|
||||
}
|
||||
pb.start();
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Impossible d'ouvrir le navigateur sur " + url
|
||||
+ " : " + e.getMessage() + ". Ouvrez-le manuellement.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Ouvre un dossier dans le gestionnaire de fichiers du systeme. */
|
||||
public static void openFolder(Path dir) {
|
||||
try {
|
||||
Files.createDirectories(dir);
|
||||
String os = System.getProperty("os.name", "").toLowerCase();
|
||||
ProcessBuilder pb;
|
||||
if (os.contains("win")) {
|
||||
pb = new ProcessBuilder("explorer.exe", dir.toString());
|
||||
} else if (os.contains("mac")) {
|
||||
pb = new ProcessBuilder("open", dir.toString());
|
||||
} else {
|
||||
pb = new ProcessBuilder("xdg-open", dir.toString());
|
||||
}
|
||||
pb.start();
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Ouverture du dossier impossible : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Ouvre un fichier texte dans l'editeur par defaut (Bloc-notes sous Windows). */
|
||||
public static void openInEditor(Path file) {
|
||||
try {
|
||||
String os = System.getProperty("os.name", "").toLowerCase();
|
||||
ProcessBuilder pb;
|
||||
if (os.contains("win")) {
|
||||
// notepad : toujours present, ouvre proprement un .properties
|
||||
// (dont l'association par defaut n'est pas garantie).
|
||||
pb = new ProcessBuilder("notepad.exe", file.toString());
|
||||
} else if (os.contains("mac")) {
|
||||
pb = new ProcessBuilder("open", "-t", file.toString());
|
||||
} else {
|
||||
pb = new ProcessBuilder("xdg-open", file.toString());
|
||||
}
|
||||
pb.start();
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Ouverture du fichier impossible : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static Path loremindHome() {
|
||||
String home = System.getProperty("loremind.home");
|
||||
if (home != null && !home.isBlank()) return Path.of(home);
|
||||
return Path.of(System.getProperty("user.home"), ".loremind");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.info.BuildProperties;
|
||||
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Verification des mises a jour pour l'application de BUREAU (profil "local").
|
||||
* <p>
|
||||
* Contrairement au mode Docker (registry + Watchtower, cf.
|
||||
* {@link com.loremind.infrastructure.updates.UpdateCheckService}), il n'y a pas
|
||||
* de mise a jour automatique : on interroge l'API <b>GitHub Releases</b> pour la
|
||||
* derniere release STABLE, on compare a la version courante du binaire, et si
|
||||
* une version plus recente existe on le signale (via l'icone systray, cf.
|
||||
* {@link SystemTrayManager}). L'utilisateur telecharge puis lance le nouvel
|
||||
* installeur (MSI de meme UpgradeCode = mise a jour en place).
|
||||
* <p>
|
||||
* {@code /releases/latest} ne renvoie que les releases stables (pas les
|
||||
* prereleases) : les utilisateurs stables ne sont donc pas notifies des betas.
|
||||
*/
|
||||
@Service
|
||||
@Profile("local")
|
||||
public class DesktopUpdateService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DesktopUpdateService.class);
|
||||
|
||||
private final RestTemplate http;
|
||||
private final boolean enabled;
|
||||
private final String releasesApiUrl;
|
||||
/** Version semver du binaire courant (ex: "0.14.0"), ou null en dev sans build-info. */
|
||||
private final String currentVersion;
|
||||
|
||||
public DesktopUpdateService(
|
||||
RestTemplateBuilder builder,
|
||||
@Value("${desktop.update.enabled:true}") boolean enabled,
|
||||
@Value("${desktop.update.releases-api-url:https://api.github.com/repos/IGMLcreation/LoreMind/releases/latest}") String releasesApiUrl,
|
||||
@Nullable BuildProperties buildProperties) {
|
||||
this.http = builder
|
||||
.setConnectTimeout(Duration.ofSeconds(5))
|
||||
.setReadTimeout(Duration.ofSeconds(10))
|
||||
.build();
|
||||
this.enabled = enabled;
|
||||
this.releasesApiUrl = releasesApiUrl;
|
||||
this.currentVersion = buildProperties != null ? buildProperties.getVersion() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interroge GitHub Releases. Retourne les infos de mise a jour SI une version
|
||||
* plus recente que la version courante existe, sinon {@code Optional.empty()}
|
||||
* (a jour, desactive, ou verification impossible — jamais d'exception propagee).
|
||||
*/
|
||||
public Optional<UpdateInfo> checkForUpdate() {
|
||||
if (!enabled || currentVersion == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
// GitHub exige un User-Agent ; l'Accept versionne l'API.
|
||||
headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop");
|
||||
headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json");
|
||||
|
||||
ResponseEntity<JsonNode> resp = http.exchange(
|
||||
releasesApiUrl, HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
|
||||
JsonNode body = resp.getBody();
|
||||
if (body == null || body.path("tag_name").isMissingNode()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String tag = body.path("tag_name").asText(""); // ex: "v0.15.0"
|
||||
String releaseUrl = body.path("html_url").asText(null); // page de la release
|
||||
String latest = tag.startsWith("v") ? tag.substring(1) : tag;
|
||||
|
||||
if (!latest.isBlank() && compareSemver(currentVersion, latest) < 0) {
|
||||
log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion);
|
||||
return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl));
|
||||
}
|
||||
log.info("[Update] A jour (courante : {}, derniere release : {}).", currentVersion, latest);
|
||||
return Optional.empty();
|
||||
} catch (Exception e) {
|
||||
// Hors-ligne, rate-limit GitHub, etc. : non bloquant, on ne notifie juste pas.
|
||||
log.info("[Update] Verification GitHub Releases impossible : {}", e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** Infos d'une mise a jour disponible. */
|
||||
public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {}
|
||||
|
||||
/**
|
||||
* Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore).
|
||||
* @return <0 si a<b, 0 si egales, >0 si a>b.
|
||||
*/
|
||||
static int compareSemver(String a, String b) {
|
||||
int[] va = parse(a);
|
||||
int[] vb = parse(b);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int cmp = Integer.compare(va[i], vb[i]);
|
||||
if (cmp != 0) return cmp;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int[] parse(String version) {
|
||||
String core = version.split("[-+]", 2)[0]; // retire -beta, -rc, +build...
|
||||
String[] parts = core.split("\\.");
|
||||
int[] out = new int[3];
|
||||
for (int i = 0; i < 3 && i < parts.length; i++) {
|
||||
try {
|
||||
out[i] = Integer.parseInt(parts[i].trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
out[i] = 0;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Configuration UTILISATEUR du mode bureau, dans un fichier éditable
|
||||
* {@code ~/.loremind/loremind.properties} (port HTTP, identifiants admin).
|
||||
* <p>
|
||||
* Pourquoi un fichier et pas l'UI : le port et le mot de passe admin sont requis
|
||||
* AVANT que le serveur (et donc l'UI web) ne démarre — impossible de les régler
|
||||
* depuis l'app elle-même. Un fichier texte simple, lu au démarrage, est le
|
||||
* pattern standard d'une app de bureau. Les modifs prennent effet au prochain
|
||||
* lancement.
|
||||
* <p>
|
||||
* - {@code server.port} : lu ici (résolution du port) ET par Spring.
|
||||
* - {@code admin.username} / {@code admin.password} : chargés par Spring via
|
||||
* {@code spring.config.import} (cf. application-local.properties) — ils
|
||||
* surchargent les défauts du profil local.
|
||||
* <p>
|
||||
* Repli de port : si le port configuré est occupé, on en choisit un libre
|
||||
* automatiquement (évite un échec de démarrage cryptique sur conflit de port)
|
||||
* et on écrit le port réellement utilisé dans {@code ~/.loremind/.port} pour que
|
||||
* l'ouverture du navigateur (instance gagnante OU 2e double-clic) cible la bonne URL.
|
||||
*/
|
||||
public final class DesktopUserConfig {
|
||||
|
||||
private DesktopUserConfig() {}
|
||||
|
||||
private static final String DEFAULT_TEMPLATE = """
|
||||
# ============================================================
|
||||
# Configuration locale de LoreMind (mode bureau)
|
||||
# ------------------------------------------------------------
|
||||
# Modifiez ces valeurs puis RELANCEZ LoreMind pour appliquer.
|
||||
# ============================================================
|
||||
|
||||
# Port HTTP local de l'application (http://localhost:<port>).
|
||||
# Si ce port est deja occupe par une autre application, LoreMind
|
||||
# choisira automatiquement un autre port libre au demarrage.
|
||||
server.port=8080
|
||||
|
||||
# Identifiants de la page Parametres (acces admin).
|
||||
# Accessible uniquement en local sur cette machine.
|
||||
admin.username=admin
|
||||
admin.password=admin
|
||||
""";
|
||||
|
||||
/** Chemin du fichier de config utilisateur (pour l'ouvrir depuis le menu systray). */
|
||||
public static Path getConfigFile() {
|
||||
return configFile();
|
||||
}
|
||||
|
||||
/** Dossier de données/config de l'instance ({@code ~/.loremind}). */
|
||||
public static Path getHomeDir() {
|
||||
return loremindHome();
|
||||
}
|
||||
|
||||
/** Crée le fichier de config avec des valeurs par défaut commentées s'il n'existe pas. */
|
||||
public static void ensureExists() {
|
||||
Path file = configFile();
|
||||
if (Files.exists(file)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, DEFAULT_TEMPLATE);
|
||||
System.out.println("[Desktop] Config utilisateur creee : " + file);
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Impossible de creer " + file + " : " + e.getMessage()
|
||||
+ " — defauts utilises (port 8080, admin/admin).");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Résout le port à utiliser : le port configuré s'il est libre, sinon un port
|
||||
* libre choisi automatiquement. Publie le résultat dans la propriété système
|
||||
* {@code server.port} (que Spring lira en priorité) et dans {@code ~/.loremind/.port}.
|
||||
*
|
||||
* @return le port effectivement retenu.
|
||||
*/
|
||||
public static int resolveAndPublishPort() {
|
||||
int wanted = configuredPort();
|
||||
int chosen = isPortFree(wanted) ? wanted : findFreePort(wanted);
|
||||
if (chosen != wanted) {
|
||||
System.out.println("[Desktop] Port " + wanted + " occupe — repli sur le port libre " + chosen + ".");
|
||||
}
|
||||
System.setProperty("server.port", String.valueOf(chosen));
|
||||
try {
|
||||
Files.writeString(portFile(), String.valueOf(chosen));
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Ecriture du port impossible (" + e.getMessage() + ").");
|
||||
}
|
||||
return chosen;
|
||||
}
|
||||
|
||||
/**
|
||||
* Port sur lequel l'application répond réellement (pour ouvrir le navigateur).
|
||||
* Ordre : propriété système (instance gagnante) → fichier .port (2e double-clic)
|
||||
* → port configuré → 8080.
|
||||
*/
|
||||
public static int runningPort() {
|
||||
String sys = System.getProperty("server.port");
|
||||
if (sys != null && !sys.isBlank()) {
|
||||
try { return Integer.parseInt(sys.trim()); } catch (NumberFormatException ignored) { /* fallthrough */ }
|
||||
}
|
||||
try {
|
||||
Path p = portFile();
|
||||
if (Files.exists(p)) {
|
||||
return Integer.parseInt(Files.readString(p).trim());
|
||||
}
|
||||
} catch (IOException | NumberFormatException ignored) { /* fallthrough */ }
|
||||
return configuredPort();
|
||||
}
|
||||
|
||||
/** Port lu dans le fichier de config utilisateur (défaut 8080). */
|
||||
private static int configuredPort() {
|
||||
Path file = configFile();
|
||||
if (Files.exists(file)) {
|
||||
Properties props = new Properties();
|
||||
try (InputStream in = Files.newInputStream(file)) {
|
||||
props.load(in);
|
||||
String v = props.getProperty("server.port");
|
||||
if (v != null && !v.isBlank()) {
|
||||
return Integer.parseInt(v.trim());
|
||||
}
|
||||
} catch (IOException | NumberFormatException ignored) { /* défaut */ }
|
||||
}
|
||||
return 8080;
|
||||
}
|
||||
|
||||
private static boolean isPortFree(int port) {
|
||||
try (ServerSocket s = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"))) {
|
||||
s.setReuseAddress(true);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int findFreePort(int fallbackIfNone) {
|
||||
try (ServerSocket s = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) {
|
||||
return s.getLocalPort();
|
||||
} catch (IOException e) {
|
||||
return fallbackIfNone; // tres improbable ; on retente le port voulu
|
||||
}
|
||||
}
|
||||
|
||||
private static Path configFile() {
|
||||
return loremindHome().resolve("loremind.properties");
|
||||
}
|
||||
|
||||
private static Path portFile() {
|
||||
return loremindHome().resolve(".port");
|
||||
}
|
||||
|
||||
private static Path loremindHome() {
|
||||
String home = System.getProperty("loremind.home");
|
||||
if (home != null && !home.isBlank()) return Path.of(home);
|
||||
return Path.of(System.getProperty("user.home"), ".loremind");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.Image;
|
||||
import java.awt.MenuItem;
|
||||
import java.awt.PopupMenu;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.SystemTray;
|
||||
import java.awt.TrayIcon;
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
/**
|
||||
* Icone dans la zone de notification (barre des taches) en mode bureau
|
||||
* (profil "local"). Donne a l'utilisateur un controle visible de l'application,
|
||||
* qui tourne sinon en serveur sans fenetre : impossible autrement de la fermer
|
||||
* proprement (fermer l'onglet du navigateur laisse le Core et le Brain tourner).
|
||||
* <p>
|
||||
* Menu : « Ouvrir LoreMind » (ouvre le navigateur) et « Quitter LoreMind »
|
||||
* (ferme le contexte Spring — ce qui declenche le {@code @PreDestroy} de
|
||||
* {@link com.loremind.infrastructure.ai.BrainSidecar} et arrete donc aussi le
|
||||
* Brain — puis termine le process).
|
||||
* <p>
|
||||
* Necessite que le mode headless soit desactive (cf. LoreMindApplication.main,
|
||||
* qui appelle {@code setHeadless(false)} en profil local). Le module
|
||||
* {@code java.desktop} est embarque dans le runtime jpackage.
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class SystemTrayManager {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SystemTrayManager.class);
|
||||
|
||||
private final ConfigurableApplicationContext context;
|
||||
private final DesktopUpdateService updateService;
|
||||
private TrayIcon trayIcon;
|
||||
private PopupMenu popup;
|
||||
|
||||
public SystemTrayManager(ConfigurableApplicationContext context,
|
||||
DesktopUpdateService updateService) {
|
||||
this.context = context;
|
||||
this.updateService = updateService;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void install() {
|
||||
if (!SystemTray.isSupported()) {
|
||||
log.warn("[Tray] Zone de notification non supportee sur ce systeme — "
|
||||
+ "pas d'icone. Pour quitter : menu de la fenetre console, ou gestionnaire des taches.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
popup = new PopupMenu();
|
||||
|
||||
MenuItem open = new MenuItem("Ouvrir LoreMind");
|
||||
open.addActionListener(e -> DesktopSingleInstance.openAppInBrowser());
|
||||
popup.add(open);
|
||||
|
||||
popup.addSeparator();
|
||||
|
||||
// Reglages : ouvre loremind.properties (port, identifiants admin) dans
|
||||
// l'editeur. Les changements prennent effet au prochain demarrage.
|
||||
MenuItem editConfig = new MenuItem("Modifier la configuration (port, identifiants…)");
|
||||
editConfig.addActionListener(e -> {
|
||||
DesktopUserConfig.ensureExists();
|
||||
DesktopSingleInstance.openInEditor(DesktopUserConfig.getConfigFile());
|
||||
});
|
||||
popup.add(editConfig);
|
||||
|
||||
// Acces au dossier de donnees (~/.loremind : base, images, config…).
|
||||
MenuItem openFolder = new MenuItem("Ouvrir le dossier LoreMind");
|
||||
openFolder.addActionListener(e -> DesktopSingleInstance.openFolder(DesktopUserConfig.getHomeDir()));
|
||||
popup.add(openFolder);
|
||||
|
||||
popup.addSeparator();
|
||||
|
||||
MenuItem quit = new MenuItem("Quitter LoreMind");
|
||||
quit.addActionListener(e -> quit());
|
||||
popup.add(quit);
|
||||
|
||||
trayIcon = new TrayIcon(createIcon(), "LoreMind", popup);
|
||||
trayIcon.setImageAutoSize(true);
|
||||
// Double-clic sur l'icone : ouvre l'application dans le navigateur.
|
||||
trayIcon.addActionListener(e -> DesktopSingleInstance.openAppInBrowser());
|
||||
|
||||
SystemTray.getSystemTray().add(trayIcon);
|
||||
log.info("[Tray] Icone installee dans la zone de notification.");
|
||||
|
||||
// Verification de mise a jour en arriere-plan (appel reseau GitHub) :
|
||||
// ne bloque pas le demarrage ; met a jour le menu/notifie si dispo.
|
||||
new Thread(this::checkForUpdate, "loremind-update-check").start();
|
||||
} catch (Exception e) {
|
||||
// Echec non bloquant : l'app reste utilisable, seul le confort de l'icone manque.
|
||||
log.warn("[Tray] Installation de l'icone impossible : {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interroge GitHub Releases ; si une version plus recente existe, ajoute un
|
||||
* item de menu « Telecharger » et affiche une bulle de notification. L'item
|
||||
* ouvre la page de la release dans le navigateur (telechargement manuel du
|
||||
* nouvel installeur).
|
||||
*/
|
||||
private void checkForUpdate() {
|
||||
updateService.checkForUpdate().ifPresent(info -> {
|
||||
String label = "⬇ Telecharger la mise a jour (v" + info.latestVersion() + ")";
|
||||
MenuItem update = new MenuItem(label);
|
||||
update.addActionListener(e -> DesktopSingleInstance.openUrl(info.releaseUrl()));
|
||||
// En tete de menu pour la visibilite, suivi d'un separateur.
|
||||
popup.insert(update, 0);
|
||||
popup.insertSeparator(1);
|
||||
|
||||
trayIcon.displayMessage(
|
||||
"LoreMind — mise a jour disponible",
|
||||
"Version " + info.latestVersion() + " disponible (vous avez " + info.currentVersion()
|
||||
+ "). Menu de l'icone → Telecharger.",
|
||||
TrayIcon.MessageType.INFO);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Arret propre depuis le menu « Quitter » : on retire l'icone puis on ferme
|
||||
* le contexte Spring dans un thread dedie (l'action s'execute sur l'EDT AWT ;
|
||||
* fermer le contexte + arreter Tomcat/Brain depuis l'EDT pourrait le bloquer).
|
||||
*/
|
||||
private void quit() {
|
||||
log.info("[Tray] Demande de fermeture de l'application.");
|
||||
new Thread(() -> {
|
||||
int code = SpringApplication.exit(context, () -> 0);
|
||||
System.exit(code);
|
||||
}, "loremind-shutdown").start();
|
||||
}
|
||||
|
||||
/** Retire l'icone si le contexte se ferme par une autre voie (ex. Ctrl+C). */
|
||||
@PreDestroy
|
||||
public void remove() {
|
||||
if (trayIcon != null) {
|
||||
SystemTray.getSystemTray().remove(trayIcon);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Genere une petite icone (carre arrondi violet « L ») sans dependre d'un
|
||||
* fichier image — robuste quel que soit l'empaquetage.
|
||||
*/
|
||||
private Image createIcon() {
|
||||
int size = 16;
|
||||
BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setColor(new Color(0x8B, 0x5C, 0xF6)); // violet de marque LoreMind
|
||||
g.fillRoundRect(0, 0, size, size, 5, 5);
|
||||
g.setColor(Color.WHITE);
|
||||
g.setFont(new Font("SansSerif", Font.BOLD, 12));
|
||||
g.drawString("L", 4, 13);
|
||||
g.dispose();
|
||||
return img;
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,14 @@ import com.loremind.infrastructure.persistence.entity.ImageJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Repository Spring Data JPA pour ImageJpaEntity.
|
||||
* Ne contient aucune requete custom pour l'instant : CRUD standard suffit.
|
||||
*/
|
||||
@Repository
|
||||
public interface ImageJpaRepository extends JpaRepository<ImageJpaEntity, Long> {
|
||||
|
||||
/** Recherche par cle de stockage (unique). Utilise par l'import de contenu. */
|
||||
Optional<ImageJpaEntity> findByStorageKey(String storageKey);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.loremind.infrastructure.storage;
|
||||
|
||||
import com.loremind.domain.images.ports.ImageStorage;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Adaptateur d'infrastructure : implemente le port ImageStorage en stockant
|
||||
* les binaires sur le SYSTEME DE FICHIERS local.
|
||||
* <p>
|
||||
* Pendant a {@link MinioImageStorageAdapter} pour le mode "local-first"
|
||||
* (application de bureau empaquetee via jpackage, sans Docker ni MinIO).
|
||||
* Active uniquement quand {@code storage.backend=filesystem} ; en l'absence
|
||||
* de cette propriete, c'est l'adaptateur MinIO qui prend le relais (defaut).
|
||||
* <p>
|
||||
* On reutilise EXACTEMENT le meme schema de cle que MinIO ({@code images/UUID.ext})
|
||||
* pour que les cles restent interchangeables entre les deux backends : une base
|
||||
* migree de l'un vers l'autre continue de fonctionner sans reecriture.
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "storage.backend", havingValue = "filesystem")
|
||||
public class FilesystemImageStorageAdapter implements ImageStorage {
|
||||
|
||||
private final Path root;
|
||||
|
||||
public FilesystemImageStorageAdapter(@Value("${storage.filesystem.path}") String basePath) {
|
||||
this.root = Path.of(basePath).toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void ensureRootExists() {
|
||||
try {
|
||||
Files.createDirectories(root);
|
||||
System.out.println("[Storage] Backend filesystem actif — racine : " + root);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Impossible de creer le dossier de stockage : " + root, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String upload(String filename, String contentType, InputStream data, long sizeBytes) {
|
||||
String storageKey = generateStorageKey(filename);
|
||||
Path target = resolveKey(storageKey);
|
||||
try {
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(data, target);
|
||||
return storageKey;
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Echec de l'ecriture de l'image sur disque : " + target, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void store(String storageKey, String contentType, InputStream data, long sizeBytes) {
|
||||
Path target = resolveKey(storageKey);
|
||||
try {
|
||||
Files.createDirectories(target.getParent());
|
||||
// Ecrase si la cle existe deja (contrat de store-avec-cle).
|
||||
Files.copy(data, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Echec de l'ecriture de l'image sur disque (cle imposee) : " + target, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream download(String storageKey) {
|
||||
Path source = resolveKey(storageKey);
|
||||
if (!Files.exists(source)) {
|
||||
// Cle orpheline : meme contrat que MinIO (null plutot qu'exception).
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Files.newInputStream(source);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Echec de la lecture de l'image : " + source, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String storageKey) {
|
||||
try {
|
||||
Files.deleteIfExists(resolveKey(storageKey));
|
||||
} catch (IOException e) {
|
||||
// Suppression idempotente : on loggue mais on ne propage pas (cf. MinIO).
|
||||
System.err.println("[Storage] Erreur suppression (non bloquante) : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resout une cle opaque en chemin physique, en se premunissant contre la
|
||||
* traversee de repertoire : le chemin resolu DOIT rester sous {@code root}
|
||||
* (une cle malveillante du type {@code ../../etc/passwd} est rejetee).
|
||||
*/
|
||||
private Path resolveKey(String storageKey) {
|
||||
Path resolved = root.resolve(storageKey).normalize();
|
||||
if (!resolved.startsWith(root)) {
|
||||
throw new IllegalArgumentException("Cle de stockage invalide (hors racine) : " + storageKey);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** Identique a MinioImageStorageAdapter : cle unique + extension d'origine. */
|
||||
private String generateStorageKey(String originalFilename) {
|
||||
return "images/" + UUID.randomUUID() + extractExtension(originalFilename);
|
||||
}
|
||||
|
||||
private String extractExtension(String filename) {
|
||||
if (filename == null) return "";
|
||||
int dot = filename.lastIndexOf('.');
|
||||
if (dot < 0 || dot == filename.length() - 1) return "";
|
||||
String ext = filename.substring(dot).toLowerCase();
|
||||
// On n'accepte que les extensions connues pour eviter les injections de path.
|
||||
return ext.matches("\\.(jpg|jpeg|png|webp|gif)") ? ext : "";
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import io.minio.MakeBucketArgs;
|
||||
import io.minio.MinioClient;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -14,8 +15,13 @@ import org.springframework.context.annotation.Configuration;
|
||||
* Expose un bean MinioClient singleton injecte dans MinioImageStorageAdapter.
|
||||
* S'assure au demarrage que le bucket configure existe (filet de securite :
|
||||
* normalement docker-compose/minio-init l'a deja cree).
|
||||
* <p>
|
||||
* Desactive en mode local-first ({@code storage.backend=filesystem}) : aucun
|
||||
* client MinIO n'est alors instancie, donc aucune tentative de connexion au
|
||||
* boot. Defaut = actif (propriete absente ou {@code minio}).
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnProperty(name = "storage.backend", havingValue = "minio", matchIfMissing = true)
|
||||
public class MinioConfig {
|
||||
|
||||
@Value("${minio.endpoint}")
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.minio.PutObjectArgs;
|
||||
import io.minio.RemoveObjectArgs;
|
||||
import io.minio.errors.ErrorResponseException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.InputStream;
|
||||
@@ -17,8 +18,13 @@ import java.util.UUID;
|
||||
* MinIO (compatible S3) comme backend de stockage d'objets.
|
||||
* <p>
|
||||
* Le domaine ne sait rien de MinIO : il manipule juste des cles opaques.
|
||||
* <p>
|
||||
* Backend par defaut ({@code storage.backend=minio} ou propriete absente).
|
||||
* Le mode local-first le remplace par {@link FilesystemImageStorageAdapter}
|
||||
* via {@code storage.backend=filesystem}.
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "storage.backend", havingValue = "minio", matchIfMissing = true)
|
||||
public class MinioImageStorageAdapter implements ImageStorage {
|
||||
|
||||
private final MinioClient minioClient;
|
||||
@@ -48,6 +54,22 @@ public class MinioImageStorageAdapter implements ImageStorage {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void store(String storageKey, String contentType, InputStream data, long sizeBytes) {
|
||||
try {
|
||||
minioClient.putObject(
|
||||
PutObjectArgs.builder()
|
||||
.bucket(bucket)
|
||||
.object(storageKey)
|
||||
.stream(data, sizeBytes, -1)
|
||||
.contentType(contentType)
|
||||
.build()
|
||||
);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Echec du store MinIO (cle imposee) : " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream download(String storageKey) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
package com.loremind.infrastructure.transfer;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.loremind.domain.images.ports.ImageStorage;
|
||||
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||
import com.loremind.infrastructure.persistence.entity.*;
|
||||
import com.loremind.infrastructure.persistence.jpa.*;
|
||||
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
||||
import org.springframework.boot.info.BuildProperties;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* Service d'EXPORT du "contenu" en format logique (JSON) portable.
|
||||
* <p>
|
||||
* Construit un {@link ContentExport} a partir des entites JPA puis le serialise
|
||||
* dans un .zip contenant :
|
||||
* <ul>
|
||||
* <li>{@code manifest.json} — metadonnees (version de format, version app, date)</li>
|
||||
* <li>{@code data.json} — tout le contenu (pretty-printed)</li>
|
||||
* <li>{@code images/<storageKey>} — un binaire par image referencee</li>
|
||||
* </ul>
|
||||
* Volontairement DECOUPLE de la base : c'est un export logique, pas un dump,
|
||||
* pour fonctionner entre Postgres (Docker) et H2 (local).
|
||||
*/
|
||||
@Service
|
||||
public class ExportService {
|
||||
|
||||
private static final int FORMAT_VERSION = 1;
|
||||
|
||||
// Réutilise le converter JPA pour (dé)sérialiser les prérequis dans le MÊME
|
||||
// format que la base (discriminant "kind"), au lieu de Jackson polymorphe.
|
||||
private static final PrerequisiteListJsonConverter PREREQ_CONVERTER = new PrerequisiteListJsonConverter();
|
||||
|
||||
private final GameSystemJpaRepository gameSystemRepo;
|
||||
private final LoreJpaRepository loreRepo;
|
||||
private final LoreNodeJpaRepository loreNodeRepo;
|
||||
private final TemplateJpaRepository templateRepo;
|
||||
private final PageJpaRepository pageRepo;
|
||||
private final CampaignJpaRepository campaignRepo;
|
||||
private final ArcJpaRepository arcRepo;
|
||||
private final ChapterJpaRepository chapterRepo;
|
||||
private final SceneJpaRepository sceneRepo;
|
||||
private final CharacterJpaRepository characterRepo;
|
||||
private final NpcJpaRepository npcRepo;
|
||||
private final EnemyJpaRepository enemyRepo;
|
||||
private final ItemCatalogJpaRepository itemCatalogRepo;
|
||||
private final RandomTableJpaRepository randomTableRepo;
|
||||
private final ImageJpaRepository imageRepo;
|
||||
private final ImageStorage imageStorage;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final String appVersion;
|
||||
|
||||
public ExportService(GameSystemJpaRepository gameSystemRepo,
|
||||
LoreJpaRepository loreRepo,
|
||||
LoreNodeJpaRepository loreNodeRepo,
|
||||
TemplateJpaRepository templateRepo,
|
||||
PageJpaRepository pageRepo,
|
||||
CampaignJpaRepository campaignRepo,
|
||||
ArcJpaRepository arcRepo,
|
||||
ChapterJpaRepository chapterRepo,
|
||||
SceneJpaRepository sceneRepo,
|
||||
CharacterJpaRepository characterRepo,
|
||||
NpcJpaRepository npcRepo,
|
||||
EnemyJpaRepository enemyRepo,
|
||||
ItemCatalogJpaRepository itemCatalogRepo,
|
||||
RandomTableJpaRepository randomTableRepo,
|
||||
ImageJpaRepository imageRepo,
|
||||
ImageStorage imageStorage,
|
||||
ObjectMapper objectMapper,
|
||||
@Nullable BuildProperties buildProperties) {
|
||||
this.gameSystemRepo = gameSystemRepo;
|
||||
this.loreRepo = loreRepo;
|
||||
this.loreNodeRepo = loreNodeRepo;
|
||||
this.templateRepo = templateRepo;
|
||||
this.pageRepo = pageRepo;
|
||||
this.campaignRepo = campaignRepo;
|
||||
this.arcRepo = arcRepo;
|
||||
this.chapterRepo = chapterRepo;
|
||||
this.sceneRepo = sceneRepo;
|
||||
this.characterRepo = characterRepo;
|
||||
this.npcRepo = npcRepo;
|
||||
this.enemyRepo = enemyRepo;
|
||||
this.itemCatalogRepo = itemCatalogRepo;
|
||||
this.randomTableRepo = randomTableRepo;
|
||||
this.imageRepo = imageRepo;
|
||||
this.imageStorage = imageStorage;
|
||||
this.objectMapper = objectMapper;
|
||||
this.appVersion = buildProperties != null ? buildProperties.getVersion() : "dev";
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge toutes les entites du perimetre et les mappe vers les DTO plats.
|
||||
*
|
||||
* @param exportedAt horodatage ISO stampe par la couche appelante (controller)
|
||||
*/
|
||||
public ContentExport buildExport(String exportedAt) {
|
||||
ContentExport.Manifest manifest =
|
||||
new ContentExport.Manifest(FORMAT_VERSION, appVersion, exportedAt);
|
||||
|
||||
List<ContentExport.GameSystemDto> gameSystems = gameSystemRepo.findAll().stream()
|
||||
.map(this::toGameSystemDto).toList();
|
||||
List<ContentExport.LoreDto> lores = loreRepo.findAll().stream()
|
||||
.map(this::toLoreDto).toList();
|
||||
List<ContentExport.LoreNodeDto> loreNodes = loreNodeRepo.findAll().stream()
|
||||
.map(this::toLoreNodeDto).toList();
|
||||
List<ContentExport.TemplateDto> templates = templateRepo.findAll().stream()
|
||||
.map(this::toTemplateDto).toList();
|
||||
List<ContentExport.PageDto> pages = pageRepo.findAll().stream()
|
||||
.map(this::toPageDto).toList();
|
||||
List<ContentExport.CampaignDto> campaigns = campaignRepo.findAll().stream()
|
||||
.map(this::toCampaignDto).toList();
|
||||
List<ContentExport.ArcDto> arcs = arcRepo.findAll().stream()
|
||||
.map(this::toArcDto).toList();
|
||||
List<ContentExport.ChapterDto> chapters = chapterRepo.findAll().stream()
|
||||
.map(this::toChapterDto).toList();
|
||||
List<ContentExport.SceneDto> scenes = sceneRepo.findAll().stream()
|
||||
.map(this::toSceneDto).toList();
|
||||
List<ContentExport.CharacterDto> characters = characterRepo.findAll().stream()
|
||||
.map(this::toCharacterDto).toList();
|
||||
List<ContentExport.NpcDto> npcs = npcRepo.findAll().stream()
|
||||
.map(this::toNpcDto).toList();
|
||||
List<ContentExport.EnemyDto> enemies = enemyRepo.findAll().stream()
|
||||
.map(this::toEnemyDto).toList();
|
||||
List<ContentExport.ItemCatalogDto> itemCatalogs = itemCatalogRepo.findAll().stream()
|
||||
.map(this::toItemCatalogDto).toList();
|
||||
List<ContentExport.RandomTableDto> randomTables = randomTableRepo.findAll().stream()
|
||||
.map(this::toRandomTableDto).toList();
|
||||
List<ContentExport.ImageDto> images = imageRepo.findAll().stream()
|
||||
.map(this::toImageDto).toList();
|
||||
|
||||
return new ContentExport(manifest, gameSystems, lores, loreNodes, templates,
|
||||
pages, campaigns, arcs, chapters, scenes, characters, npcs, enemies,
|
||||
itemCatalogs, randomTables, images);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialise un export dans le flux fourni au format .zip.
|
||||
* <p>
|
||||
* Les binaires d'images ne sont ecrits que pour les storageKeys REFERENCES
|
||||
* par les entites exportees (illustration/map/portrait/header/imageValues),
|
||||
* pas pour toute la table images — on evite de trimballer des orphelins.
|
||||
*/
|
||||
public void writeZip(ContentExport export, OutputStream out) {
|
||||
try (ZipOutputStream zip = new ZipOutputStream(out)) {
|
||||
// manifest.json
|
||||
zip.putNextEntry(new ZipEntry("manifest.json"));
|
||||
zip.write(objectMapper.writerWithDefaultPrettyPrinter()
|
||||
.writeValueAsBytes(export.manifest()));
|
||||
zip.closeEntry();
|
||||
|
||||
// data.json
|
||||
zip.putNextEntry(new ZipEntry("data.json"));
|
||||
zip.write(objectMapper.copy()
|
||||
.enable(SerializationFeature.INDENT_OUTPUT)
|
||||
.writeValueAsBytes(export));
|
||||
zip.closeEntry();
|
||||
|
||||
// Binaires images : uniquement ceux reellement references.
|
||||
Set<String> referenced = collectReferencedStorageKeys(export);
|
||||
Set<String> written = new LinkedHashSet<>();
|
||||
for (String key : referenced) {
|
||||
if (key == null || key.isBlank() || !written.add(key)) {
|
||||
continue;
|
||||
}
|
||||
try (InputStream data = imageStorage.download(key)) {
|
||||
if (data == null) {
|
||||
continue; // cle orpheline : on ignore silencieusement
|
||||
}
|
||||
zip.putNextEntry(new ZipEntry("images/" + key));
|
||||
data.transferTo(zip);
|
||||
zip.closeEntry();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Echec de la generation du zip d'export", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collecte tous les storageKeys references par le contenu exporte :
|
||||
* Arc/Chapter/Scene (illustration + map), Character/Npc/Enemy
|
||||
* (portrait + header + imageValues), Page (imageValues).
|
||||
*/
|
||||
private Set<String> collectReferencedStorageKeys(ContentExport export) {
|
||||
Set<String> keys = new LinkedHashSet<>();
|
||||
for (ContentExport.ArcDto a : export.arcs()) {
|
||||
addAll(keys, a.illustrationImageIds());
|
||||
addAll(keys, a.mapImageIds());
|
||||
}
|
||||
for (ContentExport.ChapterDto c : export.chapters()) {
|
||||
addAll(keys, c.illustrationImageIds());
|
||||
addAll(keys, c.mapImageIds());
|
||||
}
|
||||
for (ContentExport.SceneDto s : export.scenes()) {
|
||||
addAll(keys, s.illustrationImageIds());
|
||||
addAll(keys, s.mapImageIds());
|
||||
}
|
||||
for (ContentExport.CharacterDto c : export.characters()) {
|
||||
add(keys, c.portraitImageId());
|
||||
add(keys, c.headerImageId());
|
||||
addImageValues(keys, c.imageValues());
|
||||
}
|
||||
for (ContentExport.NpcDto n : export.npcs()) {
|
||||
add(keys, n.portraitImageId());
|
||||
add(keys, n.headerImageId());
|
||||
addImageValues(keys, n.imageValues());
|
||||
}
|
||||
for (ContentExport.EnemyDto e : export.enemies()) {
|
||||
add(keys, e.portraitImageId());
|
||||
add(keys, e.headerImageId());
|
||||
addImageValues(keys, e.imageValues());
|
||||
}
|
||||
for (ContentExport.PageDto p : export.pages()) {
|
||||
addImageValues(keys, p.imageValues());
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private void add(Set<String> keys, String key) {
|
||||
if (key != null && !key.isBlank()) keys.add(key);
|
||||
}
|
||||
|
||||
private void addAll(Set<String> keys, List<String> list) {
|
||||
if (list != null) list.forEach(k -> add(keys, k));
|
||||
}
|
||||
|
||||
private void addImageValues(Set<String> keys, java.util.Map<String, List<String>> imageValues) {
|
||||
if (imageValues != null) imageValues.values().forEach(l -> addAll(keys, l));
|
||||
}
|
||||
|
||||
// ----- Mappers entite -> DTO -----
|
||||
|
||||
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
|
||||
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
|
||||
e.getEnemyTemplate(), e.getAuthor(), e.isPublic());
|
||||
}
|
||||
|
||||
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
|
||||
return new ContentExport.LoreDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getNodeCount(), e.getPageCount());
|
||||
}
|
||||
|
||||
private ContentExport.LoreNodeDto toLoreNodeDto(LoreNodeJpaEntity e) {
|
||||
return new ContentExport.LoreNodeDto(e.getId(), e.getName(), e.getIcon(),
|
||||
e.getParentId(), e.getLoreId());
|
||||
}
|
||||
|
||||
private ContentExport.TemplateDto toTemplateDto(TemplateJpaEntity e) {
|
||||
return new ContentExport.TemplateDto(e.getId(), e.getLoreId(), e.getName(),
|
||||
e.getDescription(), e.getDefaultNodeId(), e.getFields());
|
||||
}
|
||||
|
||||
private ContentExport.PageDto toPageDto(PageJpaEntity e) {
|
||||
return new ContentExport.PageDto(e.getId(), e.getLoreId(), e.getNodeId(),
|
||||
e.getTemplateId(), e.getTitle(), e.getValues(), e.getImageValues(),
|
||||
e.getKeyValueValues(), e.getTableValues(), e.getNotes(), e.getTags(),
|
||||
e.getRelatedPageIds());
|
||||
}
|
||||
|
||||
private ContentExport.CampaignDto toCampaignDto(CampaignJpaEntity e) {
|
||||
return new ContentExport.CampaignDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getArcsCount(), e.getLoreId(), e.getGameSystemId());
|
||||
}
|
||||
|
||||
private ContentExport.ArcDto toArcDto(ArcJpaEntity e) {
|
||||
return new ContentExport.ArcDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getCampaignId(), e.getOrder(),
|
||||
e.getType() != null ? e.getType().name() : null,
|
||||
e.getIcon(), e.getThemes(), e.getStakes(), e.getGmNotes(),
|
||||
e.getRewards(), e.getResolution(), e.getRelatedPageIds(),
|
||||
e.getIllustrationImageIds(), e.getMapImageIds());
|
||||
}
|
||||
|
||||
private ContentExport.ChapterDto toChapterDto(ChapterJpaEntity e) {
|
||||
return new ContentExport.ChapterDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getArcId(), e.getOrder(), PREREQ_CONVERTER.convertToDatabaseColumn(e.getPrerequisites()), e.getIcon(),
|
||||
e.getGmNotes(), e.getPlayerObjectives(), e.getNarrativeStakes(),
|
||||
e.getRelatedPageIds(), e.getIllustrationImageIds(), e.getMapImageIds());
|
||||
}
|
||||
|
||||
private ContentExport.SceneDto toSceneDto(SceneJpaEntity e) {
|
||||
return new ContentExport.SceneDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getChapterId(), e.getOrder(), e.getIcon(), e.getLocation(),
|
||||
e.getTiming(), e.getAtmosphere(), e.getPlayerNarration(),
|
||||
e.getGmSecretNotes(), e.getChoicesConsequences(), e.getCombatDifficulty(),
|
||||
e.getEnemies(), e.getEnemyIds(), e.getRelatedPageIds(),
|
||||
e.getIllustrationImageIds(), e.getMapImageIds(), e.getBranches(), e.getRooms());
|
||||
}
|
||||
|
||||
private ContentExport.CharacterDto toCharacterDto(CharacterJpaEntity e) {
|
||||
return new ContentExport.CharacterDto(e.getId(), e.getName(), e.getPortraitImageId(),
|
||||
e.getHeaderImageId(), e.getValues(), e.getImageValues(), e.getKeyValueValues(),
|
||||
e.getCampaignId(), e.getPlaythroughId(), e.getOrder());
|
||||
}
|
||||
|
||||
private ContentExport.NpcDto toNpcDto(NpcJpaEntity e) {
|
||||
return new ContentExport.NpcDto(e.getId(), e.getName(), e.getPortraitImageId(),
|
||||
e.getHeaderImageId(), e.getValues(), e.getImageValues(), e.getKeyValueValues(),
|
||||
e.getCampaignId(), e.getRelatedPageIds(), e.getFolder(), e.getOrder());
|
||||
}
|
||||
|
||||
private ContentExport.EnemyDto toEnemyDto(EnemyJpaEntity e) {
|
||||
return new ContentExport.EnemyDto(e.getId(), e.getName(), e.getLevel(), e.getFolder(),
|
||||
e.getPortraitImageId(), e.getHeaderImageId(), e.getValues(), e.getImageValues(),
|
||||
e.getKeyValueValues(), e.getCampaignId(), e.getOrder());
|
||||
}
|
||||
|
||||
private ContentExport.ItemCatalogDto toItemCatalogDto(ItemCatalogJpaEntity e) {
|
||||
List<ContentExport.CatalogItemDto> items = new ArrayList<>();
|
||||
if (e.getItems() != null) {
|
||||
for (CatalogItemJpaEntity i : e.getItems()) {
|
||||
items.add(new ContentExport.CatalogItemDto(i.getId(), i.getName(),
|
||||
i.getPrice(), i.getCategory(), i.getDescription(), i.getPosition()));
|
||||
}
|
||||
}
|
||||
return new ContentExport.ItemCatalogDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getIcon(), e.getCampaignId(), e.getOrder(), items);
|
||||
}
|
||||
|
||||
private ContentExport.RandomTableDto toRandomTableDto(RandomTableJpaEntity e) {
|
||||
List<ContentExport.RandomTableEntryDto> entries = new ArrayList<>();
|
||||
if (e.getEntries() != null) {
|
||||
for (RandomTableEntryJpaEntity en : e.getEntries()) {
|
||||
entries.add(new ContentExport.RandomTableEntryDto(en.getId(), en.getMinRoll(),
|
||||
en.getMaxRoll(), en.getLabel(), en.getDetail(), en.getPosition()));
|
||||
}
|
||||
}
|
||||
return new ContentExport.RandomTableDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getDiceFormula(), e.getIcon(), e.getCampaignId(), e.getOrder(), entries);
|
||||
}
|
||||
|
||||
private ContentExport.ImageDto toImageDto(ImageJpaEntity e) {
|
||||
return new ContentExport.ImageDto(e.getId(), e.getFilename(), e.getContentType(),
|
||||
e.getSizeBytes(), e.getStorageKey());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.loremind.infrastructure.transfer;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Resume d'un import : nombre d'entites creees par type, + nombre d'images
|
||||
* reuploadees / reutilisees.
|
||||
*/
|
||||
public record ImportResult(Map<String, Integer> created, int imagesUploaded, int imagesReused) {
|
||||
|
||||
public static class Builder {
|
||||
private final Map<String, Integer> created = new LinkedHashMap<>();
|
||||
private int imagesUploaded;
|
||||
private int imagesReused;
|
||||
|
||||
public void count(String type, int n) {
|
||||
created.merge(type, n, Integer::sum);
|
||||
}
|
||||
|
||||
public void imageUploaded() { imagesUploaded++; }
|
||||
|
||||
public void imageReused() { imagesReused++; }
|
||||
|
||||
public ImportResult build() {
|
||||
return new ImportResult(created, imagesUploaded, imagesReused);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,616 @@
|
||||
package com.loremind.infrastructure.transfer;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Prerequisite;
|
||||
import com.loremind.domain.campaigncontext.SceneBranch;
|
||||
import com.loremind.domain.images.ports.ImageStorage;
|
||||
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||
import com.loremind.infrastructure.persistence.entity.*;
|
||||
import com.loremind.infrastructure.persistence.jpa.*;
|
||||
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/**
|
||||
* Service d'IMPORT de contenu en mode FUSION.
|
||||
* <p>
|
||||
* On NE remplace PAS l'existant : chaque entite importee est reinseree avec un
|
||||
* NOUVEL id auto-genere, et toutes les references (FK Long et refs faibles
|
||||
* String) sont remappees oldId -> newId. Cela permet d'agreger plusieurs exports
|
||||
* dans une meme base sans collision, entre Postgres et H2.
|
||||
* <p>
|
||||
* Algorithme :
|
||||
* <ol>
|
||||
* <li>Parse le zip : {@code data.json} -> {@link ContentExport}, binaires gardes en memoire.</li>
|
||||
* <li>Reecrit les images sous LEUR CLE D'ORIGINE (pas de remapping de cle) ;
|
||||
* skip si une ImageJpaEntity avec cette cle existe deja.</li>
|
||||
* <li>Insere top-down en construisant les maps de remapping par type.</li>
|
||||
* <li>2e passe : remappe les references qui pointent vers des types inserees
|
||||
* plus tard (parentId, defaultNodeId, refs faibles String) puis re-save.</li>
|
||||
* </ol>
|
||||
* Les references vers un id absent des maps (ex. relatedPageId hors export) sont
|
||||
* CONSERVEES telles quelles (choix : ne pas perdre d'info, ne jamais planter).
|
||||
*/
|
||||
@Service
|
||||
public class ImportService {
|
||||
|
||||
// (Dé)sérialise les prérequis dans le format "kind" du converter JPA (Prerequisite
|
||||
// est scellé, non sérialisable en polymorphe par l'ObjectMapper standard).
|
||||
private static final PrerequisiteListJsonConverter PREREQ_CONVERTER = new PrerequisiteListJsonConverter();
|
||||
|
||||
private final GameSystemJpaRepository gameSystemRepo;
|
||||
private final LoreJpaRepository loreRepo;
|
||||
private final LoreNodeJpaRepository loreNodeRepo;
|
||||
private final TemplateJpaRepository templateRepo;
|
||||
private final PageJpaRepository pageRepo;
|
||||
private final CampaignJpaRepository campaignRepo;
|
||||
private final ArcJpaRepository arcRepo;
|
||||
private final ChapterJpaRepository chapterRepo;
|
||||
private final SceneJpaRepository sceneRepo;
|
||||
private final CharacterJpaRepository characterRepo;
|
||||
private final NpcJpaRepository npcRepo;
|
||||
private final EnemyJpaRepository enemyRepo;
|
||||
private final ItemCatalogJpaRepository itemCatalogRepo;
|
||||
private final RandomTableJpaRepository randomTableRepo;
|
||||
private final ImageJpaRepository imageRepo;
|
||||
private final ImageStorage imageStorage;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public ImportService(GameSystemJpaRepository gameSystemRepo,
|
||||
LoreJpaRepository loreRepo,
|
||||
LoreNodeJpaRepository loreNodeRepo,
|
||||
TemplateJpaRepository templateRepo,
|
||||
PageJpaRepository pageRepo,
|
||||
CampaignJpaRepository campaignRepo,
|
||||
ArcJpaRepository arcRepo,
|
||||
ChapterJpaRepository chapterRepo,
|
||||
SceneJpaRepository sceneRepo,
|
||||
CharacterJpaRepository characterRepo,
|
||||
NpcJpaRepository npcRepo,
|
||||
EnemyJpaRepository enemyRepo,
|
||||
ItemCatalogJpaRepository itemCatalogRepo,
|
||||
RandomTableJpaRepository randomTableRepo,
|
||||
ImageJpaRepository imageRepo,
|
||||
ImageStorage imageStorage,
|
||||
ObjectMapper objectMapper) {
|
||||
this.gameSystemRepo = gameSystemRepo;
|
||||
this.loreRepo = loreRepo;
|
||||
this.loreNodeRepo = loreNodeRepo;
|
||||
this.templateRepo = templateRepo;
|
||||
this.pageRepo = pageRepo;
|
||||
this.campaignRepo = campaignRepo;
|
||||
this.arcRepo = arcRepo;
|
||||
this.chapterRepo = chapterRepo;
|
||||
this.sceneRepo = sceneRepo;
|
||||
this.characterRepo = characterRepo;
|
||||
this.npcRepo = npcRepo;
|
||||
this.enemyRepo = enemyRepo;
|
||||
this.itemCatalogRepo = itemCatalogRepo;
|
||||
this.randomTableRepo = randomTableRepo;
|
||||
this.imageRepo = imageRepo;
|
||||
this.imageStorage = imageStorage;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ImportResult importZip(InputStream zipStream) {
|
||||
// 1. Parse du zip.
|
||||
ContentExport export = null;
|
||||
Map<String, byte[]> imageBinaries = new LinkedHashMap<>(); // storageKey -> binaire
|
||||
try (ZipInputStream zip = new ZipInputStream(zipStream)) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zip.getNextEntry()) != null) {
|
||||
String name = entry.getName();
|
||||
if ("data.json".equals(name)) {
|
||||
export = objectMapper.readValue(readAll(zip), ContentExport.class);
|
||||
} else if (name.startsWith("images/") && !entry.isDirectory()) {
|
||||
// La cle de stockage est le chemin sans le prefixe "images/" du zip,
|
||||
// c'est-a-dire EXACTEMENT le storageKey d'origine ("images/UUID.ext").
|
||||
String storageKey = name.substring("images/".length());
|
||||
imageBinaries.put(storageKey, readAll(zip));
|
||||
}
|
||||
// manifest.json : ignore a l'import (info seulement).
|
||||
zip.closeEntry();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Echec de lecture du zip d'import", e);
|
||||
}
|
||||
if (export == null) {
|
||||
throw new IllegalArgumentException("Archive invalide : data.json introuvable");
|
||||
}
|
||||
|
||||
ImportResult.Builder result = new ImportResult.Builder();
|
||||
|
||||
// 2. Reecriture des images (cle preservee).
|
||||
importImages(export, imageBinaries, result);
|
||||
|
||||
// 3. Insertion top-down + maps de remapping.
|
||||
Map<Long, Long> gameSystemMap = new HashMap<>();
|
||||
Map<Long, Long> loreMap = new HashMap<>();
|
||||
Map<Long, Long> loreNodeMap = new HashMap<>();
|
||||
Map<Long, Long> templateMap = new HashMap<>();
|
||||
Map<Long, Long> pageMap = new HashMap<>();
|
||||
Map<Long, Long> campaignMap = new HashMap<>();
|
||||
Map<Long, Long> arcMap = new HashMap<>();
|
||||
Map<Long, Long> chapterMap = new HashMap<>();
|
||||
Map<Long, Long> npcMap = new HashMap<>();
|
||||
Map<Long, Long> enemyMap = new HashMap<>();
|
||||
Map<Long, Long> characterMap = new HashMap<>();
|
||||
Map<Long, Long> sceneMap = new HashMap<>();
|
||||
|
||||
// -- GameSystem
|
||||
for (ContentExport.GameSystemDto d : nullSafe(export.gameSystems())) {
|
||||
GameSystemJpaEntity e = new GameSystemJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setRulesMarkdown(d.rulesMarkdown());
|
||||
e.setCharacterTemplate(d.characterTemplate());
|
||||
e.setNpcTemplate(d.npcTemplate());
|
||||
e.setEnemyTemplate(d.enemyTemplate());
|
||||
e.setAuthor(d.author());
|
||||
e.setPublic(d.isPublic());
|
||||
gameSystemMap.put(d.id(), gameSystemRepo.save(e).getId());
|
||||
}
|
||||
result.count("gameSystems", gameSystemMap.size());
|
||||
|
||||
// -- Lore
|
||||
for (ContentExport.LoreDto d : nullSafe(export.lores())) {
|
||||
LoreJpaEntity e = new LoreJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setNodeCount(d.nodeCount());
|
||||
e.setPageCount(d.pageCount());
|
||||
loreMap.put(d.id(), loreRepo.save(e).getId());
|
||||
}
|
||||
result.count("lores", loreMap.size());
|
||||
|
||||
// -- LoreNode (parentId remappe en 2e passe)
|
||||
List<LoreNodeJpaEntity> loreNodesToFix = new ArrayList<>();
|
||||
for (ContentExport.LoreNodeDto d : nullSafe(export.loreNodes())) {
|
||||
LoreNodeJpaEntity e = new LoreNodeJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setIcon(d.icon());
|
||||
e.setParentId(d.parentId()); // remappe plus bas
|
||||
e.setLoreId(remapRequired(loreMap, d.loreId()));
|
||||
LoreNodeJpaEntity saved = loreNodeRepo.save(e);
|
||||
loreNodeMap.put(d.id(), saved.getId());
|
||||
if (d.parentId() != null) loreNodesToFix.add(saved);
|
||||
}
|
||||
result.count("loreNodes", loreNodeMap.size());
|
||||
|
||||
// -- Template (defaultNodeId remappe en 2e passe)
|
||||
List<ContentExport.TemplateDto> templatesWithDefaultNode = new ArrayList<>();
|
||||
for (ContentExport.TemplateDto d : nullSafe(export.templates())) {
|
||||
TemplateJpaEntity e = new TemplateJpaEntity();
|
||||
e.setLoreId(remapRequired(loreMap, d.loreId()));
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setDefaultNodeId(d.defaultNodeId()); // remappe plus bas
|
||||
e.setFields(d.fields());
|
||||
templateMap.put(d.id(), templateRepo.save(e).getId());
|
||||
if (d.defaultNodeId() != null) templatesWithDefaultNode.add(d);
|
||||
}
|
||||
result.count("templates", templateMap.size());
|
||||
|
||||
// -- Page (relatedPageIds remappe en 2e passe)
|
||||
for (ContentExport.PageDto d : nullSafe(export.pages())) {
|
||||
PageJpaEntity e = new PageJpaEntity();
|
||||
e.setLoreId(remapRequired(loreMap, d.loreId()));
|
||||
e.setNodeId(remapRequired(loreNodeMap, d.nodeId()));
|
||||
e.setTemplateId(remapNullable(templateMap, d.templateId()));
|
||||
e.setTitle(d.title());
|
||||
e.setValues(d.values());
|
||||
e.setImageValues(d.imageValues());
|
||||
e.setKeyValueValues(d.keyValueValues());
|
||||
e.setTableValues(d.tableValues());
|
||||
e.setNotes(d.notes());
|
||||
e.setTags(d.tags());
|
||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||
pageMap.put(d.id(), pageRepo.save(e).getId());
|
||||
}
|
||||
result.count("pages", pageMap.size());
|
||||
|
||||
// -- Campaign (loreId/gameSystemId String remappes en 2e passe)
|
||||
for (ContentExport.CampaignDto d : nullSafe(export.campaigns())) {
|
||||
CampaignJpaEntity e = new CampaignJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setArcsCount(d.arcsCount());
|
||||
e.setLoreId(d.loreId()); // remappe plus bas
|
||||
e.setGameSystemId(d.gameSystemId()); // remappe plus bas
|
||||
campaignMap.put(d.id(), campaignRepo.save(e).getId());
|
||||
}
|
||||
result.count("campaigns", campaignMap.size());
|
||||
|
||||
// -- Arc (relatedPageIds remappe en 2e passe)
|
||||
for (ContentExport.ArcDto d : nullSafe(export.arcs())) {
|
||||
ArcJpaEntity e = new ArcJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||
e.setOrder(d.order());
|
||||
e.setType(parseArcType(d.type()));
|
||||
e.setIcon(d.icon());
|
||||
e.setThemes(d.themes());
|
||||
e.setStakes(d.stakes());
|
||||
e.setGmNotes(d.gmNotes());
|
||||
e.setRewards(d.rewards());
|
||||
e.setResolution(d.resolution());
|
||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||
e.setIllustrationImageIds(d.illustrationImageIds());
|
||||
e.setMapImageIds(d.mapImageIds());
|
||||
arcMap.put(d.id(), arcRepo.save(e).getId());
|
||||
}
|
||||
result.count("arcs", arcMap.size());
|
||||
|
||||
// -- ItemCatalog (+ items en cascade)
|
||||
int catalogCount = 0, itemCount = 0;
|
||||
for (ContentExport.ItemCatalogDto d : nullSafe(export.itemCatalogs())) {
|
||||
ItemCatalogJpaEntity e = new ItemCatalogJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setIcon(d.icon());
|
||||
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||
e.setOrder(d.order());
|
||||
List<CatalogItemJpaEntity> items = new ArrayList<>();
|
||||
for (ContentExport.CatalogItemDto i : nullSafe(d.items())) {
|
||||
CatalogItemJpaEntity item = new CatalogItemJpaEntity();
|
||||
item.setName(i.name());
|
||||
item.setPrice(i.price());
|
||||
item.setCategory(i.category());
|
||||
item.setDescription(i.description());
|
||||
item.setPosition(i.position());
|
||||
item.setCatalog(e); // lien parent requis pour la cascade
|
||||
items.add(item);
|
||||
itemCount++;
|
||||
}
|
||||
e.setItems(items);
|
||||
itemCatalogRepo.save(e);
|
||||
catalogCount++;
|
||||
}
|
||||
result.count("itemCatalogs", catalogCount);
|
||||
result.count("catalogItems", itemCount);
|
||||
|
||||
// -- RandomTable (+ entries en cascade)
|
||||
int tableCount = 0, entryCount = 0;
|
||||
for (ContentExport.RandomTableDto d : nullSafe(export.randomTables())) {
|
||||
RandomTableJpaEntity e = new RandomTableJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setDiceFormula(d.diceFormula());
|
||||
e.setIcon(d.icon());
|
||||
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||
e.setOrder(d.order());
|
||||
List<RandomTableEntryJpaEntity> entries = new ArrayList<>();
|
||||
for (ContentExport.RandomTableEntryDto en : nullSafe(d.entries())) {
|
||||
RandomTableEntryJpaEntity entryE = new RandomTableEntryJpaEntity();
|
||||
entryE.setMinRoll(en.minRoll());
|
||||
entryE.setMaxRoll(en.maxRoll());
|
||||
entryE.setLabel(en.label());
|
||||
entryE.setDetail(en.detail());
|
||||
entryE.setPosition(en.position());
|
||||
entryE.setRandomTable(e);
|
||||
entries.add(entryE);
|
||||
entryCount++;
|
||||
}
|
||||
e.setEntries(entries);
|
||||
randomTableRepo.save(e);
|
||||
tableCount++;
|
||||
}
|
||||
result.count("randomTables", tableCount);
|
||||
result.count("randomTableEntries", entryCount);
|
||||
|
||||
// -- Chapter (prerequisites + relatedPageIds remappes en 2e passe)
|
||||
for (ContentExport.ChapterDto d : nullSafe(export.chapters())) {
|
||||
ChapterJpaEntity e = new ChapterJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setArcId(remapRequired(arcMap, d.arcId()));
|
||||
e.setOrder(d.order());
|
||||
e.setPrerequisites(PREREQ_CONVERTER.convertToEntityAttribute(d.prerequisitesJson())); // remappe plus bas
|
||||
e.setIcon(d.icon());
|
||||
e.setGmNotes(d.gmNotes());
|
||||
e.setPlayerObjectives(d.playerObjectives());
|
||||
e.setNarrativeStakes(d.narrativeStakes());
|
||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||
e.setIllustrationImageIds(d.illustrationImageIds());
|
||||
e.setMapImageIds(d.mapImageIds());
|
||||
chapterMap.put(d.id(), chapterRepo.save(e).getId());
|
||||
}
|
||||
result.count("chapters", chapterMap.size());
|
||||
|
||||
// -- Npc (relatedPageIds remappe en 2e passe)
|
||||
for (ContentExport.NpcDto d : nullSafe(export.npcs())) {
|
||||
NpcJpaEntity e = new NpcJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setPortraitImageId(d.portraitImageId());
|
||||
e.setHeaderImageId(d.headerImageId());
|
||||
e.setValues(d.values());
|
||||
e.setImageValues(d.imageValues());
|
||||
e.setKeyValueValues(d.keyValueValues());
|
||||
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||
e.setFolder(d.folder());
|
||||
e.setOrder(d.order());
|
||||
npcMap.put(d.id(), npcRepo.save(e).getId());
|
||||
}
|
||||
result.count("npcs", npcMap.size());
|
||||
|
||||
// -- Enemy
|
||||
for (ContentExport.EnemyDto d : nullSafe(export.enemies())) {
|
||||
EnemyJpaEntity e = new EnemyJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setLevel(d.level());
|
||||
e.setFolder(d.folder());
|
||||
e.setPortraitImageId(d.portraitImageId());
|
||||
e.setHeaderImageId(d.headerImageId());
|
||||
e.setValues(d.values());
|
||||
e.setImageValues(d.imageValues());
|
||||
e.setKeyValueValues(d.keyValueValues());
|
||||
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||
e.setOrder(d.order());
|
||||
enemyMap.put(d.id(), enemyRepo.save(e).getId());
|
||||
}
|
||||
result.count("enemies", enemyMap.size());
|
||||
|
||||
// -- Character (playthroughId mis a null : hors perimetre)
|
||||
for (ContentExport.CharacterDto d : nullSafe(export.characters())) {
|
||||
CharacterJpaEntity e = new CharacterJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setPortraitImageId(d.portraitImageId());
|
||||
e.setHeaderImageId(d.headerImageId());
|
||||
e.setValues(d.values());
|
||||
e.setImageValues(d.imageValues());
|
||||
e.setKeyValueValues(d.keyValueValues());
|
||||
e.setCampaignId(remapNullable(campaignMap, d.campaignId()));
|
||||
e.setPlaythroughId(null); // Playthrough hors perimetre d'export
|
||||
e.setOrder(d.order());
|
||||
characterMap.put(d.id(), characterRepo.save(e).getId());
|
||||
}
|
||||
result.count("characters", characterMap.size());
|
||||
|
||||
// -- Scene (enemyIds + relatedPageIds + branches remappes en 2e passe)
|
||||
for (ContentExport.SceneDto d : nullSafe(export.scenes())) {
|
||||
SceneJpaEntity e = new SceneJpaEntity();
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setChapterId(remapRequired(chapterMap, d.chapterId()));
|
||||
e.setOrder(d.order());
|
||||
e.setIcon(d.icon());
|
||||
e.setLocation(d.location());
|
||||
e.setTiming(d.timing());
|
||||
e.setAtmosphere(d.atmosphere());
|
||||
e.setPlayerNarration(d.playerNarration());
|
||||
e.setGmSecretNotes(d.gmSecretNotes());
|
||||
e.setChoicesConsequences(d.choicesConsequences());
|
||||
e.setCombatDifficulty(d.combatDifficulty());
|
||||
e.setEnemies(d.enemies());
|
||||
e.setEnemyIds(d.enemyIds()); // remappe plus bas
|
||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||
e.setIllustrationImageIds(d.illustrationImageIds());
|
||||
e.setMapImageIds(d.mapImageIds());
|
||||
e.setBranches(d.branches()); // remappe plus bas
|
||||
e.setRooms(d.rooms()); // Rooms: UUID, non remappes
|
||||
sceneMap.put(d.id(), sceneRepo.save(e).getId());
|
||||
}
|
||||
result.count("scenes", sceneMap.size());
|
||||
|
||||
// 4. 2e PASSE de remapping.
|
||||
|
||||
// LoreNode.parentId
|
||||
for (LoreNodeJpaEntity e : loreNodesToFix) {
|
||||
Long newParent = loreNodeMap.get(e.getParentId());
|
||||
if (newParent != null) {
|
||||
e.setParentId(newParent);
|
||||
loreNodeRepo.save(e);
|
||||
}
|
||||
}
|
||||
|
||||
// Template.defaultNodeId
|
||||
for (ContentExport.TemplateDto d : templatesWithDefaultNode) {
|
||||
Long newTemplateId = templateMap.get(d.id());
|
||||
Long newNode = loreNodeMap.get(d.defaultNodeId());
|
||||
if (newTemplateId != null && newNode != null) {
|
||||
templateRepo.findById(newTemplateId).ifPresent(t -> {
|
||||
t.setDefaultNodeId(newNode);
|
||||
templateRepo.save(t);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Campaign.loreId & gameSystemId (refs faibles String -> remap via maps Long).
|
||||
for (Long newCampaignId : campaignMap.values()) {
|
||||
campaignRepo.findById(newCampaignId).ifPresent(c -> {
|
||||
String newLore = remapStringId(loreMap, c.getLoreId());
|
||||
String newGs = remapStringId(gameSystemMap, c.getGameSystemId());
|
||||
c.setLoreId(newLore);
|
||||
c.setGameSystemId(newGs);
|
||||
campaignRepo.save(c);
|
||||
});
|
||||
}
|
||||
|
||||
// Page.relatedPageIds
|
||||
for (Long newPageId : pageMap.values()) {
|
||||
pageRepo.findById(newPageId).ifPresent(p -> {
|
||||
p.setRelatedPageIds(remapStringList(pageMap, p.getRelatedPageIds()));
|
||||
pageRepo.save(p);
|
||||
});
|
||||
}
|
||||
|
||||
// Arc.relatedPageIds
|
||||
for (Long newArcId : arcMap.values()) {
|
||||
arcRepo.findById(newArcId).ifPresent(a -> {
|
||||
a.setRelatedPageIds(remapStringList(pageMap, a.getRelatedPageIds()));
|
||||
arcRepo.save(a);
|
||||
});
|
||||
}
|
||||
|
||||
// Chapter.relatedPageIds + prerequisites(QuestCompleted -> map Chapter)
|
||||
for (Long newChapterId : chapterMap.values()) {
|
||||
chapterRepo.findById(newChapterId).ifPresent(c -> {
|
||||
c.setRelatedPageIds(remapStringList(pageMap, c.getRelatedPageIds()));
|
||||
c.setPrerequisites(remapPrerequisites(chapterMap, c.getPrerequisites()));
|
||||
chapterRepo.save(c);
|
||||
});
|
||||
}
|
||||
|
||||
// Npc.relatedPageIds
|
||||
for (Long newNpcId : npcMap.values()) {
|
||||
npcRepo.findById(newNpcId).ifPresent(n -> {
|
||||
n.setRelatedPageIds(remapStringList(pageMap, n.getRelatedPageIds()));
|
||||
npcRepo.save(n);
|
||||
});
|
||||
}
|
||||
|
||||
// Scene.relatedPageIds + enemyIds(map Enemy) + branches.targetSceneId(map Scene)
|
||||
for (Long newSceneId : sceneMap.values()) {
|
||||
sceneRepo.findById(newSceneId).ifPresent(s -> {
|
||||
s.setRelatedPageIds(remapStringList(pageMap, s.getRelatedPageIds()));
|
||||
s.setEnemyIds(remapStringList(enemyMap, s.getEnemyIds()));
|
||||
s.setBranches(remapBranches(sceneMap, s.getBranches()));
|
||||
sceneRepo.save(s);
|
||||
});
|
||||
}
|
||||
|
||||
return result.build();
|
||||
}
|
||||
|
||||
// ----- Images -----
|
||||
|
||||
private void importImages(ContentExport export,
|
||||
Map<String, byte[]> imageBinaries,
|
||||
ImportResult.Builder result) {
|
||||
// Index des metadonnees d'image par cle (depuis le data.json).
|
||||
Map<String, ContentExport.ImageDto> metaByKey = new HashMap<>();
|
||||
for (ContentExport.ImageDto img : nullSafe(export.images())) {
|
||||
if (img.storageKey() != null) metaByKey.put(img.storageKey(), img);
|
||||
}
|
||||
|
||||
for (Map.Entry<String, byte[]> bin : imageBinaries.entrySet()) {
|
||||
String storageKey = bin.getKey();
|
||||
byte[] data = bin.getValue();
|
||||
if (imageRepo.findByStorageKey(storageKey).isPresent()) {
|
||||
// Image deja presente : on reutilise, pas de reupload (eviter doublon).
|
||||
result.imageReused();
|
||||
continue;
|
||||
}
|
||||
ContentExport.ImageDto meta = metaByKey.get(storageKey);
|
||||
String contentType = meta != null && meta.contentType() != null
|
||||
? meta.contentType() : guessContentType(storageKey);
|
||||
long size = meta != null ? meta.sizeBytes() : data.length;
|
||||
|
||||
imageStorage.store(storageKey, contentType, new ByteArrayInputStream(data), data.length);
|
||||
|
||||
ImageJpaEntity e = new ImageJpaEntity();
|
||||
e.setFilename(meta != null && meta.filename() != null
|
||||
? meta.filename() : fileNameOf(storageKey));
|
||||
e.setContentType(contentType);
|
||||
e.setSizeBytes(size);
|
||||
e.setStorageKey(storageKey);
|
||||
imageRepo.save(e);
|
||||
result.imageUploaded();
|
||||
}
|
||||
}
|
||||
|
||||
// ----- Helpers de remapping -----
|
||||
|
||||
/** Remap obligatoire d'une FK Long : si absente de la map, on garde l'ancienne valeur. */
|
||||
private Long remapRequired(Map<Long, Long> map, Long oldId) {
|
||||
if (oldId == null) return null;
|
||||
return map.getOrDefault(oldId, oldId);
|
||||
}
|
||||
|
||||
/** Remap d'une FK Long nullable : null reste null. */
|
||||
private Long remapNullable(Map<Long, Long> map, Long oldId) {
|
||||
if (oldId == null) return null;
|
||||
return map.getOrDefault(oldId, oldId);
|
||||
}
|
||||
|
||||
/** Remap d'un id stocke en String ("oldLong" -> "newLong") via une map Long. */
|
||||
private String remapStringId(Map<Long, Long> map, String oldId) {
|
||||
if (oldId == null || oldId.isBlank()) return oldId;
|
||||
try {
|
||||
Long newId = map.get(Long.parseLong(oldId.trim()));
|
||||
return newId != null ? String.valueOf(newId) : oldId;
|
||||
} catch (NumberFormatException ex) {
|
||||
return oldId; // pas un Long : on laisse tel quel
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> remapStringList(Map<Long, Long> map, List<String> ids) {
|
||||
if (ids == null) return null;
|
||||
List<String> out = new ArrayList<>(ids.size());
|
||||
for (String id : ids) out.add(remapStringId(map, id));
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<Prerequisite> remapPrerequisites(Map<Long, Long> chapterMap, List<Prerequisite> prereqs) {
|
||||
if (prereqs == null) return null;
|
||||
List<Prerequisite> out = new ArrayList<>(prereqs.size());
|
||||
for (Prerequisite p : prereqs) {
|
||||
if (p instanceof Prerequisite.QuestCompleted qc) {
|
||||
out.add(new Prerequisite.QuestCompleted(remapStringId(chapterMap, qc.questId())));
|
||||
} else {
|
||||
out.add(p); // FlagSet / SessionReached : inchanges
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<SceneBranch> remapBranches(Map<Long, Long> sceneMap, List<SceneBranch> branches) {
|
||||
if (branches == null) return null;
|
||||
List<SceneBranch> out = new ArrayList<>(branches.size());
|
||||
for (SceneBranch b : branches) {
|
||||
out.add(new SceneBranch(b.label(), remapStringId(sceneMap, b.targetSceneId()), b.condition()));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private com.loremind.domain.campaigncontext.ArcType parseArcType(String type) {
|
||||
if (type == null) return com.loremind.domain.campaigncontext.ArcType.LINEAR;
|
||||
try {
|
||||
return com.loremind.domain.campaigncontext.ArcType.valueOf(type);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return com.loremind.domain.campaigncontext.ArcType.LINEAR;
|
||||
}
|
||||
}
|
||||
|
||||
// ----- Helpers divers -----
|
||||
|
||||
private static <T> List<T> nullSafe(List<T> list) {
|
||||
return list != null ? list : List.of();
|
||||
}
|
||||
|
||||
private static byte[] readAll(InputStream in) throws IOException {
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
in.transferTo(buffer);
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
private static String fileNameOf(String storageKey) {
|
||||
int slash = storageKey.lastIndexOf('/');
|
||||
return slash >= 0 ? storageKey.substring(slash + 1) : storageKey;
|
||||
}
|
||||
|
||||
private static String guessContentType(String storageKey) {
|
||||
String lower = storageKey.toLowerCase();
|
||||
if (lower.endsWith(".png")) return "image/png";
|
||||
if (lower.endsWith(".gif")) return "image/gif";
|
||||
if (lower.endsWith(".webp")) return "image/webp";
|
||||
if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
|
||||
return "application/octet-stream";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.loremind.infrastructure.transfer.dto;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Room;
|
||||
import com.loremind.domain.campaigncontext.SceneBranch;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Format d'export LOGIQUE (JSON) du "contenu" de LoreMind.
|
||||
* <p>
|
||||
* Records plats, miroirs des champs des entites JPA — volontairement DECOUPLES
|
||||
* des entites pour la stabilite inter-versions (le schema JPA peut bouger sans
|
||||
* casser un .zip exporte). Chaque record porte son {@code id} d'origine (Long)
|
||||
* afin que l'import puisse construire les maps de remapping oldId -> newId.
|
||||
* <p>
|
||||
* Les sous-objets riches (TemplateField, Prerequisite, SceneBranch, Room)
|
||||
* reutilisent les types domaine existants : Jackson sait les (de)serialiser
|
||||
* (records ou Lombok), et on evite de dupliquer la structure.
|
||||
*/
|
||||
public record ContentExport(
|
||||
Manifest manifest,
|
||||
List<GameSystemDto> gameSystems,
|
||||
List<LoreDto> lores,
|
||||
List<LoreNodeDto> loreNodes,
|
||||
List<TemplateDto> templates,
|
||||
List<PageDto> pages,
|
||||
List<CampaignDto> campaigns,
|
||||
List<ArcDto> arcs,
|
||||
List<ChapterDto> chapters,
|
||||
List<SceneDto> scenes,
|
||||
List<CharacterDto> characters,
|
||||
List<NpcDto> npcs,
|
||||
List<EnemyDto> enemies,
|
||||
List<ItemCatalogDto> itemCatalogs,
|
||||
List<RandomTableDto> randomTables,
|
||||
List<ImageDto> images
|
||||
) {
|
||||
|
||||
/**
|
||||
* Metadonnees de l'export. {@code exportedAt} est passe en parametre depuis
|
||||
* la couche requete (PAS Instant.now() ici, pour rester deterministe et
|
||||
* testable).
|
||||
*/
|
||||
public record Manifest(
|
||||
int formatVersion,
|
||||
String appVersion,
|
||||
String exportedAt
|
||||
) {}
|
||||
|
||||
public record GameSystemDto(
|
||||
Long id,
|
||||
String name,
|
||||
String description,
|
||||
String rulesMarkdown,
|
||||
List<TemplateField> characterTemplate,
|
||||
List<TemplateField> npcTemplate,
|
||||
List<TemplateField> enemyTemplate,
|
||||
String author,
|
||||
boolean isPublic
|
||||
) {}
|
||||
|
||||
public record LoreDto(
|
||||
Long id,
|
||||
String name,
|
||||
String description,
|
||||
int nodeCount,
|
||||
int pageCount
|
||||
) {}
|
||||
|
||||
public record LoreNodeDto(
|
||||
Long id,
|
||||
String name,
|
||||
String icon,
|
||||
Long parentId,
|
||||
Long loreId
|
||||
) {}
|
||||
|
||||
public record TemplateDto(
|
||||
Long id,
|
||||
Long loreId,
|
||||
String name,
|
||||
String description,
|
||||
Long defaultNodeId,
|
||||
List<TemplateField> fields
|
||||
) {}
|
||||
|
||||
public record PageDto(
|
||||
Long id,
|
||||
Long loreId,
|
||||
Long nodeId,
|
||||
Long templateId,
|
||||
String title,
|
||||
Map<String, String> values,
|
||||
Map<String, List<String>> imageValues,
|
||||
Map<String, Map<String, String>> keyValueValues,
|
||||
Map<String, List<Map<String, String>>> tableValues,
|
||||
String notes,
|
||||
List<String> tags,
|
||||
List<String> relatedPageIds
|
||||
) {}
|
||||
|
||||
public record CampaignDto(
|
||||
Long id,
|
||||
String name,
|
||||
String description,
|
||||
int arcsCount,
|
||||
String loreId,
|
||||
String gameSystemId
|
||||
) {}
|
||||
|
||||
public record ArcDto(
|
||||
Long id,
|
||||
String name,
|
||||
String description,
|
||||
Long campaignId,
|
||||
int order,
|
||||
String type,
|
||||
String icon,
|
||||
String themes,
|
||||
String stakes,
|
||||
String gmNotes,
|
||||
String rewards,
|
||||
String resolution,
|
||||
List<String> relatedPageIds,
|
||||
List<String> illustrationImageIds,
|
||||
List<String> mapImageIds
|
||||
) {}
|
||||
|
||||
public record ChapterDto(
|
||||
Long id,
|
||||
String name,
|
||||
String description,
|
||||
Long arcId,
|
||||
int order,
|
||||
// Prerequisites en JSON brut (format "kind" du converter JPA) : Prerequisite
|
||||
// est un type scellé SANS annotations Jackson, donc impossible à (dé)sérialiser
|
||||
// en polymorphe via l'ObjectMapper standard. On réutilise
|
||||
// PrerequisiteListJsonConverter (format on-disk stable, identique à la base).
|
||||
String prerequisitesJson,
|
||||
String icon,
|
||||
String gmNotes,
|
||||
String playerObjectives,
|
||||
String narrativeStakes,
|
||||
List<String> relatedPageIds,
|
||||
List<String> illustrationImageIds,
|
||||
List<String> mapImageIds
|
||||
) {}
|
||||
|
||||
public record SceneDto(
|
||||
Long id,
|
||||
String name,
|
||||
String description,
|
||||
Long chapterId,
|
||||
int order,
|
||||
String icon,
|
||||
String location,
|
||||
String timing,
|
||||
String atmosphere,
|
||||
String playerNarration,
|
||||
String gmSecretNotes,
|
||||
String choicesConsequences,
|
||||
String combatDifficulty,
|
||||
String enemies,
|
||||
List<String> enemyIds,
|
||||
List<String> relatedPageIds,
|
||||
List<String> illustrationImageIds,
|
||||
List<String> mapImageIds,
|
||||
List<SceneBranch> branches,
|
||||
List<Room> rooms
|
||||
) {}
|
||||
|
||||
public record CharacterDto(
|
||||
Long id,
|
||||
String name,
|
||||
String portraitImageId,
|
||||
String headerImageId,
|
||||
Map<String, String> values,
|
||||
Map<String, List<String>> imageValues,
|
||||
Map<String, Map<String, String>> keyValueValues,
|
||||
Long campaignId,
|
||||
Long playthroughId,
|
||||
int order
|
||||
) {}
|
||||
|
||||
public record NpcDto(
|
||||
Long id,
|
||||
String name,
|
||||
String portraitImageId,
|
||||
String headerImageId,
|
||||
Map<String, String> values,
|
||||
Map<String, List<String>> imageValues,
|
||||
Map<String, Map<String, String>> keyValueValues,
|
||||
Long campaignId,
|
||||
List<String> relatedPageIds,
|
||||
String folder,
|
||||
int order
|
||||
) {}
|
||||
|
||||
public record EnemyDto(
|
||||
Long id,
|
||||
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,
|
||||
Long campaignId,
|
||||
int order
|
||||
) {}
|
||||
|
||||
public record ItemCatalogDto(
|
||||
Long id,
|
||||
String name,
|
||||
String description,
|
||||
String icon,
|
||||
Long campaignId,
|
||||
int order,
|
||||
List<CatalogItemDto> items
|
||||
) {}
|
||||
|
||||
public record CatalogItemDto(
|
||||
Long id,
|
||||
String name,
|
||||
String price,
|
||||
String category,
|
||||
String description,
|
||||
int position
|
||||
) {}
|
||||
|
||||
public record RandomTableDto(
|
||||
Long id,
|
||||
String name,
|
||||
String description,
|
||||
String diceFormula,
|
||||
String icon,
|
||||
Long campaignId,
|
||||
int order,
|
||||
List<RandomTableEntryDto> entries
|
||||
) {}
|
||||
|
||||
public record RandomTableEntryDto(
|
||||
Long id,
|
||||
int minRoll,
|
||||
int maxRoll,
|
||||
String label,
|
||||
String detail,
|
||||
int position
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Metadonnees d'une image. Le binaire voyage a part dans le zip sous
|
||||
* {@code images/<storageKey>}. La cle est PRESERVEE telle quelle a l'import.
|
||||
*/
|
||||
public record ImageDto(
|
||||
Long id,
|
||||
String filename,
|
||||
String contentType,
|
||||
long sizeBytes,
|
||||
String storageKey
|
||||
) {}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.context.request.async.AsyncRequestNotUsableException;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
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
|
||||
* la connexion (onglet ferme, proxy coupe...), la reponse n'est plus utilisable.
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.resource.PathResourceResolver;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Service du front Angular en statique par le Core, en mode local-first.
|
||||
* <p>
|
||||
* En deploiement Docker, le front est servi par un conteneur nginx dedie
|
||||
* (service {@code web}) et le Core reste une API pure. En mode local
|
||||
* (application de bureau empaquetee), il n'y a pas de nginx : le build Angular
|
||||
* est copie dans {@code classpath:/static/} (cf. profil Maven de packaging) et
|
||||
* le Core le sert lui-meme sur la meme origine que l'API.
|
||||
* <p>
|
||||
* Active uniquement sous le profil {@code local} pour ne RIEN changer au
|
||||
* comportement du conteneur Core en production.
|
||||
* <p>
|
||||
* Fallback SPA : toute route qui ne correspond pas a un fichier statique reel
|
||||
* (et qui n'est pas une route d'API) renvoie {@code index.html}, afin que le
|
||||
* routing cote Angular (deep links, rechargement de page) fonctionne.
|
||||
*/
|
||||
@Configuration
|
||||
@Profile("local")
|
||||
public class LocalWebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
// Fichiers de traduction (assets/i18n/*.json) : nom STABLE (non hashe),
|
||||
// donc jamais mis en cache, sinon le navigateur ressert un JSON perime
|
||||
// (voire un 304 sur un corps en cache obsolete) apres une mise a jour.
|
||||
// Symptome observe : les libelles restent en cles brutes pour une langue.
|
||||
// Motif plus specifique que "/**" => prioritaire pour ces chemins.
|
||||
registry.addResourceHandler("/assets/i18n/**")
|
||||
.addResourceLocations("classpath:/static/assets/i18n/")
|
||||
.setCacheControl(CacheControl.noStore());
|
||||
|
||||
registry.addResourceHandler("/**")
|
||||
.addResourceLocations("classpath:/static/")
|
||||
.resourceChain(true)
|
||||
.addResolver(new PathResourceResolver() {
|
||||
@Override
|
||||
protected Resource getResource(String resourcePath, Resource location) throws IOException {
|
||||
Resource requested = location.createRelative(resourcePath);
|
||||
if (requested.exists() && requested.isReadable()) {
|
||||
return requested;
|
||||
}
|
||||
// Ne JAMAIS rabattre les routes techniques sur index.html :
|
||||
// une API inexistante doit rester un 404, pas du HTML.
|
||||
if (resourcePath.startsWith("api/") || resourcePath.startsWith("actuator/")) {
|
||||
return null;
|
||||
}
|
||||
// Un ASSET manquant (chemin avec extension : .json, .js, .css,
|
||||
// .png...) doit renvoyer 404 — surtout PAS index.html. Sinon un
|
||||
// loader JSON (ex. ngx-translate chargeant assets/i18n/fr.json)
|
||||
// recevrait du HTML en 200 et echouerait au parse, donnant des
|
||||
// cles brutes a l'ecran. On ne rabat sur la coquille SPA que les
|
||||
// vraies routes applicatives (sans extension de fichier).
|
||||
if (hasFileExtension(resourcePath)) {
|
||||
return null;
|
||||
}
|
||||
// Route applicative Angular -> on sert la coquille SPA.
|
||||
Resource index = new ClassPathResource("/static/index.html");
|
||||
return index.exists() ? index : null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si le dernier segment du chemin contient un point (donc une extension
|
||||
* de fichier : {@code assets/i18n/fr.json}, {@code main.js}...). Les routes
|
||||
* applicatives Angular ({@code settings}, {@code campaigns/42}) n'en ont pas.
|
||||
*/
|
||||
private static boolean hasFileExtension(String resourcePath) {
|
||||
int lastSlash = resourcePath.lastIndexOf('/');
|
||||
String lastSegment = resourcePath.substring(lastSlash + 1);
|
||||
return lastSegment.contains(".");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Capture la langue de l'utilisateur (entête {@code X-User-Language} envoyé par le
|
||||
* frontend) dans {@link UserLanguageHolder} pour la durée de la requête, puis la
|
||||
* nettoie systématiquement.
|
||||
* <p>
|
||||
* Les clients du Brain liront ce ThreadLocal au moment de construire leur appel
|
||||
* (sur ce même thread servlet) pour relayer la langue au Brain. Indispensable de
|
||||
* {@code clear()} en {@code finally} : les threads servlet sont recyclés dans un
|
||||
* pool, une valeur oubliée fuiterait sur la requête suivante.
|
||||
*/
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class UserLanguageFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
try {
|
||||
UserLanguageHolder.set(request.getHeader(UserLanguageHolder.HEADER));
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
UserLanguageHolder.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Langue de l'utilisateur courant, portée par un ThreadLocal le temps d'une
|
||||
* requête HTTP entrante.
|
||||
* <p>
|
||||
* Le frontend Angular envoie son choix de langue (code court {@code fr}/{@code en})
|
||||
* via l'entête {@code X-User-Language}. {@link UserLanguageFilter} la capture ici,
|
||||
* et les clients du Brain ({@code RestTemplateConfig} pour les appels bloquants,
|
||||
* les clients WebClient pour le streaming) la relaient au Brain — qui rédige alors
|
||||
* ses réponses IA dans cette langue.
|
||||
* <p>
|
||||
* Repli systématique sur le français si rien n'est fourni (vieux client, appel interne).
|
||||
*/
|
||||
public final class UserLanguageHolder {
|
||||
|
||||
/** Nom de l'entête HTTP relayant la langue, du frontend jusqu'au Brain. */
|
||||
public static final String HEADER = "X-User-Language";
|
||||
|
||||
/** Langue par défaut quand l'entête est absent ou non reconnu. */
|
||||
public static final String DEFAULT = "fr";
|
||||
|
||||
/** Langues supportées (alignées sur LanguageService Angular et NAMES côté Brain). */
|
||||
private static final Set<String> SUPPORTED = Set.of("fr", "en");
|
||||
|
||||
private static final ThreadLocal<String> CURRENT = ThreadLocal.withInitial(() -> DEFAULT);
|
||||
|
||||
private UserLanguageHolder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise un code/entête langue arbitraire vers un code supporté.
|
||||
* Tolère la casse, les variantes régionales ({@code en-US}) et un
|
||||
* {@code Accept-Language} complet ({@code fr-FR,fr;q=0.9}). Repli {@code DEFAULT}.
|
||||
*/
|
||||
public static String normalize(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return DEFAULT;
|
||||
}
|
||||
String primary = raw.split(",")[0].split(";")[0].trim().toLowerCase();
|
||||
String base = primary.split("-")[0];
|
||||
return SUPPORTED.contains(base) ? base : DEFAULT;
|
||||
}
|
||||
|
||||
public static void set(String language) {
|
||||
CURRENT.set(normalize(language));
|
||||
}
|
||||
|
||||
public static String get() {
|
||||
return CURRENT.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
CURRENT.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.infrastructure.transfer.ExportService;
|
||||
import com.loremind.infrastructure.transfer.ImportResult;
|
||||
import com.loremind.infrastructure.transfer.ImportService;
|
||||
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Endpoints d'EXPORT / IMPORT du "contenu" (admin).
|
||||
* <p>
|
||||
* - {@code GET /api/admin/data/export} : telecharge un .zip portable.<br>
|
||||
* - {@code POST /api/admin/data/import} : importe un .zip en mode FUSION.
|
||||
* <p>
|
||||
* Garde le mode demo coherent avec {@code SettingsController} : ces operations
|
||||
* sont desactivees en demo (donnees partagees, pas d'ecriture massive).
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/data")
|
||||
public class DataTransferController {
|
||||
|
||||
private final ExportService exportService;
|
||||
private final ImportService importService;
|
||||
private final boolean demoMode;
|
||||
|
||||
public DataTransferController(ExportService exportService,
|
||||
ImportService importService,
|
||||
@Value("${app.demo-mode:false}") boolean demoMode) {
|
||||
this.exportService = exportService;
|
||||
this.importService = importService;
|
||||
this.demoMode = demoMode;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/export", produces = "application/zip")
|
||||
public ResponseEntity<StreamingResponseBody> export() {
|
||||
guardDemoMode();
|
||||
// Stamp de l'horodatage cote requete (PAS dans un init statique).
|
||||
String exportedAt = Instant.now().toString();
|
||||
ContentExport content = exportService.buildExport(exportedAt);
|
||||
|
||||
StreamingResponseBody body = out -> exportService.writeZip(content, out);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"loremind-export.zip\"")
|
||||
.contentType(MediaType.parseMediaType("application/zip"))
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ResponseEntity<ImportResult> importData(@RequestParam("file") MultipartFile file) {
|
||||
guardDemoMode();
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Fichier d'import vide");
|
||||
}
|
||||
try {
|
||||
ImportResult result = importService.importZip(file.getInputStream());
|
||||
return ResponseEntity.ok(result);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Echec de lecture du fichier d'import", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void guardDemoMode() {
|
||||
if (demoMode) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Data transfer disabled in demo mode");
|
||||
}
|
||||
}
|
||||
}
|
||||
103
core/src/main/resources/application-local.properties
Normal file
103
core/src/main/resources/application-local.properties
Normal file
@@ -0,0 +1,103 @@
|
||||
# ============================================================================
|
||||
# Profil "local" — mode local-first (application de bureau, sans Docker)
|
||||
# ============================================================================
|
||||
# Active via : --spring.profiles.active=local (ou SPRING_PROFILES_ACTIVE=local)
|
||||
#
|
||||
# Objectif : faire tourner le Core sur le poste de l'utilisateur SANS aucune
|
||||
# infrastructure externe (ni Postgres, ni MinIO, ni Docker). Toutes les donnees
|
||||
# vivent sous loremind.home (defaut : ~/.loremind).
|
||||
#
|
||||
# Surcharge UNIQUEMENT ce qui differe du profil par defaut (application.properties) :
|
||||
# le reste (timeouts, multipart, licensing...) est herite tel quel.
|
||||
|
||||
# --- Config utilisateur editable (port + identifiants admin) ----------------
|
||||
# Charge ~/.loremind/loremind.properties s'il existe (cree au 1er lancement par
|
||||
# DesktopUserConfig). "optional:" = pas d'erreur s'il manque. Les valeurs y
|
||||
# definies (server.port, admin.username, admin.password) SURCHARGENT les defauts
|
||||
# ci-dessous (un import a une priorite superieure au fichier qui l'importe).
|
||||
# NB : le port effectif est de toute facon fixe par DesktopUserConfig au demarrage
|
||||
# (propriete systeme server.port, avec repli si le port est occupe).
|
||||
spring.config.import=optional:file:${user.home}/.loremind/loremind.properties
|
||||
|
||||
# --- Serveur : ecoute UNIQUEMENT sur la boucle locale -----------------------
|
||||
# App de bureau mono-utilisateur : jamais exposee au reseau (securite). Et ca
|
||||
# rend coherent le test "port libre" de DesktopUserConfig (qui teste 127.0.0.1)
|
||||
# avec l'adresse de bind reelle de Tomcat -> le repli sur port libre fonctionne
|
||||
# meme si une autre appli occupe le port sur une autre interface.
|
||||
server.address=127.0.0.1
|
||||
|
||||
# --- Base de donnees : H2 en mode fichier, compatibilite PostgreSQL ---------
|
||||
# MODE=PostgreSQL : H2 interprete le SQL PostgreSQL -> les MEMES migrations
|
||||
# Flyway (ecrites en SQL Postgres) tournent ici comme sur la prod Postgres.
|
||||
# Aligne aussi la casse des identifiants (minuscules, comme PG).
|
||||
# DB_CLOSE_ON_EXIT=FALSE : Spring/Hikari pilote la fermeture (pas le shutdown
|
||||
# hook H2). AUTO_SERVER volontairement absent (interdit avec DB_CLOSE_ON_EXIT,
|
||||
# et inutile pour un process unique).
|
||||
# NON_KEYWORDS=VALUE : PostgreSQL accepte `value` comme nom de colonne non-quote
|
||||
# (colonne de playthrough_flag), mais H2 le reserve par defaut -> on le relache
|
||||
# pour que le baseline SQL Postgres (non-quote) passe aussi sur H2. Ajouter
|
||||
# d'autres mots ici si une migration future utilise un identifiant reserve H2.
|
||||
spring.datasource.url=jdbc:h2:file:${loremind.home}/db/loremind;MODE=PostgreSQL;DB_CLOSE_ON_EXIT=FALSE;NON_KEYWORDS=VALUE
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
# Schema gere par Flyway (cf. application.properties) ; Hibernate valide seulement.
|
||||
spring.jpa.hibernate.ddl-auto=validate
|
||||
spring.jpa.show-sql=false
|
||||
|
||||
# --- Stockage des images : systeme de fichiers -----------------------------
|
||||
storage.backend=filesystem
|
||||
storage.filesystem.path=${loremind.home}/images
|
||||
|
||||
# --- Brain : service IA Python lance en sidecar sur le poste ---------------
|
||||
brain.base-url=http://localhost:8000
|
||||
# Secret partage Core <-> Brain. En local il n'a pas de role securitaire fort
|
||||
# (tout est sur localhost, mono-utilisateur) mais le Brain est fail-closed :
|
||||
# il DOIT etre defini des deux cotes. Le lanceur de sidecar (BrainSidecar)
|
||||
# propage cette meme valeur au process Brain via la variable BRAIN_INTERNAL_SECRET.
|
||||
brain.internal-secret=${BRAIN_INTERNAL_SECRET:loremind-local-secret}
|
||||
|
||||
# --- Brain en sidecar (lance par le Core) ----------------------------------
|
||||
# Le Core demarre lui-meme le process Brain (pas de Docker en local).
|
||||
brain.sidecar.enabled=${BRAIN_SIDECAR_ENABLED:true}
|
||||
# Le Brain ecrit son dossier data/ (index vectoriel, settings) sous ce dossier.
|
||||
brain.sidecar.working-dir=${loremind.home}/brain
|
||||
# Commande de lancement. VIDE par defaut : le dev qui lance le Brain a la main
|
||||
# n'est pas perturbe. Le packaging (jpackage) la renseigne vers l'exe PyInstaller.
|
||||
# - Empaquete : chemin de l'exe, ex. C:/Program Files/LoreMind/brain/loremind-brain.exe
|
||||
# - Dev : python,-m,uvicorn,app.main:app,--host,127.0.0.1,--port,8000
|
||||
# (avec brain.sidecar.working-dir pointant sur le dossier brain/)
|
||||
brain.sidecar.command=${BRAIN_SIDECAR_COMMAND:}
|
||||
|
||||
# --- Admin (localhost uniquement) ------------------------------------------
|
||||
# Application mono-utilisateur sur le poste : l'utilisateur EST l'admin.
|
||||
# Defauts admin/admin, SURCHARGEABLES par l'utilisateur dans
|
||||
# ~/.loremind/loremind.properties (cf. spring.config.import ci-dessus).
|
||||
admin.username=${ADMIN_USERNAME:admin}
|
||||
admin.password=${ADMIN_PASSWORD:admin}
|
||||
|
||||
# --- Front servi par le Core (meme origine) --------------------------------
|
||||
# Le front Angular est servi en statique par le Core (cf. LocalWebConfig),
|
||||
# donc tout est sur http://localhost:8080 : CORS sans objet, mais on autorise
|
||||
# l'origine locale par securite si un dev lance Angular separement.
|
||||
spring.web.cors.allowed-origins=http://localhost:8080,http://localhost:4200
|
||||
|
||||
# Mode demo desactive (instance personnelle complete).
|
||||
app.demo-mode=false
|
||||
|
||||
# --- Licensing / Patreon : desactive en mode bureau ------------------------
|
||||
# Le gating par IMAGE Docker (canal beta tire d'un registry prive) n'a aucun
|
||||
# sens hors Docker. On coupe toute la machinerie : daemon de refresh no-op,
|
||||
# /api/license/* renvoie enabled=false, et l'UI masque la section Patreon.
|
||||
# La distribution beta desktop se fait par installeur beta via Patreon, pas
|
||||
# par une connexion in-app.
|
||||
licensing.enabled=false
|
||||
|
||||
# --- Verification des mises a jour (bureau) --------------------------------
|
||||
# Interroge l'API GitHub Releases (derniere release STABLE) au demarrage ; si
|
||||
# une version plus recente existe, l'icone systray le signale (bulle + item
|
||||
# « Telecharger »). Pas de mise a jour auto : l'utilisateur telecharge et lance
|
||||
# le nouvel installeur. Mettre a false pour desactiver toute requete sortante.
|
||||
desktop.update.enabled=${DESKTOP_UPDATE_CHECK:true}
|
||||
desktop.update.releases-api-url=https://api.github.com/repos/IGMLcreation/LoreMind/releases/latest
|
||||
@@ -22,10 +22,26 @@ spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
|
||||
# Configuration JPA / Hibernate
|
||||
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
# Le schema est desormais gere par Flyway (migrations versionnees), plus par
|
||||
# Hibernate. ddl-auto=validate : Hibernate ne MODIFIE plus le schema, il verifie
|
||||
# juste au demarrage que les entites correspondent au schema cree par Flyway
|
||||
# (filet de securite contre les derives entites<->migrations).
|
||||
spring.jpa.hibernate.ddl-auto=validate
|
||||
spring.jpa.show-sql=true
|
||||
spring.jpa.properties.hibernate.format_sql=true
|
||||
|
||||
# ============================================================================
|
||||
# Flyway : migrations de schema versionnees (src/main/resources/db/migration).
|
||||
# ============================================================================
|
||||
# baseline-on-migrate : sur une base EXISTANTE (prod deja peuplee, sans table
|
||||
# d'historique Flyway), Flyway l'estampille a la version baseline SANS rejouer
|
||||
# V1 -> les donnees existantes sont preservees. Sur une base VIDE (install
|
||||
# neuve), Flyway joue V1__baseline.sql normalement pour creer le schema.
|
||||
spring.flyway.enabled=true
|
||||
spring.flyway.baseline-on-migrate=true
|
||||
spring.flyway.baseline-version=1
|
||||
spring.flyway.baseline-description=Baseline (schema pre-Flyway, gere jusque-la par ddl-auto)
|
||||
|
||||
# Configuration CORS pour autoriser le Frontend Angular
|
||||
spring.web.cors.allowed-origins=${CORS_ALLOWED_ORIGINS:http://localhost:4200}
|
||||
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
|
||||
@@ -48,6 +64,17 @@ brain.internal-secret=${BRAIN_INTERNAL_SECRET:}
|
||||
admin.username=${ADMIN_USERNAME:admin}
|
||||
admin.password=${ADMIN_PASSWORD:}
|
||||
|
||||
# Repertoire de base de l'instance (donnees locales hors Docker).
|
||||
# Utilise par le profil "local" (H2 fichier, stockage images filesystem...).
|
||||
loremind.home=${LOREMIND_HOME:${user.home}/.loremind}
|
||||
|
||||
# Backend de stockage des binaires d'images (port ImageStorage) :
|
||||
# - minio : MinIO/S3 (defaut — deploiement Docker/serveur)
|
||||
# - filesystem : systeme de fichiers local (mode local-first / jpackage)
|
||||
storage.backend=${STORAGE_BACKEND:minio}
|
||||
# Racine du stockage filesystem (ignoree si storage.backend=minio).
|
||||
storage.filesystem.path=${STORAGE_FS_PATH:${loremind.home}/images}
|
||||
|
||||
# Configuration MinIO (Shared Kernel images - Object Storage)
|
||||
# Le bucket est cree automatiquement par le service minio-init (docker-compose up -d).
|
||||
# Defaults OK pour dev local ; overrides en prod via env.
|
||||
|
||||
424
core/src/main/resources/db/migration/V1__baseline.sql
Normal file
424
core/src/main/resources/db/migration/V1__baseline.sql
Normal file
@@ -0,0 +1,424 @@
|
||||
|
||||
create table arcs (
|
||||
"order" integer not null,
|
||||
campaign_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
type varchar(16) default 'LINEAR' not null check (type in ('LINEAR','HUB')),
|
||||
description TEXT,
|
||||
gm_notes TEXT,
|
||||
icon varchar(255),
|
||||
illustration_image_ids TEXT,
|
||||
map_image_ids TEXT,
|
||||
name varchar(255) not null,
|
||||
related_page_ids TEXT,
|
||||
resolution TEXT,
|
||||
rewards TEXT,
|
||||
stakes TEXT,
|
||||
themes TEXT,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table campaigns (
|
||||
arcs_count integer not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
description TEXT,
|
||||
game_system_id varchar(255),
|
||||
lore_id varchar(255),
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table catalog_items (
|
||||
position integer not null,
|
||||
catalog_id bigint not null,
|
||||
id bigint generated by default as identity,
|
||||
price varchar(64),
|
||||
category varchar(128),
|
||||
description TEXT,
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table chapters (
|
||||
"order" integer not null,
|
||||
arc_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
description TEXT,
|
||||
gm_notes TEXT,
|
||||
icon varchar(255),
|
||||
illustration_image_ids TEXT,
|
||||
map_image_ids TEXT,
|
||||
name varchar(255) not null,
|
||||
narrative_stakes TEXT,
|
||||
player_objectives TEXT,
|
||||
prerequisites TEXT,
|
||||
related_page_ids TEXT,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table characters (
|
||||
"order" integer not null,
|
||||
campaign_id bigint,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
playthrough_id bigint,
|
||||
updated_at timestamp(6) not null,
|
||||
field_values TEXT,
|
||||
header_image_id varchar(255),
|
||||
image_values TEXT,
|
||||
key_value_values TEXT,
|
||||
name varchar(255) not null,
|
||||
portrait_image_id varchar(255),
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table conversation_messages (
|
||||
conversation_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
role varchar(16) not null,
|
||||
content TEXT not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table conversations (
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
campaign_id varchar(255),
|
||||
entity_id varchar(255),
|
||||
entity_type varchar(255),
|
||||
lore_id varchar(255),
|
||||
title varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table enemies (
|
||||
"order" integer not null,
|
||||
campaign_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
field_values TEXT,
|
||||
folder varchar(255),
|
||||
header_image_id varchar(255),
|
||||
image_values TEXT,
|
||||
key_value_values TEXT,
|
||||
level varchar(255),
|
||||
name varchar(255) not null,
|
||||
portrait_image_id varchar(255),
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table game_systems (
|
||||
is_public boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
author varchar(255),
|
||||
character_template TEXT,
|
||||
description TEXT,
|
||||
enemy_template TEXT,
|
||||
name varchar(255) not null,
|
||||
npc_template TEXT,
|
||||
rules_markdown TEXT,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table images (
|
||||
id bigint generated by default as identity,
|
||||
size_bytes bigint not null,
|
||||
uploaded_at timestamp(6) not null,
|
||||
content_type varchar(255) not null,
|
||||
filename varchar(255) not null,
|
||||
storage_key varchar(255) not null unique,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table item_catalogs (
|
||||
"order" integer not null,
|
||||
campaign_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
icon varchar(64),
|
||||
description TEXT,
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table licenses (
|
||||
beta_channel_enabled boolean not null,
|
||||
last_refresh_succeeded boolean not null,
|
||||
created_at timestamp(6) with time zone not null,
|
||||
expires_at timestamp(6) with time zone not null,
|
||||
issued_at timestamp(6) with time zone not null,
|
||||
last_refresh_attempt_at timestamp(6) with time zone,
|
||||
updated_at timestamp(6) with time zone not null,
|
||||
id varchar(255) not null,
|
||||
instance_id varchar(255) not null,
|
||||
patreon_user_id varchar(255) not null,
|
||||
raw_jwt TEXT not null,
|
||||
tier_id varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table lore_nodes (
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
lore_id bigint not null,
|
||||
parent_id bigint,
|
||||
updated_at timestamp(6) not null,
|
||||
icon varchar(64),
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table lores (
|
||||
node_count integer not null,
|
||||
page_count integer not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
description TEXT,
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table notebook_messages (
|
||||
archived_at timestamp(6),
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
notebook_id bigint not null,
|
||||
role varchar(16) not null,
|
||||
content TEXT not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table notebook_sources (
|
||||
chunk_count integer not null,
|
||||
page_count integer not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
notebook_id bigint not null,
|
||||
status varchar(16) not null,
|
||||
filename varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table notebooks (
|
||||
campaign_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table npcs (
|
||||
"order" integer not null,
|
||||
campaign_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
field_values TEXT,
|
||||
folder varchar(255),
|
||||
header_image_id varchar(255),
|
||||
image_values TEXT,
|
||||
key_value_values TEXT,
|
||||
name varchar(255) not null,
|
||||
portrait_image_id varchar(255),
|
||||
related_page_ids TEXT,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table pages (
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
lore_id bigint not null,
|
||||
node_id bigint not null,
|
||||
template_id bigint,
|
||||
updated_at timestamp(6) not null,
|
||||
image_values_json TEXT,
|
||||
key_value_values TEXT,
|
||||
notes TEXT,
|
||||
related_page_ids TEXT,
|
||||
table_values TEXT,
|
||||
tags TEXT,
|
||||
title varchar(255) not null,
|
||||
values_json TEXT,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table playthrough_flag (
|
||||
value boolean not null,
|
||||
id bigint generated by default as identity,
|
||||
playthrough_id bigint not null,
|
||||
name varchar(128) not null,
|
||||
primary key (id),
|
||||
constraint uk_playthrough_flag_name unique (playthrough_id, name)
|
||||
);
|
||||
|
||||
create table playthroughs (
|
||||
campaign_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
description TEXT,
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table quest_progression (
|
||||
chapter_id bigint not null,
|
||||
id bigint generated by default as identity,
|
||||
playthrough_id bigint not null,
|
||||
status varchar(16) not null check (status in ('NOT_STARTED','IN_PROGRESS','COMPLETED')),
|
||||
primary key (id),
|
||||
constraint uk_quest_progression_unique unique (playthrough_id, chapter_id)
|
||||
);
|
||||
|
||||
create table random_table_entries (
|
||||
max_roll integer not null,
|
||||
min_roll integer not null,
|
||||
position integer not null,
|
||||
id bigint generated by default as identity,
|
||||
random_table_id bigint not null,
|
||||
detail TEXT,
|
||||
label varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table random_tables (
|
||||
"order" integer not null,
|
||||
campaign_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
dice_formula varchar(32) not null,
|
||||
icon varchar(64),
|
||||
description TEXT,
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table scenes (
|
||||
"order" integer not null,
|
||||
chapter_id bigint not null,
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
updated_at timestamp(6) not null,
|
||||
atmosphere TEXT,
|
||||
branches TEXT,
|
||||
choices_consequences TEXT,
|
||||
combat_difficulty TEXT,
|
||||
description TEXT,
|
||||
enemies TEXT,
|
||||
enemy_ids TEXT,
|
||||
gm_secret_notes TEXT,
|
||||
icon varchar(255),
|
||||
illustration_image_ids TEXT,
|
||||
location TEXT,
|
||||
map_image_ids TEXT,
|
||||
name varchar(255) not null,
|
||||
player_narration TEXT,
|
||||
related_page_ids TEXT,
|
||||
rooms TEXT,
|
||||
timing TEXT,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table session_entries (
|
||||
created_at timestamp(6) not null,
|
||||
id bigint generated by default as identity,
|
||||
occurred_at timestamp(6) not null,
|
||||
updated_at timestamp(6) not null,
|
||||
type varchar(32) not null check (type in ('NOTE','EVENT','DICE_ROLL','PLAYER_ACTION')),
|
||||
content TEXT not null,
|
||||
session_id varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table sessions (
|
||||
created_at timestamp(6) not null,
|
||||
ended_at timestamp(6),
|
||||
id bigint generated by default as identity,
|
||||
playthrough_id bigint,
|
||||
started_at timestamp(6) not null,
|
||||
updated_at timestamp(6) not null,
|
||||
campaign_id varchar(255),
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table templates (
|
||||
created_at timestamp(6) not null,
|
||||
default_node_id bigint,
|
||||
id bigint generated by default as identity,
|
||||
lore_id bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
description TEXT,
|
||||
fields TEXT,
|
||||
name varchar(255) not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create index idx_catalog_items_catalog_id
|
||||
on catalog_items (catalog_id);
|
||||
|
||||
create index idx_conv_lore_entity
|
||||
on conversations (lore_id, entity_type, entity_id, updated_at);
|
||||
|
||||
create index idx_conv_campaign_entity
|
||||
on conversations (campaign_id, entity_type, entity_id, updated_at);
|
||||
|
||||
create index idx_enemies_campaign_id
|
||||
on enemies (campaign_id);
|
||||
|
||||
create index idx_item_catalogs_campaign_id
|
||||
on item_catalogs (campaign_id);
|
||||
|
||||
create index idx_notebook_messages_notebook_id
|
||||
on notebook_messages (notebook_id);
|
||||
|
||||
create index idx_notebook_sources_notebook_id
|
||||
on notebook_sources (notebook_id);
|
||||
|
||||
create index idx_notebooks_campaign_id
|
||||
on notebooks (campaign_id);
|
||||
|
||||
create index ix_playthrough_flag_playthrough
|
||||
on playthrough_flag (playthrough_id);
|
||||
|
||||
create index ix_playthrough_campaign
|
||||
on playthroughs (campaign_id);
|
||||
|
||||
create index ix_quest_progression_playthrough
|
||||
on quest_progression (playthrough_id);
|
||||
|
||||
create index idx_random_table_entries_table_id
|
||||
on random_table_entries (random_table_id);
|
||||
|
||||
create index idx_session_entries_session_id
|
||||
on session_entries (session_id);
|
||||
|
||||
alter table if exists catalog_items
|
||||
add constraint FK7tuoq6mwuc00yv0hhpiw4aoni
|
||||
foreign key (catalog_id)
|
||||
references item_catalogs;
|
||||
|
||||
alter table if exists conversation_messages
|
||||
add constraint FKcr8qqgnqnaqq2hw3gr4wtfe2a
|
||||
foreign key (conversation_id)
|
||||
references conversations;
|
||||
|
||||
alter table if exists random_table_entries
|
||||
add constraint FKly4syvpfit2kibfjut67xxrrq
|
||||
foreign key (random_table_id)
|
||||
references random_tables;
|
||||
@@ -11,6 +11,7 @@ import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||
@@ -48,6 +49,8 @@ public class CampaignStructuralContextBuilderTest {
|
||||
private CharacterRepository characterRepository;
|
||||
@Mock
|
||||
private NpcRepository npcRepository;
|
||||
@Mock
|
||||
private EnemyRepository enemyRepository;
|
||||
|
||||
@InjectMocks
|
||||
private CampaignStructuralContextBuilder builder;
|
||||
|
||||
@@ -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.ChatMessage;
|
||||
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.PageSummary;
|
||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||
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 java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -284,4 +293,252 @@ class BrainChatPayloadBuilderTest {
|
||||
assertFalse(payload.containsKey("lore_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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.application.generationcontext.StreamChatForCampaignUseCase;
|
||||
import com.loremind.application.generationcontext.StreamChatForLoreUseCase;
|
||||
import com.loremind.application.generationcontext.StreamChatForSessionUseCase;
|
||||
import com.loremind.domain.generationcontext.ChatMessage;
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatMessageDTO;
|
||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamCampaignRequestDTO;
|
||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamRequestDTO;
|
||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamSessionRequestDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link AiChatController} (chat IA streame en SSE).
|
||||
* <p>
|
||||
* Les trois use cases ({@link StreamChatForLoreUseCase},
|
||||
* {@link StreamChatForCampaignUseCase}, {@link StreamChatForSessionUseCase}) sont
|
||||
* mockes : sinon chaque test ferait un vrai appel au Brain (indisponible en test).
|
||||
* <p>
|
||||
* Le {@code TaskExecutor} ("applicationTaskExecutor") est mocke pour executer la
|
||||
* tache de streaming EN LIGNE (synchrone) : tous les events SSE sont ecrits avant
|
||||
* le retour du controleur, ce qui rend les assertions sur le flux deterministes.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class AiChatControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
|
||||
@MockBean private StreamChatForLoreUseCase loreUseCase;
|
||||
@MockBean private StreamChatForCampaignUseCase campaignUseCase;
|
||||
@MockBean private StreamChatForSessionUseCase sessionUseCase;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Tache de streaming executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private MvcResult perform(String url, Object body) throws Exception {
|
||||
return mockMvc.perform(post(url)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(body)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
// --- /chat/stream (Lore) ------------------------------------------------
|
||||
|
||||
@Test
|
||||
void chatStream_streamsUsageTokenDone() throws Exception {
|
||||
// Le use case mocke joue : usage -> 1 token -> fin.
|
||||
doAnswer(inv -> {
|
||||
Consumer<ChatUsage> onUsage = inv.getArgument(3);
|
||||
Consumer<String> onToken = inv.getArgument(4);
|
||||
Runnable onComplete = inv.getArgument(5);
|
||||
onUsage.accept(new ChatUsage(10, 20, 30, 8000));
|
||||
onToken.accept("Bonjour");
|
||||
onComplete.run();
|
||||
return null;
|
||||
}).when(loreUseCase).execute(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamRequestDTO body = new ChatStreamRequestDTO();
|
||||
body.setLoreId("lore-1");
|
||||
body.setMessages(List.of(new ChatMessageDTO("user", "Salut ?")));
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream", body);
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("\"system\":10")))
|
||||
.andExpect(content().string(containsString("\"max\":8000")))
|
||||
.andExpect(content().string(containsString("Bonjour")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_passesDomainMessagesToUseCase() throws Exception {
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(5)).run(); return null; })
|
||||
.when(loreUseCase).execute(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamRequestDTO body = new ChatStreamRequestDTO();
|
||||
body.setLoreId("lore-1");
|
||||
body.setPageId("page-9");
|
||||
body.setMessages(List.of(
|
||||
new ChatMessageDTO("user", "Q1"),
|
||||
new ChatMessageDTO("assistant", "R1")));
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream", body);
|
||||
mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
org.mockito.ArgumentCaptor<List<ChatMessage>> captor =
|
||||
org.mockito.ArgumentCaptor.forClass(List.class);
|
||||
verify(loreUseCase).execute(
|
||||
org.mockito.ArgumentMatchers.eq("lore-1"),
|
||||
org.mockito.ArgumentMatchers.eq("page-9"),
|
||||
captor.capture(), any(), any(), any(), any());
|
||||
List<ChatMessage> passed = captor.getValue();
|
||||
org.junit.jupiter.api.Assertions.assertEquals(2, passed.size());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("user", passed.get(0).role());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("Q1", passed.get(0).content());
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_useCaseInvokesError_emitsError() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException("brain HS"));
|
||||
return null;
|
||||
}).when(loreUseCase).execute(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamRequestDTO body = new ChatStreamRequestDTO();
|
||||
body.setLoreId("lore-1");
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("brain HS")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_useCaseThrows_emitsError() throws Exception {
|
||||
// Lore introuvable -> le use case leve, le controller catch et fail(emitter).
|
||||
doThrow(new IllegalArgumentException("Lore introuvable"))
|
||||
.when(loreUseCase).execute(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamRequestDTO body = new ChatStreamRequestDTO();
|
||||
body.setLoreId("missing");
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Lore introuvable")));
|
||||
}
|
||||
|
||||
// --- /chat/stream-campaign ----------------------------------------------
|
||||
|
||||
@Test
|
||||
void chatStreamCampaign_streamsTokenThenDone() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onToken = inv.getArgument(5);
|
||||
Runnable onComplete = inv.getArgument(6);
|
||||
onToken.accept("Campagne");
|
||||
onComplete.run();
|
||||
return null;
|
||||
}).when(campaignUseCase).execute(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamCampaignRequestDTO body = new ChatStreamCampaignRequestDTO();
|
||||
body.setCampaignId("camp-1");
|
||||
body.setEntityType("scene");
|
||||
body.setEntityId("scene-3");
|
||||
body.setMessages(List.of(new ChatMessageDTO("user", "Aide")));
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream-campaign", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Campagne")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStreamCampaign_useCaseThrows_emitsError() throws Exception {
|
||||
doThrow(new IllegalArgumentException("Campagne introuvable"))
|
||||
.when(campaignUseCase).execute(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamCampaignRequestDTO body = new ChatStreamCampaignRequestDTO();
|
||||
body.setCampaignId("missing");
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream-campaign", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Campagne introuvable")));
|
||||
}
|
||||
|
||||
// --- /chat/stream-session -----------------------------------------------
|
||||
|
||||
@Test
|
||||
void chatStreamSession_streamsTokenThenDone() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onToken = inv.getArgument(3);
|
||||
Runnable onComplete = inv.getArgument(4);
|
||||
onToken.accept("Session");
|
||||
onComplete.run();
|
||||
return null;
|
||||
}).when(sessionUseCase).execute(any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamSessionRequestDTO body = new ChatStreamSessionRequestDTO();
|
||||
body.setSessionId("sess-1");
|
||||
body.setMessages(List.of(new ChatMessageDTO("user", "Resume")));
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream-session", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Session")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStreamSession_useCaseThrows_emitsError() throws Exception {
|
||||
doThrow(new IllegalArgumentException("Session introuvable"))
|
||||
.when(sessionUseCase).execute(any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamSessionRequestDTO body = new ChatStreamSessionRequestDTO();
|
||||
body.setSessionId("missing");
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream-session", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Session introuvable")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.CampaignAdaptService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link CampaignAdaptController} (conseil PDF -> campagne, SSE).
|
||||
* <p>
|
||||
* Le {@link CampaignAdaptService} est mocke : il appelle le Brain (indisponible en
|
||||
* test). Le {@code TaskExecutor} ("applicationTaskExecutor") est mocke pour executer
|
||||
* la tache de streaming EN LIGNE -> events SSE deterministes.
|
||||
* <p>
|
||||
* Signature de {@code adviseStreaming(campaignId, pdfBytes, filename, messagesJson,
|
||||
* onToken, onComplete, onError)} : indices des callbacks -> onToken=4, onComplete=5,
|
||||
* onError=6.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class CampaignAdaptControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@MockBean private CampaignAdaptService campaignAdaptService;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Tache de streaming executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private MockMultipartFile pdf(byte[] content) {
|
||||
return new MockMultipartFile("file", "aventure.pdf", "application/pdf", content);
|
||||
}
|
||||
|
||||
private MvcResult perform(MockMultipartFile file) throws Exception {
|
||||
return mockMvc.perform(multipart("/api/campaigns/{id}/adapt-pdf/stream", "camp-1")
|
||||
.file(file)
|
||||
.param("messages", "[]"))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
void adaptStream_streamsTokenThenDone() throws Exception {
|
||||
// Le service mocke joue : 1 token -> fin.
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onToken = inv.getArgument(4);
|
||||
Runnable onComplete = inv.getArgument(5);
|
||||
onToken.accept("Conseil markdown");
|
||||
onComplete.run();
|
||||
return null;
|
||||
}).when(campaignAdaptService).adviseStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = perform(pdf("%PDF-1.4 fake".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Conseil markdown")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adaptStream_serviceInvokesError_emitsError() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException("brain HS"));
|
||||
return null;
|
||||
}).when(campaignAdaptService).adviseStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = perform(pdf("%PDF-1.4 fake".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("brain HS")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adaptStream_campaignMissing_emitsError() throws Exception {
|
||||
// Le service leve IllegalArgumentException -> le controller catch et envoie "Campagne introuvable.".
|
||||
doThrow(new IllegalArgumentException("Campagne introuvable : camp-1"))
|
||||
.when(campaignAdaptService).adviseStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = perform(pdf("%PDF-1.4 fake".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("Campagne introuvable")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adaptStream_emptyFile_emitsError_withoutCallingService() throws Exception {
|
||||
// Fichier vide : branche court-circuit, le service n'est jamais appele.
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/adapt-pdf/stream", "camp-1")
|
||||
.file(new MockMultipartFile("file", "vide.pdf", "application/pdf", new byte[0])))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("Fichier PDF vide")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Prerequisite;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration de {@link CampaignFlagController}.
|
||||
* Unique endpoint : list (GET) qui déduplique les noms de faits (Prerequisite.FlagSet)
|
||||
* référencés dans les prérequis des chapitres de la campagne.
|
||||
* Fixtures : campaign -> arc -> chapters avec prérequis FlagSet.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class CampaignFlagControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private ArcRepository arcRepository;
|
||||
@Autowired private ChapterRepository chapterRepository;
|
||||
|
||||
private String campaignId;
|
||||
private String arcId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Chaîne de fixtures : campaign -> arc
|
||||
campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
arcId = arcRepository.save(Arc.builder().campaignId(campaignId).name("A").order(0).build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsEmptyArray_whenNoFlagPrerequisites() throws Exception {
|
||||
// Chapitre sans prérequis FlagSet => aucun fait référencé
|
||||
chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch").order(0).build());
|
||||
mockMvc.perform(get("/api/campaigns/{cid}/flags", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$.length()").value(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsDeduplicatedSortedFlagNames() throws Exception {
|
||||
// Deux chapitres référençant des FlagSet, avec un doublon "alpha"
|
||||
chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch1").order(0)
|
||||
.prerequisites(List.of(
|
||||
new Prerequisite.FlagSet("zeta"),
|
||||
new Prerequisite.FlagSet("alpha")))
|
||||
.build());
|
||||
chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch2").order(1)
|
||||
.prerequisites(List.of(
|
||||
new Prerequisite.FlagSet("alpha"), // doublon
|
||||
new Prerequisite.QuestCompleted("q-1"))) // ignoré (pas un FlagSet)
|
||||
.build());
|
||||
|
||||
mockMvc.perform(get("/api/campaigns/{cid}/flags", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$.length()").value(2))
|
||||
// TreeSet => tri alphabétique : alpha avant zeta
|
||||
.andExpect(jsonPath("$[0]").value("alpha"))
|
||||
.andExpect(jsonPath("$[1]").value("zeta"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsEmptyArray_forUnknownCampaign() throws Exception {
|
||||
// Campagne sans arcs => liste vide (pas d'erreur)
|
||||
mockMvc.perform(get("/api/campaigns/{cid}/flags", "999999999"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$.length()").value(0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.application.campaigncontext.CampaignImportService;
|
||||
import com.loremind.application.campaigncontext.CampaignImportService.ApplyResult;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link CampaignImportController} (import PDF -> arbre).
|
||||
* <p>
|
||||
* Le {@link CampaignImportService} est mocke : son {@code importStructureStreaming}
|
||||
* delegue sinon au Brain Python (indisponible en test) et {@code applyStructure}
|
||||
* persiste en base. On controle ici les callbacks (progress / done / error) du
|
||||
* streaming et le mapping HTTP du apply.
|
||||
* <p>
|
||||
* Le {@code TaskExecutor} ("applicationTaskExecutor") est mocke pour executer la
|
||||
* tache d'import EN LIGNE (synchrone) : tous les events SSE sont ecrits avant le
|
||||
* retour du controleur, rendant les assertions sur le flux deterministes.
|
||||
* <p>
|
||||
* Indices des callbacks de
|
||||
* {@link CampaignImportService#importStructureStreaming} :
|
||||
* (0) pdfBytes, (1) filename, (2) onProgress, (3) onHeartbeat, (4) onStatus,
|
||||
* (5) onDone, (6) onError.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class CampaignImportControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
|
||||
@MockBean private CampaignImportService campaignImportService;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
private static final String CAMPAIGN_ID = "camp-1";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Tache d'import executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private MockMultipartFile pdf(byte[] bytes) {
|
||||
return new MockMultipartFile("file", "campagne.pdf", "application/pdf", bytes);
|
||||
}
|
||||
|
||||
// --- POST /stream (SSE) ------------------------------------------------
|
||||
|
||||
@Test
|
||||
void importStream_emptyFile_emitsError() throws Exception {
|
||||
MockMultipartFile empty = pdf(new byte[0]);
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID).file(empty))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("vide")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_happyPath_streamsDone() throws Exception {
|
||||
// Le service mocke joue : onDone avec une proposition vide.
|
||||
doAnswer(inv -> {
|
||||
Consumer<CampaignImportProposal> onDone = inv.getArgument(5);
|
||||
onDone.accept(new CampaignImportProposal(List.of(), List.of()));
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_serviceError_emitsError() throws Exception {
|
||||
// Le service mocke joue : onError avec un message.
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException("Brain injoignable"));
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("Brain injoignable")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_thrownException_emitsError() throws Exception {
|
||||
// Le service leve directement (catch general du controleur).
|
||||
doAnswer(inv -> { throw new RuntimeException("boom extraction"); })
|
||||
.when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("boom extraction")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_progressAndStatus_streamedBeforeDone() throws Exception {
|
||||
// Joue la sequence complete des callbacks intermediaires (progress / status /
|
||||
// heartbeat) puis onDone -> couvre sendEvent("progress"), sendEvent("status")
|
||||
// et sendHeartbeat (helpers SSE non touches par les tests precedents).
|
||||
doAnswer(inv -> {
|
||||
Consumer<CampaignImportProgress> onProgress = inv.getArgument(2);
|
||||
Runnable onHeartbeat = inv.getArgument(3);
|
||||
Consumer<String> onStatus = inv.getArgument(4);
|
||||
Consumer<CampaignImportProposal> onDone = inv.getArgument(5);
|
||||
onProgress.accept(new CampaignImportProgress(2, 10, 5, 1, 1, 2, 3, 4));
|
||||
onStatus.accept("Analyse en cours");
|
||||
onHeartbeat.run();
|
||||
onDone.accept(new CampaignImportProposal(List.of(), List.of()));
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("progress")))
|
||||
.andExpect(content().string(containsString("status")))
|
||||
.andExpect(content().string(containsString("Analyse en cours")))
|
||||
.andExpect(content().string(containsString("keepalive")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_nullStatus_emitsEmptyMessage() throws Exception {
|
||||
// onStatus(null) -> branche "status != null ? status : \"\"" du controleur.
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onStatus = inv.getArgument(4);
|
||||
Consumer<CampaignImportProposal> onDone = inv.getArgument(5);
|
||||
onStatus.accept(null);
|
||||
onDone.accept(new CampaignImportProposal(List.of(), List.of()));
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("status")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_nullErrorMessage_emitsFallbackMessage() throws Exception {
|
||||
// onError avec un message null -> sendError utilise "Erreur inconnue.".
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException()); // getMessage() == null
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Erreur inconnue")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_serviceThrows_emitsError() throws Exception {
|
||||
// Le service LEVE (au lieu d'invoquer onError) : le catch(Exception) du
|
||||
// controleur relaie le message via sendError.
|
||||
doThrow(new RuntimeException("panne interne"))
|
||||
.when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("panne interne")));
|
||||
}
|
||||
|
||||
// --- POST /apply -------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void apply_returns200_withSummary() throws Exception {
|
||||
when(campaignImportService.applyStructure(eq(CAMPAIGN_ID), any()))
|
||||
.thenReturn(new ApplyResult(1, 2, 3, 4));
|
||||
CampaignImportProposal proposal = new CampaignImportProposal(List.of(), List.of());
|
||||
|
||||
mockMvc.perform(post("/api/campaigns/{id}/import-structure/apply", CAMPAIGN_ID)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(proposal)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.arcsCreated").value(1))
|
||||
.andExpect(jsonPath("$.chaptersCreated").value(2))
|
||||
.andExpect(jsonPath("$.scenesCreated").value(3))
|
||||
.andExpect(jsonPath("$.npcsCreated").value(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
void apply_returns404_whenCampaignMissing() throws Exception {
|
||||
when(campaignImportService.applyStructure(any(), any()))
|
||||
.thenThrow(new IllegalArgumentException("Campagne introuvable"));
|
||||
CampaignImportProposal proposal = new CampaignImportProposal(List.of(), List.of());
|
||||
|
||||
mockMvc.perform(post("/api/campaigns/{id}/import-structure/apply", CAMPAIGN_ID)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(proposal)))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.application.campaigncontext.CampaignImportService;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Test UNITAIRE pur (sans Spring) de {@link CampaignImportController} dédié au code
|
||||
* défensif de déconnexion du navigateur, INTESTABLE via MockMvc : là-bas, un envoi
|
||||
* SSE après {@code complete()} met l'emitter dans l'état « already completed » qui
|
||||
* remonte en {@code ServletException} (échec de test) au lieu d'exécuter la branche.
|
||||
* <p>
|
||||
* En instanciant le controller à la main (exécuteur en ligne, vrai ObjectMapper,
|
||||
* service mocké), on pilote directement la séquence : envoi initial → {@code complete()}
|
||||
* → un envoi ultérieur échoue et bascule {@code clientGone=true} → les callbacks
|
||||
* suivants empruntent alors les branches {@code ClientGoneException} / early-return.
|
||||
*/
|
||||
class CampaignImportControllerUnitTest {
|
||||
|
||||
private final CampaignImportService service = mock(CampaignImportService.class);
|
||||
/** Exécuteur synchrone : la tâche d'import tourne dans le thread du test. */
|
||||
private final TaskExecutor inlineExecutor = Runnable::run;
|
||||
private final CampaignImportController controller =
|
||||
new CampaignImportController(service, inlineExecutor, new ObjectMapper());
|
||||
|
||||
private static CampaignImportProgress progress() {
|
||||
return new CampaignImportProgress(1, 1, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_clientDisconnect_exercisesDefensiveBranches() throws Exception {
|
||||
// Scénario de déconnexion : on termine le flux puis on continue d'émettre.
|
||||
// Le 1er envoi post-complete échoue -> clientGone=true ; les callbacks suivants
|
||||
// court-circuitent (ClientGoneException sur sendEvent/sendHeartbeat, early-return
|
||||
// sur le callback d'erreur). Chaque étape est isolée car ClientGoneException
|
||||
// (privée) se propage hors des callbacks — comme en prod où elle remonte au
|
||||
// pipeline amont pour stopper le Brain.
|
||||
doAnswer(inv -> {
|
||||
Consumer<CampaignImportProgress> onProgress = inv.getArgument(2);
|
||||
Runnable onHeartbeat = inv.getArgument(3);
|
||||
Consumer<CampaignImportProposal> onDone = inv.getArgument(5);
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
|
||||
// 1) Termine proprement le flux (event "done" + complete()).
|
||||
onDone.accept(new CampaignImportProposal(List.of(), List.of()));
|
||||
// 2) Envoi post-complete : send échoue -> catch -> clientGone=true.
|
||||
try { onProgress.accept(progress()); } catch (RuntimeException ignored) { }
|
||||
// 3) clientGone=true -> sendHeartbeat lève ClientGoneException (branche garde).
|
||||
try { onHeartbeat.run(); } catch (RuntimeException ignored) { }
|
||||
// 4) clientGone=true -> sendEvent lève ClientGoneException (branche garde).
|
||||
try { onProgress.accept(progress()); } catch (RuntimeException ignored) { }
|
||||
// 5) clientGone=true -> le callback d'erreur prend l'early-return (pas d'envoi).
|
||||
onError.accept(new RuntimeException("tardif"));
|
||||
return null;
|
||||
}).when(service).importStructureStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "campagne.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
SseEmitter emitter = controller.importStream("camp-1", file);
|
||||
|
||||
assertNotNull(emitter);
|
||||
verify(service).importStructureStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ChapterDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -34,13 +36,18 @@ class ChapterControllerTest {
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private ArcRepository arcRepository;
|
||||
@Autowired private ChapterRepository chapterRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
|
||||
private String arcId;
|
||||
private String playthroughId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
String campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
arcId = arcRepository.save(Arc.builder().campaignId(campaignId).name("A").order(0).build()).getId();
|
||||
// playthroughId REEL (id numerique) : l'enrichissement du statut le parse.
|
||||
playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campaignId).name("Table").description("").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -106,4 +113,52 @@ class ChapterControllerTest {
|
||||
mockMvc.perform(delete("/api/chapters/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// getById avec ?playthroughId= : branche d'enrichissement du statut.
|
||||
// Le playthrough est inexistant -> snapshot vide -> statut NOT_STARTED, mais la branche est couverte.
|
||||
@Test
|
||||
void getById_withPlaythroughId_enrichesStatus() throws Exception {
|
||||
Chapter saved = chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch").order(0).build());
|
||||
mockMvc.perform(get("/api/chapters/{id}", saved.getId()).param("playthroughId", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.progressionStatus").value("NOT_STARTED"));
|
||||
}
|
||||
|
||||
// getAll avec ?playthroughId= : branche d'enrichissement sur la liste.
|
||||
@Test
|
||||
void getAll_withPlaythroughId_enrichesStatus() throws Exception {
|
||||
chapterRepository.save(Chapter.builder().arcId(arcId).name("A").order(0).build());
|
||||
mockMvc.perform(get("/api/chapters").param("playthroughId", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].progressionStatus").value("NOT_STARTED"));
|
||||
}
|
||||
|
||||
// deletion-impact : chapitre existant -> 200 avec le compte de scènes (0 ici).
|
||||
@Test
|
||||
void deletionImpact_returns200_whenExists() throws Exception {
|
||||
Chapter saved = chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch").order(0).build());
|
||||
mockMvc.perform(get("/api/chapters/{id}/deletion-impact", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.scenes").value(0));
|
||||
}
|
||||
|
||||
// deletion-impact : chapitre inexistant -> 404.
|
||||
@Test
|
||||
void deletionImpact_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/chapters/{id}/deletion-impact", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// update sur id inexistant : le service lève IllegalArgumentException -> 400.
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
ChapterDTO dto = new ChapterDTO();
|
||||
dto.setName("new");
|
||||
dto.setArcId(arcId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/chapters/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.CharacterDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/** Tests d'intégration CRUD du CharacterController (PJ liés à un Playthrough). */
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class CharacterControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private CharacterRepository characterRepository;
|
||||
|
||||
private String playthroughId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
String campId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campId).name("Table").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
CharacterDTO dto = new CharacterDTO();
|
||||
dto.setName("Aragorn");
|
||||
dto.setPlaythroughId(playthroughId);
|
||||
mockMvc.perform(post("/api/characters")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Aragorn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Character saved = characterRepository.save(
|
||||
Character.builder().playthroughId(playthroughId).name("PJ").order(0).build());
|
||||
mockMvc.perform(get("/api/characters/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("PJ"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/characters/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByPlaythrough_returnsArray() throws Exception {
|
||||
characterRepository.save(Character.builder().playthroughId(playthroughId).name("A").order(0).build());
|
||||
mockMvc.perform(get("/api/characters/playthrough/{playthroughId}", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
/** Recherche enrichie : le campaignId est résolu via le Playthrough. */
|
||||
@Test
|
||||
void search_returnsEnrichedResult() throws Exception {
|
||||
characterRepository.save(Character.builder().playthroughId(playthroughId).name("Legolas").order(0).build());
|
||||
mockMvc.perform(get("/api/characters/search").param("q", "Legolas"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].name").value("Legolas"))
|
||||
.andExpect(jsonPath("$[0].campaignId").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
Character saved = characterRepository.save(
|
||||
Character.builder().playthroughId(playthroughId).name("old").order(0).build());
|
||||
CharacterDTO dto = new CharacterDTO();
|
||||
dto.setName("new");
|
||||
dto.setPlaythroughId(playthroughId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/characters/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
CharacterDTO dto = new CharacterDTO();
|
||||
dto.setName("x");
|
||||
dto.setPlaythroughId(playthroughId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/characters/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Character saved = characterRepository.save(
|
||||
Character.builder().playthroughId(playthroughId).name("X").order(0).build());
|
||||
mockMvc.perform(delete("/api/characters/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.infrastructure.updates.UpdateCheckService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link ConfigController}.
|
||||
* <p>
|
||||
* GET /api/config renvoie {demoMode, updateCheckEnabled}. Le service de mise a
|
||||
* jour est mocke pour piloter la valeur de updateCheckEnabled sans dependre de
|
||||
* la configuration reelle (Watchtower/registry indisponibles en test).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class ConfigControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@MockBean private UpdateCheckService updates;
|
||||
|
||||
@Test
|
||||
void getPublicConfig_returns200_updateCheckEnabledTrue() throws Exception {
|
||||
when(updates.isEnabled()).thenReturn(true);
|
||||
mockMvc.perform(get("/api/config"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.updateCheckEnabled").value(true))
|
||||
.andExpect(jsonPath("$.demoMode").value(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPublicConfig_returns200_updateCheckEnabledFalse() throws Exception {
|
||||
when(updates.isEnabled()).thenReturn(false);
|
||||
mockMvc.perform(get("/api/config"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.updateCheckEnabled").value(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Enemy;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/** Tests d'intégration CRUD du EnemyController (bestiaire de campagne). */
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class EnemyControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private EnemyRepository enemyRepository;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
}
|
||||
|
||||
/** Requête = record EnemyRequest(name, level, folder, ..., campaignId, order). */
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
EnemyController.EnemyRequest req = new EnemyController.EnemyRequest(
|
||||
"Gobelin", "FP 1", "Humanoïdes", null, null,
|
||||
Map.of(), Map.of(), Map.of(), campaignId, null);
|
||||
mockMvc.perform(post("/api/enemies")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Gobelin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Enemy saved = enemyRepository.save(Enemy.builder().campaignId(campaignId).name("E").order(0).build());
|
||||
mockMvc.perform(get("/api/enemies/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("E"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/enemies/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByCampaign_returnsArray() throws Exception {
|
||||
enemyRepository.save(Enemy.builder().campaignId(campaignId).name("A").order(0).build());
|
||||
mockMvc.perform(get("/api/enemies/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_returnsArray() throws Exception {
|
||||
enemyRepository.save(Enemy.builder().campaignId(campaignId).name("Dragon").order(0).build());
|
||||
mockMvc.perform(get("/api/enemies/search").param("q", "Dragon"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
Enemy saved = enemyRepository.save(Enemy.builder().campaignId(campaignId).name("old").order(0).build());
|
||||
EnemyController.EnemyRequest req = new EnemyController.EnemyRequest(
|
||||
"new", null, null, null, null,
|
||||
Map.of(), Map.of(), Map.of(), campaignId, 0);
|
||||
mockMvc.perform(put("/api/enemies/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
EnemyController.EnemyRequest req = new EnemyController.EnemyRequest(
|
||||
"x", null, null, null, null,
|
||||
Map.of(), Map.of(), Map.of(), campaignId, 0);
|
||||
mockMvc.perform(put("/api/enemies/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Enemy saved = enemyRepository.save(Enemy.builder().campaignId(campaignId).name("X").order(0).build());
|
||||
mockMvc.perform(delete("/api/enemies/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,43 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
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 com.loremind.domain.gamesystemcontext.ports.RulesPdfImporter;
|
||||
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
@@ -32,6 +52,29 @@ class GameSystemControllerTest {
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
|
||||
@MockBean private RulesPdfImporter rulesPdfImporter;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Tache de l'import streame executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
/** Cree un GameSystem minimal via l'API et renvoie son id. */
|
||||
private String createGameSystem(String name) throws Exception {
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
dto.setName(name);
|
||||
MvcResult posted = mockMvc.perform(post("/api/game-systems")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
return objectMapper.readValue(
|
||||
posted.getResponse().getContentAsString(), GameSystemDTO.class).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_persistsCharacterAndNpcTemplates() throws Exception {
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
@@ -105,4 +148,228 @@ class GameSystemControllerTest {
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().is4xxClientError());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_persistsEnemyTemplate() throws Exception {
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
dto.setName("Bestiaire");
|
||||
dto.setEnemyTemplate(List.of(
|
||||
new TemplateFieldDTO("Niveau", "NUMBER", null),
|
||||
new TemplateFieldDTO("Tactique", "TEXT", null)));
|
||||
|
||||
mockMvc.perform(post("/api/game-systems")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.enemyTemplate.length()").value(2))
|
||||
.andExpect(jsonPath("$.enemyTemplate[0].name").value("Niveau"))
|
||||
.andExpect(jsonPath("$.enemyTemplate[1].type").value("TEXT"));
|
||||
}
|
||||
|
||||
// --- CRUD : lecture / recherche / suppression ---------------------------
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
String id = createGameSystem("Lisible");
|
||||
mockMvc.perform(get("/api/game-systems/{id}", id))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(id))
|
||||
.andExpect(jsonPath("$.name").value("Lisible"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/game-systems/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAll_returnsArray() throws Exception {
|
||||
createGameSystem("Systeme A");
|
||||
mockMvc.perform(get("/api/game-systems"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_returnsMatching() throws Exception {
|
||||
createGameSystem("Dragonbane Unique");
|
||||
mockMvc.perform(get("/api/game-systems/search").param("q", "Dragonbane"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[?(@.name == 'Dragonbane Unique')]").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204_thenGone() throws Exception {
|
||||
String id = createGameSystem("A supprimer");
|
||||
mockMvc.perform(delete("/api/game-systems/{id}", id))
|
||||
.andExpect(status().isNoContent());
|
||||
mockMvc.perform(get("/api/game-systems/{id}", id))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- Import de regles (PDF) : multipart ---------------------------------
|
||||
|
||||
@Test
|
||||
void importRules_returns200_withSections() throws Exception {
|
||||
when(rulesPdfImporter.importRules(any(), any()))
|
||||
.thenReturn(new RulesImportResult(Map.of("Combat", "## Combat\n- d20"), 5, 1));
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
mockMvc.perform(multipart("/api/game-systems/import-rules").file(file))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.pageCount").value(5))
|
||||
.andExpect(jsonPath("$.ocrPageCount").value(1))
|
||||
.andExpect(jsonPath("$.sections.Combat").value("## Combat\n- d20"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_returns400_whenFileEmpty() throws Exception {
|
||||
MockMultipartFile empty = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[0]);
|
||||
mockMvc.perform(multipart("/api/game-systems/import-rules").file(empty))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_returns502_whenBrainFails() throws Exception {
|
||||
when(rulesPdfImporter.importRules(any(), any()))
|
||||
.thenThrow(new RulesImportException("Brain injoignable"));
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
mockMvc.perform(multipart("/api/game-systems/import-rules").file(file))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
|
||||
// --- Import de regles streame (SSE) -------------------------------------
|
||||
|
||||
@Test
|
||||
void importRulesStream_emitsProgressThenDone() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<RulesImportProgress> onProgress = inv.getArgument(2);
|
||||
Consumer<RulesImportResult> onDone = inv.getArgument(5);
|
||||
onProgress.accept(new RulesImportProgress(1, 2, 5, 0, List.of("Combat")));
|
||||
onDone.accept(new RulesImportResult(Map.of("Combat", "## Combat"), 5, 0));
|
||||
return null;
|
||||
}).when(rulesPdfImporter).importRulesStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(file))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("progress")))
|
||||
.andExpect(content().string(containsString("done")))
|
||||
.andExpect(content().string(containsString("Combat")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRulesStream_emptyFile_emitsError() throws Exception {
|
||||
MockMultipartFile empty = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[0]);
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(empty))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("vide")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRulesStream_brainError_emitsError() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException("structuration KO"));
|
||||
return null;
|
||||
}).when(rulesPdfImporter).importRulesStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(file))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("structuration KO")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Couvre {@code sendImportHeartbeat} (callback onHeartbeat, arg 3) ET la branche
|
||||
* "status" de {@code sendImportEvent} (callback onStatus, arg 4) : un import qui
|
||||
* envoie un keepalive et un message de statut avant de produire son resultat.
|
||||
*/
|
||||
@Test
|
||||
void importRulesStream_emitsHeartbeatAndStatus_thenDone() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Runnable onHeartbeat = inv.getArgument(3);
|
||||
Consumer<String> onStatus = inv.getArgument(4);
|
||||
Consumer<RulesImportResult> onDone = inv.getArgument(5);
|
||||
// Keepalive (commentaire SSE, ignore par le front) -> sendImportHeartbeat.
|
||||
onHeartbeat.run();
|
||||
// Message de statut lisible -> sendImportEvent(..., "status", ...).
|
||||
onStatus.accept("Fournisseur sature, nouvelle tentative...");
|
||||
onDone.accept(new RulesImportResult(Map.of("Combat", "## Combat"), 5, 0));
|
||||
return null;
|
||||
}).when(rulesPdfImporter).importRulesStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(file))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
// Le commentaire keepalive est present dans le flux brut.
|
||||
.andExpect(content().string(containsString("keepalive")))
|
||||
// L'event "status" et son message sont serialises.
|
||||
.andExpect(content().string(containsString("status")))
|
||||
.andExpect(content().string(containsString("Fournisseur sature")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Couvre la branche onStatus avec un message null : le controleur substitue une
|
||||
* chaine vide ({@code status != null ? status : ""}) sans planter.
|
||||
*/
|
||||
@Test
|
||||
void importRulesStream_nullStatus_emitsEmptyStatus() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onStatus = inv.getArgument(4);
|
||||
Consumer<RulesImportResult> onDone = inv.getArgument(5);
|
||||
onStatus.accept(null);
|
||||
onDone.accept(new RulesImportResult(Map.of("Combat", "## Combat"), 5, 0));
|
||||
return null;
|
||||
}).when(rulesPdfImporter).importRulesStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(file))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("status")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.application.gamesystemcontext.GameSystemService;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportProgress;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportResult;
|
||||
import com.loremind.infrastructure.web.mapper.GameSystemMapper;
|
||||
import com.loremind.infrastructure.web.mapper.TemplateFieldMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Test UNITAIRE pur (sans Spring) de {@link GameSystemController} dédié au code
|
||||
* défensif de déconnexion du navigateur de l'import streamé, INTESTABLE via MockMvc
|
||||
* (un envoi SSE après {@code complete()} y remonte en ServletException au lieu
|
||||
* d'exécuter la branche). Voir {@link CampaignImportControllerUnitTest} pour le détail
|
||||
* de l'approche — même séquence : complete -> send échoue -> {@code clientGone=true}
|
||||
* -> les callbacks suivants empruntent les branches {@code ClientGoneException}.
|
||||
*/
|
||||
class GameSystemControllerUnitTest {
|
||||
|
||||
private final GameSystemService service = mock(GameSystemService.class);
|
||||
private final TaskExecutor inlineExecutor = Runnable::run;
|
||||
private final GameSystemController controller = new GameSystemController(
|
||||
service, mock(GameSystemMapper.class), mock(TemplateFieldMapper.class),
|
||||
inlineExecutor, new ObjectMapper());
|
||||
|
||||
private static RulesImportProgress progress() {
|
||||
return new RulesImportProgress(1, 1, 0, 0, List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRulesStream_clientDisconnect_exercisesDefensiveBranches() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<RulesImportProgress> onProgress = inv.getArgument(2);
|
||||
Runnable onHeartbeat = inv.getArgument(3);
|
||||
Consumer<RulesImportResult> onDone = inv.getArgument(5);
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
|
||||
// 1) Termine le flux (event "done" + complete()).
|
||||
onDone.accept(new RulesImportResult(Map.of(), 0, 0));
|
||||
// 2) Envoi post-complete : send échoue -> catch -> clientGone=true.
|
||||
try { onProgress.accept(progress()); } catch (RuntimeException ignored) { }
|
||||
// 3) clientGone=true -> sendImportHeartbeat lève ClientGoneException.
|
||||
try { onHeartbeat.run(); } catch (RuntimeException ignored) { }
|
||||
// 4) clientGone=true -> sendImportEvent lève ClientGoneException.
|
||||
try { onProgress.accept(progress()); } catch (RuntimeException ignored) { }
|
||||
// 5) clientGone=true -> callback d'erreur en early-return.
|
||||
onError.accept(new RuntimeException("tardif"));
|
||||
return null;
|
||||
}).when(service).importRulesFromPdfStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
SseEmitter emitter = controller.importRulesStream(file);
|
||||
|
||||
assertNotNull(emitter);
|
||||
verify(service).importRulesFromPdfStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.images.ImageService;
|
||||
import com.loremind.domain.images.Image;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link ImageController} (Shared Kernel images).
|
||||
* <p>
|
||||
* Le {@link ImageService} est mocke : il orchestre sinon MinIO (binaire) +
|
||||
* Postgres (metadonnees) via ses deux ports. On evite ainsi tout acces a MinIO,
|
||||
* indisponible en test, tout en couvrant le mapping HTTP du controleur
|
||||
* (upload / metadata / content streaming / delete + cas 400 / 404).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class ImageControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@MockBean private ImageService imageService;
|
||||
|
||||
private Image sampleImage() {
|
||||
return Image.builder()
|
||||
.id("img-1")
|
||||
.filename("portrait.png")
|
||||
.contentType("image/png")
|
||||
.sizeBytes(3)
|
||||
.storageKey("images/img-1.png")
|
||||
.uploadedAt(LocalDateTime.of(2026, 1, 1, 12, 0))
|
||||
.build();
|
||||
}
|
||||
|
||||
private MockMultipartFile pngFile(byte[] bytes) {
|
||||
return new MockMultipartFile("file", "portrait.png", "image/png", bytes);
|
||||
}
|
||||
|
||||
// --- POST /api/images --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void upload_returns200_withMetadata() throws Exception {
|
||||
when(imageService.upload(eq("portrait.png"), eq("image/png"), any(InputStream.class), anyLong()))
|
||||
.thenReturn(sampleImage());
|
||||
|
||||
mockMvc.perform(multipart("/api/images").file(pngFile(new byte[]{1, 2, 3})))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value("img-1"))
|
||||
.andExpect(jsonPath("$.filename").value("portrait.png"))
|
||||
.andExpect(jsonPath("$.contentType").value("image/png"))
|
||||
.andExpect(jsonPath("$.sizeBytes").value(3))
|
||||
.andExpect(jsonPath("$.url").value("/api/images/img-1/content"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void upload_returns400_whenEmpty() throws Exception {
|
||||
mockMvc.perform(multipart("/api/images").file(pngFile(new byte[0])))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void upload_returns400_whenServiceRejects() throws Exception {
|
||||
// Validation metier (MIME non autorise, taille...) -> IllegalArgumentException.
|
||||
when(imageService.upload(any(), any(), any(InputStream.class), anyLong()))
|
||||
.thenThrow(new IllegalArgumentException("Type de fichier non supporte."));
|
||||
|
||||
mockMvc.perform(multipart("/api/images")
|
||||
.file(new MockMultipartFile("file", "evil.exe", "application/octet-stream",
|
||||
new byte[]{1, 2, 3})))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
// --- GET /api/images/{id} ----------------------------------------------
|
||||
|
||||
@Test
|
||||
void getMetadata_returns200() throws Exception {
|
||||
when(imageService.getById("img-1")).thenReturn(Optional.of(sampleImage()));
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}", "img-1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value("img-1"))
|
||||
.andExpect(jsonPath("$.url").value("/api/images/img-1/content"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_returns404_whenMissing() throws Exception {
|
||||
when(imageService.getById("nope")).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}", "nope"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- GET /api/images/{id}/content --------------------------------------
|
||||
|
||||
@Test
|
||||
void getContent_returns200_withBinary() throws Exception {
|
||||
byte[] data = {10, 20, 30};
|
||||
when(imageService.getById("img-1")).thenReturn(Optional.of(sampleImage()));
|
||||
when(imageService.downloadById("img-1"))
|
||||
.thenReturn(Optional.of(new ByteArrayInputStream(data)));
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}/content", "img-1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string("Content-Type", "image/png"))
|
||||
.andExpect(header().string("Cross-Origin-Resource-Policy", "cross-origin"))
|
||||
.andExpect(content().bytes(data));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getContent_returns404_whenMetadataMissing() throws Exception {
|
||||
when(imageService.getById("nope")).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}/content", "nope"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getContent_returns404_whenBinaryLost() throws Exception {
|
||||
// Metadonnees presentes mais binaire absent (incoherence) -> 404.
|
||||
when(imageService.getById("img-1")).thenReturn(Optional.of(sampleImage()));
|
||||
when(imageService.downloadById("img-1")).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}/content", "img-1"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- DELETE /api/images/{id} -------------------------------------------
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
mockMvc.perform(delete("/api/images/{id}", "img-1"))
|
||||
.andExpect(status().isNoContent());
|
||||
verify(imageService).deleteById("img-1");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.ItemCatalog;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerationException;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerator;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogRepository;
|
||||
import com.loremind.infrastructure.web.controller.ItemCatalogController.GenerateRequest;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ItemCatalogDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link ItemCatalogController} (CRUD + recherche +
|
||||
* generation IA d'un catalogue d'objets).
|
||||
* <p>
|
||||
* Le port {@link ItemCatalogGenerator} (client du Brain) est mocke : sinon
|
||||
* l'endpoint /generate ferait un vrai appel reseau au service IA (indisponible
|
||||
* en test). Les repos reels servent aux fixtures.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class ItemCatalogControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private ItemCatalogRepository catalogRepository;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
|
||||
@MockBean private ItemCatalogGenerator generator;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(
|
||||
Campaign.builder().name("Camp").description("desc").build()).getId();
|
||||
}
|
||||
|
||||
private ItemCatalogDTO dto(String name) {
|
||||
ItemCatalogDTO dto = new ItemCatalogDTO();
|
||||
dto.setName(name);
|
||||
dto.setDescription("Une boutique");
|
||||
dto.setIcon("store");
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setOrder(0);
|
||||
return dto;
|
||||
}
|
||||
|
||||
// --- POST / -------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
mockMvc.perform(post("/api/item-catalogs")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto("Echoppe"))))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Echoppe"))
|
||||
.andExpect(jsonPath("$.campaignId").value(campaignId));
|
||||
}
|
||||
|
||||
// --- GET /{id} ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
ItemCatalog saved = catalogRepository.save(ItemCatalog.builder()
|
||||
.name("Tresor").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/item-catalogs/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Tresor"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/item-catalogs/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- GET /campaign/{campaignId} -----------------------------------------
|
||||
|
||||
@Test
|
||||
void getByCampaign_returnsArray() throws Exception {
|
||||
catalogRepository.save(ItemCatalog.builder()
|
||||
.name("A").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/item-catalogs/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].name").value("A"));
|
||||
}
|
||||
|
||||
// --- PUT /{id} ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
ItemCatalog saved = catalogRepository.save(ItemCatalog.builder()
|
||||
.name("old").campaignId(campaignId).order(0).build());
|
||||
ItemCatalogDTO dto = dto("new");
|
||||
mockMvc.perform(put("/api/item-catalogs/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
// Le service leve IllegalArgumentException -> GlobalExceptionHandler -> 400.
|
||||
mockMvc.perform(put("/api/item-catalogs/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto("x"))))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
// --- DELETE /{id} -------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
ItemCatalog saved = catalogRepository.save(ItemCatalog.builder()
|
||||
.name("X").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(delete("/api/item-catalogs/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- GET /search --------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void search_returnsArray() throws Exception {
|
||||
catalogRepository.save(ItemCatalog.builder()
|
||||
.name("Forge de Naheulbeuk").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/item-catalogs/search").param("q", "Forge"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
// --- POST /generate -----------------------------------------------------
|
||||
|
||||
@Test
|
||||
void generate_returns200() throws Exception {
|
||||
when(generator.generate(any(), any())).thenReturn(
|
||||
new ItemCatalogGenerator.GeneratedCatalog(
|
||||
"Boutique magique",
|
||||
"Objets enchantes",
|
||||
List.of(CatalogItem.builder().name("Potion").price("50 po").build())));
|
||||
|
||||
GenerateRequest req = new GenerateRequest(campaignId, "une boutique de magie");
|
||||
mockMvc.perform(post("/api/item-catalogs/generate")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Boutique magique"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns502_whenBrainUnreachable() throws Exception {
|
||||
when(generator.generate(any(), any()))
|
||||
.thenThrow(new ItemCatalogGenerationException("Brain injoignable"));
|
||||
|
||||
GenerateRequest req = new GenerateRequest(campaignId, "boutique");
|
||||
mockMvc.perform(post("/api/item-catalogs/generate")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.licensing.ChannelSwitcherService;
|
||||
import com.loremind.application.licensing.LicenseService;
|
||||
import com.loremind.application.licensing.LicenseService.InstallException;
|
||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
||||
import com.loremind.domain.licensing.LicenseStatus;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link LicenseController} (gestion licence Patreon).
|
||||
* <p>
|
||||
* {@code /api/license/**} exige le role ADMIN (HTTP Basic) : chaque requete porte
|
||||
* l'entete d'auth construite a partir des identifiants de test (cf.
|
||||
* src/test/resources/application.properties). Sans cet entete, la securite
|
||||
* renverrait 401.
|
||||
* <p>
|
||||
* Les deux services applicatifs sont mockes : {@link LicenseService} (qui appelle
|
||||
* sinon le relais OAuth distant + verification JWT) et {@link ChannelSwitcherService}
|
||||
* (qui ecrit sinon dans un volume partage avec le sidecar). Aucun acces reseau ni
|
||||
* fichier reel.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class LicenseControllerTest {
|
||||
|
||||
/** Identifiants definis dans src/test/resources/application.properties. */
|
||||
private static final String ADMIN_AUTH = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("test-admin:test-admin-password".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@MockBean private LicenseService licenseService;
|
||||
@MockBean private ChannelSwitcherService channelSwitcher;
|
||||
|
||||
private LicenseSnapshot validSnapshot() {
|
||||
return new LicenseSnapshot(
|
||||
LicenseStatus.VALID, "user-42", "tier-1", "li-xyz",
|
||||
Instant.now().plusSeconds(3600), Instant.now(), true, true);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Valeurs par defaut neutres ; chaque test surcharge ce dont il a besoin.
|
||||
when(licenseService.isLicensingEnabled()).thenReturn(true);
|
||||
when(licenseService.getCurrentSnapshot()).thenReturn(validSnapshot());
|
||||
}
|
||||
|
||||
// --- Securite ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getStatus_returns401_withoutAuth() throws Exception {
|
||||
mockMvc.perform(get("/api/license"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
// --- GET /api/license --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getStatus_returns200() throws Exception {
|
||||
mockMvc.perform(get("/api/license").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.enabled").value(true))
|
||||
.andExpect(jsonPath("$.status").value("VALID"))
|
||||
.andExpect(jsonPath("$.patreonUserId").value("user-42"));
|
||||
}
|
||||
|
||||
// --- GET /api/license/connect-url --------------------------------------
|
||||
|
||||
@Test
|
||||
void getConnectUrl_returns200() throws Exception {
|
||||
when(licenseService.buildConnectUrl()).thenReturn("https://relay/oauth?x=1");
|
||||
mockMvc.perform(get("/api/license/connect-url").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.url").value("https://relay/oauth?x=1"));
|
||||
}
|
||||
|
||||
// --- POST /api/license/install -----------------------------------------
|
||||
|
||||
@Test
|
||||
void install_returns200_onValidJwt() throws Exception {
|
||||
when(licenseService.installToken("good-jwt")).thenReturn(validSnapshot());
|
||||
mockMvc.perform(post("/api/license/install")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"jwt\":\"good-jwt\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value("VALID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void install_returns400_whenJwtMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/license/install")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"jwt\":\"\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error").value("missing jwt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void install_returns400_whenInstallFails() throws Exception {
|
||||
when(licenseService.installToken("bad-jwt"))
|
||||
.thenThrow(new InstallException("Invalid JWT: signature"));
|
||||
mockMvc.perform(post("/api/license/install")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"jwt\":\"bad-jwt\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error").value("Invalid JWT: signature"));
|
||||
}
|
||||
|
||||
// --- DELETE /api/license -----------------------------------------------
|
||||
|
||||
@Test
|
||||
void disconnect_returns204() throws Exception {
|
||||
mockMvc.perform(delete("/api/license").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- POST /api/license/refresh -----------------------------------------
|
||||
|
||||
@Test
|
||||
void refresh_returns200() throws Exception {
|
||||
mockMvc.perform(post("/api/license/refresh").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value("VALID"));
|
||||
}
|
||||
|
||||
// --- PUT /api/license/beta-channel -------------------------------------
|
||||
|
||||
@Test
|
||||
void setBetaChannel_returns200() throws Exception {
|
||||
when(licenseService.setBetaChannelEnabled(eq(false))).thenReturn(validSnapshot());
|
||||
mockMvc.perform(put("/api/license/beta-channel")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"enabled\":false}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value("VALID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBetaChannel_returns409_whenNoLicense() throws Exception {
|
||||
when(licenseService.setBetaChannelEnabled(anyBoolean()))
|
||||
.thenThrow(new IllegalStateException("No license installed"));
|
||||
mockMvc.perform(put("/api/license/beta-channel")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"enabled\":true}"))
|
||||
.andExpect(status().isConflict())
|
||||
.andExpect(jsonPath("$.error").value("No license installed"));
|
||||
}
|
||||
|
||||
// --- GET /api/license/channel ------------------------------------------
|
||||
|
||||
@Test
|
||||
void getChannel_returns200() throws Exception {
|
||||
when(channelSwitcher.getCurrentChannel()).thenReturn(ChannelSwitcherService.Channel.STABLE);
|
||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
||||
when(channelSwitcher.getLastResult()).thenReturn(null);
|
||||
mockMvc.perform(get("/api/license/channel").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.currentChannel").value("stable"))
|
||||
.andExpect(jsonPath("$.switcherAvailable").value(true));
|
||||
}
|
||||
|
||||
// --- POST /api/license/channel/switch ----------------------------------
|
||||
|
||||
@Test
|
||||
void switchChannel_returns400_whenChannelMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error").value("missing channel"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns400_whenChannelInvalid() throws Exception {
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"nightly\"}"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns403_whenBetaWithoutLicense() throws Exception {
|
||||
// Snapshot EXPIRED -> pas d'acces beta.
|
||||
when(licenseService.getCurrentSnapshot()).thenReturn(new LicenseSnapshot(
|
||||
LicenseStatus.EXPIRED, null, null, null, null, null, false, false));
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"beta\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns503_whenSwitcherUnavailable() throws Exception {
|
||||
// Licence VALID (autorise beta) mais sidecar absent.
|
||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(false);
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"beta\"}"))
|
||||
.andExpect(status().isServiceUnavailable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns202_onSuccess() throws Exception {
|
||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
||||
when(channelSwitcher.requestSwitch(ChannelSwitcherService.Channel.STABLE))
|
||||
.thenReturn("cmd-1");
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"stable\"}"))
|
||||
.andExpect(status().isAccepted())
|
||||
.andExpect(jsonPath("$.id").value("cmd-1"))
|
||||
.andExpect(jsonPath("$.channel").value("stable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns500_whenWriteFails() throws Exception {
|
||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
||||
doThrow(new IOException("disk full"))
|
||||
.when(channelSwitcher).requestSwitch(ChannelSwitcherService.Channel.STABLE);
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"stable\"}"))
|
||||
.andExpect(status().isInternalServerError());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Notebook;
|
||||
import com.loremind.domain.campaigncontext.NotebookSource;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookChatStreamer;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookException;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookIndexer;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link NotebookController} (atelier RAG).
|
||||
* <p>
|
||||
* Les ports vers le Brain sont mockes : {@link NotebookIndexer} (indexation des
|
||||
* sources) et {@link NotebookChatStreamer} (chat ancre streame), sinon chaque test
|
||||
* ferait un vrai appel HTTP au Brain (indisponible en test).
|
||||
* <p>
|
||||
* Le {@code TaskExecutor} ("applicationTaskExecutor") est egalement mocke pour
|
||||
* executer la tache du chat stream EN LIGNE (synchrone) : tous les events SSE sont
|
||||
* ainsi ecrits avant le retour du controleur, ce qui rend les assertions sur le
|
||||
* flux deterministes (pas de course entre threads).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class NotebookControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private NotebookRepository notebookRepository;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
|
||||
@MockBean private NotebookIndexer indexer;
|
||||
@MockBean private NotebookChatStreamer chatStreamer;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(
|
||||
Campaign.builder().name("C").description("").build()).getId();
|
||||
// Tache du chat stream executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private Notebook persistNotebook() {
|
||||
return notebookRepository.save(
|
||||
Notebook.builder().campaignId(campaignId).name("Atelier").build());
|
||||
}
|
||||
|
||||
// --- Notebooks (CRUD) ---
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
var req = new NotebookController.CreateRequest(campaignId, "Mon atelier");
|
||||
mockMvc.perform(post("/api/notebooks")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").exists())
|
||||
.andExpect(jsonPath("$.name").value("Mon atelier"))
|
||||
.andExpect(jsonPath("$.campaignId").value(campaignId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_blankName_fallsBackToDefault() throws Exception {
|
||||
var req = new NotebookController.CreateRequest(campaignId, " ");
|
||||
mockMvc.perform(post("/api/notebooks")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Nouvel atelier"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listByCampaign_returnsArray() throws Exception {
|
||||
persistNotebook();
|
||||
mockMvc.perform(get("/api/notebooks/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].campaignId").value(campaignId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returns200_withSourcesAndMessages() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
mockMvc.perform(get("/api/notebooks/{id}", nb.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(nb.getId()))
|
||||
.andExpect(jsonPath("$.name").value("Atelier"))
|
||||
.andExpect(jsonPath("$.sources").isArray())
|
||||
.andExpect(jsonPath("$.messages").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/notebooks/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rename_returns200() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
var req = new NotebookController.RenameRequest("Renomme");
|
||||
mockMvc.perform(put("/api/notebooks/{id}", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Renomme"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
mockMvc.perform(delete("/api/notebooks/{id}", nb.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- Sources ---
|
||||
|
||||
@Test
|
||||
void addSource_returns200_andIndexes() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
when(indexer.index(any(), any(), any()))
|
||||
.thenReturn(new NotebookIndexer.IndexResult(12, 3, 0));
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "livre.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
mockMvc.perform(multipart("/api/notebooks/{id}/sources", nb.getId()).file(file))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.filename").value("livre.pdf"))
|
||||
.andExpect(jsonPath("$.status").value("READY"))
|
||||
.andExpect(jsonPath("$.chunkCount").value(12))
|
||||
.andExpect(jsonPath("$.pageCount").value(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addSource_returns502_whenBrainFails() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
when(indexer.index(any(), any(), any()))
|
||||
.thenThrow(new NotebookException("Brain injoignable"));
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "livre.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
mockMvc.perform(multipart("/api/notebooks/{id}/sources", nb.getId()).file(file))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSource_returns204() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
NotebookSource src = notebookRepository.saveSource(NotebookSource.builder()
|
||||
.notebookId(nb.getId()).filename("s.pdf").status("READY").build());
|
||||
mockMvc.perform(delete("/api/notebooks/sources/{sourceId}", src.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- Conversation : vider (archiver) + archives ---
|
||||
|
||||
@Test
|
||||
void clearChat_returns204() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
mockMvc.perform(post("/api/notebooks/{id}/chat/clear", nb.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearChat_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/notebooks/{id}/chat/clear", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listArchives_returnsArray() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
mockMvc.perform(get("/api/notebooks/{id}/chat/archives", nb.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
// --- Chat ancre streame (SSE) ---
|
||||
|
||||
@Test
|
||||
void chatStream_happyPath_streamsTokenThenDone() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
// Le streamer mocke joue : 1 token puis fin.
|
||||
doAnswer(inv -> {
|
||||
java.util.function.Consumer<String> onToken = inv.getArgument(5);
|
||||
Runnable onDone = inv.getArgument(7);
|
||||
onToken.accept("Bonjour");
|
||||
onDone.run();
|
||||
return null;
|
||||
}).when(chatStreamer).stream(any(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean(),
|
||||
any(), any(), any(), any(), any());
|
||||
|
||||
var req = new NotebookController.ChatRequest("Salut ?", false, null, null);
|
||||
MvcResult result = mockMvc.perform(post("/api/notebooks/{id}/chat/stream", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Bonjour")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
|
||||
// La reponse de l'assistant a ete persistee a la fin du stream.
|
||||
boolean persisted = notebookRepository.findMessagesByNotebookId(nb.getId()).stream()
|
||||
.anyMatch(m -> "assistant".equals(m.getRole()) && "Bonjour".equals(m.getContent()));
|
||||
org.junit.jupiter.api.Assertions.assertTrue(persisted, "reponse assistant persistee");
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_emptyMessage_emitsError() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
var req = new NotebookController.ChatRequest(" ", false, null, null);
|
||||
MvcResult result = mockMvc.perform(post("/api/notebooks/{id}/chat/stream", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_streamerError_emitsError() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
doAnswer(inv -> {
|
||||
java.util.function.Consumer<Throwable> onError = inv.getArgument(8);
|
||||
onError.accept(new RuntimeException("boom"));
|
||||
return null;
|
||||
}).when(chatStreamer).stream(any(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean(),
|
||||
any(), any(), any(), any(), any());
|
||||
|
||||
var req = new NotebookController.ChatRequest("Salut ?", false, null, null);
|
||||
MvcResult result = mockMvc.perform(post("/api/notebooks/{id}/chat/stream", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("boom")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_returns404_whenMissing() throws Exception {
|
||||
var req = new NotebookController.ChatRequest("Salut ?", false, null, null);
|
||||
mockMvc.perform(post("/api/notebooks/{id}/chat/stream", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_deepMode_emitsSourcesAndProgress() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
// Source PRETE -> remontee par readySourceIds, donc selectionnable via sourceIds.
|
||||
NotebookSource src = notebookRepository.saveSource(NotebookSource.builder()
|
||||
.notebookId(nb.getId()).filename("s.pdf").status("READY").build());
|
||||
|
||||
// Le streamer mocke joue, en mode approfondi : sources -> progress -> token -> fin.
|
||||
doAnswer(inv -> {
|
||||
java.util.function.Consumer<String> onSourcesJson = inv.getArgument(4);
|
||||
java.util.function.Consumer<String> onToken = inv.getArgument(5);
|
||||
java.util.function.Consumer<NotebookChatStreamer.Progress> onProgress = inv.getArgument(6);
|
||||
Runnable onDone = inv.getArgument(7);
|
||||
onSourcesJson.accept("{\"sources\":[{\"source_id\":\"" + src.getId() + "\",\"page\":1}]}");
|
||||
onProgress.accept(new NotebookChatStreamer.Progress(1, 3));
|
||||
onToken.accept("Reponse");
|
||||
onDone.run();
|
||||
return null;
|
||||
}).when(chatStreamer).stream(any(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean(),
|
||||
any(), any(), any(), any(), any());
|
||||
|
||||
// deep=true + sourceIds (filtrage) + archiveIds non nuls (branche buildArchiveContext).
|
||||
var req = new NotebookController.ChatRequest(
|
||||
"Analyse complete ?", true,
|
||||
java.util.List.of(src.getId()), java.util.List.of("2020-01-01T00:00"));
|
||||
MvcResult result = mockMvc.perform(post("/api/notebooks/{id}/chat/stream", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("sources")))
|
||||
.andExpect(content().string(containsString("progress")))
|
||||
.andExpect(content().string(containsString("Reponse")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Npc;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/** Tests d'intégration CRUD du NpcController. */
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class NpcControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private NpcRepository npcRepository;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
NpcDTO dto = new NpcDTO();
|
||||
dto.setName("Gandalf");
|
||||
dto.setCampaignId(campaignId);
|
||||
mockMvc.perform(post("/api/npcs")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Gandalf"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Npc saved = npcRepository.save(Npc.builder().campaignId(campaignId).name("N").order(0).build());
|
||||
mockMvc.perform(get("/api/npcs/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("N"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/npcs/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByCampaign_returnsArray() throws Exception {
|
||||
npcRepository.save(Npc.builder().campaignId(campaignId).name("A").order(0).build());
|
||||
mockMvc.perform(get("/api/npcs/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_returnsArray() throws Exception {
|
||||
npcRepository.save(Npc.builder().campaignId(campaignId).name("Frodon").order(0).build());
|
||||
mockMvc.perform(get("/api/npcs/search").param("q", "Frodon"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByLore_returnsArray() throws Exception {
|
||||
mockMvc.perform(get("/api/npcs/lore/{loreId}", "lore-1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
Npc saved = npcRepository.save(Npc.builder().campaignId(campaignId).name("old").order(0).build());
|
||||
NpcDTO dto = new NpcDTO();
|
||||
dto.setName("new");
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/npcs/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
NpcDTO dto = new NpcDTO();
|
||||
dto.setName("x");
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/npcs/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Npc saved = npcRepository.save(Npc.builder().campaignId(campaignId).name("X").order(0).build());
|
||||
mockMvc.perform(delete("/api/npcs/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.generationcontext.GeneratePageValuesUseCase;
|
||||
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link PageGenerationController} (generation IA de Page).
|
||||
* <p>
|
||||
* Le use case {@link GeneratePageValuesUseCase} est mocke : il orchestre l'appel
|
||||
* au Brain (AiProvider), indisponible en test. On verifie le mapping des
|
||||
* exceptions du use case vers les codes HTTP :
|
||||
* <ul>
|
||||
* <li>OK -> 200 + {@code {values:{...}}}</li>
|
||||
* <li>IllegalArgumentException (page introuvable) -> 404</li>
|
||||
* <li>AiProviderException (Brain HS) -> 502</li>
|
||||
* <li>IllegalStateException "aucun champ" -> 422</li>
|
||||
* <li>IllegalStateException autre (incoherence BDD) -> 500</li>
|
||||
* </ul>
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class PageGenerationControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@MockBean private GeneratePageValuesUseCase generatePageValuesUseCase;
|
||||
|
||||
@Test
|
||||
void generate_returns200_withSuggestions() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("p1")))
|
||||
.thenReturn(Map.of("nom", "Aldric", "race", "Elfe"));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "p1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.values.nom").value("Aldric"))
|
||||
.andExpect(jsonPath("$.values.race").value("Elfe"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns404_whenPageMissing() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("missing")))
|
||||
.thenThrow(new IllegalArgumentException("Page non trouvée"));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "missing"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns502_whenBrainDown() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("p1")))
|
||||
.thenThrow(new AiProviderException("Brain unreachable"));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "p1"))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns422_whenTemplateHasNoFields() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("p1")))
|
||||
.thenThrow(new IllegalStateException("Le template 'X' n'a aucun champ texte à générer."));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "p1"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns500_whenBddInconsistent() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("p1")))
|
||||
.thenThrow(new IllegalStateException("Template introuvable (id=t1)"));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "p1"))
|
||||
.andExpect(status().isInternalServerError());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.Session;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.domain.playcontext.ports.SessionRepository;
|
||||
import com.loremind.infrastructure.web.dto.playcontext.PlaythroughDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration du PlaythroughController.
|
||||
* Fixture parente : Campaign (un Playthrough référence une campagne).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class PlaythroughControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private SessionRepository sessionRepository;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
}
|
||||
|
||||
private Playthrough savePlaythrough() {
|
||||
return playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campaignId).name("Partie").description("d").build());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
PlaythroughDTO dto = new PlaythroughDTO();
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setName("Table du vendredi");
|
||||
dto.setDescription("desc");
|
||||
mockMvc.perform(post("/api/playthroughs")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Table du vendredi"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_returns400_whenCampaignMissing() throws Exception {
|
||||
PlaythroughDTO dto = new PlaythroughDTO();
|
||||
dto.setCampaignId("999999999");
|
||||
dto.setName("X");
|
||||
mockMvc.perform(post("/api/playthroughs")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Playthrough p = savePlaythrough();
|
||||
mockMvc.perform(get("/api/playthroughs/{id}", p.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Partie"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/playthroughs/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_byCampaign_returnsArray() throws Exception {
|
||||
savePlaythrough();
|
||||
mockMvc.perform(get("/api/playthroughs").param("campaignId", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_withoutCampaign_returnsEmptyArray() throws Exception {
|
||||
savePlaythrough();
|
||||
mockMvc.perform(get("/api/playthroughs"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
Playthrough p = savePlaythrough();
|
||||
PlaythroughDTO dto = new PlaythroughDTO();
|
||||
dto.setName("Renommée");
|
||||
dto.setDescription("nouvelle desc");
|
||||
mockMvc.perform(put("/api/playthroughs/{id}", p.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Renommée"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
PlaythroughDTO dto = new PlaythroughDTO();
|
||||
dto.setName("X");
|
||||
mockMvc.perform(put("/api/playthroughs/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Playthrough p = savePlaythrough();
|
||||
mockMvc.perform(delete("/api/playthroughs/{id}", p.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns400_whenMissing() throws Exception {
|
||||
mockMvc.perform(delete("/api/playthroughs/{id}", "999999999"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_returns200() throws Exception {
|
||||
Playthrough p = savePlaythrough();
|
||||
sessionRepository.save(Session.builder()
|
||||
.name("S").playthroughId(p.getId())
|
||||
.startedAt(java.time.LocalDateTime.now()).build());
|
||||
mockMvc.perform(get("/api/playthroughs/{id}/deletion-impact", p.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.sessions").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/playthroughs/{id}/deletion-impact", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughFlagRepository;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.infrastructure.web.dto.playcontext.PlaythroughFlagDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration de {@link PlaythroughFlagController}.
|
||||
* Couvre les 3 endpoints : list (GET), setFlag (PUT), deleteFlag (DELETE).
|
||||
* Les flags sont indexés par playthroughId : on crée une campagne puis un playthrough en fixture.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class PlaythroughFlagControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private PlaythroughFlagRepository flagRepository;
|
||||
|
||||
private String playthroughId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Chaîne de fixtures : campaign -> playthrough
|
||||
String campId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campId).name("Table").description("").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsEmptyArray_whenNoFlags() throws Exception {
|
||||
mockMvc.perform(get("/api/playthroughs/{pid}/flags", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsExistingFlags() throws Exception {
|
||||
// Pré-positionne un flag via le repo réel
|
||||
flagRepository.setFlag(playthroughId, "porte_ouverte", true);
|
||||
mockMvc.perform(get("/api/playthroughs/{pid}/flags", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].name").value("porte_ouverte"))
|
||||
.andExpect(jsonPath("$[0].value").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setFlag_returns200_andEcho() throws Exception {
|
||||
PlaythroughFlagDTO body = new PlaythroughFlagDTO("dragon_vaincu", true);
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/flags/{name}", playthroughId, "dragon_vaincu")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(body)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("dragon_vaincu"))
|
||||
.andExpect(jsonPath("$.value").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setFlag_false_returns200() throws Exception {
|
||||
PlaythroughFlagDTO body = new PlaythroughFlagDTO("ignore", false);
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/flags/{name}", playthroughId, "ignore")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(body)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.value").value(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFlag_returns204() throws Exception {
|
||||
flagRepository.setFlag(playthroughId, "a_supprimer", true);
|
||||
mockMvc.perform(delete("/api/playthroughs/{pid}/flags/{name}", playthroughId, "a_supprimer"))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFlag_returns204_whenAbsent() throws Exception {
|
||||
// deleteFlag est idempotent : pas d'erreur même si le flag n'existe pas
|
||||
mockMvc.perform(delete("/api/playthroughs/{pid}/flags/{name}", playthroughId, "inexistant"))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user