diff --git a/brain/app/api/routers/chat.py b/brain/app/api/routers/chat.py index bd6e81c..d1f59fe 100644 --- a/brain/app/api/routers/chat.py +++ b/brain/app/api/routers/chat.py @@ -1,5 +1,6 @@ """Endpoint du chat contextuel (/chat/stream) : Structural Context + jauge tokens.""" import json +import logging from typing import Annotated, AsyncIterator import tiktoken @@ -22,6 +23,8 @@ from app.core.language import get_user_language from app.domain.models import ChatMessage from app.domain.ports import LLMProviderError +logger = logging.getLogger(__name__) + router = APIRouter() # 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 "event: done\ndata: {}\n\n" 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" return StreamingResponse(event_stream(), media_type="text/event-stream") diff --git a/brain/app/api/routers/generation.py b/brain/app/api/routers/generation.py index 8f20df8..81d7825 100644 --- a/brain/app/api/routers/generation.py +++ b/brain/app/api/routers/generation.py @@ -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 scene_drafts as scene_drafts_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.language import get_user_language from app.domain.models import PageGenerationContext @@ -370,3 +371,105 @@ def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dic continue out[field.key] = text 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 diff --git a/brain/app/api/routers/imports.py b/brain/app/api/routers/imports.py index 9e28dee..65e778b 100644 --- a/brain/app/api/routers/imports.py +++ b/brain/app/api/routers/imports.py @@ -107,6 +107,7 @@ async def import_rules_stream( except PdfExtractionError as exc: yield sse_event("error", {"message": str(exc)}) except LLMProviderError as exc: + logger.warning("Import : erreur du fournisseur IA : %s", exc) yield sse_event("error", {"message": str(exc)}) 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 @@ -143,6 +144,7 @@ async def import_campaign_stream( except PdfExtractionError as exc: yield sse_event("error", {"message": str(exc)}) except LLMProviderError as exc: + logger.warning("Import : erreur du fournisseur IA : %s", exc) yield sse_event("error", {"message": str(exc)}) except Exception as exc: # noqa: BLE001 — voir import règles : on ne laisse pas # une erreur inattendue casser le flux sans détail. @@ -189,6 +191,7 @@ async def adapt_campaign_stream( except PdfExtractionError as exc: yield sse_event("error", {"message": str(exc)}) except LLMProviderError as exc: + logger.warning("Import : erreur du fournisseur IA : %s", exc) yield sse_event("error", {"message": str(exc)}) return StreamingResponse(event_stream(), media_type="text/event-stream") diff --git a/brain/app/api/routers/notebooks.py b/brain/app/api/routers/notebooks.py index c8c5c86..7fa9d2c 100644 --- a/brain/app/api/routers/notebooks.py +++ b/brain/app/api/routers/notebooks.py @@ -97,6 +97,7 @@ async def chat_notebook_stream( yield sse_event(ev_type, ev) yield sse_event("done", {}) except (LLMProviderError, EmbeddingError) as exc: + logger.warning("Atelier : erreur du fournisseur IA : %s", exc) yield sse_event("error", {"message": str(exc)}) except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale du flux. logger.exception("Chat notebook : erreur inattendue.") @@ -125,6 +126,7 @@ async def chat_notebook_deep_stream( ev_type = ev.pop("type") yield sse_event(ev_type, ev) except (LLMProviderError, EmbeddingError) as exc: + logger.warning("Atelier : erreur du fournisseur IA : %s", exc) yield sse_event("error", {"message": str(exc)}) except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale. logger.exception("Analyse approfondie : erreur inattendue.") diff --git a/brain/app/api/routers/spells.py b/brain/app/api/routers/spells.py new file mode 100644 index 0000000..6c4b2d1 --- /dev/null +++ b/brain/app/api/routers/spells.py @@ -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 diff --git a/brain/app/api/routers/training.py b/brain/app/api/routers/training.py new file mode 100644 index 0000000..4c20ca3 --- /dev/null +++ b/brain/app/api/routers/training.py @@ -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()) diff --git a/brain/app/application/prompts/rule_training.py b/brain/app/application/prompts/rule_training.py new file mode 100644 index 0000000..a2d6369 --- /dev/null +++ b/brain/app/application/prompts/rule_training.py @@ -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." + ) diff --git a/brain/app/application/prompts/sheet_template.py b/brain/app/application/prompts/sheet_template.py new file mode 100644 index 0000000..2894120 --- /dev/null +++ b/brain/app/application/prompts/sheet_template.py @@ -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." + ) diff --git a/brain/app/application/prompts/spell_extraction.py b/brain/app/application/prompts/spell_extraction.py new file mode 100644 index 0000000..c69dcd4 --- /dev/null +++ b/brain/app/application/prompts/spell_extraction.py @@ -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." + ) diff --git a/brain/app/infrastructure/base_openai_adapter.py b/brain/app/infrastructure/base_openai_adapter.py index 305c63c..a3c5f4d 100644 --- a/brain/app/infrastructure/base_openai_adapter.py +++ b/brain/app/infrastructure/base_openai_adapter.py @@ -31,6 +31,15 @@ logger = logging.getLogger(__name__) _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: """Base des adapters clients d'une API OpenAI-compatible (chat/completions SSE). @@ -100,7 +109,8 @@ class BaseOpenAICompatibleAdapter: temperature: float | None = None, ) -> AsyncIterator[str]: 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 ------------------------------------------------- @@ -117,19 +127,24 @@ class BaseOpenAICompatibleAdapter: """ async def _collect() -> str: chunks: list[str] = [] + started = False agen = self._stream(messages, None, temperature, output_format) try: while True: - # Borne SEULEMENT l'attente du 1er token ; ensuite on laisse - # générer (le ceiling global couvre le reste). - first = _FIRST_TOKEN_TIMEOUT_SECONDS if not chunks else None + # Borne SEULEMENT l'attente du 1er signe d'activité ; ensuite on + # laisse générer (le ceiling global couvre le reste). Un jeton vide + # (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: token = await asyncio.wait_for(agen.__anext__(), timeout=first) except StopAsyncIteration: break except asyncio.TimeoutError: raise LLMProviderError(self._first_token_timeout_message()) - chunks.append(token) + started = True + if token: + chunks.append(token) finally: await agen.aclose() return "".join(chunks) @@ -195,7 +210,13 @@ class BaseOpenAICompatibleAdapter: @staticmethod 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(): if not line or not line.startswith("data:"): continue # lignes vides ou commentaires keep-alive (`: ...`) @@ -211,8 +232,11 @@ class BaseOpenAICompatibleAdapter: continue delta = choices[0].get("delta") or {} content = delta.get("content") - if content: - yield content + if isinstance(content, str): + if content: + yield content + elif isinstance(content, list): + yield _answer_text(content) def _format_http_error(self, exc: httpx.HTTPError) -> str: """Message lisible (timeout, quota 429, crédits 402, modèle inconnu…).""" diff --git a/brain/app/main.py b/brain/app/main.py index 77aa33d..7965e57 100644 --- a/brain/app/main.py +++ b/brain/app/main.py @@ -9,7 +9,9 @@ import hmac import logging from fastapi import FastAPI, Request +from fastapi.exception_handlers import http_exception_handler from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException from app.api.routers import ( chat, @@ -18,7 +20,9 @@ from app.api.routers import ( models, notebooks, settings as settings_router, + spells, tables, + training, ) from app.core.config import get_settings 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( title="LoreMind Brain", description="Backend IA pour la génération de contenu narratif.", - version="1.6.2", + version="1.7.0-beta", ) logger = logging.getLogger(__name__) @@ -61,6 +65,18 @@ async def require_internal_secret(request: Request, call_next): 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") def health() -> dict[str, str]: """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(chat.router) app.include_router(tables.router) +app.include_router(training.router) +app.include_router(spells.router) app.include_router(imports.router) app.include_router(notebooks.router) app.include_router(settings_router.router) diff --git a/brain/run_local.py b/brain/run_local.py index 341d441..f4c7571 100644 --- a/brain/run_local.py +++ b/brain/run_local.py @@ -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 ailleurs, sous ~/.loremind/brain, pour y ecrire le dossier data/). """ +import copy +import logging import os import sys _HERE = os.path.dirname(os.path.abspath(__file__)) 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 # 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 @@ -40,6 +53,17 @@ import uvicorn # 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__": # 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()) diff --git a/brain/tests/test_error_logging.py b/brain/tests/test_error_logging.py new file mode 100644 index 0000000..51db082 --- /dev/null +++ b/brain/tests/test_error_logging.py @@ -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"] == [] diff --git a/brain/tests/test_openai_compatible_adapters.py b/brain/tests/test_openai_compatible_adapters.py index 580e7fa..c7afeb3 100644 --- a/brain/tests/test_openai_compatible_adapters.py +++ b/brain/tests/test_openai_compatible_adapters.py @@ -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): with pytest.raises(LLMProviderError): 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") == "" diff --git a/brain/tests/test_rule_training.py b/brain/tests/test_rule_training.py new file mode 100644 index 0000000..eba2ca0 --- /dev/null +++ b/brain/tests/test_rule_training.py @@ -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."} diff --git a/brain/tests/test_sheet_template.py b/brain/tests/test_sheet_template.py new file mode 100644 index 0000000..39dc916 --- /dev/null +++ b/brain/tests/test_sheet_template.py @@ -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."} diff --git a/brain/tests/test_spell_extraction.py b/brain/tests/test_spell_extraction.py new file mode 100644 index 0000000..831bff2 --- /dev/null +++ b/brain/tests/test_spell_extraction.py @@ -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": []} diff --git a/core/pom.xml b/core/pom.xml index cf40b7c..05b511b 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -14,7 +14,7 @@ com.loremind loremind-core - 1.6.2 + 1.7.0-beta LoreMind Core Backend Core - Architecture Hexagonale diff --git a/core/src/main/java/com/loremind/application/campaigncontext/CampaignReadinessService.java b/core/src/main/java/com/loremind/application/campaigncontext/CampaignReadinessService.java index 86e4e81..6ed3bf3 100644 --- a/core/src/main/java/com/loremind/application/campaigncontext/CampaignReadinessService.java +++ b/core/src/main/java/com/loremind/application/campaigncontext/CampaignReadinessService.java @@ -114,7 +114,7 @@ public class CampaignReadinessService { if (totalScenes == 0 && !anyQuestHasNodes(quests)) { gaps.add(new ReadinessGap(ReadinessEntityType.CAMPAIGN, campaignId, campaignName, "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)); } @@ -146,9 +146,11 @@ public class CampaignReadinessService { chapterIds.add(chapter.getId()); List scenes = sceneRepository.findByChapterId(chapter.getId()); 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(), - labelOr(chapter.getName(), "Chapitre"), "CHAP-001-NO-SCENE", - "Chapitre vide : ajoutez au moins une scène pour pouvoir le jouer.", + labelOr(chapter.getName(), kind), "CHAP-001-NO-SCENE", + kind + " vide : ajoutez au moins une scène pour pouvoir la jouer.", ReadinessSeverity.BLOCKING, arc.getId(), chapter.getId())); } Set chapterSceneIds = scenes.stream() @@ -163,9 +165,8 @@ public class CampaignReadinessService { } private ReadinessGap emptyArcGap(Arc arc) { - String msg = arc.getType() == ArcType.HUB - ? "Arc vide : ajoutez une quête (ou un chapitre), ou supprimez-le." - : "Arc vide : ajoutez un chapitre, ou supprimez-le."; + // Même mot pour l'auteur, que l'arc soit linéaire ou à ordre libre (HUB) : une aventure. + String msg = "Arc vide : ajoutez une aventure, ou supprimez-le."; return new ReadinessGap(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"), "ARC-001-EMPTY", msg, ReadinessSeverity.BLOCKING, arc.getId(), null); } @@ -204,7 +205,7 @@ public class CampaignReadinessService { if (invalid) { gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-010-BRANCH-INVALID", "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)); } } @@ -274,20 +275,24 @@ public class CampaignReadinessService { private void checkQuest(Quest quest, Set allChapterIds, Set allSceneIds, Set questIds, List 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. if (quest.getNodes() == null || quest.getNodes().isEmpty()) { 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 -> n.nodeType() == null || isBlank(n.nodeId()) || (n.nodeType() == NodeType.CHAPTER && !allChapterIds.contains(n.nodeId())) || (n.nodeType() == NodeType.SCENE && !allSceneIds.contains(n.nodeId())))) { gaps.add(questGap(quest, "QUEST-010-NODE-REF-BROKEN", - "Nœud de quête cassé : dans « " + name - + " », un chapitre ou une scène référencé n'existe plus.")); + "Lien cassé : dans « " + name + + " », une aventure ou une scène référencée n'existe plus.")); } // CAMP-010 — prérequis QuestCompleted pointant une quête disparue. @@ -297,7 +302,7 @@ public class CampaignReadinessService { .anyMatch(qid -> isBlank(qid) || !questIds.contains(qid))) { gaps.add(questGap(quest, "CAMP-010-DANGLING-QUEST-PREREQ", "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) { 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) { diff --git a/core/src/main/java/com/loremind/application/campaigncontext/ChapterService.java b/core/src/main/java/com/loremind/application/campaigncontext/ChapterService.java index c0768a8..9d7da9e 100644 --- a/core/src/main/java/com/loremind/application/campaigncontext/ChapterService.java +++ b/core/src/main/java/com/loremind/application/campaigncontext/ChapterService.java @@ -78,7 +78,32 @@ public class ChapterService { } 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); } diff --git a/core/src/main/java/com/loremind/application/campaigncontext/GuidedKeys.java b/core/src/main/java/com/loremind/application/campaigncontext/GuidedKeys.java new file mode 100644 index 0000000..083d029 --- /dev/null +++ b/core/src/main/java/com/loremind/application/campaigncontext/GuidedKeys.java @@ -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; + } +} diff --git a/core/src/main/java/com/loremind/application/campaigncontext/GuidedMethodShapes.java b/core/src/main/java/com/loremind/application/campaigncontext/GuidedMethodShapes.java new file mode 100644 index 0000000..2b6b34f --- /dev/null +++ b/core/src/main/java/com/loremind/application/campaigncontext/GuidedMethodShapes.java @@ -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. + * + *

Une méthode absente de cette table reste utilisable : la relecture ne dit simplement + * rien de propre à elle.

+ */ +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> 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 rolesOf(String method) { + return method == null ? List.of() : ROLES.getOrDefault(method, List.of()); + } +} diff --git a/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeleton.java b/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeleton.java index a2c308a..186ba81 100644 --- a/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeleton.java +++ b/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeleton.java @@ -11,9 +11,14 @@ import java.util.List; * 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. * - *

Placement : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le chapitre - * est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la suite). - * Exactement l'un des deux.

+ *

Placement en chapitre : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le + * chapitre est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la + * suite). Exactement l'un des deux.

+ * + *

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.

