Bêta 1.7.0 : catalogue de sorts, entraînement aux règles, fiches tirées des règles
Systèmes de jeu - Édition d'un système en onglets : Présentation, Règles, Structure des fiches, Sorts ; recherche dans les règles, sections repliées, enregistrement toujours visible. - Catalogue de sorts (V32) : un sort par fiche, champs propres au système, recherche et filtres par niveau et par école ; inclus dans l'export et l'import du contenu. - Proposition de sorts à partir des règles : lecture morceau par morceau, un sort n'est proposé que si son nom et un passage cité se retrouvent dans le texte. - Sorts connus des fiches PJ, PNJ et ennemi (V33, table à part) et onglet Sorts du mode séance. - Proposition des champs d'une fiche (PJ, PNJ, ennemi) à partir des règles. Campagnes - Entraînement aux règles : situations tirées des scènes, corrigé qui cite les règles ; sections et citations dans la langue de l'interface. - Fiches de campagne en noyau + rubriques (scène, arc, aventure, quête annexe). - Vocabulaire : aventure, ordre libre, quête annexe. - Méthode guidée mémorisée sur l'aventure (V30). Livret PDF - Thème « Parchemin », placement des illustrations (V31), renvois vers les PNJ. Bureau et IA - Journal du Brain (logs/brain.log) et erreurs de l'IA mieux rapportées. Passage à la 1.7.0-beta.
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
"""Endpoint du chat contextuel (/chat/stream) : Structural Context + jauge tokens."""
|
"""Endpoint du chat contextuel (/chat/stream) : Structural Context + jauge tokens."""
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from typing import Annotated, AsyncIterator
|
from typing import Annotated, AsyncIterator
|
||||||
|
|
||||||
import tiktoken
|
import tiktoken
|
||||||
@@ -22,6 +23,8 @@ from app.core.language import get_user_language
|
|||||||
from app.domain.models import ChatMessage
|
from app.domain.models import ChatMessage
|
||||||
from app.domain.ports import LLMProviderError
|
from app.domain.ports import LLMProviderError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
# Encodeur tiktoken partagé — chargé une fois pour éviter le coût de lookup
|
# Encodeur tiktoken partagé — chargé une fois pour éviter le coût de lookup
|
||||||
@@ -118,6 +121,7 @@ async def chat_stream(
|
|||||||
yield f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
yield f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
||||||
yield "event: done\ndata: {}\n\n"
|
yield "event: done\ndata: {}\n\n"
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Conversation : erreur du fournisseur IA : %s", exc)
|
||||||
yield f"event: error\ndata: {json.dumps({'message': str(exc)})}\n\n"
|
yield f"event: error\ndata: {json.dumps({'message': str(exc)})}\n\n"
|
||||||
|
|
||||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from app.application.prompts import guided_answers as guided_answers_prompts
|
|||||||
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
||||||
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
||||||
from app.application.prompts import session_recap as session_recap_prompts
|
from app.application.prompts import session_recap as session_recap_prompts
|
||||||
|
from app.application.prompts import sheet_template as sheet_template_prompts
|
||||||
from app.core.config import Settings, get_settings
|
from app.core.config import Settings, get_settings
|
||||||
from app.core.language import get_user_language
|
from app.core.language import get_user_language
|
||||||
from app.domain.models import PageGenerationContext
|
from app.domain.models import PageGenerationContext
|
||||||
@@ -370,3 +371,105 @@ def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dic
|
|||||||
continue
|
continue
|
||||||
out[field.key] = text
|
out[field.key] = text
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# --- Modèle de fiche proposé à partir des règles (PJ, PNJ, ennemi) --------------------------
|
||||||
|
|
||||||
|
# Schéma de la sortie : passé tel quel aux modèles locaux (sortie structurée), traduit en
|
||||||
|
# mode JSON par les fournisseurs cloud.
|
||||||
|
_SHEET_TEMPLATE_SCHEMA: dict = {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"fields": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": {"type": "string"},
|
||||||
|
"type": {"type": "string", "enum": list(sheet_template_prompts.ALLOWED_TYPES)},
|
||||||
|
"labels": {"type": "array", "items": {"type": "string"}},
|
||||||
|
"source": {"type": "string"},
|
||||||
|
},
|
||||||
|
"required": ["name", "type"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["fields"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class SheetTemplateRequestDTO(BaseModel):
|
||||||
|
"""Sections de règles utiles (choisies et bornées par le Core) + champs déjà en place."""
|
||||||
|
|
||||||
|
sheet: Literal["character", "npc", "enemy"] = "character"
|
||||||
|
system_name: str = Field(default="")
|
||||||
|
sections: dict[str, str] = Field(default_factory=dict)
|
||||||
|
existing_fields: list[str] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class SheetFieldDTO(BaseModel):
|
||||||
|
"""Un champ proposé. `type` est relayé tel quel : le Core écarte les types inconnus."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
type: str
|
||||||
|
labels: list[str] = Field(default_factory=list)
|
||||||
|
source: str = Field(default="")
|
||||||
|
|
||||||
|
|
||||||
|
class SheetTemplateResponseDTO(BaseModel):
|
||||||
|
fields: list[SheetFieldDTO]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate/sheet-template", response_model=SheetTemplateResponseDTO)
|
||||||
|
async def generate_sheet_template(
|
||||||
|
body: SheetTemplateRequestDTO,
|
||||||
|
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
|
) -> SheetTemplateResponseDTO:
|
||||||
|
"""Propose les champs d'une fiche (PJ, PNJ, ennemi) à partir des règles du système.
|
||||||
|
|
||||||
|
Rien n'est enregistré : le MJ coche les champs à ajouter à son modèle. Une liste vide
|
||||||
|
signifie que les règles fournies ne décrivent pas cette fiche.
|
||||||
|
"""
|
||||||
|
sections = {t: c for t, c in body.sections.items() if t.strip() and c.strip()}
|
||||||
|
if not sections:
|
||||||
|
raise HTTPException(status_code=422, detail="Aucune règle fournie pour proposer une fiche.")
|
||||||
|
prompt = sheet_template_prompts.sheet_template_prompt(
|
||||||
|
body.sheet, body.system_name, sections, body.existing_fields, language)
|
||||||
|
try:
|
||||||
|
# Température basse : relevé fidèle de ce que disent les règles, pas de création.
|
||||||
|
raw = await generate_with_retry(
|
||||||
|
llm, prompt, output_format=_SHEET_TEMPLATE_SCHEMA, temperature=0.2)
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
if not isinstance(parsed, dict):
|
||||||
|
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de fiche exploitable.")
|
||||||
|
return SheetTemplateResponseDTO(fields=_clean_sheet_fields(parsed.get("fields")))
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_sheet_fields(raw: object) -> list[SheetFieldDTO]:
|
||||||
|
"""Garde les entrées bien formées (nom et type en texte) ; lignes et source nettoyées.
|
||||||
|
|
||||||
|
Le tri métier (doublons, types inconnus, listes sans lignes, plafond) est fait par le Core.
|
||||||
|
"""
|
||||||
|
out: list[SheetFieldDTO] = []
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
return out
|
||||||
|
for entry in raw:
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
continue
|
||||||
|
name, kind = entry.get("name"), entry.get("type")
|
||||||
|
if not isinstance(name, str) or not name.strip() or not isinstance(kind, str):
|
||||||
|
continue
|
||||||
|
labels = entry.get("labels")
|
||||||
|
source = entry.get("source")
|
||||||
|
out.append(SheetFieldDTO(
|
||||||
|
name=name.strip(),
|
||||||
|
type=kind.strip().upper(),
|
||||||
|
labels=[str(l).strip() for l in labels if isinstance(l, (str, int, float)) and str(l).strip()]
|
||||||
|
if isinstance(labels, list) else [],
|
||||||
|
source=source.strip() if isinstance(source, str) else "",
|
||||||
|
))
|
||||||
|
return out
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ async def import_rules_stream(
|
|||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except Exception as exc: # noqa: BLE001 — filet : une erreur inattendue ne doit
|
except Exception as exc: # noqa: BLE001 — filet : une erreur inattendue ne doit
|
||||||
# PAS casser le flux SSE brutalement (sinon le Core n'a qu'un message générique
|
# PAS casser le flux SSE brutalement (sinon le Core n'a qu'un message générique
|
||||||
@@ -143,6 +144,7 @@ async def import_campaign_stream(
|
|||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except Exception as exc: # noqa: BLE001 — voir import règles : on ne laisse pas
|
except Exception as exc: # noqa: BLE001 — voir import règles : on ne laisse pas
|
||||||
# une erreur inattendue casser le flux sans détail.
|
# une erreur inattendue casser le flux sans détail.
|
||||||
@@ -189,6 +191,7 @@ async def adapt_campaign_stream(
|
|||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
|
|
||||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||||
|
|||||||
@@ -97,6 +97,7 @@ async def chat_notebook_stream(
|
|||||||
yield sse_event(ev_type, ev)
|
yield sse_event(ev_type, ev)
|
||||||
yield sse_event("done", {})
|
yield sse_event("done", {})
|
||||||
except (LLMProviderError, EmbeddingError) as exc:
|
except (LLMProviderError, EmbeddingError) as exc:
|
||||||
|
logger.warning("Atelier : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale du flux.
|
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale du flux.
|
||||||
logger.exception("Chat notebook : erreur inattendue.")
|
logger.exception("Chat notebook : erreur inattendue.")
|
||||||
@@ -125,6 +126,7 @@ async def chat_notebook_deep_stream(
|
|||||||
ev_type = ev.pop("type")
|
ev_type = ev.pop("type")
|
||||||
yield sse_event(ev_type, ev)
|
yield sse_event(ev_type, ev)
|
||||||
except (LLMProviderError, EmbeddingError) as exc:
|
except (LLMProviderError, EmbeddingError) as exc:
|
||||||
|
logger.warning("Atelier : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale.
|
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale.
|
||||||
logger.exception("Analyse approfondie : erreur inattendue.")
|
logger.exception("Analyse approfondie : erreur inattendue.")
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""Catalogue de sorts : relevé des sorts décrits dans un morceau de règles."""
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from app.api.deps import get_llm_provider
|
||||||
|
from app.application.llm_json import load_json_object
|
||||||
|
from app.application.llm_retry import generate_with_retry
|
||||||
|
from app.application.prompts import spell_extraction as spell_prompts
|
||||||
|
from app.domain.ports import LLMProvider, LLMProviderError
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# Schéma de sortie : passé tel quel aux modèles locaux (sortie structurée), traduit en mode
|
||||||
|
# JSON par les fournisseurs cloud.
|
||||||
|
_SPELLS_SCHEMA: dict = {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"spells": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": {"type": "string"},
|
||||||
|
"level": {"type": "string"},
|
||||||
|
"school": {"type": "string"},
|
||||||
|
"description": {"type": "string"},
|
||||||
|
"values": {"type": "object"},
|
||||||
|
"excerpt": {"type": "string"},
|
||||||
|
},
|
||||||
|
"required": ["name", "description", "excerpt"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["spells"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class SpellFieldDTO(BaseModel):
|
||||||
|
"""Un champ du modèle de sort du système. `type` : `TEXT` ou `NUMBER`."""
|
||||||
|
|
||||||
|
name: str = Field(default="")
|
||||||
|
type: str = Field(default="TEXT")
|
||||||
|
|
||||||
|
|
||||||
|
class SpellExtractionRequestDTO(BaseModel):
|
||||||
|
"""Un morceau de règles (borné par le Core) et les champs à remplir pour chaque sort."""
|
||||||
|
|
||||||
|
system_name: str = Field(default="")
|
||||||
|
section_title: str = Field(default="")
|
||||||
|
text: str = Field(default="")
|
||||||
|
fields: list[SpellFieldDTO] = Field(default_factory=list)
|
||||||
|
avoid: list[str] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class ExtractedSpellDTO(BaseModel):
|
||||||
|
"""Un sort relevé. `excerpt` : passage du texte, que le Core vérifie mot pour mot."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
level: str = ""
|
||||||
|
school: str = ""
|
||||||
|
description: str
|
||||||
|
values: dict[str, str] = Field(default_factory=dict)
|
||||||
|
excerpt: str
|
||||||
|
|
||||||
|
|
||||||
|
class SpellExtractionResponseDTO(BaseModel):
|
||||||
|
spells: list[ExtractedSpellDTO]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate/spell-extraction", response_model=SpellExtractionResponseDTO)
|
||||||
|
async def generate_spell_extraction(
|
||||||
|
body: SpellExtractionRequestDTO,
|
||||||
|
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||||
|
) -> SpellExtractionResponseDTO:
|
||||||
|
"""Relève les sorts décrits dans un morceau de règles. Rien n'est enregistré.
|
||||||
|
|
||||||
|
Le Core vérifie ensuite, pour chaque sort, que son nom et le passage cité se retrouvent
|
||||||
|
dans le texte envoyé ; une liste vide signifie que le morceau ne décrit aucun sort.
|
||||||
|
"""
|
||||||
|
if not body.text.strip():
|
||||||
|
raise HTTPException(status_code=422, detail="Aucun texte de règles fourni.")
|
||||||
|
prompt = spell_prompts.spell_extraction_prompt(
|
||||||
|
body.system_name, body.section_title, body.text,
|
||||||
|
[f.model_dump() for f in body.fields], body.avoid)
|
||||||
|
try:
|
||||||
|
# Température basse : on relève ce qui est écrit, on n'écrit rien.
|
||||||
|
raw = await generate_with_retry(llm, prompt, output_format=_SPELLS_SCHEMA, temperature=0.1)
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
if not isinstance(parsed, dict):
|
||||||
|
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de liste de sorts exploitable.")
|
||||||
|
return SpellExtractionResponseDTO(spells=_clean_spells(parsed.get("spells")))
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: object) -> str:
|
||||||
|
"""Texte d'une valeur renvoyée par le modèle (un nombre arrive parfois en nombre)."""
|
||||||
|
if isinstance(value, bool) or value is None:
|
||||||
|
return ""
|
||||||
|
if isinstance(value, (str, int, float)):
|
||||||
|
return str(value).strip()
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_spells(raw: object) -> list[ExtractedSpellDTO]:
|
||||||
|
"""Garde les sorts complets (nom, description et passage cité non vides).
|
||||||
|
|
||||||
|
La vérification du nom et du passage contre les règles est faite par le Core.
|
||||||
|
"""
|
||||||
|
out: list[ExtractedSpellDTO] = []
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
return out
|
||||||
|
for entry in raw:
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
continue
|
||||||
|
name, description, excerpt = (_text(entry.get(key)) for key in ("name", "description", "excerpt"))
|
||||||
|
if not name or not description or not excerpt:
|
||||||
|
continue
|
||||||
|
values = entry.get("values")
|
||||||
|
out.append(ExtractedSpellDTO(
|
||||||
|
name=name,
|
||||||
|
level=_text(entry.get("level")),
|
||||||
|
school=_text(entry.get("school")),
|
||||||
|
description=description,
|
||||||
|
values={str(k).strip(): _text(v) for k, v in values.items() if str(k).strip() and _text(v)}
|
||||||
|
if isinstance(values, dict) else {},
|
||||||
|
excerpt=excerpt,
|
||||||
|
))
|
||||||
|
return out
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
"""Entraînement aux règles : série de situations à trancher, comparaison d'une réponse."""
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from app.api.deps import get_llm_provider
|
||||||
|
from app.application.llm_json import load_json_object
|
||||||
|
from app.application.llm_retry import generate_with_retry
|
||||||
|
from app.application.prompts import rule_training as rule_training_prompts
|
||||||
|
from app.core.language import get_user_language
|
||||||
|
from app.domain.ports import LLMProvider, LLMProviderError
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# Schémas de sortie : passés tels quels aux modèles locaux (sortie structurée), traduits en
|
||||||
|
# mode JSON par les fournisseurs cloud.
|
||||||
|
_DRILLS_SCHEMA: dict = {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"drills": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"scene": {"type": "integer"},
|
||||||
|
"situation": {"type": "string"},
|
||||||
|
"section": {"type": "string"},
|
||||||
|
"excerpt": {"type": "string"},
|
||||||
|
"ruling": {"type": "string"},
|
||||||
|
},
|
||||||
|
"required": ["situation", "section", "excerpt", "ruling"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["drills"],
|
||||||
|
}
|
||||||
|
|
||||||
|
_REVIEW_SCHEMA: dict = {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"verdict": {"type": "string", "enum": list(rule_training_prompts.VERDICTS)},
|
||||||
|
"feedback": {"type": "string"},
|
||||||
|
},
|
||||||
|
"required": ["verdict", "feedback"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class DrillSceneDTO(BaseModel):
|
||||||
|
"""Une scène du scénario, résumée par le Core : le décor d'une situation."""
|
||||||
|
|
||||||
|
name: str = Field(default="")
|
||||||
|
kind: str = Field(default="")
|
||||||
|
text: str = Field(default="")
|
||||||
|
|
||||||
|
|
||||||
|
class RuleDrillsRequestDTO(BaseModel):
|
||||||
|
"""Sections de règles utiles (choisies et bornées par le Core) + scènes du scénario."""
|
||||||
|
|
||||||
|
system_name: str = Field(default="")
|
||||||
|
sections: dict[str, str] = Field(default_factory=dict)
|
||||||
|
scenes: list[DrillSceneDTO] = Field(default_factory=list)
|
||||||
|
count: int = Field(default=5, ge=1, le=10)
|
||||||
|
avoid: list[str] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class RuleDrillDTO(BaseModel):
|
||||||
|
"""Une situation et son corrigé. `scene` : numéro de la scène (à partir de 1), 0 si aucune."""
|
||||||
|
|
||||||
|
scene: int = 0
|
||||||
|
situation: str
|
||||||
|
section: str
|
||||||
|
excerpt: str
|
||||||
|
ruling: str
|
||||||
|
|
||||||
|
|
||||||
|
class RuleDrillsResponseDTO(BaseModel):
|
||||||
|
drills: list[RuleDrillDTO]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate/rule-drills", response_model=RuleDrillsResponseDTO)
|
||||||
|
async def generate_rule_drills(
|
||||||
|
body: RuleDrillsRequestDTO,
|
||||||
|
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
|
) -> RuleDrillsResponseDTO:
|
||||||
|
"""Prépare une série de situations à trancher, corrigé compris, en un seul appel.
|
||||||
|
|
||||||
|
Rien n'est enregistré. Le Core vérifie ensuite chaque extrait cité contre les règles
|
||||||
|
envoyées ; une liste vide signifie que les extraits ne contiennent aucune règle de table.
|
||||||
|
"""
|
||||||
|
sections = {t: c for t, c in body.sections.items() if t.strip() and c.strip()}
|
||||||
|
if not sections:
|
||||||
|
raise HTTPException(status_code=422, detail="Aucune règle fournie pour préparer une série.")
|
||||||
|
prompt = rule_training_prompts.rule_drills_prompt(
|
||||||
|
body.system_name, sections, [s.model_dump() for s in body.scenes],
|
||||||
|
body.count, body.avoid, language)
|
||||||
|
try:
|
||||||
|
# Température moyenne : des situations variées, mais un extrait recopié fidèlement.
|
||||||
|
raw = await generate_with_retry(llm, prompt, output_format=_DRILLS_SCHEMA, temperature=0.5)
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
if not isinstance(parsed, dict):
|
||||||
|
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de série exploitable.")
|
||||||
|
return RuleDrillsResponseDTO(drills=_clean_drills(parsed.get("drills")))
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_drills(raw: object) -> list[RuleDrillDTO]:
|
||||||
|
"""Garde les situations complètes (quatre textes non vides) ; numéro de scène ramené à un entier.
|
||||||
|
|
||||||
|
La vérification de l'extrait contre les règles est faite par le Core.
|
||||||
|
"""
|
||||||
|
out: list[RuleDrillDTO] = []
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
return out
|
||||||
|
for entry in raw:
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
continue
|
||||||
|
texts = [entry.get(key) for key in ("situation", "section", "excerpt", "ruling")]
|
||||||
|
if not all(isinstance(t, str) and t.strip() for t in texts):
|
||||||
|
continue
|
||||||
|
scene = entry.get("scene")
|
||||||
|
if isinstance(scene, str) and scene.strip().isdigit():
|
||||||
|
scene = int(scene.strip())
|
||||||
|
out.append(RuleDrillDTO(
|
||||||
|
scene=scene if isinstance(scene, int) and not isinstance(scene, bool) and scene > 0 else 0,
|
||||||
|
situation=texts[0].strip(),
|
||||||
|
section=texts[1].strip(),
|
||||||
|
excerpt=texts[2].strip(),
|
||||||
|
ruling=texts[3].strip(),
|
||||||
|
))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class RuleDrillReviewRequestDTO(BaseModel):
|
||||||
|
"""La décision du MJ face au corrigé d'une situation."""
|
||||||
|
|
||||||
|
system_name: str = Field(default="")
|
||||||
|
section_title: str = Field(default="")
|
||||||
|
section_text: str = Field(default="")
|
||||||
|
situation: str = Field(default="")
|
||||||
|
excerpt: str = Field(default="")
|
||||||
|
ruling: str = Field(default="")
|
||||||
|
answer: str = Field(default="")
|
||||||
|
|
||||||
|
|
||||||
|
class RuleDrillReviewResponseDTO(BaseModel):
|
||||||
|
"""`verdict` : `right`, `partial` ou `off`."""
|
||||||
|
|
||||||
|
verdict: str
|
||||||
|
feedback: str
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate/rule-drill-review", response_model=RuleDrillReviewResponseDTO)
|
||||||
|
async def generate_rule_drill_review(
|
||||||
|
body: RuleDrillReviewRequestDTO,
|
||||||
|
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
|
) -> RuleDrillReviewResponseDTO:
|
||||||
|
"""Compare la décision écrite par le MJ aux règles et au corrigé de la situation."""
|
||||||
|
if not body.answer.strip() or not body.situation.strip() or not body.section_text.strip():
|
||||||
|
raise HTTPException(status_code=422, detail="Situation, règles et réponse sont nécessaires.")
|
||||||
|
prompt = rule_training_prompts.rule_drill_review_prompt(
|
||||||
|
body.system_name, body.section_title, body.section_text, body.situation,
|
||||||
|
body.excerpt, body.ruling, body.answer, language)
|
||||||
|
try:
|
||||||
|
raw = await generate_with_retry(llm, prompt, output_format=_REVIEW_SCHEMA, temperature=0.2)
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
verdict = parsed.get("verdict") if isinstance(parsed, dict) else None
|
||||||
|
feedback = parsed.get("feedback") if isinstance(parsed, dict) else None
|
||||||
|
if (not isinstance(verdict, str) or verdict.strip().lower() not in rule_training_prompts.VERDICTS
|
||||||
|
or not isinstance(feedback, str) or not feedback.strip()):
|
||||||
|
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de comparaison exploitable.")
|
||||||
|
return RuleDrillReviewResponseDTO(verdict=verdict.strip().lower(), feedback=feedback.strip())
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""Prompts de l'entraînement aux règles : série de situations, puis comparaison d'une réponse.
|
||||||
|
|
||||||
|
Le MJ apprend son système en tranchant des situations tirées de ses propres scènes. Le
|
||||||
|
Core envoie les sections de règles utiles (déjà choisies et bornées) et un résumé des
|
||||||
|
scènes ; ce module ne fait que formuler les prompts.
|
||||||
|
|
||||||
|
Deux principes tiennent toute la fonction :
|
||||||
|
- le corrigé cite les règles MOT POUR MOT : le Core vérifie que l'extrait se retrouve
|
||||||
|
dans la section envoyée, et écarte la situation sinon ;
|
||||||
|
- le modèle ne lance aucun dé et ne calcule rien : il dit quelle règle s'applique.
|
||||||
|
"""
|
||||||
|
from app.core.language import language_name
|
||||||
|
|
||||||
|
# Verdicts possibles d'une comparaison (relayés tels quels au Core).
|
||||||
|
VERDICTS = ("right", "partial", "off")
|
||||||
|
|
||||||
|
|
||||||
|
def _rules_block(sections: dict[str, str]) -> str:
|
||||||
|
return "\n\n".join(
|
||||||
|
f"### {title.strip()}\n{content.strip()}"
|
||||||
|
for title, content in (sections or {}).items()
|
||||||
|
if isinstance(content, str) and content.strip()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _system_label(system_name: str) -> str:
|
||||||
|
return system_name.strip() if system_name and system_name.strip() else "ce jeu"
|
||||||
|
|
||||||
|
|
||||||
|
def rule_drills_prompt(system_name: str, sections: dict[str, str], scenes: list[dict],
|
||||||
|
count: int, avoid: list[str], language: str) -> str:
|
||||||
|
"""Prompt d'une série. `scenes` = [{"name", "kind", "text"}] (peut être vide)."""
|
||||||
|
scene_lines = []
|
||||||
|
for index, scene in enumerate(scenes or [], start=1):
|
||||||
|
name = str(scene.get("name") or "").strip() or f"Scène {index}"
|
||||||
|
kind = str(scene.get("kind") or "").strip()
|
||||||
|
text = str(scene.get("text") or "").strip()
|
||||||
|
head = f"[{index}] {name}" + (f" ({kind})" if kind else "")
|
||||||
|
scene_lines.append(f"{head}\n{text}" if text else head)
|
||||||
|
if scene_lines:
|
||||||
|
scenes_block = (
|
||||||
|
"Scènes du scénario (le décor des situations ; elles ne contiennent AUCUNE règle) :\n"
|
||||||
|
+ "\n\n".join(scene_lines) + "\n\n"
|
||||||
|
"Chaque situation se passe dans UNE de ces scènes et reprend ce qui s'y trouve "
|
||||||
|
'(lieu, personnages, adversaires). "scene" = le numéro entre crochets de cette scène.\n'
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
scenes_block = (
|
||||||
|
"Aucune scène n'est fournie : imagine des situations typiques d'une partie de ce "
|
||||||
|
'jeu, et mets "scene" à 0.\n'
|
||||||
|
)
|
||||||
|
avoided = "\n".join(f"- {s.strip()}" for s in avoid or [] if s and s.strip())
|
||||||
|
avoid_block = (
|
||||||
|
"\nSituations DÉJÀ posées (propose autre chose, sur d'autres règles si possible) :\n"
|
||||||
|
f"{avoided}\n" if avoided else ""
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
f"Tu prépares un entraînement pour un MJ qui apprend les règles du jeu de rôle "
|
||||||
|
f"« {_system_label(system_name)} » avant de le faire jouer.\n"
|
||||||
|
f"Écris {count} situations de table. Dans chacune, un joueur tente quelque chose, ou "
|
||||||
|
"quelque chose arrive aux personnages, et le MJ doit décider quelle règle s'applique. "
|
||||||
|
"Le MJ répondra de mémoire, puis lira ton corrigé.\n\n"
|
||||||
|
"Extraits des règles (SEULE source autorisée pour les règles) :\n"
|
||||||
|
f"{_rules_block(sections)}\n\n"
|
||||||
|
f"{scenes_block}"
|
||||||
|
f"{avoid_block}\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||||
|
'- Format exact : {"drills": [{"scene": 1, "situation": "…", "section": "titre de la '
|
||||||
|
'section", "excerpt": "…", "ruling": "…"}]}\n'
|
||||||
|
'- "situation" : 2 ou 3 phrases concrètes sur ce qui se passe à la table (un joueur annonce '
|
||||||
|
"une action, un adversaire agit, un danger se déclenche), puis une question courte. N'y "
|
||||||
|
"donne ni la règle ni la réponse, et ne nomme pas la valeur ou le jet à utiliser. Ce n'est "
|
||||||
|
"pas une question de cours : ne demande pas quelle caractéristique consulter ni comment "
|
||||||
|
"une valeur se calcule en général.\n"
|
||||||
|
"- Adresse-toi directement au MJ, à la deuxième personne (« vous » en français), dans la "
|
||||||
|
"question comme dans le corrigé : pas de « le MJ doit… ».\n"
|
||||||
|
"- Chaque situation porte sur UNE règle précise, écrite dans les extraits. N'utilise "
|
||||||
|
"aucune règle absente des extraits et n'importe pas les habitudes d'un autre jeu. Si les "
|
||||||
|
'extraits ne contiennent aucune règle applicable à la table, renvoie {"drills": []}.\n'
|
||||||
|
'- "excerpt" : le passage des extraits qui tranche la situation, COPIÉ MOT POUR MOT '
|
||||||
|
"(1 à 4 phrases qui se suivent). Ne reformule pas, ne corrige pas, ne coupe pas au milieu, "
|
||||||
|
"n'ajoute ni points de suspension ni guillemets.\n"
|
||||||
|
'- "section" : le titre EXACT de la section d\'où vient ce passage.\n'
|
||||||
|
'- "ruling" : ce que le MJ doit faire à la table, en 2 à 4 phrases, en s\'appuyant '
|
||||||
|
"uniquement sur le passage cité.\n"
|
||||||
|
"- Ne lance AUCUN dé et ne calcule aucun résultat : dis quel jet, quelle valeur ou quelle "
|
||||||
|
"procédure s'applique, pas ce qui en sort.\n"
|
||||||
|
"- Varie les règles et les sections d'une situation à l'autre, et commence par les règles "
|
||||||
|
"qui servent le plus souvent en jeu.\n"
|
||||||
|
f"- Rédige situations et corrigés en {language_name(language)}. Le passage cité reste "
|
||||||
|
"dans la langue des extraits, tel quel.\n"
|
||||||
|
"Renvoie maintenant le JSON."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def rule_drill_review_prompt(system_name: str, section_title: str, section_text: str,
|
||||||
|
situation: str, excerpt: str, ruling: str, answer: str,
|
||||||
|
language: str) -> str:
|
||||||
|
"""Prompt de comparaison : la décision écrite par le MJ face au corrigé."""
|
||||||
|
return (
|
||||||
|
f"Un MJ s'entraîne aux règles du jeu de rôle « {_system_label(system_name)} ». "
|
||||||
|
"Il a tranché une situation de mémoire ; compare sa décision aux règles.\n\n"
|
||||||
|
f"Règles — section « {section_title.strip()} » (SEULE source autorisée) :\n"
|
||||||
|
f"{section_text.strip()}\n\n"
|
||||||
|
f"Situation :\n{situation.strip()}\n\n"
|
||||||
|
f"Passage qui s'applique :\n{excerpt.strip()}\n\n"
|
||||||
|
f"Corrigé de référence :\n{ruling.strip()}\n\n"
|
||||||
|
f"Décision du MJ :\n{answer.strip()}\n\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||||
|
'- Format exact : {"verdict": "right", "feedback": "…"}\n'
|
||||||
|
'- "verdict" : "right" si la décision applique la règle ; "partial" si elle va dans le '
|
||||||
|
'bon sens mais oublie ou déforme un point ; "off" si elle applique autre chose.\n'
|
||||||
|
'- "feedback" : 1 à 3 phrases adressées au MJ à la deuxième personne (« vous » en '
|
||||||
|
"français). Dis ce qui est juste, puis ce qui manque "
|
||||||
|
"ou diverge, en nommant le point de règle. Une décision différente du corrigé mais "
|
||||||
|
"conforme aux règles fournies est juste.\n"
|
||||||
|
"- Juge sur le fond, pas sur la formulation ni sur l'orthographe.\n"
|
||||||
|
"- Ne t'appuie que sur les règles fournies. Ne lance aucun dé et ne calcule rien.\n"
|
||||||
|
f"- Rédige le retour en {language_name(language)}.\n"
|
||||||
|
"Renvoie maintenant le JSON."
|
||||||
|
)
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Prompt de proposition d'un modèle de fiche (PJ, PNJ, ennemi) à partir des règles.
|
||||||
|
|
||||||
|
Le Core envoie les sections de règles utiles (déjà choisies et bornées en taille) ; ce
|
||||||
|
module ne fait que formuler le prompt. La fiche est une liste de champs typés que le MJ
|
||||||
|
relit avant de les ajouter : seule source autorisée = les extraits fournis, rien n'est
|
||||||
|
inventé ni emprunté à un autre jeu.
|
||||||
|
"""
|
||||||
|
from app.core.language import language_name
|
||||||
|
|
||||||
|
# Types qu'un champ proposé peut prendre (les autres types de l'appli — image, tableau —
|
||||||
|
# ne se déduisent pas des règles).
|
||||||
|
ALLOWED_TYPES = ("TEXT", "NUMBER", "KEY_VALUE_LIST")
|
||||||
|
|
||||||
|
_SHEETS: dict[str, tuple[str, str]] = {
|
||||||
|
"character": (
|
||||||
|
"PERSONNAGE JOUEUR",
|
||||||
|
"Ce qu'un joueur note sur sa feuille : son identité de jeu (classe, métier, origine… "
|
||||||
|
"si le jeu en a), ses caractéristiques, ses jauges (points de vie…), ses compétences, "
|
||||||
|
"son équipement, ses capacités.",
|
||||||
|
),
|
||||||
|
"npc": (
|
||||||
|
"PERSONNAGE NON-JOUEUR",
|
||||||
|
"Une fiche COURTE : ce que les règles demandent pour faire jouer un PNJ (valeurs de jeu "
|
||||||
|
"simplifiées, attitude, rôle). Les champs purement narratifs (apparence, motivation) "
|
||||||
|
"existent en général déjà : ne les propose que si les règles les nomment. Ne recopie ni la "
|
||||||
|
"fiche d'une créature ou d'un monstre, ni la feuille complète d'un personnage joueur : si les "
|
||||||
|
"règles ne disent rien de particulier sur les PNJ, renvoie une liste vide.",
|
||||||
|
),
|
||||||
|
"enemy": (
|
||||||
|
"ENNEMI (créature, adversaire)",
|
||||||
|
"Le bloc de statistiques de combat tel que les règles le présentent : défense, points de "
|
||||||
|
"vie, attaques, capacités spéciales, faiblesses, butin… Le niveau est déjà géré par "
|
||||||
|
"l'application.",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def sheet_label(sheet: str) -> str:
|
||||||
|
"""Nom lisible de la fiche (pour le prompt et les messages)."""
|
||||||
|
return _SHEETS.get(sheet, _SHEETS["character"])[0]
|
||||||
|
|
||||||
|
|
||||||
|
def sheet_template_prompt(sheet: str, system_name: str, sections: dict[str, str],
|
||||||
|
existing_fields: list[str], language: str) -> str:
|
||||||
|
"""Construit le prompt. `sections` = {titre → règles} ; `existing_fields` = noms déjà en place."""
|
||||||
|
label, guidance = _SHEETS.get(sheet, _SHEETS["character"])
|
||||||
|
rules = "\n\n".join(
|
||||||
|
f"### {title.strip()}\n{content.strip()}"
|
||||||
|
for title, content in (sections or {}).items()
|
||||||
|
if isinstance(content, str) and content.strip()
|
||||||
|
)
|
||||||
|
existing = "\n".join(f"- {name.strip()}" for name in existing_fields or [] if name and name.strip())
|
||||||
|
existing_block = (
|
||||||
|
"\nChamps DÉJÀ présents dans la fiche (ne les repropose pas, même sous un autre nom) :\n"
|
||||||
|
f"{existing}\n" if existing else ""
|
||||||
|
)
|
||||||
|
system = system_name.strip() if system_name and system_name.strip() else "ce jeu"
|
||||||
|
return (
|
||||||
|
f"Tu aides un MJ à préparer la fiche de {label} du jeu de rôle « {system} » dans une "
|
||||||
|
"application de préparation de parties.\n"
|
||||||
|
"Une fiche est une liste de CHAMPS que le MJ remplira ensuite pour chaque fiche.\n"
|
||||||
|
f"{guidance}\n\n"
|
||||||
|
"Types de champ disponibles :\n"
|
||||||
|
'- "TEXT" : texte libre (classe, historique, équipement, capacités…).\n'
|
||||||
|
'- "NUMBER" : UNE valeur numérique (niveau, points de vie, défense…).\n'
|
||||||
|
'- "KEY_VALUE_LIST" : une liste FIXE de lignes ayant chacune une valeur (caractéristiques, '
|
||||||
|
'compétences, jets de sauvegarde…). "labels" donne ces lignes, dans l\'ordre des règles.\n\n'
|
||||||
|
"Extraits des règles (SEULE source autorisée) :\n"
|
||||||
|
f"{rules}\n"
|
||||||
|
f"{existing_block}\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||||
|
'- Format exact : {"fields": [{"name": "nom du champ", "type": "KEY_VALUE_LIST", '
|
||||||
|
'"labels": ["ligne 1", "ligne 2"], "source": "titre de la section"}, '
|
||||||
|
'{"name": "nom du champ", "type": "NUMBER", "labels": [], "source": "titre de la section"}]}\n'
|
||||||
|
"- Ne propose QUE des champs que les extraits décrivent. N'invente rien et n'importe pas "
|
||||||
|
'les habitudes d\'un autre jeu. Si les extraits ne décrivent pas cette fiche, renvoie {"fields": []}.\n'
|
||||||
|
"- Reprends les termes EXACTS des règles, y compris pour nommer un groupe : si le jeu appelle "
|
||||||
|
"ses caractéristiques « Traits » ou ses compétences « Savoir-faire », le champ porte ce nom.\n"
|
||||||
|
'- "labels" : uniquement pour KEY_VALUE_LIST, de 2 à 30 lignes ; liste vide pour les autres types.\n'
|
||||||
|
'- "source" : le titre EXACT de la section d\'où vient le champ.\n'
|
||||||
|
"- N'inclus ni le nom, ni le portrait, ni les images : l'application les gère déjà.\n"
|
||||||
|
"- De 5 à 20 champs, du plus important au moins important. Regroupe : UNE liste pour un "
|
||||||
|
"groupe de valeurs de même nature, plutôt qu'un champ par valeur.\n"
|
||||||
|
f"- Noms de champs et lignes en {language_name(language)}, en gardant les termes propres au jeu.\n"
|
||||||
|
"Renvoie maintenant le JSON."
|
||||||
|
)
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""Prompt du relevé de sorts dans un texte de règles.
|
||||||
|
|
||||||
|
Le MJ a déjà les règles de son système ; il veut en tirer un catalogue de sorts sans les
|
||||||
|
retaper. Le Core envoie UN morceau de règles (borné) et les champs du modèle de sort ; ce
|
||||||
|
module ne fait que formuler le prompt.
|
||||||
|
|
||||||
|
Un principe tient toute la fonction : le modèle RELÈVE, il n'écrit pas. Le nom du sort est
|
||||||
|
celui du texte, la description est recopiée, et chaque sort cite un passage MOT POUR MOT :
|
||||||
|
le Core vérifie que le nom et le passage se retrouvent dans le texte envoyé, et écarte le
|
||||||
|
sort sinon.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _system_label(system_name: str) -> str:
|
||||||
|
return system_name.strip() if system_name and system_name.strip() else "ce jeu"
|
||||||
|
|
||||||
|
|
||||||
|
def spell_extraction_prompt(system_name: str, section_title: str, text: str,
|
||||||
|
fields: list[dict], avoid: list[str]) -> str:
|
||||||
|
"""Prompt du relevé. `fields` = [{"name", "type"}] (peut être vide) ; `avoid` = noms déjà relevés."""
|
||||||
|
field_lines = []
|
||||||
|
for field in fields or []:
|
||||||
|
name = str(field.get("name") or "").strip()
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
kind = "nombre" if str(field.get("type") or "").upper() == "NUMBER" else "texte"
|
||||||
|
field_lines.append(f"- {name} ({kind})")
|
||||||
|
if field_lines:
|
||||||
|
fields_block = (
|
||||||
|
"Champs d'un sort dans ce système (les SEULES clés autorisées dans \"values\") :\n"
|
||||||
|
+ "\n".join(field_lines) + "\n"
|
||||||
|
'Dans "values", ne mets un champ que si le texte donne sa valeur pour ce sort ; '
|
||||||
|
"recopie la valeur telle qu'elle est écrite. Un champ « nombre » ne reçoit que des "
|
||||||
|
"chiffres.\n"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
fields_block = 'Aucun champ particulier n\'est défini : renvoie "values": {}.\n'
|
||||||
|
avoided = "\n".join(f"- {name.strip()}" for name in avoid or [] if name and name.strip())
|
||||||
|
avoid_block = (
|
||||||
|
"\nSorts DÉJÀ relevés (ne les renvoie pas) :\n"
|
||||||
|
f"{avoided}\n" if avoided else ""
|
||||||
|
)
|
||||||
|
title = section_title.strip()
|
||||||
|
source = f"section « {title} »" if title else "extrait"
|
||||||
|
return (
|
||||||
|
f"Tu aides un MJ à constituer le catalogue de sorts du jeu de rôle "
|
||||||
|
f"« {_system_label(system_name)} » à partir de ses règles.\n"
|
||||||
|
"Relève CHAQUE sort décrit dans le texte ci-dessous. Compte comme un sort tout effet "
|
||||||
|
"magique NOMMÉ que l'on lance ou active et dont le texte décrit l'effet (sort, "
|
||||||
|
"incantation, prière, pouvoir, rituel…).\n\n"
|
||||||
|
f"Texte des règles — {source} (SEULE source autorisée) :\n"
|
||||||
|
f"{text.strip()}\n\n"
|
||||||
|
f"{fields_block}"
|
||||||
|
f"{avoid_block}\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||||
|
'- Format exact : {"spells": [{"name": "…", "level": "…", "school": "…", '
|
||||||
|
'"description": "…", "values": {"Champ": "valeur"}, "excerpt": "…"}]}\n'
|
||||||
|
'- "name" : le nom du sort, écrit EXACTEMENT comme dans le texte.\n'
|
||||||
|
'- "level" : son niveau, rang, cercle ou palier si le texte le donne (« 1 », « Tour de '
|
||||||
|
'magie », « Rang II »), sinon "".\n'
|
||||||
|
'- "school" : son école, sa liste ou sa tradition si le texte la donne, sinon "".\n'
|
||||||
|
'- "description" : ce que fait le sort, RECOPIÉ depuis le texte, en entier. Ne résume '
|
||||||
|
"pas, ne traduis pas, n'ajoute rien. Laisse de côté la ligne du nom et les valeurs déjà "
|
||||||
|
'rangées dans "level", "school" ou "values".\n'
|
||||||
|
'- "excerpt" : UNE phrase de la description de ce sort, COPIÉE MOT POUR MOT depuis le '
|
||||||
|
"texte (au moins 25 caractères), sans points de suspension ni guillemets ajoutés.\n"
|
||||||
|
"- N'invente aucun sort et ne complète pas avec ce que tu sais d'un autre jeu. Un sort "
|
||||||
|
"seulement cité, sans que le texte décrive son effet, n'est pas relevé.\n"
|
||||||
|
"- Ne relève pas les règles générales de magie (comment lancer un sort, ce que coûte la "
|
||||||
|
"magie) : seulement les sorts eux-mêmes.\n"
|
||||||
|
'- Si le texte ne décrit aucun sort, renvoie {"spells": []}.\n'
|
||||||
|
"- Garde la langue du texte : ne traduis ni les noms ni les descriptions.\n"
|
||||||
|
"Renvoie maintenant le JSON."
|
||||||
|
)
|
||||||
@@ -31,6 +31,15 @@ logger = logging.getLogger(__name__)
|
|||||||
_FIRST_TOKEN_TIMEOUT_SECONDS = 120.0
|
_FIRST_TOKEN_TIMEOUT_SECONDS = 120.0
|
||||||
|
|
||||||
|
|
||||||
|
def _answer_text(chunks: list[object]) -> str:
|
||||||
|
"""Texte de réponse d'une liste de morceaux typés ; la réflexion est écartée."""
|
||||||
|
parts: list[str] = []
|
||||||
|
for chunk in chunks:
|
||||||
|
if isinstance(chunk, dict) and chunk.get("type") == "text" and isinstance(chunk.get("text"), str):
|
||||||
|
parts.append(chunk["text"])
|
||||||
|
return "".join(parts)
|
||||||
|
|
||||||
|
|
||||||
class BaseOpenAICompatibleAdapter:
|
class BaseOpenAICompatibleAdapter:
|
||||||
"""Base des adapters clients d'une API OpenAI-compatible (chat/completions SSE).
|
"""Base des adapters clients d'une API OpenAI-compatible (chat/completions SSE).
|
||||||
|
|
||||||
@@ -100,7 +109,8 @@ class BaseOpenAICompatibleAdapter:
|
|||||||
temperature: float | None = None,
|
temperature: float | None = None,
|
||||||
) -> AsyncIterator[str]:
|
) -> AsyncIterator[str]:
|
||||||
async for token in self._stream(messages, system_prompt, temperature):
|
async for token in self._stream(messages, system_prompt, temperature):
|
||||||
yield token
|
if token: # jeton vide = le modèle réfléchit encore, rien à afficher
|
||||||
|
yield token
|
||||||
|
|
||||||
# --- Mécanique partagée -------------------------------------------------
|
# --- Mécanique partagée -------------------------------------------------
|
||||||
|
|
||||||
@@ -117,19 +127,24 @@ class BaseOpenAICompatibleAdapter:
|
|||||||
"""
|
"""
|
||||||
async def _collect() -> str:
|
async def _collect() -> str:
|
||||||
chunks: list[str] = []
|
chunks: list[str] = []
|
||||||
|
started = False
|
||||||
agen = self._stream(messages, None, temperature, output_format)
|
agen = self._stream(messages, None, temperature, output_format)
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
# Borne SEULEMENT l'attente du 1er token ; ensuite on laisse
|
# Borne SEULEMENT l'attente du 1er signe d'activité ; ensuite on
|
||||||
# générer (le ceiling global couvre le reste).
|
# laisse générer (le ceiling global couvre le reste). Un jeton vide
|
||||||
first = _FIRST_TOKEN_TIMEOUT_SECONDS if not chunks else None
|
# (modèle qui réfléchit) compte comme activité : il n'est pas en
|
||||||
|
# file d'attente.
|
||||||
|
first = None if started else _FIRST_TOKEN_TIMEOUT_SECONDS
|
||||||
try:
|
try:
|
||||||
token = await asyncio.wait_for(agen.__anext__(), timeout=first)
|
token = await asyncio.wait_for(agen.__anext__(), timeout=first)
|
||||||
except StopAsyncIteration:
|
except StopAsyncIteration:
|
||||||
break
|
break
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
raise LLMProviderError(self._first_token_timeout_message())
|
raise LLMProviderError(self._first_token_timeout_message())
|
||||||
chunks.append(token)
|
started = True
|
||||||
|
if token:
|
||||||
|
chunks.append(token)
|
||||||
finally:
|
finally:
|
||||||
await agen.aclose()
|
await agen.aclose()
|
||||||
return "".join(chunks)
|
return "".join(chunks)
|
||||||
@@ -195,7 +210,13 @@ class BaseOpenAICompatibleAdapter:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def _parse_sse(response: httpx.Response) -> AsyncIterator[str]:
|
async def _parse_sse(response: httpx.Response) -> AsyncIterator[str]:
|
||||||
"""SSE OpenAI : lignes `data: {json}`, fin sur `data: [DONE]`."""
|
"""SSE OpenAI : lignes `data: {json}`, fin sur `data: [DONE]`.
|
||||||
|
|
||||||
|
Un modèle à raisonnement (Mistral Large 4…) envoie `content` sous forme de
|
||||||
|
LISTE de morceaux typés : sa réflexion (`thinking`), puis le texte de la
|
||||||
|
réponse (`text`). Seul le texte est transmis ; pendant la réflexion on émet
|
||||||
|
un jeton VIDE, qui signale l'activité sans rien ajouter à la réponse.
|
||||||
|
"""
|
||||||
async for line in response.aiter_lines():
|
async for line in response.aiter_lines():
|
||||||
if not line or not line.startswith("data:"):
|
if not line or not line.startswith("data:"):
|
||||||
continue # lignes vides ou commentaires keep-alive (`: ...`)
|
continue # lignes vides ou commentaires keep-alive (`: ...`)
|
||||||
@@ -211,8 +232,11 @@ class BaseOpenAICompatibleAdapter:
|
|||||||
continue
|
continue
|
||||||
delta = choices[0].get("delta") or {}
|
delta = choices[0].get("delta") or {}
|
||||||
content = delta.get("content")
|
content = delta.get("content")
|
||||||
if content:
|
if isinstance(content, str):
|
||||||
yield content
|
if content:
|
||||||
|
yield content
|
||||||
|
elif isinstance(content, list):
|
||||||
|
yield _answer_text(content)
|
||||||
|
|
||||||
def _format_http_error(self, exc: httpx.HTTPError) -> str:
|
def _format_http_error(self, exc: httpx.HTTPError) -> str:
|
||||||
"""Message lisible (timeout, quota 429, crédits 402, modèle inconnu…)."""
|
"""Message lisible (timeout, quota 429, crédits 402, modèle inconnu…)."""
|
||||||
|
|||||||
+19
-1
@@ -9,7 +9,9 @@ import hmac
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.exception_handlers import http_exception_handler
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
|
|
||||||
from app.api.routers import (
|
from app.api.routers import (
|
||||||
chat,
|
chat,
|
||||||
@@ -18,7 +20,9 @@ from app.api.routers import (
|
|||||||
models,
|
models,
|
||||||
notebooks,
|
notebooks,
|
||||||
settings as settings_router,
|
settings as settings_router,
|
||||||
|
spells,
|
||||||
tables,
|
tables,
|
||||||
|
training,
|
||||||
)
|
)
|
||||||
from app.core.config import get_settings
|
from app.core.config import get_settings
|
||||||
from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_model
|
from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_model
|
||||||
@@ -26,7 +30,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LoreMind Brain",
|
title="LoreMind Brain",
|
||||||
description="Backend IA pour la génération de contenu narratif.",
|
description="Backend IA pour la génération de contenu narratif.",
|
||||||
version="1.6.2",
|
version="1.7.0-beta",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -61,6 +65,18 @@ async def require_internal_secret(request: Request, call_next):
|
|||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(StarletteHTTPException)
|
||||||
|
async def log_server_errors(request: Request, exc: StarletteHTTPException):
|
||||||
|
"""Journalise les erreurs 5xx avec leur détail (message du fournisseur IA…).
|
||||||
|
|
||||||
|
Sans cela le journal ne garde que « 502 Bad Gateway » : la cause réelle n'est
|
||||||
|
visible que dans la réponse, que le Core résume. La réponse est inchangée.
|
||||||
|
"""
|
||||||
|
if exc.status_code >= 500:
|
||||||
|
logger.warning("%s %s -> HTTP %s : %s", request.method, request.url.path, exc.status_code, exc.detail)
|
||||||
|
return await http_exception_handler(request, exc)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
def health() -> dict[str, str]:
|
def health() -> dict[str, str]:
|
||||||
"""Sonde de santé — permet au Core Java de vérifier que le Brain répond."""
|
"""Sonde de santé — permet au Core Java de vérifier que le Brain répond."""
|
||||||
@@ -85,6 +101,8 @@ async def _auto_install_embedding_model() -> None:
|
|||||||
app.include_router(generation.router)
|
app.include_router(generation.router)
|
||||||
app.include_router(chat.router)
|
app.include_router(chat.router)
|
||||||
app.include_router(tables.router)
|
app.include_router(tables.router)
|
||||||
|
app.include_router(training.router)
|
||||||
|
app.include_router(spells.router)
|
||||||
app.include_router(imports.router)
|
app.include_router(imports.router)
|
||||||
app.include_router(notebooks.router)
|
app.include_router(notebooks.router)
|
||||||
app.include_router(settings_router.router)
|
app.include_router(settings_router.router)
|
||||||
|
|||||||
+25
-1
@@ -13,12 +13,25 @@ On insere le dossier de CE fichier dans sys.path pour que le package `app`
|
|||||||
soit importable quel que soit le repertoire de travail (le Core fixe le cwd
|
soit importable quel que soit le repertoire de travail (le Core fixe le cwd
|
||||||
ailleurs, sous ~/.loremind/brain, pour y ecrire le dossier data/).
|
ailleurs, sous ~/.loremind/brain, pour y ecrire le dossier data/).
|
||||||
"""
|
"""
|
||||||
|
import copy
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
sys.path.insert(0, _HERE)
|
sys.path.insert(0, _HERE)
|
||||||
|
|
||||||
|
# Journal : le Core ecrit la sortie du Brain dans logs/brain.log. On la met en
|
||||||
|
# UTF-8 (sinon les accents dependent de la page de code Windows) et on date les
|
||||||
|
# journaux de l'application AVANT de l'importer : certains messages sont emis
|
||||||
|
# des le chargement (ex. OCR indisponible). httpx reste discret : une ligne par
|
||||||
|
# appel sortant n'apporte rien.
|
||||||
|
for _stream in (sys.stdout, sys.stderr):
|
||||||
|
if hasattr(_stream, "reconfigure"):
|
||||||
|
_stream.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s : %(message)s")
|
||||||
|
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||||
|
|
||||||
# OCR : si un Tesseract est bundlé à côté (mode desktop), on y pointe pytesseract
|
# OCR : si un Tesseract est bundlé à côté (mode desktop), on y pointe pytesseract
|
||||||
# AVANT que l'app n'importe le pdf_extractor (qui détecte la version au chargement).
|
# AVANT que l'app n'importe le pdf_extractor (qui détecte la version au chargement).
|
||||||
# tessdata (fra+eng) est embarqué dans tesseract/tessdata. Sans ce bloc, l'OCR
|
# tessdata (fra+eng) est embarqué dans tesseract/tessdata. Sans ce bloc, l'OCR
|
||||||
@@ -40,6 +53,17 @@ import uvicorn # noqa: E402
|
|||||||
|
|
||||||
from app.main import app # noqa: E402
|
from app.main import app # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _dated_log_config() -> dict:
|
||||||
|
"""Journaux d'uvicorn (demarrage, requetes) dates eux aussi : une ligne sans
|
||||||
|
date ne permet pas de retrouver une panne."""
|
||||||
|
config = copy.deepcopy(uvicorn.config.LOGGING_CONFIG)
|
||||||
|
config["formatters"]["default"]["fmt"] = "%(asctime)s %(levelprefix)s %(message)s"
|
||||||
|
config["formatters"]["access"]["fmt"] = (
|
||||||
|
'%(asctime)s %(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s')
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# host 127.0.0.1 : accessible uniquement depuis le Core sur la meme machine.
|
# host 127.0.0.1 : accessible uniquement depuis le Core sur la meme machine.
|
||||||
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
|
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info", log_config=_dated_log_config())
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Journal du Brain : une erreur 5xx renvoyée par une route y figure avec son détail.
|
||||||
|
|
||||||
|
En application de bureau, la sortie du Brain est écrite dans `logs/brain.log`. Sans ce
|
||||||
|
détail, le journal ne garderait que « 502 Bad Gateway » et la cause (clé refusée, quota,
|
||||||
|
modèle inconnu…) resterait introuvable.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.api.deps import get_llm_provider
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
_SECRET = "secret-de-test"
|
||||||
|
_BODY = {"method_name": "Donjon en 5 salles", "idea": "Une tour", "fields": [{"key": "name", "label": "Nom"}]}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(monkeypatch):
|
||||||
|
monkeypatch.setenv("INTERNAL_SHARED_SECRET", _SECRET)
|
||||||
|
with TestClient(app) as test_client:
|
||||||
|
test_client.headers["X-Internal-Secret"] = _SECRET
|
||||||
|
yield test_client
|
||||||
|
app.dependency_overrides.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_5xx_error_is_logged_with_its_detail_and_still_returned(client, caplog):
|
||||||
|
def failing_provider():
|
||||||
|
raise HTTPException(status_code=502, detail="Erreur Mistral : clé refusée (401).")
|
||||||
|
|
||||||
|
app.dependency_overrides[get_llm_provider] = failing_provider
|
||||||
|
with caplog.at_level(logging.WARNING, logger="app.main"):
|
||||||
|
response = client.post("/generate/guided-answers", json=_BODY)
|
||||||
|
|
||||||
|
assert response.status_code == 502
|
||||||
|
assert response.json() == {"detail": "Erreur Mistral : clé refusée (401)."}
|
||||||
|
logged = [r.getMessage() for r in caplog.records if r.name == "app.main"]
|
||||||
|
assert logged == ["POST /generate/guided-answers -> HTTP 502 : Erreur Mistral : clé refusée (401)."]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_4xx_error_is_not_logged(client, caplog):
|
||||||
|
def refusing_provider():
|
||||||
|
raise HTTPException(status_code=422, detail="Demande invalide.")
|
||||||
|
|
||||||
|
app.dependency_overrides[get_llm_provider] = refusing_provider
|
||||||
|
with caplog.at_level(logging.WARNING, logger="app.main"):
|
||||||
|
response = client.post("/generate/guided-answers", json=_BODY)
|
||||||
|
|
||||||
|
assert response.status_code == 422
|
||||||
|
assert [r for r in caplog.records if r.name == "app.main"] == []
|
||||||
@@ -202,3 +202,52 @@ async def test_sse_skips_keepalive_and_malformed_lines(cls, url, skw, supports_j
|
|||||||
def test_missing_api_key_raises_at_construction(cls, skw):
|
def test_missing_api_key_raises_at_construction(cls, skw):
|
||||||
with pytest.raises(LLMProviderError):
|
with pytest.raises(LLMProviderError):
|
||||||
cls(_settings(**skw))
|
cls(_settings(**skw))
|
||||||
|
|
||||||
|
|
||||||
|
# --- Modèles à raisonnement : `content` en liste de morceaux typés -----------
|
||||||
|
|
||||||
|
def _sse_deltas(*contents: object) -> str:
|
||||||
|
"""Comme `_sse`, mais `content` peut être une liste de morceaux typés."""
|
||||||
|
lines: list[str] = []
|
||||||
|
for c in contents:
|
||||||
|
lines.append("data: " + json.dumps({"choices": [{"delta": {"content": c}}]}))
|
||||||
|
lines.append("")
|
||||||
|
lines += ["data: [DONE]", ""]
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
# Les trois phases d'un flux Mistral Large 4 : réflexion, fin de réflexion + début
|
||||||
|
# de la réponse dans la même liste, puis suite de la réponse en texte simple.
|
||||||
|
_REASONING_STREAM = _sse_deltas(
|
||||||
|
[{"type": "thinking", "thinking": [{"type": "text", "text": "L'utilisateur veut"}]}],
|
||||||
|
[{"type": "thinking", "thinking": [{"type": "text", "text": " un mot."}]}],
|
||||||
|
[{"type": "thinking", "thinking": [], "closed": True}, {"type": "text", "text": "Bon"}],
|
||||||
|
"jour",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||||
|
@respx.mock
|
||||||
|
async def test_generate_keeps_only_the_answer_of_a_reasoning_model(cls, url, skw, supports_json, label):
|
||||||
|
respx.post(url).mock(return_value=httpx.Response(200, text=_REASONING_STREAM))
|
||||||
|
svc = cls(_settings(**skw))
|
||||||
|
assert await svc.generate("x", output_format="json") == "Bonjour"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||||
|
@respx.mock
|
||||||
|
async def test_stream_chat_hides_the_thinking_of_a_reasoning_model(cls, url, skw, supports_json, label):
|
||||||
|
respx.post(url).mock(return_value=httpx.Response(200, text=_REASONING_STREAM))
|
||||||
|
svc = cls(_settings(**skw))
|
||||||
|
tokens = [t async for t in svc.stream_chat([ChatMessage(role="user", content="x")])]
|
||||||
|
assert tokens == ["Bon", "jour"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||||
|
@respx.mock
|
||||||
|
async def test_generate_survives_a_reasoning_only_stream(cls, url, skw, supports_json, label):
|
||||||
|
"""Que de la réflexion, aucune réponse : chaîne vide, pas d'exception de type."""
|
||||||
|
body = _sse_deltas([{"type": "thinking", "thinking": [{"type": "text", "text": "…"}]}])
|
||||||
|
respx.post(url).mock(return_value=httpx.Response(200, text=body))
|
||||||
|
svc = cls(_settings(**skw))
|
||||||
|
assert await svc.generate("x") == ""
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
"""Entraînement aux règles : prompts, nettoyage et routes (série, comparaison)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.api.deps import get_llm_provider
|
||||||
|
from app.api.routers.training import _clean_drills
|
||||||
|
from app.application.prompts.rule_training import rule_drill_review_prompt, rule_drills_prompt
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
_SECRET = "secret-de-test"
|
||||||
|
_SECTIONS = {"Combat": "Une attaque réussit si le jet dépasse la Garde.", "Repos": "Une nuit rend tous les PV."}
|
||||||
|
_SCENES = [{"name": "La crypte", "kind": "ENCOUNTER", "text": "Deux gardes devant une statue."}]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeLLM:
|
||||||
|
def __init__(self, response: str) -> None:
|
||||||
|
self.response = response
|
||||||
|
self.prompt: str | None = None
|
||||||
|
self.output_format: object = None
|
||||||
|
self.temperature: float | None = None
|
||||||
|
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
self.prompt = prompt
|
||||||
|
self.output_format = output_format
|
||||||
|
self.temperature = temperature
|
||||||
|
return self.response
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(monkeypatch):
|
||||||
|
monkeypatch.setenv("INTERNAL_SHARED_SECRET", _SECRET)
|
||||||
|
with TestClient(app) as test_client:
|
||||||
|
test_client.headers["X-Internal-Secret"] = _SECRET
|
||||||
|
yield test_client
|
||||||
|
app.dependency_overrides.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_drills_prompt_carries_rules_scenes_count_avoided_and_language():
|
||||||
|
prompt = rule_drills_prompt(
|
||||||
|
"Brumes", {**_SECTIONS, "Vide": " "}, _SCENES, 4, ["Un joueur saute le ravin.", " "], "en")
|
||||||
|
|
||||||
|
assert "« Brumes »" in prompt
|
||||||
|
assert "Écris 4 situations" in prompt
|
||||||
|
assert "### Combat\nUne attaque réussit si le jet dépasse la Garde." in prompt
|
||||||
|
assert "### Vide" not in prompt, "une section sans contenu n'est pas envoyée"
|
||||||
|
assert "[1] La crypte (ENCOUNTER)\nDeux gardes devant une statue." in prompt
|
||||||
|
assert "- Un joueur saute le ravin." in prompt
|
||||||
|
assert "MOT POUR MOT" in prompt
|
||||||
|
assert "Ne lance AUCUN dé" in prompt
|
||||||
|
assert '{"drills": []}' in prompt
|
||||||
|
assert "anglais" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_drills_prompt_without_scene_or_avoided_situation():
|
||||||
|
prompt = rule_drills_prompt("", _SECTIONS, [], 5, [], "fr")
|
||||||
|
|
||||||
|
assert "« ce jeu »" in prompt
|
||||||
|
assert "Aucune scène n'est fournie" in prompt
|
||||||
|
assert "DÉJÀ posées" not in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_review_prompt_carries_the_section_the_answer_and_the_verdicts():
|
||||||
|
prompt = rule_drill_review_prompt(
|
||||||
|
"Brumes", "Combat", _SECTIONS["Combat"], "Un joueur frappe le garde.",
|
||||||
|
"Une attaque réussit si le jet dépasse la Garde.", "Demandez un jet contre la Garde.",
|
||||||
|
"Je demande un jet d'attaque.", "fr")
|
||||||
|
|
||||||
|
assert "section « Combat »" in prompt
|
||||||
|
assert "Décision du MJ :\nJe demande un jet d'attaque." in prompt
|
||||||
|
assert '"right"' in prompt and '"partial"' in prompt and '"off"' in prompt
|
||||||
|
assert "français" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_keeps_complete_drills_and_normalizes_the_scene_number():
|
||||||
|
out = _clean_drills([
|
||||||
|
{"scene": 2, "situation": " S ", "section": " Combat ", "excerpt": " E ", "ruling": " R "},
|
||||||
|
{"scene": "1", "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||||
|
{"scene": -3, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||||
|
{"scene": True, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||||
|
{"scene": 1, "situation": "S", "section": "Repos", "excerpt": " ", "ruling": "R"},
|
||||||
|
{"scene": 1, "situation": "S", "section": "Repos", "excerpt": "E"},
|
||||||
|
"pas un objet",
|
||||||
|
])
|
||||||
|
|
||||||
|
assert [d.model_dump() for d in out] == [
|
||||||
|
{"scene": 2, "situation": "S", "section": "Combat", "excerpt": "E", "ruling": "R"},
|
||||||
|
{"scene": 1, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||||
|
{"scene": 0, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||||
|
{"scene": 0, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||||
|
]
|
||||||
|
assert _clean_drills({"drills": []}) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_drills_route_returns_the_series(client):
|
||||||
|
llm = FakeLLM('{"drills": [{"scene": 1, "situation": "Un joueur frappe.", "section": "Combat", '
|
||||||
|
'"excerpt": "Une attaque réussit si le jet dépasse la Garde.", "ruling": "Jet contre la Garde."}]}')
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||||
|
|
||||||
|
response = client.post("/generate/rule-drills", json={
|
||||||
|
"system_name": "Brumes", "sections": _SECTIONS, "scenes": _SCENES, "count": 3})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"drills": [{
|
||||||
|
"scene": 1, "situation": "Un joueur frappe.", "section": "Combat",
|
||||||
|
"excerpt": "Une attaque réussit si le jet dépasse la Garde.", "ruling": "Jet contre la Garde."}]}
|
||||||
|
assert "Écris 3 situations" in llm.prompt and "[1] La crypte" in llm.prompt
|
||||||
|
assert isinstance(llm.output_format, dict), "sortie structurée demandée au modèle"
|
||||||
|
|
||||||
|
|
||||||
|
def test_drills_route_refuses_a_request_without_rules(client):
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("{}")
|
||||||
|
|
||||||
|
response = client.post("/generate/rule-drills", json={"sections": {"Combat": " "}})
|
||||||
|
|
||||||
|
assert response.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_drills_route_reports_an_unusable_answer(client):
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("Je ne sais pas.")
|
||||||
|
|
||||||
|
response = client.post("/generate/rule-drills", json={"sections": _SECTIONS})
|
||||||
|
|
||||||
|
assert response.status_code == 502
|
||||||
|
assert response.json() == {"detail": "Le modèle n'a pas renvoyé de série exploitable."}
|
||||||
|
|
||||||
|
|
||||||
|
_REVIEW_BODY = {
|
||||||
|
"system_name": "Brumes", "section_title": "Combat", "section_text": _SECTIONS["Combat"],
|
||||||
|
"situation": "Un joueur frappe le garde.", "excerpt": "Une attaque réussit si le jet dépasse la Garde.",
|
||||||
|
"ruling": "Jet contre la Garde.", "answer": "Je demande un jet d'attaque."}
|
||||||
|
|
||||||
|
|
||||||
|
def test_review_route_returns_the_verdict(client):
|
||||||
|
llm = FakeLLM('{"verdict": "Partial", "feedback": " Il manque la Garde. "}')
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||||
|
|
||||||
|
response = client.post("/generate/rule-drill-review", json=_REVIEW_BODY)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"verdict": "partial", "feedback": "Il manque la Garde."}
|
||||||
|
assert llm.temperature == 0.2
|
||||||
|
|
||||||
|
|
||||||
|
def test_review_route_refuses_an_empty_answer(client):
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("{}")
|
||||||
|
|
||||||
|
response = client.post("/generate/rule-drill-review", json={**_REVIEW_BODY, "answer": " "})
|
||||||
|
|
||||||
|
assert response.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("answer", [
|
||||||
|
"Je ne sais pas.",
|
||||||
|
'{"verdict": "bravo", "feedback": "ok"}',
|
||||||
|
'{"verdict": "right", "feedback": ""}',
|
||||||
|
])
|
||||||
|
def test_review_route_reports_an_unusable_answer(client, answer):
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM(answer)
|
||||||
|
|
||||||
|
response = client.post("/generate/rule-drill-review", json=_REVIEW_BODY)
|
||||||
|
|
||||||
|
assert response.status_code == 502
|
||||||
|
assert response.json() == {"detail": "Le modèle n'a pas renvoyé de comparaison exploitable."}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""Modèle de fiche proposé à partir des règles : prompt, nettoyage et route."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.api.deps import get_llm_provider
|
||||||
|
from app.api.routers.generation import _clean_sheet_fields
|
||||||
|
from app.application.prompts.sheet_template import sheet_template_prompt
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
_SECRET = "secret-de-test"
|
||||||
|
_SECTIONS = {"Création de personnage": "Six caractéristiques : Force, Agilité…", "Combat": "Les PV…"}
|
||||||
|
|
||||||
|
|
||||||
|
class FakeLLM:
|
||||||
|
def __init__(self, response: str) -> None:
|
||||||
|
self.response = response
|
||||||
|
self.prompt: str | None = None
|
||||||
|
self.output_format: object = None
|
||||||
|
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
self.prompt = prompt
|
||||||
|
self.output_format = output_format
|
||||||
|
return self.response
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(monkeypatch):
|
||||||
|
monkeypatch.setenv("INTERNAL_SHARED_SECRET", _SECRET)
|
||||||
|
with TestClient(app) as test_client:
|
||||||
|
test_client.headers["X-Internal-Secret"] = _SECRET
|
||||||
|
yield test_client
|
||||||
|
app.dependency_overrides.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_contains_rules_existing_fields_sheet_and_language():
|
||||||
|
prompt = sheet_template_prompt(
|
||||||
|
"character", "Nimble", {**_SECTIONS, "Vide": " "}, ["Histoire", " "], "en")
|
||||||
|
|
||||||
|
assert "PERSONNAGE JOUEUR" in prompt
|
||||||
|
assert "« Nimble »" in prompt
|
||||||
|
assert "### Création de personnage\nSix caractéristiques : Force, Agilité…" in prompt
|
||||||
|
assert "### Vide" not in prompt, "une section sans contenu n'est pas envoyée"
|
||||||
|
assert "- Histoire" in prompt
|
||||||
|
assert "SEULE source autorisée" in prompt
|
||||||
|
assert '{"fields": []}' in prompt
|
||||||
|
assert "anglais" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_adapts_to_the_sheet_and_omits_the_existing_block_when_empty():
|
||||||
|
enemy = sheet_template_prompt("enemy", "", _SECTIONS, [], "fr")
|
||||||
|
assert "ENNEMI" in enemy
|
||||||
|
assert "« ce jeu »" in enemy
|
||||||
|
assert "DÉJÀ présents" not in enemy
|
||||||
|
assert "PERSONNAGE NON-JOUEUR" in sheet_template_prompt("npc", "X", _SECTIONS, [], "fr")
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_keeps_well_formed_fields_and_normalizes_them():
|
||||||
|
out = _clean_sheet_fields([
|
||||||
|
{"name": " Caractéristiques ", "type": "key_value_list", "labels": ["Force", " ", 3], "source": " Combat "},
|
||||||
|
{"name": "PV", "type": "NUMBER"},
|
||||||
|
{"name": "", "type": "TEXT"},
|
||||||
|
{"name": "Sans type"},
|
||||||
|
{"name": ["liste"], "type": "TEXT"},
|
||||||
|
"pas un objet",
|
||||||
|
])
|
||||||
|
|
||||||
|
assert [f.model_dump() for f in out] == [
|
||||||
|
{"name": "Caractéristiques", "type": "KEY_VALUE_LIST", "labels": ["Force", "3"], "source": "Combat"},
|
||||||
|
{"name": "PV", "type": "NUMBER", "labels": [], "source": ""},
|
||||||
|
]
|
||||||
|
assert _clean_sheet_fields({"fields": []}) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_returns_the_proposed_fields(client):
|
||||||
|
llm = FakeLLM('{"fields": [{"name": "Points de vie", "type": "NUMBER", "labels": [], "source": "Combat"}]}')
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||||
|
|
||||||
|
response = client.post("/generate/sheet-template", json={
|
||||||
|
"sheet": "enemy", "system_name": "Nimble", "sections": _SECTIONS, "existing_fields": ["Butin"]})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {
|
||||||
|
"fields": [{"name": "Points de vie", "type": "NUMBER", "labels": [], "source": "Combat"}]}
|
||||||
|
assert "ENNEMI" in llm.prompt and "- Butin" in llm.prompt
|
||||||
|
assert isinstance(llm.output_format, dict), "sortie structurée demandée au modèle"
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_refuses_a_request_without_rules(client):
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("{}")
|
||||||
|
|
||||||
|
response = client.post("/generate/sheet-template", json={"sheet": "character", "sections": {"Combat": " "}})
|
||||||
|
|
||||||
|
assert response.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_reports_an_unusable_answer(client):
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("Je ne sais pas.")
|
||||||
|
|
||||||
|
response = client.post("/generate/sheet-template", json={"sheet": "character", "sections": _SECTIONS})
|
||||||
|
|
||||||
|
assert response.status_code == 502
|
||||||
|
assert response.json() == {"detail": "Le modèle n'a pas renvoyé de fiche exploitable."}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""Relevé de sorts dans un texte de règles : prompt, nettoyage et route."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.api.deps import get_llm_provider
|
||||||
|
from app.api.routers.spells import _clean_spells
|
||||||
|
from app.application.prompts.spell_extraction import spell_extraction_prompt
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
_SECRET = "secret-de-test"
|
||||||
|
_TEXT = (
|
||||||
|
"### Éclair de givre\nNiveau 1 — Évocation. Portée : 18 m.\n"
|
||||||
|
"Un trait de givre frappe une cible : 2d6 dégâts de froid."
|
||||||
|
)
|
||||||
|
_FIELDS = [{"name": "Portée", "type": "TEXT"}, {"name": "Coût", "type": "NUMBER"}, {"name": " ", "type": "TEXT"}]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeLLM:
|
||||||
|
def __init__(self, response: str) -> None:
|
||||||
|
self.response = response
|
||||||
|
self.prompt: str | None = None
|
||||||
|
self.output_format: object = None
|
||||||
|
self.temperature: float | None = None
|
||||||
|
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
self.prompt = prompt
|
||||||
|
self.output_format = output_format
|
||||||
|
self.temperature = temperature
|
||||||
|
return self.response
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(monkeypatch):
|
||||||
|
monkeypatch.setenv("INTERNAL_SHARED_SECRET", _SECRET)
|
||||||
|
with TestClient(app) as test_client:
|
||||||
|
test_client.headers["X-Internal-Secret"] = _SECRET
|
||||||
|
yield test_client
|
||||||
|
app.dependency_overrides.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_carries_text_fields_avoided_names_and_fidelity_rules():
|
||||||
|
prompt = spell_extraction_prompt("Brumes", "Magie", _TEXT, _FIELDS, ["Voile de brume", " "])
|
||||||
|
|
||||||
|
assert "« Brumes »" in prompt
|
||||||
|
assert "section « Magie »" in prompt
|
||||||
|
assert "Un trait de givre frappe une cible" in prompt
|
||||||
|
assert "- Portée (texte)" in prompt
|
||||||
|
assert "- Coût (nombre)" in prompt
|
||||||
|
assert "- (" not in prompt, "un champ sans nom n'est pas envoyé"
|
||||||
|
assert "- Voile de brume" in prompt
|
||||||
|
assert "MOT POUR MOT" in prompt
|
||||||
|
assert "EXACTEMENT comme dans le texte" in prompt
|
||||||
|
assert "Ne résume" in prompt
|
||||||
|
assert "ne traduis" in prompt
|
||||||
|
assert '{"spells": []}' in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_without_field_title_or_avoided_name():
|
||||||
|
prompt = spell_extraction_prompt("", "", _TEXT, [], [])
|
||||||
|
|
||||||
|
assert "« ce jeu »" in prompt
|
||||||
|
assert "— extrait (SEULE source autorisée)" in prompt
|
||||||
|
assert '"values": {}' in prompt
|
||||||
|
assert "DÉJÀ relevés" not in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_spells_keeps_complete_entries_and_stringifies_values():
|
||||||
|
spells = _clean_spells([
|
||||||
|
{"name": " Éclair ", "level": 1, "school": None, "description": " Un trait. ",
|
||||||
|
"values": {"Portée": " 18 m ", "Coût": 2, "Vide": " ", " ": "x", "Liste": ["a"]}, "excerpt": " Un trait. "},
|
||||||
|
{"name": "Sans description", "description": " ", "excerpt": "Un passage."},
|
||||||
|
{"name": "Sans passage", "description": "Un effet."},
|
||||||
|
{"name": "", "description": "Un effet.", "excerpt": "Un passage."},
|
||||||
|
{"name": "Valeurs mal formées", "description": "Un effet.", "excerpt": "Un passage.", "values": ["x"]},
|
||||||
|
"pas un objet",
|
||||||
|
])
|
||||||
|
|
||||||
|
assert [s.name for s in spells] == ["Éclair", "Valeurs mal formées"]
|
||||||
|
assert spells[0].level == "1"
|
||||||
|
assert spells[0].school == ""
|
||||||
|
assert spells[0].description == "Un trait."
|
||||||
|
assert spells[0].values == {"Portée": "18 m", "Coût": "2"}
|
||||||
|
assert spells[1].values == {}
|
||||||
|
assert _clean_spells(None) == []
|
||||||
|
assert _clean_spells({"name": "x"}) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_returns_cleaned_spells_with_low_temperature(client):
|
||||||
|
llm = FakeLLM(json.dumps({"spells": [
|
||||||
|
{"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
||||||
|
"description": "Un trait de givre frappe une cible : 2d6 dégâts de froid.",
|
||||||
|
"values": {"Portée": "18 m"}, "excerpt": "Un trait de givre frappe une cible"},
|
||||||
|
{"name": "Incomplet"},
|
||||||
|
]}))
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||||
|
|
||||||
|
response = client.post("/generate/spell-extraction", json={
|
||||||
|
"system_name": "Brumes", "section_title": "Magie", "text": _TEXT,
|
||||||
|
"fields": _FIELDS, "avoid": ["Voile de brume"]})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"spells": [{
|
||||||
|
"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
||||||
|
"description": "Un trait de givre frappe une cible : 2d6 dégâts de froid.",
|
||||||
|
"values": {"Portée": "18 m"}, "excerpt": "Un trait de givre frappe une cible"}]}
|
||||||
|
assert llm.temperature == 0.1
|
||||||
|
assert llm.output_format["required"] == ["spells"]
|
||||||
|
assert "- Voile de brume" in llm.prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_rejects_empty_text_and_reports_unusable_answer(client):
|
||||||
|
llm = FakeLLM("pas du JSON")
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||||
|
|
||||||
|
assert client.post("/generate/spell-extraction", json={"text": " "}).status_code == 422
|
||||||
|
assert llm.prompt is None, "aucun appel au modèle sans texte"
|
||||||
|
|
||||||
|
response = client.post("/generate/spell-extraction", json={"text": _TEXT})
|
||||||
|
assert response.status_code == 502
|
||||||
|
assert "exploitable" in response.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_with_no_spell_returns_empty_list(client):
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM('{"spells": []}')
|
||||||
|
|
||||||
|
response = client.post("/generate/spell-extraction", json={"text": "Une nuit complète rend tous les PV."})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"spells": []}
|
||||||
+1
-1
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
<groupId>com.loremind</groupId>
|
<groupId>com.loremind</groupId>
|
||||||
<artifactId>loremind-core</artifactId>
|
<artifactId>loremind-core</artifactId>
|
||||||
<version>1.6.2</version>
|
<version>1.7.0-beta</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
|
|||||||
+18
-13
@@ -114,7 +114,7 @@ public class CampaignReadinessService {
|
|||||||
if (totalScenes == 0 && !anyQuestHasNodes(quests)) {
|
if (totalScenes == 0 && !anyQuestHasNodes(quests)) {
|
||||||
gaps.add(new ReadinessGap(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
gaps.add(new ReadinessGap(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
||||||
"CAMP-001-NO-CONTENT",
|
"CAMP-001-NO-CONTENT",
|
||||||
"Campagne vide : ajoutez un arc avec une scène, ou créez une quête, pour commencer à jouer.",
|
"Campagne vide : ajoutez une scène ou une aventure pour commencer à jouer.",
|
||||||
ReadinessSeverity.BLOCKING, null, null));
|
ReadinessSeverity.BLOCKING, null, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,9 +146,11 @@ public class CampaignReadinessService {
|
|||||||
chapterIds.add(chapter.getId());
|
chapterIds.add(chapter.getId());
|
||||||
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId());
|
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId());
|
||||||
if (scenes.isEmpty()) {
|
if (scenes.isEmpty()) {
|
||||||
|
// Arc SYSTEM : ses chapitres sont les espaces de scènes des quêtes annexes.
|
||||||
|
String kind = arc.getType() == ArcType.SYSTEM ? "Quête annexe" : "Aventure";
|
||||||
gaps.add(new ReadinessGap(ReadinessEntityType.CHAPTER, chapter.getId(),
|
gaps.add(new ReadinessGap(ReadinessEntityType.CHAPTER, chapter.getId(),
|
||||||
labelOr(chapter.getName(), "Chapitre"), "CHAP-001-NO-SCENE",
|
labelOr(chapter.getName(), kind), "CHAP-001-NO-SCENE",
|
||||||
"Chapitre vide : ajoutez au moins une scène pour pouvoir le jouer.",
|
kind + " vide : ajoutez au moins une scène pour pouvoir la jouer.",
|
||||||
ReadinessSeverity.BLOCKING, arc.getId(), chapter.getId()));
|
ReadinessSeverity.BLOCKING, arc.getId(), chapter.getId()));
|
||||||
}
|
}
|
||||||
Set<String> chapterSceneIds = scenes.stream()
|
Set<String> chapterSceneIds = scenes.stream()
|
||||||
@@ -163,9 +165,8 @@ public class CampaignReadinessService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private ReadinessGap emptyArcGap(Arc arc) {
|
private ReadinessGap emptyArcGap(Arc arc) {
|
||||||
String msg = arc.getType() == ArcType.HUB
|
// Même mot pour l'auteur, que l'arc soit linéaire ou à ordre libre (HUB) : une aventure.
|
||||||
? "Arc vide : ajoutez une quête (ou un chapitre), ou supprimez-le."
|
String msg = "Arc vide : ajoutez une aventure, ou supprimez-le.";
|
||||||
: "Arc vide : ajoutez un chapitre, ou supprimez-le.";
|
|
||||||
return new ReadinessGap(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
return new ReadinessGap(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
||||||
"ARC-001-EMPTY", msg, ReadinessSeverity.BLOCKING, arc.getId(), null);
|
"ARC-001-EMPTY", msg, ReadinessSeverity.BLOCKING, arc.getId(), null);
|
||||||
}
|
}
|
||||||
@@ -204,7 +205,7 @@ public class CampaignReadinessService {
|
|||||||
if (invalid) {
|
if (invalid) {
|
||||||
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-010-BRANCH-INVALID",
|
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-010-BRANCH-INVALID",
|
||||||
"Branche cassée : une sortie de « " + labelOr(scene.getName(), SCENE_FALLBACK_NAME)
|
"Branche cassée : une sortie de « " + labelOr(scene.getName(), SCENE_FALLBACK_NAME)
|
||||||
+ " » pointe dans le vide, hors du chapitre, ou sur elle-même.",
|
+ " » pointe dans le vide, hors de l'aventure, ou sur elle-même.",
|
||||||
ReadinessSeverity.BLOCKING));
|
ReadinessSeverity.BLOCKING));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,20 +275,24 @@ public class CampaignReadinessService {
|
|||||||
|
|
||||||
private void checkQuest(Quest quest, Set<String> allChapterIds, Set<String> allSceneIds,
|
private void checkQuest(Quest quest, Set<String> allChapterIds, Set<String> allSceneIds,
|
||||||
Set<String> questIds, List<ReadinessGap> gaps) {
|
Set<String> questIds, List<ReadinessGap> gaps) {
|
||||||
String name = labelOr(quest.getName(), "Quête");
|
// Rattachée à un arc (HUB, « à ordre libre ») : c'est une aventure de cet arc pour
|
||||||
|
// l'auteur. Sans arc : une quête annexe.
|
||||||
|
boolean adventure = !isBlank(quest.getArcId());
|
||||||
|
String name = labelOr(quest.getName(), adventure ? "Aventure" : "Quête annexe");
|
||||||
|
|
||||||
// QUEST-001 — quête sans nœud ; sinon QUEST-010 — nœud pointant dans le vide.
|
// QUEST-001 — quête sans nœud ; sinon QUEST-010 — nœud pointant dans le vide.
|
||||||
if (quest.getNodes() == null || quest.getNodes().isEmpty()) {
|
if (quest.getNodes() == null || quest.getNodes().isEmpty()) {
|
||||||
gaps.add(questGap(quest, "QUEST-001-NO-NODES",
|
gaps.add(questGap(quest, "QUEST-001-NO-NODES",
|
||||||
"Quête sans contenu : ajoutez au moins un chapitre ou une scène à « " + name + " »."));
|
(adventure ? "Aventure" : "Quête annexe")
|
||||||
|
+ " sans contenu : ajoutez au moins une scène à « " + name + " »."));
|
||||||
} else if (quest.getNodes().stream().anyMatch(n ->
|
} else if (quest.getNodes().stream().anyMatch(n ->
|
||||||
n.nodeType() == null
|
n.nodeType() == null
|
||||||
|| isBlank(n.nodeId())
|
|| isBlank(n.nodeId())
|
||||||
|| (n.nodeType() == NodeType.CHAPTER && !allChapterIds.contains(n.nodeId()))
|
|| (n.nodeType() == NodeType.CHAPTER && !allChapterIds.contains(n.nodeId()))
|
||||||
|| (n.nodeType() == NodeType.SCENE && !allSceneIds.contains(n.nodeId())))) {
|
|| (n.nodeType() == NodeType.SCENE && !allSceneIds.contains(n.nodeId())))) {
|
||||||
gaps.add(questGap(quest, "QUEST-010-NODE-REF-BROKEN",
|
gaps.add(questGap(quest, "QUEST-010-NODE-REF-BROKEN",
|
||||||
"Nœud de quête cassé : dans « " + name
|
"Lien cassé : dans « " + name
|
||||||
+ " », un chapitre ou une scène référencé n'existe plus."));
|
+ " », une aventure ou une scène référencée n'existe plus."));
|
||||||
}
|
}
|
||||||
|
|
||||||
// CAMP-010 — prérequis QuestCompleted pointant une quête disparue.
|
// CAMP-010 — prérequis QuestCompleted pointant une quête disparue.
|
||||||
@@ -297,7 +302,7 @@ public class CampaignReadinessService {
|
|||||||
.anyMatch(qid -> isBlank(qid) || !questIds.contains(qid))) {
|
.anyMatch(qid -> isBlank(qid) || !questIds.contains(qid))) {
|
||||||
gaps.add(questGap(quest, "CAMP-010-DANGLING-QUEST-PREREQ",
|
gaps.add(questGap(quest, "CAMP-010-DANGLING-QUEST-PREREQ",
|
||||||
"Prérequis cassé : « " + name
|
"Prérequis cassé : « " + name
|
||||||
+ " » dépend d'une quête qui n'existe plus. Corrigez la condition de déblocage."));
|
+ " » dépend d'une aventure ou d'une quête qui n'existe plus. Corrigez la condition de déblocage."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -331,7 +336,7 @@ public class CampaignReadinessService {
|
|||||||
|
|
||||||
private ReadinessGap questGap(Quest quest, String ruleId, String message) {
|
private ReadinessGap questGap(Quest quest, String ruleId, String message) {
|
||||||
return new ReadinessGap(ReadinessEntityType.QUEST, quest.getId(),
|
return new ReadinessGap(ReadinessEntityType.QUEST, quest.getId(),
|
||||||
labelOr(quest.getName(), "Quête"), ruleId, message, ReadinessSeverity.BLOCKING, null, null);
|
labelOr(quest.getName(), isBlank(quest.getArcId()) ? "Quête annexe" : "Aventure"), ruleId, message, ReadinessSeverity.BLOCKING, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int severityRank(ReadinessSeverity severity) {
|
private static int severityRank(ReadinessSeverity severity) {
|
||||||
|
|||||||
@@ -78,7 +78,32 @@ public class ChapterService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Chapter chapter = existingChapter.get();
|
Chapter chapter = existingChapter.get();
|
||||||
BeanUtils.copyProperties(updated, chapter, "id");
|
// guidedMethod : jamais porté par le formulaire d'édition, il ne doit pas être effacé.
|
||||||
|
BeanUtils.copyProperties(updated, chapter, "id", "guidedMethod");
|
||||||
|
return chapterRepository.save(chapter);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rattache le chapitre à une méthode guidée, ou l'en détache ({@code null} / vide).
|
||||||
|
* Changer ou retirer la méthode efface le rôle de ses scènes : un rôle n'a de sens que
|
||||||
|
* dans la méthode qui le définit. Transactionnel.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException chapitre inconnu ou identifiant de méthode invalide
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Chapter setGuidedMethod(String id, String method) {
|
||||||
|
Chapter chapter = chapterRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Chapter non trouvé avec l'ID: " + id));
|
||||||
|
String next = GuidedKeys.normalize(method);
|
||||||
|
if (!java.util.Objects.equals(next, chapter.getGuidedMethod())) {
|
||||||
|
for (var scene : sceneRepository.findByChapterId(id)) {
|
||||||
|
if (scene.getGuidedRole() != null) {
|
||||||
|
scene.setGuidedRole(null);
|
||||||
|
sceneRepository.save(scene);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chapter.setGuidedMethod(next);
|
||||||
return chapterRepository.save(chapter);
|
return chapterRepository.save(chapter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Identifiants des méthodes guidées et de leurs rôles (« five-room », « room3 »…). Le Core
|
||||||
|
* ne connaît pas la liste des méthodes (elles sont décrites côté front) : il vérifie
|
||||||
|
* seulement la forme de l'identifiant avant de le stocker.
|
||||||
|
*/
|
||||||
|
final class GuidedKeys {
|
||||||
|
|
||||||
|
private static final Pattern KEY = Pattern.compile("[A-Za-z0-9_-]{1,64}");
|
||||||
|
|
||||||
|
private GuidedKeys() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return l'identifiant nettoyé, ou {@code null} s'il est absent ou vide
|
||||||
|
* @throws IllegalArgumentException identifiant mal formé
|
||||||
|
*/
|
||||||
|
static String normalize(String key) {
|
||||||
|
if (key == null || key.isBlank()) return null;
|
||||||
|
String trimmed = key.trim();
|
||||||
|
if (!KEY.matcher(trimmed).matches()) {
|
||||||
|
throw new IllegalArgumentException("Identifiant de méthode guidée invalide.");
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forme des méthodes guidées que la relecture sait juger : pour chaque méthode, ses rôles
|
||||||
|
* dans l'ordre. Les méthodes elles-mêmes (questions, textes) sont décrites côté front
|
||||||
|
* ({@code web/src/app/campaigns/guided/methods}) ; seule cette liste est répétée ici, et le
|
||||||
|
* test front {@code guided-methods.spec.ts} vérifie que les deux côtés disent la même chose.
|
||||||
|
*
|
||||||
|
* <p>Une méthode absente de cette table reste utilisable : la relecture ne dit simplement
|
||||||
|
* rien de propre à elle.</p>
|
||||||
|
*/
|
||||||
|
final class GuidedMethodShapes {
|
||||||
|
|
||||||
|
static final String FIVE_ROOM = "five-room";
|
||||||
|
static final String INVESTIGATION = "investigation";
|
||||||
|
static final String VILLAIN_PLAN = "villain-plan";
|
||||||
|
|
||||||
|
/** Donjon en 5 salles : l'épreuve, qui ne se règle pas à l'épée. */
|
||||||
|
static final String FIVE_ROOM_TRIAL = "room2";
|
||||||
|
/** Enquête en nœuds : la conclusion, que trois pistes doivent atteindre. */
|
||||||
|
static final String INVESTIGATION_CONCLUSION = "conclusion";
|
||||||
|
|
||||||
|
private static final Map<String, List<String>> ROLES = Map.of(
|
||||||
|
FIVE_ROOM, List.of("room1", "room2", "room3", "room4", "room5"),
|
||||||
|
INVESTIGATION, List.of("hook", "node1", "node2", "node3", "conclusion", "proactive"),
|
||||||
|
VILLAIN_PLAN, List.of("step1", "step2", "step3", "step4", "step5", "step6"));
|
||||||
|
|
||||||
|
private GuidedMethodShapes() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rôles de la méthode, dans l'ordre ; liste vide si la méthode est absente ou inconnue. */
|
||||||
|
static List<String> rolesOf(String method) {
|
||||||
|
return method == null ? List.of() : ROLES.getOrDefault(method, List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,9 +11,14 @@ import java.util.List;
|
|||||||
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
|
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
|
||||||
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
|
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
|
||||||
*
|
*
|
||||||
* <p>Placement : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le chapitre
|
* <p>Placement en chapitre : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le
|
||||||
* est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la suite).
|
* chapitre est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la
|
||||||
* Exactement l'un des deux.</p>
|
* suite). Exactement l'un des deux.</p>
|
||||||
|
*
|
||||||
|
* <p>Placement en quête ({@code asQuest}) : l'aventure devient une quête, rangée dans l'arc
|
||||||
|
* de quêtes {@code arcId} (arc HUB), ou libre si {@code arcId} est absent. Le texte du
|
||||||
|
* chapitre va sur la quête ; ses scènes vont dans le chapitre-conteneur de la quête, qui
|
||||||
|
* garde la méthode.</p>
|
||||||
*
|
*
|
||||||
* @param arcId arc existant où ajouter le chapitre, ou {@code null}
|
* @param arcId arc existant où ajouter le chapitre, ou {@code null}
|
||||||
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
||||||
@@ -24,6 +29,10 @@ import java.util.List;
|
|||||||
* @param links liens explicites entre scènes (indices dans {@code scenes}), ou {@code null} :
|
* @param links liens explicites entre scènes (indices dans {@code scenes}), ou {@code null} :
|
||||||
* une enquête en nœuds relie ses pistes en réseau, pas en chaîne
|
* une enquête en nœuds relie ses pistes en réseau, pas en chaîne
|
||||||
* @param clock horloge à créer dans chaque partie de la campagne (plan du méchant), ou {@code null}
|
* @param clock horloge à créer dans chaque partie de la campagne (plan du méchant), ou {@code null}
|
||||||
|
* @param method identifiant de la méthode suivie (« five-room »…), gardé sur le chapitre, ou {@code null}
|
||||||
|
* @param asQuest {@code true} : créer une quête plutôt qu'un chapitre
|
||||||
|
* @param intoChapterId chapitre VIDE de {@code arcId} à remplir au lieu d'en créer un (campagne « à plat » :
|
||||||
|
* son chapitre créé d'office) ; ignoré s'il a déjà des scènes ou n'est pas dans l'arc
|
||||||
*/
|
*/
|
||||||
public record GuidedSkeleton(
|
public record GuidedSkeleton(
|
||||||
String arcId,
|
String arcId,
|
||||||
@@ -33,13 +42,29 @@ public record GuidedSkeleton(
|
|||||||
boolean linkSequentially,
|
boolean linkSequentially,
|
||||||
String linkLabel,
|
String linkLabel,
|
||||||
List<LinkSpec> links,
|
List<LinkSpec> links,
|
||||||
ClockSpec clock
|
ClockSpec clock,
|
||||||
|
String method,
|
||||||
|
Boolean asQuest,
|
||||||
|
String intoChapterId
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
/** Squelette rangé dans un nouveau chapitre (ni quête, ni chapitre vide à remplir). */
|
||||||
|
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||||
|
boolean linkSequentially, String linkLabel, List<LinkSpec> links, ClockSpec clock,
|
||||||
|
String method) {
|
||||||
|
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, links, clock, method, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Squelette sans méthode nommée (appels antérieurs à la mémorisation de la méthode). */
|
||||||
|
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||||
|
boolean linkSequentially, String linkLabel, List<LinkSpec> links, ClockSpec clock) {
|
||||||
|
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, links, clock, null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
/** Squelette sans liens explicites ni horloge (Donjon en 5 salles). */
|
/** Squelette sans liens explicites ni horloge (Donjon en 5 salles). */
|
||||||
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||||
boolean linkSequentially, String linkLabel) {
|
boolean linkSequentially, String linkLabel) {
|
||||||
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, null, null);
|
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, null, null, null, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param gmNotes notes réservées au MJ (vérité cachée d'une enquête, plan complet du méchant) */
|
/** @param gmNotes notes réservées au MJ (vérité cachée d'une enquête, plan complet du méchant) */
|
||||||
@@ -71,19 +96,30 @@ public record GuidedSkeleton(
|
|||||||
public record ClockSpec(String name, String description, int segments) {
|
public record ClockSpec(String name, String description, int segments) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param role rôle de la scène dans la méthode (« room3 », « conclusion »…), ou {@code null} */
|
||||||
public record SceneSpec(
|
public record SceneSpec(
|
||||||
String name, String description, SceneType type, String location,
|
String name, String description, SceneType type, String location,
|
||||||
String choicesConsequences, String gmSecretNotes, String enemies) {
|
String choicesConsequences, String gmSecretNotes, String enemies, String role) {
|
||||||
|
public SceneSpec(String name, String description, SceneType type, String location,
|
||||||
|
String choicesConsequences, String gmSecretNotes, String enemies) {
|
||||||
|
this(name, description, type, location, choicesConsequences, gmSecretNotes, enemies, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ce qui a été créé, pour que le front ouvre directement le chapitre.
|
* Ce qui a été créé, pour que le front ouvre directement le chapitre.
|
||||||
*
|
*
|
||||||
* @param clocks nombre d'horloges créées (une par partie de la campagne)
|
* @param clocks nombre d'horloges créées (une par partie de la campagne)
|
||||||
|
* @param questId quête créée (placement en quête), ou {@code null} ; {@code arcId} et
|
||||||
|
* {@code chapterId} désignent alors son chapitre-conteneur
|
||||||
*/
|
*/
|
||||||
public record Result(String arcId, String chapterId, List<String> sceneIds, int clocks) {
|
public record Result(String arcId, String chapterId, List<String> sceneIds, int clocks, String questId) {
|
||||||
|
public Result(String arcId, String chapterId, List<String> sceneIds, int clocks) {
|
||||||
|
this(arcId, chapterId, sceneIds, clocks, null);
|
||||||
|
}
|
||||||
|
|
||||||
public Result(String arcId, String chapterId, List<String> sceneIds) {
|
public Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||||
this(arcId, chapterId, sceneIds, 0);
|
this(arcId, chapterId, sceneIds, 0, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+108
-8
@@ -2,6 +2,10 @@ package com.loremind.application.campaigncontext;
|
|||||||
|
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||||
|
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||||
|
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
@@ -26,7 +30,10 @@ import java.util.Objects;
|
|||||||
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
|
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
|
||||||
*
|
*
|
||||||
* <p>Ne fait qu'ajouter : rien d'existant n'est modifié, à part l'ordre naturel (le nouvel
|
* <p>Ne fait qu'ajouter : rien d'existant n'est modifié, à part l'ordre naturel (le nouvel
|
||||||
* arc et le nouveau chapitre se placent à la suite). Transactionnel : tout ou rien.</p>
|
* arc et le nouveau chapitre se placent à la suite). Seule exception : le chapitre VIDE
|
||||||
|
* d'une campagne « à plat », créé d'office, peut être rempli au lieu d'être doublé.
|
||||||
|
* L'aventure peut aussi devenir une quête (arc de quêtes ou quête libre).
|
||||||
|
* Transactionnel : tout ou rien.</p>
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
public class GuidedSkeletonService {
|
public class GuidedSkeletonService {
|
||||||
@@ -39,6 +46,8 @@ public class GuidedSkeletonService {
|
|||||||
private final SceneService sceneService;
|
private final SceneService sceneService;
|
||||||
private final PlaythroughRepository playthroughRepository;
|
private final PlaythroughRepository playthroughRepository;
|
||||||
private final ClockService clockService;
|
private final ClockService clockService;
|
||||||
|
private final QuestService questService;
|
||||||
|
private final QuestRepository questRepository;
|
||||||
|
|
||||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
@@ -47,7 +56,9 @@ public class GuidedSkeletonService {
|
|||||||
ChapterService chapterService,
|
ChapterService chapterService,
|
||||||
SceneService sceneService,
|
SceneService sceneService,
|
||||||
PlaythroughRepository playthroughRepository,
|
PlaythroughRepository playthroughRepository,
|
||||||
ClockService clockService) {
|
ClockService clockService,
|
||||||
|
QuestService questService,
|
||||||
|
QuestRepository questRepository) {
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
@@ -56,17 +67,26 @@ public class GuidedSkeletonService {
|
|||||||
this.sceneService = sceneService;
|
this.sceneService = sceneService;
|
||||||
this.playthroughRepository = playthroughRepository;
|
this.playthroughRepository = playthroughRepository;
|
||||||
this.clockService = clockService;
|
this.clockService = clockService;
|
||||||
|
this.questService = questService;
|
||||||
|
this.questRepository = questRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Où l'aventure a été rangée : son chapitre (ou conteneur de quête) et, le cas échéant, la quête. */
|
||||||
|
private record Placement(Chapter chapter, String questId) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
|
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
|
||||||
* arc d'une autre campagne ou non linéaire)
|
* arc d'une autre campagne ou du mauvais type)
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||||
validate(skeleton);
|
validate(skeleton);
|
||||||
String arcId = resolveArc(campaignId, skeleton);
|
String method = GuidedKeys.normalize(skeleton.method());
|
||||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
Placement placement = isQuest(skeleton)
|
||||||
|
? placeInQuest(campaignId, skeleton, method)
|
||||||
|
: placeInChapter(campaignId, skeleton, method);
|
||||||
|
Chapter chapter = placement.chapter();
|
||||||
|
|
||||||
// Une scène sans nom est ignorée ; byIndex garde la position d'origine pour les liens.
|
// Une scène sans nom est ignorée ; byIndex garde la position d'origine pour les liens.
|
||||||
List<Scene> scenes = new ArrayList<>();
|
List<Scene> scenes = new ArrayList<>();
|
||||||
@@ -85,6 +105,7 @@ public class GuidedSkeletonService {
|
|||||||
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
||||||
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
||||||
.enemies(blankToNull(spec.enemies()))
|
.enemies(blankToNull(spec.enemies()))
|
||||||
|
.guidedRole(chapter.getGuidedMethod() == null ? null : GuidedKeys.normalize(spec.role()))
|
||||||
.chapterId(chapter.getId())
|
.chapterId(chapter.getId())
|
||||||
.order(order++)
|
.order(order++)
|
||||||
.build());
|
.build());
|
||||||
@@ -100,7 +121,80 @@ public class GuidedSkeletonService {
|
|||||||
}
|
}
|
||||||
int clocks = createClocks(campaignId, skeleton.clock());
|
int clocks = createClocks(campaignId, skeleton.clock());
|
||||||
|
|
||||||
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList(), clocks);
|
return new GuidedSkeleton.Result(chapter.getArcId(), chapter.getId(),
|
||||||
|
scenes.stream().map(Scene::getId).toList(), clocks, placement.questId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isQuest(GuidedSkeleton skeleton) {
|
||||||
|
return Boolean.TRUE.equals(skeleton.asQuest());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aventure rangée dans un chapitre : le chapitre vide désigné s'il est utilisable, sinon un nouveau. */
|
||||||
|
private Placement placeInChapter(String campaignId, GuidedSkeleton skeleton, String method) {
|
||||||
|
String arcId = resolveArc(campaignId, skeleton);
|
||||||
|
Chapter empty = emptyChapterToFill(arcId, skeleton.intoChapterId());
|
||||||
|
Chapter chapter = empty != null
|
||||||
|
? fillChapter(empty, skeleton.chapter(), method)
|
||||||
|
: createChapter(arcId, skeleton.chapter(), method);
|
||||||
|
return new Placement(chapter, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le chapitre désigné, s'il est bien dans l'arc et sans aucune scène ; sinon {@code null}. */
|
||||||
|
private Chapter emptyChapterToFill(String arcId, String chapterId) {
|
||||||
|
if (isBlank(chapterId)) return null;
|
||||||
|
return chapterRepository.findById(chapterId)
|
||||||
|
.filter(c -> arcId.equals(c.getArcId()))
|
||||||
|
.filter(c -> sceneRepository.findByChapterId(c.getId()).isEmpty())
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Chapter fillChapter(Chapter chapter, GuidedSkeleton.ChapterSpec spec, String method) {
|
||||||
|
chapter.setName(spec.name().trim());
|
||||||
|
chapter.setDescription(blankToNull(spec.description()));
|
||||||
|
chapter.setPlayerObjectives(blankToNull(spec.playerObjectives()));
|
||||||
|
chapter.setNarrativeStakes(blankToNull(spec.narrativeStakes()));
|
||||||
|
chapter.setGmNotes(blankToNull(spec.gmNotes()));
|
||||||
|
chapter.setGuidedMethod(method);
|
||||||
|
return chapterRepository.save(chapter);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aventure rangée dans une quête : le texte du chapitre va sur la quête (c'est elle que le
|
||||||
|
* MJ lit), les scènes dans son chapitre-conteneur, qui garde la méthode.
|
||||||
|
*/
|
||||||
|
private Placement placeInQuest(String campaignId, GuidedSkeleton skeleton, String method) {
|
||||||
|
String hubArcId = isBlank(skeleton.arcId()) ? null : resolveHubArc(campaignId, skeleton.arcId());
|
||||||
|
GuidedSkeleton.ChapterSpec spec = skeleton.chapter();
|
||||||
|
int order = questRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.mapToInt(Quest::getOrder).max().orElse(0) + 1;
|
||||||
|
Quest quest = questService.createQuest(Quest.builder()
|
||||||
|
.campaignId(campaignId)
|
||||||
|
.arcId(hubArcId)
|
||||||
|
.name(spec.name().trim())
|
||||||
|
.description(blankToNull(spec.description()))
|
||||||
|
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||||
|
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||||
|
.gmNotes(blankToNull(spec.gmNotes()))
|
||||||
|
.order(order)
|
||||||
|
.build());
|
||||||
|
Chapter container = quest.getNodes().stream()
|
||||||
|
.filter(n -> n.nodeType() == NodeType.CHAPTER)
|
||||||
|
.map(QuestNodeRef::nodeId)
|
||||||
|
.findFirst()
|
||||||
|
.flatMap(chapterRepository::findById)
|
||||||
|
.orElseThrow(() -> new IllegalStateException("La quête créée n'a pas de conteneur de scènes."));
|
||||||
|
container.setGuidedMethod(method);
|
||||||
|
return new Placement(chapterRepository.save(container), quest.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveHubArc(String campaignId, String arcId) {
|
||||||
|
Arc arc = arcRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.filter(a -> arcId.equals(a.getId())).findFirst()
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Arc introuvable dans cette campagne."));
|
||||||
|
if (arc.getType() != ArcType.HUB) {
|
||||||
|
throw new IllegalArgumentException("Une quête guidée se range dans un arc de quêtes.");
|
||||||
|
}
|
||||||
|
return arc.getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -150,7 +244,12 @@ public class GuidedSkeletonService {
|
|||||||
}
|
}
|
||||||
boolean hasArc = !isBlank(skeleton.arcId());
|
boolean hasArc = !isBlank(skeleton.arcId());
|
||||||
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
||||||
if (hasArc == hasNewArc) {
|
if (isQuest(skeleton)) {
|
||||||
|
// Quête : arc de quêtes facultatif (absent = quête libre), jamais de nouvel arc.
|
||||||
|
if (hasNewArc) {
|
||||||
|
throw new IllegalArgumentException("Une quête guidée ne crée pas d'arc.");
|
||||||
|
}
|
||||||
|
} else if (hasArc == hasNewArc) {
|
||||||
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
|
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
|
||||||
}
|
}
|
||||||
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
||||||
@@ -183,7 +282,7 @@ public class GuidedSkeletonService {
|
|||||||
.build()).getId();
|
.build()).getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec) {
|
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec, String method) {
|
||||||
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
||||||
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
||||||
return chapterService.createChapter(Chapter.builder()
|
return chapterService.createChapter(Chapter.builder()
|
||||||
@@ -192,6 +291,7 @@ public class GuidedSkeletonService {
|
|||||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||||
.gmNotes(blankToNull(spec.gmNotes()))
|
.gmNotes(blankToNull(spec.gmNotes()))
|
||||||
|
.guidedMethod(method)
|
||||||
.arcId(arcId)
|
.arcId(arcId)
|
||||||
.order(nextOrder)
|
.order(nextOrder)
|
||||||
.build());
|
.build());
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Arc « implicite » : le seul arc visible de la campagne, linéaire, vide de texte et encore à
|
||||||
|
* son nom d'office. L'auteur ne l'a pas créé (il vient d'une scène ajoutée rapidement ou
|
||||||
|
* d'une méthode guidée) : l'interface ne le lui montre pas comme un arc, et la relecture ne
|
||||||
|
* doit donc ni lui réclamer des enjeux, ni le citer par son nom.
|
||||||
|
*
|
||||||
|
* <p>Miroir de {@code implicitArc} côté front ({@code web/src/app/campaigns/flat-structure.ts}) ;
|
||||||
|
* le test front {@code flat-structure.spec.ts} vérifie que les deux côtés connaissent les
|
||||||
|
* mêmes noms d'office.</p>
|
||||||
|
*/
|
||||||
|
public final class ImplicitArc {
|
||||||
|
|
||||||
|
/** Noms donnés à l'arc créé d'office, dans chaque langue de l'interface. */
|
||||||
|
public static final List<String> DEFAULT_NAMES = List.of("Arc principal", "Main arc");
|
||||||
|
|
||||||
|
private ImplicitArc() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean is(Arc arc, List<Arc> campaignArcs) {
|
||||||
|
long visible = campaignArcs.stream().filter(a -> a.getType() != ArcType.SYSTEM).count();
|
||||||
|
return visible == 1
|
||||||
|
&& arc.getType() != ArcType.SYSTEM && arc.getType() != ArcType.HUB
|
||||||
|
&& isDefaultName(arc.getName())
|
||||||
|
&& isBare(arc);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** L'arc porte-t-il encore le nom qu'on lui a donné d'office ? (le livret PDF applique la même règle) */
|
||||||
|
public static boolean isDefaultName(String name) {
|
||||||
|
return name != null && DEFAULT_NAMES.contains(name.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aucun contenu d'écriture dans l'arc (son nom ne compte pas). */
|
||||||
|
private static boolean isBare(Arc arc) {
|
||||||
|
return allBlank(arc.getDescription(), arc.getThemes(), arc.getStakes(), arc.getRewards(),
|
||||||
|
arc.getResolution(), arc.getGmNotes(), arc.getHiddenTruth(), arc.getHooks())
|
||||||
|
&& (arc.getIllustrationImageIds() == null || arc.getIllustrationImageIds().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean allBlank(String... values) {
|
||||||
|
for (String v : values) {
|
||||||
|
if (v != null && !v.isBlank()) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.structure.Scene;
|
|||||||
import com.loremind.domain.campaigncontext.generation.SceneDraft;
|
import com.loremind.domain.campaigncontext.generation.SceneDraft;
|
||||||
import com.loremind.domain.shared.ReorderSupport;
|
import com.loremind.domain.shared.ReorderSupport;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import org.springframework.beans.BeanUtils;
|
import org.springframework.beans.BeanUtils;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -80,7 +81,8 @@ public class SceneService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Scene scene = existingScene.get();
|
Scene scene = existingScene.get();
|
||||||
BeanUtils.copyProperties(updated, scene, "id");
|
// guidedRole : jamais porté par le formulaire d'édition, il ne doit pas être effacé.
|
||||||
|
BeanUtils.copyProperties(updated, scene, "id", "guidedRole");
|
||||||
|
|
||||||
// Validation métier : le graphe narratif doit rester cohérent.
|
// Validation métier : le graphe narratif doit rester cohérent.
|
||||||
validateBranches(scene);
|
validateBranches(scene);
|
||||||
@@ -88,6 +90,53 @@ public class SceneService {
|
|||||||
return sceneRepository.save(scene);
|
return sceneRepository.save(scene);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crée, à la fin du chapitre, la scène qui tient un rôle de sa méthode guidée (rôle
|
||||||
|
* resté sans scène, ou méthode appliquée après coup à un chapitre existant).
|
||||||
|
* Transactionnel.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException nom vide ou identifiant de rôle invalide
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Scene createGuidedScene(String chapterId, String name, SceneType type, String role) {
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("La scène doit avoir un nom.");
|
||||||
|
}
|
||||||
|
int order = sceneRepository.findByChapterId(chapterId).stream()
|
||||||
|
.mapToInt(Scene::getOrder).max().orElse(-1) + 1;
|
||||||
|
Scene created = sceneRepository.save(Scene.builder()
|
||||||
|
.name(name.trim())
|
||||||
|
.type(type != null ? type : SceneType.GENERIC)
|
||||||
|
.chapterId(chapterId)
|
||||||
|
.order(order)
|
||||||
|
.build());
|
||||||
|
return setGuidedRole(created.getId(), role);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Donne à la scène un rôle dans la méthode guidée de son chapitre, ou le retire
|
||||||
|
* ({@code null} / vide). Un rôle est tenu par une seule scène : la scène du même chapitre
|
||||||
|
* qui le tenait le perd. Transactionnel.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException scène inconnue ou identifiant de rôle invalide
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Scene setGuidedRole(String id, String role) {
|
||||||
|
Scene scene = sceneRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Scene non trouvée avec l'ID: " + id));
|
||||||
|
String next = GuidedKeys.normalize(role);
|
||||||
|
if (next != null) {
|
||||||
|
for (Scene other : sceneRepository.findByChapterId(scene.getChapterId())) {
|
||||||
|
if (!id.equals(other.getId()) && next.equals(other.getGuidedRole())) {
|
||||||
|
other.setGuidedRole(null);
|
||||||
|
sceneRepository.save(other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scene.setGuidedRole(next);
|
||||||
|
return sceneRepository.save(scene);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Patch CIBLÉ champ-par-champ d'une scène (Pilier A — co-création). Applique
|
* Patch CIBLÉ champ-par-champ d'une scène (Pilier A — co-création). Applique
|
||||||
* UNIQUEMENT les {@link FieldProposal} reçus (valeurs acceptées par l'utilisateur) sur
|
* UNIQUEMENT les {@link FieldProposal} reçus (valeurs acceptées par l'utilisateur) sur
|
||||||
@@ -200,6 +249,7 @@ public class SceneService {
|
|||||||
if (chapterId != null && !chapterId.isBlank() && !chapterId.equals(scene.getChapterId())) {
|
if (chapterId != null && !chapterId.isBlank() && !chapterId.equals(scene.getChapterId())) {
|
||||||
scene.setChapterId(chapterId);
|
scene.setChapterId(chapterId);
|
||||||
scene.setBranches(new ArrayList<>());
|
scene.setBranches(new ArrayList<>());
|
||||||
|
scene.setGuidedRole(null); // le rôle appartenait à la méthode de l'ancien chapitre
|
||||||
}
|
}
|
||||||
scene.setOrder(i);
|
scene.setOrder(i);
|
||||||
},
|
},
|
||||||
|
|||||||
+140
-15
@@ -9,7 +9,9 @@ import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
|||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||||
|
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
@@ -64,6 +66,8 @@ public class WritingReviewService {
|
|||||||
static final int DUNGEON_MIN_ROOMS = 4;
|
static final int DUNGEON_MIN_ROOMS = 4;
|
||||||
/** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */
|
/** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */
|
||||||
static final int PROACTIVE_MIN_SCENES = 3;
|
static final int PROACTIVE_MIN_SCENES = 3;
|
||||||
|
/** WRITE-021 : nombre minimal d'étapes écrites pour juger un plan du méchant. */
|
||||||
|
static final int PLAN_MIN_STEPS = 3;
|
||||||
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
||||||
static final int MONOTONOUS_RUN = 3;
|
static final int MONOTONOUS_RUN = 3;
|
||||||
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
||||||
@@ -73,6 +77,18 @@ public class WritingReviewService {
|
|||||||
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
|
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
|
||||||
static final double UNTYPED_RATIO = 0.7;
|
static final double UNTYPED_RATIO = 0.7;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paramètre ajouté aux remarques d'un chapitre qui suit une méthode guidée : le front
|
||||||
|
* ne lui conseille pas d'en suivre une autre.
|
||||||
|
*/
|
||||||
|
static final String PARAM_GUIDED_METHOD = "guidedMethod";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paramètre ajouté quand l'arc d'une remarque est l'arc créé d'office : le front choisit
|
||||||
|
* alors la formulation qui ne nomme pas l'arc ({@code observationNoArc}).
|
||||||
|
*/
|
||||||
|
static final String PARAM_IMPLICIT_ARC = "implicitArc";
|
||||||
|
|
||||||
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
|
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
|
||||||
static final String KIND_COMBAT = "COMBAT";
|
static final String KIND_COMBAT = "COMBAT";
|
||||||
|
|
||||||
@@ -115,8 +131,17 @@ public class WritingReviewService {
|
|||||||
List<WritingRemark> campaignRemarks = new ArrayList<>();
|
List<WritingRemark> campaignRemarks = new ArrayList<>();
|
||||||
List<WritingRemark> treeRemarks = new ArrayList<>();
|
List<WritingRemark> treeRemarks = new ArrayList<>();
|
||||||
|
|
||||||
Set<String> arcsWithQuests = questRepository.findByCampaignId(campaignId).stream()
|
List<Quest> quests = questRepository.findByCampaignId(campaignId);
|
||||||
|
Set<String> arcsWithQuests = quests.stream()
|
||||||
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||||
|
// Le texte d'une quête vit sur la quête, pas sur son chapitre-conteneur : ses enjeux
|
||||||
|
// valent pour lui (sinon WRITE-005 réclamerait des enjeux déjà écrits).
|
||||||
|
Set<String> chaptersWithQuestStakes = quests.stream()
|
||||||
|
.filter(q -> !isBlank(q.getNarrativeStakes()) && q.getNodes() != null)
|
||||||
|
.flatMap(q -> q.getNodes().stream())
|
||||||
|
.filter(n -> n.nodeType() == NodeType.CHAPTER)
|
||||||
|
.map(QuestNodeRef::nodeId)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||||
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||||
@@ -127,6 +152,8 @@ public class WritingReviewService {
|
|||||||
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
||||||
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||||
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
||||||
|
// Arc créé d'office, que l'auteur n'a jamais vu : on ne lui réclame rien, on ne le cite pas.
|
||||||
|
boolean implicitArc = ImplicitArc.is(arc, arcs);
|
||||||
|
|
||||||
// WRITE-017 — une seule accroche : les personnages n'ont qu'une raison de s'en mêler.
|
// WRITE-017 — une seule accroche : les personnages n'ont qu'une raison de s'en mêler.
|
||||||
if (visibleArc && countLines(arc.getHooks()) == 1) {
|
if (visibleArc && countLines(arc.getHooks()) == 1) {
|
||||||
@@ -134,7 +161,7 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
||||||
if (visibleArc && isBlank(arc.getStakes())
|
if (visibleArc && !implicitArc && isBlank(arc.getStakes())
|
||||||
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
||||||
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||||
}
|
}
|
||||||
@@ -147,7 +174,8 @@ public class WritingReviewService {
|
|||||||
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
|
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
|
||||||
|
|
||||||
if (visibleArc) {
|
if (visibleArc) {
|
||||||
reviewChapter(arc, chapter, scenes, treeRemarks);
|
reviewChapter(arc, chapter, scenes, chaptersWithQuestStakes.contains(chapter.getId()), treeRemarks);
|
||||||
|
reviewGuidedMethod(arc, chapter, scenes, treeRemarks);
|
||||||
}
|
}
|
||||||
for (Scene scene : scenes) {
|
for (Scene scene : scenes) {
|
||||||
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
||||||
@@ -159,7 +187,7 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
|
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
|
||||||
checkSingleEnding(arc, lastChapterScenes, treeRemarks);
|
checkSingleEnding(arc, implicitArc, lastChapterScenes, treeRemarks);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +209,8 @@ public class WritingReviewService {
|
|||||||
|
|
||||||
// --- Niveau chapitre ---------------------------------------------------------------
|
// --- Niveau chapitre ---------------------------------------------------------------
|
||||||
|
|
||||||
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, boolean questHasStakes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
|
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
|
||||||
|
|
||||||
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
|
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
|
||||||
@@ -200,7 +229,7 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
|
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
|
||||||
if (isBlank(chapter.getNarrativeStakes())) {
|
if (isBlank(chapter.getNarrativeStakes()) && !questHasStakes) {
|
||||||
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,6 +242,81 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Méthode guidée du chapitre ----------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Règles propres à la méthode guidée que suit le chapitre (Donjon en 5 salles, Enquête
|
||||||
|
* en nœuds, Plan du méchant) : la méthode promet une forme, la relecture vérifie qu'elle
|
||||||
|
* tient encore après les retouches du MJ. Chapitre sans méthode, ou méthode inconnue du
|
||||||
|
* Core : rien.
|
||||||
|
*/
|
||||||
|
private void reviewGuidedMethod(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||||
|
List<String> roles = GuidedMethodShapes.rolesOf(chapter.getGuidedMethod());
|
||||||
|
if (roles.isEmpty() || scenes.isEmpty()) return;
|
||||||
|
Map<String, Scene> byRole = new HashMap<>();
|
||||||
|
for (Scene s : scenes) {
|
||||||
|
if (!isBlank(s.getGuidedRole())) byRole.putIfAbsent(s.getGuidedRole(), s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// WRITE-018 — méthode incomplète : des temps de la méthode n'ont plus (ou pas encore) de scène.
|
||||||
|
long missing = roles.stream().filter(r -> !byRole.containsKey(r)).count();
|
||||||
|
if (missing > 0) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-018-METHOD-INCOMPLETE", WritingRemarkCategory.PACING,
|
||||||
|
Map.of("count", String.valueOf(missing), "total", String.valueOf(roles.size()))));
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (chapter.getGuidedMethod()) {
|
||||||
|
case GuidedMethodShapes.FIVE_ROOM -> checkTrialIsCombat(arc, chapter, byRole, out);
|
||||||
|
case GuidedMethodShapes.INVESTIGATION -> checkConclusionClues(arc, chapter, byRole, scenes, out);
|
||||||
|
case GuidedMethodShapes.VILLAIN_PLAN -> checkPlanSigns(arc, chapter, byRole.values(), out);
|
||||||
|
default -> { /* méthode sans règle propre */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WRITE-019 — Donjon en 5 salles : l'épreuve (2e salle) est devenue un combat. */
|
||||||
|
private void checkTrialIsCombat(Arc arc, Chapter chapter, Map<String, Scene> byRole, List<WritingRemark> out) {
|
||||||
|
Scene trial = byRole.get(GuidedMethodShapes.FIVE_ROOM_TRIAL);
|
||||||
|
if (trial != null && isCombat(trial)) {
|
||||||
|
out.add(sceneRemark(arc, chapter, trial, "WRITE-019-TRIAL-IS-COMBAT", WritingRemarkCategory.PACING, Map.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-020 — Enquête en nœuds : la conclusion n'est plus atteinte par trois pistes.
|
||||||
|
* Une conclusion de type révélation est déjà relue par WRITE-003 : on ne le dit pas deux fois.
|
||||||
|
*/
|
||||||
|
private void checkConclusionClues(Arc arc, Chapter chapter, Map<String, Scene> byRole, List<Scene> scenes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
|
Scene conclusion = byRole.get(GuidedMethodShapes.INVESTIGATION_CONCLUSION);
|
||||||
|
if (conclusion == null || isBlank(conclusion.getId()) || typeOf(conclusion) == SceneType.REVELATION) return;
|
||||||
|
int incoming = incomingSources(conclusion, scenes).size();
|
||||||
|
if (incoming < REVELATION_MIN_INCOMING) {
|
||||||
|
out.add(sceneRemark(arc, chapter, conclusion, "WRITE-020-CONCLUSION-FEW-CLUES", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("incoming", String.valueOf(incoming))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-021 — Plan du méchant : la plupart des étapes ne disent pas ce que les joueurs
|
||||||
|
* peuvent en voir. Un plan invisible ne laisse aucune occasion de réagir.
|
||||||
|
*/
|
||||||
|
private void checkPlanSigns(Arc arc, Chapter chapter, java.util.Collection<Scene> steps, List<WritingRemark> out) {
|
||||||
|
if (steps.size() < PLAN_MIN_STEPS) return;
|
||||||
|
long silent = steps.stream().filter(s -> isBlank(s.getChoicesConsequences())).count();
|
||||||
|
if (silent * 2 > steps.size()) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-021-PLAN-WITHOUT-SIGNS", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("count", String.valueOf(silent), "total", String.valueOf(steps.size()))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scènes du chapitre (autres qu'elle-même) qui portent un lien vers {@code scene}. */
|
||||||
|
private static List<Scene> incomingSources(Scene scene, List<Scene> chapterScenes) {
|
||||||
|
return chapterScenes.stream()
|
||||||
|
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||||
|
.filter(s -> s.getBranches().stream().anyMatch(b -> scene.getId().equals(b.targetSceneId())))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
private record MonotonousRun(String kind, int length) {}
|
private record MonotonousRun(String kind, int length) {}
|
||||||
|
|
||||||
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
|
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
|
||||||
@@ -325,7 +429,15 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
checkChokepoint(arc, chapter, scenes, next, out);
|
// Un donjon en 5 salles s'enchaîne par construction : y voir un passage obligé
|
||||||
|
// reviendrait à reprocher au MJ d'avoir suivi la méthode.
|
||||||
|
if (!followsFiveRooms(chapter)) {
|
||||||
|
checkChokepoint(arc, chapter, scenes, next, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean followsFiveRooms(Chapter chapter) {
|
||||||
|
return GuidedMethodShapes.FIVE_ROOM.equals(chapter.getGuidedMethod());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -412,11 +524,11 @@ public class WritingReviewService {
|
|||||||
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||||
List<WritingRemark> out) {
|
List<WritingRemark> out) {
|
||||||
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
||||||
|
// La récompense d'un donjon en 5 salles se mérite au bout du parcours : une seule
|
||||||
|
// salle y mène, et c'est voulu (la règle des 3 indices vaut pour une enquête).
|
||||||
|
if (followsFiveRooms(chapter) && !isBlank(scene.getGuidedRole())) return;
|
||||||
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
||||||
List<Scene> sources = chapterScenes.stream()
|
List<Scene> sources = incomingSources(scene, chapterScenes);
|
||||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
|
||||||
.filter(s -> s.getBranches().stream().anyMatch(b -> scene.getId().equals(b.targetSceneId())))
|
|
||||||
.toList();
|
|
||||||
if (sources.size() < REVELATION_MIN_INCOMING) {
|
if (sources.size() < REVELATION_MIN_INCOMING) {
|
||||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||||
Map.of("incoming", String.valueOf(sources.size()))));
|
Map.of("incoming", String.valueOf(sources.size()))));
|
||||||
@@ -459,12 +571,17 @@ public class WritingReviewService {
|
|||||||
// --- Niveau arc -----------------------------------------------------------------------
|
// --- Niveau arc -----------------------------------------------------------------------
|
||||||
|
|
||||||
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
|
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
|
||||||
private void checkSingleEnding(Arc arc, List<Scene> lastChapterScenes, List<WritingRemark> out) {
|
private void checkSingleEnding(Arc arc, boolean implicitArc, List<Scene> lastChapterScenes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
|
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
|
||||||
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
|
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
|
||||||
|
// Arc créé d'office : le front parle alors de la fin « de la campagne », sans nommer l'arc.
|
||||||
|
Map<String, String> params = implicitArc
|
||||||
|
? Map.of("arc", labelOr(arc.getName(), "Arc"), PARAM_IMPLICIT_ARC, "true")
|
||||||
|
: Map.of("arc", labelOr(arc.getName(), "Arc"));
|
||||||
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
|
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
|
||||||
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
|
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
|
||||||
Map.of("arc", labelOr(arc.getName(), "Arc")), arc.getId(), finale.getChapterId()));
|
params, arc.getId(), finale.getChapterId()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -514,13 +631,21 @@ public class WritingReviewService {
|
|||||||
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
|
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
|
||||||
WritingRemarkCategory category, Map<String, String> params) {
|
WritingRemarkCategory category, Map<String, String> params) {
|
||||||
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
|
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
|
||||||
ruleId, category, params, arc.getId(), chapter.getId());
|
ruleId, category, withMethod(chapter, params), arc.getId(), chapter.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
|
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
|
||||||
WritingRemarkCategory category, Map<String, String> params) {
|
WritingRemarkCategory category, Map<String, String> params) {
|
||||||
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
|
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
|
||||||
ruleId, category, params, arc.getId(), chapter.getId());
|
ruleId, category, withMethod(chapter, params), arc.getId(), chapter.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Les paramètres de la remarque, plus la méthode guidée du chapitre s'il en suit une. */
|
||||||
|
private static Map<String, String> withMethod(Chapter chapter, Map<String, String> params) {
|
||||||
|
if (isBlank(chapter.getGuidedMethod())) return params;
|
||||||
|
Map<String, String> all = new HashMap<>(params);
|
||||||
|
all.put(PARAM_GUIDED_METHOD, chapter.getGuidedMethod());
|
||||||
|
return all;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
|
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
|
||||||
|
|||||||
+1
-1
@@ -61,7 +61,7 @@ public class GameSystemContextBuilder {
|
|||||||
* Découpe le markdown par titres H2. Préserve l'ordre d'apparition (LinkedHashMap).
|
* 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).
|
* Le contenu avant le premier H2 est ignoré (préambule libre).
|
||||||
*/
|
*/
|
||||||
Map<String, String> parseH2Sections(String markdown) {
|
static Map<String, String> parseH2Sections(String markdown) {
|
||||||
Map<String, String> sections = new LinkedHashMap<>();
|
Map<String, String> sections = new LinkedHashMap<>();
|
||||||
if (markdown == null || markdown.isBlank()) return sections;
|
if (markdown == null || markdown.isBlank()) return sections;
|
||||||
|
|
||||||
|
|||||||
+601
@@ -0,0 +1,601 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.Enemy;
|
||||||
|
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.EnemyRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Room;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrill;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RuleTrainingCoach;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RuleTrainingCoach.DrillCandidate;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RuleTrainingCoach.SceneBrief;
|
||||||
|
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.EnumMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
import java.util.function.IntUnaryOperator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entraînement aux règles : le MJ tranche des situations tirées de ses scènes, puis lit un
|
||||||
|
* corrigé qui cite les règles de son système.
|
||||||
|
* <p>
|
||||||
|
* Une série se prépare en UN appel à l'IA (situations et corrigés ensemble) ; la comparaison
|
||||||
|
* d'une réponse écrite est un second appel, facultatif. Rien n'est enregistré.
|
||||||
|
* <p>
|
||||||
|
* Garde-fou central : une situation n'est gardée que si l'extrait cité se retrouve mot pour
|
||||||
|
* mot (aux espaces, à la casse et à la mise en forme près) dans une section de règles
|
||||||
|
* envoyée. L'extrait affiché vient donc toujours des règles du MJ ; seule la lecture qu'en
|
||||||
|
* fait l'IA reste à relire.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class RuleTrainingService {
|
||||||
|
|
||||||
|
/** Taille totale des règles envoyées (~6 000 jetons), comme pour la proposition de fiche. */
|
||||||
|
static final int MAX_RULES_CHARS = 24_000;
|
||||||
|
/** Part maximale d'une section : au-delà, elle est parcourue par morceaux d'une série à l'autre. */
|
||||||
|
static final int MAX_SECTION_CHARS = 9_000;
|
||||||
|
/** En dessous, un reste de budget ne vaut pas un extrait tronqué de plus. */
|
||||||
|
static final int MIN_WINDOW_CHARS = 400;
|
||||||
|
|
||||||
|
static final int DRILL_COUNT = 5;
|
||||||
|
static final int MAX_DRILLS = 8;
|
||||||
|
static final int MAX_SCENES = 8;
|
||||||
|
static final int MAX_SCENE_CHARS = 1_500;
|
||||||
|
static final int MAX_SCENE_FIELD_CHARS = 400;
|
||||||
|
static final int MAX_AVOIDED = 10;
|
||||||
|
static final int MAX_ANSWER_CHARS = 2_000;
|
||||||
|
|
||||||
|
/** Un extrait plus court ne prouve rien (« un jet », « 1d6 »). */
|
||||||
|
static final int MIN_EXCERPT_CHARS = 25;
|
||||||
|
/** Un extrait plus long n'est plus une citation, c'est la section recopiée. */
|
||||||
|
static final int MAX_EXCERPT_CHARS = 1_500;
|
||||||
|
/** Morceau minimal d'un extrait coupé par des points de suspension. */
|
||||||
|
static final int MIN_FRAGMENT_CHARS = 12;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections conseillées selon le type de scène (comparaison par {@code contains} sur le
|
||||||
|
* titre en minuscules, comme {@link com.loremind.domain.gamesystemcontext.GenerationIntent}).
|
||||||
|
*/
|
||||||
|
private static final Map<SceneType, Set<String>> FOCUS = new EnumMap<>(SceneType.class);
|
||||||
|
|
||||||
|
static {
|
||||||
|
FOCUS.put(SceneType.ENCOUNTER, Set.of("combat", "monstre", "monster", "créature", "creature",
|
||||||
|
"ennemi", "enemy", "adversaire", "bestiaire", "bestiary", "état", "etat", "condition",
|
||||||
|
"blessure", "dégât", "degat", "damage", "initiative"));
|
||||||
|
FOCUS.put(SceneType.LOCATION, Set.of("exploration", "déplacement", "deplacement", "movement",
|
||||||
|
"voyage", "travel", "piège", "piege", "trap", "perception", "environnement",
|
||||||
|
"environment", "danger", "hazard", "lumière", "light"));
|
||||||
|
FOCUS.put(SceneType.NPC, Set.of("social", "interaction", "pnj", "npc", "compétence",
|
||||||
|
"competence", "skill", "réaction", "reaction", "influence"));
|
||||||
|
FOCUS.put(SceneType.EVENT, Set.of("compétence", "competence", "skill", "test", "jet",
|
||||||
|
"résolution", "resolution", "action"));
|
||||||
|
FOCUS.put(SceneType.REVELATION, Set.of("enquête", "enquete", "investigation", "compétence",
|
||||||
|
"competence", "skill", "perception", "indice", "clue", "connaissance", "knowledge"));
|
||||||
|
FOCUS.put(SceneType.GENERIC, Set.of("résolution", "resolution", "test", "jet", "compétence",
|
||||||
|
"competence", "skill", "action", "base", "core", "système", "systeme", "mécanique",
|
||||||
|
"mecanique", "mechanic"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum Status { READY, NO_SYSTEM, NO_RULES }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Section de règles proposée au choix. {@code suggestedFor} : types de scène qui la
|
||||||
|
* précochent. {@code otherLanguage} : rédigée dans l'autre langue que l'interface, donc
|
||||||
|
* masquée tant que le MJ ne demande pas à la voir.
|
||||||
|
*/
|
||||||
|
public record SectionInfo(String title, int chars, List<SceneType> suggestedFor, boolean otherLanguage) {}
|
||||||
|
|
||||||
|
/** Sections des règles ({@code titre → texte}) et titres de celles rédigées dans l'autre langue. */
|
||||||
|
record Rules(Map<String, String> sections, Set<String> otherLanguage) {}
|
||||||
|
|
||||||
|
public record SceneInfo(String id, String name, SceneType type) {}
|
||||||
|
|
||||||
|
/** Aventure (ou espace de scènes d'une quête annexe) et ses scènes, dans l'ordre de la campagne. */
|
||||||
|
public record AdventureInfo(String id, String arcId, String name, boolean sideQuest, List<SceneInfo> scenes) {}
|
||||||
|
|
||||||
|
/** Ce que l'écran propose avant une série. */
|
||||||
|
public record Options(Status status, String gameSystemId, String gameSystemName,
|
||||||
|
List<SectionInfo> sections, List<AdventureInfo> adventures) {}
|
||||||
|
|
||||||
|
/** Une série. {@code dropped} : situations écartées parce que leur extrait ne figurait pas dans les règles. */
|
||||||
|
public record Series(String gameSystemName, List<RuleDrill> drills, List<String> sections, int dropped) {}
|
||||||
|
|
||||||
|
private final CampaignRepository campaignRepository;
|
||||||
|
private final ArcRepository arcRepository;
|
||||||
|
private final ChapterRepository chapterRepository;
|
||||||
|
private final SceneRepository sceneRepository;
|
||||||
|
private final EnemyRepository enemyRepository;
|
||||||
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
private final CurrentLanguage currentLanguage;
|
||||||
|
private final RuleTrainingCoach coach;
|
||||||
|
/** Choisit le morceau d'une section trop longue (borne exclusive → rang). */
|
||||||
|
private final IntUnaryOperator windowPicker;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public RuleTrainingService(CampaignRepository campaignRepository, ArcRepository arcRepository,
|
||||||
|
ChapterRepository chapterRepository, SceneRepository sceneRepository,
|
||||||
|
EnemyRepository enemyRepository, GameSystemRepository gameSystemRepository,
|
||||||
|
CurrentLanguage currentLanguage, RuleTrainingCoach coach) {
|
||||||
|
this(campaignRepository, arcRepository, chapterRepository, sceneRepository, enemyRepository,
|
||||||
|
gameSystemRepository, currentLanguage, coach,
|
||||||
|
bound -> ThreadLocalRandom.current().nextInt(bound));
|
||||||
|
}
|
||||||
|
|
||||||
|
RuleTrainingService(CampaignRepository campaignRepository, ArcRepository arcRepository,
|
||||||
|
ChapterRepository chapterRepository, SceneRepository sceneRepository,
|
||||||
|
EnemyRepository enemyRepository, GameSystemRepository gameSystemRepository,
|
||||||
|
CurrentLanguage currentLanguage, RuleTrainingCoach coach,
|
||||||
|
IntUnaryOperator windowPicker) {
|
||||||
|
this.campaignRepository = campaignRepository;
|
||||||
|
this.arcRepository = arcRepository;
|
||||||
|
this.chapterRepository = chapterRepository;
|
||||||
|
this.sceneRepository = sceneRepository;
|
||||||
|
this.enemyRepository = enemyRepository;
|
||||||
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
this.currentLanguage = currentLanguage;
|
||||||
|
this.coach = coach;
|
||||||
|
this.windowPicker = windowPicker;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Ce que l'écran propose ---------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException si la campagne est inconnue
|
||||||
|
*/
|
||||||
|
public Options options(String campaignId) {
|
||||||
|
Campaign campaign = campaign(campaignId);
|
||||||
|
List<AdventureInfo> adventures = adventures(campaignId);
|
||||||
|
Optional<GameSystem> system = system(campaign);
|
||||||
|
if (system.isEmpty()) {
|
||||||
|
return new Options(Status.NO_SYSTEM, null, "", List.of(), adventures);
|
||||||
|
}
|
||||||
|
GameSystem gs = system.get();
|
||||||
|
Rules rules = rules(gs);
|
||||||
|
List<SectionInfo> sections = rules.sections().entrySet().stream()
|
||||||
|
.map(e -> new SectionInfo(e.getKey(), e.getValue().length(), suggestedFor(e.getKey()),
|
||||||
|
rules.otherLanguage().contains(e.getKey())))
|
||||||
|
.toList();
|
||||||
|
return new Options(sections.isEmpty() ? Status.NO_RULES : Status.READY,
|
||||||
|
gs.getId(), nz(gs.getName()), sections, adventures);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<AdventureInfo> adventures(String campaignId) {
|
||||||
|
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||||
|
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||||
|
List<AdventureInfo> out = new ArrayList<>();
|
||||||
|
for (Arc arc : arcs) {
|
||||||
|
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
||||||
|
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||||
|
for (Chapter chapter : chapters) {
|
||||||
|
List<Scene> scenes = new ArrayList<>(sceneRepository.findByChapterId(chapter.getId()));
|
||||||
|
if (scenes.isEmpty()) continue;
|
||||||
|
scenes.sort(Comparator.comparingInt(Scene::getOrder));
|
||||||
|
out.add(new AdventureInfo(chapter.getId(), arc.getId(), nz(chapter.getName()),
|
||||||
|
arc.getType() == ArcType.SYSTEM,
|
||||||
|
scenes.stream().map(s -> new SceneInfo(s.getId(), nz(s.getName()), typeOf(s))).toList()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<SceneType> suggestedFor(String title) {
|
||||||
|
String lower = title.toLowerCase(Locale.ROOT);
|
||||||
|
return FOCUS.entrySet().stream()
|
||||||
|
.filter(e -> e.getValue().stream().anyMatch(lower::contains))
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Une série ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prépare une série.
|
||||||
|
*
|
||||||
|
* @param sceneIds scènes qui servent de décor (aucune : situations générales)
|
||||||
|
* @param sectionTitles sections à travailler, par ordre de priorité (aucune : sections
|
||||||
|
* conseillées pour ces scènes, à défaut toutes, parmi celles rédigées
|
||||||
|
* dans la langue de l'interface)
|
||||||
|
* @param avoid situations déjà posées, à ne pas reposer
|
||||||
|
* @throws IllegalArgumentException si la campagne est inconnue, sans système ou sans règles
|
||||||
|
*/
|
||||||
|
public Series prepare(String campaignId, List<String> sceneIds, List<String> sectionTitles, List<String> avoid) {
|
||||||
|
Campaign campaign = campaign(campaignId);
|
||||||
|
GameSystem gs = system(campaign)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Cette campagne n'a pas de système de jeu."));
|
||||||
|
Rules rules = rules(gs);
|
||||||
|
Map<String, String> all = rules.sections();
|
||||||
|
if (all.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Ce système de jeu n'a pas encore de règles.");
|
||||||
|
}
|
||||||
|
List<Scene> scenes = scenesOf(campaignId, sceneIds);
|
||||||
|
Map<String, String> sent = selectSections(all,
|
||||||
|
wantedTitles(all, sectionTitles, scenes, rules.otherLanguage()), windowPicker);
|
||||||
|
List<SceneBrief> briefs = scenes.stream().map(this::brief).toList();
|
||||||
|
|
||||||
|
List<DrillCandidate> candidates = coach.prepare(nz(gs.getName()), sent, briefs, DRILL_COUNT, clean(avoid));
|
||||||
|
List<RuleDrill> drills = inLanguage(validate(candidates, sent, scenes), rules.otherLanguage(),
|
||||||
|
currentLanguage.get());
|
||||||
|
int received = candidates == null ? 0 : candidates.size();
|
||||||
|
return new Series(nz(gs.getName()), drills, List.copyOf(sent.keySet()), Math.max(0, received - drills.size()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Titres demandés qui existent ; à défaut ceux conseillés pour ces scènes ; à défaut tous.
|
||||||
|
* Une section rédigée dans l'autre langue n'est prise que si elle est demandée.
|
||||||
|
*/
|
||||||
|
static List<String> wantedTitles(Map<String, String> all, List<String> requested, List<Scene> scenes,
|
||||||
|
Set<String> otherLanguage) {
|
||||||
|
List<String> wanted = new ArrayList<>();
|
||||||
|
for (String title : requested == null ? List.<String>of() : requested) {
|
||||||
|
findTitle(all.keySet(), title).filter(t -> !wanted.contains(t)).ifPresent(wanted::add);
|
||||||
|
}
|
||||||
|
if (!wanted.isEmpty()) return wanted;
|
||||||
|
|
||||||
|
Set<SceneType> types = new LinkedHashSet<>();
|
||||||
|
scenes.forEach(s -> types.add(typeOf(s)));
|
||||||
|
if (types.isEmpty()) types.add(SceneType.GENERIC);
|
||||||
|
List<String> offered = all.keySet().stream().filter(t -> !otherLanguage.contains(t)).toList();
|
||||||
|
for (String title : offered) {
|
||||||
|
if (suggestedFor(title).stream().anyMatch(types::contains)) wanted.add(title);
|
||||||
|
}
|
||||||
|
return wanted.isEmpty() ? new ArrayList<>(offered) : wanted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Titres des sections rédigées dans l'autre langue que l'interface. Aucun si toutes le
|
||||||
|
* sont : des règles qui n'existent que dans une langue restent proposées en entier.
|
||||||
|
*/
|
||||||
|
static Set<String> otherLanguageTitles(Map<String, String> sections, String language) {
|
||||||
|
String wanted = RulesLanguage.of(language);
|
||||||
|
Set<String> other = new LinkedHashSet<>();
|
||||||
|
sections.forEach((title, content) -> {
|
||||||
|
if (RulesLanguage.detect(content).filter(found -> !found.equals(wanted)).isPresent()) other.add(title);
|
||||||
|
});
|
||||||
|
return other.size() == sections.size() ? Set.of() : other;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections envoyées, dans l'ordre demandé et dans la limite du budget. Une section trop
|
||||||
|
* longue n'envoie qu'un de ses morceaux : la série suivante en verra un autre.
|
||||||
|
*/
|
||||||
|
static Map<String, String> selectSections(Map<String, String> all, List<String> ordered, IntUnaryOperator picker) {
|
||||||
|
Map<String, String> selected = new LinkedHashMap<>();
|
||||||
|
int remaining = MAX_RULES_CHARS;
|
||||||
|
for (String title : ordered) {
|
||||||
|
String content = all.get(title);
|
||||||
|
if (content == null || content.isBlank()) continue;
|
||||||
|
int allowed = Math.min(MAX_SECTION_CHARS, remaining);
|
||||||
|
if (content.length() > allowed) {
|
||||||
|
if (allowed < MIN_WINDOW_CHARS) break;
|
||||||
|
List<String> windows = windows(content, allowed);
|
||||||
|
content = windows.get(Math.floorMod(picker.applyAsInt(windows.size()), windows.size()));
|
||||||
|
}
|
||||||
|
selected.put(title, content);
|
||||||
|
remaining -= content.length();
|
||||||
|
if (remaining <= 0) break;
|
||||||
|
}
|
||||||
|
return selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Découpe un texte en morceaux d'au plus {@code max} caractères, aux lignes vides si possible. */
|
||||||
|
static List<String> windows(String content, int max) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
StringBuilder current = new StringBuilder();
|
||||||
|
for (String paragraph : content.split("\\n\\s*\\n")) {
|
||||||
|
String p = paragraph.strip();
|
||||||
|
if (p.isEmpty()) continue;
|
||||||
|
if (current.length() > 0 && current.length() + 2 + p.length() > max) {
|
||||||
|
out.add(current.toString());
|
||||||
|
current.setLength(0);
|
||||||
|
}
|
||||||
|
while (p.length() > max) {
|
||||||
|
if (current.length() > 0) {
|
||||||
|
out.add(current.toString());
|
||||||
|
current.setLength(0);
|
||||||
|
}
|
||||||
|
out.add(p.substring(0, max));
|
||||||
|
p = p.substring(max).strip();
|
||||||
|
}
|
||||||
|
if (p.isEmpty()) continue;
|
||||||
|
if (current.length() > 0) current.append("\n\n");
|
||||||
|
current.append(p);
|
||||||
|
}
|
||||||
|
if (current.length() > 0) out.add(current.toString());
|
||||||
|
return out.isEmpty() ? List.of(content.substring(0, Math.min(max, content.length()))) : out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Tri de la réponse -------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Garde les situations dont l'extrait figure dans une section envoyée. La section annoncée
|
||||||
|
* est corrigée si l'extrait se trouve dans une autre ; une situation sans extrait retrouvé,
|
||||||
|
* ou posée deux fois, est écartée.
|
||||||
|
*/
|
||||||
|
static List<RuleDrill> validate(List<DrillCandidate> candidates, Map<String, String> sent, List<Scene> scenes) {
|
||||||
|
Map<String, String> normalized = new LinkedHashMap<>();
|
||||||
|
sent.forEach((title, content) -> normalized.put(title, normalize(content)));
|
||||||
|
|
||||||
|
List<RuleDrill> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (DrillCandidate c : candidates == null ? List.<DrillCandidate>of() : candidates) {
|
||||||
|
if (out.size() >= MAX_DRILLS) break;
|
||||||
|
if (c == null || isBlank(c.situation()) || isBlank(c.ruling()) || isBlank(c.excerpt())) continue;
|
||||||
|
String excerpt = c.excerpt().strip();
|
||||||
|
if (excerpt.length() > MAX_EXCERPT_CHARS) continue;
|
||||||
|
Optional<String> section = locate(excerpt, c.section(), normalized);
|
||||||
|
if (section.isEmpty()) continue;
|
||||||
|
String situation = c.situation().strip();
|
||||||
|
if (!seen.add(situation.toLowerCase(Locale.ROOT))) continue;
|
||||||
|
|
||||||
|
Scene scene = c.scene() >= 1 && c.scene() <= scenes.size() ? scenes.get(c.scene() - 1) : null;
|
||||||
|
out.add(new RuleDrill(scene == null ? null : scene.getId(), scene == null ? "" : nz(scene.getName()),
|
||||||
|
situation, section.get(), excerpt, c.ruling().strip()));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Écarte les situations dont la citation est rédigée dans l'autre langue que l'interface
|
||||||
|
* (un passage resté en version originale dans une section traduite). Les sections que le
|
||||||
|
* MJ a choisies en sachant qu'elles sont dans l'autre langue ne sont pas concernées.
|
||||||
|
*/
|
||||||
|
static List<RuleDrill> inLanguage(List<RuleDrill> drills, Set<String> otherLanguage, String language) {
|
||||||
|
String wanted = RulesLanguage.of(language);
|
||||||
|
return drills.stream()
|
||||||
|
.filter(d -> otherLanguage.contains(d.section())
|
||||||
|
|| RulesLanguage.detect(d.excerpt()).filter(found -> !found.equals(wanted)).isEmpty())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Section qui contient l'extrait : celle annoncée d'abord, sinon la première autre. */
|
||||||
|
private static Optional<String> locate(String excerpt, String announced, Map<String, String> normalized) {
|
||||||
|
Optional<String> first = findTitle(normalized.keySet(), announced);
|
||||||
|
if (first.isPresent() && contains(normalized.get(first.get()), excerpt)) return first;
|
||||||
|
return normalized.entrySet().stream()
|
||||||
|
.filter(e -> contains(e.getValue(), excerpt))
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* L'extrait figure-t-il dans le texte (déjà normalisé) ? Un extrait coupé par des points de
|
||||||
|
* suspension est accepté si ses morceaux s'y suivent dans l'ordre.
|
||||||
|
*/
|
||||||
|
static boolean contains(String normalizedText, String excerpt) {
|
||||||
|
int total = 0;
|
||||||
|
int from = 0;
|
||||||
|
for (String part : excerpt.split("\\[\\s*(?:…|\\.{3})\\s*]|…|\\.{3}")) {
|
||||||
|
String fragment = normalize(part);
|
||||||
|
if (fragment.length() < MIN_FRAGMENT_CHARS) continue;
|
||||||
|
int at = normalizedText.indexOf(fragment, from);
|
||||||
|
if (at < 0) return false;
|
||||||
|
from = at + fragment.length();
|
||||||
|
total += fragment.length();
|
||||||
|
}
|
||||||
|
return total >= MIN_EXCERPT_CHARS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Texte ramené à ce qui se lit : minuscules, mise en forme markdown et guillemets retirés,
|
||||||
|
* apostrophes et espaces unifiés. Un modèle qui recopie « **Garde** » en « Garde » cite
|
||||||
|
* fidèlement ; un modèle qui reformule ne passe pas.
|
||||||
|
*/
|
||||||
|
static String normalize(String text) {
|
||||||
|
if (text == null) return "";
|
||||||
|
StringBuilder sb = new StringBuilder(text.length());
|
||||||
|
boolean space = false;
|
||||||
|
for (int i = 0; i < text.length(); i++) {
|
||||||
|
char ch = text.charAt(i);
|
||||||
|
if (ch == '’' || ch == '‘' || ch == 'ʼ') ch = '\'';
|
||||||
|
if (ch == '*' || ch == '_' || ch == '`' || ch == '#' || ch == '>' || ch == '|'
|
||||||
|
|| ch == '"' || ch == '«' || ch == '»' || ch == '“' || ch == '”') {
|
||||||
|
ch = ' ';
|
||||||
|
}
|
||||||
|
if (Character.isWhitespace(ch) || Character.isSpaceChar(ch)) {
|
||||||
|
space = sb.length() > 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (space) {
|
||||||
|
sb.append(' ');
|
||||||
|
space = false;
|
||||||
|
}
|
||||||
|
sb.append(Character.toLowerCase(ch));
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Comparaison d'une réponse -----------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare la décision écrite par le MJ aux règles de la section et au corrigé.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException si la réponse est vide, ou si la section n'existe plus
|
||||||
|
*/
|
||||||
|
public RuleDrillReview review(String campaignId, String section, String situation,
|
||||||
|
String excerpt, String ruling, String answer) {
|
||||||
|
if (isBlank(answer) || isBlank(situation)) {
|
||||||
|
throw new IllegalArgumentException("Écrivez votre décision avant de la comparer.");
|
||||||
|
}
|
||||||
|
GameSystem gs = system(campaign(campaignId))
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Cette campagne n'a pas de système de jeu."));
|
||||||
|
Map<String, String> all = rules(gs).sections();
|
||||||
|
String title = findTitle(all.keySet(), section)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Cette section n'existe plus dans les règles."));
|
||||||
|
String trimmed = answer.strip();
|
||||||
|
return coach.review(nz(gs.getName()), title, windowAround(all.get(title), nz(excerpt)),
|
||||||
|
situation.strip(), nz(excerpt).strip(), nz(ruling).strip(),
|
||||||
|
trimmed.length() > MAX_ANSWER_CHARS ? trimmed.substring(0, MAX_ANSWER_CHARS) : trimmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** La section entière si elle tient, sinon son morceau qui contient l'extrait (à défaut le premier). */
|
||||||
|
static String windowAround(String content, String excerpt) {
|
||||||
|
if (content.length() <= MAX_SECTION_CHARS) return content;
|
||||||
|
List<String> windows = windows(content, MAX_SECTION_CHARS);
|
||||||
|
return windows.stream()
|
||||||
|
.filter(w -> contains(normalize(w), excerpt))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(windows.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Chargement --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private Campaign campaign(String campaignId) {
|
||||||
|
return campaignRepository.findById(campaignId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Campagne inconnue : " + campaignId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Optional<GameSystem> system(Campaign campaign) {
|
||||||
|
return campaign.getGameSystemId() == null || campaign.getGameSystemId().isBlank()
|
||||||
|
? Optional.empty()
|
||||||
|
: gameSystemRepository.findById(campaign.getGameSystemId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections non vides des règles, prises dans l'onglet de la langue de l'interface (repli
|
||||||
|
* sur l'autre s'il est vide), avec celles dont le texte est en réalité dans l'autre langue.
|
||||||
|
*/
|
||||||
|
private Rules rules(GameSystem gs) {
|
||||||
|
String language = currentLanguage.get();
|
||||||
|
Map<String, String> sections = new LinkedHashMap<>();
|
||||||
|
GameSystemContextBuilder.parseH2Sections(gs.rulesFor(language)).forEach((title, content) -> {
|
||||||
|
if (!isBlank(title) && !isBlank(content)) sections.put(title, content);
|
||||||
|
});
|
||||||
|
return new Rules(sections, otherLanguageTitles(sections, language));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scènes demandées qui appartiennent bien à la campagne, dans l'ordre demandé, sans doublon. */
|
||||||
|
private List<Scene> scenesOf(String campaignId, List<String> sceneIds) {
|
||||||
|
List<Scene> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String id : sceneIds == null ? List.<String>of() : sceneIds) {
|
||||||
|
if (out.size() >= MAX_SCENES) break;
|
||||||
|
if (id == null || !seen.add(id)) continue;
|
||||||
|
sceneRepository.findById(id).filter(s -> belongsTo(s, campaignId)).ifPresent(out::add);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean belongsTo(Scene scene, String campaignId) {
|
||||||
|
return Optional.ofNullable(scene.getChapterId())
|
||||||
|
.flatMap(chapterRepository::findById)
|
||||||
|
.map(Chapter::getArcId)
|
||||||
|
.flatMap(arcRepository::findById)
|
||||||
|
.map(arc -> Objects.equals(arc.getCampaignId(), campaignId))
|
||||||
|
.orElse(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Résumé d'une scène ------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Ce qu'il faut de la scène pour y situer une action : lieu, personnages, adversaires. */
|
||||||
|
private SceneBrief brief(Scene scene) {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
line(sb, "Résumé", scene.getDescription());
|
||||||
|
line(sb, "Lieu", scene.getLocation());
|
||||||
|
line(sb, "Moment", scene.getTiming());
|
||||||
|
line(sb, "Ambiance", scene.getAtmosphere());
|
||||||
|
line(sb, "Narration", scene.getPlayerNarration());
|
||||||
|
line(sb, "Choix", scene.getChoicesConsequences());
|
||||||
|
line(sb, "Adversaires", joinNonBlank(scene.getEnemies(), enemyNames(scene.getEnemyIds())));
|
||||||
|
line(sb, "Tactique", scene.getTactics());
|
||||||
|
line(sb, "Difficulté", scene.getCombatDifficulty());
|
||||||
|
line(sb, "Pièces", rooms(scene.getRooms()));
|
||||||
|
line(sb, "Notes du MJ", scene.getGmSecretNotes());
|
||||||
|
String text = sb.toString().strip();
|
||||||
|
return new SceneBrief(nz(scene.getName()), kindLabel(typeOf(scene)),
|
||||||
|
text.length() > MAX_SCENE_CHARS ? text.substring(0, MAX_SCENE_CHARS).stripTrailing() + "…" : text);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void line(StringBuilder sb, String label, String value) {
|
||||||
|
if (isBlank(value)) return;
|
||||||
|
String v = value.strip().replaceAll("\\s+", " ");
|
||||||
|
if (v.length() > MAX_SCENE_FIELD_CHARS) v = v.substring(0, MAX_SCENE_FIELD_CHARS).stripTrailing() + "…";
|
||||||
|
sb.append(label).append(" : ").append(v).append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
private String enemyNames(List<String> enemyIds) {
|
||||||
|
List<String> names = new ArrayList<>();
|
||||||
|
for (String id : enemyIds == null ? List.<String>of() : enemyIds) {
|
||||||
|
enemyRepository.findById(id).map(Enemy::getName).filter(n -> !isBlank(n)).ifPresent(names::add);
|
||||||
|
}
|
||||||
|
return String.join(", ", names);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String rooms(List<Room> rooms) {
|
||||||
|
List<String> parts = new ArrayList<>();
|
||||||
|
for (Room room : rooms == null ? List.<Room>of() : rooms) {
|
||||||
|
if (room == null || isBlank(room.getName())) continue;
|
||||||
|
parts.add(joinNonBlank(room.getName().strip(), joinNonBlank(room.getEnemies(), room.getTraps())));
|
||||||
|
}
|
||||||
|
return String.join(" ; ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String kindLabel(SceneType type) {
|
||||||
|
return switch (type) {
|
||||||
|
case LOCATION -> "lieu à explorer";
|
||||||
|
case ENCOUNTER -> "rencontre ou combat";
|
||||||
|
case NPC -> "scène autour d'un personnage";
|
||||||
|
case EVENT -> "événement";
|
||||||
|
case REVELATION -> "révélation";
|
||||||
|
case GENERIC -> "";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Utilitaires -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static SceneType typeOf(Scene scene) {
|
||||||
|
return scene.getType() == null ? SceneType.GENERIC : scene.getType();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<String> findTitle(Set<String> titles, String wanted) {
|
||||||
|
if (isBlank(wanted)) return Optional.empty();
|
||||||
|
String key = wanted.strip();
|
||||||
|
return titles.stream().filter(t -> t.equalsIgnoreCase(key)).findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> clean(List<String> values) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
for (String value : values == null ? List.<String>of() : values) {
|
||||||
|
if (out.size() >= MAX_AVOIDED) break;
|
||||||
|
if (!isBlank(value)) out.add(value.strip());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String joinNonBlank(String a, String b) {
|
||||||
|
if (isBlank(a)) return nz(b).strip();
|
||||||
|
if (isBlank(b)) return a.strip();
|
||||||
|
return a.strip() + " — " + b.strip();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String value) {
|
||||||
|
return value == null ? "" : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String value) {
|
||||||
|
return value == null || value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Langue dans laquelle un passage de règles est rédigé, d'après ses mots outils.
|
||||||
|
* <p>
|
||||||
|
* L'onglet français des règles peut contenir du texte anglais (livre importé en version
|
||||||
|
* originale), et l'inverse : le champ dans lequel un texte est rangé ne dit pas sa langue.
|
||||||
|
* Un passage trop court, ou partagé entre les deux langues, reste indéterminé.
|
||||||
|
*/
|
||||||
|
final class RulesLanguage {
|
||||||
|
|
||||||
|
static final String FRENCH = "fr";
|
||||||
|
static final String ENGLISH = "en";
|
||||||
|
|
||||||
|
/** En dessous, le passage (un tableau de chiffres, trois mots) ne permet pas de trancher. */
|
||||||
|
static final int MIN_MARKERS = 5;
|
||||||
|
|
||||||
|
/** Mots outils propres à une langue : « a », « on », « plus » ou « or » sont écartés. */
|
||||||
|
private static final Set<String> FRENCH_WORDS = Set.of(
|
||||||
|
"le", "la", "les", "de", "des", "une", "un", "du", "au", "aux", "et", "est", "sont", "dans",
|
||||||
|
"pour", "que", "qui", "avec", "vous", "votre", "vos", "sur", "pas", "ce", "cette", "ces",
|
||||||
|
"ou", "par", "peut", "ne", "se", "leur", "leurs", "chaque", "lorsque", "à", "il", "elle",
|
||||||
|
"ils", "mais", "être");
|
||||||
|
private static final Set<String> ENGLISH_WORDS = Set.of(
|
||||||
|
"the", "of", "and", "to", "is", "in", "you", "your", "that", "with", "for", "it", "as",
|
||||||
|
"can", "are", "be", "this", "when", "at", "from", "by", "not", "each", "may", "any", "if",
|
||||||
|
"must", "has", "have", "their", "they", "will", "which");
|
||||||
|
|
||||||
|
private static final Pattern WORD = Pattern.compile("\\p{L}+");
|
||||||
|
|
||||||
|
private RulesLanguage() {}
|
||||||
|
|
||||||
|
/** {@code fr} ou {@code en} si l'une des deux domine nettement, sinon rien. */
|
||||||
|
static Optional<String> detect(String text) {
|
||||||
|
if (text == null) return Optional.empty();
|
||||||
|
int french = 0;
|
||||||
|
int english = 0;
|
||||||
|
Matcher matcher = WORD.matcher(text.toLowerCase(Locale.ROOT));
|
||||||
|
while (matcher.find()) {
|
||||||
|
String word = matcher.group();
|
||||||
|
if (FRENCH_WORDS.contains(word)) french++;
|
||||||
|
else if (ENGLISH_WORDS.contains(word)) english++;
|
||||||
|
}
|
||||||
|
if (french + english < MIN_MARKERS) return Optional.empty();
|
||||||
|
if (french * 2 >= english * 3) return Optional.of(FRENCH);
|
||||||
|
if (english * 2 >= french * 3) return Optional.of(ENGLISH);
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Langue de l'interface ramenée à {@code fr} ou {@code en} ({@code fr} par défaut). */
|
||||||
|
static String of(String language) {
|
||||||
|
return ENGLISH.equalsIgnoreCase(language) ? ENGLISH : FRENCH;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetSpellRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sorts connus d'une fiche (PJ, PNJ ou ennemi) : des liens vers des sorts du catalogue du
|
||||||
|
* système, rangés à part des fiches. Une fiche garde ainsi exactement ce qu'elle portait
|
||||||
|
* avant, et un sort retiré du catalogue disparaît de lui-même des fiches.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class SheetSpellService {
|
||||||
|
|
||||||
|
/** Garde-fou : aucune fiche ne connaît autant de sorts. */
|
||||||
|
static final int MAX_SPELLS = 500;
|
||||||
|
|
||||||
|
private final SheetSpellRepository sheetSpellRepository;
|
||||||
|
private final SpellRepository spellRepository;
|
||||||
|
private final CharacterRepository characterRepository;
|
||||||
|
private final NpcRepository npcRepository;
|
||||||
|
private final EnemyRepository enemyRepository;
|
||||||
|
|
||||||
|
public SheetSpellService(SheetSpellRepository sheetSpellRepository, SpellRepository spellRepository,
|
||||||
|
CharacterRepository characterRepository, NpcRepository npcRepository,
|
||||||
|
EnemyRepository enemyRepository) {
|
||||||
|
this.sheetSpellRepository = sheetSpellRepository;
|
||||||
|
this.spellRepository = spellRepository;
|
||||||
|
this.characterRepository = characterRepository;
|
||||||
|
this.npcRepository = npcRepository;
|
||||||
|
this.enemyRepository = enemyRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException si la fiche est inconnue
|
||||||
|
*/
|
||||||
|
public List<String> spellIds(SheetKind kind, String ownerId) {
|
||||||
|
requireOwner(kind, ownerId);
|
||||||
|
return sheetSpellRepository.findSpellIds(kind, ownerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remplace les sorts connus de la fiche. Les doublons et les sorts qui n'existent plus
|
||||||
|
* sont ignorés ; l'ordre reçu est gardé.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException si la fiche est inconnue ou si la liste est démesurée
|
||||||
|
*/
|
||||||
|
public List<String> replace(SheetKind kind, String ownerId, List<String> spellIds) {
|
||||||
|
requireOwner(kind, ownerId);
|
||||||
|
List<String> wanted = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String id : spellIds == null ? List.<String>of() : spellIds) {
|
||||||
|
if (isNumber(id) && seen.add(id.strip())) wanted.add(id.strip());
|
||||||
|
}
|
||||||
|
if (wanted.size() > MAX_SPELLS) {
|
||||||
|
throw new IllegalArgumentException("Une fiche ne peut pas connaître plus de " + MAX_SPELLS + " sorts.");
|
||||||
|
}
|
||||||
|
Set<String> existing = new HashSet<>(spellRepository.existingIds(wanted));
|
||||||
|
List<String> kept = wanted.stream().filter(existing::contains).toList();
|
||||||
|
sheetSpellRepository.replace(kind, ownerId, kept);
|
||||||
|
return kept;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireOwner(SheetKind kind, String ownerId) {
|
||||||
|
boolean known = isNumber(ownerId) && switch (kind) {
|
||||||
|
case CHARACTER -> characterRepository.findById(ownerId.strip()).isPresent();
|
||||||
|
case NPC -> npcRepository.findById(ownerId.strip()).isPresent();
|
||||||
|
case ENEMY -> enemyRepository.findById(ownerId.strip()).isPresent();
|
||||||
|
};
|
||||||
|
if (!known) {
|
||||||
|
throw new IllegalArgumentException("Fiche inconnue : " + kind.wireName() + " " + ownerId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Les identifiants sont des entiers en base : tout le reste est ignoré plutôt que de planter. */
|
||||||
|
private static boolean isNumber(String value) {
|
||||||
|
return value != null && value.strip().matches("\\d{1,18}");
|
||||||
|
}
|
||||||
|
}
|
||||||
+209
@@ -0,0 +1,209 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetFieldProposal;
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetTemplateAdvisor;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetTemplateAdvisor.Candidate;
|
||||||
|
import com.loremind.domain.shared.template.FieldType;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Propose les champs d'une fiche (PJ, PNJ, ennemi) à partir des règles d'un système.
|
||||||
|
* <p>
|
||||||
|
* Travaille sur les règles telles qu'elles sont affichées dans l'éditeur (enregistrées
|
||||||
|
* ou non) : un système dont les règles viennent d'être importées, ou saisies à la main
|
||||||
|
* depuis longtemps, en profite de la même façon. Rien n'est enregistré : la proposition
|
||||||
|
* ne fait qu'AJOUTER des champs, que le MJ choisit un par un.
|
||||||
|
* <p>
|
||||||
|
* Deux garde-fous : seules les sections utiles à la fiche partent vers l'IA, dans une
|
||||||
|
* taille bornée ; et la réponse est triée (types connus, noms uniques, listes
|
||||||
|
* réellement remplies, plafond) avant d'atteindre l'écran.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class SheetTemplateProposalService {
|
||||||
|
|
||||||
|
/** Taille totale des règles envoyées (~6 000 jetons, l'ordre de grandeur d'un morceau d'import). */
|
||||||
|
static final int MAX_RULES_CHARS = 24_000;
|
||||||
|
/** Part maximale d'une seule section : une section géante ne doit pas évincer les autres. */
|
||||||
|
static final int MAX_SECTION_CHARS = 9_000;
|
||||||
|
/** En dessous, un reste de budget ne vaut pas un extrait tronqué de plus. */
|
||||||
|
static final int MIN_EXCERPT_CHARS = 400;
|
||||||
|
|
||||||
|
static final int MAX_FIELDS = 25;
|
||||||
|
static final int MAX_NAME_CHARS = 60;
|
||||||
|
static final int MIN_LABELS = 2;
|
||||||
|
static final int MAX_LABELS = 30;
|
||||||
|
static final int MAX_LABEL_CHARS = 40;
|
||||||
|
|
||||||
|
/** Champs que l'application gère elle-même sur toutes les fiches. */
|
||||||
|
private static final Set<String> RESERVED_NAMES = Set.of(
|
||||||
|
"nom", "name", "portrait", "bandeau", "header", "image", "images", "illustration");
|
||||||
|
/** En plus, sur la fiche d'ennemi. */
|
||||||
|
private static final Set<String> RESERVED_ENEMY_NAMES = Set.of("niveau", "level", "dossier", "folder");
|
||||||
|
|
||||||
|
private static final Set<FieldType> PROPOSABLE_TYPES =
|
||||||
|
Set.of(FieldType.TEXT, FieldType.NUMBER, FieldType.KEY_VALUE_LIST);
|
||||||
|
|
||||||
|
/** Section de règles telle qu'affichée dans l'éditeur. */
|
||||||
|
public record RuleSection(String title, String content) {}
|
||||||
|
|
||||||
|
private final SheetTemplateAdvisor advisor;
|
||||||
|
|
||||||
|
public SheetTemplateProposalService(SheetTemplateAdvisor advisor) {
|
||||||
|
this.advisor = advisor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException si aucune règle n'est fournie
|
||||||
|
*/
|
||||||
|
public List<SheetFieldProposal> propose(SheetKind kind, String systemName,
|
||||||
|
List<RuleSection> rules, List<String> existingFieldNames) {
|
||||||
|
Map<String, String> all = mergeSections(rules);
|
||||||
|
if (all.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Aucune règle à partir de laquelle proposer une fiche.");
|
||||||
|
}
|
||||||
|
Map<String, String> selected = selectSections(all, kind);
|
||||||
|
List<Candidate> candidates = advisor.propose(
|
||||||
|
kind, systemName == null ? "" : systemName.trim(), selected, cleanNames(existingFieldNames));
|
||||||
|
return validate(candidates, kind, selected.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Choix des sections envoyées ---------------------------------------------------------
|
||||||
|
|
||||||
|
/** Sections non vides, ordre préservé ; deux sections de même titre sont réunies. */
|
||||||
|
static Map<String, String> mergeSections(List<RuleSection> rules) {
|
||||||
|
Map<String, String> merged = new LinkedHashMap<>();
|
||||||
|
Map<String, String> canonical = new LinkedHashMap<>();
|
||||||
|
for (RuleSection section : rules == null ? List.<RuleSection>of() : rules) {
|
||||||
|
if (section == null || isBlank(section.title()) || isBlank(section.content())) continue;
|
||||||
|
String title = section.title().trim();
|
||||||
|
String key = canonical.computeIfAbsent(title.toLowerCase(Locale.ROOT), k -> title);
|
||||||
|
merged.merge(key, section.content().strip(), (a, b) -> a + "\n\n" + b);
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections utiles à la fiche, par ordre de priorité, dans la limite du budget. Si aucun
|
||||||
|
* titre ne correspond (règles découpées avec des titres maison), toutes les sections sont
|
||||||
|
* candidates, dans l'ordre du document.
|
||||||
|
*/
|
||||||
|
static Map<String, String> selectSections(Map<String, String> all, SheetKind kind) {
|
||||||
|
List<String> ordered = new ArrayList<>();
|
||||||
|
for (Set<String> aliases : kind.sectionAliases()) {
|
||||||
|
for (String title : all.keySet()) {
|
||||||
|
String lower = title.toLowerCase(Locale.ROOT);
|
||||||
|
if (!ordered.contains(title) && aliases.stream().anyMatch(lower::contains)) {
|
||||||
|
ordered.add(title);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ordered.isEmpty()) {
|
||||||
|
ordered.addAll(all.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, String> selected = new LinkedHashMap<>();
|
||||||
|
int remaining = MAX_RULES_CHARS;
|
||||||
|
for (String title : ordered) {
|
||||||
|
String content = all.get(title);
|
||||||
|
int allowed = Math.min(MAX_SECTION_CHARS, remaining);
|
||||||
|
if (content.length() > allowed) {
|
||||||
|
if (allowed < MIN_EXCERPT_CHARS) break;
|
||||||
|
content = truncate(content, allowed);
|
||||||
|
}
|
||||||
|
selected.put(title, content);
|
||||||
|
remaining -= content.length();
|
||||||
|
if (remaining <= 0) break;
|
||||||
|
}
|
||||||
|
return selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Coupe au dernier saut de ligne avant la limite (à défaut, à la limite) et le signale. */
|
||||||
|
private static String truncate(String content, int max) {
|
||||||
|
int cut = content.lastIndexOf('\n', max);
|
||||||
|
if (cut < max / 2) cut = max;
|
||||||
|
return content.substring(0, cut).stripTrailing() + "\n[…]";
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Tri de la réponse ------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Garde les champs utilisables : type proposable, nom court, unique et non réservé, liste
|
||||||
|
* de valeurs réellement remplie. La source n'est conservée que si elle désigne une section
|
||||||
|
* envoyée. Plafonné à {@link #MAX_FIELDS}.
|
||||||
|
*/
|
||||||
|
static List<SheetFieldProposal> validate(List<Candidate> candidates, SheetKind kind, Set<String> sentTitles) {
|
||||||
|
List<SheetFieldProposal> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (Candidate c : candidates == null ? List.<Candidate>of() : candidates) {
|
||||||
|
if (out.size() >= MAX_FIELDS) break;
|
||||||
|
if (c == null || isBlank(c.name())) continue;
|
||||||
|
String name = c.name().trim().replaceAll("\\s+", " ");
|
||||||
|
String key = name.toLowerCase(Locale.ROOT);
|
||||||
|
FieldType type = parseType(c.type());
|
||||||
|
if (type == null || name.length() > MAX_NAME_CHARS || isReserved(key, kind) || seen.contains(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> labels = type == FieldType.KEY_VALUE_LIST ? cleanLabels(c.labels()) : List.of();
|
||||||
|
if (type == FieldType.KEY_VALUE_LIST && labels.size() < MIN_LABELS) continue;
|
||||||
|
seen.add(key);
|
||||||
|
out.add(new SheetFieldProposal(name, type, labels, matchSource(c.source(), sentTitles)));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FieldType parseType(String raw) {
|
||||||
|
if (raw == null) return null;
|
||||||
|
try {
|
||||||
|
FieldType type = FieldType.valueOf(raw.trim().toUpperCase(Locale.ROOT));
|
||||||
|
return PROPOSABLE_TYPES.contains(type) ? type : null;
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isReserved(String lowerName, SheetKind kind) {
|
||||||
|
return RESERVED_NAMES.contains(lowerName)
|
||||||
|
|| (kind == SheetKind.ENEMY && RESERVED_ENEMY_NAMES.contains(lowerName));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> cleanLabels(List<String> labels) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String label : labels == null ? List.<String>of() : labels) {
|
||||||
|
if (out.size() >= MAX_LABELS) break;
|
||||||
|
if (isBlank(label)) continue;
|
||||||
|
String clean = label.trim().replaceAll("\\s+", " ");
|
||||||
|
if (clean.length() <= MAX_LABEL_CHARS && seen.add(clean.toLowerCase(Locale.ROOT))) {
|
||||||
|
out.add(clean);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String matchSource(String source, Set<String> sentTitles) {
|
||||||
|
if (isBlank(source)) return "";
|
||||||
|
String wanted = source.trim();
|
||||||
|
return sentTitles.stream().filter(t -> t.equalsIgnoreCase(wanted)).findFirst().orElse("");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> cleanNames(List<String> names) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
for (String name : names == null ? List.<String>of() : names) {
|
||||||
|
if (!isBlank(name)) out.add(name.trim());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String s) {
|
||||||
|
return s == null || s.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.gamesystemcontext.Spell;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellRepository;
|
||||||
|
import com.loremind.domain.shared.template.FieldType;
|
||||||
|
import com.loremind.domain.shared.template.TemplateField;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Catalogue de sorts d'un système de jeu : les sorts eux-mêmes, et le « modèle de sort »
|
||||||
|
* (champs propres au système : portée, durée, coût…).
|
||||||
|
* <p>
|
||||||
|
* L'écran d'édition d'un système enregistre tout d'un coup : le catalogue est donc remplacé
|
||||||
|
* en bloc. Un sort envoyé avec son identifiant est mis à jour (son identifiant reste stable),
|
||||||
|
* un sort sans identifiant est créé, un sort absent de l'envoi est supprimé.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class SpellCatalogService {
|
||||||
|
|
||||||
|
/** Garde-fou : au-delà, l'envoi est une erreur (aucun livre n'en compte autant). */
|
||||||
|
static final int MAX_SPELLS = 3_000;
|
||||||
|
/** Longueur des colonnes nom, niveau et école. */
|
||||||
|
static final int MAX_LABEL_CHARS = 255;
|
||||||
|
|
||||||
|
/** Ce qu'un sort porte à l'enregistrement. {@code id} null = nouveau sort. */
|
||||||
|
public record SpellData(String id, String name, String level, String school, String description,
|
||||||
|
Map<String, String> values) {}
|
||||||
|
|
||||||
|
/** Le modèle de sort du système et ses sorts, dans l'ordre du catalogue. */
|
||||||
|
public record Catalog(List<TemplateField> template, List<Spell> spells) {}
|
||||||
|
|
||||||
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
private final SpellRepository spellRepository;
|
||||||
|
|
||||||
|
public SpellCatalogService(GameSystemRepository gameSystemRepository, SpellRepository spellRepository) {
|
||||||
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
this.spellRepository = spellRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException si le système est inconnu
|
||||||
|
*/
|
||||||
|
public Catalog get(String gameSystemId) {
|
||||||
|
GameSystem gs = system(gameSystemId);
|
||||||
|
return new Catalog(List.copyOf(gs.getSpellTemplate()), spellRepository.findByGameSystemId(gs.getId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remplace le modèle de sort et le catalogue du système.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException si le système est inconnu, si le modèle a un champ sans
|
||||||
|
* nom, en double ou d'un type autre que texte ou nombre, ou
|
||||||
|
* si un sort n'a pas de nom
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Catalog replace(String gameSystemId, List<TemplateField> template, List<SpellData> spells) {
|
||||||
|
GameSystem gs = system(gameSystemId);
|
||||||
|
List<SpellData> incoming = spells == null ? List.of() : spells;
|
||||||
|
if (incoming.size() > MAX_SPELLS) {
|
||||||
|
throw new IllegalArgumentException("Un catalogue ne peut pas dépasser " + MAX_SPELLS + " sorts.");
|
||||||
|
}
|
||||||
|
for (SpellData data : incoming) {
|
||||||
|
if (data == null || isBlank(data.name())) {
|
||||||
|
throw new IllegalArgumentException("Un sort n'a pas de nom.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gs.replaceSpellTemplate(supported(template));
|
||||||
|
gs = gameSystemRepository.save(gs);
|
||||||
|
|
||||||
|
Map<String, Spell> existing = new LinkedHashMap<>();
|
||||||
|
spellRepository.findByGameSystemId(gs.getId()).forEach(s -> existing.put(s.getId(), s));
|
||||||
|
|
||||||
|
List<Spell> saved = new ArrayList<>();
|
||||||
|
Set<String> kept = new HashSet<>();
|
||||||
|
for (int i = 0; i < incoming.size(); i++) {
|
||||||
|
SpellData data = incoming.get(i);
|
||||||
|
// Un identifiant inconnu, d'un autre système ou déjà vu dans l'envoi : nouveau sort.
|
||||||
|
Spell current = data.id() != null && kept.add(data.id()) ? existing.get(data.id()) : null;
|
||||||
|
Spell spell = current != null ? current : Spell.builder().gameSystemId(gs.getId()).build();
|
||||||
|
spell.setName(label(data.name()));
|
||||||
|
spell.setLevel(label(data.level()));
|
||||||
|
spell.setSchool(label(data.school()));
|
||||||
|
spell.setDescription(isBlank(data.description()) ? null : data.description().strip());
|
||||||
|
spell.setValues(cleanValues(data.values()));
|
||||||
|
spell.setOrder(i);
|
||||||
|
saved.add(spellRepository.save(spell));
|
||||||
|
}
|
||||||
|
Set<String> savedIds = new HashSet<>();
|
||||||
|
saved.forEach(s -> savedIds.add(s.getId()));
|
||||||
|
existing.keySet().stream().filter(id -> !savedIds.contains(id)).forEach(spellRepository::deleteById);
|
||||||
|
|
||||||
|
return new Catalog(List.copyOf(gs.getSpellTemplate()), saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Le modèle de sort ne porte que du texte et des nombres : une image ou une liste
|
||||||
|
* clé/valeur n'a pas de valeur simple à ranger dans un sort.
|
||||||
|
*/
|
||||||
|
private static List<TemplateField> supported(List<TemplateField> template) {
|
||||||
|
List<TemplateField> fields = template == null ? List.of() : template;
|
||||||
|
for (TemplateField field : fields) {
|
||||||
|
if (field != null && field.getType() != null
|
||||||
|
&& field.getType() != FieldType.TEXT && field.getType() != FieldType.NUMBER) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Un champ de sort est du texte ou un nombre : « " + field.getName() + " » ne l'est pas.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fields;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valeurs non vides, telles qu'envoyées. Une valeur dont le champ a quitté le modèle est
|
||||||
|
* gardée : modifier le modèle ne détruit jamais ce qui a été saisi.
|
||||||
|
*/
|
||||||
|
private static Map<String, String> cleanValues(Map<String, String> values) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (values == null) return out;
|
||||||
|
values.forEach((key, value) -> {
|
||||||
|
if (!isBlank(key) && !isBlank(value)) out.put(key.strip(), value.strip());
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GameSystem system(String gameSystemId) {
|
||||||
|
return gameSystemRepository.findById(gameSystemId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Système de jeu inconnu : " + gameSystemId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String label(String value) {
|
||||||
|
if (isBlank(value)) return null;
|
||||||
|
String trimmed = value.strip();
|
||||||
|
return trimmed.length() > MAX_LABEL_CHARS ? trimmed.substring(0, MAX_LABEL_CHARS) : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String value) {
|
||||||
|
return value == null || value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
+161
@@ -0,0 +1,161 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellProposer;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellProposer.SpellCandidate;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellProposer.SpellField;
|
||||||
|
import com.loremind.domain.shared.template.FieldType;
|
||||||
|
import com.loremind.domain.shared.template.TemplateField;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Proposition de sorts à partir des règles : l'IA relève les sorts décrits dans UN morceau
|
||||||
|
* de règles, et rien n'est enregistré (l'écran ajoute au catalogue les sorts que le MJ coche).
|
||||||
|
* <p>
|
||||||
|
* Garde-fou : un sort n'est proposé que si son nom ET le passage qu'il cite se retrouvent
|
||||||
|
* dans le texte envoyé (à la casse, aux espaces et à la mise en forme près, comme pour
|
||||||
|
* l'entraînement aux règles). Un sort inventé, ou importé d'un autre jeu, est écarté. La
|
||||||
|
* description et les valeurs, elles, restent à relire.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class SpellProposalService {
|
||||||
|
|
||||||
|
/** Un morceau plus long ferait une réponse trop longue pour être fiable : l'écran découpe avant. */
|
||||||
|
static final int MAX_TEXT_CHARS = 12_000;
|
||||||
|
static final int MAX_SPELLS = 60;
|
||||||
|
static final int MAX_AVOIDED = 150;
|
||||||
|
static final int MAX_LABEL_CHARS = 255;
|
||||||
|
/** Un nom plus court (« Ô », « X ») se retrouverait dans n'importe quel texte. */
|
||||||
|
static final int MIN_NAME_CHARS = 3;
|
||||||
|
|
||||||
|
private static final Pattern NUMBER = Pattern.compile("-?\\d+(?:[.,]\\d+)?");
|
||||||
|
|
||||||
|
/** Un sort proposé, vérifié. {@code excerpt} : passage des règles retrouvé mot pour mot. */
|
||||||
|
public record ProposedSpell(String name, String level, String school, String description,
|
||||||
|
Map<String, String> values, String excerpt) {}
|
||||||
|
|
||||||
|
/** {@code dropped} : sorts écartés parce que leur nom ou leur passage ne figurait pas dans le texte. */
|
||||||
|
public record Proposal(List<ProposedSpell> spells, int dropped) {}
|
||||||
|
|
||||||
|
private final SpellProposer proposer;
|
||||||
|
|
||||||
|
public SpellProposalService(SpellProposer proposer) {
|
||||||
|
this.proposer = proposer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param fields modèle de sort du système (les champs texte et nombre sont remplis)
|
||||||
|
* @param avoid noms déjà dans le catalogue ou déjà proposés
|
||||||
|
* @throws IllegalArgumentException si le texte est vide ou trop long
|
||||||
|
*/
|
||||||
|
public Proposal propose(String systemName, String sectionTitle, String text,
|
||||||
|
List<TemplateField> fields, List<String> avoid) {
|
||||||
|
if (isBlank(text)) {
|
||||||
|
throw new IllegalArgumentException("Aucun texte de règles à lire.");
|
||||||
|
}
|
||||||
|
if (text.length() > MAX_TEXT_CHARS) {
|
||||||
|
throw new IllegalArgumentException("Ce morceau de règles est trop long pour être lu d'une traite.");
|
||||||
|
}
|
||||||
|
List<SpellField> spellFields = spellFields(fields);
|
||||||
|
List<String> avoided = clean(avoid);
|
||||||
|
List<SpellCandidate> candidates = proposer.extract(nz(systemName).strip(), nz(sectionTitle).strip(),
|
||||||
|
text, spellFields, avoided);
|
||||||
|
return validate(candidates, text, spellFields, avoided);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Garde les sorts dont le nom et le passage cité figurent dans le texte, sans doublon. */
|
||||||
|
static Proposal validate(List<SpellCandidate> candidates, String text, List<SpellField> fields,
|
||||||
|
List<String> avoid) {
|
||||||
|
String normalized = RuleTrainingService.normalize(text);
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String name : avoid) seen.add(key(name));
|
||||||
|
|
||||||
|
List<ProposedSpell> out = new ArrayList<>();
|
||||||
|
int dropped = 0;
|
||||||
|
for (SpellCandidate c : candidates == null ? List.<SpellCandidate>of() : candidates) {
|
||||||
|
if (out.size() >= MAX_SPELLS) break;
|
||||||
|
if (c == null || isBlank(c.name()) || isBlank(c.description())) continue;
|
||||||
|
String name = label(c.name());
|
||||||
|
// Déjà connu (catalogue, morceau précédent, même réponse) : ni proposé, ni compté comme écarté.
|
||||||
|
if (seen.contains(key(name))) continue;
|
||||||
|
String normalizedName = RuleTrainingService.normalize(name);
|
||||||
|
if (normalizedName.length() < MIN_NAME_CHARS || !normalized.contains(normalizedName)
|
||||||
|
|| isBlank(c.excerpt()) || !RuleTrainingService.contains(normalized, c.excerpt())) {
|
||||||
|
dropped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(key(name));
|
||||||
|
out.add(new ProposedSpell(name, label(c.level()), label(c.school()), c.description().strip(),
|
||||||
|
values(c.values(), fields), c.excerpt().strip()));
|
||||||
|
}
|
||||||
|
return new Proposal(out, dropped);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valeurs rangées sous le nom exact du champ du modèle. Une clé hors modèle est ignorée ;
|
||||||
|
* un champ « nombre » ne garde qu'un nombre.
|
||||||
|
*/
|
||||||
|
private static Map<String, String> values(Map<String, String> raw, List<SpellField> fields) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (raw == null) return out;
|
||||||
|
for (SpellField field : fields) {
|
||||||
|
raw.entrySet().stream()
|
||||||
|
.filter(e -> e.getKey() != null && key(e.getKey()).equals(key(field.name())))
|
||||||
|
.map(Map.Entry::getValue)
|
||||||
|
.filter(v -> !isBlank(v))
|
||||||
|
.map(String::strip)
|
||||||
|
.filter(v -> !field.number() || NUMBER.matcher(v).matches())
|
||||||
|
.findFirst()
|
||||||
|
.ifPresent(v -> out.put(field.name(), v));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Champs du modèle utilisables par le relevé : nommés, en texte ou en nombre. */
|
||||||
|
private static List<SpellField> spellFields(List<TemplateField> fields) {
|
||||||
|
List<SpellField> out = new ArrayList<>();
|
||||||
|
Set<String> names = new HashSet<>();
|
||||||
|
for (TemplateField field : fields == null ? List.<TemplateField>of() : fields) {
|
||||||
|
if (field == null || isBlank(field.getName())) continue;
|
||||||
|
if (field.getType() != null && field.getType() != FieldType.TEXT && field.getType() != FieldType.NUMBER) continue;
|
||||||
|
String name = field.getName().strip();
|
||||||
|
if (names.add(key(name))) out.add(new SpellField(name, field.getType() == FieldType.NUMBER));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> clean(List<String> values) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
for (String value : values == null ? List.<String>of() : values) {
|
||||||
|
if (out.size() >= MAX_AVOIDED) break;
|
||||||
|
if (!isBlank(value)) out.add(value.strip());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String key(String name) {
|
||||||
|
return name.strip().toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String label(String value) {
|
||||||
|
if (isBlank(value)) return "";
|
||||||
|
String trimmed = value.strip();
|
||||||
|
return trimmed.length() > MAX_LABEL_CHARS ? trimmed.substring(0, MAX_LABEL_CHARS) : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String value) {
|
||||||
|
return value == null ? "" : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String value) {
|
||||||
|
return value == null || value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import lombok.Data;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité de domaine (Aggregate Root) représentant une Quête.
|
* Entité de domaine (Aggregate Root) représentant une Quête.
|
||||||
@@ -62,6 +64,13 @@ public class Quest {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement voulu dans le livret PDF pour certaines de ces illustrations : id d'image →
|
||||||
|
* nom d'un {@code ImagePlacement}. Une image absente de la carte suit les règles par défaut.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import lombok.Data;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité de domaine représentant un Arc narratif.
|
* Entité de domaine représentant un Arc narratif.
|
||||||
@@ -57,6 +59,13 @@ public class Arc {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement voulu dans le livret PDF pour certaines de ces illustrations : id d'image →
|
||||||
|
* nom d'un {@code ImagePlacement}. Une image absente de la carte suit les règles par défaut.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import lombok.Data;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité de domaine représentant un Chapter.
|
* Entité de domaine représentant un Chapter.
|
||||||
@@ -29,6 +31,14 @@ public class Chapter {
|
|||||||
private String playerObjectives; // Objectifs des joueurs dans ce chapitre
|
private String playerObjectives; // Objectifs des joueurs dans ce chapitre
|
||||||
private String narrativeStakes; // Enjeux narratifs dramatiques
|
private String narrativeStakes; // Enjeux narratifs dramatiques
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Méthode guidée suivie par ce chapitre (« five-room », « investigation »…), ou {@code null}.
|
||||||
|
* Identifiant opaque pour le Core : les méthodes sont décrites côté front. Posée par
|
||||||
|
* l'assistant ou par {@code ChapterService.setGuidedMethod} ; une mise à jour ordinaire
|
||||||
|
* du chapitre ne la touche pas.
|
||||||
|
*/
|
||||||
|
private String guidedMethod;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IDs des pages du Lore associées à ce chapitre (weak cross-context references).
|
* IDs des pages du Lore associées à ce chapitre (weak cross-context references).
|
||||||
* Permet au MJ de lier des PNJ / lieux / éléments du Lore qui apparaissent dans ce chapitre.
|
* Permet au MJ de lier des PNJ / lieux / éléments du Lore qui apparaissent dans ce chapitre.
|
||||||
@@ -42,6 +52,13 @@ public class Chapter {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement voulu dans le livret PDF pour certaines de ces illustrations : id d'image →
|
||||||
|
* nom d'un {@code ImagePlacement}. Une image absente de la carte suit les règles par défaut.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.structure;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement d'une illustration dans le livret PDF, choisi par l'auteur pour une image DANS une
|
||||||
|
* galerie donnée (celle d'un arc, d'un chapitre ou d'une quête) : la même image peut être placée
|
||||||
|
* autrement ailleurs. Les galeries portent une carte « id d'image → nom du placement » ; une
|
||||||
|
* image absente de la carte est en {@link #AUTO}.
|
||||||
|
* <p>
|
||||||
|
* Seul le thème « Parchemin » du livret en tient compte ; le thème classique l'ignore.
|
||||||
|
*/
|
||||||
|
public enum ImagePlacement {
|
||||||
|
/** Règles du thème : la première image ouvre l'arc ou le chapitre, les autres vont dans le texte. */
|
||||||
|
AUTO,
|
||||||
|
/** Image encadrée dans le texte, jamais en ouverture. */
|
||||||
|
IN_TEXT,
|
||||||
|
/** Bandeau pleine largeur en ouverture. */
|
||||||
|
BANNER,
|
||||||
|
/** Planche pleine page, à fond perdu, en ouverture (l'image est recadrée au format de la page). */
|
||||||
|
FULL_PAGE,
|
||||||
|
/** Fondue dans le bas de la dernière page, si la place s'y prête ; sinon image encadrée en fin de texte. */
|
||||||
|
FADE_BOTTOM,
|
||||||
|
/** Bandeau d'ouverture à fond perdu en haut, bord inférieur fondu dans la page. */
|
||||||
|
FADE_TOP;
|
||||||
|
|
||||||
|
/** Placement nommé ; {@link #AUTO} pour une valeur absente ou inconnue (bundle plus récent, saisie libre). */
|
||||||
|
public static ImagePlacement of(String name) {
|
||||||
|
if (name == null || name.isBlank()) return AUTO;
|
||||||
|
try {
|
||||||
|
return valueOf(name.trim().toUpperCase(Locale.ROOT));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return AUTO;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Placement d'une image d'après la carte de sa galerie ({@link #AUTO} si elle n'y figure pas). */
|
||||||
|
public static ImagePlacement of(Map<String, String> placements, String imageId) {
|
||||||
|
return placements == null || imageId == null ? AUTO : of(placements.get(imageId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Carte nettoyée, telle qu'on la stocke : seulement des images de la galerie, des placements
|
||||||
|
* connus, et rien pour {@link #AUTO} (c'est l'absence d'entrée). Ordre de la galerie.
|
||||||
|
*/
|
||||||
|
public static Map<String, String> sanitize(Map<String, String> placements, Collection<String> imageIds) {
|
||||||
|
Map<String, String> clean = new LinkedHashMap<>();
|
||||||
|
if (placements == null || imageIds == null) return clean;
|
||||||
|
for (String id : imageIds) {
|
||||||
|
ImagePlacement placement = of(placements, id);
|
||||||
|
if (placement != AUTO) clean.put(id, placement.name());
|
||||||
|
}
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import lombok.Data;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité de domaine représentant une Scene.
|
* Entité de domaine représentant une Scene.
|
||||||
@@ -19,6 +21,13 @@ public class Scene {
|
|||||||
private String name;
|
private String name;
|
||||||
private String description; // = Description courte dans l'UI
|
private String description; // = Description courte dans l'UI
|
||||||
private String chapterId; // Référence vers le Chapter parent
|
private String chapterId; // Référence vers le Chapter parent
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rôle de la scène dans la méthode guidée du chapitre (« room3 », « conclusion »…), ou
|
||||||
|
* {@code null}. Un rôle est tenu par une seule scène du chapitre. Posé par l'assistant ou
|
||||||
|
* par {@code SceneService.setGuidedRole} ; une mise à jour ordinaire ne le touche pas.
|
||||||
|
*/
|
||||||
|
private String guidedRole;
|
||||||
private int order; // Ordre de la scène dans le chapitre
|
private int order; // Ordre de la scène dans le chapitre
|
||||||
|
|
||||||
/** Cle d'icone choisie par l'utilisateur (cf. CAMPAIGN_ICON_OPTIONS cote front). */
|
/** Cle d'icone choisie par l'utilisateur (cf. CAMPAIGN_ICON_OPTIONS cote front). */
|
||||||
@@ -74,6 +83,13 @@ public class Scene {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement voulu dans le livret PDF pour certaines de ces illustrations : id d'image →
|
||||||
|
* nom d'un {@link ImagePlacement}. Une image absente de la carte suit les règles par défaut.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* "Battlemaps" de la scene destinees a l'export Foundry : liste de paires
|
* "Battlemaps" de la scene destinees a l'export Foundry : liste de paires
|
||||||
* { media + sidecar } etiquetees ({@link SceneBattlemap}). Plusieurs cartes =
|
* { media + sidecar } etiquetees ({@link SceneBattlemap}). Plusieurs cartes =
|
||||||
|
|||||||
@@ -68,6 +68,13 @@ public class GameSystem {
|
|||||||
*/
|
*/
|
||||||
private String foundryActorType;
|
private String foundryActorType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Modèle de sort : champs propres au système portés par chaque {@link Spell} du
|
||||||
|
* catalogue (portée, durée, coût…), en texte ou en nombre. Géré avec le catalogue
|
||||||
|
* (cf. SpellCatalogService), pas avec les modèles de fiche.
|
||||||
|
*/
|
||||||
|
private List<TemplateField> spellTemplate;
|
||||||
|
|
||||||
/** Auteur déclaré — futur marketplace. Nullable. */
|
/** Auteur déclaré — futur marketplace. Nullable. */
|
||||||
private String author;
|
private String author;
|
||||||
|
|
||||||
@@ -120,6 +127,16 @@ public class GameSystem {
|
|||||||
enemyTemplate = validateAndCopy(fields);
|
enemyTemplate = validateAndCopy(fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void replaceSpellTemplate(List<TemplateField> fields) {
|
||||||
|
spellTemplate = validateAndCopy(fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Jamais null : un système sans modèle de sort a une liste vide. */
|
||||||
|
public List<TemplateField> getSpellTemplate() {
|
||||||
|
if (spellTemplate == null) spellTemplate = new ArrayList<>();
|
||||||
|
return spellTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Helpers privés ----------------------------------------------------
|
// --- Helpers privés ----------------------------------------------------
|
||||||
|
|
||||||
private static List<TemplateField> appendField(List<TemplateField> current, TemplateField field) {
|
private static List<TemplateField> appendField(List<TemplateField> current, TemplateField field) {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Une situation d'entraînement aux règles et son corrigé.
|
||||||
|
* <p>
|
||||||
|
* {@code excerpt} est un passage des règles du système, retrouvé mot pour mot dans la
|
||||||
|
* section {@code section} ; {@code ruling} est la lecture qu'en fait l'IA. {@code sceneId}
|
||||||
|
* et {@code sceneName} désignent la scène qui sert de décor ({@code null} et vide si la
|
||||||
|
* situation n'est rattachée à aucune scène).
|
||||||
|
*/
|
||||||
|
public record RuleDrill(String sceneId, String sceneName, String situation,
|
||||||
|
String section, String excerpt, String ruling) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/** Comparaison de la décision écrite par le MJ avec les règles : un verdict et un retour court. */
|
||||||
|
public record RuleDrillReview(Verdict verdict, String feedback) {
|
||||||
|
|
||||||
|
public enum Verdict {
|
||||||
|
/** La décision applique la règle. */
|
||||||
|
RIGHT,
|
||||||
|
/** Elle va dans le bon sens mais oublie ou déforme un point. */
|
||||||
|
PARTIAL,
|
||||||
|
/** Elle applique autre chose. */
|
||||||
|
OFF;
|
||||||
|
|
||||||
|
/** Nom échangé avec le front et le Brain ({@code right}, {@code partial}, {@code off}). */
|
||||||
|
public String wireName() {
|
||||||
|
return name().toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Optional<Verdict> fromWireName(String value) {
|
||||||
|
if (value == null) return Optional.empty();
|
||||||
|
String wanted = value.trim().toLowerCase(Locale.ROOT);
|
||||||
|
for (Verdict verdict : values()) {
|
||||||
|
if (verdict.wireName().equals(wanted)) return Optional.of(verdict);
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.shared.template.FieldType;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Champ proposé pour un modèle de fiche, tiré des règles du système.
|
||||||
|
* <p>
|
||||||
|
* C'est une PROPOSITION : rien n'est enregistré. Le MJ choisit les champs à ajouter
|
||||||
|
* à son modèle, puis enregistre le système comme d'habitude.
|
||||||
|
*
|
||||||
|
* @param name nom du champ, dans les termes des règles
|
||||||
|
* @param type {@code TEXT}, {@code NUMBER} ou {@code KEY_VALUE_LIST}
|
||||||
|
* @param labels lignes d'une liste de valeurs (vide pour les autres types)
|
||||||
|
* @param source titre de la section de règles d'où vient le champ, ou chaîne vide
|
||||||
|
*/
|
||||||
|
public record SheetFieldProposal(String name, FieldType type, List<String> labels, String source) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche dont on propose le modèle à partir des règles : PJ, PNJ ou ennemi.
|
||||||
|
* <p>
|
||||||
|
* Chaque fiche porte ses alias de sections de règles, par ordre de priorité : les
|
||||||
|
* sections du premier groupe sont envoyées à l'IA d'abord, puis celles des suivants
|
||||||
|
* tant que le budget de taille le permet. Comparaison par {@code contains} sur le
|
||||||
|
* titre en minuscules, comme {@link GenerationIntent}.
|
||||||
|
*/
|
||||||
|
public enum SheetKind {
|
||||||
|
|
||||||
|
CHARACTER("character", List.of(
|
||||||
|
Set.of("personnage", "character", "caractéristique", "caracteristique",
|
||||||
|
"attribut", "attribute", "abilit", "stats"),
|
||||||
|
Set.of("compétence", "competence", "skill", "classe", "class",
|
||||||
|
"progression", "niveau", "level"),
|
||||||
|
Set.of("combat", "équipement", "equipement", "equipment", "magie", "magic", "sort", "spell"))),
|
||||||
|
|
||||||
|
NPC("npc", List.of(
|
||||||
|
Set.of("pnj", "npc", "non-joueur", "non joueur", "non-player"),
|
||||||
|
Set.of("personnage", "character", "caractéristique", "caracteristique",
|
||||||
|
"attribut", "attribute", "abilit", "stats"),
|
||||||
|
Set.of("compétence", "competence", "skill", "combat", "maître", "maitre", "game master"))),
|
||||||
|
|
||||||
|
ENEMY("enemy", List.of(
|
||||||
|
Set.of("monstre", "monster", "créature", "creature", "ennemi", "enemy", "enemies",
|
||||||
|
"adversaire", "adversar", "bestiaire", "bestiary"),
|
||||||
|
Set.of("combat"),
|
||||||
|
Set.of("caractéristique", "caracteristique", "attribut", "attribute", "abilit", "stats",
|
||||||
|
"état", "etat", "condition")));
|
||||||
|
|
||||||
|
private final String wireName;
|
||||||
|
private final List<Set<String>> sectionAliases;
|
||||||
|
|
||||||
|
SheetKind(String wireName, List<Set<String>> sectionAliases) {
|
||||||
|
this.wireName = wireName;
|
||||||
|
this.sectionAliases = sectionAliases;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nom échangé avec le front et le Brain ({@code character}, {@code npc}, {@code enemy}). */
|
||||||
|
public String wireName() {
|
||||||
|
return wireName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Alias de titres de sections, du groupe le plus utile au moins utile. */
|
||||||
|
public List<Set<String>> sectionAliases() {
|
||||||
|
return sectionAliases;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Optional<SheetKind> fromWireName(String value) {
|
||||||
|
if (value == null) return Optional.empty();
|
||||||
|
String wanted = value.trim().toLowerCase(Locale.ROOT);
|
||||||
|
for (SheetKind kind : values()) {
|
||||||
|
if (kind.wireName.equals(wanted)) return Optional.of(kind);
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un sort du catalogue d'un système de jeu.
|
||||||
|
* <p>
|
||||||
|
* Même principe que les fiches du bestiaire : des champs communs à tous les systèmes
|
||||||
|
* (nom, niveau, école, description) + les valeurs des champs propres au système, dont la
|
||||||
|
* liste est {@link GameSystem#getSpellTemplate()} (portée, durée, coût…). Les règles de
|
||||||
|
* magie, elles, restent dans les sections de règles du système.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class Spell {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
/** Système de jeu auquel appartient ce sort. */
|
||||||
|
private String gameSystemId;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** Niveau, rang ou cercle — texte libre (« 3 », « Tour de magie », « Rang II »). Nullable. */
|
||||||
|
private String level;
|
||||||
|
|
||||||
|
/** École, liste ou tradition, pour classer (« Évocation », « Druide »). Nullable. */
|
||||||
|
private String school;
|
||||||
|
|
||||||
|
/** Ce que fait le sort. Nullable. */
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
/** Valeurs des champs du modèle de sort : nom du champ → valeur. Jamais null après construction. */
|
||||||
|
private Map<String, String> values;
|
||||||
|
|
||||||
|
/** Rang dans le catalogue. */
|
||||||
|
private int order;
|
||||||
|
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
public Map<String, String> getValues() {
|
||||||
|
if (values == null) values = new HashMap<>();
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie : l'IA qui prépare l'entraînement aux règles.
|
||||||
|
* <p>
|
||||||
|
* Les réponses sont des candidats bruts : la vérification des extraits contre les règles
|
||||||
|
* est faite par le service appelant, jamais par l'adapter.
|
||||||
|
*
|
||||||
|
* @throws com.loremind.domain.gamesystemcontext.ports.exceptions.RuleTrainingException
|
||||||
|
* si l'IA est injoignable ou répond de façon inexploitable
|
||||||
|
*/
|
||||||
|
public interface RuleTrainingCoach {
|
||||||
|
|
||||||
|
/** Une scène du scénario, résumée : le décor d'une situation. */
|
||||||
|
record SceneBrief(String name, String kind, String text) {}
|
||||||
|
|
||||||
|
/** Situation proposée. {@code scene} : rang de la scène dans la liste envoyée (à partir de 1), 0 si aucune. */
|
||||||
|
record DrillCandidate(int scene, String situation, String section, String excerpt, String ruling) {}
|
||||||
|
|
||||||
|
/** Prépare {@code count} situations, corrigé compris, à partir des sections de règles fournies. */
|
||||||
|
List<DrillCandidate> prepare(String systemName, Map<String, String> sections,
|
||||||
|
List<SceneBrief> scenes, int count, List<String> avoid);
|
||||||
|
|
||||||
|
/** Compare la décision du MJ aux règles de la section et au corrigé de la situation. */
|
||||||
|
RuleDrillReview review(String systemName, String sectionTitle, String sectionText,
|
||||||
|
String situation, String excerpt, String ruling, String answer);
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie : sorts connus d'une fiche (PJ, PNJ ou ennemi), comme liens vers des sorts
|
||||||
|
* du catalogue du système.
|
||||||
|
*/
|
||||||
|
public interface SheetSpellRepository {
|
||||||
|
|
||||||
|
/** Identifiants des sorts connus de la fiche, dans l'ordre choisi. */
|
||||||
|
List<String> findSpellIds(SheetKind kind, String ownerId);
|
||||||
|
|
||||||
|
/** Remplace les sorts connus de la fiche par cette liste, dans cet ordre. */
|
||||||
|
void replace(SheetKind kind, String ownerId, List<String> spellIds);
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.SheetProposalException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie : propose les champs d'une fiche (PJ, PNJ, ennemi) à partir de
|
||||||
|
* sections de règles. L'implémentation délègue à l'IA ; le domaine ne connaît ni
|
||||||
|
* HTTP ni le fournisseur.
|
||||||
|
*/
|
||||||
|
public interface SheetTemplateAdvisor {
|
||||||
|
|
||||||
|
/** Champ tel que renvoyé par l'IA, avant tri métier (type en texte libre). */
|
||||||
|
record Candidate(String name, String type, List<String> labels, String source) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param kind fiche concernée
|
||||||
|
* @param systemName nom du système de jeu (peut être vide)
|
||||||
|
* @param sections sections de règles utiles, {titre → contenu}, ordre préservé
|
||||||
|
* @param existingFieldNames champs déjà présents dans le modèle
|
||||||
|
* @return les champs proposés, non triés ; liste vide si les règles ne décrivent pas la fiche
|
||||||
|
* @throws SheetProposalException si l'IA est indisponible ou répond de façon inexploitable
|
||||||
|
*/
|
||||||
|
List<Candidate> propose(SheetKind kind, String systemName,
|
||||||
|
Map<String, String> sections, List<String> existingFieldNames);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie : relève les sorts décrits dans un morceau de règles (IA).
|
||||||
|
* <p>
|
||||||
|
* Le relevé n'est qu'une proposition : l'appelant vérifie chaque sort contre le texte
|
||||||
|
* envoyé avant de le montrer.
|
||||||
|
*/
|
||||||
|
public interface SpellProposer {
|
||||||
|
|
||||||
|
/** Un champ du modèle de sort du système. {@code number} : le champ attend un nombre. */
|
||||||
|
record SpellField(String name, boolean number) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un sort relevé, non vérifié. {@code excerpt} : passage du texte censé venir mot pour
|
||||||
|
* mot de la description du sort.
|
||||||
|
*/
|
||||||
|
record SpellCandidate(String name, String level, String school, String description,
|
||||||
|
Map<String, String> values, String excerpt) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param avoid noms de sorts déjà connus, à ne pas relever de nouveau
|
||||||
|
* @throws com.loremind.domain.gamesystemcontext.ports.exceptions.SpellProposalException
|
||||||
|
* si l'IA est indisponible ou si sa réponse est inexploitable
|
||||||
|
*/
|
||||||
|
List<SpellCandidate> extract(String systemName, String sectionTitle, String text,
|
||||||
|
List<SpellField> fields, List<String> avoid);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.Spell;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie pour la persistance du catalogue de sorts d'un système de jeu.
|
||||||
|
*/
|
||||||
|
public interface SpellRepository {
|
||||||
|
|
||||||
|
Spell save(Spell spell);
|
||||||
|
|
||||||
|
/** Sorts d'un système, dans l'ordre du catalogue. */
|
||||||
|
List<Spell> findByGameSystemId(String gameSystemId);
|
||||||
|
|
||||||
|
void deleteById(String id);
|
||||||
|
|
||||||
|
/** Parmi ces identifiants, ceux qui désignent un sort existant. */
|
||||||
|
List<String> existingIds(List<String> ids);
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports.exceptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erreur de domaine : l'entraînement aux règles n'a pas pu être préparé ou corrigé (Brain
|
||||||
|
* injoignable, fournisseur IA en erreur, réponse inexploitable). Les couches supérieures
|
||||||
|
* la traduisent en réponse HTTP sans connaître l'adapter concret.
|
||||||
|
*/
|
||||||
|
public class RuleTrainingException extends RuntimeException {
|
||||||
|
|
||||||
|
public RuleTrainingException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RuleTrainingException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports.exceptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erreur de domaine : la proposition d'un modèle de fiche a échoué (Brain
|
||||||
|
* injoignable, fournisseur IA en erreur, réponse inexploitable). Les couches
|
||||||
|
* supérieures la traduisent en réponse HTTP sans connaître l'adapter concret.
|
||||||
|
*/
|
||||||
|
public class SheetProposalException extends RuntimeException {
|
||||||
|
|
||||||
|
public SheetProposalException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SheetProposalException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports.exceptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erreur de domaine : le relevé des sorts dans les règles n'a pas pu se faire (Brain
|
||||||
|
* injoignable, fournisseur IA en erreur, réponse inexploitable). Les couches supérieures
|
||||||
|
* la traduisent en réponse HTTP sans connaître l'adapter concret.
|
||||||
|
*/
|
||||||
|
public class SpellProposalException extends RuntimeException {
|
||||||
|
|
||||||
|
public SpellProposalException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SpellProposalException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,8 +69,10 @@ public class BrainAiChatClient implements AiChatProvider {
|
|||||||
try {
|
try {
|
||||||
// blockLast() : transforme le flux réactif en appel bloquant conforme
|
// blockLast() : transforme le flux réactif en appel bloquant conforme
|
||||||
// au contrat synchrone du port. L'appelant choisit le thread.
|
// au contrat synchrone du port. L'appelant choisit le thread.
|
||||||
|
// Délai entre deux évènements : un modèle à raisonnement réfléchit parfois
|
||||||
|
// plus de 100 s avant le premier mot de sa réponse.
|
||||||
flux
|
flux
|
||||||
.timeout(Duration.ofSeconds(120))
|
.timeout(Duration.ofSeconds(300))
|
||||||
.doOnNext(sse -> handleEvent(sse, callbacks))
|
.doOnNext(sse -> handleEvent(sse, callbacks))
|
||||||
.blockLast();
|
.blockLast();
|
||||||
callbacks.onComplete().run();
|
callbacks.onComplete().run();
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview.Verdict;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RuleTrainingCoach;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.RuleTrainingException;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter de sortie : entraînement aux règles via le Brain ({@code POST /generate/rule-drills}
|
||||||
|
* et {@code POST /generate/rule-drill-review}, one-shot). La langue de l'interface est relayée
|
||||||
|
* par l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainRuleTrainingClient implements RuleTrainingCoach {
|
||||||
|
|
||||||
|
private static final String DRILLS_PATH = "/generate/rule-drills";
|
||||||
|
private static final String REVIEW_PATH = "/generate/rule-drill-review";
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public BrainRuleTrainingClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<DrillCandidate> prepare(String systemName, Map<String, String> sections,
|
||||||
|
List<SceneBrief> scenes, int count, List<String> avoid) {
|
||||||
|
List<Map<String, String>> sceneDtos = new ArrayList<>();
|
||||||
|
for (SceneBrief scene : scenes == null ? List.<SceneBrief>of() : scenes) {
|
||||||
|
Map<String, String> dto = new LinkedHashMap<>();
|
||||||
|
dto.put("name", nz(scene.name()));
|
||||||
|
dto.put("kind", nz(scene.kind()));
|
||||||
|
dto.put("text", nz(scene.text()));
|
||||||
|
sceneDtos.add(dto);
|
||||||
|
}
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("system_name", nz(systemName));
|
||||||
|
req.put("sections", sections == null ? Map.of() : sections);
|
||||||
|
req.put("scenes", sceneDtos);
|
||||||
|
req.put("count", count);
|
||||||
|
req.put("avoid", avoid == null ? List.of() : avoid);
|
||||||
|
return parseDrills(call(DRILLS_PATH, req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public RuleDrillReview review(String systemName, String sectionTitle, String sectionText,
|
||||||
|
String situation, String excerpt, String ruling, String answer) {
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("system_name", nz(systemName));
|
||||||
|
req.put("section_title", nz(sectionTitle));
|
||||||
|
req.put("section_text", nz(sectionText));
|
||||||
|
req.put("situation", nz(situation));
|
||||||
|
req.put("excerpt", nz(excerpt));
|
||||||
|
req.put("ruling", nz(ruling));
|
||||||
|
req.put("answer", nz(answer));
|
||||||
|
return parseReview(call(REVIEW_PATH, req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> call(String path, Map<String, Object> req) {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
Map<String, Object> resp;
|
||||||
|
try {
|
||||||
|
resp = restTemplate.postForObject(baseUrl + path, new HttpEntity<>(req, headers), Map.class);
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
throw new RuleTrainingException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
|
} catch (RestClientResponseException e) {
|
||||||
|
throw new RuleTrainingException(
|
||||||
|
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuleTrainingException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||||
|
}
|
||||||
|
if (resp == null) throw new RuleTrainingException("Le Brain a renvoyé une réponse vide.");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lecture tolérante : une entrée mal formée est ignorée, la vérification est faite en amont. */
|
||||||
|
static List<DrillCandidate> parseDrills(Map<String, Object> resp) {
|
||||||
|
List<DrillCandidate> out = new ArrayList<>();
|
||||||
|
if (!(resp.get("drills") instanceof List<?> drills)) return out;
|
||||||
|
for (Object entry : drills) {
|
||||||
|
if (!(entry instanceof Map<?, ?> drill)) continue;
|
||||||
|
out.add(new DrillCandidate(
|
||||||
|
drill.get("scene") instanceof Number n ? n.intValue() : 0,
|
||||||
|
text(drill.get("situation")),
|
||||||
|
text(drill.get("section")),
|
||||||
|
text(drill.get("excerpt")),
|
||||||
|
text(drill.get("ruling"))));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
static RuleDrillReview parseReview(Map<String, Object> resp) {
|
||||||
|
Verdict verdict = Verdict.fromWireName(text(resp.get("verdict")))
|
||||||
|
.orElseThrow(() -> new RuleTrainingException("Le Brain a renvoyé une comparaison inexploitable."));
|
||||||
|
String feedback = text(resp.get("feedback")).strip();
|
||||||
|
if (feedback.isEmpty()) {
|
||||||
|
throw new RuleTrainingException("Le Brain a renvoyé une comparaison inexploitable.");
|
||||||
|
}
|
||||||
|
return new RuleDrillReview(verdict, feedback);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(Object value) {
|
||||||
|
return value == null ? "" : value.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String value) {
|
||||||
|
return value == null ? "" : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetTemplateAdvisor;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.SheetProposalException;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter de sortie : proposition d'un modèle de fiche via le Brain
|
||||||
|
* ({@code POST /generate/sheet-template}, one-shot). La langue de l'interface est relayée par
|
||||||
|
* l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainSheetTemplateClient implements SheetTemplateAdvisor {
|
||||||
|
|
||||||
|
private static final String PATH = "/generate/sheet-template";
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public BrainSheetTemplateClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Candidate> propose(SheetKind kind, String systemName,
|
||||||
|
Map<String, String> sections, List<String> existingFieldNames) {
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("sheet", kind.wireName());
|
||||||
|
req.put("system_name", systemName == null ? "" : systemName);
|
||||||
|
req.put("sections", sections == null ? Map.of() : sections);
|
||||||
|
req.put("existing_fields", existingFieldNames == null ? List.of() : existingFieldNames);
|
||||||
|
return parse(call(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> call(Map<String, Object> req) {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
Map<String, Object> resp;
|
||||||
|
try {
|
||||||
|
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
throw new SheetProposalException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
|
} catch (RestClientResponseException e) {
|
||||||
|
throw new SheetProposalException(
|
||||||
|
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new SheetProposalException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||||
|
}
|
||||||
|
if (resp == null) throw new SheetProposalException("Le Brain a renvoyé une réponse vide.");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lecture tolérante : une entrée mal formée est ignorée, le tri métier est fait en amont. */
|
||||||
|
static List<Candidate> parse(Map<String, Object> resp) {
|
||||||
|
List<Candidate> out = new ArrayList<>();
|
||||||
|
if (!(resp.get("fields") instanceof List<?> fields)) return out;
|
||||||
|
for (Object entry : fields) {
|
||||||
|
if (!(entry instanceof Map<?, ?> field) || field.get("name") == null) continue;
|
||||||
|
List<String> labels = new ArrayList<>();
|
||||||
|
if (field.get("labels") instanceof List<?> rawLabels) {
|
||||||
|
rawLabels.forEach(l -> { if (l != null) labels.add(l.toString()); });
|
||||||
|
}
|
||||||
|
out.add(new Candidate(
|
||||||
|
field.get("name").toString(),
|
||||||
|
field.get("type") == null ? null : field.get("type").toString(),
|
||||||
|
labels,
|
||||||
|
field.get("source") == null ? "" : field.get("source").toString()));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import java.io.IOException;
|
|||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,6 +40,9 @@ public class BrainSidecar {
|
|||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(BrainSidecar.class);
|
private static final Logger log = LoggerFactory.getLogger(BrainSidecar.class);
|
||||||
|
|
||||||
|
/** Au-dela, le journal du Brain est archive au demarrage (un seul fichier precedent garde). */
|
||||||
|
static final long MAX_LOG_BYTES = 5L * 1024 * 1024;
|
||||||
|
|
||||||
private final BrainSidecarProperties props;
|
private final BrainSidecarProperties props;
|
||||||
private final String internalSecret;
|
private final String internalSecret;
|
||||||
|
|
||||||
@@ -65,7 +69,10 @@ public class BrainSidecar {
|
|||||||
try {
|
try {
|
||||||
ProcessBuilder pb = new ProcessBuilder(props.getCommand());
|
ProcessBuilder pb = new ProcessBuilder(props.getCommand());
|
||||||
pb.redirectErrorStream(true);
|
pb.redirectErrorStream(true);
|
||||||
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
|
File logFile = prepareLogFile(props.getLogFile(), MAX_LOG_BYTES);
|
||||||
|
pb.redirectOutput(logFile != null
|
||||||
|
? ProcessBuilder.Redirect.appendTo(logFile)
|
||||||
|
: ProcessBuilder.Redirect.INHERIT);
|
||||||
|
|
||||||
File workingDir = resolveWorkingDir();
|
File workingDir = resolveWorkingDir();
|
||||||
if (workingDir != null) {
|
if (workingDir != null) {
|
||||||
@@ -78,8 +85,9 @@ public class BrainSidecar {
|
|||||||
|
|
||||||
Process started = pb.start();
|
Process started = pb.start();
|
||||||
this.process.set(started);
|
this.process.set(started);
|
||||||
log.info("[Brain] Sidecar demarre (pid={}, cwd={}).",
|
log.info("[Brain] Sidecar demarre (pid={}, cwd={}, journal={}).",
|
||||||
started.pid(), workingDir != null ? workingDir : "<heritee>");
|
started.pid(), workingDir != null ? workingDir : "<heritee>",
|
||||||
|
logFile != null ? logFile : "<sortie heritee>");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
||||||
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
||||||
@@ -106,6 +114,35 @@ public class BrainSidecar {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare le fichier journal du Brain : cree son dossier et, si le fichier depasse
|
||||||
|
* {@code maxBytes}, l'archive en {@code <nom>.1} (l'archive precedente est remplacee).
|
||||||
|
* Le journal reste ainsi borne sans tache de fond.
|
||||||
|
*
|
||||||
|
* @return le fichier a utiliser, ou {@code null} si aucun n'est configure ou s'il
|
||||||
|
* ne peut pas etre prepare (la sortie reste alors heritee du Core)
|
||||||
|
*/
|
||||||
|
static File prepareLogFile(String logFile, long maxBytes) {
|
||||||
|
if (logFile == null || logFile.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Path path = Path.of(logFile).toAbsolutePath().normalize();
|
||||||
|
try {
|
||||||
|
if (path.getParent() != null) {
|
||||||
|
Files.createDirectories(path.getParent());
|
||||||
|
}
|
||||||
|
if (Files.isRegularFile(path) && Files.size(path) > maxBytes) {
|
||||||
|
Files.move(path, path.resolveSibling(path.getFileName() + ".1"),
|
||||||
|
StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("[Brain] Journal {} inutilisable : {}. Sortie du Brain non conservee.",
|
||||||
|
path, e.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return path.toFile();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resout (et cree au besoin) le repertoire de travail du Brain. Le Brain y
|
* Resout (et cree au besoin) le repertoire de travail du Brain. Le Brain y
|
||||||
* ecrit son dossier {@code data/} (index vectoriel, settings.json).
|
* ecrit son dossier {@code data/} (index vectoriel, settings.json).
|
||||||
|
|||||||
@@ -42,6 +42,13 @@ public class BrainSidecarProperties {
|
|||||||
*/
|
*/
|
||||||
private String workingDir;
|
private String workingDir;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fichier ou ecrire la sortie du Brain (journal date : requetes, erreurs du
|
||||||
|
* fournisseur IA, traces Python). Vide = sortie heritee du Core, donc perdue
|
||||||
|
* quand l'application tourne sans console.
|
||||||
|
*/
|
||||||
|
private String logFile;
|
||||||
|
|
||||||
public boolean isEnabled() { return enabled; }
|
public boolean isEnabled() { return enabled; }
|
||||||
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||||
|
|
||||||
@@ -50,4 +57,7 @@ public class BrainSidecarProperties {
|
|||||||
|
|
||||||
public String getWorkingDir() { return workingDir; }
|
public String getWorkingDir() { return workingDir; }
|
||||||
public void setWorkingDir(String workingDir) { this.workingDir = workingDir; }
|
public void setWorkingDir(String workingDir) { this.workingDir = workingDir; }
|
||||||
|
|
||||||
|
public String getLogFile() { return logFile; }
|
||||||
|
public void setLogFile(String logFile) { this.logFile = logFile; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellProposer;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.SpellProposalException;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter de sortie : relevé des sorts dans un morceau de règles via le Brain
|
||||||
|
* ({@code POST /generate/spell-extraction}, one-shot).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainSpellProposalClient implements SpellProposer {
|
||||||
|
|
||||||
|
private static final String PATH = "/generate/spell-extraction";
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public BrainSpellProposalClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public List<SpellCandidate> extract(String systemName, String sectionTitle, String text,
|
||||||
|
List<SpellField> fields, List<String> avoid) {
|
||||||
|
List<Map<String, String>> fieldDtos = new ArrayList<>();
|
||||||
|
for (SpellField field : fields == null ? List.<SpellField>of() : fields) {
|
||||||
|
Map<String, String> dto = new LinkedHashMap<>();
|
||||||
|
dto.put("name", field.name());
|
||||||
|
dto.put("type", field.number() ? "NUMBER" : "TEXT");
|
||||||
|
fieldDtos.add(dto);
|
||||||
|
}
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("system_name", nz(systemName));
|
||||||
|
req.put("section_title", nz(sectionTitle));
|
||||||
|
req.put("text", nz(text));
|
||||||
|
req.put("fields", fieldDtos);
|
||||||
|
req.put("avoid", avoid == null ? List.of() : avoid);
|
||||||
|
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
Map<String, Object> resp;
|
||||||
|
try {
|
||||||
|
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
throw new SpellProposalException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
|
} catch (RestClientResponseException e) {
|
||||||
|
throw new SpellProposalException(
|
||||||
|
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new SpellProposalException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||||
|
}
|
||||||
|
if (resp == null) throw new SpellProposalException("Le Brain a renvoyé une réponse vide.");
|
||||||
|
return parse(resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lecture tolérante : une entrée mal formée est ignorée, la vérification est faite en amont. */
|
||||||
|
static List<SpellCandidate> parse(Map<String, Object> resp) {
|
||||||
|
List<SpellCandidate> out = new ArrayList<>();
|
||||||
|
if (!(resp.get("spells") instanceof List<?> spells)) return out;
|
||||||
|
for (Object entry : spells) {
|
||||||
|
if (!(entry instanceof Map<?, ?> spell)) continue;
|
||||||
|
Map<String, String> values = new LinkedHashMap<>();
|
||||||
|
if (spell.get("values") instanceof Map<?, ?> raw) {
|
||||||
|
raw.forEach((key, value) -> {
|
||||||
|
if (key != null && value != null) values.put(key.toString(), value.toString());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.add(new SpellCandidate(text(spell.get("name")), text(spell.get("level")), text(spell.get("school")),
|
||||||
|
text(spell.get("description")), values, text(spell.get("excerpt"))));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(Object value) {
|
||||||
|
return value == null ? "" : value.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String value) {
|
||||||
|
return value == null ? "" : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package com.loremind.infrastructure.persistence.entity;
|
|||||||
|
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
@@ -12,6 +13,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité JPA pour la persistance des Arcs en base de données PostgreSQL.
|
* Entité JPA pour la persistance des Arcs en base de données PostgreSQL.
|
||||||
@@ -93,6 +96,12 @@ public class ArcJpaEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Placement de certaines illustrations dans le livret PDF (id d'image → placement). JSON dans colonne TEXT. */
|
||||||
|
@Column(name = "illustration_placements", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
|||||||
+13
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.infrastructure.persistence.entity;
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -10,6 +11,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité JPA pour la persistance des Chapters en base de données PostgreSQL.
|
* Entité JPA pour la persistance des Chapters en base de données PostgreSQL.
|
||||||
@@ -51,6 +54,10 @@ public class ChapterJpaEntity {
|
|||||||
@Column(name = "narrative_stakes", columnDefinition = "TEXT")
|
@Column(name = "narrative_stakes", columnDefinition = "TEXT")
|
||||||
private String narrativeStakes;
|
private String narrativeStakes;
|
||||||
|
|
||||||
|
/** Méthode guidée suivie par le chapitre (V30), ou null. */
|
||||||
|
@Column(name = "guided_method", length = 64)
|
||||||
|
private String guidedMethod;
|
||||||
|
|
||||||
@Column(name = "related_page_ids", columnDefinition = "TEXT")
|
@Column(name = "related_page_ids", columnDefinition = "TEXT")
|
||||||
@Convert(converter = StringListJsonConverter.class)
|
@Convert(converter = StringListJsonConverter.class)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
@@ -61,6 +68,12 @@ public class ChapterJpaEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Placement de certaines illustrations dans le livret PDF (id d'image → placement). JSON dans colonne TEXT. */
|
||||||
|
@Column(name = "illustration_placements", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
|||||||
+5
@@ -55,6 +55,11 @@ public class GameSystemJpaEntity {
|
|||||||
@Column(name = "enemy_template", columnDefinition = "TEXT")
|
@Column(name = "enemy_template", columnDefinition = "TEXT")
|
||||||
private List<TemplateField> enemyTemplate;
|
private List<TemplateField> enemyTemplate;
|
||||||
|
|
||||||
|
/** Modèle de sort (champs propres au système de chaque sort du catalogue), en JSON. Nullable. */
|
||||||
|
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||||
|
@Column(name = "spell_template", columnDefinition = "TEXT")
|
||||||
|
private List<TemplateField> spellTemplate;
|
||||||
|
|
||||||
/** Type d'acteur Foundry pour les ennemis maison (import de structure). Nullable. */
|
/** Type d'acteur Foundry pour les ennemis maison (import de structure). Nullable. */
|
||||||
@Column(name = "foundry_actor_type")
|
@Column(name = "foundry_actor_type")
|
||||||
private String foundryActorType;
|
private String foundryActorType;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
|||||||
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.QuestNodeListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.QuestNodeListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -14,6 +15,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité JPA pour la persistance des Quests (table {@code quests}).
|
* Entité JPA pour la persistance des Quests (table {@code quests}).
|
||||||
@@ -83,6 +86,12 @@ public class QuestJpaEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Placement de certaines illustrations dans le livret PDF (id d'image → placement). JSON dans colonne TEXT. */
|
||||||
|
@Column(name = "illustration_placements", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import com.loremind.infrastructure.persistence.converter.RoomListJsonConverter;
|
|||||||
import com.loremind.infrastructure.persistence.converter.SceneBattlemapListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.SceneBattlemapListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.SceneBranchListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.SceneBranchListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -17,6 +18,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité JPA pour la persistance des Scenes en base de données PostgreSQL.
|
* Entité JPA pour la persistance des Scenes en base de données PostgreSQL.
|
||||||
@@ -48,6 +51,10 @@ public class SceneJpaEntity {
|
|||||||
@Column
|
@Column
|
||||||
private String icon;
|
private String icon;
|
||||||
|
|
||||||
|
/** Rôle de la scène dans la méthode guidée du chapitre (V30), ou null. */
|
||||||
|
@Column(name = "guided_role", length = 64)
|
||||||
|
private String guidedRole;
|
||||||
|
|
||||||
/** Type narratif du nœud (Niveau 2). Défaut GENERIC ; colonne dotée d'un default SQL (V13). */
|
/** Type narratif du nœud (Niveau 2). Défaut GENERIC ; colonne dotée d'un default SQL (V13). */
|
||||||
@Enumerated(EnumType.STRING)
|
@Enumerated(EnumType.STRING)
|
||||||
@Column(name = "scene_type", length = 32)
|
@Column(name = "scene_type", length = 32)
|
||||||
@@ -109,6 +116,12 @@ public class SceneJpaEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Placement de certaines illustrations dans le livret PDF (id d'image → placement). JSON dans colonne TEXT. */
|
||||||
|
@Column(name = "illustration_placements", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Battlemaps Foundry : liste de paires { media + sidecar } étiquetées
|
* Battlemaps Foundry : liste de paires { media + sidecar } étiquetées
|
||||||
* (variantes Jour/Nuit, étages…). JSON en TEXT via converter (V22).
|
* (variantes Jour/Nuit, étages…). JSON en TEXT via converter (V22).
|
||||||
|
|||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
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.Index;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import jakarta.persistence.UniqueConstraint;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un sort connu d'une fiche (table {@code sheet_spells}, V33) : lien entre une fiche (PJ, PNJ
|
||||||
|
* ou ennemi, désignée par son type et son identifiant) et un sort du catalogue du système.
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "sheet_spells",
|
||||||
|
indexes = @Index(name = "ix_sheet_spells_owner", columnList = "owner_type, owner_id"),
|
||||||
|
uniqueConstraints = @UniqueConstraint(name = "uk_sheet_spells_owner_spell",
|
||||||
|
columnNames = {"owner_type", "owner_id", "spell_id"}))
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SheetSpellJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/** {@code character}, {@code npc} ou {@code enemy}. */
|
||||||
|
@Column(name = "owner_type", nullable = false, length = 16)
|
||||||
|
private String ownerType;
|
||||||
|
|
||||||
|
@Column(name = "owner_id", nullable = false)
|
||||||
|
private Long ownerId;
|
||||||
|
|
||||||
|
@Column(name = "spell_id", nullable = false)
|
||||||
|
private Long spellId;
|
||||||
|
|
||||||
|
@Column(name = "\"order\"", nullable = false)
|
||||||
|
private int order;
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Convert;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.Index;
|
||||||
|
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.time.ZoneId;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entité JPA d'un sort du catalogue d'un système de jeu (table {@code spells}, V32).
|
||||||
|
* La suppression d'un système supprime ses sorts (clé étrangère en cascade).
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "spells", indexes = {
|
||||||
|
@Index(name = "ix_spells_game_system", columnList = "game_system_id")
|
||||||
|
})
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SpellJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(name = "game_system_id", nullable = false)
|
||||||
|
private Long gameSystemId;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Column(name = "level")
|
||||||
|
private String level;
|
||||||
|
|
||||||
|
@Column(name = "school")
|
||||||
|
private String school;
|
||||||
|
|
||||||
|
@Column(columnDefinition = "TEXT")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
/** Valeurs des champs du modèle de sort, en JSON. */
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Column(name = "field_values", columnDefinition = "TEXT")
|
||||||
|
private Map<String, String> values;
|
||||||
|
|
||||||
|
@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(ZoneId.systemDefault());
|
||||||
|
updatedAt = createdAt;
|
||||||
|
if (values == null) values = new HashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SheetSpellJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Modifying;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface SheetSpellJpaRepository extends JpaRepository<SheetSpellJpaEntity, Long> {
|
||||||
|
|
||||||
|
List<SheetSpellJpaEntity> findByOwnerTypeAndOwnerIdOrderByOrderAsc(String ownerType, Long ownerId);
|
||||||
|
|
||||||
|
/** Suppression directe en base : les liens suivants peuvent être réinsérés dans la même transaction. */
|
||||||
|
@Modifying(flushAutomatically = true, clearAutomatically = true)
|
||||||
|
@Query("delete from SheetSpellJpaEntity l where l.ownerType = :ownerType and l.ownerId = :ownerId")
|
||||||
|
void deleteByOwner(@Param("ownerType") String ownerType, @Param("ownerId") Long ownerId);
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SpellJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface SpellJpaRepository extends JpaRepository<SpellJpaEntity, Long> {
|
||||||
|
|
||||||
|
List<SpellJpaEntity> findByGameSystemIdOrderByOrderAsc(Long gameSystemId);
|
||||||
|
}
|
||||||
+7
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -86,6 +87,9 @@ public class PostgresArcRepository implements ArcRepository {
|
|||||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(jpaEntity.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(jpaEntity.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(jpaEntity.getCreatedAt())
|
.createdAt(jpaEntity.getCreatedAt())
|
||||||
.updatedAt(jpaEntity.getUpdatedAt())
|
.updatedAt(jpaEntity.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
@@ -114,6 +118,9 @@ public class PostgresArcRepository implements ArcRepository {
|
|||||||
.illustrationImageIds(arc.getIllustrationImageIds() != null
|
.illustrationImageIds(arc.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(arc.getIllustrationImageIds())
|
? new ArrayList<>(arc.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(arc.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(arc.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(arc.getCreatedAt())
|
.createdAt(arc.getCreatedAt())
|
||||||
.updatedAt(arc.getUpdatedAt())
|
.updatedAt(arc.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
+9
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -74,12 +75,16 @@ public class PostgresChapterRepository implements ChapterRepository {
|
|||||||
.gmNotes(jpaEntity.getGmNotes())
|
.gmNotes(jpaEntity.getGmNotes())
|
||||||
.playerObjectives(jpaEntity.getPlayerObjectives())
|
.playerObjectives(jpaEntity.getPlayerObjectives())
|
||||||
.narrativeStakes(jpaEntity.getNarrativeStakes())
|
.narrativeStakes(jpaEntity.getNarrativeStakes())
|
||||||
|
.guidedMethod(jpaEntity.getGuidedMethod())
|
||||||
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(jpaEntity.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(jpaEntity.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(jpaEntity.getCreatedAt())
|
.createdAt(jpaEntity.getCreatedAt())
|
||||||
.updatedAt(jpaEntity.getUpdatedAt())
|
.updatedAt(jpaEntity.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
@@ -97,12 +102,16 @@ public class PostgresChapterRepository implements ChapterRepository {
|
|||||||
.gmNotes(chapter.getGmNotes())
|
.gmNotes(chapter.getGmNotes())
|
||||||
.playerObjectives(chapter.getPlayerObjectives())
|
.playerObjectives(chapter.getPlayerObjectives())
|
||||||
.narrativeStakes(chapter.getNarrativeStakes())
|
.narrativeStakes(chapter.getNarrativeStakes())
|
||||||
|
.guidedMethod(chapter.getGuidedMethod())
|
||||||
.relatedPageIds(chapter.getRelatedPageIds() != null
|
.relatedPageIds(chapter.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(chapter.getRelatedPageIds())
|
? new ArrayList<>(chapter.getRelatedPageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
.illustrationImageIds(chapter.getIllustrationImageIds() != null
|
.illustrationImageIds(chapter.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(chapter.getIllustrationImageIds())
|
? new ArrayList<>(chapter.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(chapter.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(chapter.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(chapter.getCreatedAt())
|
.createdAt(chapter.getCreatedAt())
|
||||||
.updatedAt(chapter.getUpdatedAt())
|
.updatedAt(chapter.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
+4
@@ -70,6 +70,9 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.enemyTemplate(e.getEnemyTemplate() != null
|
.enemyTemplate(e.getEnemyTemplate() != null
|
||||||
? new java.util.ArrayList<>(e.getEnemyTemplate())
|
? new java.util.ArrayList<>(e.getEnemyTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
|
.spellTemplate(e.getSpellTemplate() != null
|
||||||
|
? new java.util.ArrayList<>(e.getSpellTemplate())
|
||||||
|
: new java.util.ArrayList<>())
|
||||||
.foundryActorType(e.getFoundryActorType())
|
.foundryActorType(e.getFoundryActorType())
|
||||||
.author(e.getAuthor())
|
.author(e.getAuthor())
|
||||||
.isPublic(e.isPublic())
|
.isPublic(e.isPublic())
|
||||||
@@ -95,6 +98,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.enemyTemplate(g.getEnemyTemplate() != null
|
.enemyTemplate(g.getEnemyTemplate() != null
|
||||||
? new java.util.ArrayList<>(g.getEnemyTemplate())
|
? new java.util.ArrayList<>(g.getEnemyTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
|
.spellTemplate(new java.util.ArrayList<>(g.getSpellTemplate()))
|
||||||
.foundryActorType(g.getFoundryActorType())
|
.foundryActorType(g.getFoundryActorType())
|
||||||
.author(g.getAuthor())
|
.author(g.getAuthor())
|
||||||
.isPublic(g.isPublic())
|
.isPublic(g.isPublic())
|
||||||
|
|||||||
+7
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -91,6 +92,9 @@ public class PostgresQuestRepository implements QuestRepository {
|
|||||||
.illustrationImageIds(e.getIllustrationImageIds() != null
|
.illustrationImageIds(e.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(e.getIllustrationImageIds())
|
? new ArrayList<>(e.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(e.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(e.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(e.getCreatedAt())
|
.createdAt(e.getCreatedAt())
|
||||||
.updatedAt(e.getUpdatedAt())
|
.updatedAt(e.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
@@ -121,6 +125,9 @@ public class PostgresQuestRepository implements QuestRepository {
|
|||||||
.illustrationImageIds(q.getIllustrationImageIds() != null
|
.illustrationImageIds(q.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(q.getIllustrationImageIds())
|
? new ArrayList<>(q.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(q.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(q.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(q.getCreatedAt())
|
.createdAt(q.getCreatedAt())
|
||||||
.updatedAt(q.getUpdatedAt())
|
.updatedAt(q.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
+9
@@ -9,6 +9,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,6 +83,7 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
||||||
.tactics(jpaEntity.getTactics())
|
.tactics(jpaEntity.getTactics())
|
||||||
.purpose(jpaEntity.getPurpose())
|
.purpose(jpaEntity.getPurpose())
|
||||||
|
.guidedRole(jpaEntity.getGuidedRole())
|
||||||
.enemies(jpaEntity.getEnemies())
|
.enemies(jpaEntity.getEnemies())
|
||||||
.enemyIds(jpaEntity.getEnemyIds() != null
|
.enemyIds(jpaEntity.getEnemyIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getEnemyIds())
|
? new ArrayList<>(jpaEntity.getEnemyIds())
|
||||||
@@ -92,6 +94,9 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(jpaEntity.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(jpaEntity.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.battlemaps(jpaEntity.getBattlemaps() != null
|
.battlemaps(jpaEntity.getBattlemaps() != null
|
||||||
? new ArrayList<>(jpaEntity.getBattlemaps())
|
? new ArrayList<>(jpaEntity.getBattlemaps())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
@@ -127,6 +132,7 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.combatDifficulty(scene.getCombatDifficulty())
|
.combatDifficulty(scene.getCombatDifficulty())
|
||||||
.tactics(scene.getTactics())
|
.tactics(scene.getTactics())
|
||||||
.purpose(scene.getPurpose())
|
.purpose(scene.getPurpose())
|
||||||
|
.guidedRole(scene.getGuidedRole())
|
||||||
.enemies(scene.getEnemies())
|
.enemies(scene.getEnemies())
|
||||||
.enemyIds(scene.getEnemyIds() != null
|
.enemyIds(scene.getEnemyIds() != null
|
||||||
? new ArrayList<>(scene.getEnemyIds())
|
? new ArrayList<>(scene.getEnemyIds())
|
||||||
@@ -137,6 +143,9 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.illustrationImageIds(scene.getIllustrationImageIds() != null
|
.illustrationImageIds(scene.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(scene.getIllustrationImageIds())
|
? new ArrayList<>(scene.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(scene.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(scene.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.battlemaps(scene.getBattlemaps() != null
|
.battlemaps(scene.getBattlemaps() != null
|
||||||
? new ArrayList<>(scene.getBattlemaps())
|
? new ArrayList<>(scene.getBattlemaps())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
|||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetSpellRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SheetSpellJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.SheetSpellJpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adaptateur JPA des sorts connus d'une fiche.
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class PostgresSheetSpellRepository implements SheetSpellRepository {
|
||||||
|
|
||||||
|
private final SheetSpellJpaRepository jpaRepository;
|
||||||
|
|
||||||
|
public PostgresSheetSpellRepository(SheetSpellJpaRepository jpaRepository) {
|
||||||
|
this.jpaRepository = jpaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> findSpellIds(SheetKind kind, String ownerId) {
|
||||||
|
return jpaRepository.findByOwnerTypeAndOwnerIdOrderByOrderAsc(kind.wireName(), Long.parseLong(ownerId)).stream()
|
||||||
|
.map(link -> link.getSpellId().toString())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public void replace(SheetKind kind, String ownerId, List<String> spellIds) {
|
||||||
|
Long owner = Long.parseLong(ownerId);
|
||||||
|
jpaRepository.deleteByOwner(kind.wireName(), owner);
|
||||||
|
List<SheetSpellJpaEntity> links = new ArrayList<>();
|
||||||
|
for (int i = 0; i < spellIds.size(); i++) {
|
||||||
|
links.add(SheetSpellJpaEntity.builder()
|
||||||
|
.ownerType(kind.wireName()).ownerId(owner)
|
||||||
|
.spellId(Long.parseLong(spellIds.get(i))).order(i)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
jpaRepository.saveAll(links);
|
||||||
|
}
|
||||||
|
}
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.Spell;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SpellJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.SpellJpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adaptateur JPA du catalogue de sorts.
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class PostgresSpellRepository implements SpellRepository {
|
||||||
|
|
||||||
|
private final SpellJpaRepository jpaRepository;
|
||||||
|
|
||||||
|
public PostgresSpellRepository(SpellJpaRepository jpaRepository) {
|
||||||
|
this.jpaRepository = jpaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Spell save(Spell spell) {
|
||||||
|
return toDomainEntity(jpaRepository.save(toJpaEntity(spell)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Spell> findByGameSystemId(String gameSystemId) {
|
||||||
|
return jpaRepository.findByGameSystemIdOrderByOrderAsc(Long.parseLong(gameSystemId)).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteById(String id) {
|
||||||
|
jpaRepository.deleteById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> existingIds(List<String> ids) {
|
||||||
|
if (ids == null || ids.isEmpty()) return List.of();
|
||||||
|
return jpaRepository.findAllById(ids.stream().map(Long::parseLong).toList()).stream()
|
||||||
|
.map(e -> e.getId().toString())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Spell toDomainEntity(SpellJpaEntity e) {
|
||||||
|
return Spell.builder()
|
||||||
|
.id(e.getId().toString())
|
||||||
|
.gameSystemId(e.getGameSystemId().toString())
|
||||||
|
.name(e.getName())
|
||||||
|
.level(e.getLevel())
|
||||||
|
.school(e.getSchool())
|
||||||
|
.description(e.getDescription())
|
||||||
|
.values(e.getValues() != null ? new HashMap<>(e.getValues()) : new HashMap<>())
|
||||||
|
.order(e.getOrder())
|
||||||
|
.createdAt(e.getCreatedAt())
|
||||||
|
.updatedAt(e.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private SpellJpaEntity toJpaEntity(Spell s) {
|
||||||
|
return SpellJpaEntity.builder()
|
||||||
|
.id(s.getId() != null ? Long.parseLong(s.getId()) : null)
|
||||||
|
.gameSystemId(Long.parseLong(s.getGameSystemId()))
|
||||||
|
.name(s.getName())
|
||||||
|
.level(s.getLevel())
|
||||||
|
.school(s.getSchool())
|
||||||
|
.description(s.getDescription())
|
||||||
|
.values(new HashMap<>(s.getValues()))
|
||||||
|
.order(s.getOrder())
|
||||||
|
.createdAt(s.getCreatedAt())
|
||||||
|
.updatedAt(s.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -133,6 +133,7 @@ class CampaignContentInserter {
|
|||||||
e.setHooks(d.hooks());
|
e.setHooks(d.hooks());
|
||||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
||||||
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
||||||
|
e.setIllustrationPlacements(IdRemapper.remapStringKeys(maps.imageMap, d.illustrationPlacements()));
|
||||||
maps.arcMap.put(d.id(), arcRepo.save(e).getId());
|
maps.arcMap.put(d.id(), arcRepo.save(e).getId());
|
||||||
}
|
}
|
||||||
result.count("arcs", maps.arcMap.size());
|
result.count("arcs", maps.arcMap.size());
|
||||||
@@ -216,8 +217,10 @@ class CampaignContentInserter {
|
|||||||
e.setGmNotes(d.gmNotes());
|
e.setGmNotes(d.gmNotes());
|
||||||
e.setPlayerObjectives(d.playerObjectives());
|
e.setPlayerObjectives(d.playerObjectives());
|
||||||
e.setNarrativeStakes(d.narrativeStakes());
|
e.setNarrativeStakes(d.narrativeStakes());
|
||||||
|
e.setGuidedMethod(d.guidedMethod());
|
||||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
||||||
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
||||||
|
e.setIllustrationPlacements(IdRemapper.remapStringKeys(maps.imageMap, d.illustrationPlacements()));
|
||||||
maps.chapterMap.put(d.id(), chapterRepo.save(e).getId());
|
maps.chapterMap.put(d.id(), chapterRepo.save(e).getId());
|
||||||
}
|
}
|
||||||
result.count("chapters", maps.chapterMap.size());
|
result.count("chapters", maps.chapterMap.size());
|
||||||
@@ -246,6 +249,7 @@ class CampaignContentInserter {
|
|||||||
e.setNarrativeStakes(d.narrativeStakes());
|
e.setNarrativeStakes(d.narrativeStakes());
|
||||||
e.setRelatedPageIds(d.relatedPageIds()); // remappé 2e passe
|
e.setRelatedPageIds(d.relatedPageIds()); // remappé 2e passe
|
||||||
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
||||||
|
e.setIllustrationPlacements(IdRemapper.remapStringKeys(maps.imageMap, d.illustrationPlacements()));
|
||||||
maps.questMap.put(d.id(), questRepo.save(e).getId());
|
maps.questMap.put(d.id(), questRepo.save(e).getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -317,11 +321,13 @@ class CampaignContentInserter {
|
|||||||
e.setEnemyIds(d.enemyIds()); // remappe en 2e passe
|
e.setEnemyIds(d.enemyIds()); // remappe en 2e passe
|
||||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
||||||
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
||||||
|
e.setIllustrationPlacements(IdRemapper.remapStringKeys(maps.imageMap, d.illustrationPlacements()));
|
||||||
e.setBattlemaps(resolveBattlemaps(d, maps));
|
e.setBattlemaps(resolveBattlemaps(d, maps));
|
||||||
e.setGraphX(d.graphX());
|
e.setGraphX(d.graphX());
|
||||||
e.setGraphY(d.graphY());
|
e.setGraphY(d.graphY());
|
||||||
e.setTactics(d.tactics());
|
e.setTactics(d.tactics());
|
||||||
e.setPurpose(d.purpose());
|
e.setPurpose(d.purpose());
|
||||||
|
e.setGuidedRole(d.guidedRole());
|
||||||
e.setBranches(d.branches()); // remappe en 2e passe
|
e.setBranches(d.branches()); // remappe en 2e passe
|
||||||
// Rooms : l'id (UUID) et les branches restent tels quels ; seules leurs refs
|
// Rooms : l'id (UUID) et les branches restent tels quels ; seules leurs refs
|
||||||
// d'images (galerie + plan) sont remappees vers les images importees.
|
// d'images (galerie + plan) sont remappees vers les images importees.
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import java.io.InputStream;
|
|||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.io.UncheckedIOException;
|
import java.io.UncheckedIOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.LinkedHashSet;
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
@@ -49,6 +50,8 @@ public class ExportService {
|
|||||||
private static final QuestNodeListJsonConverter NODE_CONVERTER = new QuestNodeListJsonConverter();
|
private static final QuestNodeListJsonConverter NODE_CONVERTER = new QuestNodeListJsonConverter();
|
||||||
|
|
||||||
private final GameSystemJpaRepository gameSystemRepo;
|
private final GameSystemJpaRepository gameSystemRepo;
|
||||||
|
private final SpellJpaRepository spellRepo;
|
||||||
|
private final SheetSpellJpaRepository sheetSpellRepo;
|
||||||
private final LoreJpaRepository loreRepo;
|
private final LoreJpaRepository loreRepo;
|
||||||
private final LoreNodeJpaRepository loreNodeRepo;
|
private final LoreNodeJpaRepository loreNodeRepo;
|
||||||
private final TemplateJpaRepository templateRepo;
|
private final TemplateJpaRepository templateRepo;
|
||||||
@@ -78,6 +81,8 @@ public class ExportService {
|
|||||||
private final String appVersion;
|
private final String appVersion;
|
||||||
|
|
||||||
public ExportService(GameSystemJpaRepository gameSystemRepo,
|
public ExportService(GameSystemJpaRepository gameSystemRepo,
|
||||||
|
SpellJpaRepository spellRepo,
|
||||||
|
SheetSpellJpaRepository sheetSpellRepo,
|
||||||
LoreJpaRepository loreRepo,
|
LoreJpaRepository loreRepo,
|
||||||
LoreNodeJpaRepository loreNodeRepo,
|
LoreNodeJpaRepository loreNodeRepo,
|
||||||
TemplateJpaRepository templateRepo,
|
TemplateJpaRepository templateRepo,
|
||||||
@@ -106,6 +111,8 @@ public class ExportService {
|
|||||||
ObjectMapper objectMapper,
|
ObjectMapper objectMapper,
|
||||||
@Nullable BuildProperties buildProperties) {
|
@Nullable BuildProperties buildProperties) {
|
||||||
this.gameSystemRepo = gameSystemRepo;
|
this.gameSystemRepo = gameSystemRepo;
|
||||||
|
this.spellRepo = spellRepo;
|
||||||
|
this.sheetSpellRepo = sheetSpellRepo;
|
||||||
this.loreRepo = loreRepo;
|
this.loreRepo = loreRepo;
|
||||||
this.loreNodeRepo = loreNodeRepo;
|
this.loreNodeRepo = loreNodeRepo;
|
||||||
this.templateRepo = templateRepo;
|
this.templateRepo = templateRepo;
|
||||||
@@ -177,7 +184,8 @@ public class ExportService {
|
|||||||
map(questProgressionRepo.findAll(), this::toQuestProgressionDto),
|
map(questProgressionRepo.findAll(), this::toQuestProgressionDto),
|
||||||
map(questRepo.findAll(), this::toQuestDto),
|
map(questRepo.findAll(), this::toQuestDto),
|
||||||
map(clockRepo.findAll(), this::toClockDto),
|
map(clockRepo.findAll(), this::toClockDto),
|
||||||
map(frontRepo.findAll(), this::toFrontDto));
|
map(frontRepo.findAll(), this::toFrontDto),
|
||||||
|
map(sheetSpellRepo.findAll(), this::toSheetSpellDto));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -230,7 +238,25 @@ public class ExportService {
|
|||||||
map(play.questProgressions(), this::toQuestProgressionDto),
|
map(play.questProgressions(), this::toQuestProgressionDto),
|
||||||
map(campaignQuests, this::toQuestDto),
|
map(campaignQuests, this::toQuestDto),
|
||||||
map(play.clocks(), this::toClockDto),
|
map(play.clocks(), this::toClockDto),
|
||||||
map(play.fronts(), this::toFrontDto));
|
map(play.fronts(), this::toFrontDto),
|
||||||
|
sheetSpellsOf(play.characters(), structure.npcs(), structure.enemies()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sorts connus des fiches exportées (les liens des autres campagnes restent dehors). */
|
||||||
|
private List<ContentExport.SheetSpellDto> sheetSpellsOf(List<CharacterJpaEntity> characters,
|
||||||
|
List<NpcJpaEntity> npcs, List<EnemyJpaEntity> enemies) {
|
||||||
|
Set<String> owners = new HashSet<>();
|
||||||
|
characters.forEach(c -> owners.add("character:" + c.getId()));
|
||||||
|
npcs.forEach(n -> owners.add("npc:" + n.getId()));
|
||||||
|
enemies.forEach(e -> owners.add("enemy:" + e.getId()));
|
||||||
|
return sheetSpellRepo.findAll().stream()
|
||||||
|
.filter(link -> owners.contains(link.getOwnerType() + ":" + link.getOwnerId()))
|
||||||
|
.map(this::toSheetSpellDto)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.SheetSpellDto toSheetSpellDto(SheetSpellJpaEntity e) {
|
||||||
|
return new ContentExport.SheetSpellDto(e.getOwnerType(), e.getOwnerId(), e.getSpellId(), e.getOrder());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Clôture structurelle de la campagne : arcs -> chapitres -> scènes, PNJ, ennemis, catalogues, tables. */
|
/** Clôture structurelle de la campagne : arcs -> chapitres -> scènes, PNJ, ennemis, catalogues, tables. */
|
||||||
@@ -578,7 +604,11 @@ public class ExportService {
|
|||||||
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
|
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
|
||||||
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic(),
|
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic(),
|
||||||
e.getRulesMarkdownEn());
|
e.getRulesMarkdownEn(), e.getSpellTemplate(),
|
||||||
|
spellRepo.findByGameSystemIdOrderByOrderAsc(e.getId()).stream()
|
||||||
|
.map(s -> new ContentExport.SpellDto(s.getName(), s.getLevel(), s.getSchool(),
|
||||||
|
s.getDescription(), s.getValues(), s.getId()))
|
||||||
|
.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
|
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
|
||||||
@@ -615,7 +645,7 @@ public class ExportService {
|
|||||||
e.getType() != null ? e.getType().name() : null,
|
e.getType() != null ? e.getType().name() : null,
|
||||||
e.getIcon(), e.getThemes(), e.getStakes(), e.getGmNotes(),
|
e.getIcon(), e.getThemes(), e.getStakes(), e.getGmNotes(),
|
||||||
e.getRewards(), e.getResolution(), e.getRelatedPageIds(),
|
e.getRewards(), e.getResolution(), e.getRelatedPageIds(),
|
||||||
e.getIllustrationImageIds(), e.getHiddenTruth(), e.getHooks());
|
e.getIllustrationImageIds(), e.getHiddenTruth(), e.getHooks(), e.getIllustrationPlacements());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.ChapterDto toChapterDto(ChapterJpaEntity e) {
|
private ContentExport.ChapterDto toChapterDto(ChapterJpaEntity e) {
|
||||||
@@ -624,7 +654,8 @@ public class ExportService {
|
|||||||
return new ContentExport.ChapterDto(e.getId(), e.getName(), e.getDescription(),
|
return new ContentExport.ChapterDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
e.getArcId(), e.getOrder(), "[]", e.getIcon(),
|
e.getArcId(), e.getOrder(), "[]", e.getIcon(),
|
||||||
e.getGmNotes(), e.getPlayerObjectives(), e.getNarrativeStakes(),
|
e.getGmNotes(), e.getPlayerObjectives(), e.getNarrativeStakes(),
|
||||||
e.getRelatedPageIds(), e.getIllustrationImageIds());
|
e.getRelatedPageIds(), e.getIllustrationImageIds(), e.getGuidedMethod(),
|
||||||
|
e.getIllustrationPlacements());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.QuestDto toQuestDto(QuestJpaEntity e) {
|
private ContentExport.QuestDto toQuestDto(QuestJpaEntity e) {
|
||||||
@@ -633,7 +664,7 @@ public class ExportService {
|
|||||||
PREREQ_CONVERTER.convertToDatabaseColumn(e.getPrerequisites()),
|
PREREQ_CONVERTER.convertToDatabaseColumn(e.getPrerequisites()),
|
||||||
NODE_CONVERTER.convertToDatabaseColumn(e.getNodes()),
|
NODE_CONVERTER.convertToDatabaseColumn(e.getNodes()),
|
||||||
e.getGmNotes(), e.getPlayerObjectives(), e.getNarrativeStakes(),
|
e.getGmNotes(), e.getPlayerObjectives(), e.getNarrativeStakes(),
|
||||||
e.getRelatedPageIds(), e.getIllustrationImageIds());
|
e.getRelatedPageIds(), e.getIllustrationImageIds(), e.getIllustrationPlacements());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.SceneDto toSceneDto(SceneJpaEntity e) {
|
private ContentExport.SceneDto toSceneDto(SceneJpaEntity e) {
|
||||||
@@ -644,7 +675,8 @@ public class ExportService {
|
|||||||
e.getEnemies(), e.getEnemyIds(), e.getRelatedPageIds(),
|
e.getEnemies(), e.getEnemyIds(), e.getRelatedPageIds(),
|
||||||
e.getIllustrationImageIds(), null, null, // legacy battlemap : plus émis
|
e.getIllustrationImageIds(), null, null, // legacy battlemap : plus émis
|
||||||
e.getBattlemaps(), e.getBranches(), e.getRooms(), e.getType(),
|
e.getBattlemaps(), e.getBranches(), e.getRooms(), e.getType(),
|
||||||
e.getGraphX(), e.getGraphY(), e.getTactics(), e.getPurpose());
|
e.getGraphX(), e.getGraphY(), e.getTactics(), e.getPurpose(), e.getGuidedRole(),
|
||||||
|
e.getIllustrationPlacements());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContentExport.CharacterDto toCharacterDto(CharacterJpaEntity e) {
|
private ContentExport.CharacterDto toCharacterDto(CharacterJpaEntity e) {
|
||||||
|
|||||||
@@ -45,6 +45,17 @@ final class IdRemapper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remap des CLES d'une carte « id → valeur » (ex. placement des illustrations : id d'image →
|
||||||
|
* placement) : chaque clé est réécrite via {@code map}, valeurs inchangées. Null → carte vide.
|
||||||
|
*/
|
||||||
|
static Map<String, String> remapStringKeys(Map<Long, Long> map, Map<String, String> byId) {
|
||||||
|
Map<String, String> out = new java.util.LinkedHashMap<>();
|
||||||
|
if (byId == null) return out;
|
||||||
|
byId.forEach((id, value) -> out.put(remapStringId(map, id), value));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
static List<String> remapStringList(Map<Long, Long> map, List<String> ids) {
|
static List<String> remapStringList(Map<Long, Long> map, List<String> ids) {
|
||||||
if (ids == null) return List.of();
|
if (ids == null) return List.of();
|
||||||
List<String> out = new ArrayList<>(ids.size());
|
List<String> out = new ArrayList<>(ids.size());
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ final class ImportIdMaps {
|
|||||||
final Map<Long, Long> storedFileMap = new HashMap<>();
|
final Map<Long, Long> storedFileMap = new HashMap<>();
|
||||||
|
|
||||||
final Map<Long, Long> gameSystemMap = new HashMap<>();
|
final Map<Long, Long> gameSystemMap = new HashMap<>();
|
||||||
|
/** Sorts des catalogues : sert à remapper les sorts connus des fiches. */
|
||||||
|
final Map<Long, Long> spellMap = new HashMap<>();
|
||||||
final Map<Long, Long> loreMap = new HashMap<>();
|
final Map<Long, Long> loreMap = new HashMap<>();
|
||||||
final Map<Long, Long> loreNodeMap = new HashMap<>();
|
final Map<Long, Long> loreNodeMap = new HashMap<>();
|
||||||
final Map<Long, Long> templateMap = new HashMap<>();
|
final Map<Long, Long> templateMap = new HashMap<>();
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
package com.loremind.infrastructure.transfer;
|
package com.loremind.infrastructure.transfer;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SheetSpellJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.SheetSpellJpaRepository;
|
||||||
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Façade d'IMPORT de contenu en mode FUSION.
|
* Façade d'IMPORT de contenu en mode FUSION.
|
||||||
@@ -44,6 +47,7 @@ public class ImportService {
|
|||||||
private final CampaignContentInserter campaignContentInserter;
|
private final CampaignContentInserter campaignContentInserter;
|
||||||
private final PlayStateInserter playStateInserter;
|
private final PlayStateInserter playStateInserter;
|
||||||
private final ImportReferenceRemapper referenceRemapper;
|
private final ImportReferenceRemapper referenceRemapper;
|
||||||
|
private final SheetSpellJpaRepository sheetSpellRepo;
|
||||||
|
|
||||||
public ImportService(ImportArchiveParser archiveParser,
|
public ImportService(ImportArchiveParser archiveParser,
|
||||||
ImageImporter imageImporter,
|
ImageImporter imageImporter,
|
||||||
@@ -51,7 +55,8 @@ public class ImportService {
|
|||||||
LoreContentInserter loreContentInserter,
|
LoreContentInserter loreContentInserter,
|
||||||
CampaignContentInserter campaignContentInserter,
|
CampaignContentInserter campaignContentInserter,
|
||||||
PlayStateInserter playStateInserter,
|
PlayStateInserter playStateInserter,
|
||||||
ImportReferenceRemapper referenceRemapper) {
|
ImportReferenceRemapper referenceRemapper,
|
||||||
|
SheetSpellJpaRepository sheetSpellRepo) {
|
||||||
this.archiveParser = archiveParser;
|
this.archiveParser = archiveParser;
|
||||||
this.imageImporter = imageImporter;
|
this.imageImporter = imageImporter;
|
||||||
this.storedFileImporter = storedFileImporter;
|
this.storedFileImporter = storedFileImporter;
|
||||||
@@ -59,6 +64,7 @@ public class ImportService {
|
|||||||
this.campaignContentInserter = campaignContentInserter;
|
this.campaignContentInserter = campaignContentInserter;
|
||||||
this.playStateInserter = playStateInserter;
|
this.playStateInserter = playStateInserter;
|
||||||
this.referenceRemapper = referenceRemapper;
|
this.referenceRemapper = referenceRemapper;
|
||||||
|
this.sheetSpellRepo = sheetSpellRepo;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -79,10 +85,34 @@ public class ImportService {
|
|||||||
loreContentInserter.insert(export, maps, result);
|
loreContentInserter.insert(export, maps, result);
|
||||||
campaignContentInserter.insert(export, maps, result);
|
campaignContentInserter.insert(export, maps, result);
|
||||||
playStateInserter.insert(export, maps, result);
|
playStateInserter.insert(export, maps, result);
|
||||||
|
insertSheetSpells(export, maps);
|
||||||
|
|
||||||
// 4. 2e passe de remapping.
|
// 4. 2e passe de remapping.
|
||||||
referenceRemapper.remap(maps);
|
referenceRemapper.remap(maps);
|
||||||
|
|
||||||
return result.build();
|
return result.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sorts connus des fiches : chaque lien est remappé vers la fiche et le sort importés. Un
|
||||||
|
* lien dont la fiche ou le sort n'est pas dans le bundle est laissé de côté.
|
||||||
|
*/
|
||||||
|
private void insertSheetSpells(ContentExport export, ImportIdMaps maps) {
|
||||||
|
if (export.sheetSpells() == null) return;
|
||||||
|
for (ContentExport.SheetSpellDto d : export.sheetSpells()) {
|
||||||
|
if (d == null || d.ownerType() == null) continue;
|
||||||
|
Map<Long, Long> owners = switch (d.ownerType()) {
|
||||||
|
case "character" -> maps.characterMap;
|
||||||
|
case "npc" -> maps.npcMap;
|
||||||
|
case "enemy" -> maps.enemyMap;
|
||||||
|
default -> null;
|
||||||
|
};
|
||||||
|
Long ownerId = owners == null ? null : owners.get(d.ownerId());
|
||||||
|
Long spellId = maps.spellMap.get(d.spellId());
|
||||||
|
if (ownerId == null || spellId == null) continue;
|
||||||
|
sheetSpellRepo.save(SheetSpellJpaEntity.builder()
|
||||||
|
.ownerType(d.ownerType()).ownerId(ownerId).spellId(spellId).order(d.order())
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ import com.loremind.infrastructure.persistence.entity.GameSystemJpaEntity;
|
|||||||
import com.loremind.infrastructure.persistence.entity.LoreJpaEntity;
|
import com.loremind.infrastructure.persistence.entity.LoreJpaEntity;
|
||||||
import com.loremind.infrastructure.persistence.entity.LoreNodeJpaEntity;
|
import com.loremind.infrastructure.persistence.entity.LoreNodeJpaEntity;
|
||||||
import com.loremind.infrastructure.persistence.entity.PageJpaEntity;
|
import com.loremind.infrastructure.persistence.entity.PageJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SpellJpaEntity;
|
||||||
import com.loremind.infrastructure.persistence.entity.TemplateJpaEntity;
|
import com.loremind.infrastructure.persistence.entity.TemplateJpaEntity;
|
||||||
import com.loremind.infrastructure.persistence.jpa.GameSystemJpaRepository;
|
import com.loremind.infrastructure.persistence.jpa.GameSystemJpaRepository;
|
||||||
import com.loremind.infrastructure.persistence.jpa.LoreJpaRepository;
|
import com.loremind.infrastructure.persistence.jpa.LoreJpaRepository;
|
||||||
import com.loremind.infrastructure.persistence.jpa.LoreNodeJpaRepository;
|
import com.loremind.infrastructure.persistence.jpa.LoreNodeJpaRepository;
|
||||||
import com.loremind.infrastructure.persistence.jpa.PageJpaRepository;
|
import com.loremind.infrastructure.persistence.jpa.PageJpaRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.SpellJpaRepository;
|
||||||
import com.loremind.infrastructure.persistence.jpa.TemplateJpaRepository;
|
import com.loremind.infrastructure.persistence.jpa.TemplateJpaRepository;
|
||||||
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
@@ -25,17 +27,20 @@ import java.util.List;
|
|||||||
class LoreContentInserter {
|
class LoreContentInserter {
|
||||||
|
|
||||||
private final GameSystemJpaRepository gameSystemRepo;
|
private final GameSystemJpaRepository gameSystemRepo;
|
||||||
|
private final SpellJpaRepository spellRepo;
|
||||||
private final LoreJpaRepository loreRepo;
|
private final LoreJpaRepository loreRepo;
|
||||||
private final LoreNodeJpaRepository loreNodeRepo;
|
private final LoreNodeJpaRepository loreNodeRepo;
|
||||||
private final TemplateJpaRepository templateRepo;
|
private final TemplateJpaRepository templateRepo;
|
||||||
private final PageJpaRepository pageRepo;
|
private final PageJpaRepository pageRepo;
|
||||||
|
|
||||||
LoreContentInserter(GameSystemJpaRepository gameSystemRepo,
|
LoreContentInserter(GameSystemJpaRepository gameSystemRepo,
|
||||||
|
SpellJpaRepository spellRepo,
|
||||||
LoreJpaRepository loreRepo,
|
LoreJpaRepository loreRepo,
|
||||||
LoreNodeJpaRepository loreNodeRepo,
|
LoreNodeJpaRepository loreNodeRepo,
|
||||||
TemplateJpaRepository templateRepo,
|
TemplateJpaRepository templateRepo,
|
||||||
PageJpaRepository pageRepo) {
|
PageJpaRepository pageRepo) {
|
||||||
this.gameSystemRepo = gameSystemRepo;
|
this.gameSystemRepo = gameSystemRepo;
|
||||||
|
this.spellRepo = spellRepo;
|
||||||
this.loreRepo = loreRepo;
|
this.loreRepo = loreRepo;
|
||||||
this.loreNodeRepo = loreNodeRepo;
|
this.loreNodeRepo = loreNodeRepo;
|
||||||
this.templateRepo = templateRepo;
|
this.templateRepo = templateRepo;
|
||||||
@@ -56,7 +61,24 @@ class LoreContentInserter {
|
|||||||
e.setFoundryActorType(d.foundryActorType());
|
e.setFoundryActorType(d.foundryActorType());
|
||||||
e.setAuthor(d.author());
|
e.setAuthor(d.author());
|
||||||
e.setPublic(d.isPublic());
|
e.setPublic(d.isPublic());
|
||||||
maps.gameSystemMap.put(d.id(), gameSystemRepo.save(e).getId());
|
e.setSpellTemplate(d.spellTemplate());
|
||||||
|
Long newId = gameSystemRepo.save(e).getId();
|
||||||
|
maps.gameSystemMap.put(d.id(), newId);
|
||||||
|
// Catalogue de sorts (absent des bundles antérieurs).
|
||||||
|
int order = 0;
|
||||||
|
for (ContentExport.SpellDto s : nullSafe(d.spells())) {
|
||||||
|
if (s == null || s.name() == null || s.name().isBlank()) continue;
|
||||||
|
SpellJpaEntity spell = new SpellJpaEntity();
|
||||||
|
spell.setGameSystemId(newId);
|
||||||
|
spell.setName(s.name());
|
||||||
|
spell.setLevel(s.level());
|
||||||
|
spell.setSchool(s.school());
|
||||||
|
spell.setDescription(s.description());
|
||||||
|
spell.setValues(s.values() != null ? new java.util.HashMap<>(s.values()) : new java.util.HashMap<>());
|
||||||
|
spell.setOrder(order++);
|
||||||
|
Long newSpellId = spellRepo.save(spell).getId();
|
||||||
|
if (s.id() != null) maps.spellMap.put(s.id(), newSpellId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
result.count("gameSystems", maps.gameSystemMap.size());
|
result.count("gameSystems", maps.gameSystemMap.size());
|
||||||
|
|
||||||
|
|||||||
@@ -51,9 +51,18 @@ public record ContentExport(
|
|||||||
// --- Horloges de progression (Clocks, état de Partie). Absent des anciens bundles -> nullSafe. ---
|
// --- Horloges de progression (Clocks, état de Partie). Absent des anciens bundles -> nullSafe. ---
|
||||||
List<ClockDto> clocks,
|
List<ClockDto> clocks,
|
||||||
// --- Fronts (menaces regroupant des horloges). Absent des anciens bundles -> nullSafe. ---
|
// --- Fronts (menaces regroupant des horloges). Absent des anciens bundles -> nullSafe. ---
|
||||||
List<FrontDto> fronts
|
List<FrontDto> fronts,
|
||||||
|
// --- Sorts connus des fiches (PJ, PNJ, ennemis). Absent des anciens bundles -> nullSafe. ---
|
||||||
|
List<SheetSpellDto> sheetSpells
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un sort connu d'une fiche. {@code ownerType} : {@code character}, {@code npc} ou
|
||||||
|
* {@code enemy} ; {@code ownerId} et {@code spellId} sont remappés à l'import.
|
||||||
|
*/
|
||||||
|
public record SheetSpellDto(String ownerType, Long ownerId, Long spellId, int order) {}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Metadonnees de l'export. {@code exportedAt} est passe en parametre depuis
|
* Metadonnees de l'export. {@code exportedAt} est passe en parametre depuis
|
||||||
* la couche requete (PAS Instant.now() ici, pour rester deterministe et
|
* la couche requete (PAS Instant.now() ici, pour rester deterministe et
|
||||||
@@ -79,7 +88,22 @@ public record ContentExport(
|
|||||||
String author,
|
String author,
|
||||||
boolean isPublic,
|
boolean isPublic,
|
||||||
/** Version anglaise des règles ; absente des bundles antérieurs (null). */
|
/** Version anglaise des règles ; absente des bundles antérieurs (null). */
|
||||||
String rulesMarkdownEn
|
String rulesMarkdownEn,
|
||||||
|
/** Modèle de sort ; absent des bundles antérieurs (null). */
|
||||||
|
List<TemplateField> spellTemplate,
|
||||||
|
/** Catalogue de sorts, dans l'ordre ; absent des bundles antérieurs (null). */
|
||||||
|
List<SpellDto> spells
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** Un sort du catalogue d'un système (porté par {@link GameSystemDto}). */
|
||||||
|
public record SpellDto(
|
||||||
|
String name,
|
||||||
|
String level,
|
||||||
|
String school,
|
||||||
|
String description,
|
||||||
|
java.util.Map<String, String> values,
|
||||||
|
/** Identifiant d'origine, pour remapper les sorts connus des fiches ; absent des premiers bundles (null). */
|
||||||
|
Long id
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record LoreDto(
|
public record LoreDto(
|
||||||
@@ -152,7 +176,9 @@ public record ContentExport(
|
|||||||
List<String> illustrationImageIds,
|
List<String> illustrationImageIds,
|
||||||
/** Histoire cachée et accroches ; absentes des bundles antérieurs (null). */
|
/** Histoire cachée et accroches ; absentes des bundles antérieurs (null). */
|
||||||
String hiddenTruth,
|
String hiddenTruth,
|
||||||
String hooks
|
String hooks,
|
||||||
|
/** Placement des illustrations dans le livret PDF ; absent des bundles antérieurs (null). */
|
||||||
|
Map<String, String> illustrationPlacements
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record ChapterDto(
|
public record ChapterDto(
|
||||||
@@ -171,7 +197,11 @@ public record ContentExport(
|
|||||||
String playerObjectives,
|
String playerObjectives,
|
||||||
String narrativeStakes,
|
String narrativeStakes,
|
||||||
List<String> relatedPageIds,
|
List<String> relatedPageIds,
|
||||||
List<String> illustrationImageIds
|
List<String> illustrationImageIds,
|
||||||
|
/** Méthode guidée suivie ; absente des bundles antérieurs (null). */
|
||||||
|
String guidedMethod,
|
||||||
|
/** Placement des illustrations dans le livret PDF ; absent des bundles antérieurs (null). */
|
||||||
|
Map<String, String> illustrationPlacements
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record SceneDto(
|
public record SceneDto(
|
||||||
@@ -205,7 +235,11 @@ public record ContentExport(
|
|||||||
Double graphY,
|
Double graphY,
|
||||||
/** Tactique des adversaires et utilité ; absentes des bundles antérieurs (null). */
|
/** Tactique des adversaires et utilité ; absentes des bundles antérieurs (null). */
|
||||||
String tactics,
|
String tactics,
|
||||||
String purpose
|
String purpose,
|
||||||
|
/** Rôle dans la méthode guidée du chapitre ; absent des bundles antérieurs (null). */
|
||||||
|
String guidedRole,
|
||||||
|
/** Placement des illustrations dans le livret PDF ; absent des bundles antérieurs (null). */
|
||||||
|
Map<String, String> illustrationPlacements
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record CharacterDto(
|
public record CharacterDto(
|
||||||
@@ -408,6 +442,8 @@ public record ContentExport(
|
|||||||
String playerObjectives,
|
String playerObjectives,
|
||||||
String narrativeStakes,
|
String narrativeStakes,
|
||||||
List<String> relatedPageIds,
|
List<String> relatedPageIds,
|
||||||
List<String> illustrationImageIds
|
List<String> illustrationImageIds,
|
||||||
|
/** Placement des illustrations dans le livret PDF ; absent des bundles antérieurs (null). */
|
||||||
|
Map<String, String> illustrationPlacements
|
||||||
) {}
|
) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -166,7 +166,8 @@ final class PdfAppendices {
|
|||||||
List<IndexRow> sorted = new ArrayList<>(rows);
|
List<IndexRow> sorted = new ArrayList<>(rows);
|
||||||
sorted.sort(Comparator.comparing(r -> r.name() == null ? "" : r.name().toLowerCase(Locale.ROOT)));
|
sorted.sort(Comparator.comparing(r -> r.name() == null ? "" : r.name().toLowerCase(Locale.ROOT)));
|
||||||
boolean withLevel = sorted.stream().anyMatch(r -> notBlank(r.level()));
|
boolean withLevel = sorted.stream().anyMatch(r -> notBlank(r.level()));
|
||||||
boolean withAppearances = appearances != null && !appearances.isEmpty();
|
boolean withAppearances = appearances != null
|
||||||
|
&& sorted.stream().anyMatch(r -> !appearances.getOrDefault(r.anchor(), List.of()).isEmpty());
|
||||||
|
|
||||||
b.append("<h2 class=\"section-head\" id=\"").append(anchorId).append("\">").append(esc(title)).append("</h2>");
|
b.append("<h2 class=\"section-head\" id=\"").append(anchorId).append("\">").append(esc(title)).append("</h2>");
|
||||||
b.append("<table class=\"stats-table annex-table\"><thead><tr><th>Nom</th><th>Dossier</th>");
|
b.append("<table class=\"stats-table annex-table\"><thead><tr><th>Nom</th><th>Dossier</th>");
|
||||||
@@ -188,35 +189,54 @@ final class PdfAppendices {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ou apparait chaque adversaire : ancre de sa fiche ({@code enemy-<id>}) -> scenes
|
* Ou apparait chaque fiche : ancre ({@code enemy-<id>}, {@code npc-<id>}) -> scenes (renvois).
|
||||||
* (renvois) qui le citent, dans la scene elle-meme ou dans l'une de ses pieces.
|
* D'abord les adversaires lies a une scene ou a l'une de ses pieces, puis toute fiche citee
|
||||||
|
* dans le texte d'une scene ({@code mentions} : ancre de fiche -> ancres de scenes, cf.
|
||||||
|
* {@link PdfMentions}).
|
||||||
*/
|
*/
|
||||||
static Map<String, List<String>> enemyAppearances(Structure st) {
|
static Map<String, List<String>> appearances(Structure st, Map<String, Set<String>> mentions) {
|
||||||
Map<String, Set<Long>> sceneIdsByEnemy = new LinkedHashMap<>();
|
Map<String, Set<String>> sceneAnchors = new LinkedHashMap<>();
|
||||||
Map<Long, SceneJpaEntity> byId = new LinkedHashMap<>();
|
|
||||||
for (SceneJpaEntity sc : scenesInOrder(st)) {
|
for (SceneJpaEntity sc : scenesInOrder(st)) {
|
||||||
byId.put(sc.getId(), sc);
|
|
||||||
List<String> ids = new ArrayList<>();
|
List<String> ids = new ArrayList<>();
|
||||||
if (sc.getEnemyIds() != null) ids.addAll(sc.getEnemyIds());
|
if (sc.getEnemyIds() != null) ids.addAll(sc.getEnemyIds());
|
||||||
if (sc.getRooms() != null) {
|
if (sc.getRooms() != null) {
|
||||||
for (Room r : sc.getRooms()) if (r.getEnemyIds() != null) ids.addAll(r.getEnemyIds());
|
for (Room r : sc.getRooms()) if (r.getEnemyIds() != null) ids.addAll(r.getEnemyIds());
|
||||||
}
|
}
|
||||||
for (String id : ids) {
|
for (String id : ids) {
|
||||||
if (notBlank(id)) sceneIdsByEnemy.computeIfAbsent("enemy-" + id.trim(), k -> new LinkedHashSet<>()).add(sc.getId());
|
if (notBlank(id)) {
|
||||||
|
sceneAnchors.computeIfAbsent("enemy-" + id.trim(), k -> new LinkedHashSet<>())
|
||||||
|
.add("scene-" + sc.getId());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
mentions.forEach((anchor, scenes) ->
|
||||||
|
sceneAnchors.computeIfAbsent(anchor, k -> new LinkedHashSet<>()).addAll(scenes));
|
||||||
Map<String, List<String>> out = new LinkedHashMap<>();
|
Map<String, List<String>> out = new LinkedHashMap<>();
|
||||||
sceneIdsByEnemy.forEach((enemyAnchor, sceneIds) -> {
|
sceneAnchors.forEach((anchor, scenes) -> {
|
||||||
List<String> refs = new ArrayList<>();
|
List<String> refs = new ArrayList<>();
|
||||||
for (Long sid : sceneIds) {
|
for (String scene : scenes) {
|
||||||
String anchor = "scene-" + sid;
|
String name = narrativeName(st, scene);
|
||||||
refs.add(xref(anchor, byId.get(sid).getName()) + " " + pageRef(anchor));
|
if (name != null) refs.add(xref(scene, name) + " " + pageRef(scene));
|
||||||
}
|
}
|
||||||
out.put(enemyAnchor, refs);
|
out.put(anchor, refs);
|
||||||
});
|
});
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Nom de la scene, du chapitre, de la quete ou de l'arc designe par une ancre de la narration. */
|
||||||
|
private static String narrativeName(Structure st, String anchor) {
|
||||||
|
int dash = anchor.indexOf('-');
|
||||||
|
String id = anchor.substring(dash + 1);
|
||||||
|
return switch (anchor.substring(0, dash)) {
|
||||||
|
case "scene" -> st.sceneNames.get(id);
|
||||||
|
case "ch" -> st.chapterNames.get(id);
|
||||||
|
case "quest" -> st.questNames.get(id);
|
||||||
|
case "arc" -> st.arcs.stream().filter(a -> id.equals(String.valueOf(a.getId())))
|
||||||
|
.map(ArcJpaEntity::getName).findFirst().orElse(null);
|
||||||
|
default -> null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/** Toutes les scenes dans l'ordre du livret (arcs, chapitres, scenes). */
|
/** Toutes les scenes dans l'ordre du livret (arcs, chapitres, scenes). */
|
||||||
private static List<SceneJpaEntity> scenesInOrder(Structure st) {
|
private static List<SceneJpaEntity> scenesInOrder(Structure st) {
|
||||||
List<SceneJpaEntity> out = new ArrayList<>();
|
List<SceneJpaEntity> out = new ArrayList<>();
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import org.apache.pdfbox.cos.COSName;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
|
||||||
|
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
|
||||||
|
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
|
||||||
|
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfParchmentTexture.clamp;
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfParchmentTexture.fbm;
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfParchmentTexture.smooth;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Illustration « fondue » dans la page (theme Parchemin) : une image rectangulaire ordinaire
|
||||||
|
* dont un bord, irregulier comme un coup de pinceau ou un lavis d'aquarelle, se perd dans le
|
||||||
|
* parchemin. Le bord est un MASQUE de transparence calcule ici (bruit, aucune image tierce) :
|
||||||
|
* l'auteur fournit l'image, l'application fabrique le bord.
|
||||||
|
* <p>
|
||||||
|
* Dans le PDF : l'image en JPEG, son masque en niveaux de gris (compression sans perte, demi
|
||||||
|
* resolution) attache comme {@code SMask} — transparence PDF 1.4, lue par tous les lecteurs
|
||||||
|
* courants.
|
||||||
|
*/
|
||||||
|
final class PdfBrushFade {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bord(s) de l'image qui se fondent dans la page : le haut (image de bas de page), le bas
|
||||||
|
* (bandeau d'ouverture), ou le haut et la gauche (image logee dans le coin inferieur droit).
|
||||||
|
*/
|
||||||
|
enum Edge { TOP, BOTTOM, TOP_LEFT }
|
||||||
|
|
||||||
|
/** Part de la hauteur de l'image occupee par le bord irregulier. */
|
||||||
|
static final double FADE_ZONE = 0.34;
|
||||||
|
private static final float JPEG_QUALITY = 0.8f;
|
||||||
|
|
||||||
|
private PdfBrushFade() {}
|
||||||
|
|
||||||
|
/** Image prete a dessiner : couleurs en JPEG, bord fondu en masque de transparence. */
|
||||||
|
static PDImageXObject image(PDDocument document, BufferedImage rgb, Edge edge, int seed) throws IOException {
|
||||||
|
PDImageXObject image = JPEGFactory.createFromImage(document, rgb, JPEG_QUALITY);
|
||||||
|
BufferedImage mask = mask(Math.max(2, rgb.getWidth() / 2), Math.max(2, rgb.getHeight() / 2), edge, seed);
|
||||||
|
image.getCOSObject().setItem(COSName.SMASK, LosslessFactory.createFromImage(document, mask));
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Masque (blanc = image opaque, noir = page visible). Trois couches, du coeur vers le bord :
|
||||||
|
* l'image pleine ; un trait de pinceau a la frange dechiquetee (poils secs) ; un lavis
|
||||||
|
* translucide plus large, aux contours mous.
|
||||||
|
*/
|
||||||
|
static BufferedImage mask(int width, int height, Edge edge, int seed) {
|
||||||
|
BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
|
||||||
|
double zone = height * FADE_ZONE;
|
||||||
|
// Bord horizontal (haut ou bas) : une ligne de trait et une ligne de lavis par colonne de pixels.
|
||||||
|
double[][] across = strokeLines(width, zone, seed);
|
||||||
|
// Bord gauche eventuel : memes lignes, le long de la hauteur, sur une zone plus etroite.
|
||||||
|
double sideZone = width * FADE_ZONE * 0.8;
|
||||||
|
double[][] along = edge == Edge.TOP_LEFT ? strokeLines(height, sideZone, seed + 211) : null;
|
||||||
|
for (int y = 0; y < height; y++) {
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
// Distance au bord fondu, 0 sur ce bord.
|
||||||
|
double d = edge == Edge.BOTTOM ? height - 1 - y : y;
|
||||||
|
double alpha = alpha(d, x / (double) width, zone, across[0][x], across[1][x], width, seed);
|
||||||
|
if (along != null) {
|
||||||
|
alpha = Math.min(alpha, alpha(x, y / (double) height, sideZone, along[0][y], along[1][y], height, seed + 211));
|
||||||
|
}
|
||||||
|
mask.getRaster().setSample(x, y, 0, (int) Math.round(clamp(alpha) * 255));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return mask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pour chaque point le long du bord : position du trait de pinceau [0] et du lavis [1]. */
|
||||||
|
private static double[][] strokeLines(int length, double zone, int seed) {
|
||||||
|
double[][] lines = new double[2][length];
|
||||||
|
for (int i = 0; i < length; i++) {
|
||||||
|
double u = i / (double) length;
|
||||||
|
// Trait : grande ondulation lente + dents fines des poils du pinceau.
|
||||||
|
double wave = fbm(u * 3.1 + 7, seed * 0.37, 3, seed);
|
||||||
|
double bristle = fbm(u * 46, seed * 1.3 + 2, 2, seed + 17);
|
||||||
|
lines[0][i] = zone * (0.44 + 0.34 * (wave - 0.5) * 2 + 0.15 * bristle * bristle);
|
||||||
|
// Lavis : deborde le trait vers l'exterieur, sur une ligne plus calme.
|
||||||
|
lines[1][i] = lines[0][i] - zone * (0.16 + 0.22 * fbm(u * 5.3 + 3, seed * 0.71 + 5, 3, seed + 41));
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opacite a la distance {@code d} du bord, au point {@code u} (0 a 1) le long de ce bord. */
|
||||||
|
private static double alpha(double d, double u, double zone, double stroke, double wash, int length, int seed) {
|
||||||
|
double grain = fbm(u * 38, d / length * 38, 3, seed + 73);
|
||||||
|
double core = smooth(stroke - zone * 0.09, stroke + zone * 0.13, d + (grain - 0.5) * zone * 0.16);
|
||||||
|
double veil = smooth(wash - zone * 0.1, wash + zone * 0.16, d + (grain - 0.5) * zone * 0.2) * (0.3 + 0.25 * grain);
|
||||||
|
// Rien au ras du bord : la page reste intacte la ou le texte s'arrete.
|
||||||
|
return Math.max(core, veil) * smooth(0, zone * 0.08, d);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,9 +13,20 @@ import java.util.Set;
|
|||||||
* @param printFriendly vrai = sans aplats de couleur (économie d'encre)
|
* @param printFriendly vrai = sans aplats de couleur (économie d'encre)
|
||||||
* @param sections parties incluses
|
* @param sections parties incluses
|
||||||
* @param loreScope pages de lore incluses (si la partie Lore est demandée)
|
* @param loreScope pages de lore incluses (si la partie Lore est demandée)
|
||||||
|
* @param theme habillage du livret (classique par défaut)
|
||||||
|
* @param shortNameRefs vrai (défaut) = les renvois automatiques vers les fiches citées dans le
|
||||||
|
* texte reconnaissent aussi le premier mot du nom d'un PNJ (« Maëlis » pour
|
||||||
|
* « Maëlis la Discrète ») ; faux = noms complets seulement, pour écarter
|
||||||
|
* tout risque d'homonymie
|
||||||
*/
|
*/
|
||||||
public record PdfExportOptions(boolean gmContent, PageFormat format, boolean printFriendly,
|
public record PdfExportOptions(boolean gmContent, PageFormat format, boolean printFriendly,
|
||||||
Set<Section> sections, LoreScope loreScope) {
|
Set<Section> sections, LoreScope loreScope, Theme theme, boolean shortNameRefs) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Habillage du livret. CLASSIC : la mise en page historique. PARCHMENT : rendu « livre de
|
||||||
|
* jeu de rôle » (fond parchemin, titres à capitales, encadrés et fiches façon supplément).
|
||||||
|
*/
|
||||||
|
public enum Theme { CLASSIC, PARCHMENT }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parties du livret qu'on peut inclure ou non. APPENDIX = annexes MJ (revelations et
|
* Parties du livret qu'on peut inclure ou non. APPENDIX = annexes MJ (revelations et
|
||||||
@@ -74,6 +85,27 @@ public record PdfExportOptions(boolean gmContent, PageFormat format, boolean pri
|
|||||||
sections = sections == null || sections.isEmpty()
|
sections = sections == null || sections.isEmpty()
|
||||||
? EnumSet.allOf(Section.class) : EnumSet.copyOf(sections);
|
? EnumSet.allOf(Section.class) : EnumSet.copyOf(sections);
|
||||||
loreScope = loreScope != null ? loreScope : LoreScope.ALL;
|
loreScope = loreScope != null ? loreScope : LoreScope.ALL;
|
||||||
|
theme = theme != null ? theme : Theme.CLASSIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Options au thème classique, noms courts de PNJ reconnus (signature historique). */
|
||||||
|
public PdfExportOptions(boolean gmContent, PageFormat format, boolean printFriendly,
|
||||||
|
Set<Section> sections, LoreScope loreScope) {
|
||||||
|
this(gmContent, format, printFriendly, sections, loreScope, Theme.CLASSIC, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mêmes options, avec ou sans repérage des noms courts de PNJ. */
|
||||||
|
public PdfExportOptions withShortNameRefs(boolean enabled) {
|
||||||
|
return new PdfExportOptions(gmContent, format, printFriendly, sections, loreScope, theme, enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean parchment() {
|
||||||
|
return theme == Theme.PARCHMENT;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fond parchemin dessiné sous les pages : jamais en mode impression (économie d'encre). */
|
||||||
|
public boolean parchmentBackground() {
|
||||||
|
return parchment() && !printFriendly;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Livret MJ complet en A4 : le comportement historique de l'export. */
|
/** Livret MJ complet en A4 : le comportement historique de l'export. */
|
||||||
@@ -91,6 +123,18 @@ public record PdfExportOptions(boolean gmContent, PageFormat format, boolean pri
|
|||||||
*/
|
*/
|
||||||
public static PdfExportOptions parse(String edition, String format, Boolean print,
|
public static PdfExportOptions parse(String edition, String format, Boolean print,
|
||||||
String sections, String lore) {
|
String sections, String lore) {
|
||||||
|
return parse(edition, format, print, sections, lore, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Comme {@link #parse(String, String, Boolean, String, String)}, avec le thème ({@code classic|parchment}). */
|
||||||
|
public static PdfExportOptions parse(String edition, String format, Boolean print,
|
||||||
|
String sections, String lore, String theme) {
|
||||||
|
return parse(edition, format, print, sections, lore, theme, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Toutes les options de la requête ; {@code shortNames=false} : sans les noms courts de PNJ. */
|
||||||
|
public static PdfExportOptions parse(String edition, String format, Boolean print,
|
||||||
|
String sections, String lore, String theme, Boolean shortNames) {
|
||||||
boolean gm = !"player".equalsIgnoreCase(trim(edition));
|
boolean gm = !"player".equalsIgnoreCase(trim(edition));
|
||||||
PageFormat pf = enumOrNull(PageFormat.class, format);
|
PageFormat pf = enumOrNull(PageFormat.class, format);
|
||||||
LoreScope scope = enumOrNull(LoreScope.class, lore);
|
LoreScope scope = enumOrNull(LoreScope.class, lore);
|
||||||
@@ -101,7 +145,8 @@ public record PdfExportOptions(boolean gmContent, PageFormat format, boolean pri
|
|||||||
if (sec != null) set.add(sec);
|
if (sec != null) set.add(sec);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new PdfExportOptions(gm, pf, Boolean.TRUE.equals(print), set, scope);
|
return new PdfExportOptions(gm, pf, Boolean.TRUE.equals(print), set, scope, enumOrNull(Theme.class, theme),
|
||||||
|
!Boolean.FALSE.equals(shortNames));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String trim(String s) {
|
private static String trim(String s) {
|
||||||
|
|||||||
+865
-57
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,297 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.DIV_CLOSE;
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.esc;
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.notBlank;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Illustrations du theme « Parchemin » : cadre dessine, legende, planche pleine page, bandeau
|
||||||
|
* d'ouverture, image habillee par le texte, rangee d'images. Sans etat ; le rendu (CSS) est
|
||||||
|
* dans export-parchment.css.
|
||||||
|
* <p>
|
||||||
|
* Trois contraintes du moteur (openhtmltopdf) dictent la forme du HTML, toutes mesurees :
|
||||||
|
* <ul>
|
||||||
|
* <li>une image flottante qui tombe en bas de colonne ou de page est COUPEE en deux, et un
|
||||||
|
* encadre qui la suit la chevauche : elle n'est donc posee que dans un bloc insecable
|
||||||
|
* ({@code figure-lead}) qui contient aussi le texte qui l'habille — bloc que le moteur
|
||||||
|
* deplace entier ;</li>
|
||||||
|
* <li>une image plus haute que sa page deborde sur les pages voisines ({@code overflow:
|
||||||
|
* hidden} ne rogne pas d'une page a l'autre) : la planche pleine page recoit une image deja
|
||||||
|
* recadree au format de la page (cf. {@link PdfImageEncoder.Spec#cropped}) ;</li>
|
||||||
|
* <li>une image ne peut pas s'etendre sur deux colonnes ({@code column-span} inconnu) et les
|
||||||
|
* colonnes ne sont pas equilibrees : un bandeau pleine largeur sort du flux en colonnes et
|
||||||
|
* commence en haut de page.</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
final class PdfFigures {
|
||||||
|
|
||||||
|
/** Cadre : filet (1pt) et marge (2pt) de chaque cote, plus le filet de l'image (0,6pt). */
|
||||||
|
private static final double FRAME_CM = 0.26;
|
||||||
|
private static final double CAPTION_CM = 0.45;
|
||||||
|
/** Une planche est un cheveu moins haute que sa page : a hauteur egale, l'arrondi du moteur la fait deborder. */
|
||||||
|
static final double PLATE_SLACK_CM = 0.03;
|
||||||
|
/** Quatre coins du cadre (petits carres pleins poses sur les angles). */
|
||||||
|
private static final String CORNERS = "<div class=\"fc tl\"></div><div class=\"fc tr\"></div>"
|
||||||
|
+ "<div class=\"fc bl\"></div><div class=\"fc br\"></div>";
|
||||||
|
/** Largeur moyenne d'un caractere du texte courant, en cadratins (mesuree sur le livret de demonstration). */
|
||||||
|
private static final double CHAR_EM = 0.42;
|
||||||
|
private static final double LINE_EM = 1.3;
|
||||||
|
|
||||||
|
private PdfFigures() {}
|
||||||
|
|
||||||
|
/** Longueur CSS au dixieme de millimetre (les cadres ne tolerent pas l'arrondi au millimetre). */
|
||||||
|
static String len(double cm) {
|
||||||
|
return String.format(Locale.ROOT, "%.2fcm", cm);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hauteur occupee par une image encadree de {@code widthCm} de large, legende comprise. */
|
||||||
|
static double height(PdfImage img, double widthCm, boolean caption) {
|
||||||
|
return (widthCm - FRAME_CM) * img.h() / img.w() + FRAME_CM + (caption ? CAPTION_CM : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plus grande largeur (cadre compris) tenant dans {@code maxWidthCm} sans depasser {@code maxHeightCm}. */
|
||||||
|
static double fit(PdfImage img, double maxWidthCm, double maxHeightCm) {
|
||||||
|
return Math.min(maxWidthCm, (maxHeightCm - FRAME_CM) * img.w() / img.h() + FRAME_CM);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Image encadree, avec legende eventuelle. {@code cssClass} : {@code center} (seule sur sa
|
||||||
|
* ligne) ou {@code wrap} (flottante a droite, a n'utiliser que dans un {@code figure-lead}).
|
||||||
|
*/
|
||||||
|
static String figure(PdfImage img, double widthCm, String caption, String cssClass) {
|
||||||
|
StringBuilder b = new StringBuilder(img.uri().length() + 256);
|
||||||
|
b.append("<div class=\"figure ").append(cssClass).append("\" style=\"width:").append(len(widthCm)).append("\">");
|
||||||
|
frame(b, img, widthCm);
|
||||||
|
if (notBlank(caption)) b.append("<div class=\"caption\">").append(esc(caption.trim())).append(DIV_CLOSE);
|
||||||
|
return b.append(DIV_CLOSE).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void frame(StringBuilder b, PdfImage img, double widthCm) {
|
||||||
|
b.append("<div class=\"frame\"><img style=\"width:").append(len(widthCm - FRAME_CM))
|
||||||
|
.append("\" src=\"").append(img.uri()).append("\"/>").append(CORNERS).append(DIV_CLOSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Planche pleine page, a fond perdu (page nommee {@code plate}, sans marges). L'image doit
|
||||||
|
* avoir ete recadree au rapport de la page ; la hauteur est un cheveu sous celle de la page
|
||||||
|
* pour ne jamais deborder sur la suivante.
|
||||||
|
*/
|
||||||
|
static String plate(PdfImage img, PdfExportOptions.PageFormat format, String caption) {
|
||||||
|
StringBuilder b = new StringBuilder(img.uri().length() + 256);
|
||||||
|
b.append("<div class=\"plate\"><img style=\"width:").append(len(format.widthCm))
|
||||||
|
.append(";height:").append(len(format.heightCm - PLATE_SLACK_CM))
|
||||||
|
.append("\" src=\"").append(img.uri()).append("\"/>");
|
||||||
|
if (notBlank(caption)) b.append("<div class=\"caption\">").append(esc(caption.trim())).append(DIV_CLOSE);
|
||||||
|
return b.append(DIV_CLOSE).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rapport hauteur/largeur d'une image qui supporte la pleine page sans perdre l'essentiel au recadrage. */
|
||||||
|
static boolean plateShaped(PdfImage img, PdfExportOptions.PageFormat format) {
|
||||||
|
double image = (double) img.h() / img.w();
|
||||||
|
double page = format.heightCm / format.widthCm;
|
||||||
|
return image >= page * 0.82 && image <= page * 1.25;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bandeau d'ouverture, hors du flux en colonnes : image centree sur toute la largeur utile,
|
||||||
|
* hauteur bornee. {@code fresh} : commence une nouvelle page (rien au-dessus qu'un titre
|
||||||
|
* sinon, auquel cas le bandeau le suit).
|
||||||
|
*/
|
||||||
|
static String banner(PdfImage img, double pageWidthCm, double maxHeightCm, String caption, boolean fresh) {
|
||||||
|
double width = fit(img, pageWidthCm, maxHeightCm - (notBlank(caption) ? CAPTION_CM : 0));
|
||||||
|
return "<div class=\"opener" + (fresh ? " fresh" : "") + "\">" + figure(img, width, caption, "center") + DIV_CLOSE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saut de page hors colonnes (un titre d'arc seul doit rejoindre l'ouverture de son premier chapitre). */
|
||||||
|
static final String PAGE_BREAK = "<div class=\"opener-break\"></div>";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rangee d'images de meme hauteur (champ IMAGE a plusieurs images), legende commune dessous.
|
||||||
|
* Trois par rangee au plus ; un tableau, seule disposition cote a cote fiable ici.
|
||||||
|
*/
|
||||||
|
static String gallery(List<PdfImage> images, double maxWidthCm, double maxHeightCm, String caption) {
|
||||||
|
StringBuilder b = new StringBuilder("<div class=\"gallery\">");
|
||||||
|
for (int start = 0; start < images.size(); start += 3) {
|
||||||
|
List<PdfImage> row = images.subList(start, Math.min(images.size(), start + 3));
|
||||||
|
double gaps = 0.3 * row.size();
|
||||||
|
double ratios = 0;
|
||||||
|
for (PdfImage img : row) ratios += (double) img.w() / img.h();
|
||||||
|
// Hauteur commune : la rangee entiere tient dans la largeur disponible.
|
||||||
|
double h = Math.min(maxHeightCm, (maxWidthCm - gaps - FRAME_CM * row.size()) / ratios);
|
||||||
|
b.append("<table class=\"gallery-row\"><tr>");
|
||||||
|
for (PdfImage img : row) {
|
||||||
|
double w = h * img.w() / img.h() + FRAME_CM;
|
||||||
|
b.append("<td>").append(figure(img, w, null, "center")).append("</td>");
|
||||||
|
}
|
||||||
|
b.append("</tr></table>");
|
||||||
|
}
|
||||||
|
if (notBlank(caption)) b.append("<div class=\"caption\">").append(esc(caption.trim())).append(DIV_CLOSE);
|
||||||
|
return b.append(DIV_CLOSE).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====================================================================== Colonnes equilibrees
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repartit une suite de blocs (champs, encadres) sur deux colonnes de hauteur voisine, dans
|
||||||
|
* un tableau : le moteur remplit ses colonnes l'une apres l'autre sans les equilibrer. La
|
||||||
|
* hauteur de chaque bloc est estimee d'apres la longueur de son texte. Null si le fragment
|
||||||
|
* ne s'y prete pas : un seul bloc, une image, ou un texte trop long pour tenir sur une page
|
||||||
|
* (une ligne de tableau ne se coupe pas proprement).
|
||||||
|
*/
|
||||||
|
static String balanced(String html, Measure m) {
|
||||||
|
if (html.contains("<img")) return null;
|
||||||
|
List<String> blocks = topLevelBlocks(html);
|
||||||
|
if (blocks.size() < 2) return null;
|
||||||
|
double[] heights = new double[blocks.size()];
|
||||||
|
double total = 0;
|
||||||
|
for (int i = 0; i < heights.length; i++) {
|
||||||
|
String block = blocks.get(i);
|
||||||
|
int chars = block.replaceAll("<[^>]*>", "").length();
|
||||||
|
heights[i] = Math.ceil(chars / m.charsPerLine(m.columnCm())) * m.lineCm() + 0.2
|
||||||
|
+ (block.startsWith("<div class=\"box") ? 0.75 : 0);
|
||||||
|
total += heights[i];
|
||||||
|
}
|
||||||
|
if (total / 2 > m.textHeightCm() * 0.5) return null;
|
||||||
|
// Coupure qui rapproche le plus les deux hauteurs, la colonne de gauche au moins aussi haute.
|
||||||
|
int split = 1;
|
||||||
|
double left = 0, best = Double.MAX_VALUE;
|
||||||
|
for (int i = 0; i < heights.length - 1; i++) {
|
||||||
|
left += heights[i];
|
||||||
|
double gap = Math.abs(2 * left - total) + (2 * left < total ? 0.5 : 0);
|
||||||
|
if (gap < best) {
|
||||||
|
best = gap;
|
||||||
|
split = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "<table class=\"balanced\"><tr><td class=\"bl\">" + String.join("", blocks.subList(0, split))
|
||||||
|
+ "</td><td class=\"br\">" + String.join("", blocks.subList(split, blocks.size())) + "</td></tr></table>";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Elements de premier niveau d'un fragment XHTML bien forme (tel que l'ecrit PdfHtml). */
|
||||||
|
private static List<String> topLevelBlocks(String html) {
|
||||||
|
List<String> blocks = new ArrayList<>();
|
||||||
|
int depth = 0, start = 0, i = 0;
|
||||||
|
while (i < html.length()) {
|
||||||
|
int lt = html.indexOf('<', i);
|
||||||
|
if (lt < 0) break;
|
||||||
|
int gt = html.indexOf('>', lt);
|
||||||
|
if (gt < 0) break;
|
||||||
|
boolean close = html.charAt(lt + 1) == '/';
|
||||||
|
boolean selfClosed = html.charAt(gt - 1) == '/';
|
||||||
|
if (close) depth--;
|
||||||
|
else if (!selfClosed) depth++;
|
||||||
|
i = gt + 1;
|
||||||
|
if (depth == 0) {
|
||||||
|
blocks.add(html.substring(start, i));
|
||||||
|
start = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (start < html.length() && !html.substring(start).isBlank()) blocks.add(html.substring(start));
|
||||||
|
return blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====================================================================== Image habillee
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bloc insecable « image flottante + debut du texte ». Ouvert par {@link #open}, il se
|
||||||
|
* referme de lui-meme ({@link #after}) quand le texte ecrit couvre la hauteur de l'image.
|
||||||
|
*/
|
||||||
|
static final class Lead {
|
||||||
|
/** Aucune image habillee : toutes les operations sont sans effet. */
|
||||||
|
static final Lead NONE = new Lead(null, null, 0);
|
||||||
|
|
||||||
|
private final StringBuilder body;
|
||||||
|
private final String figureHtml;
|
||||||
|
private int toWrap;
|
||||||
|
private boolean open;
|
||||||
|
|
||||||
|
private Lead(StringBuilder body, String figureHtml, int toWrap) {
|
||||||
|
this.body = body;
|
||||||
|
this.figureHtml = figureHtml;
|
||||||
|
this.toWrap = toWrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean used() {
|
||||||
|
return figureHtml != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ouvre le bloc (avant le titre, qui ne doit pas se separer de la suite). */
|
||||||
|
void open() {
|
||||||
|
if (!used()) return;
|
||||||
|
body.append("<div class=\"figure-lead\">");
|
||||||
|
open = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pose l'image (apres le titre, avant le texte qui l'habille). */
|
||||||
|
void figure() {
|
||||||
|
if (used()) body.append(figureHtml);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ce texte vient d'etre ecrit dans le bloc : il se referme quand l'image est couverte. */
|
||||||
|
void after(String text) {
|
||||||
|
if (!open || !notBlank(text)) return;
|
||||||
|
toWrap -= text.length();
|
||||||
|
if (toWrap <= 0) close();
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
if (!open) return;
|
||||||
|
body.append(DIV_CLOSE);
|
||||||
|
open = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Geometrie du texte autour d'une image : largeur de colonne, hauteur utile de page, corps. */
|
||||||
|
record Measure(double columnCm, double textHeightCm, double bodyPt, boolean columns) {
|
||||||
|
double emCm() {
|
||||||
|
return bodyPt * 2.54 / 72;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nombre de caracteres d'une ligne de {@code widthCm}. */
|
||||||
|
double charsPerLine(double widthCm) {
|
||||||
|
return widthCm / (CHAR_EM * emCm());
|
||||||
|
}
|
||||||
|
|
||||||
|
double lineCm() {
|
||||||
|
return LINE_EM * emCm();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Image habillee par le texte, si le format s'y prete ; sinon {@link Lead#NONE} (l'image
|
||||||
|
* garde alors sa place habituelle, sur la largeur de la colonne).
|
||||||
|
* <ul>
|
||||||
|
* <li>en deux colonnes, seule une image en hauteur ou carree flotte (une image en paysage
|
||||||
|
* y serait une vignette) ;</li>
|
||||||
|
* <li>les textes qui suivent doivent couvrir la hauteur de l'image — sinon un blanc
|
||||||
|
* resterait a cote d'elle ;</li>
|
||||||
|
* <li>le bloc, insecable, ne depasse pas la moitie de la page.</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* @param texts textes qui suivront l'image, dans l'ordre (les vides sont ignores)
|
||||||
|
*/
|
||||||
|
static Lead lead(StringBuilder body, PdfImage img, String caption, Measure m, List<String> texts) {
|
||||||
|
if (img == null) return Lead.NONE;
|
||||||
|
boolean wide = (double) img.w() / img.h() > 1.2;
|
||||||
|
if (m.columns() && wide) return Lead.NONE;
|
||||||
|
// Part de la colonne ; plafonnee, pour une fiche ou une page de lore en pleine largeur A4.
|
||||||
|
double width = Math.min(m.columnCm() * (m.columns() ? 0.42 : wide ? 0.48 : 0.36), wide ? 7.0 : 4.8);
|
||||||
|
double figH = height(img, width, notBlank(caption));
|
||||||
|
// Caracteres a ecrire a cote de l'image pour en couvrir la hauteur.
|
||||||
|
int needed = (int) (Math.ceil(figH / m.lineCm()) * m.charsPerLine(m.columnCm() - width - 0.3));
|
||||||
|
int written = 0;
|
||||||
|
for (String t : texts) {
|
||||||
|
if (!notBlank(t) || written >= needed) continue;
|
||||||
|
written += t.length();
|
||||||
|
}
|
||||||
|
if (written < needed * 0.9) return Lead.NONE;
|
||||||
|
// Hauteur du bloc : l'image, puis le texte qui deborde dessous, puis titre et marges.
|
||||||
|
double below = Math.max(0, written - needed) / m.charsPerLine(m.columnCm()) * m.lineCm();
|
||||||
|
if (figH + below + 1.5 > m.textHeightCm() * PdfExportService.UNBREAKABLE_MAX_HEIGHT_RATIO) return Lead.NONE;
|
||||||
|
return new Lead(body, figure(img, width, caption, "wrap"), needed);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -210,6 +210,31 @@ final class PdfHtml {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Texte d'ouverture (theme Parchemin) : texte courant sans libelle. Le premier paragraphe
|
||||||
|
* recoit une lettrine s'il commence par une lettre et compte au moins {@code dropCapMinChars}
|
||||||
|
* caracteres — plus court, la lettrine depasserait du paragraphe. La lettrine est un span
|
||||||
|
* flottant : openhtmltopdf ignore {@code float} sur le pseudo-element {@code :first-letter}.
|
||||||
|
*/
|
||||||
|
static void lead(StringBuilder b, String value, int dropCapMinChars) {
|
||||||
|
if (!notBlank(value)) return;
|
||||||
|
StringBuilder text = new StringBuilder();
|
||||||
|
prose(text, value);
|
||||||
|
String first = value.strip();
|
||||||
|
String open = "<p class=\"prose\">";
|
||||||
|
boolean dropCap = text.indexOf(open) == 0 && Character.isLetter(first.charAt(0))
|
||||||
|
&& text.indexOf("</p>") - open.length() >= dropCapMinChars;
|
||||||
|
b.append("<div class=\"lead\">");
|
||||||
|
if (dropCap) {
|
||||||
|
b.append("<p class=\"prose has-dropcap\"><span class=\"dropcap\">")
|
||||||
|
.append(esc(first.substring(0, 1).toUpperCase(Locale.ROOT))).append(SPAN_CLOSE)
|
||||||
|
.append(text, open.length() + 1, text.length());
|
||||||
|
} else {
|
||||||
|
b.append(text);
|
||||||
|
}
|
||||||
|
b.append(DIV_CLOSE);
|
||||||
|
}
|
||||||
|
|
||||||
private static String paragraphHtml(TextBlock t) {
|
private static String paragraphHtml(TextBlock t) {
|
||||||
StringBuilder p = new StringBuilder();
|
StringBuilder p = new StringBuilder();
|
||||||
for (int i = 0; i < t.lines().size(); i++) {
|
for (int i = 0; i < t.lines().size(); i++) {
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ import java.util.Base64;
|
|||||||
* blanc (aplatit la transparence) et sortie en data-URI. Le decodeur WebP TwelveMonkeys
|
* blanc (aplatit la transparence) et sortie en data-URI. Le decodeur WebP TwelveMonkeys
|
||||||
* (present au classpath) permet de decoder aussi les WebP. Tout echec de decodage renvoie
|
* (present au classpath) permet de decoder aussi les WebP. Tout echec de decodage renvoie
|
||||||
* null : l'image est simplement omise du livret plutot que de casser l'export.
|
* null : l'image est simplement omise du livret plutot que de casser l'export.
|
||||||
|
* <p>
|
||||||
|
* Une {@link Spec} precise la preparation : cote max, couleur sur laquelle la transparence est
|
||||||
|
* aplatie, et recadrage centre a un rapport largeur/hauteur donne (planche pleine page : le
|
||||||
|
* moteur de rendu ne sait pas rogner proprement une image qui deborde de la page).
|
||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
class PdfImageEncoder {
|
class PdfImageEncoder {
|
||||||
@@ -37,6 +41,27 @@ class PdfImageEncoder {
|
|||||||
static final int PORTRAIT_MAX = 700;
|
static final int PORTRAIT_MAX = 700;
|
||||||
static final int ILLUSTRATION_MAX = 1500;
|
static final int ILLUSTRATION_MAX = 1500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Preparation d'une image.
|
||||||
|
*
|
||||||
|
* @param maxDim plus grande cote, en pixels, apres redimensionnement
|
||||||
|
* @param matte couleur sous les zones transparentes (le JPEG n'a pas de transparence)
|
||||||
|
* @param cropRatio rapport largeur/hauteur auquel recadrer l'image (centree) ; 0 = entiere
|
||||||
|
*/
|
||||||
|
record Spec(int maxDim, Color matte, double cropRatio) {
|
||||||
|
static Spec of(int maxDim) {
|
||||||
|
return new Spec(maxDim, Color.WHITE, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Spec matte(Color color) {
|
||||||
|
return new Spec(maxDim, color, cropRatio);
|
||||||
|
}
|
||||||
|
|
||||||
|
Spec cropped(double widthOverHeight) {
|
||||||
|
return new Spec(maxDim, matte, widthOverHeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private final ImageJpaRepository imageRepo;
|
private final ImageJpaRepository imageRepo;
|
||||||
private final StoredFileJpaRepository storedFileRepo;
|
private final StoredFileJpaRepository storedFileRepo;
|
||||||
private final ImageStorage imageStorage;
|
private final ImageStorage imageStorage;
|
||||||
@@ -52,6 +77,21 @@ class PdfImageEncoder {
|
|||||||
|
|
||||||
/** Image LoreMind re-encodee (data-URI JPEG redimensionne), ou null. */
|
/** Image LoreMind re-encodee (data-URI JPEG redimensionne), ou null. */
|
||||||
PdfImage image(String imageId, int maxDim) {
|
PdfImage image(String imageId, int maxDim) {
|
||||||
|
return image(imageId, Spec.of(maxDim));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Legende d'une image, ou null. Le modele n'en porte pas aujourd'hui (une image n'a qu'un
|
||||||
|
* nom de fichier) : toujours null, donc aucune legende libre dans un export reel. Point de
|
||||||
|
* branchement unique le jour ou le champ existera ; le livret de demonstration le
|
||||||
|
* surcharge pour montrer le rendu vise.
|
||||||
|
*/
|
||||||
|
String caption(String imageId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pixels d'une image LoreMind preparee selon {@code spec} (dessin direct dans le PDF), ou null. */
|
||||||
|
BufferedImage raster(String imageId, Spec spec) {
|
||||||
if (imageId == null || imageId.isBlank()) return null;
|
if (imageId == null || imageId.isBlank()) return null;
|
||||||
ImageJpaEntity e;
|
ImageJpaEntity e;
|
||||||
try {
|
try {
|
||||||
@@ -60,7 +100,27 @@ class PdfImageEncoder {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (e == null) return null;
|
if (e == null) return null;
|
||||||
return encode(imageStorage.download(e.getStorageKey()), maxDim, imageId);
|
InputStream in = imageStorage.download(e.getStorageKey());
|
||||||
|
if (in == null) return null;
|
||||||
|
try (in) {
|
||||||
|
return prepare(in, spec, imageId);
|
||||||
|
} catch (IOException | RuntimeException ex) {
|
||||||
|
log.warn("Image PDF ignoree ({}) : {}", imageId, ex.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Image LoreMind preparee selon {@code spec}, ou null. */
|
||||||
|
PdfImage image(String imageId, Spec spec) {
|
||||||
|
if (imageId == null || imageId.isBlank()) return null;
|
||||||
|
ImageJpaEntity e;
|
||||||
|
try {
|
||||||
|
e = imageRepo.findById(Long.parseLong(imageId)).orElse(null);
|
||||||
|
} catch (NumberFormatException ex) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (e == null) return null;
|
||||||
|
return encode(imageStorage.download(e.getStorageKey()), spec, imageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Battlemap (fichier stocke) re-encodee, seulement si c'est une image (pas une video). */
|
/** Battlemap (fichier stocke) re-encodee, seulement si c'est une image (pas une video). */
|
||||||
@@ -70,6 +130,11 @@ class PdfImageEncoder {
|
|||||||
|
|
||||||
/** Idem, avec une cote max choisie (cartes pleine page de l'annexe : plus fines). */
|
/** Idem, avec une cote max choisie (cartes pleine page de l'annexe : plus fines). */
|
||||||
PdfImage fileImage(String fileId, int maxDim) {
|
PdfImage fileImage(String fileId, int maxDim) {
|
||||||
|
return fileImage(fileId, Spec.of(maxDim));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Battlemap preparee selon {@code spec}, ou null (video, fichier absent ou illisible). */
|
||||||
|
PdfImage fileImage(String fileId, Spec spec) {
|
||||||
if (fileId == null || fileId.isBlank()) return null;
|
if (fileId == null || fileId.isBlank()) return null;
|
||||||
StoredFileJpaEntity e;
|
StoredFileJpaEntity e;
|
||||||
try {
|
try {
|
||||||
@@ -80,37 +145,55 @@ class PdfImageEncoder {
|
|||||||
if (e == null) return null;
|
if (e == null) return null;
|
||||||
String ct = e.getContentType();
|
String ct = e.getContentType();
|
||||||
if (ct == null || !ct.startsWith("image/")) return null; // mp4/webm -> ignore
|
if (ct == null || !ct.startsWith("image/")) return null; // mp4/webm -> ignore
|
||||||
return encode(fileStorage.download(e.getStorageKey()), maxDim, fileId);
|
return encode(fileStorage.download(e.getStorageKey()), spec, fileId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Lit un flux image, le redimensionne (max maxDim) et le re-encode en data-URI JPEG. */
|
/** Lit un flux image, le recadre si demande, le redimensionne et le re-encode en data-URI JPEG. */
|
||||||
private PdfImage encode(InputStream in, int maxDim, String ref) {
|
private PdfImage encode(InputStream in, Spec spec, String ref) {
|
||||||
if (in == null) return null;
|
if (in == null) return null;
|
||||||
try (in) {
|
try (in) {
|
||||||
BufferedImage src = ImageIO.read(in);
|
BufferedImage dst = prepare(in, spec, ref);
|
||||||
if (src == null) {
|
if (dst == null) return null;
|
||||||
log.debug("Image PDF ignoree (format non decode) : {}", ref);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
int w = src.getWidth();
|
|
||||||
int h = src.getHeight();
|
|
||||||
double scale = Math.min(1.0, (double) maxDim / Math.max(w, h));
|
|
||||||
int nw = Math.max(1, (int) Math.round(w * scale));
|
|
||||||
int nh = Math.max(1, (int) Math.round(h * scale));
|
|
||||||
BufferedImage dst = new BufferedImage(nw, nh, BufferedImage.TYPE_INT_RGB);
|
|
||||||
Graphics2D g = dst.createGraphics();
|
|
||||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
|
||||||
g.setColor(Color.WHITE); // fond blanc : aplatit la transparence (JPEG sans alpha)
|
|
||||||
g.fillRect(0, 0, nw, nh);
|
|
||||||
g.drawImage(src, 0, 0, nw, nh, null);
|
|
||||||
g.dispose();
|
|
||||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
ImageIO.write(dst, "jpeg", out);
|
ImageIO.write(dst, "jpeg", out);
|
||||||
return new PdfImage("data:image/jpeg;base64," + Base64.getEncoder().encodeToString(out.toByteArray()),
|
return new PdfImage("data:image/jpeg;base64," + Base64.getEncoder().encodeToString(out.toByteArray()),
|
||||||
nw, nh);
|
dst.getWidth(), dst.getHeight());
|
||||||
} catch (IOException | RuntimeException ex) {
|
} catch (IOException | RuntimeException ex) {
|
||||||
log.warn("Image PDF ignoree ({}) : {}", ref, ex.getMessage());
|
log.warn("Image PDF ignoree ({}) : {}", ref, ex.getMessage());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Lit un flux image, le recadre si demande, le redimensionne et aplatit sa transparence. */
|
||||||
|
private static BufferedImage prepare(InputStream in, Spec spec, String ref) throws IOException {
|
||||||
|
BufferedImage src = ImageIO.read(in);
|
||||||
|
if (src == null) {
|
||||||
|
log.debug("Image PDF ignoree (format non decode) : {}", ref);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (spec.cropRatio() > 0) src = crop(src, spec.cropRatio());
|
||||||
|
int w = src.getWidth();
|
||||||
|
int h = src.getHeight();
|
||||||
|
double scale = Math.min(1.0, (double) spec.maxDim() / Math.max(w, h));
|
||||||
|
int nw = Math.max(1, (int) Math.round(w * scale));
|
||||||
|
int nh = Math.max(1, (int) Math.round(h * scale));
|
||||||
|
BufferedImage dst = new BufferedImage(nw, nh, BufferedImage.TYPE_INT_RGB);
|
||||||
|
Graphics2D g = dst.createGraphics();
|
||||||
|
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||||
|
g.setColor(spec.matte()); // fond uni : aplatit la transparence (JPEG sans alpha)
|
||||||
|
g.fillRect(0, 0, nw, nh);
|
||||||
|
g.drawImage(src, 0, 0, nw, nh, null);
|
||||||
|
g.dispose();
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plus grande partie centree de l'image au rapport largeur/hauteur demande. */
|
||||||
|
private static BufferedImage crop(BufferedImage src, double widthOverHeight) {
|
||||||
|
int w = src.getWidth();
|
||||||
|
int h = src.getHeight();
|
||||||
|
int cw = (int) Math.min(w, Math.round(h * widthOverHeight));
|
||||||
|
int ch = (int) Math.min(h, Math.round(w / widthOverHeight));
|
||||||
|
if (cw < 1 || ch < 1) return src;
|
||||||
|
return src.getSubimage((w - cw) / 2, (h - ch) / 2, cw, ch);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,403 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Deque;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.esc;
|
||||||
|
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.pageRef;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renvois automatiques vers les fiches (PNJ, adversaires) CITEES dans le texte libre du
|
||||||
|
* livret : la premiere mention d'une fiche dans une scene, une fiche ou un texte d'ouverture
|
||||||
|
* devient un lien interne suivi de sa page — « Bertoul le colporteur (p. 9) ».
|
||||||
|
* <p>
|
||||||
|
* Le modele ne lie pas les PNJ aux scenes : la mention dans le texte est la seule reference
|
||||||
|
* dont on dispose. Le reperage privilegie donc la PRECISION — un renvoi faux est pire qu'un
|
||||||
|
* renvoi absent :
|
||||||
|
* <ul>
|
||||||
|
* <li>nom de la fiche, mot entier (jamais dans un autre mot ni un mot compose), sans sa
|
||||||
|
* precision entre parentheses ni son epithete apres une virgule (« Imril (Capitaine de la
|
||||||
|
* Garde) » est cite « Imril ») et sans article initial (« du Maitre de Jais » cite « Le
|
||||||
|
* Maitre de Jais ») ;</li>
|
||||||
|
* <li>un PNJ et un adversaire de meme nom sont la meme personne : le renvoi va a la fiche du
|
||||||
|
* PNJ ; deux PNJ (ou deux adversaires) de meme nom : aucun n'est repere (homonymes) ;</li>
|
||||||
|
* <li>nom d'un seul mot : repere seulement s'il n'apparait nulle part en minuscules dans le
|
||||||
|
* livret (« Rose » ou « Garde » sont aussi des mots courants) ;</li>
|
||||||
|
* <li>nom d'adversaire en plusieurs mots : majuscule initiale indifferente (« un sbire des
|
||||||
|
* masques de suie ») ; nom de PNJ : casse exacte ;</li>
|
||||||
|
* <li>sauf option contraire ({@code shortNames}) : premier mot du nom d'un PNJ, titre saute (« Maelis »
|
||||||
|
* pour « Maelis la Discrete », « Halvrak » pour « Sergent Halvrak Stonebrow »), s'il est
|
||||||
|
* propre a cette personne et n'est ni un mot courant du livret, ni le titre d'une page de
|
||||||
|
* lore.</li>
|
||||||
|
* </ul>
|
||||||
|
* Jamais dans un titre, un libelle, un lien existant, un tableau d'index ni la fiche de la
|
||||||
|
* personne elle-meme. Ne connait que les fiches effectivement presentes dans le livret : une
|
||||||
|
* partie non exportee ne produit ni numero de page ni lien.
|
||||||
|
*/
|
||||||
|
final class PdfMentions {
|
||||||
|
|
||||||
|
/** Une fiche du livret : ancre de sa carte ({@code npc-12}, {@code enemy-7}) et nom affiche. */
|
||||||
|
record Entity(String anchor, String name, boolean npc) {}
|
||||||
|
|
||||||
|
private static final Set<String> ARTICLES = Set.of("le", "la", "les", "un", "une", "the", "a", "an");
|
||||||
|
/** Premiers mots qui ne designent personne en particulier : jamais un nom court. */
|
||||||
|
private static final Set<String> TITLES = Set.of(
|
||||||
|
"maître", "maitre", "maîtresse", "dame", "sire", "seigneur", "messire", "capitaine", "sergent",
|
||||||
|
"lieutenant", "commandant", "général", "colonel", "père", "mère", "frère", "sœur", "soeur", "oncle",
|
||||||
|
"tante", "roi", "reine", "prince", "princesse", "comte", "comtesse", "baron", "baronne", "duc",
|
||||||
|
"duchesse", "docteur", "professeur", "saint", "sainte", "grand", "grande", "vieux", "vieille",
|
||||||
|
"petit", "petite", "jeune", "maire", "garde", "chef", "monsieur", "madame", "mademoiselle",
|
||||||
|
"lord", "lady", "king", "queen", "master", "mistress", "captain", "brother", "sister", "father",
|
||||||
|
"mother", "doctor", "young", "mister", "miss", "elder", "sergeant", "general", "count", "countess",
|
||||||
|
"duke", "duchess", "mama", "papa", "little", "great");
|
||||||
|
/** Elements dont le texte n'est jamais annote (titres, libelles, liens, index, legendes). */
|
||||||
|
private static final Set<String> SKIP_TAGS = Set.of("a", "h1", "h2", "h3", "thead", "th");
|
||||||
|
private static final Set<String> SKIP_CLASSES = Set.of("persona-name", "arc-head", "chapter-head", "scene-head",
|
||||||
|
"room-head", "field-label", "box-label", "eyebrow", "scene-meta", "caption", "map-page", "annex-table",
|
||||||
|
"stat-array", "level", "dropcap", "tech-table");
|
||||||
|
/** Une nouvelle unite de lecture : la premiere mention y est de nouveau annotee. */
|
||||||
|
private static final Set<String> UNIT_CLASSES = Set.of("scene", "card", "chapter", "arc");
|
||||||
|
/** Ancres de la narration : une fiche citee ensuite « apparait » dans cette scene, ce chapitre... */
|
||||||
|
private static final List<String> CONTEXT_PREFIXES = List.of("scene-", "ch-", "quest-", "arc-");
|
||||||
|
private static final Pattern CLASS_ATTR = Pattern.compile(" class=\"([^\"]*)\"");
|
||||||
|
private static final Pattern ID_ATTR = Pattern.compile(" id=\"([^\"]*)\"");
|
||||||
|
private static final Pattern HREF_ATTR = Pattern.compile(" href=\"#([^\"]*)\"");
|
||||||
|
private static final Pattern WORD = Pattern.compile("[\\p{L}\\p{N}]+");
|
||||||
|
private static final String NOT_AFTER_WORD = "(?<![\\p{L}\\p{N}])(?<![\\p{L}\\p{N}]-)";
|
||||||
|
private static final String NOT_BEFORE_WORD = "(?![\\p{L}\\p{N}])(?!-[\\p{L}\\p{N}])";
|
||||||
|
|
||||||
|
private final Pattern pattern;
|
||||||
|
/** Entite de chaque groupe capturant du motif (meme ordre). */
|
||||||
|
private final List<Entity> byGroup;
|
||||||
|
|
||||||
|
private PdfMentions(Pattern pattern, List<Entity> byGroup) {
|
||||||
|
this.pattern = pattern;
|
||||||
|
this.byGroup = byGroup;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param entities fiches presentes dans le livret
|
||||||
|
* @param reservedTitles titres qui ne peuvent pas servir de nom court (pages de lore)
|
||||||
|
* @param shortNames reperer aussi le premier mot du nom des PNJ
|
||||||
|
* @param body corps du livret (XHTML) : sert a ecarter les mots courants
|
||||||
|
*/
|
||||||
|
static PdfMentions of(List<Entity> entities, Collection<String> reservedTitles, boolean shortNames,
|
||||||
|
CharSequence body) {
|
||||||
|
Set<String> words = shortNames || hasSingleWordName(entities) ? wordsOf(body) : Set.of();
|
||||||
|
Map<String, Entity> owners = nameOwners(entities);
|
||||||
|
// Formes a reperer -> fiche.
|
||||||
|
Map<String, Entity> forms = new LinkedHashMap<>();
|
||||||
|
for (Entity e : entities) {
|
||||||
|
String core = core(e.name());
|
||||||
|
if (core == null || owners.get(key(core)) != e) continue;
|
||||||
|
boolean single = !core.contains(" ");
|
||||||
|
if (single && isCommonWord(core, words)) continue;
|
||||||
|
forms.put(core, e);
|
||||||
|
}
|
||||||
|
if (shortNames) addShortNames(forms, entities, owners, reservedTitles, words);
|
||||||
|
|
||||||
|
List<String> ordered = new ArrayList<>(forms.keySet());
|
||||||
|
ordered.sort((a, b) -> b.length() - a.length()); // le nom le plus long d'abord
|
||||||
|
StringBuilder regex = new StringBuilder(NOT_AFTER_WORD).append("(?:");
|
||||||
|
List<Entity> byGroup = new ArrayList<>();
|
||||||
|
for (String form : ordered) {
|
||||||
|
Entity e = forms.get(form);
|
||||||
|
if (!byGroup.isEmpty()) regex.append('|');
|
||||||
|
// Adversaire en plusieurs mots : nom commun, majuscule initiale indifferente.
|
||||||
|
regex.append('(').append(formRegex(form, !e.npc() && form.contains(" "))).append(')');
|
||||||
|
byGroup.add(e);
|
||||||
|
}
|
||||||
|
regex.append(')').append(NOT_BEFORE_WORD);
|
||||||
|
return new PdfMentions(byGroup.isEmpty() ? null : Pattern.compile(regex.toString()), byGroup);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aucune fiche reperable : le corps est laisse tel quel. */
|
||||||
|
boolean isEmpty() {
|
||||||
|
return pattern == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasSingleWordName(List<Entity> entities) {
|
||||||
|
for (Entity e : entities) {
|
||||||
|
String core = core(e.name());
|
||||||
|
if (core != null && !core.contains(" ")) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nom (en minuscules) -> la fiche qu'il designe, ou null s'il est ambigu. Un PNJ et un
|
||||||
|
* adversaire de meme nom sont la meme personne (sa fiche et son bloc de stats) : le nom
|
||||||
|
* designe le PNJ. Deux PNJ, ou deux adversaires sans PNJ, de meme nom : ambigu.
|
||||||
|
*/
|
||||||
|
private static Map<String, Entity> nameOwners(List<Entity> entities) {
|
||||||
|
Map<String, List<Entity>> byName = new LinkedHashMap<>();
|
||||||
|
for (Entity e : entities) {
|
||||||
|
String core = core(e.name());
|
||||||
|
if (core != null) byName.computeIfAbsent(key(core), k -> new ArrayList<>()).add(e);
|
||||||
|
}
|
||||||
|
Map<String, Entity> owners = new HashMap<>();
|
||||||
|
byName.forEach((name, sheets) -> {
|
||||||
|
List<Entity> npcs = sheets.stream().filter(Entity::npc).toList();
|
||||||
|
owners.put(name, npcs.size() == 1 ? npcs.get(0) : sheets.size() == 1 ? sheets.get(0) : null);
|
||||||
|
});
|
||||||
|
return owners;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Premier mot (hors titre) du nom d'un PNJ, s'il ne peut designer que lui. */
|
||||||
|
private static void addShortNames(Map<String, Entity> forms, List<Entity> entities, Map<String, Entity> owners,
|
||||||
|
Collection<String> reservedTitles, Set<String> words) {
|
||||||
|
// Chaque mot de chaque nom -> personne qui le porte (null si plusieurs personnes).
|
||||||
|
Map<String, Entity> tokenOwners = new HashMap<>();
|
||||||
|
for (Entity e : entities) {
|
||||||
|
String core = core(e.name());
|
||||||
|
if (core == null) continue;
|
||||||
|
Entity owner = owners.get(key(core));
|
||||||
|
Entity person = owner != null ? owner : e; // meme personne en PNJ et en adversaire
|
||||||
|
for (String token : new LinkedHashSet<>(List.of(core.split(" ")))) {
|
||||||
|
String k = key(token);
|
||||||
|
if (!tokenOwners.containsKey(k)) tokenOwners.put(k, person);
|
||||||
|
else if (tokenOwners.get(k) != person) tokenOwners.put(k, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Set<String> reserved = new HashSet<>();
|
||||||
|
for (String title : reservedTitles) {
|
||||||
|
String core = core(title);
|
||||||
|
if (core != null) reserved.add(key(core));
|
||||||
|
}
|
||||||
|
for (Entity e : entities) {
|
||||||
|
String core = core(e.name());
|
||||||
|
if (!e.npc() || core == null || !core.contains(" ") || owners.get(key(core)) != e) continue;
|
||||||
|
String first = firstNameToken(core);
|
||||||
|
if (first == null) continue;
|
||||||
|
String k = key(first);
|
||||||
|
boolean proper = first.length() >= 4 && Character.isUpperCase(first.charAt(0))
|
||||||
|
&& first.chars().allMatch(Character::isLetter);
|
||||||
|
if (!proper || tokenOwners.get(k) != e || owners.containsKey(k)
|
||||||
|
|| reserved.contains(k) || isCommonWord(first, words)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
forms.putIfAbsent(first, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Premier mot du nom qui n'est pas un titre (« Halvrak » pour « Sergent Halvrak Stonebrow »). */
|
||||||
|
private static String firstNameToken(String core) {
|
||||||
|
for (String token : core.split(" ")) {
|
||||||
|
if (!TITLES.contains(key(token))) return token;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int firstOf(String s, char a, char b) {
|
||||||
|
int ia = s.indexOf(a), ib = s.indexOf(b);
|
||||||
|
return ia < 0 ? ib : ib < 0 ? ia : Math.min(ia, ib);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nom sous lequel le texte cite la fiche : sans la precision entre parentheses ni l'epithete
|
||||||
|
* apres une virgule (« Imril (Capitaine de la Garde) », « Krogg, Goblin King »), sans article
|
||||||
|
* initial ni espaces superflus ; null s'il est trop court pour etre repere.
|
||||||
|
*/
|
||||||
|
static String core(String name) {
|
||||||
|
if (name == null) return null;
|
||||||
|
int cut = firstOf(name, '(', ',');
|
||||||
|
if (cut > 0) name = name.substring(0, cut);
|
||||||
|
String n = name.replace(' ', ' ').replace('’', '\'').strip().replaceAll("\\s+", " ");
|
||||||
|
String lower = n.toLowerCase(Locale.ROOT);
|
||||||
|
if (lower.startsWith("l'") && n.length() > 2) {
|
||||||
|
n = n.substring(2).strip();
|
||||||
|
} else {
|
||||||
|
int space = n.indexOf(' ');
|
||||||
|
if (space > 0 && ARTICLES.contains(lower.substring(0, space))) n = n.substring(space + 1);
|
||||||
|
}
|
||||||
|
boolean letters = n.chars().filter(Character::isLetter).count() >= 3;
|
||||||
|
return letters ? n : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String key(String s) {
|
||||||
|
return s.toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le mot existe aussi sans majuscule dans le livret : c'est un mot courant, pas un nom. */
|
||||||
|
private static boolean isCommonWord(String word, Set<String> words) {
|
||||||
|
String lower = word.toLowerCase(Locale.ROOT);
|
||||||
|
return !lower.equals(word) && words.contains(lower);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tous les mots du texte du livret (hors balises), casse conservee. */
|
||||||
|
private static Set<String> wordsOf(CharSequence body) {
|
||||||
|
Set<String> words = new HashSet<>();
|
||||||
|
String html = body.toString();
|
||||||
|
int i = 0;
|
||||||
|
while (i < html.length()) {
|
||||||
|
int lt = html.indexOf('<', i);
|
||||||
|
int end = lt < 0 ? html.length() : lt;
|
||||||
|
if (end > i) {
|
||||||
|
Matcher m = WORD.matcher(html).region(i, end);
|
||||||
|
while (m.find()) words.add(m.group());
|
||||||
|
}
|
||||||
|
if (lt < 0) break;
|
||||||
|
int gt = html.indexOf('>', lt);
|
||||||
|
if (gt < 0) break;
|
||||||
|
i = gt + 1;
|
||||||
|
}
|
||||||
|
return words;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Motif d'une forme, telle qu'elle apparait dans le XHTML (echappee, espaces et apostrophes varies). */
|
||||||
|
private static String formRegex(String form, boolean anyInitialCase) {
|
||||||
|
StringBuilder r = new StringBuilder();
|
||||||
|
for (int i = 0; i < form.length(); i++) {
|
||||||
|
char c = form.charAt(i);
|
||||||
|
if (c == ' ') {
|
||||||
|
r.append("[ \\u00A0]+");
|
||||||
|
} else if (c == '\'') {
|
||||||
|
r.append("['’]");
|
||||||
|
} else if (i == 0 && anyInitialCase && Character.isLetter(c)) {
|
||||||
|
r.append('[').append(Pattern.quote(String.valueOf(Character.toUpperCase(c))))
|
||||||
|
.append(Pattern.quote(String.valueOf(Character.toLowerCase(c)))).append(']');
|
||||||
|
} else {
|
||||||
|
r.append(Pattern.quote(esc(String.valueOf(c))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====================================================================== Annotation
|
||||||
|
|
||||||
|
/** Element ouvert, avec ce qu'il impose au texte qu'il contient. */
|
||||||
|
private record Frame(boolean skip, boolean quiet, String card, boolean dropCap) {}
|
||||||
|
|
||||||
|
/** Etat d'un passage sur le corps du livret. */
|
||||||
|
private static final class Pass {
|
||||||
|
final Deque<Frame> stack = new ArrayDeque<>();
|
||||||
|
/** Fiches deja renvoyees dans l'unite de lecture courante. */
|
||||||
|
final Set<String> seen = new HashSet<>();
|
||||||
|
final Map<String, Set<String>> appearances = new LinkedHashMap<>();
|
||||||
|
/** Ancre de la scene, du chapitre, de la quete ou de l'arc en cours ; null hors narration. */
|
||||||
|
String context;
|
||||||
|
/** Le texte qui vient continue le mot commence par une lettrine. */
|
||||||
|
boolean glued;
|
||||||
|
|
||||||
|
void appears(String sheetAnchor) {
|
||||||
|
if (context != null) appearances.computeIfAbsent(sheetAnchor, k -> new LinkedHashSet<>()).add(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annote le corps du livret (remplace son contenu) et rend, pour chaque fiche citee, les
|
||||||
|
* ancres des scenes, chapitres, quetes ou arcs ou elle apparait, dans l'ordre du livret.
|
||||||
|
*/
|
||||||
|
Map<String, Set<String>> linkInto(StringBuilder body) {
|
||||||
|
Pass pass = new Pass();
|
||||||
|
if (isEmpty()) return pass.appearances;
|
||||||
|
String html = body.toString();
|
||||||
|
StringBuilder out = new StringBuilder(html.length() + 4096);
|
||||||
|
int i = 0;
|
||||||
|
while (i < html.length()) {
|
||||||
|
int lt = html.indexOf('<', i);
|
||||||
|
int end = lt < 0 ? html.length() : lt;
|
||||||
|
if (end > i) {
|
||||||
|
String text = html.substring(i, end);
|
||||||
|
Frame top = pass.stack.peek();
|
||||||
|
if (top != null && top.skip()) out.append(text);
|
||||||
|
else annotate(text, top, pass, out);
|
||||||
|
}
|
||||||
|
pass.glued = false;
|
||||||
|
if (lt < 0) break;
|
||||||
|
int gt = html.indexOf('>', lt);
|
||||||
|
if (gt < 0) {
|
||||||
|
out.append(html, lt, html.length());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
String tag = html.substring(lt, gt + 1);
|
||||||
|
out.append(tag);
|
||||||
|
i = gt + 1;
|
||||||
|
if (tag.startsWith("</")) {
|
||||||
|
if (!pass.stack.isEmpty()) pass.glued = pass.stack.pop().dropCap();
|
||||||
|
} else if (!tag.endsWith("/>")) {
|
||||||
|
pass.stack.push(open(tag, tagName(tag), pass));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
body.setLength(0);
|
||||||
|
body.append(out);
|
||||||
|
return pass.appearances;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Frame open(String tag, String name, Pass pass) {
|
||||||
|
Frame parent = pass.stack.peek();
|
||||||
|
Set<String> classes = Set.of();
|
||||||
|
Matcher c = CLASS_ATTR.matcher(tag);
|
||||||
|
if (c.find()) classes = Set.of(c.group(1).trim().split("\\s+"));
|
||||||
|
Matcher idm = ID_ATTR.matcher(tag);
|
||||||
|
String id = idm.find() ? idm.group(1) : "";
|
||||||
|
|
||||||
|
boolean skip = (parent != null && parent.skip()) || SKIP_TAGS.contains(name);
|
||||||
|
for (String cls : classes) skip |= SKIP_CLASSES.contains(cls);
|
||||||
|
// Texte a lire aux joueurs : la fiche y « apparait », mais on n'y glisse pas de renvoi.
|
||||||
|
boolean quiet = (parent != null && parent.quiet()) || classes.contains("readaloud");
|
||||||
|
String card = parent != null ? parent.card() : null;
|
||||||
|
if (isSheet(id)) card = id;
|
||||||
|
if ("h1".equals(name)) pass.context = null; // nouvelle partie : fiches, tables, lore...
|
||||||
|
if (CONTEXT_PREFIXES.stream().anyMatch(id::startsWith)) pass.context = id;
|
||||||
|
if ("h1".equals(name) || "h2".equals(name) || classes.stream().anyMatch(UNIT_CLASSES::contains)) {
|
||||||
|
pass.seen.clear();
|
||||||
|
}
|
||||||
|
// Un renvoi deja pose par le rendu (adversaires d'un combat) vaut premiere mention.
|
||||||
|
if ("a".equals(name) && classes.contains("xref")) {
|
||||||
|
Matcher h = HREF_ATTR.matcher(tag);
|
||||||
|
if (h.find() && isSheet(h.group(1))) {
|
||||||
|
pass.seen.add(h.group(1));
|
||||||
|
pass.appears(h.group(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Frame(skip, quiet, card, classes.contains("dropcap"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isSheet(String anchor) {
|
||||||
|
return anchor.startsWith("npc-") || anchor.startsWith("enemy-");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void annotate(String text, Frame top, Pass pass, StringBuilder out) {
|
||||||
|
Matcher m = pattern.matcher(text);
|
||||||
|
int last = 0;
|
||||||
|
while (m.find()) {
|
||||||
|
if (m.start() == 0 && pass.glued) continue; // suite d'un mot coupe par une balise (lettrine)
|
||||||
|
Entity e = entityOf(m);
|
||||||
|
if (top != null && e.anchor().equals(top.card())) continue; // la fiche ne se cite pas elle-meme
|
||||||
|
pass.appears(e.anchor());
|
||||||
|
if ((top != null && top.quiet()) || !pass.seen.add(e.anchor())) continue;
|
||||||
|
out.append(text, last, m.start())
|
||||||
|
.append("<a class=\"xref\" href=\"#").append(e.anchor()).append("\">").append(m.group())
|
||||||
|
.append("</a> ").append(pageRef(e.anchor()));
|
||||||
|
last = m.end();
|
||||||
|
}
|
||||||
|
out.append(text, last, text.length());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Entity entityOf(Matcher m) {
|
||||||
|
for (int g = 1; g <= byGroup.size(); g++) {
|
||||||
|
if (m.group(g) != null) return byGroup.get(g - 1);
|
||||||
|
}
|
||||||
|
throw new IllegalStateException("Mention sans fiche : " + m.group());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String tagName(String tag) {
|
||||||
|
int start = tag.startsWith("</") ? 2 : 1;
|
||||||
|
int end = start;
|
||||||
|
while (end < tag.length() && Character.isLetterOrDigit(tag.charAt(end))) end++;
|
||||||
|
return tag.substring(start, end).toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||||
|
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||||
|
import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
|
||||||
|
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
|
||||||
|
import org.apache.pdfbox.util.Matrix;
|
||||||
|
|
||||||
|
import java.awt.Color;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Habillage du theme « Parchemin », dessine APRES la pagination (sous le contenu) : la mise
|
||||||
|
* en page, les renvois et le texte ne bougent pas.
|
||||||
|
* <ul>
|
||||||
|
* <li>fond parchemin sur chaque page — une seule image embarquee dans le PDF et reutilisee
|
||||||
|
* par toutes les pages (retournee une page sur deux : deux pages en vis-a-vis ne montrent
|
||||||
|
* pas les memes taches ; tournee d'un quart de tour sous les cartes en paysage) ; jamais
|
||||||
|
* en mode impression, ou une carte imprimee reste donc sur blanc ;</li>
|
||||||
|
* <li>filet sous le titre courant et pied de page orne autour du numero de page, sur les
|
||||||
|
* pages portrait.</li>
|
||||||
|
* </ul>
|
||||||
|
* Seule la couverture illustree a fond perdu n'a pas de parchemin dessous.
|
||||||
|
*/
|
||||||
|
final class PdfParchmentDecor {
|
||||||
|
private static final Color RED = new Color(0x7a2a1a);
|
||||||
|
private static final Color GOLD = new Color(0xb08d4a);
|
||||||
|
private static final Color PRINT = new Color(0x8a8a8a);
|
||||||
|
private static final float CM = 72f / 2.54f;
|
||||||
|
|
||||||
|
private static final Color PLATE_FILL = new Color(0xf3e6c4);
|
||||||
|
|
||||||
|
private PdfParchmentDecor() {}
|
||||||
|
|
||||||
|
/** Rectangle d'une page, en points PDF (origine en bas a gauche). */
|
||||||
|
record Area(float x, float y, float width, float height) {}
|
||||||
|
|
||||||
|
/** Image fondue a dessiner sur une page : zone, pixels deja recadres, bord qui se fond. */
|
||||||
|
record Fade(int page, Area area, BufferedImage image, PdfBrushFade.Edge edge, int seed) {}
|
||||||
|
|
||||||
|
/** Part de la hauteur de la page qu'une image fondue en bas de page doit au moins occuper. */
|
||||||
|
private static final double FADE_MIN_HEIGHT_RATIO = 0.24;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zone d'une image fondue, d'apres son emplacement reserve une fois la mise en page faite.
|
||||||
|
* <ul>
|
||||||
|
* <li>bord superieur fondu (image de bas de page) : de l'emplacement — la fin du texte —
|
||||||
|
* jusqu'au bas de la page, a fond perdu en bas et sur les cotes ; null s'il reste moins
|
||||||
|
* d'un quart de page, ou si l'emplacement est seul en haut d'une page (rien au-dessus) ;</li>
|
||||||
|
* <li>bord inferieur fondu (bandeau d'ouverture) : l'emplacement lui-meme, prolonge jusqu'au
|
||||||
|
* haut de la page s'il en occupe le debut.</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* @param slotBottom distance du bas de l'emplacement au bas de la page, en points
|
||||||
|
* @param slotHeight hauteur de l'emplacement, en points
|
||||||
|
* @param aspect hauteur / largeur de l'image
|
||||||
|
*/
|
||||||
|
static Area fadeArea(PdfExportOptions.PageFormat format, PdfBrushFade.Edge edge, float slotBottom,
|
||||||
|
float slotHeight, double aspect) {
|
||||||
|
float pageWidth = (float) format.widthCm * CM;
|
||||||
|
float pageHeight = (float) format.heightCm * CM;
|
||||||
|
float contentTop = pageHeight - (float) format.marginTopCm * CM;
|
||||||
|
float slotTop = slotBottom + slotHeight;
|
||||||
|
boolean firstOnPage = slotTop > contentTop - 3;
|
||||||
|
if (edge == PdfBrushFade.Edge.BOTTOM) {
|
||||||
|
float top = firstOnPage ? pageHeight : slotTop;
|
||||||
|
return new Area(0, slotBottom, pageWidth, top - slotBottom);
|
||||||
|
}
|
||||||
|
float available = slotTop - 0.3f * CM;
|
||||||
|
if (firstOnPage || available < pageHeight * FADE_MIN_HEIGHT_RATIO) return null;
|
||||||
|
// Pas plus haute que l'image ne le supporte : au-dela, on n'en verrait qu'une bande etroite.
|
||||||
|
float height = (float) Math.min(available, pageWidth * aspect * 1.2);
|
||||||
|
return new Area(0, 0, pageWidth, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zone d'une image fondue logee dans le coin inferieur droit, quand la pleine largeur n'est
|
||||||
|
* pas libre : en deux colonnes, la colonne de gauche est pleine mais le texte s'arrete plus
|
||||||
|
* haut dans celle de droite. De la fin du texte au bas de la page, de la gouttiere au bord
|
||||||
|
* droit. Null si le texte finit dans la colonne de gauche ou s'il reste moins d'un quart de page.
|
||||||
|
*
|
||||||
|
* @param markX abscisse du repere pose a la fin du texte, en points
|
||||||
|
* @param markBottom distance du bas du repere au bas de la page, en points
|
||||||
|
*/
|
||||||
|
static Area cornerArea(PdfExportOptions.PageFormat format, float markX, float markBottom, float markHeight) {
|
||||||
|
float pageWidth = (float) format.widthCm * CM;
|
||||||
|
float pageHeight = (float) format.heightCm * CM;
|
||||||
|
if (markX < pageWidth / 2) return null;
|
||||||
|
float available = markBottom + markHeight - 0.3f * CM;
|
||||||
|
if (available < pageHeight * FADE_MIN_HEIGHT_RATIO) return null;
|
||||||
|
float x = markX - 0.3f * CM;
|
||||||
|
float width = pageWidth - x;
|
||||||
|
return new Area(x, 0, width, Math.min(available, width * 1.45f));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param illustratedCover vrai si la premiere page est une couverture illustree a fond perdu */
|
||||||
|
static void draw(PDDocument document, PdfExportOptions options, boolean illustratedCover) throws IOException {
|
||||||
|
draw(document, options, illustratedCover, List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param illustratedCover vrai si la premiere page est une couverture illustree a fond perdu
|
||||||
|
* @param fades images fondues, dessinees sur le parchemin et sous le contenu
|
||||||
|
*/
|
||||||
|
static void draw(PDDocument document, PdfExportOptions options, boolean illustratedCover, List<Fade> fades)
|
||||||
|
throws IOException {
|
||||||
|
PDImageXObject texture = options.parchmentBackground()
|
||||||
|
? JPEGFactory.createFromByteArray(document, PdfParchmentTexture.jpeg()) : null;
|
||||||
|
PdfExportOptions.PageFormat format = options.format();
|
||||||
|
float folioY = (float) format.marginBottomCm * CM / 2;
|
||||||
|
float side = (float) format.marginSideCm * CM;
|
||||||
|
// Sous le titre courant (centre dans la marge haute), a distance du contenu.
|
||||||
|
float headerRuleDrop = (float) format.marginTopCm * CM * 0.7f;
|
||||||
|
for (int i = 0; i < document.getNumberOfPages(); i++) {
|
||||||
|
var page = document.getPage(i);
|
||||||
|
PDRectangle bounds = page.getMediaBox();
|
||||||
|
boolean landscape = bounds.getWidth() > bounds.getHeight();
|
||||||
|
boolean cover = i == 0;
|
||||||
|
if ((cover && illustratedCover) || ((cover || landscape) && texture == null)) continue;
|
||||||
|
Object[] overHeader = null;
|
||||||
|
try (var canvas = new PDPageContentStream(document, page,
|
||||||
|
PDPageContentStream.AppendMode.PREPEND, true, true)) {
|
||||||
|
canvas.saveGraphicsState();
|
||||||
|
if (texture != null && landscape) landscapeBackground(canvas, texture, bounds, i % 2 == 1);
|
||||||
|
else if (texture != null) background(canvas, texture, bounds, i % 2 == 1);
|
||||||
|
boolean fadedTop = false, fadedBottom = false;
|
||||||
|
for (Fade fade : fades) {
|
||||||
|
if (fade.page() != i) continue;
|
||||||
|
PDImageXObject image = PdfBrushFade.image(document, fade.image(), fade.edge(), fade.seed());
|
||||||
|
Area a = fade.area();
|
||||||
|
canvas.drawImage(image, a.x(), a.y(), a.width(), a.height());
|
||||||
|
if (fade.edge() == PdfBrushFade.Edge.TOP) {
|
||||||
|
fadedBottom = true;
|
||||||
|
} else if (fade.edge() == PdfBrushFade.Edge.BOTTOM) {
|
||||||
|
fadedTop = true;
|
||||||
|
if (a.y() + a.height() > bounds.getHeight() - 1) overHeader = new Object[]{image, a};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Titre courant et numero de page sont masques sur la premiere page (cf. export-parchment.css) ;
|
||||||
|
// les cartes en paysage ont leur propre pied de page, sans ornement.
|
||||||
|
if (!cover && !landscape) {
|
||||||
|
if (!fadedTop) {
|
||||||
|
headerRule(canvas, side, bounds.getWidth() - side, bounds.getHeight() - headerRuleDrop,
|
||||||
|
options.printFriendly());
|
||||||
|
}
|
||||||
|
// Sur une image de bas de page, le numero se lit dans un cartouche clair.
|
||||||
|
if (fadedBottom) folioPlate(canvas, bounds.getWidth() / 2, folioY);
|
||||||
|
else folio(canvas, bounds.getWidth() / 2, folioY, options.printFriendly());
|
||||||
|
}
|
||||||
|
canvas.restoreGraphicsState();
|
||||||
|
}
|
||||||
|
if (overHeader != null) {
|
||||||
|
// Bandeau a fond perdu en haut : l'image repasse AU-DESSUS du contenu dans la seule
|
||||||
|
// marge haute, pour couvrir le titre courant que le moteur y a ecrit.
|
||||||
|
float marginTop = (float) format.marginTopCm * CM;
|
||||||
|
Area a = (Area) overHeader[1];
|
||||||
|
try (var over = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
||||||
|
over.addRect(0, bounds.getHeight() - marginTop, bounds.getWidth(), marginTop);
|
||||||
|
over.clip();
|
||||||
|
over.drawImage((PDImageXObject) overHeader[0], a.x(), a.y(), a.width(), a.height());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Petit cartouche clair sous le numero de page (lisible sur une image sombre). */
|
||||||
|
private static void folioPlate(PDPageContentStream c, float center, float y) throws IOException {
|
||||||
|
float w = 17, h = 8.5f, k = 0.55f;
|
||||||
|
c.setNonStrokingColor(PLATE_FILL);
|
||||||
|
c.setStrokingColor(GOLD);
|
||||||
|
c.setLineWidth(.6f);
|
||||||
|
c.moveTo(center - w, y);
|
||||||
|
c.curveTo(center - w, y + h * k, center - w * k, y + h, center, y + h);
|
||||||
|
c.curveTo(center + w * k, y + h, center + w, y + h * k, center + w, y);
|
||||||
|
c.curveTo(center + w, y - h * k, center + w * k, y - h, center, y - h);
|
||||||
|
c.curveTo(center - w * k, y - h, center - w, y - h * k, center - w, y);
|
||||||
|
c.closePath();
|
||||||
|
c.fillAndStroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void background(PDPageContentStream c, PDImageXObject texture, PDRectangle bounds,
|
||||||
|
boolean mirrored) throws IOException {
|
||||||
|
c.saveGraphicsState();
|
||||||
|
if (mirrored) c.transform(new Matrix(-1, 0, 0, 1, bounds.getWidth(), 0));
|
||||||
|
c.drawImage(texture, 0, 0, bounds.getWidth(), bounds.getHeight());
|
||||||
|
c.restoreGraphicsState();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Page en paysage : la meme image, tournee d'un quart de tour (dans un sens ou dans l'autre). */
|
||||||
|
private static void landscapeBackground(PDPageContentStream c, PDImageXObject texture, PDRectangle bounds,
|
||||||
|
boolean reversed) throws IOException {
|
||||||
|
c.saveGraphicsState();
|
||||||
|
c.transform(reversed ? new Matrix(0, -1, 1, 0, 0, bounds.getHeight())
|
||||||
|
: new Matrix(0, 1, -1, 0, bounds.getWidth(), 0));
|
||||||
|
c.drawImage(texture, 0, 0, bounds.getHeight(), bounds.getWidth());
|
||||||
|
c.restoreGraphicsState();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void headerRule(PDPageContentStream c, float left, float right, float y,
|
||||||
|
boolean print) throws IOException {
|
||||||
|
c.setStrokingColor(print ? PRINT : GOLD);
|
||||||
|
c.setLineWidth(.5f);
|
||||||
|
c.moveTo(left, y);
|
||||||
|
c.lineTo(right, y);
|
||||||
|
c.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** De part et d'autre du numero : un fuseau effile termine par un losange. */
|
||||||
|
private static void folio(PDPageContentStream c, float center, float y, boolean print) throws IOException {
|
||||||
|
c.setNonStrokingColor(print ? PRINT : GOLD);
|
||||||
|
for (int side : new int[]{-1, 1}) {
|
||||||
|
float inner = center + side * 15, outer = center + side * 62;
|
||||||
|
float belly = inner + (outer - inner) * 0.3f;
|
||||||
|
c.moveTo(inner, y);
|
||||||
|
c.curveTo(belly, y + 1.1f, belly, y + 1.1f, outer, y);
|
||||||
|
c.curveTo(belly, y - 1.1f, belly, y - 1.1f, inner, y);
|
||||||
|
c.closePath();
|
||||||
|
c.fill();
|
||||||
|
}
|
||||||
|
c.setNonStrokingColor(print ? PRINT : RED);
|
||||||
|
for (int side : new int[]{-1, 1}) {
|
||||||
|
float x = center + side * 66.5f;
|
||||||
|
c.moveTo(x, y + 2.6f);
|
||||||
|
c.lineTo(x + 2.6f, y);
|
||||||
|
c.lineTo(x, y - 2.6f);
|
||||||
|
c.lineTo(x - 2.6f, y);
|
||||||
|
c.closePath();
|
||||||
|
c.fill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import javax.imageio.IIOImage;
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import javax.imageio.ImageWriteParam;
|
||||||
|
import javax.imageio.ImageWriter;
|
||||||
|
import javax.imageio.stream.MemoryCacheImageOutputStream;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Texture de parchemin ORIGINALE, calculee (aucune image tierce) : nuages de bruit pour les
|
||||||
|
* variations de teinte, aureoles discretes, grain du papier et bords assombris irreguliers.
|
||||||
|
* Le germe est fixe : la texture est identique d'un export a l'autre. Elle est calculee une
|
||||||
|
* seule fois par JVM (au premier export « Parchemin ») puis conservee en JPEG.
|
||||||
|
*/
|
||||||
|
final class PdfParchmentTexture {
|
||||||
|
|
||||||
|
/** Proportions d'une page A (1 : racine de 2) ; environ 105 ppp sur un A4, 150 sur un A5. */
|
||||||
|
static final int WIDTH = 868;
|
||||||
|
static final int HEIGHT = 1228;
|
||||||
|
private static final float JPEG_QUALITY = 0.8f;
|
||||||
|
|
||||||
|
// Teintes (R, V, B) entre lesquelles la texture se promene.
|
||||||
|
private static final double[] LIGHT = {250, 242, 221};
|
||||||
|
private static final double[] DARK = {232, 216, 180};
|
||||||
|
private static final double[] STAIN = {214, 190, 146};
|
||||||
|
private static final double[] BURN = {168, 128, 82};
|
||||||
|
|
||||||
|
private PdfParchmentTexture() {}
|
||||||
|
|
||||||
|
/** JPEG de la texture, calcule au premier appel. */
|
||||||
|
static byte[] jpeg() {
|
||||||
|
return Holder.JPEG;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Holder {
|
||||||
|
static final byte[] JPEG = encode(render());
|
||||||
|
}
|
||||||
|
|
||||||
|
static BufferedImage render() {
|
||||||
|
BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
|
||||||
|
double ratio = HEIGHT / (double) WIDTH;
|
||||||
|
for (int y = 0; y < HEIGHT; y++) {
|
||||||
|
double v = y / (double) WIDTH; // meme echelle sur les deux axes : bruit non etire
|
||||||
|
for (int x = 0; x < WIDTH; x++) {
|
||||||
|
double u = x / (double) WIDTH;
|
||||||
|
img.setRGB(x, y, pixel(u, v, ratio));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return img;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int pixel(double u, double v, double ratio) {
|
||||||
|
// 1. Grandes variations de teinte (nuages) et grain fin du papier.
|
||||||
|
double cloud = fbm(u * 2.6, v * 2.6, 5, 11);
|
||||||
|
double grain = fbm(u * 46, v * 46, 2, 23);
|
||||||
|
double tone = clamp(0.5 + (cloud - 0.5) * 1.5 + (grain - 0.5) * 0.22);
|
||||||
|
|
||||||
|
// 2. Aureoles : zones ou un bruit moyen depasse un seuil, avec un lisere plus marque.
|
||||||
|
double blot = fbm(u * 5.2 + 31, v * 5.2 + 17, 4, 37);
|
||||||
|
double stain = smooth(0.66, 0.8, blot) * 0.2 + bump(blot, 0.672, 0.018) * 0.1;
|
||||||
|
|
||||||
|
// 3. Bords : distance au bord le plus proche, rendue irreguliere par le bruit.
|
||||||
|
double distance = Math.min(Math.min(u, 1 - u), Math.min(v, ratio - v));
|
||||||
|
double wobble = (fbm(u * 9 + 5, v * 9 + 3, 3, 53) - 0.5) * 0.07;
|
||||||
|
double edge = 1 - smooth(0, 0.075, distance + wobble);
|
||||||
|
edge = edge * edge * 0.46 + (1 - smooth(0, 0.3, distance)) * 0.1;
|
||||||
|
|
||||||
|
int rgb = 0;
|
||||||
|
for (int c = 0; c < 3; c++) {
|
||||||
|
double value = LIGHT[c] + (DARK[c] - LIGHT[c]) * tone;
|
||||||
|
value += (STAIN[c] - value) * stain;
|
||||||
|
value += (BURN[c] - value) * clamp(edge);
|
||||||
|
rgb = (rgb << 8) | (int) Math.round(clamp(value / 255) * 255);
|
||||||
|
}
|
||||||
|
return rgb;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] encode(BufferedImage img) {
|
||||||
|
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
|
||||||
|
try {
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream(160_000);
|
||||||
|
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||||
|
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||||
|
param.setCompressionQuality(JPEG_QUALITY);
|
||||||
|
try (MemoryCacheImageOutputStream stream = new MemoryCacheImageOutputStream(out)) {
|
||||||
|
writer.setOutput(stream);
|
||||||
|
writer.write(null, new IIOImage(img, null, null), param);
|
||||||
|
}
|
||||||
|
return out.toByteArray();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException("Texture parchemin : encodage JPEG impossible", e);
|
||||||
|
} finally {
|
||||||
|
writer.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Bruit de valeur (treillis hache, interpolation lissee) -----
|
||||||
|
|
||||||
|
/** Bruit fractal dans [0, 1] : somme d'octaves de plus en plus fines et faibles. */
|
||||||
|
static double fbm(double x, double y, int octaves, int seed) {
|
||||||
|
double sum = 0, amplitude = 0.5, total = 0;
|
||||||
|
for (int o = 0; o < octaves; o++) {
|
||||||
|
sum += amplitude * noise(x, y, seed + o * 101);
|
||||||
|
total += amplitude;
|
||||||
|
x *= 2.03;
|
||||||
|
y *= 2.03;
|
||||||
|
amplitude *= 0.5;
|
||||||
|
}
|
||||||
|
return sum / total;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double noise(double x, double y, int seed) {
|
||||||
|
int xi = (int) Math.floor(x), yi = (int) Math.floor(y);
|
||||||
|
double fx = fade(x - xi), fy = fade(y - yi);
|
||||||
|
double top = lerp(lattice(xi, yi, seed), lattice(xi + 1, yi, seed), fx);
|
||||||
|
double bottom = lerp(lattice(xi, yi + 1, seed), lattice(xi + 1, yi + 1, seed), fx);
|
||||||
|
return lerp(top, bottom, fy);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valeur pseudo-aleatoire stable dans [0, 1] pour un noeud du treillis. */
|
||||||
|
private static double lattice(int x, int y, int seed) {
|
||||||
|
int h = x * 374761393 + y * 668265263 + seed * 1442695041;
|
||||||
|
h = (h ^ (h >>> 13)) * 1274126177;
|
||||||
|
h ^= h >>> 16;
|
||||||
|
return (h & 0xFFFFFF) / (double) 0xFFFFFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double fade(double t) {
|
||||||
|
return t * t * t * (t * (t * 6 - 15) + 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double lerp(double a, double b, double t) {
|
||||||
|
return a + (b - a) * t;
|
||||||
|
}
|
||||||
|
|
||||||
|
static double clamp(double v) {
|
||||||
|
return Math.max(0, Math.min(1, v));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 0 sous {@code from}, 1 au-dela de {@code to}, transition douce entre les deux. */
|
||||||
|
static double smooth(double from, double to, double v) {
|
||||||
|
double t = clamp((v - from) / (to - from));
|
||||||
|
return t * t * (3 - 2 * t);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bosse de hauteur 1 centree sur {@code center}, nulle au-dela de {@code width}. */
|
||||||
|
private static double bump(double v, double center, double width) {
|
||||||
|
double t = clamp(1 - Math.abs(v - center) / width);
|
||||||
|
return t * t * (3 - 2 * t);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -59,6 +59,17 @@ public class ChapterController {
|
|||||||
return ResponseEntity.ok(chapterMapper.toDTO(updated));
|
return ResponseEntity.ok(chapterMapper.toDTO(updated));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Rattache le chapitre à une méthode guidée, ou l'en détache ({@code method} nul ou vide). */
|
||||||
|
@PutMapping("/{id}/guided-method")
|
||||||
|
public ResponseEntity<ChapterDTO> setGuidedMethod(@PathVariable String id, @RequestBody GuidedMethodRequest req) {
|
||||||
|
if (!chapterService.chapterExists(id)) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(chapterMapper.toDTO(chapterService.setGuidedMethod(id, req.method())));
|
||||||
|
}
|
||||||
|
|
||||||
|
public record GuidedMethodRequest(String method) {}
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ResponseEntity<Void> deleteChapter(@PathVariable String id) {
|
public ResponseEntity<Void> deleteChapter(@PathVariable String id) {
|
||||||
chapterService.deleteChapter(id);
|
chapterService.deleteChapter(id);
|
||||||
|
|||||||
+7
-3
@@ -23,7 +23,9 @@ import java.util.NoSuchElementException;
|
|||||||
* <p>
|
* <p>
|
||||||
* Options (toutes facultatives, defaut = livret MJ complet en A4) :
|
* Options (toutes facultatives, defaut = livret MJ complet en A4) :
|
||||||
* {@code edition=gm|player}, {@code format=A4|A5|LETTER}, {@code print=true} (sans aplats),
|
* {@code edition=gm|player}, {@code format=A4|A5|LETTER}, {@code print=true} (sans aplats),
|
||||||
* {@code sections=NARRATIVE,QUESTS,NPCS,ENEMIES,TABLES,LORE}, {@code lore=ALL|LINKED}.
|
* {@code sections=NARRATIVE,QUESTS,NPCS,ENEMIES,TABLES,LORE}, {@code lore=ALL|LINKED},
|
||||||
|
* {@code theme=classic|parchment} (habillage ; classique par defaut), {@code shortNames=false}
|
||||||
|
* (renvois automatiques : ne plus reconnaitre le premier mot du nom des PNJ, noms complets seulement).
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/campaigns/{campaignId}/pdf-export")
|
@RequestMapping("/api/campaigns/{campaignId}/pdf-export")
|
||||||
@@ -41,8 +43,10 @@ public class PdfExportController {
|
|||||||
@RequestParam(required = false) String format,
|
@RequestParam(required = false) String format,
|
||||||
@RequestParam(required = false) Boolean print,
|
@RequestParam(required = false) Boolean print,
|
||||||
@RequestParam(required = false) String sections,
|
@RequestParam(required = false) String sections,
|
||||||
@RequestParam(required = false) String lore) {
|
@RequestParam(required = false) String lore,
|
||||||
PdfExportOptions options = PdfExportOptions.parse(edition, format, print, sections, lore);
|
@RequestParam(required = false) String theme,
|
||||||
|
@RequestParam(required = false) Boolean shortNames) {
|
||||||
|
PdfExportOptions options = PdfExportOptions.parse(edition, format, print, sections, lore, theme, shortNames);
|
||||||
byte[] pdf;
|
byte[] pdf;
|
||||||
String name;
|
String name;
|
||||||
try {
|
try {
|
||||||
|
|||||||
+110
@@ -0,0 +1,110 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.gamesystemcontext.RuleTrainingService;
|
||||||
|
import com.loremind.application.gamesystemcontext.RuleTrainingService.Options;
|
||||||
|
import com.loremind.application.gamesystemcontext.RuleTrainingService.Series;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.RuleTrainingException;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entraînement aux règles d'une campagne : le MJ tranche des situations tirées de ses scènes
|
||||||
|
* et lit un corrigé qui cite les règles de son système. Rien n'est enregistré.
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>{@code GET .../options} — sections de règles et scènes proposées au choix ;</li>
|
||||||
|
* <li>{@code POST .../series} — une série de situations, corrigé compris (un appel à l'IA) ;</li>
|
||||||
|
* <li>{@code POST .../review} — comparaison de la décision écrite par le MJ (un appel à l'IA).</li>
|
||||||
|
* </ul>
|
||||||
|
* 400 si la campagne est inconnue, sans système ou sans règles ; 502 si l'IA est indisponible.
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/campaigns/{campaignId}/rule-training")
|
||||||
|
public class RuleTrainingController {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(RuleTrainingController.class);
|
||||||
|
|
||||||
|
public record SectionDto(String title, int chars, List<String> suggestedFor, boolean otherLanguage) {}
|
||||||
|
|
||||||
|
public record SceneDto(String id, String name, String type) {}
|
||||||
|
|
||||||
|
public record AdventureDto(String id, String arcId, String name, boolean sideQuest, List<SceneDto> scenes) {}
|
||||||
|
|
||||||
|
/** {@code status} : {@code READY}, {@code NO_SYSTEM} ou {@code NO_RULES}. */
|
||||||
|
public record OptionsResponse(String status, String gameSystemId, String gameSystemName,
|
||||||
|
List<SectionDto> sections, List<AdventureDto> adventures) {}
|
||||||
|
|
||||||
|
public record SeriesRequest(List<String> sceneIds, List<String> sectionTitles, List<String> avoid) {}
|
||||||
|
|
||||||
|
public record DrillDto(String sceneId, String sceneName, String situation,
|
||||||
|
String section, String excerpt, String ruling) {}
|
||||||
|
|
||||||
|
public record SeriesResponse(String gameSystemName, List<DrillDto> drills, List<String> sections, int dropped) {}
|
||||||
|
|
||||||
|
public record ReviewRequest(String section, String situation, String excerpt, String ruling, String answer) {}
|
||||||
|
|
||||||
|
/** {@code verdict} : {@code right}, {@code partial} ou {@code off}. */
|
||||||
|
public record ReviewResponse(String verdict, String feedback) {}
|
||||||
|
|
||||||
|
private final RuleTrainingService service;
|
||||||
|
|
||||||
|
public RuleTrainingController(RuleTrainingService service) {
|
||||||
|
this.service = service;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/options")
|
||||||
|
public ResponseEntity<OptionsResponse> options(@PathVariable String campaignId) {
|
||||||
|
Options o = service.options(campaignId);
|
||||||
|
return ResponseEntity.ok(new OptionsResponse(
|
||||||
|
o.status().name(), o.gameSystemId(), o.gameSystemName(),
|
||||||
|
o.sections().stream()
|
||||||
|
.map(s -> new SectionDto(s.title(), s.chars(), s.suggestedFor().stream().map(Enum::name).toList(),
|
||||||
|
s.otherLanguage()))
|
||||||
|
.toList(),
|
||||||
|
o.adventures().stream()
|
||||||
|
.map(a -> new AdventureDto(a.id(), a.arcId(), a.name(), a.sideQuest(),
|
||||||
|
a.scenes().stream().map(s -> new SceneDto(s.id(), s.name(), s.type().name())).toList()))
|
||||||
|
.toList()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/series")
|
||||||
|
public ResponseEntity<SeriesResponse> series(@PathVariable String campaignId, @RequestBody SeriesRequest body) {
|
||||||
|
try {
|
||||||
|
Series series = service.prepare(campaignId, body.sceneIds(), body.sectionTitles(), body.avoid());
|
||||||
|
return ResponseEntity.ok(new SeriesResponse(
|
||||||
|
series.gameSystemName(),
|
||||||
|
series.drills().stream()
|
||||||
|
.map(d -> new DrillDto(d.sceneId(), d.sceneName(), d.situation(),
|
||||||
|
d.section(), d.excerpt(), d.ruling()))
|
||||||
|
.toList(),
|
||||||
|
series.sections(), series.dropped()));
|
||||||
|
} catch (RuleTrainingException e) {
|
||||||
|
log.warn("Série d'entraînement aux règles échouée : {}", e.getMessage());
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/review")
|
||||||
|
public ResponseEntity<ReviewResponse> review(@PathVariable String campaignId, @RequestBody ReviewRequest body) {
|
||||||
|
try {
|
||||||
|
RuleDrillReview review = service.review(campaignId, body.section(), body.situation(),
|
||||||
|
body.excerpt(), body.ruling(), body.answer());
|
||||||
|
return ResponseEntity.ok(new ReviewResponse(review.verdict().wireName(), review.feedback()));
|
||||||
|
} catch (RuleTrainingException e) {
|
||||||
|
log.warn("Comparaison d'une réponse d'entraînement échouée : {}", e.getMessage());
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package com.loremind.infrastructure.web.controller;
|
|||||||
|
|
||||||
import com.loremind.application.campaigncontext.SceneService;
|
import com.loremind.application.campaigncontext.SceneService;
|
||||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
import com.loremind.infrastructure.web.dto.campaigncontext.SceneDTO;
|
import com.loremind.infrastructure.web.dto.campaigncontext.SceneDTO;
|
||||||
import com.loremind.infrastructure.web.mapper.SceneMapper;
|
import com.loremind.infrastructure.web.mapper.SceneMapper;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -56,6 +57,26 @@ public class SceneController {
|
|||||||
return ResponseEntity.ok(sceneMapper.toDTO(updatedScene));
|
return ResponseEntity.ok(sceneMapper.toDTO(updatedScene));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Donne à la scène un rôle dans la méthode guidée de son chapitre, ou le retire ({@code role} nul ou vide). */
|
||||||
|
@PutMapping("/{id}/guided-role")
|
||||||
|
public ResponseEntity<SceneDTO> setGuidedRole(@PathVariable String id, @RequestBody GuidedRoleRequest req) {
|
||||||
|
if (sceneService.getSceneById(id).isEmpty()) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(sceneMapper.toDTO(sceneService.setGuidedRole(id, req.role())));
|
||||||
|
}
|
||||||
|
|
||||||
|
public record GuidedRoleRequest(String role) {}
|
||||||
|
|
||||||
|
/** Crée, à la fin du chapitre, la scène qui tient un rôle de sa méthode guidée. */
|
||||||
|
@PostMapping("/guided")
|
||||||
|
public ResponseEntity<SceneDTO> createGuidedScene(@RequestBody GuidedSceneRequest req) {
|
||||||
|
Scene created = sceneService.createGuidedScene(req.chapterId(), req.name(), req.type(), req.role());
|
||||||
|
return ResponseEntity.ok(sceneMapper.toDTO(created));
|
||||||
|
}
|
||||||
|
|
||||||
|
public record GuidedSceneRequest(String chapterId, String name, SceneType type, String role) {}
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ResponseEntity<Void> deleteScene(@PathVariable String id) {
|
public ResponseEntity<Void> deleteScene(@PathVariable String id) {
|
||||||
sceneService.deleteScene(id);
|
sceneService.deleteScene(id);
|
||||||
|
|||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.gamesystemcontext.SheetTemplateProposalService;
|
||||||
|
import com.loremind.application.gamesystemcontext.SheetTemplateProposalService.RuleSection;
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.SheetProposalException;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Proposition d'un modèle de fiche (PJ, PNJ, ennemi) à partir des règles d'un système.
|
||||||
|
* Rien n'est enregistré : l'éditeur du système ajoute les champs choisis à son modèle,
|
||||||
|
* que l'utilisateur enregistre ensuite comme d'habitude.
|
||||||
|
*
|
||||||
|
* <p>{@code POST /api/game-systems/sheet-proposal} → {@code {fields: [{name, type, labels, source}]}} ;
|
||||||
|
* 400 si la fiche est inconnue ou si aucune règle n'est fournie, 502 si l'IA est indisponible.
|
||||||
|
* Le corps porte les règles telles qu'affichées (enregistrées ou non), d'où l'absence
|
||||||
|
* d'identifiant de système : la proposition marche aussi pendant la création.</p>
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/game-systems/sheet-proposal")
|
||||||
|
public class SheetProposalController {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(SheetProposalController.class);
|
||||||
|
|
||||||
|
public record RuleSectionDto(String title, String content) {}
|
||||||
|
|
||||||
|
/** {@code sheet} : {@code character}, {@code npc} ou {@code enemy}. */
|
||||||
|
public record ProposalRequest(String sheet, String systemName,
|
||||||
|
List<RuleSectionDto> sections, List<String> existingFields) {}
|
||||||
|
|
||||||
|
public record FieldDto(String name, String type, List<String> labels, String source) {}
|
||||||
|
|
||||||
|
public record ProposalResponse(List<FieldDto> fields) {}
|
||||||
|
|
||||||
|
private final SheetTemplateProposalService service;
|
||||||
|
|
||||||
|
public SheetProposalController(SheetTemplateProposalService service) {
|
||||||
|
this.service = service;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<ProposalResponse> propose(@RequestBody ProposalRequest body) {
|
||||||
|
SheetKind kind = SheetKind.fromWireName(body.sheet())
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Fiche inconnue : " + body.sheet()));
|
||||||
|
List<RuleSection> rules = (body.sections() == null ? List.<RuleSectionDto>of() : body.sections()).stream()
|
||||||
|
.filter(s -> s != null)
|
||||||
|
.map(s -> new RuleSection(s.title(), s.content()))
|
||||||
|
.toList();
|
||||||
|
try {
|
||||||
|
List<FieldDto> fields = service.propose(kind, body.systemName(), rules, body.existingFields()).stream()
|
||||||
|
.map(f -> new FieldDto(f.name(), f.type().name(), f.labels(), f.source()))
|
||||||
|
.toList();
|
||||||
|
return ResponseEntity.ok(new ProposalResponse(fields));
|
||||||
|
} catch (SheetProposalException e) {
|
||||||
|
log.warn("Proposition de fiche ({}) échouée : {}", kind.wireName(), e.getMessage());
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+48
@@ -0,0 +1,48 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.gamesystemcontext.SheetSpellService;
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sorts connus d'une fiche : {@code GET} les lit, {@code PUT} les remplace.
|
||||||
|
* {@code sheet} vaut {@code character}, {@code npc} ou {@code enemy}. Fiche inconnue ou type
|
||||||
|
* inconnu : 400 ({@code GlobalExceptionHandler}).
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/sheet-spells/{sheet}/{ownerId}")
|
||||||
|
public class SheetSpellController {
|
||||||
|
|
||||||
|
/** Identifiants de sorts du catalogue du système, dans l'ordre choisi. */
|
||||||
|
public record SheetSpellsDto(List<String> spellIds) {}
|
||||||
|
|
||||||
|
private final SheetSpellService service;
|
||||||
|
|
||||||
|
public SheetSpellController(SheetSpellService service) {
|
||||||
|
this.service = service;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public ResponseEntity<SheetSpellsDto> get(@PathVariable String sheet, @PathVariable String ownerId) {
|
||||||
|
return ResponseEntity.ok(new SheetSpellsDto(service.spellIds(kind(sheet), ownerId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping
|
||||||
|
public ResponseEntity<SheetSpellsDto> replace(@PathVariable String sheet, @PathVariable String ownerId,
|
||||||
|
@RequestBody SheetSpellsDto body) {
|
||||||
|
return ResponseEntity.ok(new SheetSpellsDto(service.replace(kind(sheet), ownerId, body.spellIds())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SheetKind kind(String sheet) {
|
||||||
|
return SheetKind.fromWireName(sheet)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Fiche inconnue : " + sheet));
|
||||||
|
}
|
||||||
|
}
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.gamesystemcontext.SpellCatalogService;
|
||||||
|
import com.loremind.application.gamesystemcontext.SpellCatalogService.Catalog;
|
||||||
|
import com.loremind.application.gamesystemcontext.SpellCatalogService.SpellData;
|
||||||
|
import com.loremind.domain.gamesystemcontext.Spell;
|
||||||
|
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||||
|
import com.loremind.infrastructure.web.mapper.TemplateFieldMapper;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Catalogue de sorts d'un système de jeu.
|
||||||
|
* <p>
|
||||||
|
* {@code GET} le lit ; {@code PUT} le remplace en bloc (modèle de sort + sorts), comme
|
||||||
|
* l'écran d'édition d'un système enregistre tout d'un coup. Système inconnu, sort sans nom
|
||||||
|
* ou modèle invalide : 400 ({@code GlobalExceptionHandler}).
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/game-systems/{gameSystemId}/spells")
|
||||||
|
public class SpellCatalogController {
|
||||||
|
|
||||||
|
/** Un sort. {@code id} absent à l'envoi = nouveau sort. */
|
||||||
|
public record SpellDto(String id, String name, String level, String school, String description,
|
||||||
|
Map<String, String> values) {}
|
||||||
|
|
||||||
|
public record CatalogDto(List<TemplateFieldDTO> template, List<SpellDto> spells) {}
|
||||||
|
|
||||||
|
private final SpellCatalogService service;
|
||||||
|
private final TemplateFieldMapper fieldMapper;
|
||||||
|
|
||||||
|
public SpellCatalogController(SpellCatalogService service, TemplateFieldMapper fieldMapper) {
|
||||||
|
this.service = service;
|
||||||
|
this.fieldMapper = fieldMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public ResponseEntity<CatalogDto> get(@PathVariable String gameSystemId) {
|
||||||
|
return ResponseEntity.ok(toDto(service.get(gameSystemId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping
|
||||||
|
public ResponseEntity<CatalogDto> replace(@PathVariable String gameSystemId, @RequestBody CatalogDto body) {
|
||||||
|
List<SpellData> spells = body.spells() == null ? List.of() : body.spells().stream()
|
||||||
|
.map(s -> s == null ? null
|
||||||
|
: new SpellData(s.id(), s.name(), s.level(), s.school(), s.description(), s.values()))
|
||||||
|
.toList();
|
||||||
|
return ResponseEntity.ok(toDto(service.replace(gameSystemId, fieldMapper.toDomainList(body.template()), spells)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private CatalogDto toDto(Catalog catalog) {
|
||||||
|
return new CatalogDto(fieldMapper.toDTOList(catalog.template()),
|
||||||
|
catalog.spells().stream().map(SpellCatalogController::toDto).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SpellDto toDto(Spell s) {
|
||||||
|
return new SpellDto(s.getId(), s.getName(), s.getLevel(), s.getSchool(), s.getDescription(), s.getValues());
|
||||||
|
}
|
||||||
|
}
|
||||||
+70
@@ -0,0 +1,70 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.gamesystemcontext.SpellProposalService;
|
||||||
|
import com.loremind.application.gamesystemcontext.SpellProposalService.Proposal;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.SpellProposalException;
|
||||||
|
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||||
|
import com.loremind.infrastructure.web.mapper.TemplateFieldMapper;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Proposition de sorts à partir des règles d'un système : l'IA relève les sorts décrits dans
|
||||||
|
* UN morceau de règles. Rien n'est enregistré : l'éditeur ajoute au catalogue les sorts que
|
||||||
|
* l'utilisateur coche, puis celui-ci enregistre le système comme d'habitude.
|
||||||
|
*
|
||||||
|
* <p>{@code POST /api/game-systems/spell-proposal} → {@code {spells: [...], dropped}} ; 400 si
|
||||||
|
* le texte est vide ou trop long, 502 si l'IA est indisponible. Le corps porte le texte tel
|
||||||
|
* qu'affiché (enregistré ou non), d'où l'absence d'identifiant de système. L'écran découpe les
|
||||||
|
* règles et appelle une fois par morceau : il peut ainsi montrer l'avancement et s'arrêter.</p>
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/game-systems/spell-proposal")
|
||||||
|
public class SpellProposalController {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(SpellProposalController.class);
|
||||||
|
|
||||||
|
public record ProposalRequest(String systemName, String sectionTitle, String text,
|
||||||
|
List<TemplateFieldDTO> fields, List<String> avoid) {}
|
||||||
|
|
||||||
|
/** {@code excerpt} : passage des règles retrouvé mot pour mot dans le texte envoyé. */
|
||||||
|
public record SpellDto(String name, String level, String school, String description,
|
||||||
|
Map<String, String> values, String excerpt) {}
|
||||||
|
|
||||||
|
/** {@code dropped} : sorts écartés, leur nom ou leur passage ne figurant pas dans le texte. */
|
||||||
|
public record ProposalResponse(List<SpellDto> spells, int dropped) {}
|
||||||
|
|
||||||
|
private final SpellProposalService service;
|
||||||
|
private final TemplateFieldMapper fieldMapper;
|
||||||
|
|
||||||
|
public SpellProposalController(SpellProposalService service, TemplateFieldMapper fieldMapper) {
|
||||||
|
this.service = service;
|
||||||
|
this.fieldMapper = fieldMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<ProposalResponse> propose(@RequestBody ProposalRequest body) {
|
||||||
|
try {
|
||||||
|
Proposal proposal = service.propose(body.systemName(), body.sectionTitle(), body.text(),
|
||||||
|
fieldMapper.toDomainList(body.fields()), body.avoid());
|
||||||
|
return ResponseEntity.ok(new ProposalResponse(
|
||||||
|
proposal.spells().stream()
|
||||||
|
.map(s -> new SpellDto(s.name(), s.level(), s.school(), s.description(), s.values(), s.excerpt()))
|
||||||
|
.toList(),
|
||||||
|
proposal.dropped()));
|
||||||
|
} catch (SpellProposalException e) {
|
||||||
|
log.warn("Proposition de sorts échouée : {}", e.getMessage());
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user