Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f1989c1d77 | |||
| 8efdf5d0e0 | |||
| 96bc5de942 | |||
| 84ccdd53ad | |||
| 29978058ee | |||
| e510f64336 | |||
| f189f67aaf | |||
| 8efa148739 | |||
| 8f4dd3e9d6 | |||
| bf38b6695f | |||
| 49a82d05f7 | |||
| b0fe8de708 | |||
| 71449bee1b | |||
| 1e34f7f954 | |||
| e185dabc45 |
338
INSTALL.md
338
INSTALL.md
@@ -1,75 +1,311 @@
|
||||
# Installation de LoreMindMJ
|
||||
|
||||
## Prerequis
|
||||
Ce document decrit la procedure d'installation de LoreMindMJ. Temps estime :
|
||||
5 a 10 minutes selon la qualite de la connexion reseau.
|
||||
|
||||
- **Docker Desktop** ([Windows](https://www.docker.com/products/docker-desktop/) / [Mac](https://www.docker.com/products/docker-desktop/))
|
||||
ou **Docker Engine + Compose v2** (Linux).
|
||||
- (Optionnel) **[Ollama](https://ollama.com/)** si tu veux un LLM local.
|
||||
Sinon, une cle API [1min.ai](https://1min.ai) suffit.
|
||||
## 1. Prerequis
|
||||
|
||||
## Installation (5 minutes)
|
||||
|
||||
1. Telecharge `docker-compose.yml` et `.env.example` depuis la [derniere release](https://git.igmlcreation.fr/ietm64/LoreMindMJ/releases) dans un dossier a toi.
|
||||
|
||||
2. Renomme `.env.example` en `.env` et ouvre-le dans un editeur texte. Trois variables sont **obligatoires** :
|
||||
- `POSTGRES_PASSWORD` : mot de passe de la base (choisis-en un).
|
||||
- `ADMIN_PASSWORD` : protege l'ecran Parametres de l'appli. Tu le taperas dans une popup du navigateur.
|
||||
- `BRAIN_INTERNAL_SECRET` : secret interne partage entre les services. Genere une valeur aleatoire :
|
||||
- **Docker Desktop** ([Windows](https://www.docker.com/products/docker-desktop/) /
|
||||
[Mac](https://www.docker.com/products/docker-desktop/)) ou
|
||||
**Docker Engine + Compose v2** (Linux). Verification :
|
||||
```
|
||||
openssl rand -hex 32
|
||||
docker --version
|
||||
docker compose version
|
||||
```
|
||||
(Sous Windows sans openssl : utilise un generateur en ligne type "random hex string 64 chars".)
|
||||
Compose v2 est requis : la commande est `docker compose`, non `docker-compose`.
|
||||
|
||||
Sans ces trois variables, `docker compose up` refusera de demarrer — c'est volontaire pour eviter un deploiement non-securise par defaut.
|
||||
- **Un fournisseur LLM**, au choix :
|
||||
- **[Ollama](https://ollama.com/)** installe sur la machine hote (gratuit,
|
||||
local, necessite environ 6 Go de RAM libre pour les modeles recommandes).
|
||||
- **Une cle API [1min.ai](https://1min.ai)** (hebergement cloud, facturation
|
||||
a l'usage, aucune installation supplementaire requise).
|
||||
|
||||
3. Dans un terminal, place-toi dans le dossier et lance :
|
||||
```
|
||||
docker compose up -d
|
||||
```
|
||||
Le premier demarrage telecharge les images (~500 Mo) et initialise la base. Compte 1-2 minutes.
|
||||
- Environ **2 Go d'espace disque** pour les images Docker, auxquels s'ajoute
|
||||
la taille des modeles Ollama si l'option locale est retenue.
|
||||
|
||||
4. Ouvre http://localhost:8081 dans ton navigateur. Bon jeu !
|
||||
## 2. Recuperation des fichiers
|
||||
|
||||
## Mise a jour
|
||||
Telecharger les deux fichiers suivants depuis la
|
||||
[derniere release](https://git.igmlcreation.fr/ietm64/LoreMindMJ/releases) et
|
||||
les placer dans un dossier dedie (par exemple `~/loremind/` ou
|
||||
`C:\Programs\loremind\`) :
|
||||
|
||||
- `docker-compose.yml`
|
||||
- `.env.example`
|
||||
|
||||
Le code source n'est pas necessaire : les images sont pre-construites et
|
||||
publiees sur le registry Gitea `git.igmlcreation.fr` (non Docker Hub). Le
|
||||
premier `docker compose pull` les telechargera automatiquement.
|
||||
|
||||
## 3. Configuration du fichier `.env`
|
||||
|
||||
Renommer `.env.example` en `.env` et l'ouvrir dans un editeur de texte. **Trois
|
||||
variables sont obligatoires** ; sans elles, `docker compose up` refusera de
|
||||
demarrer. Ce comportement est volontaire afin d'eviter tout deploiement
|
||||
non-securise par defaut.
|
||||
|
||||
### `POSTGRES_PASSWORD`
|
||||
|
||||
Mot de passe de la base de donnees PostgreSQL. Choisir une valeur robuste.
|
||||
Seuls les conteneurs utilisent cette valeur : il n'est pas necessaire de la
|
||||
memoriser au-dela du fichier `.env`.
|
||||
|
||||
### `ADMIN_PASSWORD`
|
||||
|
||||
Protege l'ecran **Parametres** de l'application via HTTP Basic. Cette valeur
|
||||
sera demandee par le navigateur lors de toute modification de la configuration
|
||||
(changement de modele LLM, saisie de cle API, etc.). Le nom d'utilisateur par
|
||||
defaut est `admin`, modifiable via la variable `ADMIN_USERNAME`.
|
||||
|
||||
### `BRAIN_INTERNAL_SECRET`
|
||||
|
||||
Secret partage entre le service Java (`core`) et le service Python (`brain`).
|
||||
Empeche toute requete externe d'atteindre directement le service Brain.
|
||||
Generer une valeur aleatoire de 64 caracteres hexadecimaux :
|
||||
|
||||
```
|
||||
openssl rand -hex 32
|
||||
```
|
||||
|
||||
Sous Windows sans `openssl`, utiliser PowerShell :
|
||||
|
||||
```powershell
|
||||
-join ((48..57) + (97..102) | Get-Random -Count 64 | % {[char]$_})
|
||||
```
|
||||
|
||||
### Variables optionnelles
|
||||
|
||||
- `WEB_PORT` (defaut `8081`) : port d'ecoute de l'interface web.
|
||||
- `ADMIN_USERNAME` (defaut `admin`) : identifiant de la popup Parametres.
|
||||
- `LLM_PROVIDER` (defaut `ollama`) : choix du fournisseur LLM (voir
|
||||
section 5).
|
||||
|
||||
Les autres variables (`MINIO_USER`/`MINIO_PASSWORD`, `POSTGRES_DB`,
|
||||
`POSTGRES_USER`) disposent de valeurs par defaut adaptees a un deploiement
|
||||
personnel et peuvent etre conservees en l'etat.
|
||||
|
||||
## 4. Lancement de la stack
|
||||
|
||||
Depuis le dossier contenant `docker-compose.yml` et `.env` :
|
||||
|
||||
```
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Le premier demarrage telecharge les images (environ 1 a 2 Go au total) et
|
||||
initialise la base. Compter 2 a 5 minutes selon la qualite de la connexion.
|
||||
La progression peut etre suivie via :
|
||||
|
||||
```
|
||||
docker compose logs -f
|
||||
```
|
||||
|
||||
(`Ctrl+C` pour quitter l'affichage ; les services continuent de fonctionner
|
||||
en arriere-plan.)
|
||||
|
||||
Une fois les services en etat `healthy`, ouvrir **http://localhost:8081**
|
||||
dans un navigateur.
|
||||
|
||||
### Verification du fonctionnement
|
||||
|
||||
```
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
Cinq conteneurs doivent apparaitre en etat `Up` ou `healthy` :
|
||||
`loremind-postgres`, `loremind-minio`, `loremind-core`, `loremind-brain`,
|
||||
`loremind-web`. Le conteneur `loremind-minio-init` s'arrete automatiquement
|
||||
apres creation du bucket d'images : ce comportement est normal.
|
||||
|
||||
## 5. Configuration du fournisseur LLM
|
||||
|
||||
### Ollama (local, gratuit)
|
||||
|
||||
Installer Ollama sur la machine hote (pas dans Docker), puis telecharger un
|
||||
modele :
|
||||
|
||||
```
|
||||
ollama pull gemma4:26b
|
||||
```
|
||||
|
||||
Dans `.env` :
|
||||
|
||||
```
|
||||
LLM_PROVIDER=ollama
|
||||
LLM_MODEL=gemma4:26b
|
||||
OLLAMA_BASE_URL=http://host.docker.internal:11434
|
||||
```
|
||||
|
||||
L'adresse `host.docker.internal` permet au conteneur `brain` d'atteindre
|
||||
Ollama sur la machine hote. Cette resolution est native sous Docker Desktop
|
||||
(Mac / Windows). Sous Linux, le fichier `docker-compose.yml` declare un
|
||||
`extra_hosts` equivalent.
|
||||
|
||||
### 1min.ai (cloud, paye)
|
||||
|
||||
Dans `.env` :
|
||||
|
||||
```
|
||||
LLM_PROVIDER=onemin
|
||||
ONEMIN_API_KEY=sk-...
|
||||
ONEMIN_MODEL=gpt-4o-mini
|
||||
```
|
||||
|
||||
### Modification a chaud
|
||||
|
||||
Le fournisseur, le modele et la cle API peuvent etre modifies a chaud depuis
|
||||
l'ecran **Parametres** de l'application. Les modifications sont persistees
|
||||
dans un volume Docker et survivent aux redemarrages. Les variables d'env du
|
||||
fichier `.env` sont uniquement utilisees comme valeurs initiales au premier
|
||||
demarrage.
|
||||
|
||||
## 6. Mise a jour
|
||||
|
||||
```
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Les donnees (base Postgres, images MinIO, settings Brain) sont dans des volumes Docker et survivent aux mises a jour.
|
||||
Les donnees (base PostgreSQL, images MinIO, configuration Brain) sont
|
||||
stockees dans des volumes Docker et survivent aux mises a jour.
|
||||
|
||||
## LLM : Ollama ou 1min.ai ?
|
||||
## 7. Sauvegarde
|
||||
|
||||
**Ollama (local, gratuit)** — Edite `.env` :
|
||||
```
|
||||
LLM_PROVIDER=ollama
|
||||
LLM_MODEL=gemma4:26b
|
||||
```
|
||||
Telecharge le modele au prealable : `ollama pull gemma4:26b`.
|
||||
Les donnees sont reparties dans trois volumes Docker :
|
||||
|
||||
**1min.ai (cloud, paye)** — Edite `.env` :
|
||||
```
|
||||
LLM_PROVIDER=onemin
|
||||
ONEMIN_API_KEY=sk-...
|
||||
ONEMIN_MODEL=open-mistral-nemo
|
||||
```
|
||||
- `loremindmj_postgres-data` — ensemble des donnees applicatives (lores,
|
||||
campagnes, pages, templates, branches narratives, etc.).
|
||||
- `loremindmj_minio-data` — images uploadees.
|
||||
- `loremindmj_brain-data` — parametres IA (fournisseur courant, cle API
|
||||
1min.ai).
|
||||
|
||||
Tu peux aussi changer tout ca a chaud depuis l'ecran Parametres de l'appli.
|
||||
### Export SQL de la base
|
||||
|
||||
## Problemes frequents
|
||||
|
||||
- **Port 8081 deja pris** : change `WEB_PORT=8082` (ou autre) dans `.env`.
|
||||
- **Ollama injoignable** : verifie qu'Ollama tourne (`ollama serve`) et que le modele est bien telecharge.
|
||||
- **"set ADMIN_PASSWORD in .env" / "set BRAIN_INTERNAL_SECRET in .env"** au lancement : tu as oublie une des variables obligatoires de l'etape 2.
|
||||
- **Popup "Ce site vous demande de vous connecter" sur l'ecran Parametres** : c'est normal. Utilise `admin` (ou ce que tu as mis dans `ADMIN_USERNAME`) et ton `ADMIN_PASSWORD`.
|
||||
- **Tout casser et repartir de zero** : `docker compose down -v` supprime les volumes (attention, perte de donnees).
|
||||
|
||||
## Sauvegarde
|
||||
|
||||
Les donnees sont dans les volumes Docker : `loremindmj_postgres-data`, `loremindmj_minio-data`, `loremindmj_brain-data`.
|
||||
|
||||
Sauvegarde rapide de la base :
|
||||
```
|
||||
docker compose exec postgres pg_dump -U loremind loremind > backup.sql
|
||||
```
|
||||
|
||||
### Sauvegarde complete des volumes
|
||||
|
||||
Arreter la stack au prealable afin de garantir la coherence des donnees :
|
||||
|
||||
```
|
||||
docker compose stop
|
||||
docker run --rm -v loremindmj_postgres-data:/data -v $(pwd):/backup alpine tar czf /backup/postgres-data.tar.gz -C /data .
|
||||
docker run --rm -v loremindmj_minio-data:/data -v $(pwd):/backup alpine tar czf /backup/minio-data.tar.gz -C /data .
|
||||
docker compose start
|
||||
```
|
||||
|
||||
Sous Windows PowerShell, remplacer `$(pwd)` par `${PWD}`.
|
||||
|
||||
## 8. Resolution des problemes
|
||||
|
||||
### Port 8081 deja utilise
|
||||
|
||||
Modifier `WEB_PORT=8082` (ou toute autre valeur libre) dans `.env`, puis
|
||||
relancer :
|
||||
|
||||
```
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### Erreur "set POSTGRES_PASSWORD in .env" (ou variable equivalente) au lancement
|
||||
|
||||
Une des trois variables obligatoires de l'etape 3 est manquante. Verifier le
|
||||
contenu du fichier `.env`.
|
||||
|
||||
### Popup "Ce site vous demande de vous connecter" sur l'ecran Parametres
|
||||
|
||||
Comportement attendu : il s'agit de l'authentification HTTP Basic. Utiliser
|
||||
la valeur de `ADMIN_USERNAME` (par defaut `admin`) et celle de
|
||||
`ADMIN_PASSWORD`.
|
||||
|
||||
### Erreurs `password authentication failed` en boucle dans les logs Postgres
|
||||
|
||||
Si la variable `POSTGRES_PASSWORD` a ete modifiee apres un premier lancement,
|
||||
le volume Postgres conserve l'ancien mot de passe (initialise une seule fois).
|
||||
Deux options :
|
||||
|
||||
- **Redemarrer avec un volume vierge** (entraine la perte des donnees) :
|
||||
```
|
||||
docker compose down -v
|
||||
docker compose up -d
|
||||
```
|
||||
- **Modifier le mot de passe en base** sans toucher au volume :
|
||||
```
|
||||
docker compose exec postgres psql -U postgres
|
||||
```
|
||||
Puis dans le prompt `psql` :
|
||||
```sql
|
||||
ALTER USER loremind WITH PASSWORD 'valeur_exacte_du_env';
|
||||
\q
|
||||
```
|
||||
Redemarrer ensuite le Core : `docker compose restart core`.
|
||||
|
||||
### Erreur "502 Bad Gateway" ou message d'erreur IA dans l'interface
|
||||
|
||||
Le service Brain ne parvient pas a contacter le fournisseur LLM. Verifier :
|
||||
|
||||
- **Ollama** : `ollama serve` est-il actif ? Le modele est-il telecharge
|
||||
(`ollama list`) ? La valeur de `LLM_MODEL` correspond-elle exactement au
|
||||
nom d'un modele liste ?
|
||||
- **1min.ai** : la cle API est-elle valide ? Le modele existe-t-il ?
|
||||
- Consulter les logs du Brain :
|
||||
```
|
||||
docker compose logs brain
|
||||
```
|
||||
|
||||
### Un service ne demarre pas ou reste en etat `unhealthy`
|
||||
|
||||
Consulter les logs du service concerne :
|
||||
|
||||
```
|
||||
docker compose logs <service>
|
||||
```
|
||||
|
||||
Services disponibles : `postgres`, `minio`, `core`, `brain`, `web`.
|
||||
|
||||
### Redemarrage d'un service apres modification du `.env`
|
||||
|
||||
```
|
||||
docker compose up -d <service>
|
||||
```
|
||||
|
||||
Redemarrage complet : `docker compose restart`.
|
||||
|
||||
### Remise a zero complete (PERTE DES DONNEES)
|
||||
|
||||
```
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
L'option `-v` supprime les volumes. L'ensemble des lores, campagnes, images
|
||||
et parametres est perdu de maniere definitive.
|
||||
|
||||
### "No such image" ou "pull access denied" au premier lancement
|
||||
|
||||
Le registry Gitea peut necessiter une authentification selon la visibilite
|
||||
configuree pour les images. Contacter l'editeur du projet.
|
||||
|
||||
## 9. Exposition reseau des services
|
||||
|
||||
- **Interface web** : http://localhost:8081 (port configurable via
|
||||
`WEB_PORT`).
|
||||
- **PostgreSQL** : accessible uniquement via le reseau Docker interne, non
|
||||
expose vers l'hote.
|
||||
- **MinIO** : accessible uniquement via le reseau Docker interne. Les images
|
||||
transitent par le reverse-proxy Java sur `/api/images/{id}/content`. Le
|
||||
binding `127.0.0.1:9000/9001` defini dans `docker-compose.override.yml`
|
||||
n'est actif qu'en developpement.
|
||||
- **Brain Python** : accessible uniquement via le reseau Docker interne.
|
||||
Toute requete doit porter l'en-tete `X-Internal-Secret`, injectee
|
||||
automatiquement par le Core Java et jamais exposee au navigateur.
|
||||
|
||||
## 10. Desinstallation
|
||||
|
||||
```
|
||||
docker compose down -v
|
||||
docker image rm git.igmlcreation.fr/ietm64/core git.igmlcreation.fr/ietm64/brain git.igmlcreation.fr/ietm64/web
|
||||
```
|
||||
|
||||
Supprimer ensuite le dossier contenant `docker-compose.yml` et `.env`.
|
||||
|
||||
@@ -67,4 +67,9 @@ docker compose up -d --build
|
||||
|
||||
## License
|
||||
|
||||
[À définir]
|
||||
LoreMind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
||||
|
||||
En pratique :
|
||||
- Tu peux l'utiliser gratuitement, l'héberger où tu veux, le modifier, le redistribuer.
|
||||
- Si tu modifies le code et que tu exposes l'application modifiée sur un réseau (même en SaaS privé), tu dois rendre tes modifications publiques sous la même licence.
|
||||
- Les univers (Lore) et campagnes que tu crées avec LoreMind **t'appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
||||
|
||||
@@ -20,6 +20,8 @@ from app.domain.models import (
|
||||
CampaignStructuralContext,
|
||||
ChatMessage,
|
||||
ChapterSummary,
|
||||
CharacterSummary,
|
||||
GameSystemContext,
|
||||
LoreStructuralContext,
|
||||
NarrativeEntityContext,
|
||||
PageContext,
|
||||
@@ -63,16 +65,17 @@ class ChatUseCase:
|
||||
page_context: PageContext | None = None,
|
||||
campaign_context: CampaignStructuralContext | None = None,
|
||||
narrative_entity: NarrativeEntityContext | None = None,
|
||||
game_system_context: GameSystemContext | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Streame les tokens de la réponse assistant pour le dernier message user.
|
||||
|
||||
Les 4 contextes sont tous optionnels, mais au moins l'un des deux
|
||||
Les contextes sont tous optionnels, mais au moins l'un des deux
|
||||
"niveaux haut" (lore_context ou campaign_context) doit être fourni
|
||||
pour que le prompt ait du sens. Le controller (main.py) applique
|
||||
cette règle à la frontière HTTP.
|
||||
"""
|
||||
system_prompt = self._build_system_prompt(
|
||||
lore_context, page_context, campaign_context, narrative_entity
|
||||
lore_context, page_context, campaign_context, narrative_entity, game_system_context
|
||||
)
|
||||
async for token in self._llm.stream_chat(
|
||||
messages,
|
||||
@@ -81,6 +84,21 @@ class ChatUseCase:
|
||||
):
|
||||
yield token
|
||||
|
||||
def build_system_prompt(
|
||||
self,
|
||||
lore_context: LoreStructuralContext | None = None,
|
||||
page_context: PageContext | None = None,
|
||||
campaign_context: CampaignStructuralContext | None = None,
|
||||
narrative_entity: NarrativeEntityContext | None = None,
|
||||
game_system_context: GameSystemContext | None = None,
|
||||
) -> str:
|
||||
"""Version publique — utilisée par le controller HTTP pour compter
|
||||
les tokens du system prompt avant de streamer (jauge de contexte).
|
||||
"""
|
||||
return self._build_system_prompt(
|
||||
lore_context, page_context, campaign_context, narrative_entity, game_system_context
|
||||
)
|
||||
|
||||
# --- Construction du system prompt --------------------------------------
|
||||
|
||||
def _build_system_prompt(
|
||||
@@ -89,12 +107,15 @@ class ChatUseCase:
|
||||
page: PageContext | None,
|
||||
campaign: CampaignStructuralContext | None,
|
||||
narrative: NarrativeEntityContext | None,
|
||||
game_system: GameSystemContext | None = None,
|
||||
) -> str:
|
||||
sections = [_BASE_SYSTEM]
|
||||
if lore is not None:
|
||||
sections.append(self._format_lore(lore))
|
||||
if campaign is not None:
|
||||
sections.append(self._format_campaign(campaign, lore_present=lore is not None))
|
||||
if game_system is not None:
|
||||
sections.append(self._format_game_system(game_system))
|
||||
if page is not None:
|
||||
sections.append(self._format_page(page))
|
||||
if narrative is not None:
|
||||
@@ -176,14 +197,40 @@ class ChatUseCase:
|
||||
if lore_present
|
||||
else "\n(Cette campagne n'est associée à aucun univers — tu peux proposer des éléments d'ambiance libres.)"
|
||||
)
|
||||
characters_block = ChatUseCase._format_characters(ctx.characters)
|
||||
return (
|
||||
"--- CAMPAGNE COURANTE ---\n"
|
||||
f"Nom : {ctx.campaign_name}{desc}{lore_note}\n\n"
|
||||
f"Nom : {ctx.campaign_name}{desc}{lore_note}\n"
|
||||
f"{characters_block}\n"
|
||||
"Structure narrative (les flèches → indiquent des transitions de scène "
|
||||
"déclenchées par un choix des joueurs) :\n"
|
||||
f"{arcs_block}"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _format_characters(characters: list[CharacterSummary]) -> str:
|
||||
"""Bloc PJ — liste nom + snippet. Rappel anti-hallucination IA.
|
||||
|
||||
Si la campagne n'a aucun PJ, on le signale explicitement : l'IA ne
|
||||
doit pas inventer "les héros" ou leurs noms dans ses suggestions.
|
||||
"""
|
||||
if not characters:
|
||||
return (
|
||||
"\nPersonnages joueurs : aucune fiche pour l'instant. Ne suppose "
|
||||
"ni noms ni classes pour les PJ tant que le MJ ne les a pas créés.\n"
|
||||
)
|
||||
lines = ["\nPersonnages joueurs (PJ) :"]
|
||||
for c in characters:
|
||||
if c.snippet:
|
||||
lines.append(f"- **{c.name}** — {c.snippet}")
|
||||
else:
|
||||
lines.append(f"- **{c.name}** (fiche vide)")
|
||||
lines.append(
|
||||
"Pour une fiche complète (stats, backstory), n'invente rien : "
|
||||
"demande au MJ d'ouvrir l'éditeur du PJ pour te donner les détails."
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
@staticmethod
|
||||
def _format_arcs(arcs: list[ArcSummary]) -> str:
|
||||
if not arcs:
|
||||
@@ -234,12 +281,46 @@ class ChatUseCase:
|
||||
noun = "illustration" if count == 1 else "illustrations"
|
||||
return f" [{count} {noun}]"
|
||||
|
||||
# --- Bloc Système de JDR ------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _format_game_system(gs: GameSystemContext) -> str:
|
||||
"""Bloc des règles du système de JDR de la campagne.
|
||||
|
||||
Les sections ont été filtrées côté Core selon l'intent (combat,
|
||||
classes, lore...). Si aucune section n'a matché, on affiche juste
|
||||
le nom du système comme rappel de cadre.
|
||||
"""
|
||||
desc = f"\nDescription : {gs.system_description}" if gs.system_description else ""
|
||||
if not gs.sections:
|
||||
return (
|
||||
"--- SYSTÈME DE JDR ---\n"
|
||||
f"Nom : {gs.system_name}{desc}\n"
|
||||
"(Aucune section de règles pertinente pour ce type de génération — "
|
||||
"reste cohérent avec l'univers et les conventions du système.)"
|
||||
)
|
||||
sections_block = "\n\n".join(
|
||||
f"### {title}\n{content}" for title, content in gs.sections.items()
|
||||
)
|
||||
return (
|
||||
"--- SYSTÈME DE JDR ---\n"
|
||||
f"Nom : {gs.system_name}{desc}\n\n"
|
||||
"Respecte scrupuleusement les règles et conventions ci-dessous quand "
|
||||
"tu proposes des stats, classes, rencontres, mécaniques ou éléments "
|
||||
"d'ambiance. Les noms propres (classes, sorts, monstres) doivent "
|
||||
"venir de ces règles — n'en invente pas d'autres.\n\n"
|
||||
f"{sections_block}"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _format_narrative_entity(ne: NarrativeEntityContext) -> str:
|
||||
"""Bloc équivalent à _format_page mais pour Arc/Chapter/Scene."""
|
||||
type_label = {"arc": "ARC", "chapter": "CHAPITRE", "scene": "SCÈNE"}.get(
|
||||
ne.entity_type.lower(), ne.entity_type.upper()
|
||||
)
|
||||
type_label = {
|
||||
"arc": "ARC",
|
||||
"chapter": "CHAPITRE",
|
||||
"scene": "SCÈNE",
|
||||
"character": "FICHE DE PERSONNAGE",
|
||||
}.get(ne.entity_type.lower(), ne.entity_type.upper())
|
||||
if ne.fields:
|
||||
fields_block = "\n".join(
|
||||
f'- "{key}" : {value or "(vide)"}'
|
||||
|
||||
@@ -169,6 +169,20 @@ class CampaignStructuralContext:
|
||||
campaign_name: str
|
||||
campaign_description: str | None
|
||||
arcs: list[ArcSummary]
|
||||
characters: list["CharacterSummary"] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CharacterSummary:
|
||||
"""Résumé d'un PJ : nom + snippet court extrait du markdown de la fiche.
|
||||
|
||||
La fiche complète n'est JAMAIS dans ce résumé — elle n'arrive que si le PJ
|
||||
est l'entité focus (via NarrativeEntityContext entity_type="character").
|
||||
Ça plafonne le coût token à ~40 tokens/PJ quel que soit le détail des fiches.
|
||||
"""
|
||||
|
||||
name: str
|
||||
snippet: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -184,3 +198,20 @@ class NarrativeEntityContext:
|
||||
entity_type: str
|
||||
title: str
|
||||
fields: dict[str, str]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GameSystemContext:
|
||||
"""Règles d'un système de JDR (D&D, Nimble, homebrew...) injectées
|
||||
dans le system prompt pour que l'IA respecte les mécaniques du jeu.
|
||||
|
||||
Les sections ont été présélectionnées côté Core selon l'intent
|
||||
(SCENE → combat/PNJ, CHAPTER → combat/classes, ARC → lore/factions,
|
||||
GENERIC → toutes). Indexées par titre H2 original.
|
||||
|
||||
Campagne uniquement au MVP : jamais présent sur un chat Lore.
|
||||
"""
|
||||
|
||||
system_name: str
|
||||
system_description: str | None
|
||||
sections: dict[str, str]
|
||||
|
||||
@@ -9,6 +9,7 @@ from typing import Annotated, AsyncIterator, Literal
|
||||
|
||||
import hmac
|
||||
import httpx
|
||||
import tiktoken
|
||||
from fastapi import Depends, FastAPI, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -21,7 +22,9 @@ from app.domain.models import (
|
||||
ArcSummary,
|
||||
CampaignStructuralContext,
|
||||
ChapterSummary,
|
||||
CharacterSummary,
|
||||
ChatMessage,
|
||||
GameSystemContext,
|
||||
LoreStructuralContext,
|
||||
NarrativeEntityContext,
|
||||
PageContext,
|
||||
@@ -37,10 +40,27 @@ from app.infrastructure.onemin_adapter import OneMinAiLLMProvider
|
||||
app = FastAPI(
|
||||
title="LoreMind Brain",
|
||||
description="Backend IA pour la génération de contenu narratif.",
|
||||
version="0.2.0",
|
||||
version="0.6.0",
|
||||
)
|
||||
|
||||
|
||||
# Encodeur tiktoken partagé — chargé une fois pour éviter le coût de lookup
|
||||
# à chaque requête. On utilise cl100k_base (GPT-3.5/4) comme tokenizer
|
||||
# universel approximatif : ±10% d'écart avec Llama/Gemma mais largement
|
||||
# suffisant pour une jauge visuelle à l'utilisateur.
|
||||
_TOKEN_ENCODER: tiktoken.Encoding | None = None
|
||||
|
||||
|
||||
def _count_tokens(text: str | None) -> int:
|
||||
"""Compte les tokens d'un texte via tiktoken. Null/empty → 0."""
|
||||
if not text:
|
||||
return 0
|
||||
global _TOKEN_ENCODER
|
||||
if _TOKEN_ENCODER is None:
|
||||
_TOKEN_ENCODER = tiktoken.get_encoding("cl100k_base")
|
||||
return len(_TOKEN_ENCODER.encode(text))
|
||||
|
||||
|
||||
# Chemins exemptes d'auth inter-service : healthcheck docker + introspection
|
||||
# FastAPI (docs uniquement utiles en dev ; en prod docker-compose, le Brain
|
||||
# n'est pas expose en dehors du reseau interne donc pas un risque).
|
||||
@@ -178,22 +198,42 @@ class ArcSummaryDTO(BaseModel):
|
||||
illustration_count: int = 0
|
||||
|
||||
|
||||
class CharacterSummaryDTO(BaseModel):
|
||||
"""Résumé d'un PJ : nom + snippet. Pas de fiche complète au niveau résumé."""
|
||||
|
||||
name: str
|
||||
snippet: str = ""
|
||||
|
||||
|
||||
class CampaignContextDTO(BaseModel):
|
||||
"""Carte narrative enrichie : arcs → chapitres → scènes avec synopsis."""
|
||||
|
||||
campaign_name: str
|
||||
campaign_description: str | None = None
|
||||
arcs: list[ArcSummaryDTO] = Field(default_factory=list)
|
||||
characters: list[CharacterSummaryDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class NarrativeEntityDTO(BaseModel):
|
||||
"""Entité narrative (arc/chapter/scene) en cours d'édition — focus optionnel."""
|
||||
"""Entité narrative (arc/chapter/scene/character) en cours d'édition — focus optionnel."""
|
||||
|
||||
entity_type: str = Field(pattern="^(arc|chapter|scene)$")
|
||||
entity_type: str = Field(pattern="^(arc|chapter|scene|character)$")
|
||||
title: str
|
||||
fields: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class GameSystemContextDTO(BaseModel):
|
||||
"""Règles de JDR présélectionnées par le Core (filtrées par intent).
|
||||
|
||||
Les sections sont un dict titre_H2 → contenu_markdown. Peuvent être
|
||||
vides si aucune section ne matchait l'intent de génération courant.
|
||||
"""
|
||||
|
||||
system_name: str
|
||||
system_description: str | None = None
|
||||
sections: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class ChatStreamRequestDTO(BaseModel):
|
||||
"""Requête de chat streamé : historique + contextes structurels.
|
||||
|
||||
@@ -208,6 +248,7 @@ class ChatStreamRequestDTO(BaseModel):
|
||||
page_context: PageContextDTO | None = None
|
||||
campaign_context: CampaignContextDTO | None = None
|
||||
narrative_entity: NarrativeEntityDTO | None = None
|
||||
game_system_context: GameSystemContextDTO | None = None
|
||||
|
||||
def has_scope(self) -> bool:
|
||||
"""Vrai si au moins un contexte racine (Lore ou Campagne) est fourni."""
|
||||
@@ -334,8 +375,35 @@ async def chat_stream(
|
||||
page_context = _to_page_context(body.page_context)
|
||||
campaign_context = _to_campaign_context(body.campaign_context)
|
||||
narrative_entity = _to_narrative_entity(body.narrative_entity)
|
||||
game_system_context = _to_game_system_context(body.game_system_context)
|
||||
|
||||
# --- Comptage tokens pour la jauge de contexte frontend ---
|
||||
# On construit le system prompt une fois ici pour le compter — le use case
|
||||
# le reconstruira à l'identique en interne (coût négligeable : concat de str).
|
||||
# Cette duplication évite de complexifier le contrat stream() avec un
|
||||
# paramètre optionnel system_prompt précalculé.
|
||||
system_prompt_preview = use_case.build_system_prompt(
|
||||
lore_context=lore_context,
|
||||
page_context=page_context,
|
||||
campaign_context=campaign_context,
|
||||
narrative_entity=narrative_entity,
|
||||
game_system_context=game_system_context,
|
||||
)
|
||||
# Dernier message = "current" (souvent user), le reste = historique accumulé.
|
||||
current_msg = messages[-1] if messages else None
|
||||
history_msgs = messages[:-1] if messages else []
|
||||
settings = get_settings()
|
||||
usage_payload = {
|
||||
"system": _count_tokens(system_prompt_preview),
|
||||
"history": sum(_count_tokens(m.content) for m in history_msgs),
|
||||
"current": _count_tokens(current_msg.content) if current_msg else 0,
|
||||
"max": settings.llm_num_ctx,
|
||||
}
|
||||
|
||||
async def event_stream() -> AsyncIterator[str]:
|
||||
# Event 'usage' émis en tout premier : le frontend peut afficher la
|
||||
# jauge avant même le premier token de réponse.
|
||||
yield f"event: usage\ndata: {json.dumps(usage_payload, ensure_ascii=False)}\n\n"
|
||||
try:
|
||||
async for token in use_case.stream(
|
||||
messages,
|
||||
@@ -343,6 +411,7 @@ async def chat_stream(
|
||||
page_context=page_context,
|
||||
campaign_context=campaign_context,
|
||||
narrative_entity=narrative_entity,
|
||||
game_system_context=game_system_context,
|
||||
):
|
||||
# json.dumps avec ensure_ascii=False pour préserver les accents
|
||||
yield f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
||||
@@ -353,6 +422,60 @@ async def chat_stream(
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
|
||||
|
||||
# --- Auto-titre d'une conversation persistee --------------------------------
|
||||
|
||||
|
||||
class SummarizeTitleMessageDTO(BaseModel):
|
||||
role: Literal["user", "assistant", "system"]
|
||||
content: str
|
||||
|
||||
|
||||
class SummarizeTitleRequestDTO(BaseModel):
|
||||
"""Premiers messages d'une conversation pour auto-generer un titre court."""
|
||||
|
||||
messages: list[SummarizeTitleMessageDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SummarizeTitleResponseDTO(BaseModel):
|
||||
title: str
|
||||
|
||||
|
||||
_TITLE_SYSTEM_PROMPT = (
|
||||
"Tu generes un titre court (4 a 7 mots max) qui resume le sujet de la "
|
||||
"conversation ci-dessous. Reponds UNIQUEMENT par le titre, sans guillemets, "
|
||||
"sans ponctuation finale, sans prefixe type 'Titre :'. Le titre doit etre "
|
||||
"en francais et capturer le sujet metier (pas 'Conversation IA')."
|
||||
)
|
||||
|
||||
|
||||
@app.post("/summarize/conversation-title", response_model=SummarizeTitleResponseDTO)
|
||||
async def summarize_conversation_title(
|
||||
body: SummarizeTitleRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> SummarizeTitleResponseDTO:
|
||||
"""Genere un titre court a partir des premiers echanges de la conversation.
|
||||
|
||||
Appele par le core apres le 1er couple user/assistant, pour remplacer le
|
||||
titre provisoire "Nouvelle conversation" par quelque chose de parlant.
|
||||
"""
|
||||
if not body.messages:
|
||||
raise HTTPException(status_code=422, detail="Au moins un message requis")
|
||||
|
||||
transcript = "\n".join(f"{m.role.upper()}: {m.content}" for m in body.messages[:6])
|
||||
prompt = f"{_TITLE_SYSTEM_PROMPT}\n\nConversation :\n{transcript}\n\nTitre :"
|
||||
try:
|
||||
raw = await llm.generate(prompt)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
title = raw.strip().splitlines()[0].strip().strip('"').strip("'").rstrip(".")
|
||||
if len(title) > 80:
|
||||
title = title[:80].rstrip()
|
||||
if not title:
|
||||
title = "Nouvelle conversation"
|
||||
return SummarizeTitleResponseDTO(title=title)
|
||||
|
||||
|
||||
# --- Mapping DTO → domaine (frontière HTTP) ---------------------------------
|
||||
|
||||
|
||||
@@ -426,10 +549,15 @@ def _to_campaign_context(dto: CampaignContextDTO | None) -> CampaignStructuralCo
|
||||
)
|
||||
for arc in dto.arcs
|
||||
]
|
||||
characters = [
|
||||
CharacterSummary(name=c.name, snippet=c.snippet)
|
||||
for c in dto.characters
|
||||
]
|
||||
return CampaignStructuralContext(
|
||||
campaign_name=dto.campaign_name,
|
||||
campaign_description=dto.campaign_description,
|
||||
arcs=arcs,
|
||||
characters=characters,
|
||||
)
|
||||
|
||||
|
||||
@@ -449,6 +577,9 @@ class SettingsDTO(BaseModel):
|
||||
onemin_model: str
|
||||
# True si une cle 1min.ai est deja configuree — pas de leak de la cle elle-meme.
|
||||
onemin_api_key_set: bool
|
||||
# Fenetre de contexte effective passee au modele (num_ctx Ollama) — sert
|
||||
# aussi de plafond a la jauge de contexte UI.
|
||||
llm_num_ctx: int
|
||||
|
||||
|
||||
class SettingsUpdateDTO(BaseModel):
|
||||
@@ -460,6 +591,7 @@ class SettingsUpdateDTO(BaseModel):
|
||||
onemin_model: str | None = None
|
||||
# Chaine vide => on efface la cle. None => pas de changement.
|
||||
onemin_api_key: str | None = None
|
||||
llm_num_ctx: int | None = None
|
||||
|
||||
|
||||
def _to_settings_dto(s: Settings) -> SettingsDTO:
|
||||
@@ -469,6 +601,7 @@ def _to_settings_dto(s: Settings) -> SettingsDTO:
|
||||
llm_model=s.llm_model,
|
||||
onemin_model=s.onemin_model,
|
||||
onemin_api_key_set=bool(s.onemin_api_key),
|
||||
llm_num_ctx=s.llm_num_ctx,
|
||||
)
|
||||
|
||||
|
||||
@@ -512,6 +645,50 @@ async def list_ollama_models(
|
||||
return {"models": sorted(models)}
|
||||
|
||||
|
||||
class OllamaModelInfoDTO(BaseModel):
|
||||
"""Info utile extraite de /api/show pour un modele Ollama donne.
|
||||
|
||||
`context_length` = fenetre de contexte max supportee par le modele
|
||||
(extraite des metadonnees GGUF). 0 si inconnue. Le frontend s'en sert
|
||||
pour borner le slider de num_ctx dans les Parametres.
|
||||
"""
|
||||
|
||||
context_length: int = 0
|
||||
|
||||
|
||||
@app.post("/models/ollama/info", response_model=OllamaModelInfoDTO)
|
||||
async def get_ollama_model_info(
|
||||
body: dict[str, str],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> OllamaModelInfoDTO:
|
||||
"""Retourne les metadonnees d'un modele Ollama via /api/show.
|
||||
|
||||
On passe par POST (et pas GET /models/ollama/{name}) parce que les noms
|
||||
Ollama contiennent souvent un `:` (ex: `gemma3:e2b`) qui se segmente
|
||||
mal dans une URL — le body JSON evite le probleme d'escaping.
|
||||
|
||||
Le champ qui nous interesse est `model_info["<arch>.context_length"]`
|
||||
(ex: `gemma3.context_length: 131072`). L'arch varie selon le modele, on
|
||||
scanne donc tous les champs finissant par `.context_length`.
|
||||
"""
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="name requis")
|
||||
url = f"{settings.ollama_base_url}/api/show"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
response = await client.post(url, json={"model": name})
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except httpx.HTTPError:
|
||||
return OllamaModelInfoDTO(context_length=0)
|
||||
model_info = data.get("model_info") or {}
|
||||
for key, value in model_info.items():
|
||||
if key.endswith(".context_length") and isinstance(value, int):
|
||||
return OllamaModelInfoDTO(context_length=value)
|
||||
return OllamaModelInfoDTO(context_length=0)
|
||||
|
||||
|
||||
@app.get("/models/onemin")
|
||||
def list_onemin_models() -> dict[str, list[dict[str, object]]]:
|
||||
"""Catalogue statique des modeles 1min.ai, groupes par fournisseur.
|
||||
@@ -596,3 +773,13 @@ def _to_narrative_entity(dto: NarrativeEntityDTO | None) -> NarrativeEntityConte
|
||||
title=dto.title,
|
||||
fields=dict(dto.fields),
|
||||
)
|
||||
|
||||
|
||||
def _to_game_system_context(dto: GameSystemContextDTO | None) -> GameSystemContext | None:
|
||||
if dto is None:
|
||||
return None
|
||||
return GameSystemContext(
|
||||
system_name=dto.system_name,
|
||||
system_description=dto.system_description,
|
||||
sections=dict(dto.sections),
|
||||
)
|
||||
|
||||
@@ -4,3 +4,9 @@ httpx==0.27.*
|
||||
pydantic-settings==2.6.*
|
||||
|
||||
pydantic
|
||||
|
||||
# Comptage de tokens pour la jauge de contexte (UI chat drawer).
|
||||
# L'encodage cl100k_base (GPT-4/3.5) donne une approximation correcte pour
|
||||
# la plupart des modeles Llama/Gemma/Mistral (~5-10% d'ecart) — suffisant
|
||||
# pour une jauge visuelle.
|
||||
tiktoken==0.8.*
|
||||
|
||||
11
core/lombok.config
Normal file
11
core/lombok.config
Normal file
@@ -0,0 +1,11 @@
|
||||
## LoreMind Core - Configuration Lombok
|
||||
#
|
||||
# addLombokGeneratedAnnotation : ajoute @lombok.Generated sur toutes les
|
||||
# methodes generees par Lombok (equals, hashCode, toString, builders,
|
||||
# getters/setters, etc.). JaCoCo 0.8.2+ reconnait cette annotation et
|
||||
# exclut automatiquement ces methodes du rapport de couverture.
|
||||
#
|
||||
# Objectif : mesurer la couverture UNIQUEMENT sur le code que nous ecrivons,
|
||||
# pas sur le bytecode auto-genere (qui fausse les metriques : branches et
|
||||
# instructions gonflees par les equals/hashCode).
|
||||
lombok.addLombokGeneratedAnnotation = true
|
||||
25
core/pom.xml
25
core/pom.xml
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>0.2.0</version>
|
||||
<version>0.6.0</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
@@ -99,6 +99,29 @@
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<!-- JaCoCo : rapport de couverture des tests unitaires.
|
||||
Rapport HTML auto-genere a chaque `mvn test` dans target/site/jacoco/. -->
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>0.8.12</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>prepare-agent</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -17,11 +21,20 @@ import java.util.Optional;
|
||||
public class ArcService {
|
||||
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
|
||||
public ArcService(ArcRepository arcRepository) {
|
||||
public ArcService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
}
|
||||
|
||||
/** Compte des entités qui seront supprimées en cascade avec l'arc. */
|
||||
public record DeletionImpact(int chapters, int scenes) {}
|
||||
|
||||
public Arc createArc(String name, String description, String campaignId, int order) {
|
||||
Arc arc = Arc.builder()
|
||||
.name(name)
|
||||
@@ -59,7 +72,31 @@ public class ArcService {
|
||||
return arcRepository.save(arc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule l'impact d'une suppression en cascade : chapitres + scènes
|
||||
* qui disparaîtront avec l'arc.
|
||||
*/
|
||||
public DeletionImpact getDeletionImpact(String id) {
|
||||
List<Chapter> chapters = chapterRepository.findByArcId(id);
|
||||
int sceneTotal = 0;
|
||||
for (Chapter chapter : chapters) {
|
||||
sceneTotal += sceneRepository.findByChapterId(chapter.getId()).size();
|
||||
}
|
||||
return new DeletionImpact(chapters.size(), sceneTotal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime l'arc et toutes ses entités dépendantes (chapitres → scènes).
|
||||
* Transactionnel : atomique.
|
||||
*/
|
||||
@Transactional
|
||||
public void deleteArc(String id) {
|
||||
for (Chapter chapter : chapterRepository.findByArcId(id)) {
|
||||
for (var scene : sceneRepository.findByChapterId(chapter.getId())) {
|
||||
sceneRepository.deleteById(scene.getId());
|
||||
}
|
||||
chapterRepository.deleteById(chapter.getId());
|
||||
}
|
||||
arcRepository.deleteById(id);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -16,9 +23,22 @@ import java.util.Optional;
|
||||
public class CampaignService {
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final CharacterRepository characterRepository;
|
||||
|
||||
public CampaignService(CampaignRepository campaignRepository) {
|
||||
public CampaignService(
|
||||
CampaignRepository campaignRepository,
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
CharacterRepository characterRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.characterRepository = characterRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,13 +48,20 @@ public class CampaignService {
|
||||
*
|
||||
* <p>{@code loreId} est nullable : une campagne peut exister sans univers associé.</p>
|
||||
*/
|
||||
public record CampaignData(String name, String description, String loreId) {}
|
||||
public record CampaignData(String name, String description, String loreId, String gameSystemId) {}
|
||||
|
||||
/**
|
||||
* Compte des entités qui seront supprimées en cascade si la campagne est effacée.
|
||||
* Utilisé par l'UI pour afficher un récapitulatif dans le dialogue de confirmation.
|
||||
*/
|
||||
public record DeletionImpact(int arcs, int chapters, int scenes, int characters) {}
|
||||
|
||||
public Campaign createCampaign(CampaignData data) {
|
||||
Campaign campaign = Campaign.builder()
|
||||
.name(data.name())
|
||||
.description(data.description())
|
||||
.loreId(normalizeLoreId(data.loreId()))
|
||||
.loreId(normalizeId(data.loreId()))
|
||||
.gameSystemId(normalizeId(data.gameSystemId()))
|
||||
.arcsCount(0)
|
||||
.build();
|
||||
return campaignRepository.save(campaign);
|
||||
@@ -57,19 +84,61 @@ public class CampaignService {
|
||||
Campaign campaign = existingCampaign.get();
|
||||
campaign.setName(data.name());
|
||||
campaign.setDescription(data.description());
|
||||
campaign.setLoreId(normalizeLoreId(data.loreId()));
|
||||
campaign.setLoreId(normalizeId(data.loreId()));
|
||||
campaign.setGameSystemId(normalizeId(data.gameSystemId()));
|
||||
return campaignRepository.save(campaign);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise un loreId entrant : une chaîne vide/blanche est traitée comme "pas de lien".
|
||||
* Normalise un ID entrant : une chaîne vide/blanche est traitée comme "pas de lien".
|
||||
* Utile car les payloads JSON peuvent envoyer "" au lieu de null.
|
||||
*/
|
||||
private String normalizeLoreId(String loreId) {
|
||||
return (loreId == null || loreId.isBlank()) ? null : loreId;
|
||||
private String normalizeId(String id) {
|
||||
return (id == null || id.isBlank()) ? null : id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule l'impact d'une suppression en cascade : nombre d'arcs, chapitres,
|
||||
* scènes et personnages qui disparaîtront avec la campagne. Utilisé par l'UI
|
||||
* pour afficher "X arcs, Y chapitres, Z scènes seront supprimés".
|
||||
*/
|
||||
public DeletionImpact getDeletionImpact(String id) {
|
||||
List<Arc> arcs = arcRepository.findByCampaignId(id);
|
||||
int chapterTotal = 0;
|
||||
int sceneTotal = 0;
|
||||
for (Arc arc : arcs) {
|
||||
List<Chapter> chapters = chapterRepository.findByArcId(arc.getId());
|
||||
chapterTotal += chapters.size();
|
||||
for (Chapter chapter : chapters) {
|
||||
sceneTotal += sceneRepository.findByChapterId(chapter.getId()).size();
|
||||
}
|
||||
}
|
||||
int characterTotal = characterRepository.findByCampaignId(id).size();
|
||||
return new DeletionImpact(arcs.size(), chapterTotal, sceneTotal, characterTotal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime la campagne et toutes ses entités dépendantes (arcs → chapitres →
|
||||
* scènes, plus les personnages). L'opération est transactionnelle : soit
|
||||
* tout disparaît, soit rien ne change. Les FKs applicatives n'ayant pas
|
||||
* de contrainte CASCADE au niveau DB, on orchestre la cascade ici.
|
||||
*/
|
||||
@Transactional
|
||||
public void deleteCampaign(String id) {
|
||||
List<Arc> arcs = arcRepository.findByCampaignId(id);
|
||||
for (Arc arc : arcs) {
|
||||
List<Chapter> chapters = chapterRepository.findByArcId(arc.getId());
|
||||
for (Chapter chapter : chapters) {
|
||||
for (var scene : sceneRepository.findByChapterId(chapter.getId())) {
|
||||
sceneRepository.deleteById(scene.getId());
|
||||
}
|
||||
chapterRepository.deleteById(chapter.getId());
|
||||
}
|
||||
arcRepository.deleteById(arc.getId());
|
||||
}
|
||||
for (var character : characterRepository.findByCampaignId(id)) {
|
||||
characterRepository.deleteById(character.getId());
|
||||
}
|
||||
campaignRepository.deleteById(id);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,10 @@ package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -17,11 +19,16 @@ import java.util.Optional;
|
||||
public class ChapterService {
|
||||
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
|
||||
public ChapterService(ChapterRepository chapterRepository) {
|
||||
public ChapterService(ChapterRepository chapterRepository, SceneRepository sceneRepository) {
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
}
|
||||
|
||||
/** Compte des scènes qui seront supprimées en cascade avec le chapitre. */
|
||||
public record DeletionImpact(int scenes) {}
|
||||
|
||||
public Chapter createChapter(String name, String description, String arcId, int order) {
|
||||
Chapter chapter = Chapter.builder()
|
||||
.name(name)
|
||||
@@ -58,7 +65,17 @@ public class ChapterService {
|
||||
return chapterRepository.save(chapter);
|
||||
}
|
||||
|
||||
/** Compte des scènes qui tomberont avec le chapitre. */
|
||||
public DeletionImpact getDeletionImpact(String id) {
|
||||
return new DeletionImpact(sceneRepository.findByChapterId(id).size());
|
||||
}
|
||||
|
||||
/** Supprime le chapitre et toutes ses scènes. Transactionnel : atomique. */
|
||||
@Transactional
|
||||
public void deleteChapter(String id) {
|
||||
for (var scene : sceneRepository.findByChapterId(id)) {
|
||||
sceneRepository.deleteById(scene.getId());
|
||||
}
|
||||
chapterRepository.deleteById(id);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Service d'application pour les fiches de personnages (PJ).
|
||||
*/
|
||||
@Service
|
||||
public class CharacterService {
|
||||
|
||||
private final CharacterRepository characterRepository;
|
||||
|
||||
public CharacterService(CharacterRepository characterRepository) {
|
||||
this.characterRepository = characterRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameter Object pour la création / mise à jour d'un Character.
|
||||
* `order` est fourni par le controller ; si absent, le service le calcule.
|
||||
*/
|
||||
public record CharacterData(String name, String markdownContent, String campaignId, Integer order) {}
|
||||
|
||||
public Character createCharacter(CharacterData data) {
|
||||
int order = data.order() != null
|
||||
? data.order()
|
||||
: nextOrderFor(data.campaignId());
|
||||
Character character = Character.builder()
|
||||
.name(data.name())
|
||||
.markdownContent(data.markdownContent())
|
||||
.campaignId(data.campaignId())
|
||||
.order(order)
|
||||
.build();
|
||||
return characterRepository.save(character);
|
||||
}
|
||||
|
||||
public Optional<Character> getCharacterById(String id) {
|
||||
return characterRepository.findById(id);
|
||||
}
|
||||
|
||||
public List<Character> getCharactersByCampaignId(String campaignId) {
|
||||
return characterRepository.findByCampaignId(campaignId);
|
||||
}
|
||||
|
||||
public Character updateCharacter(String id, CharacterData data) {
|
||||
Character existing = characterRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Character non trouvé avec l'ID: " + id));
|
||||
existing.setName(data.name());
|
||||
existing.setMarkdownContent(data.markdownContent());
|
||||
if (data.order() != null) {
|
||||
existing.setOrder(data.order());
|
||||
}
|
||||
// campaignId n'est pas modifiable après création (cross-campagne move hors scope MVP).
|
||||
return characterRepository.save(existing);
|
||||
}
|
||||
|
||||
public void deleteCharacter(String id) {
|
||||
characterRepository.deleteById(id);
|
||||
}
|
||||
|
||||
/** Renvoie la prochaine position libre — append en fin de liste. */
|
||||
private int nextOrderFor(String campaignId) {
|
||||
return characterRepository.findByCampaignId(campaignId).stream()
|
||||
.mapToInt(Character::getOrder)
|
||||
.max()
|
||||
.orElse(-1) + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.loremind.application.conversationcontext;
|
||||
|
||||
import com.loremind.domain.conversationcontext.Conversation;
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
import com.loremind.domain.conversationcontext.ports.ConversationRepository;
|
||||
import com.loremind.domain.conversationcontext.ports.ConversationTitleGenerator;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Service d'application du contexte Conversation.
|
||||
*
|
||||
* Regroupe les cas d'usage CRUD + append message + rename. Un seul
|
||||
* service suffit — le contexte est simple et les operations fortement
|
||||
* liees (meme aggregat).
|
||||
*
|
||||
* Regles metier :
|
||||
* - exactement un ancrage parent (loreId XOR campaignId) ;
|
||||
* - entityType et entityId vont ensemble (tous deux null = niveau racine,
|
||||
* tous deux non-null = niveau entite precise).
|
||||
*/
|
||||
@Service
|
||||
public class ConversationService {
|
||||
|
||||
private final ConversationRepository repository;
|
||||
private final ConversationTitleGenerator titleGenerator;
|
||||
|
||||
public ConversationService(ConversationRepository repository,
|
||||
ConversationTitleGenerator titleGenerator) {
|
||||
this.repository = repository;
|
||||
this.titleGenerator = titleGenerator;
|
||||
}
|
||||
|
||||
/** Donnees de creation d'une conversation. Titre optionnel — sera auto-genere si absent. */
|
||||
public record CreateData(
|
||||
String title,
|
||||
String loreId,
|
||||
String campaignId,
|
||||
String entityType,
|
||||
String entityId) {}
|
||||
|
||||
public Conversation create(CreateData data) {
|
||||
validateAnchor(data.loreId(), data.campaignId(), data.entityType(), data.entityId());
|
||||
|
||||
String title = (data.title() == null || data.title().isBlank())
|
||||
? "Nouvelle conversation"
|
||||
: data.title().trim();
|
||||
|
||||
Conversation conv = Conversation.builder()
|
||||
.title(title)
|
||||
.loreId(data.loreId())
|
||||
.campaignId(data.campaignId())
|
||||
.entityType(data.entityType())
|
||||
.entityId(data.entityId())
|
||||
.build();
|
||||
return repository.save(conv);
|
||||
}
|
||||
|
||||
public Optional<Conversation> getById(String id) {
|
||||
return repository.findById(id);
|
||||
}
|
||||
|
||||
public List<Conversation> listByContext(String loreId, String campaignId, String entityType, String entityId) {
|
||||
validateAnchor(loreId, campaignId, entityType, entityId);
|
||||
return repository.findByContext(loreId, campaignId, entityType, entityId);
|
||||
}
|
||||
|
||||
public void rename(String id, String title) {
|
||||
if (title == null || title.isBlank()) {
|
||||
throw new IllegalArgumentException("Le titre ne peut pas etre vide");
|
||||
}
|
||||
if (repository.findById(id).isEmpty()) {
|
||||
throw new IllegalArgumentException("Conversation introuvable : " + id);
|
||||
}
|
||||
repository.updateTitle(id, title.trim());
|
||||
}
|
||||
|
||||
public void delete(String id) {
|
||||
repository.deleteById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-genere un titre a partir des premiers messages et le persiste.
|
||||
* Appele typiquement apres le 1er couple user/assistant pour remplacer
|
||||
* le titre provisoire. Echec silencieux (fallback dans l'adaptateur) —
|
||||
* on n'empeche pas la conversation de fonctionner si le Brain est down.
|
||||
*/
|
||||
public String autoGenerateTitle(String conversationId) {
|
||||
Conversation conv = repository.findById(conversationId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Conversation introuvable : " + conversationId));
|
||||
List<ConversationMessage> seeds = conv.getMessages();
|
||||
if (seeds == null || seeds.isEmpty()) {
|
||||
return conv.getTitle();
|
||||
}
|
||||
String title = titleGenerator.generate(seeds);
|
||||
repository.updateTitle(conversationId, title);
|
||||
return title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute un message (user ou assistant) a une conversation existante.
|
||||
* L'horodatage et l'id sont assignes par la couche persistance.
|
||||
*/
|
||||
public ConversationMessage appendMessage(String conversationId, String role, String content) {
|
||||
if (role == null || (!role.equals("user") && !role.equals("assistant") && !role.equals("system"))) {
|
||||
throw new IllegalArgumentException("Role invalide : " + role);
|
||||
}
|
||||
if (content == null || content.isEmpty()) {
|
||||
throw new IllegalArgumentException("Contenu vide interdit");
|
||||
}
|
||||
ConversationMessage msg = ConversationMessage.builder()
|
||||
.role(role)
|
||||
.content(content)
|
||||
.build();
|
||||
return repository.appendMessage(conversationId, msg);
|
||||
}
|
||||
|
||||
// ---------- Validation ----------
|
||||
|
||||
private void validateAnchor(String loreId, String campaignId, String entityType, String entityId) {
|
||||
boolean hasLore = loreId != null && !loreId.isBlank();
|
||||
boolean hasCamp = campaignId != null && !campaignId.isBlank();
|
||||
if (hasLore == hasCamp) {
|
||||
throw new IllegalArgumentException("Exactement un parent attendu : loreId XOR campaignId");
|
||||
}
|
||||
boolean hasType = entityType != null && !entityType.isBlank();
|
||||
boolean hasEntId = entityId != null && !entityId.isBlank();
|
||||
if (hasType != hasEntId) {
|
||||
throw new IllegalArgumentException("entityType et entityId doivent etre tous deux null ou tous deux non-null");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.loremind.application.gamesystemcontext;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Construit un {@link GameSystemContext} à partir d'un gameSystemId et d'un intent.
|
||||
* <p>
|
||||
* Pipeline :
|
||||
* 1. Charge le GameSystem (retourne Optional.empty si introuvable — dégradation gracieuse).
|
||||
* 2. Parse le markdown par titres H2 (## Section) → Map<Titre, Contenu>.
|
||||
* 3. Filtre les sections selon l'intent via les alias {@link GenerationIntent#getSectionAliases()}.
|
||||
* GENERIC = pas de filtre.
|
||||
* <p>
|
||||
* Parsing à la volée (pas de cache) : les règles d'un système font
|
||||
* typiquement 5-20kB, le coût de parsing est négligeable devant l'appel LLM.
|
||||
*/
|
||||
@Service
|
||||
public class GameSystemContextBuilder {
|
||||
|
||||
/** Matche "## Titre" en début de ligne (multiline). Capture le titre en groupe 1. */
|
||||
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(.+?)\\s*$");
|
||||
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
|
||||
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) {
|
||||
this.gameSystemRepository = gameSystemRepository;
|
||||
}
|
||||
|
||||
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
||||
if (gameSystemId == null || gameSystemId.isBlank()) return Optional.empty();
|
||||
return gameSystemRepository.findById(gameSystemId)
|
||||
.map(gs -> build(gs, intent));
|
||||
}
|
||||
|
||||
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
||||
Map<String, String> allSections = parseH2Sections(gs.getRulesMarkdown());
|
||||
Map<String, String> filtered = filterByIntent(allSections, intent);
|
||||
return GameSystemContext.builder()
|
||||
.systemName(gs.getName())
|
||||
.systemDescription(gs.getDescription())
|
||||
.sections(filtered)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Découpe le markdown par titres H2. Préserve l'ordre d'apparition (LinkedHashMap).
|
||||
* Le contenu avant le premier H2 est ignoré (préambule libre).
|
||||
*/
|
||||
Map<String, String> parseH2Sections(String markdown) {
|
||||
Map<String, String> sections = new LinkedHashMap<>();
|
||||
if (markdown == null || markdown.isBlank()) return sections;
|
||||
|
||||
Matcher m = H2_HEADER.matcher(markdown);
|
||||
String currentTitle = null;
|
||||
int currentContentStart = -1;
|
||||
|
||||
while (m.find()) {
|
||||
if (currentTitle != null) {
|
||||
sections.put(currentTitle, markdown.substring(currentContentStart, m.start()).strip());
|
||||
}
|
||||
currentTitle = m.group(1).trim();
|
||||
currentContentStart = m.end();
|
||||
}
|
||||
if (currentTitle != null) {
|
||||
sections.put(currentTitle, markdown.substring(currentContentStart).strip());
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
|
||||
private Map<String, String> filterByIntent(Map<String, String> sections, GenerationIntent intent) {
|
||||
if (intent.matchesAllSections()) return sections;
|
||||
Map<String, String> filtered = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, String> e : sections.entrySet()) {
|
||||
String titleLower = e.getKey().toLowerCase();
|
||||
boolean match = intent.getSectionAliases().stream().anyMatch(titleLower::contains);
|
||||
if (match) {
|
||||
filtered.put(e.getKey(), e.getValue());
|
||||
}
|
||||
}
|
||||
return filtered;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.loremind.application.gamesystemcontext;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class GameSystemService {
|
||||
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
|
||||
public GameSystemService(GameSystemRepository gameSystemRepository) {
|
||||
this.gameSystemRepository = gameSystemRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameter Object pour la création / mise à jour d'un GameSystem.
|
||||
*/
|
||||
public record GameSystemData(
|
||||
String name,
|
||||
String description,
|
||||
String rulesMarkdown,
|
||||
String author,
|
||||
boolean isPublic
|
||||
) {}
|
||||
|
||||
public GameSystem createGameSystem(GameSystemData data) {
|
||||
GameSystem gameSystem = GameSystem.builder()
|
||||
.name(data.name())
|
||||
.description(data.description())
|
||||
.rulesMarkdown(data.rulesMarkdown())
|
||||
.author(normalize(data.author()))
|
||||
.isPublic(data.isPublic())
|
||||
.build();
|
||||
return gameSystemRepository.save(gameSystem);
|
||||
}
|
||||
|
||||
public Optional<GameSystem> getGameSystemById(String id) {
|
||||
return gameSystemRepository.findById(id);
|
||||
}
|
||||
|
||||
public List<GameSystem> getAllGameSystems() {
|
||||
return gameSystemRepository.findAll();
|
||||
}
|
||||
|
||||
public GameSystem updateGameSystem(String id, GameSystemData data) {
|
||||
GameSystem existing = gameSystemRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("GameSystem non trouvé avec l'ID: " + id));
|
||||
existing.setName(data.name());
|
||||
existing.setDescription(data.description());
|
||||
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||
existing.setAuthor(normalize(data.author()));
|
||||
existing.setPublic(data.isPublic());
|
||||
return gameSystemRepository.save(existing);
|
||||
}
|
||||
|
||||
public void deleteGameSystem(String id) {
|
||||
gameSystemRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public boolean gameSystemExists(String id) {
|
||||
return gameSystemRepository.existsById(id);
|
||||
}
|
||||
|
||||
public List<GameSystem> searchGameSystems(String query) {
|
||||
if (query == null || query.isBlank()) return List.of();
|
||||
return gameSystemRepository.searchByName(query.trim());
|
||||
}
|
||||
|
||||
private String normalize(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value;
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,18 @@ package com.loremind.application.generationcontext;
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.Scene;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@@ -38,18 +41,24 @@ public class CampaignStructuralContextBuilder {
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final CharacterRepository characterRepository;
|
||||
|
||||
public CampaignStructuralContextBuilder(
|
||||
CampaignRepository campaignRepository,
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository) {
|
||||
SceneRepository sceneRepository,
|
||||
CharacterRepository characterRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.characterRepository = characterRepository;
|
||||
}
|
||||
|
||||
/** Longueur max du snippet de PJ injecté dans le contexte (coût tokens maîtrisé). */
|
||||
private static final int CHARACTER_SNIPPET_MAX_LEN = 160;
|
||||
|
||||
/**
|
||||
* Construit la carte narrative d'une Campagne (arcs → chapitres → scènes,
|
||||
* nom + description courte à chaque niveau).
|
||||
@@ -65,13 +74,42 @@ public class CampaignStructuralContextBuilder {
|
||||
.map(this::toArcSummary)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<CharacterSummary> characters = characterRepository.findByCampaignId(campaignId).stream()
|
||||
.sorted(Comparator.comparingInt(Character::getOrder))
|
||||
.map(this::toCharacterSummary)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return CampaignStructuralContext.builder()
|
||||
.campaignName(campaign.getName())
|
||||
.campaignDescription(campaign.getDescription())
|
||||
.arcs(arcs)
|
||||
.characters(characters)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Projette un PJ vers un résumé court : nom + 1re ligne "signifiante" du
|
||||
* markdown (ni vide, ni un titre). Permet à l'IA de savoir "qui est Thorin"
|
||||
* sans injecter toute sa fiche.
|
||||
*/
|
||||
private CharacterSummary toCharacterSummary(Character c) {
|
||||
return CharacterSummary.builder()
|
||||
.name(c.getName())
|
||||
.snippet(extractSnippet(c.getMarkdownContent()))
|
||||
.build();
|
||||
}
|
||||
|
||||
private static String extractSnippet(String markdown) {
|
||||
if (markdown == null || markdown.isBlank()) return "";
|
||||
String firstLine = markdown.lines()
|
||||
.map(String::strip)
|
||||
.filter(l -> !l.isEmpty() && !l.startsWith("#"))
|
||||
.findFirst()
|
||||
.orElse("");
|
||||
if (firstLine.length() <= CHARACTER_SNIPPET_MAX_LEN) return firstLine;
|
||||
return firstLine.substring(0, CHARACTER_SNIPPET_MAX_LEN - 1).stripTrailing() + "…";
|
||||
}
|
||||
|
||||
private ArcSummary toArcSummary(Arc arc) {
|
||||
List<ChapterSummary> chapters = chapterRepository.findByArcId(arc.getId()).stream()
|
||||
.sorted(Comparator.comparingInt(Chapter::getOrder))
|
||||
|
||||
@@ -2,9 +2,11 @@ package com.loremind.application.generationcontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.Scene;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -26,20 +28,23 @@ public class NarrativeEntityContextBuilder {
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final CharacterRepository characterRepository;
|
||||
|
||||
public NarrativeEntityContextBuilder(
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository) {
|
||||
SceneRepository sceneRepository,
|
||||
CharacterRepository characterRepository) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.characterRepository = characterRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge l'entité narrative ciblée et la projette vers un VO du GenerationContext.
|
||||
*
|
||||
* @param entityType "arc", "chapter" ou "scene" (insensible à la casse)
|
||||
* @param entityType "arc", "chapter", "scene" ou "character" (insensible à la casse)
|
||||
* @param entityId l'ID de l'entité
|
||||
* @throws IllegalArgumentException si le type est inconnu ou l'entité introuvable
|
||||
*/
|
||||
@@ -49,6 +54,7 @@ public class NarrativeEntityContextBuilder {
|
||||
case "arc" -> fromArc(loadArc(entityId));
|
||||
case "chapter" -> fromChapter(loadChapter(entityId));
|
||||
case "scene" -> fromScene(loadScene(entityId));
|
||||
case "character" -> fromCharacter(loadCharacter(entityId));
|
||||
default -> throw new IllegalArgumentException("Type d'entité narrative inconnu: " + entityType);
|
||||
};
|
||||
}
|
||||
@@ -70,6 +76,11 @@ public class NarrativeEntityContextBuilder {
|
||||
.orElseThrow(() -> new IllegalArgumentException("Scène non trouvée: " + id));
|
||||
}
|
||||
|
||||
private Character loadCharacter(String id) {
|
||||
return characterRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Personnage non trouvé: " + id));
|
||||
}
|
||||
|
||||
// --- Mapping entité → VO ------------------------------------------------
|
||||
|
||||
private NarrativeEntityContext fromArc(Arc a) {
|
||||
@@ -118,6 +129,16 @@ public class NarrativeEntityContextBuilder {
|
||||
.build();
|
||||
}
|
||||
|
||||
private NarrativeEntityContext fromCharacter(Character c) {
|
||||
Map<String, String> fields = new LinkedHashMap<>();
|
||||
putField(fields, "fiche complète (markdown)", c.getMarkdownContent());
|
||||
return NarrativeEntityContext.builder()
|
||||
.entityType("character")
|
||||
.title(c.getName())
|
||||
.fields(fields)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Null/blank devient chaîne vide — uniforme côté prompt, pas de NPE côté LLM. */
|
||||
private static void putField(Map<String, String> target, String key, String value) {
|
||||
target.put(key, value == null ? "" : value);
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package com.loremind.application.generationcontext;
|
||||
|
||||
import com.loremind.application.gamesystemcontext.GameSystemContextBuilder;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||
import com.loremind.domain.generationcontext.ChatMessage;
|
||||
import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||
@@ -33,6 +37,7 @@ public class StreamChatForCampaignUseCase {
|
||||
private final CampaignStructuralContextBuilder campaignContextBuilder;
|
||||
private final LoreStructuralContextBuilder loreContextBuilder;
|
||||
private final NarrativeEntityContextBuilder narrativeEntityContextBuilder;
|
||||
private final GameSystemContextBuilder gameSystemContextBuilder;
|
||||
private final AiChatProvider aiChatProvider;
|
||||
|
||||
public StreamChatForCampaignUseCase(
|
||||
@@ -40,11 +45,13 @@ public class StreamChatForCampaignUseCase {
|
||||
CampaignStructuralContextBuilder campaignContextBuilder,
|
||||
LoreStructuralContextBuilder loreContextBuilder,
|
||||
NarrativeEntityContextBuilder narrativeEntityContextBuilder,
|
||||
GameSystemContextBuilder gameSystemContextBuilder,
|
||||
AiChatProvider aiChatProvider) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.campaignContextBuilder = campaignContextBuilder;
|
||||
this.loreContextBuilder = loreContextBuilder;
|
||||
this.narrativeEntityContextBuilder = narrativeEntityContextBuilder;
|
||||
this.gameSystemContextBuilder = gameSystemContextBuilder;
|
||||
this.aiChatProvider = aiChatProvider;
|
||||
}
|
||||
|
||||
@@ -65,6 +72,7 @@ public class StreamChatForCampaignUseCase {
|
||||
String entityType,
|
||||
String entityId,
|
||||
List<ChatMessage> messages,
|
||||
Consumer<ChatUsage> onUsage,
|
||||
Consumer<String> onToken,
|
||||
Runnable onComplete,
|
||||
Consumer<Throwable> onError) {
|
||||
@@ -76,15 +84,17 @@ public class StreamChatForCampaignUseCase {
|
||||
CampaignStructuralContext campaignContext = campaignContextBuilder.build(campaignId);
|
||||
LoreStructuralContext loreContext = loadLinkedLoreContextOrNull(campaign);
|
||||
NarrativeEntityContext narrativeEntity = buildNarrativeEntityOrNull(entityType, entityId);
|
||||
GameSystemContext gameSystemContext = loadGameSystemContextOrNull(campaign, entityType);
|
||||
|
||||
ChatRequest request = ChatRequest.builder()
|
||||
.messages(messages)
|
||||
.loreContext(loreContext)
|
||||
.campaignContext(campaignContext)
|
||||
.narrativeEntity(narrativeEntity)
|
||||
.gameSystemContext(gameSystemContext)
|
||||
.build();
|
||||
|
||||
aiChatProvider.streamChat(request, onToken, onComplete, onError);
|
||||
aiChatProvider.streamChat(request, onUsage, onToken, onComplete, onError);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,4 +112,16 @@ public class StreamChatForCampaignUseCase {
|
||||
if (entityId == null || entityId.isBlank()) return null;
|
||||
return narrativeEntityContextBuilder.build(entityType, entityId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge le GameSystemContext si la campagne est liée à un GameSystem.
|
||||
* L'entityType détermine quelles sections de règles sont injectées
|
||||
* (SCENE → combat/PNJ, CHAPTER → combat/classes, ARC → lore/factions, autre → toutes).
|
||||
* Retourne null en cas de GameSystem introuvable (dégradation gracieuse).
|
||||
*/
|
||||
private GameSystemContext loadGameSystemContextOrNull(Campaign campaign, String entityType) {
|
||||
if (!campaign.isLinkedToGameSystem()) return null;
|
||||
GenerationIntent intent = GenerationIntent.fromNarrativeEntityType(entityType);
|
||||
return gameSystemContextBuilder.buildOptional(campaign.getGameSystemId(), intent).orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.loremind.application.generationcontext;
|
||||
|
||||
import com.loremind.domain.generationcontext.ChatMessage;
|
||||
import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||
import com.loremind.domain.generationcontext.PageContext;
|
||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||
@@ -60,6 +61,7 @@ public class StreamChatForLoreUseCase {
|
||||
String loreId,
|
||||
String pageId,
|
||||
List<ChatMessage> messages,
|
||||
Consumer<ChatUsage> onUsage,
|
||||
Consumer<String> onToken,
|
||||
Runnable onComplete,
|
||||
Consumer<Throwable> onError) {
|
||||
@@ -75,7 +77,7 @@ public class StreamChatForLoreUseCase {
|
||||
.pageContext(pageContext)
|
||||
.build();
|
||||
|
||||
aiChatProvider.streamChat(request, onToken, onComplete, onError);
|
||||
aiChatProvider.streamChat(request, onUsage, onToken, onComplete, onError);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.loremind.application.lorecontext;
|
||||
|
||||
import com.loremind.domain.lorecontext.LoreNode;
|
||||
import com.loremind.domain.lorecontext.Page;
|
||||
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
||||
import com.loremind.domain.lorecontext.ports.PageRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -16,11 +20,20 @@ import java.util.Optional;
|
||||
public class LoreNodeService {
|
||||
|
||||
private final LoreNodeRepository loreNodeRepository;
|
||||
private final PageRepository pageRepository;
|
||||
|
||||
public LoreNodeService(LoreNodeRepository loreNodeRepository) {
|
||||
public LoreNodeService(LoreNodeRepository loreNodeRepository, PageRepository pageRepository) {
|
||||
this.loreNodeRepository = loreNodeRepository;
|
||||
this.pageRepository = pageRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compte des entités qui seront supprimées en cascade si le dossier est effacé :
|
||||
* le dossier lui-même n'est pas compté, seuls les descendants (sous-dossiers
|
||||
* récursifs + pages de l'ensemble du sous-arbre).
|
||||
*/
|
||||
public record DeletionImpact(int folders, int pages) {}
|
||||
|
||||
/**
|
||||
* Crée un LoreNode (dossier) à partir d'un "objet changes" porteur des valeurs
|
||||
* souhaitées (pattern Parameter Object) : évite les signatures qui gonflent
|
||||
@@ -68,7 +81,64 @@ public class LoreNodeService {
|
||||
return loreNodeRepository.save(existing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule l'impact d'une suppression en cascade : nombre de sous-dossiers
|
||||
* (récursif, sans compter la racine) et de pages dans l'ensemble du sous-arbre.
|
||||
*/
|
||||
public DeletionImpact getDeletionImpact(String id) {
|
||||
List<LoreNode> descendants = collectDescendants(id);
|
||||
int pageTotal = pageRepository.findByNodeId(id).size();
|
||||
for (LoreNode descendant : descendants) {
|
||||
pageTotal += pageRepository.findByNodeId(descendant.getId()).size();
|
||||
}
|
||||
return new DeletionImpact(descendants.size(), pageTotal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime le dossier et tout son sous-arbre (sous-dossiers récursifs + pages).
|
||||
* Suppression en profondeur d'abord (feuilles → racine) pour limiter les
|
||||
* références orphelines en cours de transaction. Les FKs applicatives n'ayant
|
||||
* pas de CASCADE en DB, on orchestre la descente ici.
|
||||
*/
|
||||
@Transactional
|
||||
public void deleteLoreNode(String id) {
|
||||
List<LoreNode> descendants = collectDescendants(id);
|
||||
// Descendants retournés en ordre BFS (haut → bas) : on inverse pour
|
||||
// supprimer les feuilles en premier, puis on finit par la racine.
|
||||
for (int i = descendants.size() - 1; i >= 0; i--) {
|
||||
String descendantId = descendants.get(i).getId();
|
||||
deletePagesOfNode(descendantId);
|
||||
loreNodeRepository.deleteById(descendantId);
|
||||
}
|
||||
deletePagesOfNode(id);
|
||||
loreNodeRepository.deleteById(id);
|
||||
}
|
||||
|
||||
private void deletePagesOfNode(String nodeId) {
|
||||
for (Page page : pageRepository.findByNodeId(nodeId)) {
|
||||
pageRepository.deleteById(page.getId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retourne tous les descendants (hors racine) d'un dossier, en ordre BFS.
|
||||
* Parcours itératif pour éviter tout risque de débordement de pile sur
|
||||
* une arborescence profonde malicieuse.
|
||||
*/
|
||||
private List<LoreNode> collectDescendants(String rootId) {
|
||||
List<LoreNode> result = new ArrayList<>();
|
||||
List<String> frontier = new ArrayList<>();
|
||||
frontier.add(rootId);
|
||||
while (!frontier.isEmpty()) {
|
||||
List<String> nextFrontier = new ArrayList<>();
|
||||
for (String parentId : frontier) {
|
||||
for (LoreNode child : loreNodeRepository.findByParentId(parentId)) {
|
||||
result.add(child);
|
||||
nextFrontier.add(child.getId());
|
||||
}
|
||||
}
|
||||
frontier = nextFrontier;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
package com.loremind.application.lorecontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.lorecontext.Lore;
|
||||
import com.loremind.domain.lorecontext.LoreNode;
|
||||
import com.loremind.domain.lorecontext.Page;
|
||||
import com.loremind.domain.lorecontext.Template;
|
||||
import com.loremind.domain.lorecontext.ports.LoreNodeRepository;
|
||||
import com.loremind.domain.lorecontext.ports.LoreRepository;
|
||||
import com.loremind.domain.lorecontext.ports.PageRepository;
|
||||
import com.loremind.domain.lorecontext.ports.TemplateRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -26,15 +33,28 @@ public class LoreService {
|
||||
private final LoreRepository loreRepository;
|
||||
private final LoreNodeRepository loreNodeRepository;
|
||||
private final PageRepository pageRepository;
|
||||
private final TemplateRepository templateRepository;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public LoreService(LoreRepository loreRepository,
|
||||
LoreNodeRepository loreNodeRepository,
|
||||
PageRepository pageRepository) {
|
||||
PageRepository pageRepository,
|
||||
TemplateRepository templateRepository,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.loreRepository = loreRepository;
|
||||
this.loreNodeRepository = loreNodeRepository;
|
||||
this.pageRepository = pageRepository;
|
||||
this.templateRepository = templateRepository;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compte des entités qui seront supprimées / détachées en cascade si le Lore
|
||||
* est effacé. `detachedCampaigns` : campagnes qui perdront leur référence à
|
||||
* ce Lore (leur loreId sera nullé) mais resteront présentes.
|
||||
*/
|
||||
public record DeletionImpact(int folders, int pages, int templates, int detachedCampaigns) {}
|
||||
|
||||
public Lore createLore(String name, String description) {
|
||||
Lore lore = Lore.builder()
|
||||
.name(name)
|
||||
@@ -83,7 +103,54 @@ public class LoreService {
|
||||
return loreRepository.save(lore);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule l'impact d'une suppression de Lore en cascade : dossiers + pages
|
||||
* + templates supprimés, et campagnes qui seront détachées (loreId → null
|
||||
* sans être supprimées, car une campagne peut vivre sans univers).
|
||||
*/
|
||||
public DeletionImpact getDeletionImpact(String id) {
|
||||
int folders = (int) loreNodeRepository.countByLoreId(id);
|
||||
int pages = (int) pageRepository.countByLoreId(id);
|
||||
int templates = templateRepository.findByLoreId(id).size();
|
||||
int detached = countCampaignsReferencingLore(id);
|
||||
return new DeletionImpact(folders, pages, templates, detached);
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime le Lore et toutes ses entités dépendantes (dossiers, pages, templates).
|
||||
* Les campagnes qui référençaient ce Lore sont conservées — leur loreId est
|
||||
* mis à null (une campagne peut légitimement exister sans univers associé).
|
||||
* Opération transactionnelle : atomique.
|
||||
*/
|
||||
@Transactional
|
||||
public void deleteLore(String id) {
|
||||
// Pages d'abord : elles référencent nodeId ET loreId, on les supprime
|
||||
// globalement via loreId pour éviter d'en rater une rattachée à un
|
||||
// node orphelin (ne devrait pas arriver, mais ceinture+bretelles).
|
||||
for (Page page : pageRepository.findByLoreId(id)) {
|
||||
pageRepository.deleteById(page.getId());
|
||||
}
|
||||
for (LoreNode node : loreNodeRepository.findByLoreId(id)) {
|
||||
loreNodeRepository.deleteById(node.getId());
|
||||
}
|
||||
for (Template template : templateRepository.findByLoreId(id)) {
|
||||
templateRepository.deleteById(template.getId());
|
||||
}
|
||||
// Détache les campagnes : on garde la campagne, on nulle juste la référence.
|
||||
for (Campaign campaign : campaignRepository.findAll()) {
|
||||
if (id.equals(campaign.getLoreId())) {
|
||||
campaign.setLoreId(null);
|
||||
campaignRepository.save(campaign);
|
||||
}
|
||||
}
|
||||
loreRepository.deleteById(id);
|
||||
}
|
||||
|
||||
private int countCampaignsReferencingLore(String id) {
|
||||
int count = 0;
|
||||
for (Campaign campaign : campaignRepository.findAll()) {
|
||||
if (id.equals(campaign.getLoreId())) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,12 +38,18 @@ public class Arc {
|
||||
private List<String> relatedPageIds = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* IDs des images (Shared Kernel) servant d'illustrations a cet arc.
|
||||
* IDs des images (Shared Kernel) servant d'illustrations a cet arc (ambiance).
|
||||
* Galerie ordonnee : la 1ere image est l'illustration principale.
|
||||
*/
|
||||
@Builder.Default
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* IDs des images utilisees comme cartes / plans (outil de table).
|
||||
*/
|
||||
@Builder.Default
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,18 @@ public class Campaign {
|
||||
*/
|
||||
private String loreId;
|
||||
|
||||
/**
|
||||
* Référence faible (weak reference) vers un GameSystem.
|
||||
* Nullable : une campagne peut être "générique" (pas de système de JDR déclaré).
|
||||
* Weak reference pour respecter la séparation des Bounded Contexts.
|
||||
*/
|
||||
private String gameSystemId;
|
||||
|
||||
public boolean isLinkedToLore() {
|
||||
return this.loreId != null && !this.loreId.isBlank();
|
||||
}
|
||||
|
||||
public boolean isLinkedToGameSystem() {
|
||||
return this.gameSystemId != null && !this.gameSystemId.isBlank();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,11 +34,17 @@ public class Chapter {
|
||||
private List<String> relatedPageIds = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* IDs des images (Shared Kernel) illustrant ce chapitre.
|
||||
* IDs des images (Shared Kernel) illustrant ce chapitre (ambiance).
|
||||
*/
|
||||
@Builder.Default
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* IDs des images utilisees comme cartes / plans pour ce chapitre (outil de table).
|
||||
*/
|
||||
@Builder.Default
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.loremind.domain.campaigncontext;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Fiche de personnage joueur (PJ) d'une campagne.
|
||||
* <p>
|
||||
* MVP : contenu markdown libre, l'utilisateur met ce qu'il veut (stats,
|
||||
* backstory, équipement). Évolution prévue vers un système templaté par
|
||||
* GameSystem (la fiche Nimble n'a pas les mêmes champs qu'une fiche D&D).
|
||||
* <p>
|
||||
* Scope strict PJ : les PNJ restent dans le Lore (pages templatées) ou
|
||||
* dans les scènes elles-mêmes. Si le besoin de PNJ spécifiques à une
|
||||
* campagne remonte, on étendra l'entité (ex: type enum PJ/PNJ).
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class Character {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* Contenu libre en markdown — stats + backstory + notes. Nullable à la création,
|
||||
* renseigné progressivement par le MJ.
|
||||
*/
|
||||
private String markdownContent;
|
||||
|
||||
/** Référence vers la Campaign parente. */
|
||||
private String campaignId;
|
||||
|
||||
/** Ordre d'affichage dans la liste des PJ de la campagne. */
|
||||
private int order;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -48,11 +48,19 @@ public class Scene {
|
||||
|
||||
/**
|
||||
* IDs des images (Shared Kernel) illustrant cette scene.
|
||||
* Utile pour carte du lieu, portraits des PNJ principaux, ambiance.
|
||||
* Vocation "ambiance" : portraits, decors, moodboard. Rendu facon editorial.
|
||||
*/
|
||||
@Builder.Default
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* IDs des images utilisees comme cartes / plans.
|
||||
* Vocation "outil de table" : plan de donjon, carte du lieu, schema tactique.
|
||||
* Rendu different des illustrations : vignettes plus grandes, ratio natif preserve.
|
||||
*/
|
||||
@Builder.Default
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Sorties narratives possibles depuis cette scène (graphe intra-chapitre).
|
||||
* Chaque branche décrit un choix des joueurs et la scène de destination.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.loremind.domain.campaigncontext.ports;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Port de sortie pour la persistance des fiches de personnages (PJ).
|
||||
*/
|
||||
public interface CharacterRepository {
|
||||
|
||||
Character save(Character character);
|
||||
|
||||
Optional<Character> findById(String id);
|
||||
|
||||
List<Character> findByCampaignId(String campaignId);
|
||||
|
||||
void deleteById(String id);
|
||||
|
||||
boolean existsById(String id);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.loremind.domain.conversationcontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Agregat d'une conversation de chat IA persistee.
|
||||
*
|
||||
* Une conversation est ancree sur exactement un niveau de contexte :
|
||||
* - un Lore (optionnellement une page precise)
|
||||
* - une Campagne (optionnellement une entite narrative : arc/chapitre/scene)
|
||||
*
|
||||
* C'est cet ancrage qui permet au drawer de filtrer les conversations
|
||||
* a afficher dans la sidebar selon l'ecran en cours.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Conversation {
|
||||
|
||||
private String id;
|
||||
private String title;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
/** Un seul des deux est non-null. */
|
||||
private String loreId;
|
||||
private String campaignId;
|
||||
|
||||
/**
|
||||
* Type d'entite focus, null si la conversation est ancree au niveau
|
||||
* Lore/Campagne racine (pas sur une page/scene precise).
|
||||
* Valeurs : "page", "arc", "chapter", "scene", "character".
|
||||
*/
|
||||
private String entityType;
|
||||
private String entityId;
|
||||
|
||||
@Builder.Default
|
||||
private List<ConversationMessage> messages = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.loremind.domain.conversationcontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Un message persiste d'une conversation.
|
||||
*
|
||||
* Distinct de {@link com.loremind.domain.generationcontext.ChatMessage}
|
||||
* qui reste un simple record role+content pour le streaming LLM. Ici
|
||||
* on ajoute id et horodatage, necessaires pour l'affichage / l'ordre.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ConversationMessage {
|
||||
|
||||
private String id;
|
||||
/** "user" | "assistant" | "system". */
|
||||
private String role;
|
||||
private String content;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.loremind.domain.conversationcontext.ports;
|
||||
|
||||
import com.loremind.domain.conversationcontext.Conversation;
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Port de persistance des conversations de chat IA.
|
||||
*
|
||||
* Les methodes de lecture par contexte acceptent des filtres nullables :
|
||||
* - `loreId` OU `campaignId` doit etre non-null (mais pas les deux)
|
||||
* - `entityType` + `entityId` : soit tous les deux null (niveau racine),
|
||||
* soit tous les deux non-null (niveau entite precise).
|
||||
*/
|
||||
public interface ConversationRepository {
|
||||
|
||||
Conversation save(Conversation conversation);
|
||||
|
||||
Optional<Conversation> findById(String id);
|
||||
|
||||
/**
|
||||
* Liste les conversations filtrees par contexte strict, triees par
|
||||
* updatedAt desc. Les messages ne sont PAS chargees (liste vide) pour
|
||||
* garder la payload legere — la sidebar n'affiche que les titres.
|
||||
*/
|
||||
List<Conversation> findByContext(
|
||||
String loreId,
|
||||
String campaignId,
|
||||
String entityType,
|
||||
String entityId);
|
||||
|
||||
void deleteById(String id);
|
||||
|
||||
/**
|
||||
* Ajoute un message a une conversation existante. Met a jour updatedAt
|
||||
* de la conversation parent. Renvoie le message persiste (avec id + ts).
|
||||
*/
|
||||
ConversationMessage appendMessage(String conversationId, ConversationMessage message);
|
||||
|
||||
/** Rename atomique — ne touche pas aux messages. */
|
||||
void updateTitle(String conversationId, String title);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.loremind.domain.conversationcontext.ports;
|
||||
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Port : generation d'un titre court a partir des premiers echanges d'une
|
||||
* conversation. Implemente via un appel Brain /summarize/conversation-title.
|
||||
*/
|
||||
public interface ConversationTitleGenerator {
|
||||
|
||||
/** Renvoie un titre en francais (4-7 mots max). Jamais null ni vide. */
|
||||
String generate(List<ConversationMessage> firstMessages);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.loremind.domain.gamesystemcontext;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Entité de domaine représentant un GameSystem (système de JDR).
|
||||
* <p>
|
||||
* Porte les règles d'un système (D&D, Nimble, Pathfinder, homebrew...) sous forme
|
||||
* d'un markdown monolithique structuré par titres H2. Les sections sont extraites
|
||||
* à la volée lors de l'injection dans les prompts IA (cf. GameSystemContextSelector).
|
||||
* <p>
|
||||
* {@code author} et {@code isPublic} sont des champs pensés pour un futur marketplace
|
||||
* de rulesets partagés — non exploités au MVP mais persistés dès maintenant pour
|
||||
* éviter une migration ultérieure.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class GameSystem {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
||||
private String rulesMarkdown;
|
||||
|
||||
/** Auteur déclaré — futur marketplace. Nullable. */
|
||||
private String author;
|
||||
|
||||
/** Flag de partage — futur marketplace. False par défaut. */
|
||||
private boolean isPublic;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.loremind.domain.gamesystemcontext;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Intent de génération utilisé pour sélectionner les sections d'un GameSystem
|
||||
* à injecter dans le prompt IA.
|
||||
* <p>
|
||||
* Chaque intent porte une liste d'alias (case-insensitive, comparaison par
|
||||
* {@code contains}) utilisée pour matcher les titres H2 du markdown de règles.
|
||||
* <p>
|
||||
* MVP : mapping codé en dur. Évoluera vers un mapping configurable par
|
||||
* l'utilisateur dans l'éditeur de GameSystem (futur marketplace).
|
||||
*/
|
||||
public enum GenerationIntent {
|
||||
|
||||
/** Scène (combat / rencontre) : règles de résolution + format de stat block. */
|
||||
SCENE(Set.of("combat", "monstre", "monster")),
|
||||
|
||||
/** Chapitre (segment narratif) : règles de combat + archétypes pour PNJ. */
|
||||
CHAPTER(Set.of("combat", "classe", "class")),
|
||||
|
||||
/** Arc (structure narrative longue) : pas de règles spécifiques — toutes. */
|
||||
ARC(Set.of()),
|
||||
|
||||
/** Fallback : toutes les sections (intent inconnu). */
|
||||
GENERIC(Set.of());
|
||||
|
||||
private final Set<String> sectionAliases;
|
||||
|
||||
GenerationIntent(Set<String> sectionAliases) {
|
||||
this.sectionAliases = sectionAliases;
|
||||
}
|
||||
|
||||
public Set<String> getSectionAliases() {
|
||||
return sectionAliases;
|
||||
}
|
||||
|
||||
/** True si l'intent veut toutes les sections (pas de filtre). */
|
||||
public boolean matchesAllSections() {
|
||||
return sectionAliases.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mappe un entityType de NarrativeEntityContext ("arc"/"chapter"/"scene")
|
||||
* vers l'intent correspondant. Tout le reste (null, inconnu) tombe sur GENERIC.
|
||||
*/
|
||||
public static GenerationIntent fromNarrativeEntityType(String entityType) {
|
||||
if (entityType == null) return GENERIC;
|
||||
return switch (entityType.toLowerCase()) {
|
||||
case "scene" -> SCENE;
|
||||
case "chapter" -> CHAPTER;
|
||||
case "arc" -> ARC;
|
||||
default -> GENERIC;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.loremind.domain.gamesystemcontext.ports;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Port de sortie pour la persistance des GameSystems.
|
||||
*/
|
||||
public interface GameSystemRepository {
|
||||
|
||||
GameSystem save(GameSystem gameSystem);
|
||||
|
||||
Optional<GameSystem> findById(String id);
|
||||
|
||||
List<GameSystem> findAll();
|
||||
|
||||
void deleteById(String id);
|
||||
|
||||
boolean existsById(String id);
|
||||
|
||||
List<GameSystem> searchByName(String query);
|
||||
}
|
||||
@@ -30,6 +30,22 @@ public class CampaignStructuralContext {
|
||||
String campaignName;
|
||||
String campaignDescription;
|
||||
@Singular List<ArcSummary> arcs;
|
||||
/** Personnages joueurs (PJ) de la campagne. Vide si aucun. */
|
||||
@Singular List<CharacterSummary> characters;
|
||||
|
||||
/**
|
||||
* Résumé d'un PJ : nom + snippet court du markdown.
|
||||
* Pas le markdown complet pour maîtriser le coût token (chaque campagne
|
||||
* peut avoir 4-6 PJ × potentiellement 1-2k tokens/fiche = trop lourd).
|
||||
* La fiche complète n'est injectée que si le PJ est l'entité focus
|
||||
* (via NarrativeEntityContext, entity_type="character").
|
||||
*/
|
||||
@Value
|
||||
@Builder
|
||||
public static class CharacterSummary {
|
||||
String name;
|
||||
String snippet;
|
||||
}
|
||||
|
||||
/** Résumé d'un arc : nom + description courte + ses chapitres. */
|
||||
@Value
|
||||
|
||||
@@ -39,4 +39,10 @@ public class ChatRequest {
|
||||
|
||||
/** Optionnel : entité narrative en cours d'édition (arc/chapter/scene). */
|
||||
NarrativeEntityContext narrativeEntity;
|
||||
|
||||
/**
|
||||
* Optionnel : règles du système de JDR de la campagne (filtrées par intent).
|
||||
* Null si la campagne n'a pas de GameSystem associé. Campagne uniquement au MVP.
|
||||
*/
|
||||
GameSystemContext gameSystemContext;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.loremind.domain.generationcontext;
|
||||
|
||||
/**
|
||||
* Instantané d'occupation de la fenêtre de contexte à l'instant t du chat.
|
||||
* <p>
|
||||
* Émis une fois par tour de chat (juste avant le streaming des tokens) pour
|
||||
* alimenter la jauge de contexte côté frontend. Les unités sont des tokens
|
||||
* (approximés via tiktoken côté Brain — ±10% vs le tokenizer réel du modèle).
|
||||
*
|
||||
* @param system tokens consommés par le system prompt (contextes Lore/campagne injectés)
|
||||
* @param history tokens consommés par l'historique de la conversation (hors dernier message)
|
||||
* @param current tokens du dernier message utilisateur en attente de réponse
|
||||
* @param max taille maximale configurée de la fenêtre de contexte
|
||||
*/
|
||||
public record ChatUsage(int system, int history, int current, int max) {
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.loremind.domain.generationcontext;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Value;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Value Object représentant les règles de JDR injectées dans un prompt IA.
|
||||
* <p>
|
||||
* Contient uniquement les sections pertinentes pour l'intent de génération
|
||||
* en cours (sélection effectuée par GameSystemContextBuilder). Les sections
|
||||
* sont indexées par leur titre H2 original (ex : "Combat", "Classes").
|
||||
*/
|
||||
@Value
|
||||
@Builder
|
||||
public class GameSystemContext {
|
||||
|
||||
/** Nom du système de JDR (ex : "Nimble", "D&D 5.1 SRD"). */
|
||||
String systemName;
|
||||
|
||||
/** Description courte du système (nullable). */
|
||||
String systemDescription;
|
||||
|
||||
/**
|
||||
* Sections de règles pertinentes, indexées par titre H2.
|
||||
* Vide si le GameSystem n'a aucune règle ou si aucune section ne matche l'intent.
|
||||
*/
|
||||
Map<String, String> sections;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.loremind.domain.generationcontext.ports;
|
||||
|
||||
import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@@ -26,6 +27,10 @@ public interface AiChatProvider {
|
||||
* HTTP côté controller SSE).
|
||||
*
|
||||
* @param request messages + contexte Lore
|
||||
* @param onUsage invoqué une fois au début du stream avec le bilan
|
||||
* d'occupation de la fenêtre de contexte (tokens system /
|
||||
* history / current / max). Peut ne jamais être invoqué
|
||||
* si le provider ne supporte pas le comptage.
|
||||
* @param onToken invoqué à chaque token reçu du LLM (peut être appelé
|
||||
* de nombreuses fois)
|
||||
* @param onComplete invoqué une fois le stream terminé avec succès
|
||||
@@ -34,6 +39,7 @@ public interface AiChatProvider {
|
||||
*/
|
||||
void streamChat(
|
||||
ChatRequest request,
|
||||
Consumer<ChatUsage> onUsage,
|
||||
Consumer<String> onToken,
|
||||
Runnable onComplete,
|
||||
Consumer<Throwable> onError
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.loremind.domain.lorecontext;
|
||||
|
||||
/**
|
||||
* Variante de rendu pour un champ de type IMAGE.
|
||||
* <p>
|
||||
* - GALLERY : grille de vignettes (defaut, comportement historique)
|
||||
* - HERO : premiere image en banniere pleine largeur, suivantes en petit
|
||||
* - MASONRY : mosaique hauteurs variables facon Pinterest
|
||||
* - CAROUSEL : defilement horizontal
|
||||
* <p>
|
||||
* Uniquement significatif quand {@link FieldType} = IMAGE. Ignore pour TEXT.
|
||||
*/
|
||||
public enum ImageLayout {
|
||||
GALLERY,
|
||||
HERO,
|
||||
MASONRY,
|
||||
CAROUSEL
|
||||
}
|
||||
@@ -12,10 +12,9 @@ import lombok.NoArgsConstructor;
|
||||
* Le type pilote le rendu cote front (textarea vs galerie d'images) ET
|
||||
* la logique metier (seuls les champs TEXT sont envoyes a l'IA pour generation).
|
||||
* <p>
|
||||
* Evolution de `List<String> fields` vers `List<TemplateField> fields` :
|
||||
* refactor propre (DDD Value Object polymorphism) permettant d'ajouter
|
||||
* facilement d'autres types de champs (DATE, NUMBER, RICH_TEXT...) sans
|
||||
* casser le contrat.
|
||||
* Pour les champs IMAGE, {@link #layout} precise la variante de rendu
|
||||
* (gallery/hero/masonry/carousel). Nullable : l'absence equivaut a GALLERY.
|
||||
* Ignore pour les champs TEXT.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@@ -26,14 +25,26 @@ public class TemplateField {
|
||||
private String name;
|
||||
/** Type du champ, pilote le rendu et la generation IA. */
|
||||
private FieldType type;
|
||||
/** Variante de rendu pour les champs IMAGE. Null = GALLERY. */
|
||||
private ImageLayout layout;
|
||||
|
||||
/** Constructeur de retrocompat : type seul, layout=null. */
|
||||
public TemplateField(String name, FieldType type) {
|
||||
this(name, type, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ de type TEXT (cas le plus courant). */
|
||||
public static TemplateField text(String name) {
|
||||
return new TemplateField(name, FieldType.TEXT);
|
||||
return new TemplateField(name, FieldType.TEXT, null);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ de type IMAGE. */
|
||||
/** Raccourci : construit un champ de type IMAGE avec layout GALLERY. */
|
||||
public static TemplateField image(String name) {
|
||||
return new TemplateField(name, FieldType.IMAGE);
|
||||
return new TemplateField(name, FieldType.IMAGE, ImageLayout.GALLERY);
|
||||
}
|
||||
|
||||
/** Raccourci : construit un champ IMAGE avec un layout specifique. */
|
||||
public static TemplateField image(String name, ImageLayout layout) {
|
||||
return new TemplateField(name, FieldType.IMAGE, layout);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||
import com.loremind.domain.generationcontext.ChatMessage;
|
||||
import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.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.ChatUsage;
|
||||
import com.loremind.domain.generationcontext.ports.AiChatProvider;
|
||||
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -22,25 +13,21 @@ import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Adapter de sortie (Architecture Hexagonale) : implémente AiChatProvider
|
||||
* en appelant le Brain Python via WebClient + SSE (Server-Sent Events).
|
||||
* <p>
|
||||
* Responsabilités :
|
||||
* 1. Traduire ChatRequest (domaine) -> JSON attendu par /chat/stream.
|
||||
* Sérialise lore_context, page_context, campaign_context et
|
||||
* narrative_entity de façon conditionnelle selon le scénario d'appel
|
||||
* (chat Lore / chat Lore focalisé page / chat Campagne / chat Campagne
|
||||
* focalisé arc-chapter-scene).
|
||||
* 2. Consommer le flux SSE token par token.
|
||||
* 3. Invoquer onToken / onComplete / onError au bon moment.
|
||||
* 4. Traduire toute erreur technique en AiProviderException.
|
||||
* Responsabilités (après extraction) :
|
||||
* 1. Transport HTTP + consommation du flux SSE.
|
||||
* 2. Dispatch des évènements SSE (data / done / error / usage).
|
||||
* 3. Traduction des erreurs techniques en AiProviderException.
|
||||
* <p>
|
||||
* Les responsabilités auxiliaires sont déléguées :
|
||||
* - Construction du payload JSON : {@link BrainChatPayloadBuilder}.
|
||||
* - Parsing des payloads SSE : {@link BrainSseParser}.
|
||||
* <p>
|
||||
* Le domaine ne voit JAMAIS WebClient, Flux, ni la moindre URL.
|
||||
*/
|
||||
@@ -52,21 +39,28 @@ public class BrainAiChatClient implements AiChatProvider {
|
||||
new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final WebClient webClient;
|
||||
private final BrainChatPayloadBuilder payloadBuilder;
|
||||
private final BrainSseParser sseParser;
|
||||
|
||||
public BrainAiChatClient(
|
||||
WebClient.Builder builder,
|
||||
@Value("${brain.base-url}") String baseUrl) {
|
||||
@Value("${brain.base-url}") String baseUrl,
|
||||
BrainChatPayloadBuilder payloadBuilder,
|
||||
BrainSseParser sseParser) {
|
||||
this.webClient = builder.baseUrl(baseUrl).build();
|
||||
this.payloadBuilder = payloadBuilder;
|
||||
this.sseParser = sseParser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void streamChat(
|
||||
ChatRequest request,
|
||||
Consumer<ChatUsage> onUsage,
|
||||
Consumer<String> onToken,
|
||||
Runnable onComplete,
|
||||
Consumer<Throwable> onError) {
|
||||
|
||||
Map<String, Object> payload = toPayload(request);
|
||||
Map<String, Object> payload = payloadBuilder.build(request);
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(CHAT_STREAM_PATH)
|
||||
@@ -81,7 +75,7 @@ public class BrainAiChatClient implements AiChatProvider {
|
||||
// au contrat synchrone du port. L'appelant choisit le thread.
|
||||
flux
|
||||
.timeout(Duration.ofSeconds(120))
|
||||
.doOnNext(sse -> handleEvent(sse, onToken, onError))
|
||||
.doOnNext(sse -> handleEvent(sse, onUsage, onToken, onError))
|
||||
.blockLast();
|
||||
onComplete.run();
|
||||
} catch (Exception e) {
|
||||
@@ -90,12 +84,13 @@ public class BrainAiChatClient implements AiChatProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispatch selon le type d'événement SSE (data par défaut, done, error). */
|
||||
/** Dispatch selon le type d'évènement SSE (data par défaut, done, error, usage). */
|
||||
private void handleEvent(
|
||||
ServerSentEvent<String> sse,
|
||||
Consumer<ChatUsage> onUsage,
|
||||
Consumer<String> onToken,
|
||||
Consumer<Throwable> onError) {
|
||||
String event = sse.event(); // null si pas d'event: xxx -> c'est un data par défaut
|
||||
String event = sse.event(); // null si pas d'event: xxx -> data par défaut
|
||||
String data = sse.data();
|
||||
|
||||
if ("error".equals(event)) {
|
||||
@@ -104,197 +99,17 @@ public class BrainAiChatClient implements AiChatProvider {
|
||||
return;
|
||||
}
|
||||
if ("done".equals(event)) {
|
||||
return; // la fin est gérée par blockLast + onComplete
|
||||
return; // fin gérée par blockLast + onComplete
|
||||
}
|
||||
// Défaut : événement data avec JSON {"token":"..."}.
|
||||
String token = extractToken(data);
|
||||
if ("usage".equals(event)) {
|
||||
ChatUsage usage = sseParser.parseUsage(data);
|
||||
if (usage != null) onUsage.accept(usage);
|
||||
return;
|
||||
}
|
||||
// Défaut : évènement data avec JSON {"token":"..."}.
|
||||
String token = sseParser.parseToken(data);
|
||||
if (token != null && !token.isEmpty()) {
|
||||
onToken.accept(token);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse minimaliste du JSON {"token":"..."} sans pull Jackson ici.
|
||||
* Si le format se complexifie, on remplacera par un DTO Jackson.
|
||||
*/
|
||||
private String extractToken(String json) {
|
||||
if (json == null) return null;
|
||||
int idx = json.indexOf("\"token\"");
|
||||
if (idx < 0) return null;
|
||||
int colon = json.indexOf(':', idx);
|
||||
int firstQuote = json.indexOf('"', colon + 1);
|
||||
int lastQuote = json.lastIndexOf('"');
|
||||
if (firstQuote < 0 || lastQuote <= firstQuote) return null;
|
||||
return json.substring(firstQuote + 1, lastQuote)
|
||||
.replace("\\n", "\n")
|
||||
.replace("\\\"", "\"")
|
||||
.replace("\\\\", "\\");
|
||||
}
|
||||
|
||||
// --- Construction du payload JSON vers le Brain -------------------------
|
||||
|
||||
/**
|
||||
* Construit le payload JSON. Chaque contexte optionnel est omis s'il est
|
||||
* null, pour s'aligner sur le schéma Pydantic côté Brain (champs
|
||||
* Optional qui restent absents du dict transmis au LLM).
|
||||
*/
|
||||
private Map<String, Object> toPayload(ChatRequest request) {
|
||||
Map<String, Object> root = new LinkedHashMap<>();
|
||||
root.put("messages", request.getMessages().stream()
|
||||
.map(this::messageToMap)
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
if (request.getLoreContext() != null) {
|
||||
root.put("lore_context", loreContextToMap(request.getLoreContext()));
|
||||
}
|
||||
if (request.getPageContext() != null) {
|
||||
root.put("page_context", pageContextToMap(request.getPageContext()));
|
||||
}
|
||||
if (request.getCampaignContext() != null) {
|
||||
root.put("campaign_context", campaignContextToMap(request.getCampaignContext()));
|
||||
}
|
||||
if (request.getNarrativeEntity() != null) {
|
||||
root.put("narrative_entity", narrativeEntityToMap(request.getNarrativeEntity()));
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
private Map<String, Object> messageToMap(ChatMessage m) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("role", m.role());
|
||||
map.put("content", m.content());
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> loreContextToMap(LoreStructuralContext ctx) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("lore_name", ctx.getLoreName());
|
||||
map.put("lore_description", ctx.getLoreDescription());
|
||||
|
||||
Map<String, Object> foldersMap = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<PageSummary>> e : ctx.getFolders().entrySet()) {
|
||||
foldersMap.put(e.getKey(), e.getValue().stream()
|
||||
.map(this::pageSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
map.put("folders", foldersMap);
|
||||
map.put("tags", ctx.getTags());
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> pageSummaryToMap(PageSummary ps) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("title", ps.getTitle());
|
||||
map.put("template_name", ps.getTemplateName());
|
||||
// values/tags/related_page_titles ne sont sérialisés que s'ils contiennent
|
||||
// de l'info — payload réseau plus léger quand la page est vierge.
|
||||
if (ps.getValues() != null && !ps.getValues().isEmpty()) {
|
||||
map.put("values", ps.getValues());
|
||||
}
|
||||
if (ps.getTags() != null && !ps.getTags().isEmpty()) {
|
||||
map.put("tags", ps.getTags());
|
||||
}
|
||||
if (ps.getRelatedPageTitles() != null && !ps.getRelatedPageTitles().isEmpty()) {
|
||||
map.put("related_page_titles", ps.getRelatedPageTitles());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> pageContextToMap(PageContext pc) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("title", pc.getTitle());
|
||||
map.put("template_name", pc.getTemplateName());
|
||||
map.put("template_fields", pc.getTemplateFields());
|
||||
map.put("values", pc.getValues());
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> campaignContextToMap(CampaignStructuralContext ctx) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("campaign_name", ctx.getCampaignName());
|
||||
map.put("campaign_description", ctx.getCampaignDescription());
|
||||
map.put("arcs", ctx.getArcs().stream()
|
||||
.map(this::arcSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper generic pour serialiser les entites structurelles (Arc/Chapter/Scene)
|
||||
* avec name, description et illustration_count conditionnel.
|
||||
*/
|
||||
private <T> Map<String, Object> structuralSummaryToMap(
|
||||
T entity,
|
||||
java.util.function.Function<T, String> nameExtractor,
|
||||
java.util.function.Function<T, String> descriptionExtractor,
|
||||
java.util.function.Function<T, Integer> illustrationCountExtractor,
|
||||
java.util.function.BiConsumer<Map<String, Object>, T> childSerializer) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("name", nameExtractor.apply(entity));
|
||||
map.put("description", descriptionExtractor.apply(entity));
|
||||
// Envoye au Python pour enrichir le prompt ("N illustrations attachees").
|
||||
// Serialise uniquement si > 0 pour economiser le payload sur les entites sans images.
|
||||
if (illustrationCountExtractor.apply(entity) > 0) {
|
||||
map.put("illustration_count", illustrationCountExtractor.apply(entity));
|
||||
}
|
||||
childSerializer.accept(map, entity);
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> arcSummaryToMap(ArcSummary a) {
|
||||
return structuralSummaryToMap(
|
||||
a,
|
||||
ArcSummary::getName,
|
||||
ArcSummary::getDescription,
|
||||
ArcSummary::getIllustrationCount,
|
||||
(map, arc) -> map.put("chapters", arc.getChapters().stream()
|
||||
.map(this::chapterSummaryToMap)
|
||||
.collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
private Map<String, Object> chapterSummaryToMap(ChapterSummary c) {
|
||||
return structuralSummaryToMap(
|
||||
c,
|
||||
ChapterSummary::getName,
|
||||
ChapterSummary::getDescription,
|
||||
ChapterSummary::getIllustrationCount,
|
||||
(map, chapter) -> map.put("scenes", chapter.getScenes().stream()
|
||||
.map(this::sceneSummaryToMap)
|
||||
.collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
private Map<String, Object> sceneSummaryToMap(SceneSummary s) {
|
||||
return structuralSummaryToMap(
|
||||
s,
|
||||
SceneSummary::getName,
|
||||
SceneSummary::getDescription,
|
||||
SceneSummary::getIllustrationCount,
|
||||
(map, scene) -> {
|
||||
// Branches narratives : serialise uniquement si presentes, pour garder
|
||||
// un payload leger sur les scenes lineaires classiques.
|
||||
if (s.getBranches() != null && !s.getBranches().isEmpty()) {
|
||||
map.put("branches", s.getBranches().stream()
|
||||
.map(this::branchHintToMap)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Map<String, Object> branchHintToMap(BranchHint b) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("label", b.getLabel());
|
||||
map.put("target_scene_name", b.getTargetSceneName());
|
||||
if (b.getCondition() != null && !b.getCondition().isBlank()) {
|
||||
map.put("condition", b.getCondition());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> narrativeEntityToMap(NarrativeEntityContext ne) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("entity_type", ne.getEntityType());
|
||||
map.put("title", ne.getTitle());
|
||||
map.put("fields", ne.getFields());
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||
import com.loremind.domain.generationcontext.ChatMessage;
|
||||
import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||
import com.loremind.domain.generationcontext.LoreStructuralContext.PageSummary;
|
||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||
import com.loremind.domain.generationcontext.PageContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Helper d'infrastructure : traduit un ChatRequest (domaine) vers le dict JSON
|
||||
* attendu par le Brain Python (/chat/stream).
|
||||
* <p>
|
||||
* Extrait de BrainAiChatClient pour isoler la responsabilité "sérialisation
|
||||
* de payload" (SRP) — le client HTTP se concentre désormais uniquement sur le
|
||||
* transport et le streaming SSE.
|
||||
* <p>
|
||||
* Chaque contexte optionnel (lore, page, campaign, entité narrative) est omis
|
||||
* si null, pour s'aligner sur le schéma Pydantic (champs Optional absents).
|
||||
*/
|
||||
@Component
|
||||
public class BrainChatPayloadBuilder {
|
||||
|
||||
public Map<String, Object> build(ChatRequest request) {
|
||||
Map<String, Object> root = new LinkedHashMap<>();
|
||||
root.put("messages", request.getMessages().stream()
|
||||
.map(this::messageToMap)
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
if (request.getLoreContext() != null) {
|
||||
root.put("lore_context", loreContextToMap(request.getLoreContext()));
|
||||
}
|
||||
if (request.getPageContext() != null) {
|
||||
root.put("page_context", pageContextToMap(request.getPageContext()));
|
||||
}
|
||||
if (request.getCampaignContext() != null) {
|
||||
root.put("campaign_context", campaignContextToMap(request.getCampaignContext()));
|
||||
}
|
||||
if (request.getNarrativeEntity() != null) {
|
||||
root.put("narrative_entity", narrativeEntityToMap(request.getNarrativeEntity()));
|
||||
}
|
||||
if (request.getGameSystemContext() != null) {
|
||||
root.put("game_system_context", gameSystemContextToMap(request.getGameSystemContext()));
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
private Map<String, Object> gameSystemContextToMap(GameSystemContext gs) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("system_name", gs.getSystemName());
|
||||
if (gs.getSystemDescription() != null && !gs.getSystemDescription().isBlank()) {
|
||||
map.put("system_description", gs.getSystemDescription());
|
||||
}
|
||||
map.put("sections", gs.getSections() != null ? gs.getSections() : Map.of());
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> messageToMap(ChatMessage m) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("role", m.role());
|
||||
map.put("content", m.content());
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> loreContextToMap(LoreStructuralContext ctx) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("lore_name", ctx.getLoreName());
|
||||
map.put("lore_description", ctx.getLoreDescription());
|
||||
|
||||
Map<String, Object> foldersMap = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<PageSummary>> e : ctx.getFolders().entrySet()) {
|
||||
foldersMap.put(e.getKey(), e.getValue().stream()
|
||||
.map(this::pageSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
map.put("folders", foldersMap);
|
||||
map.put("tags", ctx.getTags());
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> pageSummaryToMap(PageSummary ps) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("title", ps.getTitle());
|
||||
map.put("template_name", ps.getTemplateName());
|
||||
// values/tags/related_page_titles : omis si vides pour alléger le payload.
|
||||
if (ps.getValues() != null && !ps.getValues().isEmpty()) {
|
||||
map.put("values", ps.getValues());
|
||||
}
|
||||
if (ps.getTags() != null && !ps.getTags().isEmpty()) {
|
||||
map.put("tags", ps.getTags());
|
||||
}
|
||||
if (ps.getRelatedPageTitles() != null && !ps.getRelatedPageTitles().isEmpty()) {
|
||||
map.put("related_page_titles", ps.getRelatedPageTitles());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> pageContextToMap(PageContext pc) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("title", pc.getTitle());
|
||||
map.put("template_name", pc.getTemplateName());
|
||||
map.put("template_fields", pc.getTemplateFields());
|
||||
map.put("values", pc.getValues());
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> campaignContextToMap(CampaignStructuralContext ctx) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("campaign_name", ctx.getCampaignName());
|
||||
map.put("campaign_description", ctx.getCampaignDescription());
|
||||
map.put("arcs", ctx.getArcs().stream()
|
||||
.map(this::arcSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
// Liste des PJ : omise si aucun pour alléger le prompt des campagnes sans fiches.
|
||||
if (ctx.getCharacters() != null && !ctx.getCharacters().isEmpty()) {
|
||||
map.put("characters", ctx.getCharacters().stream()
|
||||
.map(this::characterSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> characterSummaryToMap(CharacterSummary c) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("name", c.getName());
|
||||
if (c.getSnippet() != null && !c.getSnippet().isBlank()) {
|
||||
map.put("snippet", c.getSnippet());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper générique pour sérialiser les entités structurelles (Arc/Chapter/Scene)
|
||||
* avec name, description et illustration_count conditionnel.
|
||||
*/
|
||||
private <T> Map<String, Object> structuralSummaryToMap(
|
||||
T entity,
|
||||
Function<T, String> nameExtractor,
|
||||
Function<T, String> descriptionExtractor,
|
||||
Function<T, Integer> illustrationCountExtractor,
|
||||
BiConsumer<Map<String, Object>, T> childSerializer) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("name", nameExtractor.apply(entity));
|
||||
map.put("description", descriptionExtractor.apply(entity));
|
||||
if (illustrationCountExtractor.apply(entity) > 0) {
|
||||
map.put("illustration_count", illustrationCountExtractor.apply(entity));
|
||||
}
|
||||
childSerializer.accept(map, entity);
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> arcSummaryToMap(ArcSummary a) {
|
||||
return structuralSummaryToMap(
|
||||
a,
|
||||
ArcSummary::getName,
|
||||
ArcSummary::getDescription,
|
||||
ArcSummary::getIllustrationCount,
|
||||
(map, arc) -> map.put("chapters", arc.getChapters().stream()
|
||||
.map(this::chapterSummaryToMap)
|
||||
.collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
private Map<String, Object> chapterSummaryToMap(ChapterSummary c) {
|
||||
return structuralSummaryToMap(
|
||||
c,
|
||||
ChapterSummary::getName,
|
||||
ChapterSummary::getDescription,
|
||||
ChapterSummary::getIllustrationCount,
|
||||
(map, chapter) -> map.put("scenes", chapter.getScenes().stream()
|
||||
.map(this::sceneSummaryToMap)
|
||||
.collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
private Map<String, Object> sceneSummaryToMap(SceneSummary s) {
|
||||
return structuralSummaryToMap(
|
||||
s,
|
||||
SceneSummary::getName,
|
||||
SceneSummary::getDescription,
|
||||
SceneSummary::getIllustrationCount,
|
||||
(map, scene) -> {
|
||||
// Branches narratives : omises si absentes (scènes linéaires classiques).
|
||||
if (s.getBranches() != null && !s.getBranches().isEmpty()) {
|
||||
map.put("branches", s.getBranches().stream()
|
||||
.map(this::branchHintToMap)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Map<String, Object> branchHintToMap(BranchHint b) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("label", b.getLabel());
|
||||
map.put("target_scene_name", b.getTargetSceneName());
|
||||
if (b.getCondition() != null && !b.getCondition().isBlank()) {
|
||||
map.put("condition", b.getCondition());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> narrativeEntityToMap(NarrativeEntityContext ne) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("entity_type", ne.getEntityType());
|
||||
map.put("title", ne.getTitle());
|
||||
map.put("fields", ne.getFields());
|
||||
return map;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
import com.loremind.domain.conversationcontext.ports.ConversationTitleGenerator;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Adaptateur : appelle le Brain POST /summarize/conversation-title pour
|
||||
* obtenir un titre court a partir des premiers messages.
|
||||
*
|
||||
* Fallback volontairement silencieux : si le Brain est indisponible, on
|
||||
* renvoie un titre par defaut plutot que de casser l'UX chat.
|
||||
*/
|
||||
@Component
|
||||
public class BrainConversationTitleClient implements ConversationTitleGenerator {
|
||||
|
||||
private static final String PATH = "/summarize/conversation-title";
|
||||
private static final String FALLBACK = "Nouvelle conversation";
|
||||
|
||||
private final WebClient webClient;
|
||||
|
||||
public BrainConversationTitleClient(
|
||||
WebClient.Builder builder,
|
||||
@Value("${brain.base-url}") String baseUrl) {
|
||||
this.webClient = builder.baseUrl(baseUrl).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generate(List<ConversationMessage> firstMessages) {
|
||||
if (firstMessages == null || firstMessages.isEmpty()) {
|
||||
return FALLBACK;
|
||||
}
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("messages", firstMessages.stream()
|
||||
.map(m -> Map.<String, Object>of(
|
||||
"role", m.getRole(),
|
||||
"content", m.getContent() == null ? "" : m.getContent()))
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> resp = webClient.post()
|
||||
.uri(PATH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.bodyValue(payload)
|
||||
.retrieve()
|
||||
.bodyToMono(Map.class)
|
||||
.timeout(Duration.ofSeconds(20))
|
||||
.block();
|
||||
if (resp == null) return FALLBACK;
|
||||
Object title = resp.get("title");
|
||||
if (title == null) return FALLBACK;
|
||||
String s = title.toString().trim();
|
||||
return s.isEmpty() ? FALLBACK : s;
|
||||
} catch (Exception e) {
|
||||
return FALLBACK;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Helper d'infrastructure : parse les payloads JSON véhiculés dans les
|
||||
* évènements SSE reçus du Brain Python.
|
||||
* <p>
|
||||
* Implémentation volontairement minimaliste (pas de Jackson ici) car les
|
||||
* schémas attendus sont figés et simples : {"token":"..."} et
|
||||
* {"system":N,"history":N,"current":N,"max":N}. Si la complexité augmente,
|
||||
* remplacer par un ObjectMapper + DTOs.
|
||||
*/
|
||||
@Component
|
||||
public class BrainSseParser {
|
||||
|
||||
/**
|
||||
* Parse un JSON {"system":N,"history":N,"current":N,"max":N} en ChatUsage.
|
||||
* Renvoie null si le payload est illisible — l'appelant décidera de ne
|
||||
* simplement pas propager l'usage (le stream token continue).
|
||||
*/
|
||||
public ChatUsage parseUsage(String json) {
|
||||
if (json == null) return null;
|
||||
try {
|
||||
int system = extractIntField(json, "system");
|
||||
int history = extractIntField(json, "history");
|
||||
int current = extractIntField(json, "current");
|
||||
int max = extractIntField(json, "max");
|
||||
return new ChatUsage(system, history, current, max);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse {"token":"..."} et renvoie la valeur du champ token (chaîne vide
|
||||
* ou null si introuvable).
|
||||
*/
|
||||
public String parseToken(String json) {
|
||||
if (json == null) return null;
|
||||
int idx = json.indexOf("\"token\"");
|
||||
if (idx < 0) return null;
|
||||
int colon = json.indexOf(':', idx);
|
||||
int firstQuote = json.indexOf('"', colon + 1);
|
||||
int lastQuote = json.lastIndexOf('"');
|
||||
if (firstQuote < 0 || lastQuote <= firstQuote) return null;
|
||||
return json.substring(firstQuote + 1, lastQuote)
|
||||
.replace("\\n", "\n")
|
||||
.replace("\\\"", "\"")
|
||||
.replace("\\\\", "\\");
|
||||
}
|
||||
|
||||
private int extractIntField(String json, String field) {
|
||||
String needle = "\"" + field + "\"";
|
||||
int idx = json.indexOf(needle);
|
||||
if (idx < 0) return 0;
|
||||
int colon = json.indexOf(':', idx);
|
||||
if (colon < 0) return 0;
|
||||
int start = colon + 1;
|
||||
while (start < json.length() && Character.isWhitespace(json.charAt(start))) start++;
|
||||
int end = start;
|
||||
while (end < json.length() && (Character.isDigit(json.charAt(end)) || json.charAt(end) == '-')) end++;
|
||||
if (end == start) return 0;
|
||||
return Integer.parseInt(json.substring(start, end));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.loremind.infrastructure.persistence;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Seed 3 rulesets libres au premier démarrage (si la table game_systems est vide).
|
||||
* <p>
|
||||
* Objectif : donner à l'utilisateur un point de départ pour comprendre le format
|
||||
* attendu (markdown structuré par titres H2) et permettre une démo "out of the box"
|
||||
* sans devoir taper ses propres règles.
|
||||
* <p>
|
||||
* Les rulesets fournis sont des <b>extraits libres</b> (Nimble, SRD 5.1 extrait,
|
||||
* homebrew exemple) — pas des règles officielles complètes. L'utilisateur est
|
||||
* libre de les éditer, supprimer, ou les utiliser comme template.
|
||||
* <p>
|
||||
* Idempotence : ne seed qu'une fois. Si l'utilisateur supprime un ruleset seedé,
|
||||
* il ne revient pas au redémarrage — c'est voulu (respect du choix utilisateur).
|
||||
*/
|
||||
@Component
|
||||
public class GameSystemSeeder {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GameSystemSeeder.class);
|
||||
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
|
||||
public GameSystemSeeder(GameSystemRepository gameSystemRepository) {
|
||||
this.gameSystemRepository = gameSystemRepository;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void seedIfEmpty() {
|
||||
if (!gameSystemRepository.findAll().isEmpty()) {
|
||||
log.debug("GameSystem seed skipped — table non vide.");
|
||||
return;
|
||||
}
|
||||
log.info("Seed initial des GameSystems (table vide)...");
|
||||
for (GameSystem gs : defaultSystems()) {
|
||||
gameSystemRepository.save(gs);
|
||||
}
|
||||
log.info("GameSystems seedés : {}", defaultSystems().size());
|
||||
}
|
||||
|
||||
private List<GameSystem> defaultSystems() {
|
||||
return List.of(
|
||||
GameSystem.builder()
|
||||
.name("Nimble (extrait)")
|
||||
.description("Système léger et narratif, résolution rapide des combats.")
|
||||
.author("LoreMind seed")
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(NIMBLE_RULES)
|
||||
.build(),
|
||||
GameSystem.builder()
|
||||
.name("D&D 5e SRD (extrait)")
|
||||
.description("Extrait libre des bases du System Reference Document 5.1.")
|
||||
.author("LoreMind seed")
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(DND_SRD_RULES)
|
||||
.build(),
|
||||
GameSystem.builder()
|
||||
.name("Homebrew Exemple")
|
||||
.description("Template minimaliste à dupliquer pour créer votre propre système.")
|
||||
.author("LoreMind seed")
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(HOMEBREW_EXAMPLE)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
private static final String NIMBLE_RULES = """
|
||||
Système Nimble — résolution rapide, narration fluide, peu de tableaux. Agnostique (aucun univers imposé).
|
||||
|
||||
## Combat
|
||||
- Initiative libre : les joueurs décrivent leur action dans l'ordre qu'ils veulent, le MJ joue les ennemis quand la fiction l'exige.
|
||||
- Résolution : 1d20 + mod, difficulté 10/15/20 (facile/normal/dur). 20 naturel = critique (double dégâts).
|
||||
- Dégâts : arme légère 1d6, arme lourde 1d10, projectile 1d8. Pas de table d'armure, l'armure augmente la difficulté à toucher.
|
||||
- Blessures : un PJ peut encaisser 3 blessures graves avant de tomber. Pas de PV fins — on raconte les coups.
|
||||
|
||||
## Classes
|
||||
- **Guerrier** : +2 en combat, peut relancer un dé de dégât 1×/scène.
|
||||
- **Explorateur** : +2 en perception/survie, ignore la première blessure d'une scène.
|
||||
- **Mage** : peut lancer un effet de magie par scène, nécessite une composante racontée.
|
||||
- **Barde** : +2 en social, peut inspirer un allié (relance de dé).
|
||||
|
||||
## Monstres
|
||||
Les monstres ont 3 stats : Menace (difficulté à toucher), Dégâts (dé de dégât), Résistance (nombre de blessures).
|
||||
Exemples : Gobelin (Menace 10, 1d6, 1), Ogre (Menace 13, 1d10, 3), Dragon adulte (Menace 18, 2d10, 6).
|
||||
""";
|
||||
|
||||
private static final String DND_SRD_RULES = """
|
||||
Extrait libre du SRD 5.1 (Open Game License). Pour les règles complètes, consulter le SRD officiel.
|
||||
|
||||
## Combat
|
||||
- Initiative : 1d20 + mod Dex au début du combat, ordre fixe par round.
|
||||
- Action par tour : une action, une action bonus (si classe le permet), une réaction, mouvement jusqu'à la vitesse.
|
||||
- Attaque : 1d20 + mod caractéristique + bonus maîtrise vs CA de la cible.
|
||||
- Dégâts : dé de l'arme + mod caractéristique. Critique sur 20 naturel (double les dés de dégâts).
|
||||
- Avantage/Désavantage : lancer 2d20 et garder le meilleur / pire.
|
||||
|
||||
## Classes
|
||||
- **Barbare** : d12 PV, rage (+dégâts, résistance). Caractéristique principale : Force.
|
||||
- **Barde** : d8 PV, sorts + inspiration bardique. Caractéristique : Charisme.
|
||||
- **Clerc** : d8 PV, sorts divins, canalise la divinité. Caractéristique : Sagesse.
|
||||
- **Druide** : d8 PV, sorts nature + forme animale. Caractéristique : Sagesse.
|
||||
- **Ensorceleur** : d6 PV, sorts innés + métamagie. Caractéristique : Charisme.
|
||||
- **Guerrier** : d10 PV, maîtrise martiale, second souffle. Caractéristique : Force ou Dextérité.
|
||||
- **Magicien** : d6 PV, livre de sorts, grande flexibilité. Caractéristique : Intelligence.
|
||||
- **Moine** : d8 PV, arts martiaux + ki. Caractéristique : Dextérité + Sagesse.
|
||||
- **Paladin** : d10 PV, sorts + serment + imposition des mains. Caractéristique : Force + Charisme.
|
||||
- **Rôdeur** : d10 PV, ennemi juré + explorateur + sorts. Caractéristique : Dextérité + Sagesse.
|
||||
- **Roublard** : d8 PV, attaque sournoise + expertise. Caractéristique : Dextérité.
|
||||
|
||||
## Monstres
|
||||
Stat block standard : CA, PV, Vitesse, For/Dex/Con/Int/Sag/Cha, jets de sauvegarde, compétences, sens, langues, Facteur de Puissance (FP).
|
||||
Exemples : Gobelin (FP 1/4, CA 15, 7 PV), Ogre (FP 2, CA 11, 59 PV), Dragon rouge adulte (FP 17, CA 19, 256 PV).
|
||||
""";
|
||||
|
||||
private static final String HOMEBREW_EXAMPLE = """
|
||||
Template vide à dupliquer et remplir pour créer votre propre système.
|
||||
|
||||
## Combat
|
||||
(Décrivez ici comment se résout un combat : initiative, jet d'attaque, dégâts, points de vie, critiques...)
|
||||
|
||||
## Classes
|
||||
(Listez les archétypes jouables : nom, stats de base, capacités signature.)
|
||||
|
||||
## Monstres
|
||||
(Format de stat block pour vos créatures : stats, capacités spéciales, FP/niveau.)
|
||||
|
||||
## Magie
|
||||
(Si votre système a un système de magie : écoles, coût, composantes, listes de sorts/pouvoirs.)
|
||||
|
||||
## Progression
|
||||
(Comment les PJ montent en puissance : XP, niveaux, acquisitions par niveau.)
|
||||
""";
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.lorecontext.FieldType;
|
||||
import com.loremind.domain.lorecontext.ImageLayout;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
@@ -72,8 +73,20 @@ public class TemplateFieldListJsonConverter
|
||||
// Type inconnu (ajoute par une version future) : fallback TEXT.
|
||||
type = FieldType.TEXT;
|
||||
}
|
||||
ImageLayout layout = null;
|
||||
if (type == FieldType.IMAGE) {
|
||||
String layoutStr = item.path("layout").asText(null);
|
||||
if (layoutStr != null && !layoutStr.isBlank()) {
|
||||
try {
|
||||
layout = ImageLayout.valueOf(layoutStr);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
// Layout inconnu : on laisse null → rendu GALLERY par defaut cote UI.
|
||||
layout = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (name != null && !name.isBlank()) {
|
||||
result.add(new TemplateField(name, type));
|
||||
result.add(new TemplateField(name, type, layout));
|
||||
}
|
||||
}
|
||||
// Autres types de noeuds (nombre, booleen...) : ignores silencieusement.
|
||||
|
||||
@@ -68,6 +68,12 @@ public class ArcJpaEntity {
|
||||
@Builder.Default
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
/** IDs des images "cartes / plans". */
|
||||
@Column(name = "map_image_ids", columnDefinition = "TEXT")
|
||||
@Convert(converter = StringListJsonConverter.class)
|
||||
@Builder.Default
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
|
||||
@@ -45,6 +45,13 @@ public class CampaignJpaEntity {
|
||||
@Column(name = "lore_id")
|
||||
private String loreId;
|
||||
|
||||
/**
|
||||
* ID du GameSystem associé (nullable).
|
||||
* Weak reference inter-contexte — pas de @ManyToOne / pas de FK DB.
|
||||
*/
|
||||
@Column(name = "game_system_id")
|
||||
private String gameSystemId;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
|
||||
@@ -57,6 +57,11 @@ public class ChapterJpaEntity {
|
||||
@Builder.Default
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
@Column(name = "map_image_ids", columnDefinition = "TEXT")
|
||||
@Convert(converter = StringListJsonConverter.class)
|
||||
@Builder.Default
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Entité JPA pour les fiches de personnages (PJ) d'une campagne.
|
||||
* Pas de FK physique vers campaigns (weak reference cross-agrégat intra-contexte :
|
||||
* on reste dans le Campaign Context, mais l'agrégat Character est autonome).
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "characters")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CharacterJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(name = "markdown_content", columnDefinition = "TEXT")
|
||||
private String markdownContent;
|
||||
|
||||
@Column(name = "campaign_id", nullable = false)
|
||||
private Long campaignId;
|
||||
|
||||
@Column(name = "\"order\"", nullable = false)
|
||||
private int order;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Index;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Persistance d'une conversation de chat IA.
|
||||
*
|
||||
* Les refs loreId / campaignId / entityId sont des weak references (String,
|
||||
* pas de FK) — coherent avec la politique inter-contexte du reste du code.
|
||||
* Indexes compose pour accelerer le listing par contexte dans la sidebar.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "conversations", indexes = {
|
||||
@Index(name = "idx_conv_lore_entity", columnList = "lore_id,entity_type,entity_id,updated_at"),
|
||||
@Index(name = "idx_conv_campaign_entity", columnList = "campaign_id,entity_type,entity_id,updated_at")
|
||||
})
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ConversationJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String title;
|
||||
|
||||
@Column(name = "lore_id")
|
||||
private String loreId;
|
||||
|
||||
@Column(name = "campaign_id")
|
||||
private String campaignId;
|
||||
|
||||
@Column(name = "entity_type")
|
||||
private String entityType;
|
||||
|
||||
@Column(name = "entity_id")
|
||||
private String entityId;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
/**
|
||||
* Messages enfants. Charges a la demande (fetch=LAZY) pour ne pas plomber
|
||||
* le listing sidebar. Cascade ALL + orphanRemoval : la suppression d'une
|
||||
* conversation efface ses messages.
|
||||
*/
|
||||
@OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
@OrderBy("createdAt ASC, id ASC")
|
||||
@Builder.Default
|
||||
private List<ConversationMessageJpaEntity> messages = new ArrayList<>();
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Persistance d'un message appartenant a une {@link ConversationJpaEntity}.
|
||||
* Les messages sont ordonnes par createdAt ASC (ordre d'ajout = ordre lu).
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "conversation_messages")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ConversationMessageJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
/** "user" | "assistant" | "system". */
|
||||
@Column(nullable = false, length = 16)
|
||||
private String role;
|
||||
|
||||
@Column(nullable = false, columnDefinition = "TEXT")
|
||||
private String content;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
/**
|
||||
* Reference vers la conversation parent. ToString exclu pour eviter une
|
||||
* boucle infinie quand Lombok genere toString() (conv -> messages -> conv...).
|
||||
*/
|
||||
@ManyToOne(optional = false)
|
||||
@JoinColumn(name = "conversation_id", nullable = false)
|
||||
@ToString.Exclude
|
||||
private ConversationJpaEntity conversation;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Entité JPA pour la persistance des GameSystems (systèmes de JDR).
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "game_systems")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class GameSystemJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String description;
|
||||
|
||||
@Column(name = "rules_markdown", columnDefinition = "TEXT")
|
||||
private String rulesMarkdown;
|
||||
|
||||
@Column
|
||||
private String author;
|
||||
|
||||
@Column(name = "is_public", nullable = false)
|
||||
private boolean isPublic;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,11 @@ public class SceneJpaEntity {
|
||||
@Builder.Default
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
@Column(name = "map_image_ids", columnDefinition = "TEXT")
|
||||
@Convert(converter = StringListJsonConverter.class)
|
||||
@Builder.Default
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
|
||||
// Graphe narratif intra-chapitre : sorties possibles vers d'autres scènes.
|
||||
// Persisté en TEXT JSON via converter (pattern homogène avec les autres listes).
|
||||
@Column(name = "branches", columnDefinition = "TEXT")
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.CharacterJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface CharacterJpaRepository extends JpaRepository<CharacterJpaEntity, Long> {
|
||||
|
||||
List<CharacterJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.ConversationJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Repository Spring Data JPA pour ConversationJpaEntity.
|
||||
*
|
||||
* Les requetes de listing par contexte gerent explicitement les NULL parce
|
||||
* que JPQL `=` ne matche pas NULL. On combine `IS NULL` / `=` selon si le
|
||||
* filtre est fourni — plus simple qu'une Specification Criteria API.
|
||||
*/
|
||||
@Repository
|
||||
public interface ConversationJpaRepository extends JpaRepository<ConversationJpaEntity, Long> {
|
||||
|
||||
/** Listing Lore racine (entity_type IS NULL). */
|
||||
@Query("""
|
||||
SELECT c FROM ConversationJpaEntity c
|
||||
WHERE c.loreId = :loreId
|
||||
AND c.entityType IS NULL
|
||||
ORDER BY c.updatedAt DESC
|
||||
""")
|
||||
List<ConversationJpaEntity> findByLoreRoot(@Param("loreId") String loreId);
|
||||
|
||||
/** Listing Lore + entite precise. */
|
||||
@Query("""
|
||||
SELECT c FROM ConversationJpaEntity c
|
||||
WHERE c.loreId = :loreId
|
||||
AND c.entityType = :entityType
|
||||
AND c.entityId = :entityId
|
||||
ORDER BY c.updatedAt DESC
|
||||
""")
|
||||
List<ConversationJpaEntity> findByLoreAndEntity(
|
||||
@Param("loreId") String loreId,
|
||||
@Param("entityType") String entityType,
|
||||
@Param("entityId") String entityId);
|
||||
|
||||
/** Listing Campagne racine. */
|
||||
@Query("""
|
||||
SELECT c FROM ConversationJpaEntity c
|
||||
WHERE c.campaignId = :campaignId
|
||||
AND c.entityType IS NULL
|
||||
ORDER BY c.updatedAt DESC
|
||||
""")
|
||||
List<ConversationJpaEntity> findByCampaignRoot(@Param("campaignId") String campaignId);
|
||||
|
||||
/** Listing Campagne + entite precise. */
|
||||
@Query("""
|
||||
SELECT c FROM ConversationJpaEntity c
|
||||
WHERE c.campaignId = :campaignId
|
||||
AND c.entityType = :entityType
|
||||
AND c.entityId = :entityId
|
||||
ORDER BY c.updatedAt DESC
|
||||
""")
|
||||
List<ConversationJpaEntity> findByCampaignAndEntity(
|
||||
@Param("campaignId") String campaignId,
|
||||
@Param("entityType") String entityType,
|
||||
@Param("entityId") String entityId);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.GameSystemJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface GameSystemJpaRepository extends JpaRepository<GameSystemJpaEntity, Long> {
|
||||
|
||||
@Query("SELECT g FROM GameSystemJpaEntity g WHERE LOWER(g.name) LIKE LOWER(CONCAT('%', :query, '%'))")
|
||||
List<GameSystemJpaEntity> findByNameContainingIgnoreCase(@Param("query") String query);
|
||||
}
|
||||
@@ -83,6 +83,9 @@ public class PostgresArcRepository implements ArcRepository {
|
||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||
: new ArrayList<>())
|
||||
.mapImageIds(jpaEntity.getMapImageIds() != null
|
||||
? new ArrayList<>(jpaEntity.getMapImageIds())
|
||||
: new ArrayList<>())
|
||||
.createdAt(jpaEntity.getCreatedAt())
|
||||
.updatedAt(jpaEntity.getUpdatedAt())
|
||||
.build();
|
||||
@@ -107,6 +110,9 @@ public class PostgresArcRepository implements ArcRepository {
|
||||
.illustrationImageIds(arc.getIllustrationImageIds() != null
|
||||
? new ArrayList<>(arc.getIllustrationImageIds())
|
||||
: new ArrayList<>())
|
||||
.mapImageIds(arc.getMapImageIds() != null
|
||||
? new ArrayList<>(arc.getMapImageIds())
|
||||
: new ArrayList<>())
|
||||
.createdAt(arc.getCreatedAt())
|
||||
.updatedAt(arc.getUpdatedAt())
|
||||
.build();
|
||||
|
||||
@@ -71,6 +71,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
||||
.updatedAt(jpaEntity.getUpdatedAt())
|
||||
.arcsCount(jpaEntity.getArcsCount())
|
||||
.loreId(jpaEntity.getLoreId())
|
||||
.gameSystemId(jpaEntity.getGameSystemId())
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -84,6 +85,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
||||
.updatedAt(campaign.getUpdatedAt())
|
||||
.arcsCount(campaign.getArcsCount())
|
||||
.loreId(campaign.getLoreId())
|
||||
.gameSystemId(campaign.getGameSystemId())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +80,9 @@ public class PostgresChapterRepository implements ChapterRepository {
|
||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||
: new ArrayList<>())
|
||||
.mapImageIds(jpaEntity.getMapImageIds() != null
|
||||
? new ArrayList<>(jpaEntity.getMapImageIds())
|
||||
: new ArrayList<>())
|
||||
.createdAt(jpaEntity.getCreatedAt())
|
||||
.updatedAt(jpaEntity.getUpdatedAt())
|
||||
.build();
|
||||
@@ -102,6 +105,9 @@ public class PostgresChapterRepository implements ChapterRepository {
|
||||
.illustrationImageIds(chapter.getIllustrationImageIds() != null
|
||||
? new ArrayList<>(chapter.getIllustrationImageIds())
|
||||
: new ArrayList<>())
|
||||
.mapImageIds(chapter.getMapImageIds() != null
|
||||
? new ArrayList<>(chapter.getMapImageIds())
|
||||
: new ArrayList<>())
|
||||
.createdAt(chapter.getCreatedAt())
|
||||
.updatedAt(chapter.getUpdatedAt())
|
||||
.build();
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.CharacterJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.CharacterJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Repository
|
||||
public class PostgresCharacterRepository implements CharacterRepository {
|
||||
|
||||
private final CharacterJpaRepository jpaRepository;
|
||||
|
||||
public PostgresCharacterRepository(CharacterJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Character save(Character character) {
|
||||
CharacterJpaEntity entity = toJpaEntity(character);
|
||||
CharacterJpaEntity saved = jpaRepository.save(entity);
|
||||
return toDomainEntity(saved);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Character> findById(String id) {
|
||||
return jpaRepository.findById(Long.parseLong(id)).map(this::toDomainEntity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Character> findByCampaignId(String campaignId) {
|
||||
return jpaRepository.findByCampaignIdOrderByOrderAsc(Long.parseLong(campaignId)).stream()
|
||||
.map(this::toDomainEntity)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(String id) {
|
||||
jpaRepository.deleteById(Long.parseLong(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsById(String id) {
|
||||
return jpaRepository.existsById(Long.parseLong(id));
|
||||
}
|
||||
|
||||
private Character toDomainEntity(CharacterJpaEntity e) {
|
||||
return Character.builder()
|
||||
.id(e.getId().toString())
|
||||
.name(e.getName())
|
||||
.markdownContent(e.getMarkdownContent())
|
||||
.campaignId(e.getCampaignId().toString())
|
||||
.order(e.getOrder())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.updatedAt(e.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
|
||||
private CharacterJpaEntity toJpaEntity(Character c) {
|
||||
Long id = c.getId() != null ? Long.parseLong(c.getId()) : null;
|
||||
return CharacterJpaEntity.builder()
|
||||
.id(id)
|
||||
.name(c.getName())
|
||||
.markdownContent(c.getMarkdownContent())
|
||||
.campaignId(Long.parseLong(c.getCampaignId()))
|
||||
.order(c.getOrder())
|
||||
.createdAt(c.getCreatedAt())
|
||||
.updatedAt(c.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.conversationcontext.Conversation;
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
import com.loremind.domain.conversationcontext.ports.ConversationRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.ConversationJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.entity.ConversationMessageJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.ConversationJpaRepository;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Adaptateur Postgres pour ConversationRepository.
|
||||
*
|
||||
* Les methodes de listing ne chargent PAS les messages (messages LAZY,
|
||||
* liste vide renvoyee cote domaine) — la sidebar n'a besoin que des
|
||||
* meta-donnees. findById charge les messages via fetch explicite de la
|
||||
* collection dans une transaction.
|
||||
*/
|
||||
@Repository
|
||||
public class PostgresConversationRepository implements ConversationRepository {
|
||||
|
||||
private final ConversationJpaRepository jpa;
|
||||
|
||||
public PostgresConversationRepository(ConversationJpaRepository jpa) {
|
||||
this.jpa = jpa;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public Conversation save(Conversation conversation) {
|
||||
ConversationJpaEntity entity = toJpaEntity(conversation);
|
||||
ConversationJpaEntity saved = jpa.save(entity);
|
||||
return toDomain(saved, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<Conversation> findById(String id) {
|
||||
return jpa.findById(Long.parseLong(id))
|
||||
.map(e -> {
|
||||
// Force l'initialisation LAZY avant de sortir de la transaction.
|
||||
e.getMessages().size();
|
||||
return toDomain(e, true);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<Conversation> findByContext(String loreId, String campaignId, String entityType, String entityId) {
|
||||
List<ConversationJpaEntity> rows;
|
||||
if (loreId != null) {
|
||||
rows = (entityType == null)
|
||||
? jpa.findByLoreRoot(loreId)
|
||||
: jpa.findByLoreAndEntity(loreId, entityType, entityId);
|
||||
} else if (campaignId != null) {
|
||||
rows = (entityType == null)
|
||||
? jpa.findByCampaignRoot(campaignId)
|
||||
: jpa.findByCampaignAndEntity(campaignId, entityType, entityId);
|
||||
} else {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return rows.stream().map(e -> toDomain(e, false)).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void deleteById(String id) {
|
||||
jpa.deleteById(Long.parseLong(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ConversationMessage appendMessage(String conversationId, ConversationMessage message) {
|
||||
ConversationJpaEntity conv = jpa.findById(Long.parseLong(conversationId))
|
||||
.orElseThrow(() -> new EntityNotFoundException("Conversation " + conversationId));
|
||||
|
||||
ConversationMessageJpaEntity msg = ConversationMessageJpaEntity.builder()
|
||||
.role(message.getRole())
|
||||
.content(message.getContent())
|
||||
.conversation(conv)
|
||||
.build();
|
||||
conv.getMessages().add(msg);
|
||||
// Force updatedAt via @PreUpdate en modifiant la conv (touch).
|
||||
conv.setUpdatedAt(java.time.LocalDateTime.now());
|
||||
|
||||
ConversationJpaEntity saved = jpa.save(conv);
|
||||
ConversationMessageJpaEntity persisted = saved.getMessages().get(saved.getMessages().size() - 1);
|
||||
return toDomainMessage(persisted);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void updateTitle(String conversationId, String title) {
|
||||
ConversationJpaEntity conv = jpa.findById(Long.parseLong(conversationId))
|
||||
.orElseThrow(() -> new EntityNotFoundException("Conversation " + conversationId));
|
||||
conv.setTitle(title);
|
||||
jpa.save(conv);
|
||||
}
|
||||
|
||||
// ---------- Mapping ----------
|
||||
|
||||
private ConversationJpaEntity toJpaEntity(Conversation c) {
|
||||
Long id = c.getId() != null ? Long.parseLong(c.getId()) : null;
|
||||
return ConversationJpaEntity.builder()
|
||||
.id(id)
|
||||
.title(c.getTitle())
|
||||
.loreId(c.getLoreId())
|
||||
.campaignId(c.getCampaignId())
|
||||
.entityType(c.getEntityType())
|
||||
.entityId(c.getEntityId())
|
||||
.createdAt(c.getCreatedAt())
|
||||
.updatedAt(c.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
|
||||
private Conversation toDomain(ConversationJpaEntity e, boolean withMessages) {
|
||||
List<ConversationMessage> msgs = withMessages
|
||||
? e.getMessages().stream().map(this::toDomainMessage).collect(Collectors.toList())
|
||||
: new java.util.ArrayList<>();
|
||||
return Conversation.builder()
|
||||
.id(e.getId().toString())
|
||||
.title(e.getTitle())
|
||||
.loreId(e.getLoreId())
|
||||
.campaignId(e.getCampaignId())
|
||||
.entityType(e.getEntityType())
|
||||
.entityId(e.getEntityId())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.updatedAt(e.getUpdatedAt())
|
||||
.messages(msgs)
|
||||
.build();
|
||||
}
|
||||
|
||||
private ConversationMessage toDomainMessage(ConversationMessageJpaEntity e) {
|
||||
return ConversationMessage.builder()
|
||||
.id(e.getId() != null ? e.getId().toString() : null)
|
||||
.role(e.getRole())
|
||||
.content(e.getContent())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.GameSystemJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.GameSystemJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Repository
|
||||
public class PostgresGameSystemRepository implements GameSystemRepository {
|
||||
|
||||
private final GameSystemJpaRepository jpaRepository;
|
||||
|
||||
public PostgresGameSystemRepository(GameSystemJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GameSystem save(GameSystem gameSystem) {
|
||||
GameSystemJpaEntity entity = toJpaEntity(gameSystem);
|
||||
GameSystemJpaEntity saved = jpaRepository.save(entity);
|
||||
return toDomainEntity(saved);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<GameSystem> findById(String id) {
|
||||
return jpaRepository.findById(Long.parseLong(id)).map(this::toDomainEntity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<GameSystem> findAll() {
|
||||
return jpaRepository.findAll().stream()
|
||||
.map(this::toDomainEntity)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(String id) {
|
||||
jpaRepository.deleteById(Long.parseLong(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsById(String id) {
|
||||
return jpaRepository.existsById(Long.parseLong(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<GameSystem> searchByName(String query) {
|
||||
return jpaRepository.findByNameContainingIgnoreCase(query).stream()
|
||||
.map(this::toDomainEntity)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private GameSystem toDomainEntity(GameSystemJpaEntity e) {
|
||||
return GameSystem.builder()
|
||||
.id(e.getId().toString())
|
||||
.name(e.getName())
|
||||
.description(e.getDescription())
|
||||
.rulesMarkdown(e.getRulesMarkdown())
|
||||
.author(e.getAuthor())
|
||||
.isPublic(e.isPublic())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.updatedAt(e.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
|
||||
private GameSystemJpaEntity toJpaEntity(GameSystem g) {
|
||||
Long id = g.getId() != null ? Long.parseLong(g.getId()) : null;
|
||||
return GameSystemJpaEntity.builder()
|
||||
.id(id)
|
||||
.name(g.getName())
|
||||
.description(g.getDescription())
|
||||
.rulesMarkdown(g.getRulesMarkdown())
|
||||
.author(g.getAuthor())
|
||||
.isPublic(g.isPublic())
|
||||
.createdAt(g.getCreatedAt())
|
||||
.updatedAt(g.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,9 @@ public class PostgresSceneRepository implements SceneRepository {
|
||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||
: new ArrayList<>())
|
||||
.mapImageIds(jpaEntity.getMapImageIds() != null
|
||||
? new ArrayList<>(jpaEntity.getMapImageIds())
|
||||
: new ArrayList<>())
|
||||
.branches(jpaEntity.getBranches() != null
|
||||
? new ArrayList<>(jpaEntity.getBranches())
|
||||
: new ArrayList<>())
|
||||
@@ -115,6 +118,9 @@ public class PostgresSceneRepository implements SceneRepository {
|
||||
.illustrationImageIds(scene.getIllustrationImageIds() != null
|
||||
? new ArrayList<>(scene.getIllustrationImageIds())
|
||||
: new ArrayList<>())
|
||||
.mapImageIds(scene.getMapImageIds() != null
|
||||
? new ArrayList<>(scene.getMapImageIds())
|
||||
: new ArrayList<>())
|
||||
.branches(scene.getBranches() != null
|
||||
? new ArrayList<>(scene.getBranches())
|
||||
: new ArrayList<>())
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.loremind.infrastructure.web.controller;
|
||||
import com.loremind.application.generationcontext.StreamChatForCampaignUseCase;
|
||||
import com.loremind.application.generationcontext.StreamChatForLoreUseCase;
|
||||
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;
|
||||
@@ -80,6 +81,7 @@ public class AiChatController {
|
||||
try {
|
||||
streamChatForLoreUseCase.execute(
|
||||
loreId, pageId, messages,
|
||||
usage -> sendUsage(emitter, usage),
|
||||
token -> sendToken(emitter, token),
|
||||
() -> complete(emitter),
|
||||
error -> fail(emitter, error));
|
||||
@@ -100,6 +102,7 @@ public class AiChatController {
|
||||
try {
|
||||
streamChatForCampaignUseCase.execute(
|
||||
campaignId, entityType, entityId, messages,
|
||||
usage -> sendUsage(emitter, usage),
|
||||
token -> sendToken(emitter, token),
|
||||
() -> complete(emitter),
|
||||
error -> fail(emitter, error));
|
||||
@@ -110,6 +113,18 @@ public class AiChatController {
|
||||
|
||||
// --- Helpers SSE (un seul point d'écriture par type d'événement) --------
|
||||
|
||||
private void sendUsage(SseEmitter emitter, ChatUsage usage) {
|
||||
try {
|
||||
String payload = "{\"system\":" + usage.system()
|
||||
+ ",\"history\":" + usage.history()
|
||||
+ ",\"current\":" + usage.current()
|
||||
+ ",\"max\":" + usage.max() + "}";
|
||||
emitter.send(SseEmitter.event().name("usage").data(payload));
|
||||
} catch (IOException e) {
|
||||
emitter.completeWithError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendToken(SseEmitter emitter, String token) {
|
||||
try {
|
||||
emitter.send(SseEmitter.event()
|
||||
|
||||
@@ -68,4 +68,12 @@ public class ArcController {
|
||||
arcService.deleteArc(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/deletion-impact")
|
||||
public ResponseEntity<ArcService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||
if (!arcService.arcExists(id)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(arcService.getDeletionImpact(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ public class CampaignController {
|
||||
public ResponseEntity<CampaignDTO> createCampaign(@RequestBody CampaignDTO campaignDTO) {
|
||||
Campaign campaign = campaignMapper.toDomain(campaignDTO);
|
||||
Campaign createdCampaign = campaignService.createCampaign(
|
||||
new CampaignService.CampaignData(campaign.getName(), campaign.getDescription(), campaign.getLoreId())
|
||||
new CampaignService.CampaignData(campaign.getName(), campaign.getDescription(), campaign.getLoreId(), campaign.getGameSystemId())
|
||||
);
|
||||
return ResponseEntity.ok(campaignMapper.toDTO(createdCampaign));
|
||||
}
|
||||
@@ -64,7 +64,7 @@ public class CampaignController {
|
||||
public ResponseEntity<CampaignDTO> updateCampaign(@PathVariable String id, @RequestBody CampaignDTO campaignDTO) {
|
||||
Campaign updatedCampaign = campaignService.updateCampaign(
|
||||
id,
|
||||
new CampaignService.CampaignData(campaignDTO.getName(), campaignDTO.getDescription(), campaignDTO.getLoreId())
|
||||
new CampaignService.CampaignData(campaignDTO.getName(), campaignDTO.getDescription(), campaignDTO.getLoreId(), campaignDTO.getGameSystemId())
|
||||
);
|
||||
return ResponseEntity.ok(campaignMapper.toDTO(updatedCampaign));
|
||||
}
|
||||
@@ -74,4 +74,16 @@ public class CampaignController {
|
||||
campaignService.deleteCampaign(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Récapitulatif des entités qui seront supprimées en cascade : utilisé par
|
||||
* l'UI pour afficher "X arcs, Y chapitres, Z scènes..." dans la confirmation.
|
||||
*/
|
||||
@GetMapping("/{id}/deletion-impact")
|
||||
public ResponseEntity<CampaignService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||
if (!campaignService.campaignExists(id)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(campaignService.getDeletionImpact(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,4 +68,12 @@ public class ChapterController {
|
||||
chapterService.deleteChapter(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/deletion-impact")
|
||||
public ResponseEntity<ChapterService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||
if (!chapterService.chapterExists(id)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(chapterService.getDeletionImpact(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.CharacterService;
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.CharacterDTO;
|
||||
import com.loremind.infrastructure.web.mapper.CharacterMapper;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/characters")
|
||||
public class CharacterController {
|
||||
|
||||
private final CharacterService characterService;
|
||||
private final CharacterMapper characterMapper;
|
||||
|
||||
public CharacterController(CharacterService characterService, CharacterMapper characterMapper) {
|
||||
this.characterService = characterService;
|
||||
this.characterMapper = characterMapper;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<CharacterDTO> createCharacter(@RequestBody CharacterDTO dto) {
|
||||
Character created = characterService.createCharacter(
|
||||
new CharacterService.CharacterData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), null)
|
||||
);
|
||||
return ResponseEntity.ok(characterMapper.toDTO(created));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<CharacterDTO> getCharacterById(@PathVariable String id) {
|
||||
return characterService.getCharacterById(id)
|
||||
.map(c -> ResponseEntity.ok(characterMapper.toDTO(c)))
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@GetMapping("/campaign/{campaignId}")
|
||||
public ResponseEntity<List<CharacterDTO>> getCharactersByCampaign(@PathVariable String campaignId) {
|
||||
List<CharacterDTO> dtos = characterService.getCharactersByCampaignId(campaignId).stream()
|
||||
.map(characterMapper::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
return ResponseEntity.ok(dtos);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<CharacterDTO> updateCharacter(@PathVariable String id, @RequestBody CharacterDTO dto) {
|
||||
Character updated = characterService.updateCharacter(
|
||||
id,
|
||||
new CharacterService.CharacterData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), dto.getOrder())
|
||||
);
|
||||
return ResponseEntity.ok(characterMapper.toDTO(updated));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> deleteCharacter(@PathVariable String id) {
|
||||
characterService.deleteCharacter(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.conversationcontext.ConversationService;
|
||||
import com.loremind.domain.conversationcontext.Conversation;
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
import com.loremind.infrastructure.web.dto.conversationcontext.AppendMessageDTO;
|
||||
import com.loremind.infrastructure.web.dto.conversationcontext.ConversationDTO;
|
||||
import com.loremind.infrastructure.web.dto.conversationcontext.ConversationMessageDTO;
|
||||
import com.loremind.infrastructure.web.dto.conversationcontext.CreateConversationDTO;
|
||||
import com.loremind.infrastructure.web.dto.conversationcontext.RenameConversationDTO;
|
||||
import com.loremind.infrastructure.web.mapper.ConversationMapper;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* API REST des conversations persistees.
|
||||
*
|
||||
* GET /api/conversations?loreId=...&entityType=...&entityId=... (listing filtre)
|
||||
* GET /api/conversations?campaignId=...&entityType=...&entityId=...
|
||||
* GET /api/conversations/{id} (detail + messages)
|
||||
* POST /api/conversations (create)
|
||||
* PATCH /api/conversations/{id}/title (rename)
|
||||
* DELETE /api/conversations/{id}
|
||||
*
|
||||
* L'ajout de messages est piloje cote chat stream (use case dedie),
|
||||
* pas par ce controller.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/conversations")
|
||||
public class ConversationController {
|
||||
|
||||
private final ConversationService service;
|
||||
private final ConversationMapper mapper;
|
||||
|
||||
public ConversationController(ConversationService service, ConversationMapper mapper) {
|
||||
this.service = service;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<ConversationDTO>> list(
|
||||
@RequestParam(required = false) String loreId,
|
||||
@RequestParam(required = false) String campaignId,
|
||||
@RequestParam(required = false) String entityType,
|
||||
@RequestParam(required = false) String entityId) {
|
||||
List<Conversation> rows = service.listByContext(loreId, campaignId, entityType, entityId);
|
||||
return ResponseEntity.ok(rows.stream().map(mapper::toListDTO).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<ConversationDTO> getById(@PathVariable String id) {
|
||||
return service.getById(id)
|
||||
.map(c -> ResponseEntity.ok(mapper.toDTO(c)))
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<ConversationDTO> create(@RequestBody CreateConversationDTO dto) {
|
||||
Conversation created = service.create(new ConversationService.CreateData(
|
||||
dto.getTitle(),
|
||||
dto.getLoreId(),
|
||||
dto.getCampaignId(),
|
||||
dto.getEntityType(),
|
||||
dto.getEntityId()));
|
||||
return ResponseEntity.ok(mapper.toDTO(created));
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}/title")
|
||||
public ResponseEntity<Void> rename(@PathVariable String id, @RequestBody RenameConversationDTO dto) {
|
||||
service.rename(id, dto.getTitle());
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable String id) {
|
||||
service.delete(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/messages")
|
||||
public ResponseEntity<ConversationMessageDTO> appendMessage(
|
||||
@PathVariable String id,
|
||||
@RequestBody AppendMessageDTO dto) {
|
||||
ConversationMessage saved = service.appendMessage(id, dto.getRole(), dto.getContent());
|
||||
return ResponseEntity.ok(mapper.toMessageDTO(saved));
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-genere et persiste un titre base sur les premiers messages.
|
||||
* Appele par le front apres le 1er couple user/assistant.
|
||||
*/
|
||||
@PostMapping("/{id}/auto-title")
|
||||
public ResponseEntity<RenameConversationDTO> autoTitle(@PathVariable String id) {
|
||||
String title = service.autoGenerateTitle(id);
|
||||
return ResponseEntity.ok(RenameConversationDTO.builder().title(title).build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.gamesystemcontext.GameSystemService;
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||
import com.loremind.infrastructure.web.mapper.GameSystemMapper;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/game-systems")
|
||||
public class GameSystemController {
|
||||
|
||||
private final GameSystemService gameSystemService;
|
||||
private final GameSystemMapper gameSystemMapper;
|
||||
|
||||
public GameSystemController(GameSystemService gameSystemService, GameSystemMapper gameSystemMapper) {
|
||||
this.gameSystemService = gameSystemService;
|
||||
this.gameSystemMapper = gameSystemMapper;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<GameSystemDTO> createGameSystem(@RequestBody GameSystemDTO dto) {
|
||||
GameSystem created = gameSystemService.createGameSystem(toData(dto));
|
||||
return ResponseEntity.ok(gameSystemMapper.toDTO(created));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<GameSystemDTO> getGameSystemById(@PathVariable String id) {
|
||||
return gameSystemService.getGameSystemById(id)
|
||||
.map(g -> ResponseEntity.ok(gameSystemMapper.toDTO(g)))
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<GameSystemDTO>> getAllGameSystems() {
|
||||
List<GameSystemDTO> dtos = gameSystemService.getAllGameSystems().stream()
|
||||
.map(gameSystemMapper::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
return ResponseEntity.ok(dtos);
|
||||
}
|
||||
|
||||
@GetMapping("/search")
|
||||
public ResponseEntity<List<GameSystemDTO>> searchGameSystems(@RequestParam("q") String query) {
|
||||
List<GameSystemDTO> dtos = gameSystemService.searchGameSystems(query).stream()
|
||||
.map(gameSystemMapper::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
return ResponseEntity.ok(dtos);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<GameSystemDTO> updateGameSystem(@PathVariable String id, @RequestBody GameSystemDTO dto) {
|
||||
GameSystem updated = gameSystemService.updateGameSystem(id, toData(dto));
|
||||
return ResponseEntity.ok(gameSystemMapper.toDTO(updated));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> deleteGameSystem(@PathVariable String id) {
|
||||
gameSystemService.deleteGameSystem(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private GameSystemService.GameSystemData toData(GameSystemDTO dto) {
|
||||
return new GameSystemService.GameSystemData(
|
||||
dto.getName(),
|
||||
dto.getDescription(),
|
||||
dto.getRulesMarkdown(),
|
||||
dto.getAuthor(),
|
||||
dto.isPublic()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,10 @@ public class ImageController {
|
||||
.contentType(MediaType.parseMediaType(img.getContentType()))
|
||||
.contentLength(img.getSizeBytes())
|
||||
.header(HttpHeaders.CACHE_CONTROL, "public, max-age=31536000, immutable")
|
||||
// Autorise explicitement l'utilisation cross-origin du binaire dans une <img>.
|
||||
// Sans ce header, Firefox 109+ applique ORB (Opaque Response Blocking) et
|
||||
// bloque l'image quand le front (localhost:4200) la charge depuis l'API (localhost:8080).
|
||||
.header("Cross-Origin-Resource-Policy", "cross-origin")
|
||||
.body(new InputStreamResource(stream));
|
||||
}
|
||||
|
||||
|
||||
@@ -69,4 +69,17 @@ public class LoreController {
|
||||
loreService.deleteLore(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Récapitulatif des entités qui seront supprimées / détachées en cascade.
|
||||
* Utilisé par l'UI pour afficher "X dossiers, Y pages, Z templates,
|
||||
* N campagne(s) détachée(s)" dans la confirmation.
|
||||
*/
|
||||
@GetMapping("/{id}/deletion-impact")
|
||||
public ResponseEntity<LoreService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||
if (loreService.getLoreById(id).isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(loreService.getDeletionImpact(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,4 +97,16 @@ public class LoreNodeController {
|
||||
loreNodeService.deleteLoreNode(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Récapitulatif des entités qui seront supprimées en cascade : utilisé par
|
||||
* l'UI pour afficher "X sous-dossiers, Y pages..." dans la confirmation.
|
||||
*/
|
||||
@GetMapping("/{id}/deletion-impact")
|
||||
public ResponseEntity<LoreNodeService.DeletionImpact> getDeletionImpact(@PathVariable String id) {
|
||||
if (loreNodeService.getLoreNodeById(id).isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(loreNodeService.getDeletionImpact(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -53,6 +54,11 @@ public class SettingsController {
|
||||
return forward(HttpMethod.GET, "/models/ollama", null);
|
||||
}
|
||||
|
||||
@PostMapping("/models/ollama/info")
|
||||
public ResponseEntity<Map<String, Object>> getOllamaModelInfo(@RequestBody Map<String, Object> body) {
|
||||
return forward(HttpMethod.POST, "/models/ollama/info", body);
|
||||
}
|
||||
|
||||
@GetMapping("/models/onemin")
|
||||
public ResponseEntity<Map<String, Object>> listOneMinModels() {
|
||||
return forward(HttpMethod.GET, "/models/onemin", null);
|
||||
|
||||
@@ -27,6 +27,9 @@ public class ArcDTO {
|
||||
/** IDs des pages du Lore liées à cet arc (weak cross-context references). */
|
||||
private List<String> relatedPageIds = new ArrayList<>();
|
||||
|
||||
/** IDs des images (Shared Kernel) illustrant cet arc. */
|
||||
/** IDs des images (Shared Kernel) illustrant cet arc (ambiance). */
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
/** IDs des images utilisees comme cartes / plans. */
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
}
|
||||
|
||||
@@ -15,4 +15,6 @@ public class CampaignDTO {
|
||||
private int arcsCount;
|
||||
/** Nullable : campagne sans univers associé. */
|
||||
private String loreId;
|
||||
/** Nullable : campagne sans système de JDR associé (générique). */
|
||||
private String gameSystemId;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ public class ChapterDTO {
|
||||
/** IDs des pages du Lore liées (weak cross-context references). */
|
||||
private List<String> relatedPageIds = new ArrayList<>();
|
||||
|
||||
/** IDs des images (Shared Kernel) illustrant ce chapitre. */
|
||||
/** IDs des images (Shared Kernel) illustrant ce chapitre (ambiance). */
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
/** IDs des images utilisees comme cartes / plans. */
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.loremind.infrastructure.web.dto.campaigncontext;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* DTO pour les fiches de personnages (PJ) d'une campagne.
|
||||
*/
|
||||
@Data
|
||||
public class CharacterDTO {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String markdownContent;
|
||||
private String campaignId;
|
||||
private int order;
|
||||
}
|
||||
@@ -30,9 +30,12 @@ public class SceneDTO {
|
||||
/** IDs des pages du Lore liées (weak cross-context references). */
|
||||
private List<String> relatedPageIds = new ArrayList<>();
|
||||
|
||||
/** IDs des images (Shared Kernel) illustrant cette scene. */
|
||||
/** IDs des images (Shared Kernel) illustrant cette scene (ambiance). */
|
||||
private List<String> illustrationImageIds = new ArrayList<>();
|
||||
|
||||
/** IDs des images utilisees comme cartes / plans (outil de table). */
|
||||
private List<String> mapImageIds = new ArrayList<>();
|
||||
|
||||
/** Branches narratives : sorties possibles vers d'autres scènes du même chapitre. */
|
||||
private List<SceneBranchDTO> branches = new ArrayList<>();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AppendMessageDTO {
|
||||
/** "user" | "assistant" | "system". */
|
||||
private String role;
|
||||
private String content;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* DTO d'une conversation. Les messages sont inclus uniquement sur GET /{id}
|
||||
* (null pour les reponses de listing afin d'alleger la sidebar).
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ConversationDTO {
|
||||
private String id;
|
||||
private String title;
|
||||
private String loreId;
|
||||
private String campaignId;
|
||||
private String entityType;
|
||||
private String entityId;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
private List<ConversationMessageDTO> messages;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ConversationMessageDTO {
|
||||
private String id;
|
||||
private String role;
|
||||
private String content;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* Payload de creation. Le client fournit l'ancrage (lore ou campagne, +/-
|
||||
* entite focus). Le titre est optionnel — sera auto-genere apres le 1er
|
||||
* echange IA si absent.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CreateConversationDTO {
|
||||
private String title;
|
||||
private String loreId;
|
||||
private String campaignId;
|
||||
private String entityType;
|
||||
private String entityId;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.loremind.infrastructure.web.dto.conversationcontext;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RenameConversationDTO {
|
||||
private String title;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.loremind.infrastructure.web.dto.gamesystemcontext;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* DTO pour l'entité GameSystem (système de JDR).
|
||||
*/
|
||||
@Data
|
||||
public class GameSystemDTO {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String rulesMarkdown;
|
||||
private String author;
|
||||
private boolean isPublic;
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import lombok.NoArgsConstructor;
|
||||
* <p>
|
||||
* Miroir wire-friendly de {@link com.loremind.domain.lorecontext.TemplateField}.
|
||||
* Le type est serialise en string (TEXT/IMAGE) pour interop facile avec Angular.
|
||||
* Le layout (null pour TEXT, ou GALLERY/HERO/MASONRY/CAROUSEL pour IMAGE) pilote
|
||||
* le rendu visuel des champs image cote front.
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@@ -17,4 +19,11 @@ public class TemplateFieldDTO {
|
||||
private String name;
|
||||
/** "TEXT" ou "IMAGE" (string pour serialisation JSON transparente). */
|
||||
private String type;
|
||||
/** "GALLERY" | "HERO" | "MASONRY" | "CAROUSEL", null si type=TEXT. */
|
||||
private String layout;
|
||||
|
||||
/** Retrocompat : constructeur sans layout. */
|
||||
public TemplateFieldDTO(String name, String type) {
|
||||
this(name, type, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ public class ArcMapper {
|
||||
dto.setResolution(arc.getResolution());
|
||||
dto.setRelatedPageIds(copyList(arc.getRelatedPageIds()));
|
||||
dto.setIllustrationImageIds(copyList(arc.getIllustrationImageIds()));
|
||||
dto.setMapImageIds(copyList(arc.getMapImageIds()));
|
||||
return dto;
|
||||
}
|
||||
|
||||
@@ -52,6 +53,7 @@ public class ArcMapper {
|
||||
.resolution(dto.getResolution())
|
||||
.relatedPageIds(copyList(dto.getRelatedPageIds()))
|
||||
.illustrationImageIds(copyList(dto.getIllustrationImageIds()))
|
||||
.mapImageIds(copyList(dto.getMapImageIds()))
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ public class CampaignMapper {
|
||||
dto.setDescription(campaign.getDescription());
|
||||
dto.setArcsCount(campaign.getArcsCount());
|
||||
dto.setLoreId(campaign.getLoreId());
|
||||
dto.setGameSystemId(campaign.getGameSystemId());
|
||||
return dto;
|
||||
}
|
||||
|
||||
@@ -35,6 +36,7 @@ public class CampaignMapper {
|
||||
.description(dto.getDescription())
|
||||
.arcsCount(dto.getArcsCount())
|
||||
.loreId(dto.getLoreId())
|
||||
.gameSystemId(dto.getGameSystemId())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ public class ChapterMapper {
|
||||
dto.setNarrativeStakes(chapter.getNarrativeStakes());
|
||||
dto.setRelatedPageIds(copyList(chapter.getRelatedPageIds()));
|
||||
dto.setIllustrationImageIds(copyList(chapter.getIllustrationImageIds()));
|
||||
dto.setMapImageIds(copyList(chapter.getMapImageIds()));
|
||||
return dto;
|
||||
}
|
||||
|
||||
@@ -48,6 +49,7 @@ public class ChapterMapper {
|
||||
.narrativeStakes(dto.getNarrativeStakes())
|
||||
.relatedPageIds(copyList(dto.getRelatedPageIds()))
|
||||
.illustrationImageIds(copyList(dto.getIllustrationImageIds()))
|
||||
.mapImageIds(copyList(dto.getMapImageIds()))
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.loremind.infrastructure.web.mapper;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.CharacterDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CharacterMapper {
|
||||
|
||||
public CharacterDTO toDTO(Character c) {
|
||||
if (c == null) return null;
|
||||
CharacterDTO dto = new CharacterDTO();
|
||||
dto.setId(c.getId());
|
||||
dto.setName(c.getName());
|
||||
dto.setMarkdownContent(c.getMarkdownContent());
|
||||
dto.setCampaignId(c.getCampaignId());
|
||||
dto.setOrder(c.getOrder());
|
||||
return dto;
|
||||
}
|
||||
|
||||
public Character toDomain(CharacterDTO dto) {
|
||||
if (dto == null) return null;
|
||||
return Character.builder()
|
||||
.id(dto.getId())
|
||||
.name(dto.getName())
|
||||
.markdownContent(dto.getMarkdownContent())
|
||||
.campaignId(dto.getCampaignId())
|
||||
.order(dto.getOrder())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.loremind.infrastructure.web.mapper;
|
||||
|
||||
import com.loremind.domain.conversationcontext.Conversation;
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
import com.loremind.infrastructure.web.dto.conversationcontext.ConversationDTO;
|
||||
import com.loremind.infrastructure.web.dto.conversationcontext.ConversationMessageDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Conversion Domaine <-> DTO pour le contexte Conversation.
|
||||
*
|
||||
* {@link #toListDTO(Conversation)} omet les messages — utilise pour le
|
||||
* listing sidebar ou on n'expose que les metadonnees.
|
||||
*/
|
||||
@Component
|
||||
public class ConversationMapper {
|
||||
|
||||
public ConversationDTO toDTO(Conversation c) {
|
||||
List<ConversationMessageDTO> msgs = c.getMessages() == null
|
||||
? List.of()
|
||||
: c.getMessages().stream().map(this::toMessageDTO).collect(Collectors.toList());
|
||||
return ConversationDTO.builder()
|
||||
.id(c.getId())
|
||||
.title(c.getTitle())
|
||||
.loreId(c.getLoreId())
|
||||
.campaignId(c.getCampaignId())
|
||||
.entityType(c.getEntityType())
|
||||
.entityId(c.getEntityId())
|
||||
.createdAt(c.getCreatedAt())
|
||||
.updatedAt(c.getUpdatedAt())
|
||||
.messages(msgs)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Variante listing : pas de messages pour alleger la payload. */
|
||||
public ConversationDTO toListDTO(Conversation c) {
|
||||
return ConversationDTO.builder()
|
||||
.id(c.getId())
|
||||
.title(c.getTitle())
|
||||
.loreId(c.getLoreId())
|
||||
.campaignId(c.getCampaignId())
|
||||
.entityType(c.getEntityType())
|
||||
.entityId(c.getEntityId())
|
||||
.createdAt(c.getCreatedAt())
|
||||
.updatedAt(c.getUpdatedAt())
|
||||
.messages(null)
|
||||
.build();
|
||||
}
|
||||
|
||||
public ConversationMessageDTO toMessageDTO(ConversationMessage m) {
|
||||
return ConversationMessageDTO.builder()
|
||||
.id(m.getId())
|
||||
.role(m.getRole())
|
||||
.content(m.getContent())
|
||||
.createdAt(m.getCreatedAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.loremind.infrastructure.web.mapper;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class GameSystemMapper {
|
||||
|
||||
public GameSystemDTO toDTO(GameSystem g) {
|
||||
if (g == null) return null;
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
dto.setId(g.getId());
|
||||
dto.setName(g.getName());
|
||||
dto.setDescription(g.getDescription());
|
||||
dto.setRulesMarkdown(g.getRulesMarkdown());
|
||||
dto.setAuthor(g.getAuthor());
|
||||
dto.setPublic(g.isPublic());
|
||||
return dto;
|
||||
}
|
||||
|
||||
public GameSystem toDomain(GameSystemDTO dto) {
|
||||
if (dto == null) return null;
|
||||
return GameSystem.builder()
|
||||
.id(dto.getId())
|
||||
.name(dto.getName())
|
||||
.description(dto.getDescription())
|
||||
.rulesMarkdown(dto.getRulesMarkdown())
|
||||
.author(dto.getAuthor())
|
||||
.isPublic(dto.isPublic())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,9 @@ public class SceneMapper {
|
||||
dto.setIllustrationImageIds(scene.getIllustrationImageIds() != null
|
||||
? new ArrayList<>(scene.getIllustrationImageIds())
|
||||
: new ArrayList<>());
|
||||
dto.setMapImageIds(scene.getMapImageIds() != null
|
||||
? new ArrayList<>(scene.getMapImageIds())
|
||||
: new ArrayList<>());
|
||||
dto.setBranches(toBranchDTOs(scene.getBranches()));
|
||||
return dto;
|
||||
}
|
||||
@@ -70,6 +73,9 @@ public class SceneMapper {
|
||||
.illustrationImageIds(dto.getIllustrationImageIds() != null
|
||||
? new ArrayList<>(dto.getIllustrationImageIds())
|
||||
: new ArrayList<>())
|
||||
.mapImageIds(dto.getMapImageIds() != null
|
||||
? new ArrayList<>(dto.getMapImageIds())
|
||||
: new ArrayList<>())
|
||||
.branches(toBranchDomain(dto.getBranches()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.loremind.infrastructure.web.mapper;
|
||||
|
||||
import com.loremind.domain.lorecontext.FieldType;
|
||||
import com.loremind.domain.lorecontext.ImageLayout;
|
||||
import com.loremind.domain.lorecontext.TemplateField;
|
||||
import com.loremind.infrastructure.web.dto.lorecontext.TemplateFieldDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -11,6 +12,8 @@ import org.springframework.stereotype.Component;
|
||||
* <p>
|
||||
* Tolerance : un type inconnu recu du client est interprete comme TEXT
|
||||
* (plus safe que de rejeter la requete et d'interrompre la sauvegarde).
|
||||
* Un layout inconnu ou absent sur un champ IMAGE est interprete comme GALLERY.
|
||||
* Le layout est force a null pour les champs TEXT.
|
||||
*/
|
||||
@Component
|
||||
public class TemplateFieldMapper {
|
||||
@@ -18,7 +21,12 @@ public class TemplateFieldMapper {
|
||||
public TemplateFieldDTO toDTO(TemplateField field) {
|
||||
if (field == null) return null;
|
||||
String typeStr = field.getType() != null ? field.getType().name() : FieldType.TEXT.name();
|
||||
return new TemplateFieldDTO(field.getName(), typeStr);
|
||||
String layoutStr = null;
|
||||
if (field.getType() == FieldType.IMAGE) {
|
||||
ImageLayout layout = field.getLayout() != null ? field.getLayout() : ImageLayout.GALLERY;
|
||||
layoutStr = layout.name();
|
||||
}
|
||||
return new TemplateFieldDTO(field.getName(), typeStr, layoutStr);
|
||||
}
|
||||
|
||||
public TemplateField toDomain(TemplateFieldDTO dto) {
|
||||
@@ -29,6 +37,16 @@ public class TemplateFieldMapper {
|
||||
} catch (IllegalArgumentException ex) {
|
||||
type = FieldType.TEXT;
|
||||
}
|
||||
return new TemplateField(dto.getName(), type);
|
||||
ImageLayout layout = null;
|
||||
if (type == FieldType.IMAGE) {
|
||||
try {
|
||||
layout = dto.getLayout() != null
|
||||
? ImageLayout.valueOf(dto.getLayout())
|
||||
: ImageLayout.GALLERY;
|
||||
} catch (IllegalArgumentException ex) {
|
||||
layout = ImageLayout.GALLERY;
|
||||
}
|
||||
}
|
||||
return new TemplateField(dto.getName(), type, layout);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Scene;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -14,6 +18,7 @@ import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
@@ -26,6 +31,10 @@ public class ArcServiceTest {
|
||||
|
||||
@Mock
|
||||
private ArcRepository arcRepository;
|
||||
@Mock
|
||||
private ChapterRepository chapterRepository;
|
||||
@Mock
|
||||
private SceneRepository sceneRepository;
|
||||
|
||||
@InjectMocks
|
||||
private ArcService arcService;
|
||||
@@ -159,15 +168,48 @@ public class ArcServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteArc() {
|
||||
// Arrange
|
||||
doNothing().when(arcRepository).deleteById("arc-1");
|
||||
|
||||
// Act
|
||||
void testDeleteArc_EmptyArc() {
|
||||
// Aucun chapitre : Mockito renvoie List.of() par défaut.
|
||||
arcService.deleteArc("arc-1");
|
||||
|
||||
// Assert
|
||||
verify(arcRepository, times(1)).deleteById("arc-1");
|
||||
verify(arcRepository).deleteById("arc-1");
|
||||
verify(chapterRepository, never()).deleteById(anyString());
|
||||
verify(sceneRepository, never()).deleteById(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteArc_CascadesChaptersAndScenes() {
|
||||
Chapter chapter = Chapter.builder().id("chap-1").arcId("arc-1").name("C").build();
|
||||
Scene s1 = Scene.builder().id("s-1").chapterId("chap-1").name("S1").build();
|
||||
Scene s2 = Scene.builder().id("s-2").chapterId("chap-1").name("S2").build();
|
||||
|
||||
when(chapterRepository.findByArcId("arc-1")).thenReturn(List.of(chapter));
|
||||
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of(s1, s2));
|
||||
|
||||
arcService.deleteArc("arc-1");
|
||||
|
||||
verify(sceneRepository).deleteById("s-1");
|
||||
verify(sceneRepository).deleteById("s-2");
|
||||
verify(chapterRepository).deleteById("chap-1");
|
||||
verify(arcRepository).deleteById("arc-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetDeletionImpact() {
|
||||
Chapter c1 = Chapter.builder().id("chap-1").arcId("arc-1").name("C1").build();
|
||||
Chapter c2 = Chapter.builder().id("chap-2").arcId("arc-1").name("C2").build();
|
||||
Scene s1 = Scene.builder().id("s-1").chapterId("chap-1").name("S1").build();
|
||||
Scene s2 = Scene.builder().id("s-2").chapterId("chap-2").name("S2").build();
|
||||
Scene s3 = Scene.builder().id("s-3").chapterId("chap-2").name("S3").build();
|
||||
|
||||
when(chapterRepository.findByArcId("arc-1")).thenReturn(List.of(c1, c2));
|
||||
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of(s1));
|
||||
when(sceneRepository.findByChapterId("chap-2")).thenReturn(List.of(s2, s3));
|
||||
|
||||
ArcService.DeletionImpact impact = arcService.getDeletionImpact("arc-1");
|
||||
|
||||
assertEquals(2, impact.chapters());
|
||||
assertEquals(3, impact.scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.Scene;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -27,6 +35,14 @@ public class CampaignServiceTest {
|
||||
|
||||
@Mock
|
||||
private CampaignRepository campaignRepository;
|
||||
@Mock
|
||||
private ArcRepository arcRepository;
|
||||
@Mock
|
||||
private ChapterRepository chapterRepository;
|
||||
@Mock
|
||||
private SceneRepository sceneRepository;
|
||||
@Mock
|
||||
private CharacterRepository characterRepository;
|
||||
|
||||
@InjectMocks
|
||||
private CampaignService campaignService;
|
||||
@@ -50,9 +66,13 @@ public class CampaignServiceTest {
|
||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||
"New Campaign",
|
||||
"Description",
|
||||
"lore-123"
|
||||
"lore-123",
|
||||
null
|
||||
);
|
||||
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
||||
// Le repo renvoie la Campaign telle que passée — on teste la normalisation
|
||||
// du loreId dans le service, pas le comportement du repo.
|
||||
when(campaignRepository.save(any(Campaign.class)))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
// Act
|
||||
Campaign result = campaignService.createCampaign(data);
|
||||
@@ -69,9 +89,11 @@ public class CampaignServiceTest {
|
||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||
"New Campaign",
|
||||
"Description",
|
||||
null,
|
||||
null
|
||||
);
|
||||
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
||||
when(campaignRepository.save(any(Campaign.class)))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
// Act
|
||||
Campaign result = campaignService.createCampaign(data);
|
||||
@@ -88,9 +110,11 @@ public class CampaignServiceTest {
|
||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||
"New Campaign",
|
||||
"Description",
|
||||
" "
|
||||
" ",
|
||||
null
|
||||
);
|
||||
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
||||
when(campaignRepository.save(any(Campaign.class)))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
// Act
|
||||
Campaign result = campaignService.createCampaign(data);
|
||||
@@ -151,7 +175,8 @@ public class CampaignServiceTest {
|
||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||
"Updated Campaign",
|
||||
"Updated Description",
|
||||
"lore-456"
|
||||
"lore-456",
|
||||
null
|
||||
);
|
||||
when(campaignRepository.findById("campaign-1")).thenReturn(Optional.of(testCampaign));
|
||||
when(campaignRepository.save(any(Campaign.class))).thenReturn(testCampaign);
|
||||
@@ -171,7 +196,8 @@ public class CampaignServiceTest {
|
||||
CampaignService.CampaignData data = new CampaignService.CampaignData(
|
||||
"Updated Campaign",
|
||||
"Updated Description",
|
||||
"lore-456"
|
||||
"lore-456",
|
||||
null
|
||||
);
|
||||
when(campaignRepository.findById("invalid-id")).thenReturn(Optional.empty());
|
||||
|
||||
@@ -186,15 +212,75 @@ public class CampaignServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteCampaign() {
|
||||
// Arrange
|
||||
doNothing().when(campaignRepository).deleteById("campaign-1");
|
||||
|
||||
void testDeleteCampaign_EmptyCampaign() {
|
||||
// Arrange : aucune dépendance ; Mockito renvoie List.of() par défaut.
|
||||
// Act
|
||||
campaignService.deleteCampaign("campaign-1");
|
||||
|
||||
// Assert
|
||||
verify(campaignRepository, times(1)).deleteById("campaign-1");
|
||||
verify(arcRepository, never()).deleteById(anyString());
|
||||
verify(chapterRepository, never()).deleteById(anyString());
|
||||
verify(sceneRepository, never()).deleteById(anyString());
|
||||
verify(characterRepository, never()).deleteById(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteCampaign_CascadesArcsChaptersScenes() {
|
||||
// Arrange : campagne avec 1 arc → 1 chapitre → 2 scènes.
|
||||
Arc arc = Arc.builder().id("arc-1").campaignId("campaign-1").name("Arc 1").build();
|
||||
Chapter chapter = Chapter.builder().id("chap-1").arcId("arc-1").name("Chap 1").build();
|
||||
Scene scene1 = Scene.builder().id("scene-1").chapterId("chap-1").name("Scene 1").build();
|
||||
Scene scene2 = Scene.builder().id("scene-2").chapterId("chap-1").name("Scene 2").build();
|
||||
|
||||
when(arcRepository.findByCampaignId("campaign-1")).thenReturn(List.of(arc));
|
||||
when(chapterRepository.findByArcId("arc-1")).thenReturn(List.of(chapter));
|
||||
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of(scene1, scene2));
|
||||
|
||||
// Act
|
||||
campaignService.deleteCampaign("campaign-1");
|
||||
|
||||
// Assert : tout disparaît, dans l'ordre feuilles → racine.
|
||||
verify(sceneRepository).deleteById("scene-1");
|
||||
verify(sceneRepository).deleteById("scene-2");
|
||||
verify(chapterRepository).deleteById("chap-1");
|
||||
verify(arcRepository).deleteById("arc-1");
|
||||
verify(campaignRepository).deleteById("campaign-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteCampaign_CascadesCharacters() {
|
||||
Character pc = Character.builder().id("char-1").campaignId("campaign-1").name("Alric").build();
|
||||
when(characterRepository.findByCampaignId("campaign-1")).thenReturn(List.of(pc));
|
||||
|
||||
campaignService.deleteCampaign("campaign-1");
|
||||
|
||||
verify(characterRepository).deleteById("char-1");
|
||||
verify(campaignRepository).deleteById("campaign-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetDeletionImpact() {
|
||||
Arc arc = Arc.builder().id("arc-1").campaignId("campaign-1").name("Arc 1").build();
|
||||
Chapter c1 = Chapter.builder().id("chap-1").arcId("arc-1").name("C1").build();
|
||||
Chapter c2 = Chapter.builder().id("chap-2").arcId("arc-1").name("C2").build();
|
||||
Scene s1 = Scene.builder().id("s-1").chapterId("chap-1").name("S1").build();
|
||||
Scene s2 = Scene.builder().id("s-2").chapterId("chap-2").name("S2").build();
|
||||
Scene s3 = Scene.builder().id("s-3").chapterId("chap-2").name("S3").build();
|
||||
Character pc = Character.builder().id("char-1").campaignId("campaign-1").name("Alric").build();
|
||||
|
||||
when(arcRepository.findByCampaignId("campaign-1")).thenReturn(List.of(arc));
|
||||
when(chapterRepository.findByArcId("arc-1")).thenReturn(List.of(c1, c2));
|
||||
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of(s1));
|
||||
when(sceneRepository.findByChapterId("chap-2")).thenReturn(List.of(s2, s3));
|
||||
when(characterRepository.findByCampaignId("campaign-1")).thenReturn(List.of(pc));
|
||||
|
||||
CampaignService.DeletionImpact impact = campaignService.getDeletionImpact("campaign-1");
|
||||
|
||||
assertEquals(1, impact.arcs());
|
||||
assertEquals(2, impact.chapters());
|
||||
assertEquals(3, impact.scenes());
|
||||
assertEquals(1, impact.characters());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Scene;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -14,6 +16,7 @@ import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
@@ -26,6 +29,8 @@ public class ChapterServiceTest {
|
||||
|
||||
@Mock
|
||||
private ChapterRepository chapterRepository;
|
||||
@Mock
|
||||
private SceneRepository sceneRepository;
|
||||
|
||||
@InjectMocks
|
||||
private ChapterService chapterService;
|
||||
@@ -157,15 +162,36 @@ public class ChapterServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteChapter() {
|
||||
// Arrange
|
||||
doNothing().when(chapterRepository).deleteById("chapter-1");
|
||||
|
||||
// Act
|
||||
void testDeleteChapter_EmptyChapter() {
|
||||
// Aucune scène : Mockito renvoie List.of() par défaut.
|
||||
chapterService.deleteChapter("chapter-1");
|
||||
|
||||
// Assert
|
||||
verify(chapterRepository, times(1)).deleteById("chapter-1");
|
||||
verify(chapterRepository).deleteById("chapter-1");
|
||||
verify(sceneRepository, never()).deleteById(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteChapter_CascadesScenes() {
|
||||
Scene s1 = Scene.builder().id("s-1").chapterId("chapter-1").name("S1").build();
|
||||
Scene s2 = Scene.builder().id("s-2").chapterId("chapter-1").name("S2").build();
|
||||
when(sceneRepository.findByChapterId("chapter-1")).thenReturn(List.of(s1, s2));
|
||||
|
||||
chapterService.deleteChapter("chapter-1");
|
||||
|
||||
verify(sceneRepository).deleteById("s-1");
|
||||
verify(sceneRepository).deleteById("s-2");
|
||||
verify(chapterRepository).deleteById("chapter-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetDeletionImpact() {
|
||||
Scene s1 = Scene.builder().id("s-1").chapterId("chapter-1").name("S1").build();
|
||||
Scene s2 = Scene.builder().id("s-2").chapterId("chapter-1").name("S2").build();
|
||||
when(sceneRepository.findByChapterId("chapter-1")).thenReturn(List.of(s1, s2));
|
||||
|
||||
ChapterService.DeletionImpact impact = chapterService.getDeletionImpact("chapter-1");
|
||||
|
||||
assertEquals(2, impact.scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
package com.loremind.application.conversationcontext;
|
||||
|
||||
import com.loremind.domain.conversationcontext.Conversation;
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
import com.loremind.domain.conversationcontext.ports.ConversationRepository;
|
||||
import com.loremind.domain.conversationcontext.ports.ConversationTitleGenerator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests unitaires de ConversationService.
|
||||
* Focus sur :
|
||||
* - la validation XOR de l'ancrage (loreId XOR campaignId),
|
||||
* - la coherence entityType/entityId (tous deux null ou tous deux non-null),
|
||||
* - le fallback du titre a la creation,
|
||||
* - la validation des roles et contenus de message,
|
||||
* - l'auto-generation de titre (cas succes + court-circuit si pas de messages).
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ConversationServiceTest {
|
||||
|
||||
@Mock
|
||||
private ConversationRepository repository;
|
||||
|
||||
@Mock
|
||||
private ConversationTitleGenerator titleGenerator;
|
||||
|
||||
@InjectMocks
|
||||
private ConversationService service;
|
||||
|
||||
// ---------- create : validation XOR de l'ancrage -----------------------
|
||||
|
||||
@Test
|
||||
void create_rejectsBothAnchorsNull() {
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
"t", null, null, null, null);
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||
assertEquals("Exactement un parent attendu : loreId XOR campaignId", ex.getMessage());
|
||||
verifyNoInteractions(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_rejectsBothAnchorsPresent() {
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
"t", "lore-1", "camp-1", null, null);
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||
verifyNoInteractions(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_rejectsBlankLoreIdAsAbsent() {
|
||||
// Blank (espaces) = absent : c'est la regle du service.
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
"t", " ", " ", null, null);
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_rejectsEntityTypeWithoutEntityId() {
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
"t", "lore-1", null, "page", null);
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||
assertEquals("entityType et entityId doivent etre tous deux null ou tous deux non-null", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_rejectsEntityIdWithoutEntityType() {
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
"t", "lore-1", null, null, "page-42");
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(data));
|
||||
}
|
||||
|
||||
// ---------- create : cas nominaux --------------------------------------
|
||||
|
||||
@Test
|
||||
void create_withLoreAnchor_persistsBuiltConversation() {
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
"Discussion Thorin", "lore-1", null, "page", "page-42");
|
||||
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
Conversation result = service.create(data);
|
||||
|
||||
ArgumentCaptor<Conversation> captor = ArgumentCaptor.forClass(Conversation.class);
|
||||
verify(repository).save(captor.capture());
|
||||
Conversation saved = captor.getValue();
|
||||
assertEquals("Discussion Thorin", saved.getTitle());
|
||||
assertEquals("lore-1", saved.getLoreId());
|
||||
assertEquals("page", saved.getEntityType());
|
||||
assertEquals("page-42", saved.getEntityId());
|
||||
assertEquals(saved, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_withCampaignAnchor_andNoEntityFocus_persistsRootLevel() {
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
null, null, "camp-1", null, null);
|
||||
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
service.create(data);
|
||||
|
||||
ArgumentCaptor<Conversation> captor = ArgumentCaptor.forClass(Conversation.class);
|
||||
verify(repository).save(captor.capture());
|
||||
assertEquals("Nouvelle conversation", captor.getValue().getTitle(),
|
||||
"Titre absent -> fallback par defaut");
|
||||
assertEquals("camp-1", captor.getValue().getCampaignId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_trimsProvidedTitle() {
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
" Mon titre ", "lore-1", null, null, null);
|
||||
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
service.create(data);
|
||||
|
||||
ArgumentCaptor<Conversation> captor = ArgumentCaptor.forClass(Conversation.class);
|
||||
verify(repository).save(captor.capture());
|
||||
assertEquals("Mon titre", captor.getValue().getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_blankTitle_fallsBackToDefault() {
|
||||
ConversationService.CreateData data = new ConversationService.CreateData(
|
||||
" ", "lore-1", null, null, null);
|
||||
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
service.create(data);
|
||||
|
||||
ArgumentCaptor<Conversation> captor = ArgumentCaptor.forClass(Conversation.class);
|
||||
verify(repository).save(captor.capture());
|
||||
assertEquals("Nouvelle conversation", captor.getValue().getTitle());
|
||||
}
|
||||
|
||||
// ---------- getById / listByContext / delete --------------------------
|
||||
|
||||
@Test
|
||||
void getById_delegatesToRepository() {
|
||||
Conversation conv = Conversation.builder().id("c-1").build();
|
||||
when(repository.findById("c-1")).thenReturn(Optional.of(conv));
|
||||
|
||||
assertEquals(Optional.of(conv), service.getById("c-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listByContext_validatesAnchorBeforeQuerying() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> service.listByContext(null, null, null, null));
|
||||
verifyNoInteractions(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listByContext_delegates_whenAnchorValid() {
|
||||
Conversation c = Conversation.builder().id("c-1").build();
|
||||
when(repository.findByContext("lore-1", null, null, null)).thenReturn(List.of(c));
|
||||
|
||||
List<Conversation> result = service.listByContext("lore-1", null, null, null);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_delegatesToRepository() {
|
||||
service.delete("c-1");
|
||||
verify(repository).deleteById("c-1");
|
||||
}
|
||||
|
||||
// ---------- rename -----------------------------------------------------
|
||||
|
||||
@Test
|
||||
void rename_rejectsNullTitle() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.rename("c-1", null));
|
||||
verify(repository, never()).updateTitle(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rename_rejectsBlankTitle() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.rename("c-1", " "));
|
||||
verify(repository, never()).updateTitle(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rename_rejectsUnknownConversation() {
|
||||
when(repository.findById("unknown")).thenReturn(Optional.empty());
|
||||
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||
() -> service.rename("unknown", "Nouveau titre"));
|
||||
assertEquals("Conversation introuvable : unknown", ex.getMessage());
|
||||
verify(repository, never()).updateTitle(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rename_trimsTitleBeforePersist() {
|
||||
when(repository.findById("c-1")).thenReturn(Optional.of(Conversation.builder().id("c-1").build()));
|
||||
|
||||
service.rename("c-1", " Nouveau titre ");
|
||||
|
||||
verify(repository).updateTitle("c-1", "Nouveau titre");
|
||||
}
|
||||
|
||||
// ---------- appendMessage ----------------------------------------------
|
||||
|
||||
@Test
|
||||
void appendMessage_rejectsInvalidRole() {
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||
() -> service.appendMessage("c-1", "admin", "hello"));
|
||||
assertEquals("Role invalide : admin", ex.getMessage());
|
||||
verifyNoInteractions(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendMessage_rejectsNullRole() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> service.appendMessage("c-1", null, "hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendMessage_rejectsNullContent() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> service.appendMessage("c-1", "user", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendMessage_rejectsEmptyContent() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> service.appendMessage("c-1", "user", ""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendMessage_acceptsAllThreeCanonicalRoles() {
|
||||
ConversationMessage returned = ConversationMessage.builder().id("m").build();
|
||||
when(repository.appendMessage(eq("c-1"), any())).thenReturn(returned);
|
||||
|
||||
for (String role : new String[]{"user", "assistant", "system"}) {
|
||||
service.appendMessage("c-1", role, "contenu");
|
||||
}
|
||||
|
||||
ArgumentCaptor<ConversationMessage> captor = ArgumentCaptor.forClass(ConversationMessage.class);
|
||||
verify(repository, times(3)).appendMessage(eq("c-1"), captor.capture());
|
||||
assertEquals("user", captor.getAllValues().get(0).getRole());
|
||||
assertEquals("assistant", captor.getAllValues().get(1).getRole());
|
||||
assertEquals("system", captor.getAllValues().get(2).getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendMessage_passesContentVerbatim() {
|
||||
ConversationMessage returned = ConversationMessage.builder().id("m-1").build();
|
||||
when(repository.appendMessage(eq("c-1"), any())).thenReturn(returned);
|
||||
|
||||
service.appendMessage("c-1", "user", " hello avec espaces ");
|
||||
|
||||
ArgumentCaptor<ConversationMessage> captor = ArgumentCaptor.forClass(ConversationMessage.class);
|
||||
verify(repository).appendMessage(eq("c-1"), captor.capture());
|
||||
// Le service NE trim PAS le contenu — seul le titre est trim.
|
||||
assertEquals(" hello avec espaces ", captor.getValue().getContent());
|
||||
}
|
||||
|
||||
// ---------- autoGenerateTitle ------------------------------------------
|
||||
|
||||
@Test
|
||||
void autoGenerateTitle_throws_whenConversationNotFound() {
|
||||
when(repository.findById("unknown")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.autoGenerateTitle("unknown"));
|
||||
verifyNoInteractions(titleGenerator);
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoGenerateTitle_shortCircuits_whenNoMessages() {
|
||||
Conversation conv = Conversation.builder().id("c-1").title("Titre existant").messages(List.of()).build();
|
||||
when(repository.findById("c-1")).thenReturn(Optional.of(conv));
|
||||
|
||||
String result = service.autoGenerateTitle("c-1");
|
||||
|
||||
assertEquals("Titre existant", result);
|
||||
verifyNoInteractions(titleGenerator);
|
||||
verify(repository, never()).updateTitle(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoGenerateTitle_shortCircuits_whenMessagesIsNull() {
|
||||
Conversation conv = new Conversation(); // @NoArgsConstructor -> messages == null
|
||||
conv.setId("c-1");
|
||||
conv.setTitle("Titre");
|
||||
when(repository.findById("c-1")).thenReturn(Optional.of(conv));
|
||||
|
||||
assertEquals("Titre", service.autoGenerateTitle("c-1"));
|
||||
verifyNoInteractions(titleGenerator);
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoGenerateTitle_generatesAndPersists_whenMessagesPresent() {
|
||||
List<ConversationMessage> seeds = List.of(
|
||||
ConversationMessage.builder().role("user").content("bonjour").build(),
|
||||
ConversationMessage.builder().role("assistant").content("salut").build());
|
||||
Conversation conv = Conversation.builder().id("c-1").title("Ancien").messages(seeds).build();
|
||||
|
||||
when(repository.findById("c-1")).thenReturn(Optional.of(conv));
|
||||
when(titleGenerator.generate(seeds)).thenReturn("Premier echange poli");
|
||||
|
||||
String result = service.autoGenerateTitle("c-1");
|
||||
|
||||
assertEquals("Premier echange poli", result);
|
||||
verify(repository).updateTitle("c-1", "Premier echange poli");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user