* * @param arcId arc existant où ajouter le chapitre, 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} : * 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 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( String arcId, @@ -33,13 +42,29 @@ public record GuidedSkeleton( boolean linkSequentially, String linkLabel, List 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 scenes, + boolean linkSequentially, String linkLabel, List 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 scenes, + boolean linkSequentially, String linkLabel, List 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). */ public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List scenes, 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) */ @@ -71,19 +96,30 @@ public record GuidedSkeleton( 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( 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. * - * @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 sceneIds, int clocks) { + public record Result(String arcId, String chapterId, List sceneIds, int clocks, String questId) { + public Result(String arcId, String chapterId, List sceneIds, int clocks) { + this(arcId, chapterId, sceneIds, clocks, null); + } + public Result(String arcId, String chapterId, List sceneIds) { - this(arcId, chapterId, sceneIds, 0); + this(arcId, chapterId, sceneIds, 0, null); } } } diff --git a/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeletonService.java b/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeletonService.java index 62c4935..7ab8540 100644 --- a/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeletonService.java +++ b/core/src/main/java/com/loremind/application/campaigncontext/GuidedSkeletonService.java @@ -2,6 +2,10 @@ package com.loremind.application.campaigncontext; import com.loremind.domain.campaigncontext.ports.ArcRepository; 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.structure.Arc; 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. * *

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.

+ * 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.

*/ @Service public class GuidedSkeletonService { @@ -39,6 +46,8 @@ public class GuidedSkeletonService { private final SceneService sceneService; private final PlaythroughRepository playthroughRepository; private final ClockService clockService; + private final QuestService questService; + private final QuestRepository questRepository; public GuidedSkeletonService(ArcRepository arcRepository, ChapterRepository chapterRepository, @@ -47,7 +56,9 @@ public class GuidedSkeletonService { ChapterService chapterService, SceneService sceneService, PlaythroughRepository playthroughRepository, - ClockService clockService) { + ClockService clockService, + QuestService questService, + QuestRepository questRepository) { this.arcRepository = arcRepository; this.chapterRepository = chapterRepository; this.sceneRepository = sceneRepository; @@ -56,17 +67,26 @@ public class GuidedSkeletonService { this.sceneService = sceneService; this.playthroughRepository = playthroughRepository; 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, - * arc d'une autre campagne ou non linéaire) + * arc d'une autre campagne ou du mauvais type) */ @Transactional public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) { validate(skeleton); - String arcId = resolveArc(campaignId, skeleton); - Chapter chapter = createChapter(arcId, skeleton.chapter()); + String method = GuidedKeys.normalize(skeleton.method()); + 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. List scenes = new ArrayList<>(); @@ -85,6 +105,7 @@ public class GuidedSkeletonService { .choicesConsequences(blankToNull(spec.choicesConsequences())) .gmSecretNotes(blankToNull(spec.gmSecretNotes())) .enemies(blankToNull(spec.enemies())) + .guidedRole(chapter.getGuidedMethod() == null ? null : GuidedKeys.normalize(spec.role())) .chapterId(chapter.getId()) .order(order++) .build()); @@ -100,7 +121,80 @@ public class GuidedSkeletonService { } 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 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."); } if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) { @@ -183,7 +282,7 @@ public class GuidedSkeletonService { .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() .mapToInt(Chapter::getOrder).max().orElse(-1) + 1; return chapterService.createChapter(Chapter.builder() @@ -192,6 +291,7 @@ public class GuidedSkeletonService { .playerObjectives(blankToNull(spec.playerObjectives())) .narrativeStakes(blankToNull(spec.narrativeStakes())) .gmNotes(blankToNull(spec.gmNotes())) + .guidedMethod(method) .arcId(arcId) .order(nextOrder) .build()); diff --git a/core/src/main/java/com/loremind/application/campaigncontext/ImplicitArc.java b/core/src/main/java/com/loremind/application/campaigncontext/ImplicitArc.java new file mode 100644 index 0000000..a49401c --- /dev/null +++ b/core/src/main/java/com/loremind/application/campaigncontext/ImplicitArc.java @@ -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. + * + *

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.

+ */ +public final class ImplicitArc { + + /** Noms donnés à l'arc créé d'office, dans chaque langue de l'interface. */ + public static final List DEFAULT_NAMES = List.of("Arc principal", "Main arc"); + + private ImplicitArc() { + } + + static boolean is(Arc arc, List 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; + } +} diff --git a/core/src/main/java/com/loremind/application/campaigncontext/SceneService.java b/core/src/main/java/com/loremind/application/campaigncontext/SceneService.java index 7f87af4..5faceae 100644 --- a/core/src/main/java/com/loremind/application/campaigncontext/SceneService.java +++ b/core/src/main/java/com/loremind/application/campaigncontext/SceneService.java @@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.structure.Scene; import com.loremind.domain.campaigncontext.generation.SceneDraft; import com.loremind.domain.shared.ReorderSupport; import com.loremind.domain.campaigncontext.structure.SceneBranch; +import com.loremind.domain.campaigncontext.structure.SceneType; import com.loremind.domain.campaigncontext.ports.SceneRepository; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; @@ -80,7 +81,8 @@ public class SceneService { } 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. validateBranches(scene); @@ -88,6 +90,53 @@ public class SceneService { 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 * 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())) { scene.setChapterId(chapterId); scene.setBranches(new ArrayList<>()); + scene.setGuidedRole(null); // le rôle appartenait à la méthode de l'ancien chapitre } scene.setOrder(i); }, diff --git a/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewService.java b/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewService.java index 2c81a8c..9f113b9 100644 --- a/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewService.java +++ b/core/src/main/java/com/loremind/application/campaigncontext/WritingReviewService.java @@ -9,7 +9,9 @@ import com.loremind.domain.campaigncontext.bestiary.NpcStory; import com.loremind.domain.campaigncontext.ports.NpcRepository; import com.loremind.domain.campaigncontext.ports.QuestRepository; 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.QuestNodeRef; import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType; import com.loremind.domain.campaigncontext.structure.Arc; import com.loremind.domain.campaigncontext.structure.ArcType; @@ -64,6 +66,8 @@ public class WritingReviewService { static final int DUNGEON_MIN_ROOMS = 4; /** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */ 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. */ static final int MONOTONOUS_RUN = 3; /** 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. */ 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}). */ static final String KIND_COMBAT = "COMBAT"; @@ -115,8 +131,17 @@ public class WritingReviewService { List campaignRemarks = new ArrayList<>(); List treeRemarks = new ArrayList<>(); - Set arcsWithQuests = questRepository.findByCampaignId(campaignId).stream() + List quests = questRepository.findByCampaignId(campaignId); + Set arcsWithQuests = quests.stream() .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 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 arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId)); arcs.sort(Comparator.comparingInt(Arc::getOrder)); @@ -127,6 +152,8 @@ public class WritingReviewService { List chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId())); chapters.sort(Comparator.comparingInt(Chapter::getOrder)); 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. 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. - if (visibleArc && isBlank(arc.getStakes()) + if (visibleArc && !implicitArc && isBlank(arc.getStakes()) && (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) { 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(); 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) { reviewScene(arc, chapter, scene, scenes, treeRemarks); @@ -159,7 +187,7 @@ public class WritingReviewService { } 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 --------------------------------------------------------------- - private void reviewChapter(Arc arc, Chapter chapter, List scenes, List out) { + private void reviewChapter(Arc arc, Chapter chapter, List scenes, boolean questHasStakes, + List out) { 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. @@ -200,7 +229,7 @@ public class WritingReviewService { } // 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())); } @@ -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 scenes, List out) { + List roles = GuidedMethodShapes.rolesOf(chapter.getGuidedMethod()); + if (roles.isEmpty() || scenes.isEmpty()) return; + Map 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 byRole, List 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 byRole, List scenes, + List 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 steps, List 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 incomingSources(Scene scene, List 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) {} /** 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 chapterScenes, List out) { 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; - List sources = 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(); + List sources = incomingSources(scene, chapterScenes); if (sources.size() < REVELATION_MIN_INCOMING) { out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY, Map.of("incoming", String.valueOf(sources.size())))); @@ -459,12 +571,17 @@ public class WritingReviewService { // --- Niveau arc ----------------------------------------------------------------------- /** 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 lastChapterScenes, List out) { + private void checkSingleEnding(Arc arc, boolean implicitArc, List lastChapterScenes, + List out) { Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1); 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 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"), "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, WritingRemarkCategory category, Map params) { 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, WritingRemarkCategory category, Map params) { 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 withMethod(Chapter chapter, Map params) { + if (isBlank(chapter.getGuidedMethod())) return params; + Map all = new HashMap<>(params); + all.put(PARAM_GUIDED_METHOD, chapter.getGuidedMethod()); + return all; } private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category, diff --git a/core/src/main/java/com/loremind/application/gamesystemcontext/GameSystemContextBuilder.java b/core/src/main/java/com/loremind/application/gamesystemcontext/GameSystemContextBuilder.java index ccb39b0..ab11d52 100644 --- a/core/src/main/java/com/loremind/application/gamesystemcontext/GameSystemContextBuilder.java +++ b/core/src/main/java/com/loremind/application/gamesystemcontext/GameSystemContextBuilder.java @@ -61,7 +61,7 @@ public class GameSystemContextBuilder { * Découpe le markdown par titres H2. Préserve l'ordre d'apparition (LinkedHashMap). * Le contenu avant le premier H2 est ignoré (préambule libre). */ - Map parseH2Sections(String markdown) { + static Map parseH2Sections(String markdown) { Map sections = new LinkedHashMap<>(); if (markdown == null || markdown.isBlank()) return sections; diff --git a/core/src/main/java/com/loremind/application/gamesystemcontext/RuleTrainingService.java b/core/src/main/java/com/loremind/application/gamesystemcontext/RuleTrainingService.java new file mode 100644 index 0000000..8571f73 --- /dev/null +++ b/core/src/main/java/com/loremind/application/gamesystemcontext/RuleTrainingService.java @@ -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. + *

+ * 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é. + *

+ * 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> 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 suggestedFor, boolean otherLanguage) {} + + /** Sections des règles ({@code titre → texte}) et titres de celles rédigées dans l'autre langue. */ + record Rules(Map sections, Set 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 scenes) {} + + /** Ce que l'écran propose avant une série. */ + public record Options(Status status, String gameSystemId, String gameSystemName, + List sections, List 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 drills, List 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 adventures = adventures(campaignId); + Optional 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 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 adventures(String campaignId) { + List arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId)); + arcs.sort(Comparator.comparingInt(Arc::getOrder)); + List out = new ArrayList<>(); + for (Arc arc : arcs) { + List chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId())); + chapters.sort(Comparator.comparingInt(Chapter::getOrder)); + for (Chapter chapter : chapters) { + List 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 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 sceneIds, List sectionTitles, List 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 all = rules.sections(); + if (all.isEmpty()) { + throw new IllegalArgumentException("Ce système de jeu n'a pas encore de règles."); + } + List scenes = scenesOf(campaignId, sceneIds); + Map sent = selectSections(all, + wantedTitles(all, sectionTitles, scenes, rules.otherLanguage()), windowPicker); + List briefs = scenes.stream().map(this::brief).toList(); + + List candidates = coach.prepare(nz(gs.getName()), sent, briefs, DRILL_COUNT, clean(avoid)); + List 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 wantedTitles(Map all, List requested, List scenes, + Set otherLanguage) { + List wanted = new ArrayList<>(); + for (String title : requested == null ? List.of() : requested) { + findTitle(all.keySet(), title).filter(t -> !wanted.contains(t)).ifPresent(wanted::add); + } + if (!wanted.isEmpty()) return wanted; + + Set types = new LinkedHashSet<>(); + scenes.forEach(s -> types.add(typeOf(s))); + if (types.isEmpty()) types.add(SceneType.GENERIC); + List 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 otherLanguageTitles(Map sections, String language) { + String wanted = RulesLanguage.of(language); + Set 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 selectSections(Map all, List ordered, IntUnaryOperator picker) { + Map 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 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 windows(String content, int max) { + List 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 validate(List candidates, Map sent, List scenes) { + Map normalized = new LinkedHashMap<>(); + sent.forEach((title, content) -> normalized.put(title, normalize(content))); + + List out = new ArrayList<>(); + Set seen = new HashSet<>(); + for (DrillCandidate c : candidates == null ? List.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 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 inLanguage(List drills, Set 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 locate(String excerpt, String announced, Map normalized) { + Optional 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 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 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 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 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 scenesOf(String campaignId, List sceneIds) { + List out = new ArrayList<>(); + Set seen = new HashSet<>(); + for (String id : sceneIds == null ? List.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 enemyIds) { + List names = new ArrayList<>(); + for (String id : enemyIds == null ? List.of() : enemyIds) { + enemyRepository.findById(id).map(Enemy::getName).filter(n -> !isBlank(n)).ifPresent(names::add); + } + return String.join(", ", names); + } + + private static String rooms(List rooms) { + List parts = new ArrayList<>(); + for (Room room : rooms == null ? List.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 findTitle(Set 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 clean(List values) { + List out = new ArrayList<>(); + for (String value : values == null ? List.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(); + } +} diff --git a/core/src/main/java/com/loremind/application/gamesystemcontext/RulesLanguage.java b/core/src/main/java/com/loremind/application/gamesystemcontext/RulesLanguage.java new file mode 100644 index 0000000..5252d20 --- /dev/null +++ b/core/src/main/java/com/loremind/application/gamesystemcontext/RulesLanguage.java @@ -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. + *

+ * 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 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 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 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; + } +} diff --git a/core/src/main/java/com/loremind/application/gamesystemcontext/SheetSpellService.java b/core/src/main/java/com/loremind/application/gamesystemcontext/SheetSpellService.java new file mode 100644 index 0000000..0d01ae0 --- /dev/null +++ b/core/src/main/java/com/loremind/application/gamesystemcontext/SheetSpellService.java @@ -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 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 replace(SheetKind kind, String ownerId, List spellIds) { + requireOwner(kind, ownerId); + List wanted = new ArrayList<>(); + Set seen = new HashSet<>(); + for (String id : spellIds == null ? List.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 existing = new HashSet<>(spellRepository.existingIds(wanted)); + List 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}"); + } +} diff --git a/core/src/main/java/com/loremind/application/gamesystemcontext/SheetTemplateProposalService.java b/core/src/main/java/com/loremind/application/gamesystemcontext/SheetTemplateProposalService.java new file mode 100644 index 0000000..9e90cf6 --- /dev/null +++ b/core/src/main/java/com/loremind/application/gamesystemcontext/SheetTemplateProposalService.java @@ -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. + *

+ * 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. + *

+ * 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 RESERVED_NAMES = Set.of( + "nom", "name", "portrait", "bandeau", "header", "image", "images", "illustration"); + /** En plus, sur la fiche d'ennemi. */ + private static final Set RESERVED_ENEMY_NAMES = Set.of("niveau", "level", "dossier", "folder"); + + private static final Set 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 propose(SheetKind kind, String systemName, + List rules, List existingFieldNames) { + Map all = mergeSections(rules); + if (all.isEmpty()) { + throw new IllegalArgumentException("Aucune règle à partir de laquelle proposer une fiche."); + } + Map selected = selectSections(all, kind); + List 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 mergeSections(List rules) { + Map merged = new LinkedHashMap<>(); + Map canonical = new LinkedHashMap<>(); + for (RuleSection section : rules == null ? List.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 selectSections(Map all, SheetKind kind) { + List ordered = new ArrayList<>(); + for (Set 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 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 validate(List candidates, SheetKind kind, Set sentTitles) { + List out = new ArrayList<>(); + Set seen = new HashSet<>(); + for (Candidate c : candidates == null ? List.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 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 cleanLabels(List labels) { + List out = new ArrayList<>(); + Set seen = new HashSet<>(); + for (String label : labels == null ? List.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 sentTitles) { + if (isBlank(source)) return ""; + String wanted = source.trim(); + return sentTitles.stream().filter(t -> t.equalsIgnoreCase(wanted)).findFirst().orElse(""); + } + + private static List cleanNames(List names) { + List out = new ArrayList<>(); + for (String name : names == null ? List.of() : names) { + if (!isBlank(name)) out.add(name.trim()); + } + return out; + } + + private static boolean isBlank(String s) { + return s == null || s.isBlank(); + } +} diff --git a/core/src/main/java/com/loremind/application/gamesystemcontext/SpellCatalogService.java b/core/src/main/java/com/loremind/application/gamesystemcontext/SpellCatalogService.java new file mode 100644 index 0000000..2cd7c84 --- /dev/null +++ b/core/src/main/java/com/loremind/application/gamesystemcontext/SpellCatalogService.java @@ -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…). + *

+ * 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 values) {} + + /** Le modèle de sort du système et ses sorts, dans l'ordre du catalogue. */ + public record Catalog(List template, List 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 template, List spells) { + GameSystem gs = system(gameSystemId); + List 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 existing = new LinkedHashMap<>(); + spellRepository.findByGameSystemId(gs.getId()).forEach(s -> existing.put(s.getId(), s)); + + List saved = new ArrayList<>(); + Set 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 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 supported(List template) { + List 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 cleanValues(Map values) { + Map 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(); + } +} diff --git a/core/src/main/java/com/loremind/application/gamesystemcontext/SpellProposalService.java b/core/src/main/java/com/loremind/application/gamesystemcontext/SpellProposalService.java new file mode 100644 index 0000000..f45702e --- /dev/null +++ b/core/src/main/java/com/loremind/application/gamesystemcontext/SpellProposalService.java @@ -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). + *

+ * 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 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 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 fields, List 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 spellFields = spellFields(fields); + List avoided = clean(avoid); + List 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 candidates, String text, List fields, + List avoid) { + String normalized = RuleTrainingService.normalize(text); + Set seen = new HashSet<>(); + for (String name : avoid) seen.add(key(name)); + + List out = new ArrayList<>(); + int dropped = 0; + for (SpellCandidate c : candidates == null ? List.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 values(Map raw, List fields) { + Map 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 spellFields(List fields) { + List out = new ArrayList<>(); + Set names = new HashSet<>(); + for (TemplateField field : fields == null ? List.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 clean(List values) { + List out = new ArrayList<>(); + for (String value : values == null ? List.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(); + } +} diff --git a/core/src/main/java/com/loremind/domain/campaigncontext/quest/Quest.java b/core/src/main/java/com/loremind/domain/campaigncontext/quest/Quest.java index 962a36c..27a49ec 100644 --- a/core/src/main/java/com/loremind/domain/campaigncontext/quest/Quest.java +++ b/core/src/main/java/com/loremind/domain/campaigncontext/quest/Quest.java @@ -5,6 +5,8 @@ import lombok.Data; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; +import java.util.Map; /** * Entité de domaine (Aggregate Root) représentant une Quête. @@ -62,6 +64,13 @@ public class Quest { @Builder.Default private List 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 illustrationPlacements = new HashMap<>(); + private LocalDateTime createdAt; private LocalDateTime updatedAt; } diff --git a/core/src/main/java/com/loremind/domain/campaigncontext/structure/Arc.java b/core/src/main/java/com/loremind/domain/campaigncontext/structure/Arc.java index b7f2c92..b6550e6 100644 --- a/core/src/main/java/com/loremind/domain/campaigncontext/structure/Arc.java +++ b/core/src/main/java/com/loremind/domain/campaigncontext/structure/Arc.java @@ -5,6 +5,8 @@ import lombok.Data; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; +import java.util.Map; /** * Entité de domaine représentant un Arc narratif. @@ -57,6 +59,13 @@ public class Arc { @Builder.Default private List 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 illustrationPlacements = new HashMap<>(); + private LocalDateTime createdAt; private LocalDateTime updatedAt; } diff --git a/core/src/main/java/com/loremind/domain/campaigncontext/structure/Chapter.java b/core/src/main/java/com/loremind/domain/campaigncontext/structure/Chapter.java index b6d5cc1..250455b 100644 --- a/core/src/main/java/com/loremind/domain/campaigncontext/structure/Chapter.java +++ b/core/src/main/java/com/loremind/domain/campaigncontext/structure/Chapter.java @@ -5,6 +5,8 @@ import lombok.Data; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; +import java.util.Map; /** * 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 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). * 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 private List 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 illustrationPlacements = new HashMap<>(); + private LocalDateTime createdAt; private LocalDateTime updatedAt; } diff --git a/core/src/main/java/com/loremind/domain/campaigncontext/structure/ImagePlacement.java b/core/src/main/java/com/loremind/domain/campaigncontext/structure/ImagePlacement.java new file mode 100644 index 0000000..1420180 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/campaigncontext/structure/ImagePlacement.java @@ -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}. + *

+ * 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 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 sanitize(Map placements, Collection imageIds) { + Map 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; + } +} diff --git a/core/src/main/java/com/loremind/domain/campaigncontext/structure/Scene.java b/core/src/main/java/com/loremind/domain/campaigncontext/structure/Scene.java index 8228bd3..ccf5321 100644 --- a/core/src/main/java/com/loremind/domain/campaigncontext/structure/Scene.java +++ b/core/src/main/java/com/loremind/domain/campaigncontext/structure/Scene.java @@ -5,6 +5,8 @@ import lombok.Data; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; +import java.util.Map; /** * Entité de domaine représentant une Scene. @@ -19,6 +21,13 @@ public class Scene { private String name; private String description; // = Description courte dans l'UI 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 /** Cle d'icone choisie par l'utilisateur (cf. CAMPAIGN_ICON_OPTIONS cote front). */ @@ -74,6 +83,13 @@ public class Scene { @Builder.Default private List 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 illustrationPlacements = new HashMap<>(); + /** * "Battlemaps" de la scene destinees a l'export Foundry : liste de paires * { media + sidecar } etiquetees ({@link SceneBattlemap}). Plusieurs cartes = diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/GameSystem.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/GameSystem.java index a88a58c..cafa1e1 100644 --- a/core/src/main/java/com/loremind/domain/gamesystemcontext/GameSystem.java +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/GameSystem.java @@ -68,6 +68,13 @@ public class GameSystem { */ 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 spellTemplate; + /** Auteur déclaré — futur marketplace. Nullable. */ private String author; @@ -120,6 +127,16 @@ public class GameSystem { enemyTemplate = validateAndCopy(fields); } + public void replaceSpellTemplate(List fields) { + spellTemplate = validateAndCopy(fields); + } + + /** Jamais null : un système sans modèle de sort a une liste vide. */ + public List getSpellTemplate() { + if (spellTemplate == null) spellTemplate = new ArrayList<>(); + return spellTemplate; + } + // --- Helpers privés ---------------------------------------------------- private static List appendField(List current, TemplateField field) { diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/RuleDrill.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/RuleDrill.java new file mode 100644 index 0000000..909bf31 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/RuleDrill.java @@ -0,0 +1,13 @@ +package com.loremind.domain.gamesystemcontext; + +/** + * Une situation d'entraînement aux règles et son corrigé. + *

+ * {@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) { +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/RuleDrillReview.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/RuleDrillReview.java new file mode 100644 index 0000000..c97917b --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/RuleDrillReview.java @@ -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 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(); + } + } +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/SheetFieldProposal.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/SheetFieldProposal.java new file mode 100644 index 0000000..a6688e6 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/SheetFieldProposal.java @@ -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. + *

+ * 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 labels, String source) { +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/SheetKind.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/SheetKind.java new file mode 100644 index 0000000..b7cd3a2 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/SheetKind.java @@ -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. + *

+ * 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> sectionAliases; + + SheetKind(String wireName, List> 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> sectionAliases() { + return sectionAliases; + } + + public static Optional 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(); + } +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/Spell.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/Spell.java new file mode 100644 index 0000000..6fde303 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/Spell.java @@ -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. + *

+ * 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 values; + + /** Rang dans le catalogue. */ + private int order; + + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + + public Map getValues() { + if (values == null) values = new HashMap<>(); + return values; + } +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/RuleTrainingCoach.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/RuleTrainingCoach.java new file mode 100644 index 0000000..cbcca1e --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/RuleTrainingCoach.java @@ -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. + *

+ * 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 prepare(String systemName, Map sections, + List scenes, int count, List 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); +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SheetSpellRepository.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SheetSpellRepository.java new file mode 100644 index 0000000..ad14c41 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SheetSpellRepository.java @@ -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 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 spellIds); +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SheetTemplateAdvisor.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SheetTemplateAdvisor.java new file mode 100644 index 0000000..1cb81e7 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SheetTemplateAdvisor.java @@ -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 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 propose(SheetKind kind, String systemName, + Map sections, List existingFieldNames); +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SpellProposer.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SpellProposer.java new file mode 100644 index 0000000..7fe599b --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SpellProposer.java @@ -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). + *

+ * 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 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 extract(String systemName, String sectionTitle, String text, + List fields, List avoid); +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SpellRepository.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SpellRepository.java new file mode 100644 index 0000000..051d2e9 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/SpellRepository.java @@ -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 findByGameSystemId(String gameSystemId); + + void deleteById(String id); + + /** Parmi ces identifiants, ceux qui désignent un sort existant. */ + List existingIds(List ids); +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/RuleTrainingException.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/RuleTrainingException.java new file mode 100644 index 0000000..40b7033 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/RuleTrainingException.java @@ -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); + } +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/SheetProposalException.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/SheetProposalException.java new file mode 100644 index 0000000..19753e2 --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/SheetProposalException.java @@ -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); + } +} diff --git a/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/SpellProposalException.java b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/SpellProposalException.java new file mode 100644 index 0000000..b04ae4b --- /dev/null +++ b/core/src/main/java/com/loremind/domain/gamesystemcontext/ports/exceptions/SpellProposalException.java @@ -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); + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/ai/BrainAiChatClient.java b/core/src/main/java/com/loremind/infrastructure/ai/BrainAiChatClient.java index 85cbc91..dc95d65 100644 --- a/core/src/main/java/com/loremind/infrastructure/ai/BrainAiChatClient.java +++ b/core/src/main/java/com/loremind/infrastructure/ai/BrainAiChatClient.java @@ -69,8 +69,10 @@ public class BrainAiChatClient implements AiChatProvider { try { // blockLast() : transforme le flux réactif en appel bloquant conforme // 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 - .timeout(Duration.ofSeconds(120)) + .timeout(Duration.ofSeconds(300)) .doOnNext(sse -> handleEvent(sse, callbacks)) .blockLast(); callbacks.onComplete().run(); diff --git a/core/src/main/java/com/loremind/infrastructure/ai/BrainRuleTrainingClient.java b/core/src/main/java/com/loremind/infrastructure/ai/BrainRuleTrainingClient.java new file mode 100644 index 0000000..21f9d08 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/ai/BrainRuleTrainingClient.java @@ -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 prepare(String systemName, Map sections, + List scenes, int count, List avoid) { + List> sceneDtos = new ArrayList<>(); + for (SceneBrief scene : scenes == null ? List.of() : scenes) { + Map 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 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 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 call(String path, Map req) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + Map 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 parseDrills(Map resp) { + List 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 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; + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/ai/BrainSheetTemplateClient.java b/core/src/main/java/com/loremind/infrastructure/ai/BrainSheetTemplateClient.java new file mode 100644 index 0000000..a489772 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/ai/BrainSheetTemplateClient.java @@ -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 propose(SheetKind kind, String systemName, + Map sections, List existingFieldNames) { + Map 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 call(Map req) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + Map 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 parse(Map resp) { + List 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 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; + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/ai/BrainSidecar.java b/core/src/main/java/com/loremind/infrastructure/ai/BrainSidecar.java index 5252146..589f60d 100644 --- a/core/src/main/java/com/loremind/infrastructure/ai/BrainSidecar.java +++ b/core/src/main/java/com/loremind/infrastructure/ai/BrainSidecar.java @@ -14,6 +14,7 @@ import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.util.concurrent.TimeUnit; /** @@ -39,6 +40,9 @@ public class BrainSidecar { 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 String internalSecret; @@ -65,7 +69,10 @@ public class BrainSidecar { try { ProcessBuilder pb = new ProcessBuilder(props.getCommand()); 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(); if (workingDir != null) { @@ -78,8 +85,9 @@ public class BrainSidecar { Process started = pb.start(); this.process.set(started); - log.info("[Brain] Sidecar demarre (pid={}, cwd={}).", - started.pid(), workingDir != null ? workingDir : ""); + log.info("[Brain] Sidecar demarre (pid={}, cwd={}, journal={}).", + started.pid(), workingDir != null ? workingDir : "", + logFile != null ? logFile : ""); } catch (IOException e) { log.error("[Brain] Echec du lancement du sidecar (commande={}). " + "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 .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 * ecrit son dossier {@code data/} (index vectoriel, settings.json). diff --git a/core/src/main/java/com/loremind/infrastructure/ai/BrainSidecarProperties.java b/core/src/main/java/com/loremind/infrastructure/ai/BrainSidecarProperties.java index 2e69620..0664810 100644 --- a/core/src/main/java/com/loremind/infrastructure/ai/BrainSidecarProperties.java +++ b/core/src/main/java/com/loremind/infrastructure/ai/BrainSidecarProperties.java @@ -42,6 +42,13 @@ public class BrainSidecarProperties { */ 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 void setEnabled(boolean enabled) { this.enabled = enabled; } @@ -50,4 +57,7 @@ public class BrainSidecarProperties { public String getWorkingDir() { return workingDir; } public void setWorkingDir(String workingDir) { this.workingDir = workingDir; } + + public String getLogFile() { return logFile; } + public void setLogFile(String logFile) { this.logFile = logFile; } } diff --git a/core/src/main/java/com/loremind/infrastructure/ai/BrainSpellProposalClient.java b/core/src/main/java/com/loremind/infrastructure/ai/BrainSpellProposalClient.java new file mode 100644 index 0000000..f37422a --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/ai/BrainSpellProposalClient.java @@ -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 extract(String systemName, String sectionTitle, String text, + List fields, List avoid) { + List> fieldDtos = new ArrayList<>(); + for (SpellField field : fields == null ? List.of() : fields) { + Map dto = new LinkedHashMap<>(); + dto.put("name", field.name()); + dto.put("type", field.number() ? "NUMBER" : "TEXT"); + fieldDtos.add(dto); + } + Map 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 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 parse(Map resp) { + List out = new ArrayList<>(); + if (!(resp.get("spells") instanceof List spells)) return out; + for (Object entry : spells) { + if (!(entry instanceof Map spell)) continue; + Map 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; + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/entity/ArcJpaEntity.java b/core/src/main/java/com/loremind/infrastructure/persistence/entity/ArcJpaEntity.java index a099cd8..ed6e318 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/entity/ArcJpaEntity.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/entity/ArcJpaEntity.java @@ -2,6 +2,7 @@ package com.loremind.infrastructure.persistence.entity; import com.loremind.domain.campaigncontext.structure.ArcType; import com.loremind.infrastructure.persistence.converter.StringListJsonConverter; +import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter; import jakarta.persistence.*; import org.hibernate.annotations.ColumnDefault; import lombok.AllArgsConstructor; @@ -12,6 +13,8 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; 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. @@ -93,6 +96,12 @@ public class ArcJpaEntity { @Builder.Default private List 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 illustrationPlacements = new HashMap<>(); + @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt; diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/entity/ChapterJpaEntity.java b/core/src/main/java/com/loremind/infrastructure/persistence/entity/ChapterJpaEntity.java index b3cf2dc..0b98d76 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/entity/ChapterJpaEntity.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/entity/ChapterJpaEntity.java @@ -1,6 +1,7 @@ package com.loremind.infrastructure.persistence.entity; import com.loremind.infrastructure.persistence.converter.StringListJsonConverter; +import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; @@ -10,6 +11,8 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; 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. @@ -51,6 +54,10 @@ public class ChapterJpaEntity { @Column(name = "narrative_stakes", columnDefinition = "TEXT") 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") @Convert(converter = StringListJsonConverter.class) @Builder.Default @@ -61,6 +68,12 @@ public class ChapterJpaEntity { @Builder.Default private List 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 illustrationPlacements = new HashMap<>(); + @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt; diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/entity/GameSystemJpaEntity.java b/core/src/main/java/com/loremind/infrastructure/persistence/entity/GameSystemJpaEntity.java index 9adbc25..2be784a 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/entity/GameSystemJpaEntity.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/entity/GameSystemJpaEntity.java @@ -55,6 +55,11 @@ public class GameSystemJpaEntity { @Column(name = "enemy_template", columnDefinition = "TEXT") private List 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 spellTemplate; + /** Type d'acteur Foundry pour les ennemis maison (import de structure). Nullable. */ @Column(name = "foundry_actor_type") private String foundryActorType; diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/entity/QuestJpaEntity.java b/core/src/main/java/com/loremind/infrastructure/persistence/entity/QuestJpaEntity.java index 47c8ae9..5e4ccc5 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/entity/QuestJpaEntity.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/entity/QuestJpaEntity.java @@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.quest.QuestNodeRef; import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter; import com.loremind.infrastructure.persistence.converter.QuestNodeListJsonConverter; import com.loremind.infrastructure.persistence.converter.StringListJsonConverter; +import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; @@ -14,6 +15,8 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; +import java.util.Map; /** * Entité JPA pour la persistance des Quests (table {@code quests}). @@ -83,6 +86,12 @@ public class QuestJpaEntity { @Builder.Default private List 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 illustrationPlacements = new HashMap<>(); + @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt; diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/entity/SceneJpaEntity.java b/core/src/main/java/com/loremind/infrastructure/persistence/entity/SceneJpaEntity.java index 87060d6..0d5b7cd 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/entity/SceneJpaEntity.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/entity/SceneJpaEntity.java @@ -8,6 +8,7 @@ import com.loremind.infrastructure.persistence.converter.RoomListJsonConverter; import com.loremind.infrastructure.persistence.converter.SceneBattlemapListJsonConverter; import com.loremind.infrastructure.persistence.converter.SceneBranchListJsonConverter; import com.loremind.infrastructure.persistence.converter.StringListJsonConverter; +import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; @@ -17,6 +18,8 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; 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. @@ -48,6 +51,10 @@ public class SceneJpaEntity { @Column 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). */ @Enumerated(EnumType.STRING) @Column(name = "scene_type", length = 32) @@ -109,6 +116,12 @@ public class SceneJpaEntity { @Builder.Default private List 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 illustrationPlacements = new HashMap<>(); + /** * Battlemaps Foundry : liste de paires { media + sidecar } étiquetées * (variantes Jour/Nuit, étages…). JSON en TEXT via converter (V22). diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/entity/SheetSpellJpaEntity.java b/core/src/main/java/com/loremind/infrastructure/persistence/entity/SheetSpellJpaEntity.java new file mode 100644 index 0000000..9045f20 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/persistence/entity/SheetSpellJpaEntity.java @@ -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; +} diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/entity/SpellJpaEntity.java b/core/src/main/java/com/loremind/infrastructure/persistence/entity/SpellJpaEntity.java new file mode 100644 index 0000000..b30a242 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/persistence/entity/SpellJpaEntity.java @@ -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 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()); + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SheetSpellJpaRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SheetSpellJpaRepository.java new file mode 100644 index 0000000..60ae9dc --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SheetSpellJpaRepository.java @@ -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 { + + List 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); +} diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SpellJpaRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SpellJpaRepository.java new file mode 100644 index 0000000..4fa06fb --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SpellJpaRepository.java @@ -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 { + + List findByGameSystemIdOrderByOrderAsc(Long gameSystemId); +} diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresArcRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresArcRepository.java index 546af32..2c02a1e 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresArcRepository.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresArcRepository.java @@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; import java.util.Optional; /** @@ -86,6 +87,9 @@ public class PostgresArcRepository implements ArcRepository { .illustrationImageIds(jpaEntity.getIllustrationImageIds() != null ? new ArrayList<>(jpaEntity.getIllustrationImageIds()) : new ArrayList<>()) + .illustrationPlacements(jpaEntity.getIllustrationPlacements() != null + ? new HashMap<>(jpaEntity.getIllustrationPlacements()) + : new HashMap<>()) .createdAt(jpaEntity.getCreatedAt()) .updatedAt(jpaEntity.getUpdatedAt()) .build(); @@ -114,6 +118,9 @@ public class PostgresArcRepository implements ArcRepository { .illustrationImageIds(arc.getIllustrationImageIds() != null ? new ArrayList<>(arc.getIllustrationImageIds()) : new ArrayList<>()) + .illustrationPlacements(arc.getIllustrationPlacements() != null + ? new HashMap<>(arc.getIllustrationPlacements()) + : new HashMap<>()) .createdAt(arc.getCreatedAt()) .updatedAt(arc.getUpdatedAt()) .build(); diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresChapterRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresChapterRepository.java index dc854a9..562a1c5 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresChapterRepository.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresChapterRepository.java @@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; import java.util.Optional; /** @@ -74,12 +75,16 @@ public class PostgresChapterRepository implements ChapterRepository { .gmNotes(jpaEntity.getGmNotes()) .playerObjectives(jpaEntity.getPlayerObjectives()) .narrativeStakes(jpaEntity.getNarrativeStakes()) + .guidedMethod(jpaEntity.getGuidedMethod()) .relatedPageIds(jpaEntity.getRelatedPageIds() != null ? new ArrayList<>(jpaEntity.getRelatedPageIds()) : new ArrayList<>()) .illustrationImageIds(jpaEntity.getIllustrationImageIds() != null ? new ArrayList<>(jpaEntity.getIllustrationImageIds()) : new ArrayList<>()) + .illustrationPlacements(jpaEntity.getIllustrationPlacements() != null + ? new HashMap<>(jpaEntity.getIllustrationPlacements()) + : new HashMap<>()) .createdAt(jpaEntity.getCreatedAt()) .updatedAt(jpaEntity.getUpdatedAt()) .build(); @@ -97,12 +102,16 @@ public class PostgresChapterRepository implements ChapterRepository { .gmNotes(chapter.getGmNotes()) .playerObjectives(chapter.getPlayerObjectives()) .narrativeStakes(chapter.getNarrativeStakes()) + .guidedMethod(chapter.getGuidedMethod()) .relatedPageIds(chapter.getRelatedPageIds() != null ? new ArrayList<>(chapter.getRelatedPageIds()) : new ArrayList<>()) .illustrationImageIds(chapter.getIllustrationImageIds() != null ? new ArrayList<>(chapter.getIllustrationImageIds()) : new ArrayList<>()) + .illustrationPlacements(chapter.getIllustrationPlacements() != null + ? new HashMap<>(chapter.getIllustrationPlacements()) + : new HashMap<>()) .createdAt(chapter.getCreatedAt()) .updatedAt(chapter.getUpdatedAt()) .build(); diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresGameSystemRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresGameSystemRepository.java index 9de44ed..c94356e 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresGameSystemRepository.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresGameSystemRepository.java @@ -70,6 +70,9 @@ public class PostgresGameSystemRepository implements GameSystemRepository { .enemyTemplate(e.getEnemyTemplate() != null ? new java.util.ArrayList<>(e.getEnemyTemplate()) : new java.util.ArrayList<>()) + .spellTemplate(e.getSpellTemplate() != null + ? new java.util.ArrayList<>(e.getSpellTemplate()) + : new java.util.ArrayList<>()) .foundryActorType(e.getFoundryActorType()) .author(e.getAuthor()) .isPublic(e.isPublic()) @@ -95,6 +98,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository { .enemyTemplate(g.getEnemyTemplate() != null ? new java.util.ArrayList<>(g.getEnemyTemplate()) : new java.util.ArrayList<>()) + .spellTemplate(new java.util.ArrayList<>(g.getSpellTemplate())) .foundryActorType(g.getFoundryActorType()) .author(g.getAuthor()) .isPublic(g.isPublic()) diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresQuestRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresQuestRepository.java index 5edf40b..4d0bfb6 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresQuestRepository.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresQuestRepository.java @@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; import java.util.Optional; /** @@ -91,6 +92,9 @@ public class PostgresQuestRepository implements QuestRepository { .illustrationImageIds(e.getIllustrationImageIds() != null ? new ArrayList<>(e.getIllustrationImageIds()) : new ArrayList<>()) + .illustrationPlacements(e.getIllustrationPlacements() != null + ? new HashMap<>(e.getIllustrationPlacements()) + : new HashMap<>()) .createdAt(e.getCreatedAt()) .updatedAt(e.getUpdatedAt()) .build(); @@ -121,6 +125,9 @@ public class PostgresQuestRepository implements QuestRepository { .illustrationImageIds(q.getIllustrationImageIds() != null ? new ArrayList<>(q.getIllustrationImageIds()) : new ArrayList<>()) + .illustrationPlacements(q.getIllustrationPlacements() != null + ? new HashMap<>(q.getIllustrationPlacements()) + : new HashMap<>()) .createdAt(q.getCreatedAt()) .updatedAt(q.getUpdatedAt()) .build(); diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSceneRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSceneRepository.java index d942451..e030f68 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSceneRepository.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSceneRepository.java @@ -9,6 +9,7 @@ import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; +import java.util.HashMap; import java.util.Optional; /** @@ -82,6 +83,7 @@ public class PostgresSceneRepository implements SceneRepository { .combatDifficulty(jpaEntity.getCombatDifficulty()) .tactics(jpaEntity.getTactics()) .purpose(jpaEntity.getPurpose()) + .guidedRole(jpaEntity.getGuidedRole()) .enemies(jpaEntity.getEnemies()) .enemyIds(jpaEntity.getEnemyIds() != null ? new ArrayList<>(jpaEntity.getEnemyIds()) @@ -92,6 +94,9 @@ public class PostgresSceneRepository implements SceneRepository { .illustrationImageIds(jpaEntity.getIllustrationImageIds() != null ? new ArrayList<>(jpaEntity.getIllustrationImageIds()) : new ArrayList<>()) + .illustrationPlacements(jpaEntity.getIllustrationPlacements() != null + ? new HashMap<>(jpaEntity.getIllustrationPlacements()) + : new HashMap<>()) .battlemaps(jpaEntity.getBattlemaps() != null ? new ArrayList<>(jpaEntity.getBattlemaps()) : new ArrayList<>()) @@ -127,6 +132,7 @@ public class PostgresSceneRepository implements SceneRepository { .combatDifficulty(scene.getCombatDifficulty()) .tactics(scene.getTactics()) .purpose(scene.getPurpose()) + .guidedRole(scene.getGuidedRole()) .enemies(scene.getEnemies()) .enemyIds(scene.getEnemyIds() != null ? new ArrayList<>(scene.getEnemyIds()) @@ -137,6 +143,9 @@ public class PostgresSceneRepository implements SceneRepository { .illustrationImageIds(scene.getIllustrationImageIds() != null ? new ArrayList<>(scene.getIllustrationImageIds()) : new ArrayList<>()) + .illustrationPlacements(scene.getIllustrationPlacements() != null + ? new HashMap<>(scene.getIllustrationPlacements()) + : new HashMap<>()) .battlemaps(scene.getBattlemaps() != null ? new ArrayList<>(scene.getBattlemaps()) : new ArrayList<>()) diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSheetSpellRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSheetSpellRepository.java new file mode 100644 index 0000000..00322c7 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSheetSpellRepository.java @@ -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 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 spellIds) { + Long owner = Long.parseLong(ownerId); + jpaRepository.deleteByOwner(kind.wireName(), owner); + List 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); + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSpellRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSpellRepository.java new file mode 100644 index 0000000..4d28ba6 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSpellRepository.java @@ -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 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 existingIds(List 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(); + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/CampaignContentInserter.java b/core/src/main/java/com/loremind/infrastructure/transfer/CampaignContentInserter.java index e17620a..83c8fb1 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/CampaignContentInserter.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/CampaignContentInserter.java @@ -133,6 +133,7 @@ class CampaignContentInserter { e.setHooks(d.hooks()); e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe 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()); } result.count("arcs", maps.arcMap.size()); @@ -216,8 +217,10 @@ class CampaignContentInserter { e.setGmNotes(d.gmNotes()); e.setPlayerObjectives(d.playerObjectives()); e.setNarrativeStakes(d.narrativeStakes()); + e.setGuidedMethod(d.guidedMethod()); e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe 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()); } result.count("chapters", maps.chapterMap.size()); @@ -246,6 +249,7 @@ class CampaignContentInserter { e.setNarrativeStakes(d.narrativeStakes()); e.setRelatedPageIds(d.relatedPageIds()); // remappé 2e passe 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()); } @@ -317,11 +321,13 @@ class CampaignContentInserter { e.setEnemyIds(d.enemyIds()); // remappe en 2e passe e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds())); + e.setIllustrationPlacements(IdRemapper.remapStringKeys(maps.imageMap, d.illustrationPlacements())); e.setBattlemaps(resolveBattlemaps(d, maps)); e.setGraphX(d.graphX()); e.setGraphY(d.graphY()); e.setTactics(d.tactics()); e.setPurpose(d.purpose()); + e.setGuidedRole(d.guidedRole()); e.setBranches(d.branches()); // remappe en 2e passe // Rooms : l'id (UUID) et les branches restent tels quels ; seules leurs refs // d'images (galerie + plan) sont remappees vers les images importees. diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/ExportService.java b/core/src/main/java/com/loremind/infrastructure/transfer/ExportService.java index 3e921ea..98856ff 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/ExportService.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/ExportService.java @@ -19,6 +19,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.util.ArrayList; +import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -49,6 +50,8 @@ public class ExportService { private static final QuestNodeListJsonConverter NODE_CONVERTER = new QuestNodeListJsonConverter(); private final GameSystemJpaRepository gameSystemRepo; + private final SpellJpaRepository spellRepo; + private final SheetSpellJpaRepository sheetSpellRepo; private final LoreJpaRepository loreRepo; private final LoreNodeJpaRepository loreNodeRepo; private final TemplateJpaRepository templateRepo; @@ -78,6 +81,8 @@ public class ExportService { private final String appVersion; public ExportService(GameSystemJpaRepository gameSystemRepo, + SpellJpaRepository spellRepo, + SheetSpellJpaRepository sheetSpellRepo, LoreJpaRepository loreRepo, LoreNodeJpaRepository loreNodeRepo, TemplateJpaRepository templateRepo, @@ -106,6 +111,8 @@ public class ExportService { ObjectMapper objectMapper, @Nullable BuildProperties buildProperties) { this.gameSystemRepo = gameSystemRepo; + this.spellRepo = spellRepo; + this.sheetSpellRepo = sheetSpellRepo; this.loreRepo = loreRepo; this.loreNodeRepo = loreNodeRepo; this.templateRepo = templateRepo; @@ -177,7 +184,8 @@ public class ExportService { map(questProgressionRepo.findAll(), this::toQuestProgressionDto), map(questRepo.findAll(), this::toQuestDto), 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(campaignQuests, this::toQuestDto), 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 sheetSpellsOf(List characters, + List npcs, List enemies) { + Set 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. */ @@ -578,7 +604,11 @@ public class ExportService { return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(), e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(), 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) { @@ -615,7 +645,7 @@ public class ExportService { e.getType() != null ? e.getType().name() : null, e.getIcon(), e.getThemes(), e.getStakes(), e.getGmNotes(), 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) { @@ -624,7 +654,8 @@ public class ExportService { return new ContentExport.ChapterDto(e.getId(), e.getName(), e.getDescription(), e.getArcId(), e.getOrder(), "[]", e.getIcon(), e.getGmNotes(), e.getPlayerObjectives(), e.getNarrativeStakes(), - e.getRelatedPageIds(), e.getIllustrationImageIds()); + e.getRelatedPageIds(), e.getIllustrationImageIds(), e.getGuidedMethod(), + e.getIllustrationPlacements()); } private ContentExport.QuestDto toQuestDto(QuestJpaEntity e) { @@ -633,7 +664,7 @@ public class ExportService { PREREQ_CONVERTER.convertToDatabaseColumn(e.getPrerequisites()), NODE_CONVERTER.convertToDatabaseColumn(e.getNodes()), e.getGmNotes(), e.getPlayerObjectives(), e.getNarrativeStakes(), - e.getRelatedPageIds(), e.getIllustrationImageIds()); + e.getRelatedPageIds(), e.getIllustrationImageIds(), e.getIllustrationPlacements()); } private ContentExport.SceneDto toSceneDto(SceneJpaEntity e) { @@ -644,7 +675,8 @@ public class ExportService { e.getEnemies(), e.getEnemyIds(), e.getRelatedPageIds(), e.getIllustrationImageIds(), null, null, // legacy battlemap : plus émis 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) { diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/IdRemapper.java b/core/src/main/java/com/loremind/infrastructure/transfer/IdRemapper.java index 5ba2677..7ebf4cb 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/IdRemapper.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/IdRemapper.java @@ -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 remapStringKeys(Map map, Map byId) { + Map out = new java.util.LinkedHashMap<>(); + if (byId == null) return out; + byId.forEach((id, value) -> out.put(remapStringId(map, id), value)); + return out; + } + static List remapStringList(Map map, List ids) { if (ids == null) return List.of(); List out = new ArrayList<>(ids.size()); diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/ImportIdMaps.java b/core/src/main/java/com/loremind/infrastructure/transfer/ImportIdMaps.java index fe9bc9a..45aec26 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/ImportIdMaps.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/ImportIdMaps.java @@ -24,6 +24,8 @@ final class ImportIdMaps { final Map storedFileMap = new HashMap<>(); final Map gameSystemMap = new HashMap<>(); + /** Sorts des catalogues : sert à remapper les sorts connus des fiches. */ + final Map spellMap = new HashMap<>(); final Map loreMap = new HashMap<>(); final Map loreNodeMap = new HashMap<>(); final Map templateMap = new HashMap<>(); diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/ImportService.java b/core/src/main/java/com/loremind/infrastructure/transfer/ImportService.java index d266d01..609aabc 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/ImportService.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/ImportService.java @@ -1,10 +1,13 @@ 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 org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.InputStream; +import java.util.Map; /** * Façade d'IMPORT de contenu en mode FUSION. @@ -44,6 +47,7 @@ public class ImportService { private final CampaignContentInserter campaignContentInserter; private final PlayStateInserter playStateInserter; private final ImportReferenceRemapper referenceRemapper; + private final SheetSpellJpaRepository sheetSpellRepo; public ImportService(ImportArchiveParser archiveParser, ImageImporter imageImporter, @@ -51,7 +55,8 @@ public class ImportService { LoreContentInserter loreContentInserter, CampaignContentInserter campaignContentInserter, PlayStateInserter playStateInserter, - ImportReferenceRemapper referenceRemapper) { + ImportReferenceRemapper referenceRemapper, + SheetSpellJpaRepository sheetSpellRepo) { this.archiveParser = archiveParser; this.imageImporter = imageImporter; this.storedFileImporter = storedFileImporter; @@ -59,6 +64,7 @@ public class ImportService { this.campaignContentInserter = campaignContentInserter; this.playStateInserter = playStateInserter; this.referenceRemapper = referenceRemapper; + this.sheetSpellRepo = sheetSpellRepo; } @Transactional @@ -79,10 +85,34 @@ public class ImportService { loreContentInserter.insert(export, maps, result); campaignContentInserter.insert(export, maps, result); playStateInserter.insert(export, maps, result); + insertSheetSpells(export, maps); // 4. 2e passe de remapping. referenceRemapper.remap(maps); 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 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()); + } + } } diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/LoreContentInserter.java b/core/src/main/java/com/loremind/infrastructure/transfer/LoreContentInserter.java index 4d861e3..a27630b 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/LoreContentInserter.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/LoreContentInserter.java @@ -4,11 +4,13 @@ import com.loremind.infrastructure.persistence.entity.GameSystemJpaEntity; import com.loremind.infrastructure.persistence.entity.LoreJpaEntity; import com.loremind.infrastructure.persistence.entity.LoreNodeJpaEntity; 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.jpa.GameSystemJpaRepository; import com.loremind.infrastructure.persistence.jpa.LoreJpaRepository; import com.loremind.infrastructure.persistence.jpa.LoreNodeJpaRepository; 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.transfer.dto.ContentExport; import org.springframework.stereotype.Component; @@ -25,17 +27,20 @@ import java.util.List; class LoreContentInserter { private final GameSystemJpaRepository gameSystemRepo; + private final SpellJpaRepository spellRepo; private final LoreJpaRepository loreRepo; private final LoreNodeJpaRepository loreNodeRepo; private final TemplateJpaRepository templateRepo; private final PageJpaRepository pageRepo; LoreContentInserter(GameSystemJpaRepository gameSystemRepo, + SpellJpaRepository spellRepo, LoreJpaRepository loreRepo, LoreNodeJpaRepository loreNodeRepo, TemplateJpaRepository templateRepo, PageJpaRepository pageRepo) { this.gameSystemRepo = gameSystemRepo; + this.spellRepo = spellRepo; this.loreRepo = loreRepo; this.loreNodeRepo = loreNodeRepo; this.templateRepo = templateRepo; @@ -56,7 +61,24 @@ class LoreContentInserter { e.setFoundryActorType(d.foundryActorType()); e.setAuthor(d.author()); 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()); diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/dto/ContentExport.java b/core/src/main/java/com/loremind/infrastructure/transfer/dto/ContentExport.java index f463e74..ffa398e 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/dto/ContentExport.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/dto/ContentExport.java @@ -51,9 +51,18 @@ public record ContentExport( // --- Horloges de progression (Clocks, état de Partie). Absent des anciens bundles -> nullSafe. --- List clocks, // --- Fronts (menaces regroupant des horloges). Absent des anciens bundles -> nullSafe. --- - List fronts + List fronts, + // --- Sorts connus des fiches (PJ, PNJ, ennemis). Absent des anciens bundles -> nullSafe. --- + List 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 * la couche requete (PAS Instant.now() ici, pour rester deterministe et @@ -79,7 +88,22 @@ public record ContentExport( String author, boolean isPublic, /** 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 spellTemplate, + /** Catalogue de sorts, dans l'ordre ; absent des bundles antérieurs (null). */ + List 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 values, + /** Identifiant d'origine, pour remapper les sorts connus des fiches ; absent des premiers bundles (null). */ + Long id ) {} public record LoreDto( @@ -152,7 +176,9 @@ public record ContentExport( List illustrationImageIds, /** Histoire cachée et accroches ; absentes des bundles antérieurs (null). */ String hiddenTruth, - String hooks + String hooks, + /** Placement des illustrations dans le livret PDF ; absent des bundles antérieurs (null). */ + Map illustrationPlacements ) {} public record ChapterDto( @@ -171,7 +197,11 @@ public record ContentExport( String playerObjectives, String narrativeStakes, List relatedPageIds, - List illustrationImageIds + List 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 illustrationPlacements ) {} public record SceneDto( @@ -205,7 +235,11 @@ public record ContentExport( Double graphY, /** Tactique des adversaires et utilité ; absentes des bundles antérieurs (null). */ 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 illustrationPlacements ) {} public record CharacterDto( @@ -408,6 +442,8 @@ public record ContentExport( String playerObjectives, String narrativeStakes, List relatedPageIds, - List illustrationImageIds + List illustrationImageIds, + /** Placement des illustrations dans le livret PDF ; absent des bundles antérieurs (null). */ + Map illustrationPlacements ) {} } diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfAppendices.java b/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfAppendices.java index 9539cd4..ebb3641 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfAppendices.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfAppendices.java @@ -166,7 +166,8 @@ final class PdfAppendices { List sorted = new ArrayList<>(rows); sorted.sort(Comparator.comparing(r -> r.name() == null ? "" : r.name().toLowerCase(Locale.ROOT))); 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("

").append(esc(title)).append("

"); b.append(""); @@ -188,35 +189,54 @@ final class PdfAppendices { } /** - * Ou apparait chaque adversaire : ancre de sa fiche ({@code enemy-}) -> scenes - * (renvois) qui le citent, dans la scene elle-meme ou dans l'une de ses pieces. + * Ou apparait chaque fiche : ancre ({@code enemy-}, {@code npc-}) -> scenes (renvois). + * 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> enemyAppearances(Structure st) { - Map> sceneIdsByEnemy = new LinkedHashMap<>(); - Map byId = new LinkedHashMap<>(); + static Map> appearances(Structure st, Map> mentions) { + Map> sceneAnchors = new LinkedHashMap<>(); for (SceneJpaEntity sc : scenesInOrder(st)) { - byId.put(sc.getId(), sc); List ids = new ArrayList<>(); if (sc.getEnemyIds() != null) ids.addAll(sc.getEnemyIds()); if (sc.getRooms() != null) { for (Room r : sc.getRooms()) if (r.getEnemyIds() != null) ids.addAll(r.getEnemyIds()); } 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> out = new LinkedHashMap<>(); - sceneIdsByEnemy.forEach((enemyAnchor, sceneIds) -> { + sceneAnchors.forEach((anchor, scenes) -> { List refs = new ArrayList<>(); - for (Long sid : sceneIds) { - String anchor = "scene-" + sid; - refs.add(xref(anchor, byId.get(sid).getName()) + " " + pageRef(anchor)); + for (String scene : scenes) { + String name = narrativeName(st, scene); + if (name != null) refs.add(xref(scene, name) + " " + pageRef(scene)); } - out.put(enemyAnchor, refs); + out.put(anchor, refs); }); 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). */ private static List scenesInOrder(Structure st) { List out = new ArrayList<>(); diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfBrushFade.java b/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfBrushFade.java new file mode 100644 index 0000000..beb3c75 --- /dev/null +++ b/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfBrushFade.java @@ -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. + *

+ * 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); + } +} diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfExportOptions.java b/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfExportOptions.java index 53038bf..61c6317 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfExportOptions.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfExportOptions.java @@ -13,9 +13,20 @@ import java.util.Set; * @param printFriendly vrai = sans aplats de couleur (économie d'encre) * @param sections parties incluses * @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, - Set

sections, LoreScope loreScope) { + Set
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 @@ -74,6 +85,27 @@ public record PdfExportOptions(boolean gmContent, PageFormat format, boolean pri sections = sections == null || sections.isEmpty() ? EnumSet.allOf(Section.class) : EnumSet.copyOf(sections); 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
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. */ @@ -91,6 +123,18 @@ public record PdfExportOptions(boolean gmContent, PageFormat format, boolean pri */ public static PdfExportOptions parse(String edition, String format, Boolean print, 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)); PageFormat pf = enumOrNull(PageFormat.class, format); 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); } } - 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) { diff --git a/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfExportService.java b/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfExportService.java index 1d02506..7f3e578 100644 --- a/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfExportService.java +++ b/core/src/main/java/com/loremind/infrastructure/transfer/pdf/PdfExportService.java @@ -5,21 +5,29 @@ import com.loremind.domain.campaigncontext.bestiary.NpcStory; import com.loremind.domain.campaigncontext.quest.NodeType; import com.loremind.domain.campaigncontext.quest.Prerequisite; import com.loremind.domain.campaigncontext.quest.QuestNodeRef; +import com.loremind.application.campaigncontext.ImplicitArc; import com.loremind.domain.campaigncontext.structure.ArcType; +import com.loremind.domain.campaigncontext.structure.ImagePlacement; import com.loremind.domain.campaigncontext.structure.Room; import com.loremind.domain.campaigncontext.structure.RoomBranch; import com.loremind.domain.campaigncontext.structure.SceneBranch; +import com.loremind.domain.shared.template.FieldType; import com.loremind.domain.shared.template.TemplateField; import com.loremind.infrastructure.persistence.entity.*; import com.loremind.infrastructure.persistence.jpa.*; import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.LoreScope; import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.Section; import com.openhtmltopdf.outputdevice.helper.BaseRendererBuilder; +import com.openhtmltopdf.pdfboxout.PagePosition; +import com.openhtmltopdf.pdfboxout.PdfBoxRenderer; import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import com.openhtmltopdf.render.Box; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.awt.Color; +import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -57,10 +65,30 @@ public class PdfExportService { private static final double ILLUSTRATION_MAX_HEIGHT_CM = 11.0; /** Hauteur max affichee d'un portrait de fiche (colonne de 3cm de large). */ private static final double PORTRAIT_MAX_HEIGHT_CM = 4.5; + /** Largeur d'un portrait encadre (theme Parchemin), cadre compris. */ + private static final double PORTRAIT_FRAMED_WIDTH_CM = 3.3; // ----- Libelles/police repetes (S1192 ; fragments HTML generiques dans PdfHtml) ----- private static final String FONT_SERIF = "DejaVu Serif"; private static final String FONT_SANS = "DejaVu Sans"; + /** Theme Parchemin : serif de lecture et capitales de titrage (toutes deux sous licence OFL). */ + private static final String FONT_PARCHMENT_TEXT = "Crimson Text"; + private static final String FONT_PARCHMENT_TITLE = "Cinzel"; + /** Crimson Text a un oeil plus petit que DejaVu : corps agrandi pour une lecture equivalente. */ + private static final double PARCHMENT_BODY_SCALE = 1.1; + /** Teinte claire du theme Parchemin : fond des fiches, et sous les images a zones transparentes. */ + private static final Color PARCHMENT_MATTE = new Color(0xf8f2de); + /** + * Part de la hauteur utile d'une page qu'un bandeau d'ouverture peut occuper, et part qu'un + * bloc insecable (image, image habillee) peut occuper dans une colonne. Les deux se tiennent : + * sous un bandeau et ses titres, il doit rester de quoi loger le plus haut bloc insecable — le + * moteur ne sait le repousser qu'une fois, dans la colonne voisine de la MEME page ; s'il n'y + * tient pas non plus, il est coupe au bas de la page. + */ + private static final double BANNER_MAX_HEIGHT_RATIO = 0.40; + static final double UNBREAKABLE_MAX_HEIGHT_RATIO = 0.44; + /** Ouverture de la couverture illustree a fond perdu (reperee pour ne pas la recouvrir). */ + private static final String ILLUSTRATED_COVER_OPEN = "
"; private static final String ANCHOR_PART_NARRATIVE = "part-narrative"; private static final String LABEL_DESCRIPTION = "Description"; private static final String LABEL_OBJECTIFS_JOUEURS = "Objectifs joueurs"; @@ -118,18 +146,41 @@ public class PdfExportService { /** Construit le PDF de la campagne selon les options. @throws NoSuchElementException si absente. */ public byte[] export(String campaignId, PdfExportOptions options) { options = options != null ? options : PdfExportOptions.defaults(); - String xhtml = xhtml(campaignId, options); + CampaignJpaEntity campaign = campaign(campaignId); + // Une image « fondue en bas de page » n'a sa place qu'une fois la mise en page faite. Si + // le blanc ne suffit pas, le livret est recompose sans elle (elle reprend sa place + // ordinaire) : deux passes au plus, et une seule quand rien n'est a fondre. + Set unfaded = new HashSet<>(); + List slots = new ArrayList<>(); + byte[] pdf = render(buildXhtml(campaign, options, unfaded, slots), options, slots, unfaded); + if (pdf != null) return pdf; + slots = new ArrayList<>(); + return render(buildXhtml(campaign, options, unfaded, slots), options, slots, null); + } + + /** + * Rend le document. Null si une image a fondre n'a pas la place qu'il lui faut : son + * identifiant est alors ajoute a {@code rejected} (non nul a la premiere passe seulement). + */ + private byte[] render(String xhtml, PdfExportOptions options, List slots, Set rejected) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfRendererBuilder builder = new PdfRendererBuilder(); builder.useFastMode(); - registerFonts(builder); + registerFonts(builder, options); builder.withHtmlContent(xhtml, null); builder.toStream(out); try (var renderer = builder.buildPdfRenderer(); var document = renderer.getPdfDocument()) { renderer.layout(); renderer.createPDFWithoutClosing(); - PdfPageOrnaments.draw(document, options); + // Le moteur ne sait situer un element sur sa page qu'une fois les pages ecrites. + List fades = placeFades(renderer, options, slots, rejected); + if (fades == null) return null; + if (options.parchment()) { + PdfParchmentDecor.draw(document, options, xhtml.contains(ILLUSTRATED_COVER_OPEN), fades); + } else { + PdfPageOrnaments.draw(document, options); + } document.save(out); } return out.toByteArray(); @@ -140,7 +191,56 @@ public class PdfExportService { /** Document XHTML intermédiaire (exposé au paquet pour les tests de contenu). */ String xhtml(String campaignId, PdfExportOptions options) { - return buildXhtml(campaign(campaignId), options != null ? options : PdfExportOptions.defaults()); + return buildXhtml(campaign(campaignId), options != null ? options : PdfExportOptions.defaults(), + Set.of(), new ArrayList<>()); + } + + // ====================================================================== Images fondues + + /** Emplacement reserve dans la page pour une image fondue, dessinee apres la pagination. */ + record FadeSlot(String anchor, String mark, String imageId, PdfBrushFade.Edge edge, double aspect) {} + + private static final java.util.regex.Pattern FADE_ANCHOR = java.util.regex.Pattern.compile("^fade-(top|bottom|mark)-\\d+$"); + + /** + * Situe chaque image fondue d'apres la position, apres mise en page, de son emplacement + * reserve. Null si l'une d'elles n'a pas la place voulue et qu'une seconde passe est + * possible ({@code rejected} non nul) ; a la seconde passe, une image sans place n'est + * simplement pas dessinee. + */ + private List placeFades(PdfBoxRenderer renderer, PdfExportOptions options, + List slots, Set rejected) { + List fades = new ArrayList<>(); + if (slots.isEmpty()) return fades; + Map> positions = new HashMap<>(); + for (PagePosition p : renderer.findPagePositionsByID(FADE_ANCHOR)) positions.put(p.getId(), p); + boolean retry = false; + for (FadeSlot slot : slots) { + PagePosition p = positions.get(slot.anchor()); + PdfParchmentDecor.Area area = p == null ? null : PdfParchmentDecor.fadeArea(options.format(), slot.edge(), + p.getY(), p.getHeight(), slot.aspect()); + PdfBrushFade.Edge edge = slot.edge(); + // Pas de blanc sur toute la largeur : en deux colonnes, il en reste peut-etre sous la + // fin du texte, dans la colonne de droite (repere pose en fin de chapitre ou d'arc). + PagePosition mark = slot.mark() == null ? null : positions.get(slot.mark()); + if (area == null && p != null && mark != null && mark.getPageNo() == p.getPageNo()) { + area = PdfParchmentDecor.cornerArea(options.format(), mark.getX(), mark.getY(), mark.getHeight()); + edge = PdfBrushFade.Edge.TOP_LEFT; + } + if (area == null) { + if (rejected != null) { + rejected.add(slot.imageId()); + retry = true; + } + continue; + } + BufferedImage image = imageEncoder.raster(slot.imageId(), + PdfImageEncoder.Spec.of(PdfImageEncoder.ILLUSTRATION_MAX).cropped(area.width() / area.height())); + if (image != null) { + fades.add(new PdfParchmentDecor.Fade(p.getPageNo(), area, image, edge, slot.imageId().hashCode())); + } + } + return retry ? null : fades; } private CampaignJpaEntity campaign(String campaignId) { @@ -157,7 +257,16 @@ public class PdfExportService { * (subset=true) : seuls les glyphes utilises entrent dans le PDF. * Si une ressource manque, le CSS retombe sur serif/sans-serif de base. */ - private void registerFonts(PdfRendererBuilder builder) { + private void registerFonts(PdfRendererBuilder builder, PdfExportOptions options) { + if (options.parchment()) { + // DejaVu reste enregistree a la suite : repli glyphe par glyphe (fleches, ≈, cyrillique...). + font(builder, "/fonts/CrimsonText-Regular.ttf", FONT_PARCHMENT_TEXT, 400, BaseRendererBuilder.FontStyle.NORMAL); + font(builder, "/fonts/CrimsonText-Bold.ttf", FONT_PARCHMENT_TEXT, 700, BaseRendererBuilder.FontStyle.NORMAL); + font(builder, "/fonts/CrimsonText-Italic.ttf", FONT_PARCHMENT_TEXT, 400, BaseRendererBuilder.FontStyle.ITALIC); + font(builder, "/fonts/CrimsonText-BoldItalic.ttf", FONT_PARCHMENT_TEXT, 700, BaseRendererBuilder.FontStyle.ITALIC); + font(builder, "/fonts/Cinzel-Regular.ttf", FONT_PARCHMENT_TITLE, 400, BaseRendererBuilder.FontStyle.NORMAL); + font(builder, "/fonts/Cinzel-Bold.ttf", FONT_PARCHMENT_TITLE, 700, BaseRendererBuilder.FontStyle.NORMAL); + } font(builder, "/fonts/DejaVuSerif.ttf", FONT_SERIF, 400, BaseRendererBuilder.FontStyle.NORMAL); font(builder, "/fonts/DejaVuSerif-Bold.ttf", FONT_SERIF, 700, BaseRendererBuilder.FontStyle.NORMAL); font(builder, "/fonts/DejaVuSerif-Italic.ttf", FONT_SERIF, 400, BaseRendererBuilder.FontStyle.ITALIC); @@ -190,6 +299,8 @@ public class PdfExportService { final PdfExportOptions opt; /** Version MJ : les contenus reserves au MJ (secrets, consequences, combats...) sont rendus. */ final boolean gm; + /** Theme Parchemin : textes d'ouverture sans libelle (lettrine), fiches d'adversaires en bloc de stats. */ + final boolean parchment; final StringBuilder body = new StringBuilder(); /** Cartes rendues en annexe (par scene), ou null si l'annexe Cartes n'est pas demandee. */ Map> maps; @@ -202,10 +313,25 @@ public class PdfExportService { int randomTables; int lorePages; private boolean columns; + /** Images deja preparees pendant cet export (une ouverture ou une image habillee est d'abord mesuree). */ + private final Map images = new HashMap<>(); + /** Longueur du corps juste apres le dernier element qui laisse le texte en haut d'une page. */ + private int pageTopMark = -1; + /** Largeur utile dans la fiche en cours (champs IMAGE d'une fiche ou d'une page de lore) ; 0 hors fiche. */ + double cardWidthCm; + /** Images qui ne peuvent pas etre fondues dans la page (pas la place) : elles reprennent leur place ordinaire. */ + Set unfaded = Set.of(); + /** Emplacements reserves aux images fondues, dans l'ordre du livret. */ + List fades = new ArrayList<>(); + /** Repere pose a la fin du texte courant, en attente de l'emplacement d'image fondue qui le suit. */ + String fadeMark; + /** L'unique arc est l'arc cree d'office : ni titre, ni entree de sommaire, ni signet a son nom. */ + boolean implicitArc; Ctx(PdfExportOptions opt) { this.opt = opt; this.gm = opt.gmContent(); + this.parchment = opt.parchment(); } void addToc(int level, String title, String anchor) { @@ -219,7 +345,8 @@ public class PdfExportService { /** Le petit format garde une colonne ; les tables et cartes restent hors du flux. */ void beginColumns() { - columns = opt.format() == PdfExportOptions.PageFormat.A4; + columns = opt.format() == PdfExportOptions.PageFormat.A4 + || (parchment && opt.format() == PdfExportOptions.PageFormat.LETTER); if (columns) body.append("
"); } @@ -228,6 +355,51 @@ public class PdfExportService { columns = false; } + /** Rien n'a ete ecrit depuis : seul un titre precede, en haut d'une page. */ + void markPageTop() { + pageTopMark = body.length(); + } + + boolean atPageTop() { + return pageTopMark == body.length(); + } + + double textHeightCm() { + PdfExportOptions.PageFormat f = opt.format(); + return f.heightCm - f.marginTopCm - f.marginBottomCm; + } + + double bodyPt() { + return opt.format().bodyPt * (parchment ? PARCHMENT_BODY_SCALE : 1); + } + + /** Geometrie du texte courant, la ou l'on ecrit (colonne ou pleine largeur). */ + PdfFigures.Measure measure() { + return new PdfFigures.Measure(contentWidthCm(), textHeightCm(), bodyPt(), columns); + } + + /** Preparation des illustrations : sur parchemin, la transparence s'aplatit sur la teinte claire. */ + PdfImageEncoder.Spec imageSpec(int maxDim) { + PdfImageEncoder.Spec spec = PdfImageEncoder.Spec.of(maxDim); + return opt.parchmentBackground() ? spec.matte(PARCHMENT_MATTE) : spec; + } + + /** + * Texte d'ouverture d'un arc, d'un chapitre ou d'une quete (reserve au MJ). Classique : + * champ « Description ». Parchemin : texte courant sans libelle, lettrine si le premier + * paragraphe couvre au moins trois lignes. + */ + void opening(String value) { + if (!gm) return; + if (parchment) lead(body, value, dropCapMinChars()); + else block(body, LABEL_DESCRIPTION, value); + } + + /** Longueur a partir de laquelle un paragraphe couvre la hauteur d'une lettrine (trois lignes). */ + int dropCapMinChars() { + return columns ? 175 : 270; + } + /** Champ reserve au MJ : absent de la version joueurs. */ void gmBlock(String label, String value) { if (gm) block(body, label, value); @@ -239,7 +411,8 @@ public class PdfExportService { } } - private String buildXhtml(CampaignJpaEntity campaign, PdfExportOptions opt) { + private String buildXhtml(CampaignJpaEntity campaign, PdfExportOptions opt, Set unfaded, + List fadeSlots) { List npcTemplate = resolveTemplate(campaign.getGameSystemId(), true); List enemyTemplate = resolveTemplate(campaign.getGameSystemId(), false); CampaignPublication pub = campaign.getPublication() != null @@ -249,6 +422,8 @@ public class PdfExportService { // et le sommaire sont assembles ensuite en tete de document. Structure st = structureLoader.load(campaign); Ctx ctx = new Ctx(opt); + ctx.unfaded = unfaded; + ctx.fades = fadeSlots; // Cartes encodees d'abord : les scenes y renvoient au lieu de les afficher en petit. if (opt.includes(Section.MAPS)) ctx.maps = PdfAppendices.collectMaps(st, imageEncoder); List npcRows = opt.includes(Section.NPCS) ? npcEntries(campaign) : List.of(); @@ -263,7 +438,12 @@ public class PdfExportService { personas(ctx, "part-enemies", "Bestiaire", enemyRows, enemyTemplate, true); if (opt.includes(Section.TABLES)) randomTables(ctx, campaign); if (opt.includes(Section.LORE)) lore(ctx, campaign, st); - if (opt.includes(Section.APPENDIX) && ctx.gm) appendix(ctx, st, npcRows, enemyRows); + // Fiches citees dans le texte : renvoi « (p. N) » et lien, AVANT les annexes (leurs index + // listent les scenes ou chaque fiche apparait) et sans toucher aux pages de cartes. + Map> mentions = PdfMentions + .of(mentionEntities(npcRows, enemyRows), loreTitles(campaign), opt.shortNameRefs(), ctx.body) + .linkInto(ctx.body); + if (opt.includes(Section.APPENDIX) && ctx.gm) appendix(ctx, st, npcRows, enemyRows, mentions); if (ctx.maps != null) PdfAppendices.mapsPart(ctx, ctx.maps); StringBuilder full = new StringBuilder(); @@ -285,18 +465,42 @@ public class PdfExportService { * Annexes MJ : revelations et indices, index des PNJ et des adversaires (avec leurs * apparitions). Les index ne listent que les fiches presentes dans le livret. */ - private void appendix(Ctx ctx, Structure st, List npcRows, List enemyRows) { + private void appendix(Ctx ctx, Structure st, List npcRows, List enemyRows, + Map> mentions) { StringBuilder annex = new StringBuilder(); PdfAppendices.revelations(annex, st); - PdfAppendices.index(annex, "annex-npcs", "Index des PNJ", indexRows(npcRows, "npc-"), null); + // Apparitions : adversaires lies aux scenes (structure) et fiches citees dans leur texte. + Map> appearances = PdfAppendices.appearances(st, mentions); + PdfAppendices.index(annex, "annex-npcs", "Index des PNJ", indexRows(npcRows, "npc-"), appearances); PdfAppendices.index(annex, "annex-enemies", "Index des adversaires", indexRows(enemyRows, "enemy-"), - PdfAppendices.enemyAppearances(st)); + appearances); if (annex.isEmpty()) return; ctx.body.append("

Annexes

").append(annex); ctx.addToc(0, "Annexes", "part-annex"); ctx.bookmarks.append(bookmark("Annexes", "part-annex", "")); } + /** Fiches presentes dans le livret : les seules que le texte peut citer avec un renvoi. */ + private static List mentionEntities(List npcRows, List enemyRows) { + List out = new ArrayList<>(); + for (PersonaRow r : npcRows) out.add(new PdfMentions.Entity("npc-" + r.id(), r.name(), true)); + for (PersonaRow r : enemyRows) out.add(new PdfMentions.Entity("enemy-" + r.id(), r.name(), false)); + return out; + } + + /** Titres des pages de lore : un lieu ou une faction ne doit pas passer pour le nom court d'un PNJ. */ + private List loreTitles(CampaignJpaEntity campaign) { + String loreId = campaign.getLoreId(); + if (loreId == null || loreId.isBlank()) return List.of(); + try { + List titles = new ArrayList<>(); + for (PageJpaEntity p : pageRepo.findByLoreId(Long.parseLong(loreId))) titles.add(p.getTitle()); + return titles; + } catch (NumberFormatException e) { + return List.of(); + } + } + private static List indexRows(List rows, String anchorPrefix) { List out = new ArrayList<>(); for (PersonaRow r : rows) { @@ -336,9 +540,10 @@ public class PdfExportService { */ private void cover(StringBuilder b, Ctx ctx, CampaignJpaEntity c, CampaignPublication pub) { boolean published = pub.hasContent(); + if (ctx.parchment && !ctx.opt.printFriendly() && parchmentCover(b, ctx, c, pub)) return; PdfImage art = imageEncoder.image(pub.coverImageId(), PdfImageEncoder.ILLUSTRATION_MAX); if (art != null && ctx.opt.format() == PdfExportOptions.PageFormat.A4 && !ctx.opt.printFriendly()) { - illustratedCover(b, ctx, c, pub, art); + illustratedCover(b, ctx, c, pub, coverArtWithinPage(pub.coverImageId(), art)); return; } b.append("
"); @@ -374,20 +579,58 @@ public class PdfExportService { b.append(DIV_CLOSE); } + /** + * Image de la couverture A4 illustree : telle quelle si elle est au format de la page ou plus + * large (ses cotes depassent, hors page) ; recadree en hauteur si elle est plus haute que la + * page — sinon elle deborderait sur la page 2 et masquerait le haut des credits (le moteur + * ne rogne pas d'une page a l'autre). + */ + private PdfImage coverArtWithinPage(String imageId, PdfImage art) { + double page = 29.7 / 21.0; + if ((double) art.h() / art.w() <= page) return art; + PdfImage cropped = imageEncoder.image(imageId, + PdfImageEncoder.Spec.of(PdfImageEncoder.ILLUSTRATION_MAX).cropped(1 / page)); + return cropped != null ? cropped : art; + } + /** Couverture A4 illustree : image a fond perdu et cartouche contraste, sans etirer l'image. */ private static void illustratedCover(StringBuilder b, Ctx ctx, CampaignJpaEntity c, CampaignPublication pub, PdfImage art) { double scale = Math.max(21.0 / art.w(), 29.7 / art.h()); double width = art.w() * scale, height = art.h() * scale; - b.append("
") - .append("
"); + .append("\" src=\"").append(art.uri()).append("\"/>"); + coverCaption(b, ctx, c, pub, 1.0); + } + + /** + * Couverture illustree du theme Parchemin, a fond perdu dans TOUS les formats : l'image est + * recadree au format de la page avant d'etre posee (une image plus haute que la page + * deborderait sur la suivante). Faux, sans rien ecrire, s'il n'y a pas d'image exploitable. + */ + private boolean parchmentCover(StringBuilder b, Ctx ctx, CampaignJpaEntity c, CampaignPublication pub) { + PdfExportOptions.PageFormat f = ctx.opt.format(); + PdfImage art = imageEncoder.image(pub.coverImageId(), + PdfImageEncoder.Spec.of(PdfImageEncoder.ILLUSTRATION_MAX).cropped(f.widthCm / f.heightCm)); + if (art == null) return false; + b.append(ILLUSTRATED_COVER_OPEN).append(""); + coverCaption(b, ctx, c, pub, f.widthCm / PdfExportOptions.PageFormat.A4.widthCm); + return true; + } + + /** Cartouche de la couverture illustree ; {@code scale} : taille du titre rapportee au A4. */ + private static void coverCaption(StringBuilder b, Ctx ctx, CampaignJpaEntity c, CampaignPublication pub, + double scale) { + b.append("
"); String kicker = coverKicker(ctx, pub); if (kicker != null) b.append("
").append(esc(kicker)).append(DIV_CLOSE); - int titleSize = c.getName().length() > 100 ? 20 : c.getName().length() > 60 ? 26 : 32; + int titleSize = (int) Math.round((c.getName().length() > 100 ? 20 : c.getName().length() > 60 ? 26 : 32) * scale); b.append("

") .append(esc(c.getName())).append("

"); if (notBlank(pub.subtitle())) b.append("
").append(esc(pub.subtitle())).append(DIV_CLOSE); @@ -452,7 +695,12 @@ public class PdfExportService { ctx.beginColumns(); technicalTable(b, pub); String pitch = notBlank(pub.pitch()) ? pub.pitch() : c.getDescription(); - introSection(b, "L'aventure en bref", pitch); + if (ctx.parchment && notBlank(pitch)) { + b.append("

L'aventure en bref

"); + lead(b, pitch, ctx.dropCapMinChars()); + } else { + introSection(b, "L'aventure en bref", pitch); + } box(b, "warning", "Avertissements de contenu", pub.contentWarnings()); if (ctx.gm) { introSection(b, "Contexte pour le MJ", pub.gmBackground()); @@ -494,6 +742,12 @@ public class PdfExportService { if (arcs.isEmpty()) return null; if (arcs.size() == 1 && st.chaptersByArc.get(arcs.get(0).getId()).size() <= 1) return null; StringBuilder s = new StringBuilder(); + if (isImplicitArc(arcs)) { + for (ChapterJpaEntity ch : st.chaptersByArc.get(arcs.get(0).getId())) { + s.append("- ").append(ch.getName()).append('\n'); + } + return s.toString(); + } for (ArcJpaEntity arc : arcs) { List chapters = new ArrayList<>(); for (ChapterJpaEntity ch : st.chaptersByArc.get(arc.getId())) chapters.add(ch.getName()); @@ -552,17 +806,38 @@ public class PdfExportService { } } + // Arc cree d'office, que l'auteur n'a jamais vu (miroir de l'UI) : ses chapitres sont + // imprimes directement sous la partie, sans titre ni entree de sommaire « Arc principal ». + ctx.implicitArc = isImplicitArc(arcs); + + // Parchemin : la planche du premier arc precede le titre de la partie (qui, sinon, + // resterait seul sur sa page). + Gallery firstArc = gallery(arcs.get(0)); + String firstOpener = ctx.parchment ? openerId(ctx, firstArc) : null; + boolean plate = firstOpener != null && plate(ctx, firstOpener, firstArc.placement(firstOpener), true); ctx.body.append("

Structure narrative

"); ctx.addToc(0, "Structure narrative", ANCHOR_PART_NARRATIVE); narrativeBookmarks(ctx, st, arcs); ctx.beginColumns(); - for (ArcJpaEntity arc : arcs) { - arcSection(ctx, st, arc); + ctx.markPageTop(); + for (int i = 0; i < arcs.size(); i++) { + arcSection(ctx, st, arcs.get(i), plate && i == 0); } ctx.endColumns(); } + /** + * Arc cree d'office : le seul arc visible, lineaire, vide de texte et encore a son nom par + * defaut (meme regle que {@link ImplicitArc} et que {@code implicitArc} cote front). Un arc + * que l'auteur a nomme lui-meme garde son titre. + */ + static boolean isImplicitArc(List visibleArcs) { + if (visibleArcs.size() != 1) return false; + ArcJpaEntity arc = visibleArcs.get(0); + return arc.getType() != ArcType.HUB && isBare(arc) && ImplicitArc.isDefaultName(arc.getName()); + } + /** Aucun contenu d'ecriture dans l'arc (son nom ne compte pas : « Arc principal » est cree d'office). */ static boolean isBare(ArcJpaEntity arc) { return allBlank(arc.getDescription(), arc.getThemes(), arc.getStakes(), arc.getRewards(), @@ -593,30 +868,320 @@ public class PdfExportService { for (ChapterJpaEntity ch : st.chaptersByArc.get(arc.getId())) { chBms.append(bookmark(ch.getName(), "ch-" + ch.getId(), "")); } - arcBms.append(bookmark(arc.getName(), "arc-" + arc.getId(), chBms.toString())); + // Arc cree d'office : ses chapitres sont des signets directs de la partie. + if (ctx.implicitArc) arcBms.append(chBms); + else arcBms.append(bookmark(arc.getName(), "arc-" + arc.getId(), chBms.toString())); } ctx.bookmarks.append(bookmark("Structure narrative", ANCHOR_PART_NARRATIVE, arcBms.toString())); } - /** Un arc complet : en-tete + champs + tous ses chapitres. */ - private void arcSection(Ctx ctx, Structure st, ArcJpaEntity arc) { + /** + * Un arc complet : en-tete + champs + tous ses chapitres. + * + * @param plateDone la planche pleine page de cet arc a deja ete posee (avant le titre de la partie) + */ + private void arcSection(Ctx ctx, Structure st, ArcJpaEntity arc, boolean plateDone) { StringBuilder b = ctx.body; - ctx.addToc(1, arc.getName(), "arc-" + arc.getId()); - b.append("

") - .append("Arc") - .append(esc(arc.getName())).append("

"); - arcFields(ctx, arc); - - for (ChapterJpaEntity ch : st.chaptersByArc.get(arc.getId())) { - chapterSection(ctx, st, ch); + if (!ctx.implicitArc) ctx.addToc(1, arc.getName(), "arc-" + arc.getId()); + String opener = plateDone ? openerId(ctx, gallery(arc)) : arcOpener(ctx, st, arc); + boolean top = ctx.atPageTop(); + int arcStart = b.length(); + b.append("
"); + // Arc cree d'office : pas de titre « Arc principal », ses chapitres suivent directement. + if (!ctx.implicitArc) { + b.append("

") + .append("Arc") + .append(esc(arc.getName())).append("

"); } - b.append(DIV_CLOSE); + if (top) ctx.markPageTop(); + int fieldsStart = b.length(); + arcFields(ctx, arc, opener); + balanceArcIntro(ctx, st, arc, arcStart, fieldsStart); + + // Une image « fondue en bas de page » se dessine sous la fin du chapitre ou de + // l'arc ; son emplacement est hors du flux en colonnes, donc hors du bloc de l'arc. + boolean open = true; + boolean faded = false; + for (ChapterJpaEntity ch : st.chaptersByArc.get(arc.getId())) { + if (!open) b.append("
"); + open = true; + faded = false; + chapterSection(ctx, st, ch); + String fade = fadeBottomId(ctx, gallery(ch)); + if (fade != null && !ctx.unfaded.contains(fade)) { + b.append(DIV_CLOSE); + open = false; + faded = true; + fadeBottom(ctx, fade); + } + } + String arcFade = fadeBottomId(ctx, gallery(arc)); + // Deux images fondues ne se suivent pas sur la meme fin de page : celle de l'arc cede, et + // comme celle qui n'a pas la place, elle reste une image ordinaire en fin d'arc. + boolean arcFaded = arcFade != null && !faded && !ctx.unfaded.contains(arcFade); + if (arcFade != null && !arcFaded) { + if (!open) b.append("
"); + open = true; + figure(ctx, image(ctx, arcFade), imageEncoder.caption(arcFade)); + } + if (arcFaded && open) fadeMark(ctx); + if (open) b.append(DIV_CLOSE); + if (arcFaded) fadeBottom(ctx, arcFade); + } + + /** + * Image de la galerie destinee au bas de la derniere page (theme Parchemin, hors impression), + * ou null. Elle quitte sa place habituelle en tete : fondue si la place s'y prete, sinon + * image ordinaire a la fin du chapitre ou de l'arc. + */ + private String fadeBottomId(Ctx ctx, Gallery gallery) { + if (!ctx.parchment || ctx.opt.printFriendly()) return null; + for (String id : gallery.ids()) { + if (gallery.placement(id) == ImagePlacement.FADE_BOTTOM && image(ctx, id) != null) return id; + } + return null; + } + + /** La galerie sans l'image a fondre en bas de page (dessinee apres la pagination, pas dans le texte). */ + private List plain(Ctx ctx, Gallery gallery) { + return without(gallery.ids(), fadeBottomId(ctx, gallery)); + } + + /** + * Illustrations d'un arc, d'un chapitre ou d'une quete, avec le placement que l'auteur a + * choisi pour certaines ({@link ImagePlacement}). Le theme classique n'en tient pas compte. + */ + private record Gallery(List ids, Map placements) { + ImagePlacement placement(String imageId) { + return ImagePlacement.of(placements, imageId); + } + } + + private static Gallery gallery(List ids, Map placements) { + return new Gallery(ids != null ? ids : List.of(), placements != null ? placements : Map.of()); + } + + private static Gallery gallery(ArcJpaEntity arc) { + return gallery(arc.getIllustrationImageIds(), arc.getIllustrationPlacements()); + } + + private static Gallery gallery(ChapterJpaEntity chapter) { + return gallery(chapter.getIllustrationImageIds(), chapter.getIllustrationPlacements()); + } + + private static Gallery gallery(QuestJpaEntity quest) { + return gallery(quest.getIllustrationImageIds(), quest.getIllustrationPlacements()); + } + + /** + * Image d'ouverture d'une galerie (theme Parchemin) : la premiere que l'auteur a placee en + * ouverture (bandeau, pleine page, fondue en haut) ; a defaut, la premiere laissee en + * automatique. Une image « dans le texte » ou « fondue en bas de page » n'ouvre jamais. + */ + private String openerId(Ctx ctx, Gallery gallery) { + String auto = null; + for (String id : gallery.ids()) { + switch (gallery.placement(id)) { + case BANNER, FULL_PAGE, FADE_TOP -> { + if (image(ctx, id) != null) return id; + } + case AUTO -> { + if (auto == null) auto = id; + } + default -> { /* dans le texte, ou en bas de la derniere page */ } + } + } + return auto; + } + + /** + * Pose l'ouverture choisie, hors colonnes : planche pleine page si l'auteur l'a demandee + * (ou, en automatique, pour l'image en hauteur d'un arc), sinon bandeau — fondu en haut de + * page s'il l'a demande. Vrai si c'est une planche : la suite commence en haut d'une page. + */ + private boolean open(Ctx ctx, String imageId, PdfImage img, ImagePlacement placement, boolean arc) { + if (plate(ctx, imageId, placement, arc)) return true; + banner(ctx, imageId, img, arc, placement == ImagePlacement.FADE_TOP); + return false; + } + + /** Repere en fin de texte, dans le flux : sa position dira ou le texte s'arrete (colonne et hauteur). */ + private static void fadeMark(Ctx ctx) { + ctx.fadeMark = "fade-mark-" + ctx.fades.size(); + ctx.body.append("
"); + } + + /** Emplacement d'une image fondue en bas de page : marque la fin du texte, la suite commence une page. */ + private void fadeBottom(Ctx ctx, String imageId) { + PdfImage img = image(ctx, imageId); + ctx.endColumns(); + String anchor = "fade-bottom-" + ctx.fades.size(); + ctx.body.append("
"); + ctx.fades.add(new FadeSlot(anchor, ctx.fadeMark, imageId, PdfBrushFade.Edge.TOP, (double) img.h() / img.w())); + ctx.fadeMark = null; + ctx.beginColumns(); + ctx.markPageTop(); + } + + /** + * Emplacement d'un bandeau d'ouverture fondu : un vide de la hauteur de l'image, en haut d'une + * page ; l'image y est dessinee apres la pagination, a fond perdu en haut et sur les cotes, + * son bord inferieur perdu dans le parchemin. + */ + private void fadeTop(Ctx ctx, String imageId, PdfImage img) { + PdfExportOptions.PageFormat f = ctx.opt.format(); + boolean fresh = !ctx.atPageTop(); + ctx.endColumns(); + double height = Math.min(f.widthCm * img.h() / img.w(), f.heightCm * BANNER_MAX_HEIGHT_RATIO); + // Le titre remonte un peu dans le bas du fondu, ou l'image a deja disparu. + double slot = height * 0.86 - f.marginTopCm; + String anchor = "fade-top-" + ctx.fades.size(); + ctx.body.append("
"); + ctx.fades.add(new FadeSlot(anchor, null, imageId, PdfBrushFade.Edge.BOTTOM, (double) img.h() / img.w())); + } + + /** + * Theme Parchemin, deux colonnes : quand le premier chapitre de l'arc s'ouvre sur un bandeau + * pleine largeur, le texte de l'arc qui le precede est reparti sur deux colonnes de meme + * hauteur. Le moteur n'equilibre pas les colonnes : sans cela, ce texte court resterait dans + * la colonne de gauche, la droite vide au-dessus du bandeau. + */ + private void balanceArcIntro(Ctx ctx, Structure st, ArcJpaEntity arc, int arcStart, int fieldsStart) { + StringBuilder b = ctx.body; + List chapters = st.chaptersByArc.get(arc.getId()); + if (!ctx.parchment || !ctx.columns || b.length() == fieldsStart || chapters.isEmpty() + || chapterOpenerId(ctx, chapters.get(0), st) == null) { + return; + } + String balanced = PdfFigures.balanced(b.substring(fieldsStart), ctx.measure()); + if (balanced == null) return; + String head = b.substring(arcStart + "
".length(), fieldsStart); + b.setLength(arcStart); + ctx.endColumns(); + b.append("
").append(head).append(balanced).append(DIV_CLOSE); + ctx.beginColumns(); + b.append("
"); + // Le bandeau du chapitre commence quand meme une page : sous ce texte ET un bandeau, il ne + // resterait qu'un bas de page trop court pour un bloc insecable (cf. BANNER_MAX_HEIGHT_RATIO). + } + + // ----- Ouvertures illustrees (theme Parchemin) ----- + + private static String first(List ids) { + return isEmpty(ids) ? null : ids.get(0); + } + + /** La liste sans l'image deja utilisee en ouverture ({@code used} nul : la liste telle quelle). */ + private static List without(List ids, String used) { + if (used == null || ids == null || !ids.contains(used)) return ids; + List rest = new ArrayList<>(ids); + rest.remove(used); + return rest; + } + + /** Illustration preparee une seule fois par export (elle est mesuree avant d'etre placee). */ + private PdfImage image(Ctx ctx, String imageId) { + if (imageId == null) return null; + return ctx.images.computeIfAbsent(imageId, + id -> imageEncoder.image(id, ctx.imageSpec(PdfImageEncoder.ILLUSTRATION_MAX))); + } + + /** + * Planche pleine page (hors mode impression, pour une image en hauteur proche du format de + * la page) : ecrite hors colonnes, la suite reprend en haut de la page suivante. Faux, sans + * rien ecrire, si l'image ne s'y prete pas. + */ + private boolean plate(Ctx ctx, String imageId, ImagePlacement placement, boolean arc) { + PdfExportOptions.PageFormat f = ctx.opt.format(); + PdfImage img = image(ctx, imageId); + if (img == null || ctx.opt.printFriendly()) return false; + // Demandee par l'auteur : quelle que soit la forme de l'image (elle est recadree). En + // automatique : seulement pour un arc, et une image en hauteur proche du format de la page. + boolean wanted = placement == ImagePlacement.FULL_PAGE + || (placement == ImagePlacement.AUTO && arc && PdfFigures.plateShaped(img, f)); + if (!wanted) return false; + PdfImage cropped = imageEncoder.image(imageId, + PdfImageEncoder.Spec.of(PdfImageEncoder.ILLUSTRATION_MAX).cropped(f.widthCm / f.heightCm)); + if (cropped == null) return false; + ctx.endColumns(); + ctx.body.append(PdfFigures.plate(cropped, f, imageEncoder.caption(imageId))); + return true; + } + + /** + * Bandeau pleine largeur, hors colonnes. Un arc commence toujours une page ; un chapitre ou + * une quete seulement en deux colonnes (sur une colonne, le bandeau suit simplement le texte) + * — et jamais quand seul un titre precede, deja en haut de page. + */ + private void banner(Ctx ctx, String imageId, PdfImage img, boolean arc, boolean fadeTop) { + // Jamais fondu en mode impression : une image a fond perdu coute de l'encre. + if (fadeTop && !ctx.opt.printFriendly()) { + fadeTop(ctx, imageId, img); + return; + } + boolean fresh = (arc || ctx.columns) && !ctx.atPageTop(); + ctx.endColumns(); + ctx.body.append(PdfFigures.banner(img, ctx.opt.format().contentWidthCm(), + ctx.textHeightCm() * BANNER_MAX_HEIGHT_RATIO, imageEncoder.caption(imageId), fresh)); + } + + /** + * Ouverture d'un arc (theme Parchemin) : sa premiere illustration en planche pleine page ou, + * a defaut, en bandeau. Rend l'identifiant de l'image utilisee (elle ne sera pas repetee + * dans le texte), ou null. + */ + private String arcOpener(Ctx ctx, Structure st, ArcJpaEntity arc) { + if (!ctx.parchment) return null; + Gallery gallery = gallery(arc); + String id = openerId(ctx, gallery); + PdfImage img = image(ctx, id); + if (img == null) { + // Arc sans image ni texte dont le premier chapitre s'ouvre sur un bandeau : son titre + // l'accompagne en haut de la nouvelle page, au lieu de rester seul au bas de la precedente. + List chapters = st.chaptersByArc.get(arc.getId()); + if (!ctx.atPageTop() && !hasGmText(ctx, arc) && !chapters.isEmpty() + && chapterOpenerId(ctx, chapters.get(0), st) != null) { + ctx.endColumns(); + ctx.body.append(PdfFigures.PAGE_BREAK); + ctx.beginColumns(); + ctx.markPageTop(); + } + return null; + } + boolean plate = open(ctx, id, img, gallery.placement(id), true); + ctx.beginColumns(); + if (plate) ctx.markPageTop(); + return id; + } + + /** L'arc a-t-il du texte a lui dans cette edition (tous ses champs sont reserves au MJ) ? */ + private static boolean hasGmText(Ctx ctx, ArcJpaEntity arc) { + return ctx.gm && !allBlank(arc.getDescription(), arc.getThemes(), arc.getStakes(), arc.getRewards(), + arc.getResolution(), arc.getGmNotes(), arc.getHiddenTruth(), arc.getHooks()); + } + + /** Image d'ouverture d'un chapitre : celle de sa galerie, sinon celle de la quete fusionnee. */ + private String chapterOpenerId(Ctx ctx, ChapterJpaEntity ch, Structure st) { + String id = openerId(ctx, gallery(ch)); + if (image(ctx, id) != null) return id; + QuestJpaEntity fused = st.questByContainerChapter.get(ch.getId()); + id = fused != null ? openerId(ctx, gallery(fused)) : null; + return image(ctx, id) != null ? id : null; + } + + /** Placement choisi pour l'image d'ouverture d'un chapitre (galerie du chapitre, sinon de sa quete). */ + private static ImagePlacement chapterOpenerPlacement(ChapterJpaEntity ch, Structure st, String imageId) { + Gallery own = gallery(ch); + if (own.ids().contains(imageId)) return own.placement(imageId); + QuestJpaEntity fused = st.questByContainerChapter.get(ch.getId()); + return fused != null ? gallery(fused).placement(imageId) : ImagePlacement.AUTO; } /** Champs d'un arc ; tout est reserve au MJ (synopsis, enjeux, resolution...) sauf les illustrations. */ - private void arcFields(Ctx ctx, ArcJpaEntity arc) { - illustrations(ctx, arc.getIllustrationImageIds()); - ctx.gmBlock(LABEL_DESCRIPTION, arc.getDescription()); + private void arcFields(Ctx ctx, ArcJpaEntity arc, String openerId) { + illustrations(ctx, without(plain(ctx, gallery(arc)), openerId)); + ctx.opening(arc.getDescription()); ctx.gmBox(CSS_SECRET, "Histoire cachée", arc.getHiddenTruth()); ctx.gmBlock("Accroches", arc.getHooks()); ctx.gmBlock(LABEL_THEMES, arc.getThemes()); @@ -630,16 +1195,36 @@ public class PdfExportService { private void chapterSection(Ctx ctx, Structure st, ChapterJpaEntity ch) { StringBuilder b = ctx.body; QuestJpaEntity fused = st.questByContainerChapter.get(ch.getId()); - ctx.addToc(2, ch.getName(), "ch-" + ch.getId()); + // Sous un arc cree d'office, le chapitre remonte d'un niveau dans le sommaire. + ctx.addToc(ctx.implicitArc ? 1 : 2, ch.getName(), "ch-" + ch.getId()); + // Parchemin : un chapitre illustre s'ouvre sur un bandeau pleine largeur (ou, si l'auteur + // l'a choisi, sur une planche ou un bandeau fondu). L'ouverture sort du flux en colonnes, + // donc de l'arc, qui reprend aussitot apres. + String opener = ctx.parchment ? chapterOpenerId(ctx, ch, st) : null; + if (opener != null) { + boolean top = ctx.atPageTop(); + b.append(DIV_CLOSE); + if (top) ctx.markPageTop(); + boolean plate = open(ctx, opener, image(ctx, opener), chapterOpenerPlacement(ch, st, opener), false); + ctx.beginColumns(); + b.append("
"); + if (plate) ctx.markPageTop(); + } b.append("
") .append("").append(fused != null ? "Quête" : "Chapitre").append(SPAN_CLOSE) .append(esc(ch.getName())).append(DIV_CLOSE); - chapterFields(ctx, ch, fused, st); + chapterFields(ctx, ch, fused, st, opener); for (SceneJpaEntity sc : st.scenesByChapter.get(ch.getId())) { - scene(ctx, sc, st); + scene(ctx, sc, st, SCENE_IN_CHAPTER); ctx.scenes++; } + // L'image destinee au bas de la derniere page — un repere a la fin du texte (il dit + // dans quelle colonne et a quelle hauteur le texte s'arrete), ou l'image ordinaire quand la + // premiere passe a montre que la place manque. + String fade = fadeBottomId(ctx, gallery(ch)); + if (fade != null && ctx.unfaded.contains(fade)) figure(ctx, image(ctx, fade), imageEncoder.caption(fade)); + else if (fade != null) fadeMark(ctx); b.append(DIV_CLOSE); } @@ -648,17 +1233,17 @@ public class PdfExportService { * champs sont integres au meme bloc — conditions de deblocage comprises — en dedupliquant * les textes identiques (les quetes converties du legacy dupliquent le chapitre). */ - private void chapterFields(Ctx ctx, ChapterJpaEntity ch, QuestJpaEntity fused, Structure st) { - illustrations(ctx, ch.getIllustrationImageIds()); + private void chapterFields(Ctx ctx, ChapterJpaEntity ch, QuestJpaEntity fused, Structure st, String openerId) { + illustrations(ctx, without(plain(ctx, gallery(ch)), openerId)); if (fused == null) { - ctx.gmBlock(LABEL_DESCRIPTION, ch.getDescription()); + ctx.opening(ch.getDescription()); block(ctx.body, LABEL_OBJECTIFS_JOUEURS, ch.getPlayerObjectives()); ctx.gmBlock(LABEL_ENJEUX_NARRATIFS, ch.getNarrativeStakes()); ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, ch.getGmNotes()); return; } - illustrations(ctx, fused.getIllustrationImageIds()); - ctx.gmBlock(LABEL_DESCRIPTION, mergeField(ch.getDescription(), fused.getDescription())); + illustrations(ctx, without(fused.getIllustrationImageIds(), openerId)); + ctx.opening(mergeField(ch.getDescription(), fused.getDescription())); ctx.gmBlock(LABEL_CONDITIONS, renderPrerequisites(fused.getPrerequisites(), st.questNames)); if (ctx.gm) blockHtml(ctx.body, LABEL_NOEUDS, questNodeItems(fused, st)); block(ctx.body, LABEL_OBJECTIFS_JOUEURS, mergeField(ch.getPlayerObjectives(), fused.getPlayerObjectives())); @@ -685,14 +1270,14 @@ public class PdfExportService { ctx.addToc(0, "Scènes", ANCHOR_PART_NARRATIVE); ctx.beginColumns(); - arcFields(ctx, arc); - chapterFields(ctx, ch, st.questByContainerChapter.get(ch.getId()), st); + arcFields(ctx, arc, null); + chapterFields(ctx, ch, st.questByContainerChapter.get(ch.getId()), st, null); StringBuilder scBms = new StringBuilder(); for (SceneJpaEntity sc : st.scenesByChapter.get(ch.getId())) { ctx.addToc(1, sc.getName(), "scene-" + sc.getId()); scBms.append(bookmark(sc.getName(), "scene-" + sc.getId(), "")); - scene(ctx, sc, st); + scene(ctx, sc, st, List.of()); ctx.scenes++; } ctx.bookmarks.append(bookmark("Scènes", ANCHOR_PART_NARRATIVE, scBms.toString())); @@ -704,15 +1289,40 @@ public class PdfExportService { * lire, les illustrations et les cartes restent — resume, secrets, consequences, sorties * et combats sont reserves au MJ. */ - private void scene(Ctx ctx, SceneJpaEntity sc, Structure st) { + private void scene(Ctx ctx, SceneJpaEntity sc, Structure st, List wrappers) { StringBuilder b = ctx.body; - b.append("
") + Gallery gallery = gallery(sc); + // Parchemin : une image que l'auteur a placee en ouverture de la scene (bandeau, pleine page, + // fondue en haut) sort du flux en colonnes, donc des blocs qui entourent la scene. + String opener = ctx.parchment ? explicitOpenerId(ctx, gallery) : null; + if (opener != null) { + boolean top = ctx.atPageTop(); + closeWrappers(ctx, wrappers); + if (top) ctx.markPageTop(); + boolean plate = open(ctx, opener, image(ctx, opener), gallery.placement(opener), false); + ctx.beginColumns(); + openWrappers(ctx, wrappers); + if (plate) ctx.markPageTop(); + } + // La premiere illustration laissee en automatique, si le texte suffit a l'habiller, flotte en tete de scene. + String leadId = ctx.parchment ? firstAutomatic(gallery) : null; + PdfFigures.Lead lead = sceneLead(ctx, sc, leadId); + b.append("
"); + lead.open(); + // L'ancre est sur le titre, pas sur le bloc : quand le bloc commence au bas d'une colonne et + // que son titre passe a la page suivante, c'est la page du titre qu'un renvoi doit annoncer. + b.append("
") .append("Scène") .append(esc(sc.getName())).append(DIV_CLOSE); sceneMeta(b, sc); + lead.figure(); ctx.gmBlock("Résumé", sc.getDescription()); + if (ctx.gm) lead.after(sc.getDescription()); ctx.gmBlock("Utilité", sc.getPurpose()); + if (ctx.gm) lead.after(sc.getPurpose()); block(b, "Ambiance", sc.getAtmosphere(), "ambiance"); + lead.after(sc.getAtmosphere()); + lead.close(); box(b, "readaloud", "À lire aux joueurs", sc.getPlayerNarration()); ctx.gmBox(CSS_SECRET, "Notes secrètes MJ", sc.getGmSecretNotes()); ctx.gmBlock("Choix et conséquences", sc.getChoicesConsequences()); @@ -720,14 +1330,75 @@ public class PdfExportService { // Combat : difficulte + ennemis de la rencontre (fiches du bestiaire en renvoi // « p. N » + texte libre) dans le meme encadre rouge. combatBox(ctx, "Combat", sc.getCombatDifficulty(), sc.getEnemyIds(), sc.getEnemies(), sc.getTactics(), st); - illustrations(ctx, sc.getIllustrationImageIds()); + illustrations(ctx, without(without(plain(ctx, gallery), opener), lead.used() ? leadId : null)); if (ctx.maps != null) { mapLinks(ctx, sc); } else { sceneBattlemaps(ctx, sc); } rooms(ctx, sc, st); + // Image destinee au bas de la page ou la scene se termine : repere de fin de texte, ou image + // ordinaire quand la premiere passe a montre que la place manque. + String fade = fadeBottomId(ctx, gallery); + boolean faded = fade != null && !ctx.unfaded.contains(fade); + if (fade != null && !faded) figure(ctx, image(ctx, fade), imageEncoder.caption(fade)); + else if (faded) fadeMark(ctx); b.append(DIV_CLOSE); + if (faded) { + // L'emplacement est hors colonnes ; la suite du chapitre reprend sur une nouvelle page. + closeWrappers(ctx, wrappers); + fadeBottom(ctx, fade); + openWrappers(ctx, wrappers); + ctx.markPageTop(); + } + } + + /** Blocs qui entourent une scene dans la narration (arc et chapitre), une quete libre, ou aucun (mode plat). */ + private static final List SCENE_IN_CHAPTER = List.of("arc", "chapter"); + private static final List SCENE_IN_QUEST = List.of("chapter"); + + private static void closeWrappers(Ctx ctx, List wrappers) { + for (int i = 0; i < wrappers.size(); i++) ctx.body.append(DIV_CLOSE); + } + + private static void openWrappers(Ctx ctx, List wrappers) { + for (String cssClass : wrappers) ctx.body.append("
"); + } + + /** Premiere image que l'auteur a explicitement placee en ouverture (bandeau, pleine page, fondue en haut), ou null. */ + private String explicitOpenerId(Ctx ctx, Gallery gallery) { + for (String id : gallery.ids()) { + switch (gallery.placement(id)) { + case BANNER, FULL_PAGE, FADE_TOP -> { + if (image(ctx, id) != null) return id; + } + default -> { /* automatique, dans le texte ou en bas de page : pas une ouverture */ } + } + } + return null; + } + + private static String firstAutomatic(Gallery gallery) { + for (String id : gallery.ids()) { + if (gallery.placement(id) == ImagePlacement.AUTO) return id; + } + return null; + } + + private static Gallery gallery(SceneJpaEntity scene) { + return gallery(scene.getIllustrationImageIds(), scene.getIllustrationPlacements()); + } + + /** Image habillee en tete de scene (theme Parchemin), ou {@link PdfFigures.Lead#NONE}. */ + private PdfFigures.Lead sceneLead(Ctx ctx, SceneJpaEntity sc, String id) { + if (!ctx.parchment || id == null) return PdfFigures.Lead.NONE; + List texts = new ArrayList<>(); + if (ctx.gm) { + texts.add(sc.getDescription()); + texts.add(sc.getPurpose()); + } + texts.add(sc.getAtmosphere()); + return PdfFigures.lead(ctx.body, image(ctx, id), imageEncoder.caption(id), ctx.measure(), texts); } /** @@ -900,9 +1571,13 @@ public class PdfExportService { ctx.bookmarks.append(bookmark("Quêtes", "part-quests", qBms.toString())); ctx.beginColumns(); + ctx.markPageTop(); for (QuestJpaEntity q : quests) { ctx.addToc(1, q.getName(), "quest-" + q.getId()); standaloneQuest(ctx, q, st); + // Image « fondue en bas de page » : son emplacement suit la quete, hors colonnes. + String fade = fadeBottomId(ctx, gallery(q)); + if (fade != null && !ctx.unfaded.contains(fade)) fadeBottom(ctx, fade); } ctx.endColumns(); } @@ -910,10 +1585,22 @@ public class PdfExportService { /** Une quete libre/transversale : ses champs + les scenes de ses conteneurs (arc SYSTEM masque). */ private void standaloneQuest(Ctx ctx, QuestJpaEntity q, Structure st) { StringBuilder b = ctx.body; + // Parchemin : une quete illustree s'ouvre, comme un chapitre, sur un bandeau pleine largeur + // (ou sur la planche ou le bandeau fondu que l'auteur a choisi). + Gallery gallery = gallery(q); + String opener = ctx.parchment ? openerId(ctx, gallery) : null; + PdfImage openerImage = image(ctx, opener); + if (openerImage != null) { + boolean plate = open(ctx, opener, openerImage, gallery.placement(opener), false); + ctx.beginColumns(); + if (plate) ctx.markPageTop(); + } else { + opener = null; + } b.append("
Quête").append(esc(q.getName())).append(DIV_CLOSE); - illustrations(ctx, q.getIllustrationImageIds()); - ctx.gmBlock(LABEL_DESCRIPTION, q.getDescription()); + illustrations(ctx, without(plain(ctx, gallery), opener)); + ctx.opening(q.getDescription()); ctx.gmBlock(LABEL_CONDITIONS, renderPrerequisites(q.getPrerequisites(), st.questNames)); if (ctx.gm) blockHtml(ctx.body, LABEL_NOEUDS, questNodeItems(q, st)); block(b, LABEL_OBJECTIFS_JOUEURS, q.getPlayerObjectives()); @@ -922,6 +1609,11 @@ public class PdfExportService { // Scenes de ses conteneurs (arc SYSTEM, masque de la narration) : c'est ICI // que vit le contenu jouable d'une quete libre. questContainerScenes(ctx, q, st); + // Image destinee au bas de la derniere page : repere de fin de texte, ou image ordinaire + // quand la premiere passe a montre que la place manque. + String fade = fadeBottomId(ctx, gallery); + if (fade != null && ctx.unfaded.contains(fade)) figure(ctx, image(ctx, fade), imageEncoder.caption(fade)); + else if (fade != null) fadeMark(ctx); b.append(DIV_CLOSE); } @@ -930,7 +1622,7 @@ public class PdfExportService { Set containers = st.containerChapterIds(q); for (QuestNodeRef n : q.getNodes()) { for (SceneJpaEntity sc : containerScenes(n, containers, st)) { - scene(ctx, sc, st); + scene(ctx, sc, st, SCENE_IN_QUEST); ctx.scenes++; } } @@ -1083,10 +1775,18 @@ public class PdfExportService { StringBuilder b = ctx.body; // Mise en page en TABLE (portrait | contenu) : openhtmltopdf gere mal le float // + overflow (le texte se superposait au portrait). - b.append("
NomDossier
"); - PdfImage portrait = imageEncoder.image(r.portraitId(), PdfImageEncoder.PORTRAIT_MAX); - if (portrait != null) { + PdfImage portrait = ctx.parchment + ? imageEncoder.image(r.portraitId(), ctx.imageSpec(PdfImageEncoder.PORTRAIT_MAX)) + : imageEncoder.image(r.portraitId(), PdfImageEncoder.PORTRAIT_MAX); + if (portrait != null && ctx.parchment) { + // Portrait dans un cadre dessine (filets et coins), jamais une image de cadre. + b.append(""); + } else if (portrait != null) { double widthCm = Math.min(3.0, PORTRAIT_MAX_HEIGHT_CM * portrait.w() / portrait.h()); b.append(""); @@ -1103,7 +1803,10 @@ public class PdfExportService { ctx.gmBlock("Ce qu'il sait", r.story().knowledge()); } + // Largeur utile de la fiche : marges de la carte, colonne du portrait. + ctx.cardWidthCm = ctx.contentWidthCm() - 0.8 - (portrait != null ? PORTRAIT_FRAMED_WIDTH_CM + 0.5 : 0); renderFields(ctx, template, r.values(), r.keyValueValues(), r.imageValues(), null); + ctx.cardWidthCm = 0; if (enemy && r.foundryStats() != null) { Map clean = cleanStats(r.foundryStats()); @@ -1292,7 +1995,9 @@ public class PdfExportService { .append(esc(p.getTitle())).append(DIV_CLOSE); List tpl = p.getTemplateId() != null ? fieldsOf(templates.get(p.getTemplateId())) : null; + ctx.cardWidthCm = ctx.contentWidthCm() - 0.8; renderFields(ctx, tpl, p.getValues(), p.getKeyValueValues(), p.getImageValues(), p.getTableValues()); + ctx.cardWidthCm = 0; b.append(""); } } @@ -1352,12 +2057,69 @@ public class PdfExportService { } return; } - for (TemplateField f : template) { + for (int i = 0; i < template.size(); i++) { + TemplateField f = template.get(i); if (f == null || f.getName() == null || f.getType() == null) continue; + if (ctx.parchment && f.getType() == FieldType.IMAGE) { + // Une image seule est habillee par le champ de texte qui la suit, s'il est assez long. + TemplateField next = i + 1 < template.size() ? template.get(i + 1) : null; + boolean text = next != null && next.getName() != null && next.getType() == FieldType.TEXT; + String nextValue = text && values != null ? values.get(next.getName()) : null; + List ids = imageValues != null ? imageValues.get(f.getName()) : null; + if (fieldFigures(ctx, f.getName(), ids, text ? next.getName() : null, nextValue)) i++; + continue; + } renderField(ctx, f, values, keyValueValues, imageValues, tableValues); } } + /** + * Champ IMAGE d'une fiche ou d'une page de lore (theme Parchemin). Le nom du champ sert de + * legende (« Blason », « Carte de la region »), faute de legende propre a l'image. Une image + * seule est habillee par le texte du champ suivant quand il suffit a la couvrir ; plusieurs + * images forment une rangee. + * + * @return vrai si le champ de texte suivant a ete rendu ici, avec l'image + */ + private boolean fieldFigures(Ctx ctx, String name, List ids, String nextLabel, String nextText) { + List images = new ArrayList<>(); + String lastId = null; + if (ids != null) { + for (String id : ids) { + PdfImage img = image(ctx, id); + if (img == null) continue; + images.add(img); + lastId = id; + } + } + if (images.isEmpty()) return false; + StringBuilder b = ctx.body; + PdfExportOptions.PageFormat f = ctx.opt.format(); + double width = ctx.cardWidthCm > 0 ? ctx.cardWidthCm : ctx.contentWidthCm(); + double maxHeight = ILLUSTRATION_MAX_HEIGHT_CM * f.widthCm / PdfExportOptions.PageFormat.A4.widthCm; + if (images.size() > 1) { + b.append(PdfFigures.gallery(images, width, maxHeight * 0.45, name)); + return false; + } + PdfImage img = images.get(0); + String own = imageEncoder.caption(lastId); + String caption = notBlank(own) ? own : name; + PdfFigures.Measure measure = new PdfFigures.Measure(width, ctx.textHeightCm(), ctx.bodyPt(), false); + PdfFigures.Lead lead = PdfFigures.lead(b, img, caption, measure, + nextText == null ? List.of() : List.of(nextText)); + if (lead.used()) { + lead.open(); + lead.figure(); + block(b, nextLabel, nextText); + lead.close(); + return true; + } + b.append("
") + .append(PdfFigures.figure(img, PdfFigures.fit(img, width * 0.7, maxHeight * 0.7), caption, "center")) + .append(DIV_CLOSE); + return false; + } + private void renderField(Ctx ctx, TemplateField f, Map values, Map> keyValueValues, Map> imageValues, @@ -1449,16 +2211,35 @@ public class PdfExportService { private void illustrations(Ctx ctx, List imageIds) { if (imageIds == null) return; for (String id : imageIds) { + if (ctx.parchment) { + figure(ctx, image(ctx, id), imageEncoder.caption(id)); + continue; + } PdfImage img = imageEncoder.image(id, PdfImageEncoder.ILLUSTRATION_MAX); if (img != null) illustration(ctx, img, null); } } + /** Theme Parchemin : image encadree, centree sur la colonne, hauteur bornee, legende sobre. */ + private static void figure(Ctx ctx, PdfImage img, String caption) { + if (img == null) return; + double maxHeight = ILLUSTRATION_MAX_HEIGHT_CM * ctx.opt.format().widthCm / PdfExportOptions.PageFormat.A4.widthCm; + // En colonnes, l'image est insecable : elle doit tenir sous un bandeau (legende comprise). + if (ctx.columns) maxHeight = Math.min(maxHeight, ctx.textHeightCm() * UNBREAKABLE_MAX_HEIGHT_RATIO - 0.5); + // Reserve le retrait des pieces imbriquees. + double width = PdfFigures.fit(img, ctx.contentWidthCm() - 0.4, maxHeight); + ctx.body.append("
").append(PdfFigures.figure(img, width, caption, "center")).append(DIV_CLOSE); + } + /** * Une illustration centree, avec legende optionnelle. La largeur est calculee pour que * la hauteur affichee reste bornee : une image tres verticale ne mange plus la page. */ private void illustration(Ctx ctx, PdfImage img, String caption) { + if (ctx.parchment) { + figure(ctx, img, caption); + return; + } StringBuilder b = ctx.body; // Hauteur bornee proportionnellement au format (A5 : environ 7,8 cm). double maxHeight = ILLUSTRATION_MAX_HEIGHT_CM * ctx.opt.format().widthCm / PdfExportOptions.PageFormat.A4.widthCm; @@ -1504,17 +2285,40 @@ public class PdfExportService { String margins = cm(f.marginTopCm) + " " + cm(f.marginSideCm) + " " + cm(f.marginBottomCm); // Echappement CSS (chaine entre quotes) PUIS XML : le CSS vit dans
").append(PdfFigures.figure(portrait, + PdfFigures.fit(portrait, PORTRAIT_FRAMED_WIDTH_CM, PORTRAIT_MAX_HEIGHT_CM + 0.4), null, "center")) + .append("