Compare commits
5 Commits
v0.13.0-be
...
v0.14.0-be
| Author | SHA1 | Date | |
|---|---|---|---|
| 914767f793 | |||
| af3a6d443c | |||
| 6e75326779 | |||
| d0b53bb15a | |||
| bbcb5ee34e |
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
||||
app = FastAPI(
|
||||
title="LoreMind Brain",
|
||||
description="Backend IA pour la génération de contenu narratif.",
|
||||
version="0.13.0-beta",
|
||||
version="0.14.0-beta",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>0.13.0-beta</version>
|
||||
<version>0.14.0-beta</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.context.request.async.AsyncRequestNotUsableException;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
@@ -71,6 +72,21 @@ public class GlobalExceptionHandler {
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Statut HTTP explicitement choisi par un controller via {@link ResponseStatusException}
|
||||
* (ex: {@code NotebookController} -> 404 si notebook introuvable, 502 si Brain injoignable).
|
||||
* <p>
|
||||
* SANS ce handler, le fallback {@code @ExceptionHandler(Throwable.class)} ci-dessous
|
||||
* interceptait ces exceptions et renvoyait 500 — ecrasant le statut voulu (le
|
||||
* resolver natif de Spring est court-circuite des qu'un advice gere Throwable).
|
||||
*/
|
||||
@ExceptionHandler(ResponseStatusException.class)
|
||||
public ResponseEntity<Map<String, String>> handleResponseStatus(ResponseStatusException ex) {
|
||||
String reason = ex.getReason();
|
||||
return ResponseEntity.status(ex.getStatusCode())
|
||||
.body(Map.of("error", reason != null ? reason : ex.getStatusCode().toString()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Client HTTP parti pendant une reponse asynchrone (SSE) : le navigateur a ferme
|
||||
* la connexion (onglet ferme, proxy coupe...), la reponse n'est plus utilisable.
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||
@@ -48,6 +49,8 @@ public class CampaignStructuralContextBuilderTest {
|
||||
private CharacterRepository characterRepository;
|
||||
@Mock
|
||||
private NpcRepository npcRepository;
|
||||
@Mock
|
||||
private EnemyRepository enemyRepository;
|
||||
|
||||
@InjectMocks
|
||||
private CampaignStructuralContextBuilder builder;
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring, sans réseau) de
|
||||
* {@link BrainAiChatClient}.
|
||||
*
|
||||
* Principe : WebClient.Builder préconfiguré avec une ExchangeFunction mock
|
||||
* renvoyant un flux SSE canned. Le payloadBuilder est mocké ; le sseParser est
|
||||
* une instance réelle (simple parseur sans dépendance).
|
||||
*/
|
||||
class BrainAiChatClientTest {
|
||||
|
||||
/** ChatRequest minimal valide : messages vide suffit (payloadBuilder mocké). */
|
||||
private ChatRequest minimalRequest() {
|
||||
return ChatRequest.builder().messages(List.of()).build();
|
||||
}
|
||||
|
||||
/** Construit un client dont le WebClient renvoie le corps SSE fourni. */
|
||||
private BrainAiChatClient clientWithSse(String sseBody) {
|
||||
ExchangeFunction ef = req -> Mono.just(
|
||||
ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sseBody)
|
||||
.build());
|
||||
return buildClient(ef);
|
||||
}
|
||||
|
||||
/** Construit un client dont le WebClient émet une erreur transport. */
|
||||
private BrainAiChatClient clientErroring() {
|
||||
ExchangeFunction ef = req -> Mono.error(new RuntimeException("boom"));
|
||||
return buildClient(ef);
|
||||
}
|
||||
|
||||
private BrainAiChatClient buildClient(ExchangeFunction ef) {
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
BrainChatPayloadBuilder payloadBuilder = mock(BrainChatPayloadBuilder.class);
|
||||
when(payloadBuilder.build(org.mockito.ArgumentMatchers.any())).thenReturn(Map.of());
|
||||
return new BrainAiChatClient(builder, "http://brain", payloadBuilder, new BrainSseParser());
|
||||
}
|
||||
|
||||
// --- Collecteurs partagés pour les callbacks ---
|
||||
private final List<ChatUsage> usages = new ArrayList<>();
|
||||
private final List<String> tokens = new ArrayList<>();
|
||||
private final AtomicBoolean completed = new AtomicBoolean(false);
|
||||
private final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
|
||||
private final Consumer<ChatUsage> onUsage = usages::add;
|
||||
private final Consumer<String> onToken = tokens::add;
|
||||
private final Runnable onComplete = () -> completed.set(true);
|
||||
private final Consumer<Throwable> onError = error::set;
|
||||
|
||||
@Test
|
||||
void flux_complet_parse_usage_et_token_puis_complete() {
|
||||
String sse =
|
||||
"event:usage\ndata:{\"system\":1,\"history\":2,\"current\":3,\"max\":100}\n\n" +
|
||||
"data:{\"token\":\"Bonjour\"}\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
BrainAiChatClient client = clientWithSse(sse);
|
||||
|
||||
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||
|
||||
// usage parsé et propagé
|
||||
assertThat(usages).hasSize(1);
|
||||
assertThat(usages.get(0)).isEqualTo(new ChatUsage(1, 2, 3, 100));
|
||||
// token propagé
|
||||
assertThat(tokens).containsExactly("Bonjour");
|
||||
// event done ignoré (pas de token/usage supplémentaire)
|
||||
// complétion appelée, pas d'erreur
|
||||
assertThat(completed).isTrue();
|
||||
assertThat(error.get()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void plusieurs_tokens_propages_dans_l_ordre() {
|
||||
String sse =
|
||||
"data:{\"token\":\"Bon\"}\n\n" +
|
||||
"data:{\"token\":\"jour\"}\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
BrainAiChatClient client = clientWithSse(sse);
|
||||
|
||||
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||
|
||||
assertThat(tokens).containsExactly("Bon", "jour");
|
||||
assertThat(completed).isTrue();
|
||||
assertThat(error.get()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_error_declenche_onError_avec_AiProviderException() {
|
||||
String sse =
|
||||
"event:error\ndata:boom\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
BrainAiChatClient client = clientWithSse(sse);
|
||||
|
||||
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||
|
||||
assertThat(error.get())
|
||||
.isInstanceOf(AiProviderException.class)
|
||||
.hasMessageContaining("boom");
|
||||
// Aucun token émis sur ce flux.
|
||||
assertThat(tokens).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void token_vide_n_est_pas_propage() {
|
||||
String sse =
|
||||
"data:{\"token\":\"\"}\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
BrainAiChatClient client = clientWithSse(sse);
|
||||
|
||||
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||
|
||||
assertThat(tokens).isEmpty();
|
||||
assertThat(completed).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void usage_illisible_n_est_pas_propage() {
|
||||
// data usage sans champs numériques -> parser renvoie ChatUsage(0,0,0,0),
|
||||
// donc propagé ; ici on teste un usage avec data non-null mais vide d'entiers.
|
||||
String sse =
|
||||
"event:usage\ndata:{\"system\":5}\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
BrainAiChatClient client = clientWithSse(sse);
|
||||
|
||||
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||
|
||||
// Les champs absents tombent à 0 (parser tolérant).
|
||||
assertThat(usages).containsExactly(new ChatUsage(5, 0, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void erreur_transport_declenche_onError_avec_AiProviderException() {
|
||||
BrainAiChatClient client = clientErroring();
|
||||
|
||||
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||
|
||||
assertThat(error.get())
|
||||
.isInstanceOf(AiProviderException.class)
|
||||
.hasMessageContaining("streaming chat");
|
||||
// onComplete NON appelé puisqu'une exception a interrompu blockLast().
|
||||
assertThat(completed).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void flux_vide_appelle_seulement_onComplete() {
|
||||
// Flux SSE vide : aucun évènement, blockLast renvoie null, onComplete appelé.
|
||||
BrainAiChatClient client = clientWithSse("");
|
||||
|
||||
client.streamChat(minimalRequest(), onUsage, onToken, onComplete, onError);
|
||||
|
||||
assertThat(tokens).isEmpty();
|
||||
assertThat(usages).isEmpty();
|
||||
assertThat(completed).isTrue();
|
||||
assertThat(error.get()).isNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.generationcontext.GenerationContext;
|
||||
import com.loremind.domain.generationcontext.GenerationResult;
|
||||
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests unitaires PURS (JUnit 5 + Mockito, sans Spring, sans reseau) pour
|
||||
* BrainAiClient. Le RestTemplate est mocke ; on couvre toutes les branches
|
||||
* de callBrain ainsi que la traduction domaine -> wire -> domaine.
|
||||
*/
|
||||
class BrainAiClientTest {
|
||||
|
||||
private static final String BASE_URL = "http://brain";
|
||||
private static final String EXPECTED_URL = "http://brain/generate-page";
|
||||
|
||||
private GenerationContext sampleContext() {
|
||||
return new GenerationContext(
|
||||
"Aetheria",
|
||||
"Un monde de cendres",
|
||||
"PNJ",
|
||||
"Fiche personnage",
|
||||
List.of("histoire", "motto"),
|
||||
"Garde rouge"
|
||||
);
|
||||
}
|
||||
|
||||
private BrainGeneratePageResponse responseWith(Map<String, String> values) {
|
||||
BrainGeneratePageResponse r = new BrainGeneratePageResponse();
|
||||
r.setValues(values);
|
||||
return r;
|
||||
}
|
||||
|
||||
// --- Branche succes ------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void generatePage_succes_traduitReponseWireEnResultatDomaine() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||
|
||||
BrainGeneratePageResponse wire = responseWith(Map.of(
|
||||
"histoire", "Nee sous une etoile rouge",
|
||||
"motto", "Jamais genou en terre"
|
||||
));
|
||||
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||
.thenReturn(wire);
|
||||
|
||||
GenerationResult result = client.generatePage(sampleContext());
|
||||
|
||||
assertEquals(2, result.values().size());
|
||||
assertEquals("Jamais genou en terre", result.values().get("motto"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePage_appelleBonneUrlEtContentTypeJson_avecCorpsTraduit() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||
.thenReturn(responseWith(Map.of("histoire", "v")));
|
||||
|
||||
client.generatePage(sampleContext());
|
||||
|
||||
// Capture de l'URL et de l'HttpEntity envoyes au RestTemplate
|
||||
ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<HttpEntity<BrainGeneratePageRequest>> entityCaptor =
|
||||
ArgumentCaptor.forClass(HttpEntity.class);
|
||||
|
||||
org.mockito.Mockito.verify(rt).postForObject(
|
||||
urlCaptor.capture(),
|
||||
entityCaptor.capture(),
|
||||
eq(BrainGeneratePageResponse.class));
|
||||
|
||||
assertEquals(EXPECTED_URL, urlCaptor.getValue());
|
||||
|
||||
HttpEntity<BrainGeneratePageRequest> entity = entityCaptor.getValue();
|
||||
HttpHeaders headers = entity.getHeaders();
|
||||
assertEquals(MediaType.APPLICATION_JSON, headers.getContentType());
|
||||
|
||||
// Verifie la traduction domaine -> wire (exerce les getters du record)
|
||||
BrainGeneratePageRequest body = entity.getBody();
|
||||
assertEquals("Aetheria", body.loreName());
|
||||
assertEquals("Un monde de cendres", body.loreDescription());
|
||||
assertEquals("PNJ", body.folderName());
|
||||
assertEquals("Fiche personnage", body.templateName());
|
||||
assertEquals(List.of("histoire", "motto"), body.templateFields());
|
||||
assertEquals("Garde rouge", body.pageTitle());
|
||||
}
|
||||
|
||||
// --- Branche reponse null ------------------------------------------------
|
||||
|
||||
@Test
|
||||
void generatePage_reponseNull_leveAiProviderException() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||
.thenReturn(null);
|
||||
|
||||
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||
() -> client.generatePage(sampleContext()));
|
||||
assertTrue(ex.getMessage().contains("reponse vide")
|
||||
|| ex.getMessage().contains("réponse vide"));
|
||||
}
|
||||
|
||||
// --- Branche values null -------------------------------------------------
|
||||
|
||||
@Test
|
||||
void generatePage_valuesNull_leveAiProviderException() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||
|
||||
// Reponse non null mais avec values == null
|
||||
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||
.thenReturn(responseWith(null));
|
||||
|
||||
assertThrows(AiProviderException.class,
|
||||
() -> client.generatePage(sampleContext()));
|
||||
}
|
||||
|
||||
// --- Branche ResourceAccessException (Brain injoignable) -----------------
|
||||
|
||||
@Test
|
||||
void generatePage_brainInjoignable_leveAiProviderException() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||
|
||||
ResourceAccessException cause = new ResourceAccessException("down");
|
||||
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||
.thenThrow(cause);
|
||||
|
||||
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||
() -> client.generatePage(sampleContext()));
|
||||
assertTrue(ex.getMessage().contains("injoignable"));
|
||||
assertSame(cause, ex.getCause());
|
||||
}
|
||||
|
||||
// --- Branche RestClientResponseException (HTTP 4xx/5xx) ------------------
|
||||
|
||||
@Test
|
||||
void generatePage_erreurHttp_leveAiProviderExceptionAvecCode() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||
|
||||
HttpServerErrorException cause = HttpServerErrorException.create(
|
||||
HttpStatus.BAD_GATEWAY, "Bad Gateway",
|
||||
new HttpHeaders(), new byte[0], null);
|
||||
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||
.thenThrow(cause);
|
||||
|
||||
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||
() -> client.generatePage(sampleContext()));
|
||||
assertTrue(ex.getMessage().contains("502"));
|
||||
assertSame(cause, ex.getCause());
|
||||
}
|
||||
|
||||
// --- Branche AiProviderException deja traduite : re-levee telle quelle ---
|
||||
|
||||
@Test
|
||||
void generatePage_aiProviderExceptionDejaTraduite_estRelancee() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||
|
||||
AiProviderException original = new AiProviderException("deja traduite");
|
||||
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||
.thenThrow(original);
|
||||
|
||||
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||
() -> client.generatePage(sampleContext()));
|
||||
// Pas de re-enveloppement : c'est exactement la meme instance
|
||||
assertSame(original, ex);
|
||||
}
|
||||
|
||||
// --- Branche Exception generique (filet de securite) ---------------------
|
||||
|
||||
@Test
|
||||
void generatePage_exceptionGenerique_leveAiProviderException() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainAiClient client = new BrainAiClient(rt, BASE_URL);
|
||||
|
||||
RuntimeException cause = new IllegalStateException("JSON invalide");
|
||||
when(rt.postForObject(anyString(), any(), eq(BrainGeneratePageResponse.class)))
|
||||
.thenThrow(cause);
|
||||
|
||||
AiProviderException ex = assertThrows(AiProviderException.class,
|
||||
() -> client.generatePage(sampleContext()));
|
||||
assertTrue(ex.getMessage().contains("inattendue"));
|
||||
assertSame(cause, ex.getCause());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Tests unitaires PURS (JUnit 5, sans Spring ni réseau) pour {@link BrainCampaignAdaptClient}.
|
||||
* Le WebClient.Builder injecté embarque une ExchangeFunction qui renvoie un corps SSE canned.
|
||||
*/
|
||||
class BrainCampaignAdaptClientTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private BrainCampaignAdaptClient clientReturning(String sseBody) {
|
||||
ExchangeFunction ef = req -> Mono.just(
|
||||
ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sseBody)
|
||||
.build());
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainCampaignAdaptClient(builder, MAPPER, "http://brain", 30);
|
||||
}
|
||||
|
||||
private BrainCampaignAdaptClient clientFailingWith(Throwable boom) {
|
||||
ExchangeFunction ef = req -> Mono.error(boom);
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainCampaignAdaptClient(builder, MAPPER, "http://brain", 30);
|
||||
}
|
||||
|
||||
/** Collecteur de callbacks + déclenchement de adviseStreaming. */
|
||||
private static final class Collector {
|
||||
final StringBuilder tokens = new StringBuilder();
|
||||
final AtomicBoolean complete = new AtomicBoolean(false);
|
||||
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
|
||||
void invoke(BrainCampaignAdaptClient client, String filename, String brief, String messagesJson) {
|
||||
client.adviseStreaming(
|
||||
new byte[]{1, 2, 3},
|
||||
filename,
|
||||
brief,
|
||||
messagesJson,
|
||||
tokens::append,
|
||||
() -> complete.set(true),
|
||||
error::set);
|
||||
}
|
||||
|
||||
void invoke(BrainCampaignAdaptClient client) {
|
||||
invoke(client, "camp.pdf", "brief", "[]");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void streame_tokens_puis_done() {
|
||||
String sse =
|
||||
"event:token\ndata:{\"token\":\"Conseil\"}\n\n" +
|
||||
"event:token\ndata:{\"token\":\" final\"}\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals("Conseil final", c.tokens.toString());
|
||||
assertTrue(c.complete.get(), "onComplete appelé via event done");
|
||||
assertNull(c.error.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void token_vide_ou_absent_ignore() {
|
||||
// token "" -> non émis ; champ token absent -> readField renvoie data (non vide)
|
||||
// donc émis tel quel : on vérifie ce comportement réel.
|
||||
String sse =
|
||||
"event:token\ndata:{\"token\":\"\"}\n\n" +
|
||||
"event:token\ndata:{\"token\":\"OK\"}\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals("OK", c.tokens.toString());
|
||||
assertTrue(c.complete.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_error_appelle_onError_avec_runtimeexception() {
|
||||
String sse =
|
||||
"event:token\ndata:{\"token\":\"avant\"}\n\n" +
|
||||
"event:error\ndata:{\"message\":\"PDF illisible\"}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertInstanceOf(RuntimeException.class, c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("PDF illisible"));
|
||||
assertFalse(c.complete.get(), "onComplete non appelé après error terminal");
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_error_data_non_json_relaie_data_brut() {
|
||||
// readField : data non parsable -> catch -> renvoie data brut.
|
||||
String sse = "event:error\ndata:panne-brute\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("panne-brute"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void flux_clos_sans_done_appelle_onComplete() {
|
||||
// Pas de done/error -> terminated false -> onComplete de secours.
|
||||
String sse = "event:token\ndata:{\"token\":\"x\"}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals("x", c.tokens.toString());
|
||||
assertTrue(c.complete.get());
|
||||
assertNull(c.error.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void erreur_transport_traduite_en_runtimeexception() {
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientFailingWith(new RuntimeException("boom")));
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertInstanceOf(RuntimeException.class, c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("adaptation"));
|
||||
assertFalse(c.complete.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void filename_null_et_brief_null_et_messages_null_acceptes() {
|
||||
// Couvre les branches : filename blank -> "campaign.pdf", brief null -> "",
|
||||
// messagesJson null/blank -> "[]".
|
||||
String sse = "event:done\ndata:{}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse), null, null, null);
|
||||
|
||||
assertTrue(c.complete.get());
|
||||
assertNull(c.error.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void messages_blank_remplace_par_tableau_vide() {
|
||||
String sse = "event:done\ndata:{}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse), " ", " ", " ");
|
||||
|
||||
assertTrue(c.complete.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignImportException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Tests unitaires PURS (JUnit 5, sans Spring ni réseau) pour {@link BrainCampaignImportClient}.
|
||||
* <p>
|
||||
* NB : contrairement à la consigne initiale, ce client est entièrement WebClient + SSE
|
||||
* (POST /import/campaign/stream) — il n'y a PAS de RestTemplate ni d'appel one-shot.
|
||||
* On injecte donc un WebClient.Builder dont l'ExchangeFunction renvoie un corps SSE
|
||||
* canned (ou échoue), ce qui couvre {@code handleEvent} et tous les helpers de parsing.
|
||||
*/
|
||||
class BrainCampaignImportClientTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** Construit un client dont le WebClient renvoie le corps SSE fourni. */
|
||||
private BrainCampaignImportClient clientReturning(String sseBody) {
|
||||
ExchangeFunction ef = req -> Mono.just(
|
||||
ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sseBody)
|
||||
.build());
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainCampaignImportClient(builder, MAPPER, "http://brain", 30);
|
||||
}
|
||||
|
||||
/** Construit un client dont le transport échoue immédiatement (Mono.error). */
|
||||
private BrainCampaignImportClient clientFailingWith(Throwable boom) {
|
||||
ExchangeFunction ef = req -> Mono.error(boom);
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainCampaignImportClient(builder, MAPPER, "http://brain", 30);
|
||||
}
|
||||
|
||||
/** Collecteur mutable réunissant tous les callbacks de l'import streamé. */
|
||||
private static final class Collector {
|
||||
final List<CampaignImportProgress> progresses = new ArrayList<>();
|
||||
final AtomicInteger heartbeats = new AtomicInteger(0);
|
||||
final List<String> statuses = new ArrayList<>();
|
||||
final AtomicReference<CampaignImportProposal> done = new AtomicReference<>();
|
||||
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
|
||||
void invoke(BrainCampaignImportClient client) {
|
||||
invoke(client, "campaign.pdf");
|
||||
}
|
||||
|
||||
void invoke(BrainCampaignImportClient client, String filename) {
|
||||
client.importCampaignStreaming(
|
||||
new byte[]{1, 2, 3},
|
||||
filename,
|
||||
progresses::add,
|
||||
heartbeats::incrementAndGet,
|
||||
statuses::add,
|
||||
done::set,
|
||||
error::set);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- flux nominal : start -> progress -> done --------------------
|
||||
|
||||
@Test
|
||||
void streame_start_progress_done_construit_la_proposition() {
|
||||
// SSE déclenchant start (page/ocr counts), progress (compteurs), puis done (arbre complet).
|
||||
String sse =
|
||||
"event:start\ndata:{\"total\":5,\"page_count\":12,\"ocr_page_count\":3}\n\n" +
|
||||
"event:progress\ndata:{\"current\":2,\"total\":5,\"arc_count\":1,\"chapter_count\":2,\"scene_count\":4,\"npc_count\":6}\n\n" +
|
||||
"event:done\ndata:" + doneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
// start : current=0, total=5, pageCount=12, ocrPageCount=3, reste 0.
|
||||
assertEquals(2, c.progresses.size());
|
||||
CampaignImportProgress start = c.progresses.get(0);
|
||||
assertEquals(0, start.current());
|
||||
assertEquals(5, start.total());
|
||||
assertEquals(12, start.pageCount());
|
||||
assertEquals(3, start.ocrPageCount());
|
||||
|
||||
// progress : compteurs propagés + pageCount/ocr mémorisés depuis start.
|
||||
CampaignImportProgress prog = c.progresses.get(1);
|
||||
assertEquals(2, prog.current());
|
||||
assertEquals(5, prog.total());
|
||||
assertEquals(12, prog.pageCount());
|
||||
assertEquals(3, prog.ocrPageCount());
|
||||
assertEquals(1, prog.arcCount());
|
||||
assertEquals(2, prog.chapterCount());
|
||||
assertEquals(4, prog.sceneCount());
|
||||
assertEquals(6, prog.npcCount());
|
||||
|
||||
// done : arbre désérialisé (arcs/chapters/scenes/rooms + npcs).
|
||||
CampaignImportProposal proposal = c.done.get();
|
||||
assertNotNull(proposal);
|
||||
assertEquals(1, proposal.arcs().size());
|
||||
var arc = proposal.arcs().get(0);
|
||||
assertEquals("Acte I", arc.name());
|
||||
assertEquals("Mise en place", arc.description());
|
||||
assertEquals("LINEAR", arc.type());
|
||||
assertEquals(1, arc.chapters().size());
|
||||
var chapter = arc.chapters().get(0);
|
||||
assertEquals("Chapitre 1", chapter.name());
|
||||
assertEquals(1, chapter.scenes().size());
|
||||
var scene = chapter.scenes().get(0);
|
||||
assertEquals("L'auberge", scene.name());
|
||||
assertEquals("Lisez ceci", scene.playerNarration());
|
||||
assertEquals("Secret MJ", scene.gmNotes());
|
||||
assertEquals(1, scene.rooms().size());
|
||||
var room = scene.rooms().get(0);
|
||||
assertEquals("Cave", room.name());
|
||||
assertEquals("2 gobelins", room.enemies());
|
||||
assertEquals("50 po", room.loot());
|
||||
assertEquals(1, proposal.npcs().size());
|
||||
assertEquals("Thorin", proposal.npcs().get(0).name());
|
||||
assertEquals("Nain bougon", proposal.npcs().get(0).description());
|
||||
|
||||
assertNull(c.error.get(), "aucune erreur sur un flux terminé par done");
|
||||
}
|
||||
|
||||
private static String doneJson() {
|
||||
return "{"
|
||||
+ "\"arcs\":[{"
|
||||
+ " \"name\":\"Acte I\",\"description\":\"Mise en place\",\"type\":\"LINEAR\","
|
||||
+ " \"chapters\":[{"
|
||||
+ " \"name\":\"Chapitre 1\",\"description\":\"intro\","
|
||||
+ " \"scenes\":[{"
|
||||
+ " \"name\":\"L'auberge\",\"description\":\"tendue\","
|
||||
+ " \"player_narration\":\"Lisez ceci\",\"gm_notes\":\"Secret MJ\","
|
||||
+ " \"rooms\":[{\"name\":\"Cave\",\"description\":\"sombre\",\"enemies\":\"2 gobelins\",\"loot\":\"50 po\"}]"
|
||||
+ " }]"
|
||||
+ " }]"
|
||||
+ "}],"
|
||||
+ "\"npcs\":[{\"name\":\"Thorin\",\"description\":\"Nain bougon\"}]"
|
||||
+ "}";
|
||||
}
|
||||
|
||||
// ---------- events simples : heartbeat / status / chunk_failed / extracting
|
||||
|
||||
@Test
|
||||
void event_heartbeat_propage_le_keepalive() {
|
||||
String sse =
|
||||
"event:heartbeat\ndata:\n\n" +
|
||||
"event:heartbeat\ndata:\n\n" +
|
||||
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals(2, c.heartbeats.get());
|
||||
assertNotNull(c.done.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_status_relaie_le_message_lisible() {
|
||||
String sse =
|
||||
"event:status\ndata:{\"message\":\"Fournisseur saturé, nouvelle tentative\"}\n\n" +
|
||||
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals(1, c.statuses.size());
|
||||
assertEquals("Fournisseur saturé, nouvelle tentative", c.statuses.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_status_sans_champ_message_relaie_data_brut() {
|
||||
// readMessage : pas de champ "message" -> renvoie la data brute.
|
||||
String sse =
|
||||
"event:status\ndata:texte-brut\n\n" +
|
||||
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals("texte-brut", c.statuses.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_chunk_failed_compose_un_status_avec_compteurs_et_message() {
|
||||
String sse =
|
||||
"event:chunk_failed\ndata:{\"current\":3,\"total\":10,\"message\":\"timeout LLM\"}\n\n" +
|
||||
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals("Morceau 3/10 ignoré : timeout LLM", c.statuses.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_chunk_failed_sans_message_termine_par_un_point() {
|
||||
// Branche msg.isEmpty() -> suffixe "." au lieu de " : <msg>".
|
||||
String sse =
|
||||
"event:chunk_failed\ndata:{\"current\":1,\"total\":4}\n\n" +
|
||||
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals("Morceau 1/4 ignoré.", c.statuses.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_chunk_failed_avec_json_invalide_donne_zero_zero() {
|
||||
// data non-JSON -> readJson renvoie null -> current/total à 0, suffixe ".".
|
||||
String sse =
|
||||
"event:chunk_failed\ndata:pas-du-json\n\n" +
|
||||
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals("Morceau 0/0 ignoré.", c.statuses.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_extracting_emet_un_progress_neutre() {
|
||||
String sse =
|
||||
"event:extracting\ndata:\n\n" +
|
||||
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals(1, c.progresses.size());
|
||||
CampaignImportProgress p = c.progresses.get(0);
|
||||
assertEquals(0, p.current());
|
||||
assertEquals(0, p.total());
|
||||
assertEquals(0, p.pageCount());
|
||||
assertEquals(0, p.npcCount());
|
||||
}
|
||||
|
||||
private static String emptyDoneJson() {
|
||||
return "{\"arcs\":[],\"npcs\":[]}";
|
||||
}
|
||||
|
||||
// ---------- event error (terminal) -------------------------------------
|
||||
|
||||
@Test
|
||||
void event_error_appelle_onError_et_n_appelle_pas_onDone() {
|
||||
String sse =
|
||||
"event:start\ndata:{\"total\":2,\"page_count\":1,\"ocr_page_count\":0}\n\n" +
|
||||
"event:error\ndata:{\"message\":\"PDF illisible\"}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertInstanceOf(CampaignImportException.class, c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("PDF illisible"));
|
||||
assertNull(c.done.get(), "onDone non appelé après un error terminal");
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_error_sans_message_relaie_data_brut() {
|
||||
String sse = "event:error\ndata:erreur-brute\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("erreur-brute"));
|
||||
}
|
||||
|
||||
// ---------- branches de robustesse du parsing --------------------------
|
||||
|
||||
@Test
|
||||
void event_inconnu_avec_data_non_json_est_ignore() {
|
||||
// event non géré + data non-JSON -> readJson null -> return sans effet ;
|
||||
// flux clos sans done -> branche d'interruption (onError).
|
||||
String sse = "event:mystere\ndata:pas-du-json\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertTrue(c.progresses.isEmpty());
|
||||
assertTrue(c.statuses.isEmpty());
|
||||
assertNull(c.done.get());
|
||||
assertNotNull(c.error.get(), "flux interrompu sans done/error -> onError");
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_avec_champs_absents_utilise_les_valeurs_par_defaut() {
|
||||
// JSON valide mais sans page_count/ocr/total -> path().asInt() == 0.
|
||||
String sse =
|
||||
"event:start\ndata:{}\n\n" +
|
||||
"event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
CampaignImportProgress p = c.progresses.get(0);
|
||||
assertEquals(0, p.total());
|
||||
assertEquals(0, p.pageCount());
|
||||
assertEquals(0, p.ocrPageCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void done_avec_arbre_vide_donne_une_proposition_vide() {
|
||||
// Couvre toArcs/toNpcs sur des tableaux vides + text() sur champs absents.
|
||||
String sse = "event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertNotNull(c.done.get());
|
||||
assertTrue(c.done.get().arcs().isEmpty());
|
||||
assertTrue(c.done.get().npcs().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void done_avec_arc_sans_chapitres_et_npc_sans_description() {
|
||||
// toChapters sur noeud absent (path -> MissingNode, non-array) -> liste vide ;
|
||||
// text() sur "description" absent -> "".
|
||||
String sse = "event:done\ndata:{"
|
||||
+ "\"arcs\":[{\"name\":\"Solo\"}],"
|
||||
+ "\"npcs\":[{\"name\":\"Anon\"}]"
|
||||
+ "}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
var proposal = c.done.get();
|
||||
assertNotNull(proposal);
|
||||
var arc = proposal.arcs().get(0);
|
||||
assertEquals("Solo", arc.name());
|
||||
assertEquals("", arc.description());
|
||||
assertEquals("", arc.type());
|
||||
assertTrue(arc.chapters().isEmpty());
|
||||
assertEquals("Anon", proposal.npcs().get(0).name());
|
||||
assertEquals("", proposal.npcs().get(0).description());
|
||||
}
|
||||
|
||||
@Test
|
||||
void done_avec_champ_explicitement_null_donne_chaine_vide() {
|
||||
// text() : valeur JSON null -> "" (branche v.isNull()).
|
||||
String sse = "event:done\ndata:{"
|
||||
+ "\"arcs\":[{\"name\":null,\"description\":\"d\"}],"
|
||||
+ "\"npcs\":[]"
|
||||
+ "}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertEquals("", c.done.get().arcs().get(0).name());
|
||||
assertEquals("d", c.done.get().arcs().get(0).description());
|
||||
}
|
||||
|
||||
// ---------- fin de flux sans terminaison -------------------------------
|
||||
|
||||
@Test
|
||||
void flux_clos_sans_done_ni_error_appelle_onError() {
|
||||
// terminated reste false -> branche "Le flux d'import s'est interrompu...".
|
||||
String sse = "event:progress\ndata:{\"current\":1,\"total\":3}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertNull(c.done.get());
|
||||
assertNotNull(c.error.get());
|
||||
assertInstanceOf(CampaignImportException.class, c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("interrompu"));
|
||||
}
|
||||
|
||||
// ---------- erreur de transport ----------------------------------------
|
||||
|
||||
@Test
|
||||
void erreur_transport_traduite_en_CampaignImportException() {
|
||||
// Mono.error -> blockLast lève -> branche catch, expose type + message de la cause.
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientFailingWith(new RuntimeException("connexion coupée")));
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertInstanceOf(CampaignImportException.class, c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("streaming d'import"));
|
||||
assertTrue(c.error.get().getMessage().contains("connexion coupée"));
|
||||
assertNull(c.done.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void erreur_transport_sans_message_reste_geree() {
|
||||
// Cause sans message -> branche getMessage() == null (pas de " — ...").
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientFailingWith(new RuntimeException()));
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertInstanceOf(CampaignImportException.class, c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("streaming d'import"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void erreur_transport_apres_event_error_ne_double_pas_le_callback() {
|
||||
// error terminal puis le flux se clôt : terminated[0]==true -> pas de second onError.
|
||||
// (vérifie que le callback n'est appelé qu'une fois via le message attendu.)
|
||||
String sse = "event:error\ndata:{\"message\":\"stop\"}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse));
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("stop"));
|
||||
assertFalse(c.error.get().getMessage().contains("interrompu"));
|
||||
}
|
||||
|
||||
// ---------- nom de fichier ---------------------------------------------
|
||||
|
||||
@Test
|
||||
void filename_null_ou_blanc_est_accepte() {
|
||||
// Couvre la branche de repli "campaign.pdf" dans filePart + part().filename().
|
||||
String sse = "event:done\ndata:" + emptyDoneJson() + "\n\n";
|
||||
Collector c1 = new Collector();
|
||||
c1.invoke(clientReturning(sse), null);
|
||||
assertNotNull(c1.done.get());
|
||||
|
||||
Collector c2 = new Collector();
|
||||
c2.invoke(clientReturning(sse), " ");
|
||||
assertNotNull(c2.done.get());
|
||||
|
||||
Collector c3 = new Collector();
|
||||
c3.invoke(clientReturning(sse), "mon-livre.pdf");
|
||||
assertNotNull(c3.done.get());
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,21 @@ import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSu
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||
import com.loremind.domain.generationcontext.ChatMessage;
|
||||
import com.loremind.domain.generationcontext.ChatRequest;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.NpcSummary;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.RoomBranchHint;
|
||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.RoomSummary;
|
||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||
import com.loremind.domain.generationcontext.LoreStructuralContext;
|
||||
import com.loremind.domain.generationcontext.LoreStructuralContext.PageSummary;
|
||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||
import com.loremind.domain.generationcontext.PageContext;
|
||||
import com.loremind.domain.generationcontext.SessionContext;
|
||||
import com.loremind.domain.generationcontext.SessionContext.JournalEntrySummary;
|
||||
import com.loremind.domain.generationcontext.SessionContext.QuestSummary;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -284,4 +293,252 @@ class BrainChatPayloadBuilderTest {
|
||||
assertFalse(payload.containsKey("lore_context"));
|
||||
assertFalse(payload.containsKey("page_context"));
|
||||
}
|
||||
|
||||
// ---------- arc HUB + characters/npcs ----------------------------------
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_arcHub_injecteArcTypeHub() {
|
||||
// arc.hub() == true -> ajoute "arc_type":"HUB" (vocabulaire « quêtes »).
|
||||
ArcSummary arc = new ArcSummary("Hub central", "", true, 0, List.of());
|
||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||
"X", "", List.of(arc), List.of(), List.of());
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||
|
||||
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||
assertEquals("HUB", arcMap.get("arc_type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_arcLineaire_n_injectePasArcType() {
|
||||
ArcSummary arc = new ArcSummary("Lineaire", "", false, 0, List.of());
|
||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||
"X", "", List.of(arc), List.of(), List.of());
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||
|
||||
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||
assertFalse(arcMap.containsKey("arc_type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_campaignContext_serialiseCharactersEtNpcs_avecOmissionSnippetBlank() {
|
||||
// snippet renseigné -> présent ; snippet blank/null -> omis.
|
||||
CharacterSummary pj1 = new CharacterSummary("Aria", "Magicienne elfe");
|
||||
CharacterSummary pj2 = new CharacterSummary("Bran", " ");
|
||||
NpcSummary pnj1 = new NpcSummary("Garde", "Sentinelle bourrue");
|
||||
NpcSummary pnj2 = new NpcSummary("Mendiant", null);
|
||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||
"X", "", List.of(), List.of(pj1, pj2), List.of(pnj1, pnj2));
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||
|
||||
Map<String, Object> cctx = asMap(builder.build(req).get("campaign_context"));
|
||||
List<Map<String, Object>> chars = (List<Map<String, Object>>) cctx.get("characters");
|
||||
assertEquals("Aria", chars.get(0).get("name"));
|
||||
assertTrue(chars.get(0).containsKey("snippet"));
|
||||
assertFalse(chars.get(1).containsKey("snippet"), "snippet blank omis");
|
||||
|
||||
List<Map<String, Object>> npcs = (List<Map<String, Object>>) cctx.get("npcs");
|
||||
assertEquals("Garde", npcs.get(0).get("name"));
|
||||
assertTrue(npcs.get(0).containsKey("snippet"));
|
||||
assertFalse(npcs.get(1).containsKey("snippet"), "snippet null omis");
|
||||
}
|
||||
|
||||
// ---------- rooms d'une scène ------------------------------------------
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_sceneRooms_serialiseTousLesChampsEtBranchesEntrePieces() {
|
||||
RoomBranchHint exit = new RoomBranchHint("porte nord", "Salle du trone", "clé en main");
|
||||
RoomSummary room = new RoomSummary("Hall", 1, "Vaste entrée", "Spectres", List.of(exit));
|
||||
SceneSummary scene = new SceneSummary("Donjon", "", 0, List.of(), List.of(room));
|
||||
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of(chapter));
|
||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||
"X", "", List.of(arc), List.of(), List.of());
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||
|
||||
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||
Map<String, Object> sceneMap = firstOf(firstOf(arcMap, "chapters"), "scenes");
|
||||
Map<String, Object> roomMap = firstOf(sceneMap, "rooms");
|
||||
|
||||
assertEquals("Hall", roomMap.get("name"));
|
||||
assertEquals(1, roomMap.get("floor"));
|
||||
assertEquals("Vaste entrée", roomMap.get("description"));
|
||||
assertEquals("Spectres", roomMap.get("enemies"));
|
||||
Map<String, Object> branchMap = firstOf(roomMap, "branches");
|
||||
assertEquals("porte nord", branchMap.get("label"));
|
||||
assertEquals("Salle du trone", branchMap.get("target_room_name"));
|
||||
assertEquals("clé en main", branchMap.get("condition"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_sceneRooms_ometLesChampsOptionnelsVides() {
|
||||
// floor null, description/enemies blank, condition blank, branches non vides.
|
||||
RoomBranchHint exit = new RoomBranchHint("sortie", "Autre", " ");
|
||||
RoomSummary room = new RoomSummary("Cellule", null, " ", " ", List.of(exit));
|
||||
SceneSummary scene = new SceneSummary("Donjon", "", 0, List.of(), List.of(room));
|
||||
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of(chapter));
|
||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||
"X", "", List.of(arc), List.of(), List.of());
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||
|
||||
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||
Map<String, Object> sceneMap = firstOf(firstOf(arcMap, "chapters"), "scenes");
|
||||
Map<String, Object> roomMap = firstOf(sceneMap, "rooms");
|
||||
|
||||
assertFalse(roomMap.containsKey("floor"));
|
||||
assertFalse(roomMap.containsKey("description"));
|
||||
assertFalse(roomMap.containsKey("enemies"));
|
||||
Map<String, Object> branchMap = firstOf(roomMap, "branches");
|
||||
assertFalse(branchMap.containsKey("condition"), "condition blank omise");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_sceneRooms_omisesSiListeVide() {
|
||||
// s.rooms() vide -> clé "rooms" absente.
|
||||
SceneSummary scene = new SceneSummary("Lineaire", "", 0, List.of(), List.of());
|
||||
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||
ArcSummary arc = new ArcSummary("A", "", false, 0, List.of(chapter));
|
||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||
"X", "", List.of(arc), List.of(), List.of());
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||
|
||||
Map<String, Object> arcMap = firstOf(asMap(builder.build(req).get("campaign_context")), "arcs");
|
||||
Map<String, Object> sceneMap = firstOf(firstOf(arcMap, "chapters"), "scenes");
|
||||
assertFalse(sceneMap.containsKey("rooms"));
|
||||
}
|
||||
|
||||
// ---------- game_system_context ----------------------------------------
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_gameSystemContext_completInclutDescriptionEtSections() {
|
||||
GameSystemContext gs = new GameSystemContext(
|
||||
"Nimble", "JDR rapide", Map.of("Combat", "Lancez 1d20"));
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).gameSystemContext(gs).build();
|
||||
|
||||
Map<String, Object> gsm = asMap(builder.build(req).get("game_system_context"));
|
||||
assertEquals("Nimble", gsm.get("system_name"));
|
||||
assertEquals("JDR rapide", gsm.get("system_description"));
|
||||
assertEquals(Map.of("Combat", "Lancez 1d20"), gsm.get("sections"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_gameSystemContext_descriptionBlankEtSectionsNull() {
|
||||
// systemDescription blank -> omis ; sections null -> Map.of() de repli.
|
||||
GameSystemContext gs = new GameSystemContext("D&D 5.1", " ", null);
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).gameSystemContext(gs).build();
|
||||
|
||||
Map<String, Object> gsm = asMap(builder.build(req).get("game_system_context"));
|
||||
assertEquals("D&D 5.1", gsm.get("system_name"));
|
||||
assertFalse(gsm.containsKey("system_description"));
|
||||
assertEquals(Map.of(), gsm.get("sections"));
|
||||
}
|
||||
|
||||
// ---------- session_context --------------------------------------------
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_sessionContext_complet_inclutToutesLesListesPeuplees() {
|
||||
LocalDateTime now = LocalDateTime.of(2026, 6, 14, 20, 0);
|
||||
JournalEntrySummary entry = new JournalEntrySummary(
|
||||
"combat", "Le dragon attaque", now, null);
|
||||
JournalEntrySummary prev = new JournalEntrySummary(
|
||||
"info", "Le roi est mort", now, "Session 1");
|
||||
QuestSummary avail = new QuestSummary("Sauver le village", "Acte I", "Urgence");
|
||||
QuestSummary inProg = new QuestSummary("Trouver l'épée", "Acte II", " ");
|
||||
SessionContext sc = new SessionContext(
|
||||
"Session 2", true, now,
|
||||
List.of(entry), List.of(prev),
|
||||
List.of(avail), List.of(inProg),
|
||||
List.of("Quête secrète"), List.of("porte_ouverte"));
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).sessionContext(sc).build();
|
||||
|
||||
Map<String, Object> scm = asMap(builder.build(req).get("session_context"));
|
||||
assertEquals("Session 2", scm.get("session_name"));
|
||||
assertEquals(true, scm.get("active"));
|
||||
assertEquals(now.toString(), scm.get("started_at"));
|
||||
|
||||
// entries : type/content/occurredAt présents, source omis (null) sur l'entrée courante.
|
||||
Map<String, Object> entryMap = firstOf(scm, "entries");
|
||||
assertEquals("combat", entryMap.get("type"));
|
||||
assertEquals("Le dragon attaque", entryMap.get("content"));
|
||||
assertEquals(now.toString(), entryMap.get("occurred_at"));
|
||||
assertFalse(entryMap.containsKey("source_session_name"));
|
||||
|
||||
// previous_events : source renseignée.
|
||||
Map<String, Object> prevMap = firstOf(scm, "previous_events");
|
||||
assertEquals("Session 1", prevMap.get("source_session_name"));
|
||||
|
||||
// available_quests : description renseignée ; in_progress : description blank omise.
|
||||
Map<String, Object> availMap = firstOf(scm, "available_quests");
|
||||
assertEquals("Sauver le village", availMap.get("name"));
|
||||
assertEquals("Acte I", availMap.get("arc_name"));
|
||||
assertEquals("Urgence", availMap.get("description"));
|
||||
Map<String, Object> inProgMap = firstOf(scm, "in_progress_quests");
|
||||
assertFalse(inProgMap.containsKey("description"), "description blank omise");
|
||||
|
||||
assertEquals(List.of("Quête secrète"), scm.get("locked_quest_titles"));
|
||||
assertEquals(List.of("porte_ouverte"), scm.get("active_flags"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void build_sessionContext_minimal_ometListesVidesEtChampsNull() {
|
||||
// startedAt null -> omis ; entries null -> List.of() ; toutes les autres listes
|
||||
// vides/null -> clés absentes.
|
||||
SessionContext sc = new SessionContext(
|
||||
"Session vide", false, null,
|
||||
null, List.of(),
|
||||
List.of(), List.of(),
|
||||
List.of(), List.of());
|
||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).sessionContext(sc).build();
|
||||
|
||||
Map<String, Object> scm = asMap(builder.build(req).get("session_context"));
|
||||
assertEquals("Session vide", scm.get("session_name"));
|
||||
assertEquals(false, scm.get("active"));
|
||||
assertFalse(scm.containsKey("started_at"));
|
||||
assertEquals(List.of(), scm.get("entries"));
|
||||
assertFalse(scm.containsKey("previous_events"));
|
||||
assertFalse(scm.containsKey("available_quests"));
|
||||
assertFalse(scm.containsKey("in_progress_quests"));
|
||||
assertFalse(scm.containsKey("locked_quest_titles"));
|
||||
assertFalse(scm.containsKey("active_flags"));
|
||||
}
|
||||
|
||||
// ---------- tous les contextes présents simultanément ------------------
|
||||
|
||||
@Test
|
||||
void build_tousLesContextes_sontTousPresents() {
|
||||
LoreStructuralContext lore = new LoreStructuralContext("L", "", Map.of(), List.of());
|
||||
PageContext page = new PageContext("P", "T", List.of(), Map.of());
|
||||
CampaignStructuralContext camp = new CampaignStructuralContext("C", "", List.of(), List.of(), List.of());
|
||||
NarrativeEntityContext entity = new NarrativeEntityContext("scene", "S", Map.of());
|
||||
GameSystemContext gs = new GameSystemContext("G", null, Map.of());
|
||||
SessionContext sc = new SessionContext("Sess", true, null, List.of(), List.of(),
|
||||
List.of(), List.of(), List.of(), List.of());
|
||||
ChatRequest req = ChatRequest.builder()
|
||||
.messages(sampleMessages)
|
||||
.loreContext(lore)
|
||||
.pageContext(page)
|
||||
.campaignContext(camp)
|
||||
.narrativeEntity(entity)
|
||||
.gameSystemContext(gs)
|
||||
.sessionContext(sc)
|
||||
.build();
|
||||
|
||||
Map<String, Object> payload = builder.build(req);
|
||||
assertTrue(payload.containsKey("lore_context"));
|
||||
assertTrue(payload.containsKey("page_context"));
|
||||
assertTrue(payload.containsKey("campaign_context"));
|
||||
assertTrue(payload.containsKey("narrative_entity"));
|
||||
assertTrue(payload.containsKey("game_system_context"));
|
||||
assertTrue(payload.containsKey("session_context"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.conversationcontext.ConversationMessage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Tests unitaires purs (JUnit 5, sans Spring, sans réseau) de
|
||||
* {@link BrainConversationTitleClient}.
|
||||
*
|
||||
* Principe : on injecte un WebClient.Builder préconfiguré avec une
|
||||
* ExchangeFunction mock qui renvoie des réponses canned -> aucun appel réseau.
|
||||
*/
|
||||
class BrainConversationTitleClientTest {
|
||||
|
||||
private static final String FALLBACK = "Nouvelle conversation";
|
||||
|
||||
/** Construit un client dont le WebClient répond avec la réponse fournie. */
|
||||
private BrainConversationTitleClient clientReturning(ClientResponse response) {
|
||||
ExchangeFunction ef = req -> Mono.just(response);
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainConversationTitleClient(builder, "http://brain");
|
||||
}
|
||||
|
||||
/** Construit un client dont le WebClient émet une erreur transport. */
|
||||
private BrainConversationTitleClient clientErroring() {
|
||||
ExchangeFunction ef = req -> Mono.error(new RuntimeException("boom"));
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainConversationTitleClient(builder, "http://brain");
|
||||
}
|
||||
|
||||
private ClientResponse jsonOk(String body) {
|
||||
return ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.body(body)
|
||||
.build();
|
||||
}
|
||||
|
||||
private ConversationMessage msg(String role, String content) {
|
||||
return ConversationMessage.builder().role(role).content(content).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void liste_null_renvoie_fallback() {
|
||||
// Pas besoin d'appel réseau : court-circuit sur entrée null.
|
||||
BrainConversationTitleClient client = clientErroring();
|
||||
assertThat(client.generate(null)).isEqualTo(FALLBACK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void liste_vide_renvoie_fallback() {
|
||||
BrainConversationTitleClient client = clientErroring();
|
||||
assertThat(client.generate(List.of())).isEqualTo(FALLBACK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reponse_ok_avec_titre_renvoie_le_titre() {
|
||||
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\"Mon titre\"}"));
|
||||
String result = client.generate(List.of(msg("user", "Salut")));
|
||||
assertThat(result).isEqualTo("Mon titre");
|
||||
}
|
||||
|
||||
@Test
|
||||
void titre_avec_espaces_est_trimme() {
|
||||
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\" Espacé \"}"));
|
||||
String result = client.generate(List.of(msg("user", "Bonjour")));
|
||||
assertThat(result).isEqualTo("Espacé");
|
||||
}
|
||||
|
||||
@Test
|
||||
void contenu_message_null_traite_sans_npe() {
|
||||
// content null -> mappé en "" dans le payload, ne doit pas lever.
|
||||
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\"Ok\"}"));
|
||||
String result = client.generate(List.of(msg("assistant", null)));
|
||||
assertThat(result).isEqualTo("Ok");
|
||||
}
|
||||
|
||||
@Test
|
||||
void titre_absent_renvoie_fallback() {
|
||||
BrainConversationTitleClient client = clientReturning(jsonOk("{\"autre\":\"x\"}"));
|
||||
String result = client.generate(List.of(msg("user", "Hello")));
|
||||
assertThat(result).isEqualTo(FALLBACK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void titre_vide_renvoie_fallback() {
|
||||
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\"\"}"));
|
||||
String result = client.generate(List.of(msg("user", "Hello")));
|
||||
assertThat(result).isEqualTo(FALLBACK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void titre_blanc_renvoie_fallback() {
|
||||
BrainConversationTitleClient client = clientReturning(jsonOk("{\"title\":\" \"}"));
|
||||
String result = client.generate(List.of(msg("user", "Hello")));
|
||||
assertThat(result).isEqualTo(FALLBACK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void corps_json_vide_renvoie_fallback() {
|
||||
// Map décodée non null mais sans clé "title".
|
||||
BrainConversationTitleClient client = clientReturning(jsonOk("{}"));
|
||||
String result = client.generate(List.of(msg("user", "Hello")));
|
||||
assertThat(result).isEqualTo(FALLBACK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void erreur_transport_renvoie_fallback() {
|
||||
BrainConversationTitleClient client = clientErroring();
|
||||
String result = client.generate(List.of(msg("user", "Hello")));
|
||||
assertThat(result).isEqualTo(FALLBACK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reponse_500_renvoie_fallback() {
|
||||
ClientResponse err = ClientResponse.create(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.body("{\"error\":\"down\"}")
|
||||
.build();
|
||||
BrainConversationTitleClient client = clientReturning(err);
|
||||
String result = client.generate(List.of(msg("user", "Hello")));
|
||||
assertThat(result).isEqualTo(FALLBACK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* Tests unitaires des DTOs wire de l'Adapter IA :
|
||||
* - BrainGeneratePageRequest (record envoye au Brain) ;
|
||||
* - BrainGeneratePageResponse (@Data/@NoArgsConstructor recu du Brain).
|
||||
* On instancie et on appelle les accesseurs pour couvrir le code genere.
|
||||
*/
|
||||
class BrainGeneratePageRequestTest {
|
||||
|
||||
// --- BrainGeneratePageRequest -------------------------------------------
|
||||
|
||||
@Test
|
||||
void request_accesseursExposentLesChamps() {
|
||||
BrainGeneratePageRequest req = new BrainGeneratePageRequest(
|
||||
"Aetheria",
|
||||
"Un monde de cendres",
|
||||
"PNJ",
|
||||
"Fiche personnage",
|
||||
List.of("histoire", "motto"),
|
||||
"Garde rouge"
|
||||
);
|
||||
|
||||
assertEquals("Aetheria", req.loreName());
|
||||
assertEquals("Un monde de cendres", req.loreDescription());
|
||||
assertEquals("PNJ", req.folderName());
|
||||
assertEquals("Fiche personnage", req.templateName());
|
||||
assertEquals(List.of("histoire", "motto"), req.templateFields());
|
||||
assertEquals("Garde rouge", req.pageTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void request_egaliteStructurelleEtToString() {
|
||||
BrainGeneratePageRequest a = new BrainGeneratePageRequest(
|
||||
"n", "d", "f", "t", List.of("x"), "p");
|
||||
BrainGeneratePageRequest b = new BrainGeneratePageRequest(
|
||||
"n", "d", "f", "t", List.of("x"), "p");
|
||||
BrainGeneratePageRequest c = new BrainGeneratePageRequest(
|
||||
"AUTRE", "d", "f", "t", List.of("x"), "p");
|
||||
|
||||
assertEquals(a, b);
|
||||
assertEquals(a.hashCode(), b.hashCode());
|
||||
assertNotEquals(a, c);
|
||||
// toString genere : on verifie juste qu'il est non vide et contient un champ
|
||||
org.junit.jupiter.api.Assertions.assertTrue(a.toString().contains("n"));
|
||||
}
|
||||
|
||||
// --- BrainGeneratePageResponse ------------------------------------------
|
||||
|
||||
@Test
|
||||
void response_setterEtGetterValues() {
|
||||
BrainGeneratePageResponse resp = new BrainGeneratePageResponse();
|
||||
assertNull(resp.getValues());
|
||||
|
||||
Map<String, String> values = Map.of("histoire", "Nee sous une etoile rouge");
|
||||
resp.setValues(values);
|
||||
|
||||
assertEquals(values, resp.getValues());
|
||||
assertEquals("Nee sous une etoile rouge", resp.getValues().get("histoire"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void response_egaliteEtToStringGeneresParLombok() {
|
||||
BrainGeneratePageResponse a = new BrainGeneratePageResponse();
|
||||
a.setValues(Map.of("f", "v"));
|
||||
BrainGeneratePageResponse b = new BrainGeneratePageResponse();
|
||||
b.setValues(Map.of("f", "v"));
|
||||
BrainGeneratePageResponse c = new BrainGeneratePageResponse();
|
||||
c.setValues(Map.of("f", "AUTRE"));
|
||||
|
||||
assertEquals(a, b);
|
||||
assertEquals(a.hashCode(), b.hashCode());
|
||||
assertNotEquals(a, c);
|
||||
org.junit.jupiter.api.Assertions.assertTrue(a.toString().contains("values"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerationException;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerator.GeneratedCatalog;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring) de {@link BrainItemCatalogClient}.
|
||||
* Le RestTemplate est mocké : {@code postForObject(url, entity, Map.class)}.
|
||||
*/
|
||||
class BrainItemCatalogClientTest {
|
||||
|
||||
private RestTemplate rt;
|
||||
private BrainItemCatalogClient client;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rt = mock(RestTemplate.class);
|
||||
client = new BrainItemCatalogClient(rt, "http://brain");
|
||||
}
|
||||
|
||||
/** Construit une map d'objet pour le payload "items". */
|
||||
private static Map<String, Object> item(Object name, Object price, Object category, Object description) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("name", name);
|
||||
m.put("price", price);
|
||||
m.put("category", category);
|
||||
m.put("description", description);
|
||||
return m;
|
||||
}
|
||||
|
||||
// ---------- generate : cas nominal et mapping ----------
|
||||
|
||||
@Test
|
||||
void generate_reponseValide_mappeItems_etIgnoreInvalides() {
|
||||
List<Object> items = new ArrayList<>();
|
||||
items.add(item("Épée longue", "15 po", "Armes", "Tranchante")); // valide
|
||||
items.add(item("Potion", null, null, null)); // valide, champs null
|
||||
items.add(item(null, "1 po", "x", "y")); // ignoré : name null
|
||||
items.add(item(" ", "1 po", "x", "y")); // ignoré : name blank
|
||||
items.add("pas une map"); // ignoré : item non-Map
|
||||
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("name", "Boutique du forgeron");
|
||||
resp.put("description", "Au village");
|
||||
resp.put("items", items);
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
GeneratedCatalog cat = client.generate("desc", "ctx");
|
||||
|
||||
assertEquals("Boutique du forgeron", cat.name());
|
||||
assertEquals("Au village", cat.description());
|
||||
assertEquals(2, cat.items().size());
|
||||
|
||||
CatalogItem i0 = cat.items().get(0);
|
||||
assertEquals("Épée longue", i0.getName());
|
||||
assertEquals("15 po", i0.getPrice());
|
||||
assertEquals("Armes", i0.getCategory());
|
||||
assertEquals("Tranchante", i0.getDescription());
|
||||
|
||||
CatalogItem i1 = cat.items().get(1);
|
||||
assertEquals("Potion", i1.getName());
|
||||
assertNull(i1.getPrice());
|
||||
assertNull(i1.getCategory());
|
||||
assertNull(i1.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_nameAbsent_fallbackSurDescription() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("items", List.of(item("Objet", null, null, null)));
|
||||
// pas de "name" -> fallback description
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
GeneratedCatalog cat = client.generate("MaDescription", "ctx");
|
||||
assertEquals("MaDescription", cat.name());
|
||||
assertNull(cat.description());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_nameBlank_fallbackSurDescription() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("name", " ");
|
||||
resp.put("items", List.of(item("Objet", null, null, null)));
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
GeneratedCatalog cat = client.generate("Fallback", "ctx");
|
||||
assertEquals("Fallback", cat.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_argumentsNull_remplisParDefauts() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("name", "Cat");
|
||||
resp.put("items", List.of(item("Objet", null, null, null)));
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
GeneratedCatalog cat = client.generate(null, null);
|
||||
assertEquals("Cat", cat.name());
|
||||
}
|
||||
|
||||
// ---------- generate : réponse vide / pas d'items ----------
|
||||
|
||||
@Test
|
||||
void generate_reponseNull_leveException() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(null);
|
||||
|
||||
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||
() -> client.generate("d", "c"));
|
||||
assertTrue(ex.getMessage().contains("réponse vide"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_itemsAbsents_leveException() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("name", "Cat"); // pas de "items"
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||
() -> client.generate("d", "c"));
|
||||
assertTrue(ex.getMessage().contains("Aucun objet"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_itemsVide_leveException() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("items", new ArrayList<>());
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
assertThrows(ItemCatalogGenerationException.class, () -> client.generate("d", "c"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_tousItemsInvalides_leveException() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("items", List.of(item(null, null, null, null)));
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
assertThrows(ItemCatalogGenerationException.class, () -> client.generate("d", "c"));
|
||||
}
|
||||
|
||||
// ---------- generate : branches du catch ----------
|
||||
|
||||
@Test
|
||||
void generate_brainInjoignable_resourceAccess() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||
.thenThrow(new ResourceAccessException("down"));
|
||||
|
||||
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||
() -> client.generate("d", "c"));
|
||||
assertTrue(ex.getMessage().contains("injoignable"));
|
||||
assertInstanceOf(ResourceAccessException.class, ex.getCause());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_erreurHttp_restClientResponse() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||
.thenThrow(HttpServerErrorException.create(
|
||||
HttpStatus.BAD_GATEWAY, "Bad Gateway", new HttpHeaders(), new byte[0], null));
|
||||
|
||||
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||
() -> client.generate("d", "c"));
|
||||
assertTrue(ex.getMessage().contains("HTTP 502"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_erreurInattendue_exceptionGenerique() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||
.thenThrow(new IllegalStateException("boom"));
|
||||
|
||||
ItemCatalogGenerationException ex = assertThrows(ItemCatalogGenerationException.class,
|
||||
() -> client.generate("d", "c"));
|
||||
assertTrue(ex.getMessage().contains("inattendue"));
|
||||
assertInstanceOf(IllegalStateException.class, ex.getCause());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.mock.http.client.reactive.MockClientHttpRequest;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||
import org.springframework.web.reactive.function.client.ExchangeStrategies;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Couvre les sous-classes anonymes {@code new ByteArrayResource(){ getFilename() }}
|
||||
* des clients d'upload multipart : leur {@code getFilename()} (nom par défaut si
|
||||
* absent/vide) n'est appelé que lors de la SÉRIALISATION du corps, qui n'a pas lieu
|
||||
* quand le transport est mocké. On la déclenche donc explicitement :
|
||||
* <ul>
|
||||
* <li>clients RestTemplate : on capture le {@link HttpEntity} envoyé et on lit la
|
||||
* ressource « file » pour appeler {@code getFilename()} ;</li>
|
||||
* <li>clients WebClient : l'{@link ExchangeFunction} sérialise réellement le corps
|
||||
* multipart dans un {@link MockClientHttpRequest} (ce qui invoque getFilename).</li>
|
||||
* </ul>
|
||||
*/
|
||||
class BrainMultipartFilenameTest {
|
||||
|
||||
// --- Helpers ------------------------------------------------------------
|
||||
|
||||
/** ExchangeFunction qui sérialise le corps de la requête (déclenche getFilename) puis renvoie un SSE 'done'. */
|
||||
private static ExchangeFunction serializingExchange(String sse) {
|
||||
return request -> {
|
||||
MockClientHttpRequest mock = new MockClientHttpRequest(request.method(), request.url());
|
||||
// Le write-handler par défaut ne souscrit pas au corps : on draine donc le
|
||||
// flux nous-mêmes pour forcer l'écriture des parts (et l'appel à getFilename).
|
||||
mock.setWriteHandler(body -> DataBufferUtils.join(body)
|
||||
.doOnNext(DataBufferUtils::release).then());
|
||||
request.writeTo(mock, ExchangeStrategies.withDefaults()).block();
|
||||
return Mono.just(ClientResponse.create(org.springframework.http.HttpStatus.OK)
|
||||
.header(org.springframework.http.HttpHeaders.CONTENT_TYPE,
|
||||
org.springframework.http.MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sse)
|
||||
.build());
|
||||
};
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static String capturedFilename(RestTemplate rt) {
|
||||
ArgumentCaptor<HttpEntity> cap = ArgumentCaptor.forClass(HttpEntity.class);
|
||||
verify(rt).postForObject(anyString(), cap.capture(), any());
|
||||
MultiValueMap<String, Object> body = (MultiValueMap<String, Object>) cap.getValue().getBody();
|
||||
return ((Resource) body.getFirst("file")).getFilename();
|
||||
}
|
||||
|
||||
// --- BrainNotebookIndexClient (RestTemplate) ----------------------------
|
||||
|
||||
@Test
|
||||
void notebookIndex_filePart_usesGivenFilename_elseDefault() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainNotebookIndexClient client = new BrainNotebookIndexClient(rt, "http://brain");
|
||||
|
||||
try { client.index("src-1", new byte[]{1, 2}, "doc.pdf"); } catch (RuntimeException ignored) { }
|
||||
assertEquals("doc.pdf", capturedFilename(rt));
|
||||
|
||||
RestTemplate rt2 = mock(RestTemplate.class);
|
||||
BrainNotebookIndexClient client2 = new BrainNotebookIndexClient(rt2, "http://brain");
|
||||
try { client2.index("src-1", new byte[]{1, 2}, null); } catch (RuntimeException ignored) { }
|
||||
assertEquals("source.pdf", capturedFilename(rt2));
|
||||
}
|
||||
|
||||
// --- BrainRulesImportClient (RestTemplate one-shot) ---------------------
|
||||
|
||||
@Test
|
||||
void rulesImport_filePart_usesGivenFilename_elseDefault() {
|
||||
RestTemplate rt = mock(RestTemplate.class);
|
||||
BrainRulesImportClient client = new BrainRulesImportClient(
|
||||
rt, WebClient.builder(), new ObjectMapper(), "http://brain", 600);
|
||||
|
||||
try { client.importRules(new byte[]{1, 2}, "regles.pdf"); } catch (RuntimeException ignored) { }
|
||||
assertEquals("regles.pdf", capturedFilename(rt));
|
||||
|
||||
RestTemplate rt2 = mock(RestTemplate.class);
|
||||
BrainRulesImportClient client2 = new BrainRulesImportClient(
|
||||
rt2, WebClient.builder(), new ObjectMapper(), "http://brain", 600);
|
||||
try { client2.importRules(new byte[]{1, 2}, " "); } catch (RuntimeException ignored) { }
|
||||
assertEquals("rules.pdf", capturedFilename(rt2));
|
||||
}
|
||||
|
||||
// --- BrainCampaignAdaptClient (WebClient multipart) ---------------------
|
||||
|
||||
@Test
|
||||
void campaignAdapt_filePart_serializedFilename() {
|
||||
ExchangeFunction ef = serializingExchange("event:done\ndata:{}\n\n");
|
||||
BrainCampaignAdaptClient client = new BrainCampaignAdaptClient(
|
||||
WebClient.builder().exchangeFunction(ef), new ObjectMapper(), "http://brain", 30);
|
||||
|
||||
// filename présent puis null : les deux branches de getFilename sont sérialisées.
|
||||
client.adviseStreaming(new byte[]{1, 2}, "doc.pdf", "brief", "[]",
|
||||
t -> { }, () -> { }, e -> { });
|
||||
client.adviseStreaming(new byte[]{1, 2}, null, null, null,
|
||||
t -> { }, () -> { }, e -> { });
|
||||
}
|
||||
|
||||
// --- BrainCampaignImportClient (WebClient multipart) --------------------
|
||||
|
||||
@Test
|
||||
void campaignImport_filePart_serializedFilename() {
|
||||
ExchangeFunction ef = serializingExchange("event:done\ndata:{\"sections\":{}}\n\n");
|
||||
BrainCampaignImportClient client = new BrainCampaignImportClient(
|
||||
WebClient.builder().exchangeFunction(ef), new ObjectMapper(), "http://brain", 30);
|
||||
|
||||
client.importCampaignStreaming(new byte[]{1, 2}, "doc.pdf",
|
||||
p -> { }, () -> { }, s -> { }, r -> { }, e -> { });
|
||||
client.importCampaignStreaming(new byte[]{1, 2}, null,
|
||||
p -> { }, () -> { }, s -> { }, r -> { }, e -> { });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookChatStreamer.Msg;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookChatStreamer.Progress;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Tests unitaires PURS (JUnit 5 + Mockito-less) pour {@link BrainNotebookChatClient}.
|
||||
* On injecte un WebClient.Builder dont l'ExchangeFunction renvoie un corps SSE canned :
|
||||
* aucun réseau n'est sollicité.
|
||||
*/
|
||||
class BrainNotebookChatClientTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** Construit un client dont le WebClient renvoie le corps SSE fourni. */
|
||||
private BrainNotebookChatClient clientReturning(String sseBody) {
|
||||
ExchangeFunction ef = req -> Mono.just(
|
||||
ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sseBody)
|
||||
.build());
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainNotebookChatClient(builder, MAPPER, "http://brain", 30);
|
||||
}
|
||||
|
||||
/** Construit un client dont le transport échoue immédiatement. */
|
||||
private BrainNotebookChatClient clientFailingWith(Throwable boom) {
|
||||
ExchangeFunction ef = req -> Mono.error(boom);
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainNotebookChatClient(builder, MAPPER, "http://brain", 30);
|
||||
}
|
||||
|
||||
/** Collecteur réutilisable pour les callbacks. */
|
||||
private static final class Collector {
|
||||
final AtomicReference<String> sources = new AtomicReference<>();
|
||||
final StringBuilder tokens = new StringBuilder();
|
||||
final List<Progress> progresses = new ArrayList<>();
|
||||
final AtomicBoolean done = new AtomicBoolean(false);
|
||||
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
|
||||
void invoke(BrainNotebookChatClient client, boolean deep) {
|
||||
client.stream(
|
||||
List.of("s1", "s2"),
|
||||
List.of(new Msg("user", "Bonjour")),
|
||||
"ctx",
|
||||
deep,
|
||||
sources::set,
|
||||
tokens::append,
|
||||
progresses::add,
|
||||
() -> done.set(true),
|
||||
error::set);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void streame_tous_les_events_token_sources_progress_done() {
|
||||
// SSE déclenchant chaque branche de handleEvent : sources, progress, token, done.
|
||||
String sse =
|
||||
"event:sources\ndata:{\"passages\":[1,2]}\n\n" +
|
||||
"event:progress\ndata:{\"current\":2,\"total\":5}\n\n" +
|
||||
"event:token\ndata:{\"token\":\"Salut\"}\n\n" +
|
||||
"event:token\ndata:{\"token\":\" toi\"}\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse), true);
|
||||
|
||||
assertEquals("{\"passages\":[1,2]}", c.sources.get(), "JSON sources relayé brut");
|
||||
assertEquals("Salut toi", c.tokens.toString(), "tokens concaténés dans l'ordre");
|
||||
assertEquals(1, c.progresses.size());
|
||||
assertEquals(2, c.progresses.get(0).current());
|
||||
assertEquals(5, c.progresses.get(0).total());
|
||||
assertTrue(c.done.get(), "onDone appelé via event done");
|
||||
assertNull(c.error.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void token_vide_ou_absent_ignore() {
|
||||
// token vide -> non émis ; token absent -> readField null -> non émis.
|
||||
String sse =
|
||||
"event:token\ndata:{\"token\":\"\"}\n\n" +
|
||||
"event:token\ndata:{\"foo\":\"bar\"}\n\n" +
|
||||
"event:token\ndata:{\"token\":\"X\"}\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse), false);
|
||||
|
||||
assertEquals("X", c.tokens.toString(), "seul le token non vide est émis");
|
||||
assertTrue(c.done.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void progress_avec_json_invalide_donne_zero() {
|
||||
// data non-JSON -> readInt catch -> 0/0 (couvre la branche d'exception).
|
||||
String sse =
|
||||
"event:progress\ndata:pas-du-json\n\n" +
|
||||
"event:done\ndata:{}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse), true);
|
||||
|
||||
assertEquals(1, c.progresses.size());
|
||||
assertEquals(0, c.progresses.get(0).current());
|
||||
assertEquals(0, c.progresses.get(0).total());
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_error_appelle_onError_avec_NotebookException() {
|
||||
String sse =
|
||||
"event:token\ndata:{\"token\":\"avant\"}\n\n" +
|
||||
"event:error\ndata:{\"message\":\"oups modèle\"}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse), false);
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertInstanceOf(NotebookException.class, c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("oups modèle"));
|
||||
assertFalse(c.done.get(), "onDone non appelé après un error terminal");
|
||||
}
|
||||
|
||||
@Test
|
||||
void event_error_sans_message_relaie_data_brut() {
|
||||
// readMessage : pas de champ message -> renvoie data brut.
|
||||
String sse = "event:error\ndata:erreur-brute\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse), false);
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("erreur-brute"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void flux_termine_sans_done_appelle_onDone() {
|
||||
// Aucun event done/error -> terminated reste false -> onDone() de secours.
|
||||
String sse = "event:token\ndata:{\"token\":\"fin\"}\n\n";
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientReturning(sse), false);
|
||||
|
||||
assertEquals("fin", c.tokens.toString());
|
||||
assertTrue(c.done.get(), "onDone de secours appelé pour flux clos sans done");
|
||||
assertNull(c.error.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void erreur_transport_traduite_en_NotebookException() {
|
||||
Collector c = new Collector();
|
||||
c.invoke(clientFailingWith(new RuntimeException("boom")), false);
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertInstanceOf(NotebookException.class, c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("boom"));
|
||||
assertFalse(c.done.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void context_null_est_accepte() {
|
||||
// Couvre la branche context == null -> "" lors de la construction du payload.
|
||||
String sse = "event:done\ndata:{}\n\n";
|
||||
ExchangeFunction ef = req -> Mono.just(
|
||||
ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sse)
|
||||
.build());
|
||||
BrainNotebookChatClient client =
|
||||
new BrainNotebookChatClient(WebClient.builder().exchangeFunction(ef), MAPPER, "http://brain", 30);
|
||||
|
||||
AtomicBoolean done = new AtomicBoolean(false);
|
||||
client.stream(
|
||||
List.of("s1"),
|
||||
List.of(new Msg("user", "hi")),
|
||||
null,
|
||||
false,
|
||||
json -> {},
|
||||
tok -> {},
|
||||
p -> {},
|
||||
() -> done.set(true),
|
||||
err -> {});
|
||||
|
||||
assertTrue(done.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookException;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookIndexer.IndexResult;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring/réseau) de
|
||||
* {@link BrainNotebookIndexClient} : indexation multipart one-shot (RestTemplate)
|
||||
* et suppression best-effort.
|
||||
* <p>
|
||||
* {@code IndexResponse} étant une classe privée de l'adapter, on l'instancie par
|
||||
* réflexion pour piloter la valeur renvoyée par le mock RestTemplate.
|
||||
*/
|
||||
class BrainNotebookIndexClientTest {
|
||||
|
||||
private static final String BASE_URL = "http://brain";
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
private BrainNotebookIndexClient client;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
restTemplate = mock(RestTemplate.class);
|
||||
client = new BrainNotebookIndexClient(restTemplate, BASE_URL);
|
||||
}
|
||||
|
||||
/** Récupère la Class<?> de l'IndexResponse privée (telle qu'attendue par postForObject). */
|
||||
private Class<?> indexResponseClass() throws ClassNotFoundException {
|
||||
return Class.forName("com.loremind.infrastructure.ai.BrainNotebookIndexClient$IndexResponse");
|
||||
}
|
||||
|
||||
/** Instancie l'IndexResponse privée et remplit ses champs par réflexion. */
|
||||
private Object newIndexResponse(int chunks, int pageCount, int ocrPageCount) throws Exception {
|
||||
Class<?> cls = indexResponseClass();
|
||||
Constructor<?> ctor = cls.getDeclaredConstructor();
|
||||
ctor.setAccessible(true);
|
||||
Object resp = ctor.newInstance();
|
||||
setField(resp, "chunks", chunks);
|
||||
setField(resp, "pageCount", pageCount);
|
||||
setField(resp, "ocrPageCount", ocrPageCount);
|
||||
return resp;
|
||||
}
|
||||
|
||||
private void setField(Object target, String name, int value) throws Exception {
|
||||
Field f = target.getClass().getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
f.setInt(target, value);
|
||||
}
|
||||
|
||||
// --- index() -------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void index_succes_retourneIndexResult() throws Exception {
|
||||
Object wire = newIndexResponse(42, 100, 7);
|
||||
// doReturn évite l'inférence générique (Class<?> -> wildcard) qui casse thenReturn.
|
||||
doReturn(wire).when(restTemplate)
|
||||
.postForObject(anyString(), any(), eq(indexResponseClass()));
|
||||
|
||||
IndexResult result = client.index("src-1", new byte[]{1, 2, 3}, "livre.pdf");
|
||||
|
||||
assertEquals(42, result.chunks());
|
||||
assertEquals(100, result.pageCount());
|
||||
assertEquals(7, result.ocrPageCount());
|
||||
|
||||
// L'URL appelée concatène baseUrl + INDEX_PATH.
|
||||
ArgumentCaptor<String> url = ArgumentCaptor.forClass(String.class);
|
||||
verify(restTemplate).postForObject(url.capture(), any(), eq(indexResponseClass()));
|
||||
assertEquals(BASE_URL + "/index/notebook-source", url.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void index_filenameNull_utiliseNomParDefaut() throws Exception {
|
||||
Object wire = newIndexResponse(1, 1, 0);
|
||||
doReturn(wire).when(restTemplate)
|
||||
.postForObject(anyString(), any(), eq(indexResponseClass()));
|
||||
|
||||
// filename null/blank -> branche "source.pdf" du filePart.
|
||||
IndexResult result = client.index("src-1", new byte[]{9}, null);
|
||||
assertEquals(1, result.chunks());
|
||||
}
|
||||
|
||||
@Test
|
||||
void index_reponseNull_leveNotebookException() {
|
||||
when(restTemplate.postForObject(anyString(), any(), any(Class.class)))
|
||||
.thenReturn(null);
|
||||
|
||||
NotebookException ex = assertThrows(NotebookException.class,
|
||||
() -> client.index("src-1", new byte[]{1}, "f.pdf"));
|
||||
assertTrue(ex.getMessage().contains("vide"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void index_resourceAccess_leveNotebookException() {
|
||||
when(restTemplate.postForObject(anyString(), any(), any(Class.class)))
|
||||
.thenThrow(new ResourceAccessException("timeout"));
|
||||
|
||||
NotebookException ex = assertThrows(NotebookException.class,
|
||||
() -> client.index("src-1", new byte[]{1}, "f.pdf"));
|
||||
assertTrue(ex.getMessage().contains("injoignable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void index_httpServerError_leveNotebookExceptionAvecStatut() {
|
||||
HttpServerErrorException http = HttpServerErrorException.create(
|
||||
HttpStatus.BAD_GATEWAY, "Bad Gateway", new HttpHeaders(), new byte[0], null);
|
||||
when(restTemplate.postForObject(anyString(), any(), any(Class.class)))
|
||||
.thenThrow(http);
|
||||
|
||||
NotebookException ex = assertThrows(NotebookException.class,
|
||||
() -> client.index("src-1", new byte[]{1}, "f.pdf"));
|
||||
assertTrue(ex.getMessage().contains("502"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void index_erreurInattendue_leveNotebookException() {
|
||||
when(restTemplate.postForObject(anyString(), any(), any(Class.class)))
|
||||
.thenThrow(new IllegalStateException("boom"));
|
||||
|
||||
NotebookException ex = assertThrows(NotebookException.class,
|
||||
() -> client.index("src-1", new byte[]{1}, "f.pdf"));
|
||||
assertTrue(ex.getMessage().contains("inattendue"));
|
||||
}
|
||||
|
||||
// --- delete() ------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void delete_appelleRestTemplateAvecBonneUrl() {
|
||||
client.delete("src-99");
|
||||
verify(restTemplate).delete(BASE_URL + "/index/notebook-source/src-99");
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_erreurIgnoree_neRelancePas() {
|
||||
// Best-effort : une exception du RestTemplate est avalée (log warn).
|
||||
doThrow(new ResourceAccessException("down"))
|
||||
.when(restTemplate).delete(anyString());
|
||||
|
||||
// Ne doit pas lever.
|
||||
client.delete("src-99");
|
||||
verify(restTemplate).delete(BASE_URL + "/index/notebook-source/src-99");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.campaigncontext.RandomTableEntry;
|
||||
import com.loremind.domain.campaigncontext.ports.RandomTableGenerationException;
|
||||
import com.loremind.domain.campaigncontext.ports.RandomTableGenerator.GeneratedTable;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring) de {@link BrainRandomTableClient}.
|
||||
* Le RestTemplate est mocké : {@code postForObject(url, entity, Map.class)}.
|
||||
*/
|
||||
class BrainRandomTableClientTest {
|
||||
|
||||
private RestTemplate rt;
|
||||
private BrainRandomTableClient client;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rt = mock(RestTemplate.class);
|
||||
client = new BrainRandomTableClient(rt, "http://brain");
|
||||
}
|
||||
|
||||
/** Construit une map d'entrée pour le payload "entries". */
|
||||
private static Map<String, Object> entry(Object min, Object max, Object label, Object detail) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("min_roll", min);
|
||||
m.put("max_roll", max);
|
||||
m.put("label", label);
|
||||
m.put("detail", detail);
|
||||
return m;
|
||||
}
|
||||
|
||||
// ---------- generate : cas nominal et branches de parsing ----------
|
||||
|
||||
@Test
|
||||
void generate_reponseValide_plusieursEntrees_avecEntreesInvalidesIgnorees() {
|
||||
List<Object> entries = new ArrayList<>();
|
||||
entries.add(entry(1, 5, "Embuscade", "des gobelins")); // valide (Number)
|
||||
entries.add(entry("6", "10", "Trésor", null)); // valide (String -> asInt)
|
||||
entries.add(entry(null, 3, "min null", "x")); // ignorée : min null
|
||||
entries.add(entry(3, null, "max null", "x")); // ignorée : max null
|
||||
entries.add(entry(1, 2, null, "x")); // ignorée : label null
|
||||
entries.add(entry(1, 2, " ", "x")); // ignorée : label blank
|
||||
entries.add(entry("abc", 2, "min non-num", "x")); // ignorée : asInt String non-numérique
|
||||
entries.add("pas une map"); // ignorée : item non-Map
|
||||
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("name", "Table des rencontres");
|
||||
resp.put("description", "En forêt");
|
||||
resp.put("entries", entries);
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
GeneratedTable table = client.generate("desc", "1d10", "ctx");
|
||||
|
||||
assertEquals("Table des rencontres", table.name());
|
||||
assertEquals("En forêt", table.description());
|
||||
assertEquals(2, table.entries().size());
|
||||
|
||||
RandomTableEntry e0 = table.entries().get(0);
|
||||
assertEquals(1, e0.getMinRoll());
|
||||
assertEquals(5, e0.getMaxRoll());
|
||||
assertEquals("Embuscade", e0.getLabel());
|
||||
assertEquals("des gobelins", e0.getDetail());
|
||||
|
||||
RandomTableEntry e1 = table.entries().get(1);
|
||||
assertEquals(6, e1.getMinRoll());
|
||||
assertEquals(10, e1.getMaxRoll());
|
||||
assertEquals("Trésor", e1.getLabel());
|
||||
assertNull(e1.getDetail()); // detail null -> asString(null) == null
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_maxInferieurAMin_estCorrigeParMathMax() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("entries", List.of(entry(8, 3, "Inversé", null)));
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
GeneratedTable table = client.generate("d", "1d8", "c");
|
||||
RandomTableEntry e = table.entries().get(0);
|
||||
assertEquals(8, e.getMinRoll());
|
||||
assertEquals(8, e.getMaxRoll()); // Math.max(8,3) == 8
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_nameAbsent_fallbackSurDescription() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("entries", List.of(entry(1, 1, "Ok", null)));
|
||||
// pas de "name" -> asString(null) == null -> fallback description
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
GeneratedTable table = client.generate("MaDescription", "1d20", "c");
|
||||
assertEquals("MaDescription", table.name());
|
||||
assertNull(table.description()); // description absente
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_nameBlank_fallbackSurDescription() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("name", " ");
|
||||
resp.put("entries", List.of(entry(1, 1, "Ok", null)));
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
GeneratedTable table = client.generate("Fallback", "1d20", "c");
|
||||
assertEquals("Fallback", table.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_argumentsNull_remplisParDefauts_etAppelle() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("name", "T");
|
||||
resp.put("entries", List.of(entry(1, 1, "Ok", null)));
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
// description/diceFormula/context null -> branches de défaut couvertes
|
||||
GeneratedTable table = client.generate(null, null, null);
|
||||
assertEquals("T", table.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_reponseNull_leveException() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(null);
|
||||
|
||||
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||
() -> client.generate("d", "1d20", "c"));
|
||||
assertTrue(ex.getMessage().contains("réponse vide"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_entriesAbsentes_aucuneEntree_leveException() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("name", "T");
|
||||
// pas de "entries" -> rawEntries null, pas un List<?>
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||
() -> client.generate("d", "1d20", "c"));
|
||||
assertTrue(ex.getMessage().contains("Aucune entrée"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_entriesVide_leveException() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("entries", new ArrayList<>()); // List mais vide
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||
() -> client.generate("d", "1d20", "c"));
|
||||
assertTrue(ex.getMessage().contains("Aucune entrée"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_toutesEntreesInvalides_leveException() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("entries", List.of(entry(null, null, null, null)));
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
assertThrows(RandomTableGenerationException.class,
|
||||
() -> client.generate("d", "1d20", "c"));
|
||||
}
|
||||
|
||||
// ---------- generate : branches du catch ----------
|
||||
|
||||
@Test
|
||||
void generate_brainInjoignable_resourceAccess() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||
.thenThrow(new ResourceAccessException("down"));
|
||||
|
||||
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||
() -> client.generate("d", "1d20", "c"));
|
||||
assertTrue(ex.getMessage().contains("injoignable"));
|
||||
assertInstanceOf(ResourceAccessException.class, ex.getCause());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_erreurHttp_restClientResponse() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||
.thenThrow(HttpServerErrorException.create(
|
||||
HttpStatus.BAD_GATEWAY, "Bad Gateway", new HttpHeaders(), new byte[0], null));
|
||||
|
||||
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||
() -> client.generate("d", "1d20", "c"));
|
||||
assertTrue(ex.getMessage().contains("HTTP 502"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_erreurInattendue_exceptionGenerique() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||
.thenThrow(new IllegalStateException("boom"));
|
||||
|
||||
RandomTableGenerationException ex = assertThrows(RandomTableGenerationException.class,
|
||||
() -> client.generate("d", "1d20", "c"));
|
||||
assertTrue(ex.getMessage().contains("inattendue"));
|
||||
assertInstanceOf(IllegalStateException.class, ex.getCause());
|
||||
}
|
||||
|
||||
// ---------- improvise ----------
|
||||
|
||||
@Test
|
||||
void improvise_narrationPresente_retourneNarration() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("narration", "Les gobelins surgissent des fourrés.");
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
String out = client.improvise("Table", "Embuscade", "détail", "ctx");
|
||||
assertEquals("Les gobelins surgissent des fourrés.", out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void improvise_argumentsNull_remplisParDefauts() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("narration", "ok");
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
assertEquals("ok", client.improvise(null, null, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void improvise_reponseNull_retourneChaineVide() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(null);
|
||||
|
||||
assertEquals("", client.improvise("T", "L", "D", "C"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void improvise_narrationAbsente_retourneChaineVide() {
|
||||
Map<String, Object> resp = new LinkedHashMap<>(); // pas de "narration"
|
||||
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class))).thenReturn(resp);
|
||||
|
||||
assertEquals("", client.improvise("T", "L", "D", "C"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void improvise_brainInjoignable_propageException() {
|
||||
when(rt.postForObject(anyString(), any(), eq(Map.class)))
|
||||
.thenThrow(new ResourceAccessException("down"));
|
||||
|
||||
assertThrows(RandomTableGenerationException.class,
|
||||
() -> client.improvise("T", "L", "D", "C"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportProgress;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportResult;
|
||||
import com.loremind.domain.gamesystemcontext.ports.RulesImportException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests unitaires purs (JUnit 5 + Mockito, sans Spring/réseau) de
|
||||
* {@link BrainRulesImportClient} :
|
||||
* - one-shot via RestTemplate (importRules) ;
|
||||
* - streaming SSE via WebClient + ExchangeFunction (importRulesStreaming).
|
||||
* Couvre aussi indirectement les getters du DTO {@link BrainRulesImportResponse}.
|
||||
*/
|
||||
class BrainRulesImportClientTest {
|
||||
|
||||
private static final String BASE_URL = "http://brain";
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
restTemplate = mock(RestTemplate.class);
|
||||
objectMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
/** Construit le client avec un WebClient câblé sur l'ExchangeFunction fournie. */
|
||||
private BrainRulesImportClient client(ExchangeFunction ef) {
|
||||
WebClient.Builder builder = WebClient.builder().exchangeFunction(ef);
|
||||
return new BrainRulesImportClient(restTemplate, builder, objectMapper, BASE_URL, 30);
|
||||
}
|
||||
|
||||
/** Client one-shot : l'ExchangeFunction n'est jamais utilisée. */
|
||||
private BrainRulesImportClient oneShotClient() {
|
||||
return client(req -> Mono.empty());
|
||||
}
|
||||
|
||||
// --- One-shot (RestTemplate) --------------------------------------------
|
||||
|
||||
@Test
|
||||
void importRules_succes_retourneResultatEtCouvreGettersDuDto() {
|
||||
BrainRulesImportResponse wire = new BrainRulesImportResponse();
|
||||
wire.setSections(Map.of("Combat", "## Combat"));
|
||||
wire.setPageCount(12);
|
||||
wire.setOcrPageCount(3);
|
||||
// Couvre aussi les getters Lombok du DTO.
|
||||
assertEquals(Map.of("Combat", "## Combat"), wire.getSections());
|
||||
assertEquals(12, wire.getPageCount());
|
||||
assertEquals(3, wire.getOcrPageCount());
|
||||
|
||||
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||
.thenReturn(wire);
|
||||
|
||||
RulesImportResult result = oneShotClient().importRules(new byte[]{1, 2, 3}, "regles.pdf");
|
||||
|
||||
assertEquals(Map.of("Combat", "## Combat"), result.sections());
|
||||
assertEquals(12, result.pageCount());
|
||||
assertEquals(3, result.ocrPageCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_filenameNull_utiliseNomParDefaut() {
|
||||
BrainRulesImportResponse wire = new BrainRulesImportResponse();
|
||||
wire.setSections(Map.of("A", "x"));
|
||||
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||
.thenReturn(wire);
|
||||
|
||||
// filename null -> branche du filePart anonyme (getFilename par défaut).
|
||||
RulesImportResult result = oneShotClient().importRules(new byte[]{9}, null);
|
||||
assertEquals(1, result.sections().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_reponseNull_leveRulesImportException() {
|
||||
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||
.thenReturn(null);
|
||||
|
||||
RulesImportException ex = assertThrows(RulesImportException.class,
|
||||
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||
assertTrue(ex.getMessage().contains("vide"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_sectionsNull_leveRulesImportException() {
|
||||
BrainRulesImportResponse wire = new BrainRulesImportResponse();
|
||||
wire.setSections(null);
|
||||
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||
.thenReturn(wire);
|
||||
|
||||
assertThrows(RulesImportException.class,
|
||||
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_resourceAccess_leveRulesImportException() {
|
||||
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||
.thenThrow(new ResourceAccessException("timeout"));
|
||||
|
||||
RulesImportException ex = assertThrows(RulesImportException.class,
|
||||
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||
assertTrue(ex.getMessage().contains("injoignable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_httpServerError_leveRulesImportExceptionAvecStatut() {
|
||||
HttpServerErrorException http = HttpServerErrorException.create(
|
||||
HttpStatus.BAD_GATEWAY, "Bad Gateway", new HttpHeaders(), new byte[0], null);
|
||||
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||
.thenThrow(http);
|
||||
|
||||
RulesImportException ex = assertThrows(RulesImportException.class,
|
||||
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||
assertTrue(ex.getMessage().contains("502"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_erreurInattendue_leveRulesImportException() {
|
||||
when(restTemplate.postForObject(anyString(), any(), eq(BrainRulesImportResponse.class)))
|
||||
.thenThrow(new IllegalStateException("boom"));
|
||||
|
||||
RulesImportException ex = assertThrows(RulesImportException.class,
|
||||
() -> oneShotClient().importRules(new byte[]{1}, "r.pdf"));
|
||||
assertTrue(ex.getMessage().contains("inattendue"));
|
||||
}
|
||||
|
||||
// --- Collecteur de callbacks pour le streaming --------------------------
|
||||
|
||||
private static final class Collector {
|
||||
final List<RulesImportProgress> progress = new ArrayList<>();
|
||||
final AtomicInteger heartbeats = new AtomicInteger();
|
||||
final List<String> statuses = new ArrayList<>();
|
||||
final AtomicReference<RulesImportResult> done = new AtomicReference<>();
|
||||
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
}
|
||||
|
||||
private void runStreaming(String sse, Collector c) {
|
||||
ExchangeFunction ef = req -> Mono.just(
|
||||
ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sse)
|
||||
.build());
|
||||
client(ef).importRulesStreaming(
|
||||
new byte[]{1, 2}, "r.pdf",
|
||||
c.progress::add,
|
||||
c.heartbeats::incrementAndGet,
|
||||
c.statuses::add,
|
||||
c.done::set,
|
||||
c.error::set);
|
||||
}
|
||||
|
||||
// --- Streaming (WebClient + SSE) ----------------------------------------
|
||||
|
||||
@Test
|
||||
void streaming_tousLesEvenements_declenchentLesBonsCallbacks() {
|
||||
String sse =
|
||||
"event:extracting\ndata:{}\n\n" +
|
||||
"event:start\ndata:{\"total\":2,\"page_count\":10,\"ocr_page_count\":1}\n\n" +
|
||||
"event:progress\ndata:{\"current\":1,\"total\":2,\"new_sections\":[\"Combat\"]}\n\n" +
|
||||
"event:heartbeat\ndata:{}\n\n" +
|
||||
"event:status\ndata:{\"message\":\"retry\"}\n\n" +
|
||||
"event:chunk_failed\ndata:{\"current\":2,\"total\":2,\"message\":\"timeout\"}\n\n" +
|
||||
"event:done\ndata:{\"sections\":{\"Combat\":\"## Combat\"},\"page_count\":10,\"ocr_page_count\":1}\n\n";
|
||||
|
||||
Collector c = new Collector();
|
||||
runStreaming(sse, c);
|
||||
|
||||
// extracting -> progress(0,0,0,0,[]) ; start -> progress(0,2,10,1,[]) ; progress -> progress(1,2,10,1,[Combat])
|
||||
assertEquals(3, c.progress.size());
|
||||
|
||||
RulesImportProgress extracting = c.progress.get(0);
|
||||
assertEquals(0, extracting.total());
|
||||
assertTrue(extracting.newSectionTitles().isEmpty());
|
||||
|
||||
RulesImportProgress start = c.progress.get(1);
|
||||
assertEquals(0, start.current());
|
||||
assertEquals(2, start.total());
|
||||
assertEquals(10, start.pageCount());
|
||||
assertEquals(1, start.ocrPageCount());
|
||||
|
||||
RulesImportProgress prog = c.progress.get(2);
|
||||
assertEquals(1, prog.current());
|
||||
assertEquals(2, prog.total());
|
||||
assertEquals(10, prog.pageCount());
|
||||
assertEquals(1, prog.ocrPageCount());
|
||||
assertEquals(List.of("Combat"), prog.newSectionTitles());
|
||||
|
||||
assertEquals(1, c.heartbeats.get());
|
||||
|
||||
// status (readMessage -> "retry") + chunk_failed (statut formaté).
|
||||
assertEquals(2, c.statuses.size());
|
||||
assertEquals("retry", c.statuses.get(0));
|
||||
assertTrue(c.statuses.get(1).contains("Morceau 2/2"));
|
||||
assertTrue(c.statuses.get(1).contains("timeout"));
|
||||
|
||||
assertNotNull(c.done.get());
|
||||
assertEquals(Map.of("Combat", "## Combat"), c.done.get().sections());
|
||||
assertEquals(10, c.done.get().pageCount());
|
||||
assertEquals(1, c.done.get().ocrPageCount());
|
||||
|
||||
// done a positionné terminated -> pas d'onError.
|
||||
assertEquals(null, c.error.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming_evenementError_appelleOnError() {
|
||||
String sse = "event:error\ndata:{\"message\":\"LLM saturé\"}\n\n";
|
||||
Collector c = new Collector();
|
||||
runStreaming(sse, c);
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertTrue(c.error.get() instanceof RulesImportException);
|
||||
assertTrue(c.error.get().getMessage().contains("LLM saturé"));
|
||||
assertNull(c.done.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming_chunkFailedSansMessage_statutAvecPoint() {
|
||||
// node sans champ "message" -> branche "." finale.
|
||||
String sse = "event:chunk_failed\ndata:{\"current\":1,\"total\":3}\n\n";
|
||||
Collector c = new Collector();
|
||||
runStreaming(sse, c);
|
||||
|
||||
assertEquals(1, c.statuses.size());
|
||||
assertTrue(c.statuses.get(0).contains("Morceau 1/3 ignoré."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming_statusDataNonJson_readMessageRenvoieDataBrut() {
|
||||
// data non-JSON -> readJson renvoie null -> readMessage retourne le data brut.
|
||||
String sse = "event:status\ndata:texte brut\n\n";
|
||||
Collector c = new Collector();
|
||||
runStreaming(sse, c);
|
||||
|
||||
assertEquals(1, c.statuses.size());
|
||||
assertEquals("texte brut", c.statuses.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming_evenementInconnuAvecDataNonJson_estIgnore() {
|
||||
// Pas heartbeat/status/chunk_failed/error/extracting, et readJson==null -> return.
|
||||
String sse = "event:mystere\ndata:pas du json\n\n";
|
||||
Collector c = new Collector();
|
||||
runStreaming(sse, c);
|
||||
|
||||
assertTrue(c.progress.isEmpty());
|
||||
assertTrue(c.statuses.isEmpty());
|
||||
// Aucun done/error -> flux interrompu -> onError.
|
||||
assertNotNull(c.error.get());
|
||||
assertTrue(c.error.get().getMessage().contains("interrompu"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming_finSansDoneNiError_signaleFluxInterrompu() {
|
||||
// Que des heartbeats : pas de done/error -> branche "flux interrompu".
|
||||
String sse = "event:heartbeat\ndata:{}\n\n";
|
||||
Collector c = new Collector();
|
||||
runStreaming(sse, c);
|
||||
|
||||
assertEquals(1, c.heartbeats.get());
|
||||
assertNotNull(c.error.get());
|
||||
assertTrue(c.error.get() instanceof RulesImportException);
|
||||
assertTrue(c.error.get().getMessage().contains("interrompu"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming_erreurTransport_appelleOnErrorAvecCauseExposee() {
|
||||
ExchangeFunction ef = req -> Mono.error(new RuntimeException("boom"));
|
||||
Collector c = new Collector();
|
||||
client(ef).importRulesStreaming(
|
||||
new byte[]{1}, "r.pdf",
|
||||
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add,
|
||||
c.done::set, c.error::set);
|
||||
|
||||
assertNotNull(c.error.get());
|
||||
assertTrue(c.error.get() instanceof RulesImportException);
|
||||
// La cause réelle (type + message) est exposée dans le message.
|
||||
assertTrue(c.error.get().getMessage().contains("boom"));
|
||||
assertNotNull(c.error.get().getCause());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming_filenameVide_utiliseNomParDefautSansErreur() {
|
||||
// filename vide -> branches "rules.pdf" du filePart et du part().filename().
|
||||
String sse = "event:done\ndata:{\"sections\":{},\"page_count\":0,\"ocr_page_count\":0}\n\n";
|
||||
Collector c = new Collector();
|
||||
ExchangeFunction ef = req -> Mono.just(
|
||||
ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sse)
|
||||
.build());
|
||||
client(ef).importRulesStreaming(
|
||||
new byte[]{1}, " ",
|
||||
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add,
|
||||
c.done::set, c.error::set);
|
||||
|
||||
assertNotNull(c.done.get());
|
||||
assertTrue(c.done.get().sections().isEmpty());
|
||||
assertNull(c.error.get());
|
||||
}
|
||||
|
||||
// petits helpers d'assertion null/non-null (évite import statique supplémentaire)
|
||||
private static void assertNull(Object o) {
|
||||
assertTrue(o == null, "attendu null");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.application.generationcontext.StreamChatForCampaignUseCase;
|
||||
import com.loremind.application.generationcontext.StreamChatForLoreUseCase;
|
||||
import com.loremind.application.generationcontext.StreamChatForSessionUseCase;
|
||||
import com.loremind.domain.generationcontext.ChatMessage;
|
||||
import com.loremind.domain.generationcontext.ChatUsage;
|
||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatMessageDTO;
|
||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamCampaignRequestDTO;
|
||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamRequestDTO;
|
||||
import com.loremind.infrastructure.web.dto.generationcontext.ChatStreamSessionRequestDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link AiChatController} (chat IA streame en SSE).
|
||||
* <p>
|
||||
* Les trois use cases ({@link StreamChatForLoreUseCase},
|
||||
* {@link StreamChatForCampaignUseCase}, {@link StreamChatForSessionUseCase}) sont
|
||||
* mockes : sinon chaque test ferait un vrai appel au Brain (indisponible en test).
|
||||
* <p>
|
||||
* Le {@code TaskExecutor} ("applicationTaskExecutor") est mocke pour executer la
|
||||
* tache de streaming EN LIGNE (synchrone) : tous les events SSE sont ecrits avant
|
||||
* le retour du controleur, ce qui rend les assertions sur le flux deterministes.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class AiChatControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
|
||||
@MockBean private StreamChatForLoreUseCase loreUseCase;
|
||||
@MockBean private StreamChatForCampaignUseCase campaignUseCase;
|
||||
@MockBean private StreamChatForSessionUseCase sessionUseCase;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Tache de streaming executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private MvcResult perform(String url, Object body) throws Exception {
|
||||
return mockMvc.perform(post(url)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(body)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
// --- /chat/stream (Lore) ------------------------------------------------
|
||||
|
||||
@Test
|
||||
void chatStream_streamsUsageTokenDone() throws Exception {
|
||||
// Le use case mocke joue : usage -> 1 token -> fin.
|
||||
doAnswer(inv -> {
|
||||
Consumer<ChatUsage> onUsage = inv.getArgument(3);
|
||||
Consumer<String> onToken = inv.getArgument(4);
|
||||
Runnable onComplete = inv.getArgument(5);
|
||||
onUsage.accept(new ChatUsage(10, 20, 30, 8000));
|
||||
onToken.accept("Bonjour");
|
||||
onComplete.run();
|
||||
return null;
|
||||
}).when(loreUseCase).execute(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamRequestDTO body = new ChatStreamRequestDTO();
|
||||
body.setLoreId("lore-1");
|
||||
body.setMessages(List.of(new ChatMessageDTO("user", "Salut ?")));
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream", body);
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("\"system\":10")))
|
||||
.andExpect(content().string(containsString("\"max\":8000")))
|
||||
.andExpect(content().string(containsString("Bonjour")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_passesDomainMessagesToUseCase() throws Exception {
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(5)).run(); return null; })
|
||||
.when(loreUseCase).execute(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamRequestDTO body = new ChatStreamRequestDTO();
|
||||
body.setLoreId("lore-1");
|
||||
body.setPageId("page-9");
|
||||
body.setMessages(List.of(
|
||||
new ChatMessageDTO("user", "Q1"),
|
||||
new ChatMessageDTO("assistant", "R1")));
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream", body);
|
||||
mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
org.mockito.ArgumentCaptor<List<ChatMessage>> captor =
|
||||
org.mockito.ArgumentCaptor.forClass(List.class);
|
||||
verify(loreUseCase).execute(
|
||||
org.mockito.ArgumentMatchers.eq("lore-1"),
|
||||
org.mockito.ArgumentMatchers.eq("page-9"),
|
||||
captor.capture(), any(), any(), any(), any());
|
||||
List<ChatMessage> passed = captor.getValue();
|
||||
org.junit.jupiter.api.Assertions.assertEquals(2, passed.size());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("user", passed.get(0).role());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("Q1", passed.get(0).content());
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_useCaseInvokesError_emitsError() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException("brain HS"));
|
||||
return null;
|
||||
}).when(loreUseCase).execute(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamRequestDTO body = new ChatStreamRequestDTO();
|
||||
body.setLoreId("lore-1");
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("brain HS")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_useCaseThrows_emitsError() throws Exception {
|
||||
// Lore introuvable -> le use case leve, le controller catch et fail(emitter).
|
||||
doThrow(new IllegalArgumentException("Lore introuvable"))
|
||||
.when(loreUseCase).execute(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamRequestDTO body = new ChatStreamRequestDTO();
|
||||
body.setLoreId("missing");
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Lore introuvable")));
|
||||
}
|
||||
|
||||
// --- /chat/stream-campaign ----------------------------------------------
|
||||
|
||||
@Test
|
||||
void chatStreamCampaign_streamsTokenThenDone() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onToken = inv.getArgument(5);
|
||||
Runnable onComplete = inv.getArgument(6);
|
||||
onToken.accept("Campagne");
|
||||
onComplete.run();
|
||||
return null;
|
||||
}).when(campaignUseCase).execute(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamCampaignRequestDTO body = new ChatStreamCampaignRequestDTO();
|
||||
body.setCampaignId("camp-1");
|
||||
body.setEntityType("scene");
|
||||
body.setEntityId("scene-3");
|
||||
body.setMessages(List.of(new ChatMessageDTO("user", "Aide")));
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream-campaign", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Campagne")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStreamCampaign_useCaseThrows_emitsError() throws Exception {
|
||||
doThrow(new IllegalArgumentException("Campagne introuvable"))
|
||||
.when(campaignUseCase).execute(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamCampaignRequestDTO body = new ChatStreamCampaignRequestDTO();
|
||||
body.setCampaignId("missing");
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream-campaign", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Campagne introuvable")));
|
||||
}
|
||||
|
||||
// --- /chat/stream-session -----------------------------------------------
|
||||
|
||||
@Test
|
||||
void chatStreamSession_streamsTokenThenDone() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onToken = inv.getArgument(3);
|
||||
Runnable onComplete = inv.getArgument(4);
|
||||
onToken.accept("Session");
|
||||
onComplete.run();
|
||||
return null;
|
||||
}).when(sessionUseCase).execute(any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamSessionRequestDTO body = new ChatStreamSessionRequestDTO();
|
||||
body.setSessionId("sess-1");
|
||||
body.setMessages(List.of(new ChatMessageDTO("user", "Resume")));
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream-session", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Session")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStreamSession_useCaseThrows_emitsError() throws Exception {
|
||||
doThrow(new IllegalArgumentException("Session introuvable"))
|
||||
.when(sessionUseCase).execute(any(), any(), any(), any(), any(), any());
|
||||
|
||||
ChatStreamSessionRequestDTO body = new ChatStreamSessionRequestDTO();
|
||||
body.setSessionId("missing");
|
||||
|
||||
MvcResult result = perform("/api/ai/chat/stream-session", body);
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Session introuvable")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.CampaignAdaptService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link CampaignAdaptController} (conseil PDF -> campagne, SSE).
|
||||
* <p>
|
||||
* Le {@link CampaignAdaptService} est mocke : il appelle le Brain (indisponible en
|
||||
* test). Le {@code TaskExecutor} ("applicationTaskExecutor") est mocke pour executer
|
||||
* la tache de streaming EN LIGNE -> events SSE deterministes.
|
||||
* <p>
|
||||
* Signature de {@code adviseStreaming(campaignId, pdfBytes, filename, messagesJson,
|
||||
* onToken, onComplete, onError)} : indices des callbacks -> onToken=4, onComplete=5,
|
||||
* onError=6.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class CampaignAdaptControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@MockBean private CampaignAdaptService campaignAdaptService;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Tache de streaming executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private MockMultipartFile pdf(byte[] content) {
|
||||
return new MockMultipartFile("file", "aventure.pdf", "application/pdf", content);
|
||||
}
|
||||
|
||||
private MvcResult perform(MockMultipartFile file) throws Exception {
|
||||
return mockMvc.perform(multipart("/api/campaigns/{id}/adapt-pdf/stream", "camp-1")
|
||||
.file(file)
|
||||
.param("messages", "[]"))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
void adaptStream_streamsTokenThenDone() throws Exception {
|
||||
// Le service mocke joue : 1 token -> fin.
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onToken = inv.getArgument(4);
|
||||
Runnable onComplete = inv.getArgument(5);
|
||||
onToken.accept("Conseil markdown");
|
||||
onComplete.run();
|
||||
return null;
|
||||
}).when(campaignAdaptService).adviseStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = perform(pdf("%PDF-1.4 fake".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Conseil markdown")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adaptStream_serviceInvokesError_emitsError() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException("brain HS"));
|
||||
return null;
|
||||
}).when(campaignAdaptService).adviseStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = perform(pdf("%PDF-1.4 fake".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("brain HS")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adaptStream_campaignMissing_emitsError() throws Exception {
|
||||
// Le service leve IllegalArgumentException -> le controller catch et envoie "Campagne introuvable.".
|
||||
doThrow(new IllegalArgumentException("Campagne introuvable : camp-1"))
|
||||
.when(campaignAdaptService).adviseStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = perform(pdf("%PDF-1.4 fake".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("Campagne introuvable")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adaptStream_emptyFile_emitsError_withoutCallingService() throws Exception {
|
||||
// Fichier vide : branche court-circuit, le service n'est jamais appele.
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/adapt-pdf/stream", "camp-1")
|
||||
.file(new MockMultipartFile("file", "vide.pdf", "application/pdf", new byte[0])))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("Fichier PDF vide")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Prerequisite;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration de {@link CampaignFlagController}.
|
||||
* Unique endpoint : list (GET) qui déduplique les noms de faits (Prerequisite.FlagSet)
|
||||
* référencés dans les prérequis des chapitres de la campagne.
|
||||
* Fixtures : campaign -> arc -> chapters avec prérequis FlagSet.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class CampaignFlagControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private ArcRepository arcRepository;
|
||||
@Autowired private ChapterRepository chapterRepository;
|
||||
|
||||
private String campaignId;
|
||||
private String arcId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Chaîne de fixtures : campaign -> arc
|
||||
campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
arcId = arcRepository.save(Arc.builder().campaignId(campaignId).name("A").order(0).build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsEmptyArray_whenNoFlagPrerequisites() throws Exception {
|
||||
// Chapitre sans prérequis FlagSet => aucun fait référencé
|
||||
chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch").order(0).build());
|
||||
mockMvc.perform(get("/api/campaigns/{cid}/flags", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$.length()").value(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsDeduplicatedSortedFlagNames() throws Exception {
|
||||
// Deux chapitres référençant des FlagSet, avec un doublon "alpha"
|
||||
chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch1").order(0)
|
||||
.prerequisites(List.of(
|
||||
new Prerequisite.FlagSet("zeta"),
|
||||
new Prerequisite.FlagSet("alpha")))
|
||||
.build());
|
||||
chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch2").order(1)
|
||||
.prerequisites(List.of(
|
||||
new Prerequisite.FlagSet("alpha"), // doublon
|
||||
new Prerequisite.QuestCompleted("q-1"))) // ignoré (pas un FlagSet)
|
||||
.build());
|
||||
|
||||
mockMvc.perform(get("/api/campaigns/{cid}/flags", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$.length()").value(2))
|
||||
// TreeSet => tri alphabétique : alpha avant zeta
|
||||
.andExpect(jsonPath("$[0]").value("alpha"))
|
||||
.andExpect(jsonPath("$[1]").value("zeta"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsEmptyArray_forUnknownCampaign() throws Exception {
|
||||
// Campagne sans arcs => liste vide (pas d'erreur)
|
||||
mockMvc.perform(get("/api/campaigns/{cid}/flags", "999999999"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$.length()").value(0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.application.campaigncontext.CampaignImportService;
|
||||
import com.loremind.application.campaigncontext.CampaignImportService.ApplyResult;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link CampaignImportController} (import PDF -> arbre).
|
||||
* <p>
|
||||
* Le {@link CampaignImportService} est mocke : son {@code importStructureStreaming}
|
||||
* delegue sinon au Brain Python (indisponible en test) et {@code applyStructure}
|
||||
* persiste en base. On controle ici les callbacks (progress / done / error) du
|
||||
* streaming et le mapping HTTP du apply.
|
||||
* <p>
|
||||
* Le {@code TaskExecutor} ("applicationTaskExecutor") est mocke pour executer la
|
||||
* tache d'import EN LIGNE (synchrone) : tous les events SSE sont ecrits avant le
|
||||
* retour du controleur, rendant les assertions sur le flux deterministes.
|
||||
* <p>
|
||||
* Indices des callbacks de
|
||||
* {@link CampaignImportService#importStructureStreaming} :
|
||||
* (0) pdfBytes, (1) filename, (2) onProgress, (3) onHeartbeat, (4) onStatus,
|
||||
* (5) onDone, (6) onError.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class CampaignImportControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
|
||||
@MockBean private CampaignImportService campaignImportService;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
private static final String CAMPAIGN_ID = "camp-1";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Tache d'import executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private MockMultipartFile pdf(byte[] bytes) {
|
||||
return new MockMultipartFile("file", "campagne.pdf", "application/pdf", bytes);
|
||||
}
|
||||
|
||||
// --- POST /stream (SSE) ------------------------------------------------
|
||||
|
||||
@Test
|
||||
void importStream_emptyFile_emitsError() throws Exception {
|
||||
MockMultipartFile empty = pdf(new byte[0]);
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID).file(empty))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("vide")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_happyPath_streamsDone() throws Exception {
|
||||
// Le service mocke joue : onDone avec une proposition vide.
|
||||
doAnswer(inv -> {
|
||||
Consumer<CampaignImportProposal> onDone = inv.getArgument(5);
|
||||
onDone.accept(new CampaignImportProposal(List.of(), List.of()));
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_serviceError_emitsError() throws Exception {
|
||||
// Le service mocke joue : onError avec un message.
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException("Brain injoignable"));
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("Brain injoignable")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_thrownException_emitsError() throws Exception {
|
||||
// Le service leve directement (catch general du controleur).
|
||||
doAnswer(inv -> { throw new RuntimeException("boom extraction"); })
|
||||
.when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("boom extraction")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_progressAndStatus_streamedBeforeDone() throws Exception {
|
||||
// Joue la sequence complete des callbacks intermediaires (progress / status /
|
||||
// heartbeat) puis onDone -> couvre sendEvent("progress"), sendEvent("status")
|
||||
// et sendHeartbeat (helpers SSE non touches par les tests precedents).
|
||||
doAnswer(inv -> {
|
||||
Consumer<CampaignImportProgress> onProgress = inv.getArgument(2);
|
||||
Runnable onHeartbeat = inv.getArgument(3);
|
||||
Consumer<String> onStatus = inv.getArgument(4);
|
||||
Consumer<CampaignImportProposal> onDone = inv.getArgument(5);
|
||||
onProgress.accept(new CampaignImportProgress(2, 10, 5, 1, 1, 2, 3, 4));
|
||||
onStatus.accept("Analyse en cours");
|
||||
onHeartbeat.run();
|
||||
onDone.accept(new CampaignImportProposal(List.of(), List.of()));
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("progress")))
|
||||
.andExpect(content().string(containsString("status")))
|
||||
.andExpect(content().string(containsString("Analyse en cours")))
|
||||
.andExpect(content().string(containsString("keepalive")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_nullStatus_emitsEmptyMessage() throws Exception {
|
||||
// onStatus(null) -> branche "status != null ? status : \"\"" du controleur.
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onStatus = inv.getArgument(4);
|
||||
Consumer<CampaignImportProposal> onDone = inv.getArgument(5);
|
||||
onStatus.accept(null);
|
||||
onDone.accept(new CampaignImportProposal(List.of(), List.of()));
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("status")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_nullErrorMessage_emitsFallbackMessage() throws Exception {
|
||||
// onError avec un message null -> sendError utilise "Erreur inconnue.".
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException()); // getMessage() == null
|
||||
return null;
|
||||
}).when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Erreur inconnue")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_serviceThrows_emitsError() throws Exception {
|
||||
// Le service LEVE (au lieu d'invoquer onError) : le catch(Exception) du
|
||||
// controleur relaie le message via sendError.
|
||||
doThrow(new RuntimeException("panne interne"))
|
||||
.when(campaignImportService).importStructureStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/campaigns/{id}/import-structure/stream", CAMPAIGN_ID)
|
||||
.file(pdf(new byte[]{1, 2, 3})))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("panne interne")));
|
||||
}
|
||||
|
||||
// --- POST /apply -------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void apply_returns200_withSummary() throws Exception {
|
||||
when(campaignImportService.applyStructure(eq(CAMPAIGN_ID), any()))
|
||||
.thenReturn(new ApplyResult(1, 2, 3, 4));
|
||||
CampaignImportProposal proposal = new CampaignImportProposal(List.of(), List.of());
|
||||
|
||||
mockMvc.perform(post("/api/campaigns/{id}/import-structure/apply", CAMPAIGN_ID)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(proposal)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.arcsCreated").value(1))
|
||||
.andExpect(jsonPath("$.chaptersCreated").value(2))
|
||||
.andExpect(jsonPath("$.scenesCreated").value(3))
|
||||
.andExpect(jsonPath("$.npcsCreated").value(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
void apply_returns404_whenCampaignMissing() throws Exception {
|
||||
when(campaignImportService.applyStructure(any(), any()))
|
||||
.thenThrow(new IllegalArgumentException("Campagne introuvable"));
|
||||
CampaignImportProposal proposal = new CampaignImportProposal(List.of(), List.of());
|
||||
|
||||
mockMvc.perform(post("/api/campaigns/{id}/import-structure/apply", CAMPAIGN_ID)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(proposal)))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.application.campaigncontext.CampaignImportService;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Test UNITAIRE pur (sans Spring) de {@link CampaignImportController} dédié au code
|
||||
* défensif de déconnexion du navigateur, INTESTABLE via MockMvc : là-bas, un envoi
|
||||
* SSE après {@code complete()} met l'emitter dans l'état « already completed » qui
|
||||
* remonte en {@code ServletException} (échec de test) au lieu d'exécuter la branche.
|
||||
* <p>
|
||||
* En instanciant le controller à la main (exécuteur en ligne, vrai ObjectMapper,
|
||||
* service mocké), on pilote directement la séquence : envoi initial → {@code complete()}
|
||||
* → un envoi ultérieur échoue et bascule {@code clientGone=true} → les callbacks
|
||||
* suivants empruntent alors les branches {@code ClientGoneException} / early-return.
|
||||
*/
|
||||
class CampaignImportControllerUnitTest {
|
||||
|
||||
private final CampaignImportService service = mock(CampaignImportService.class);
|
||||
/** Exécuteur synchrone : la tâche d'import tourne dans le thread du test. */
|
||||
private final TaskExecutor inlineExecutor = Runnable::run;
|
||||
private final CampaignImportController controller =
|
||||
new CampaignImportController(service, inlineExecutor, new ObjectMapper());
|
||||
|
||||
private static CampaignImportProgress progress() {
|
||||
return new CampaignImportProgress(1, 1, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStream_clientDisconnect_exercisesDefensiveBranches() throws Exception {
|
||||
// Scénario de déconnexion : on termine le flux puis on continue d'émettre.
|
||||
// Le 1er envoi post-complete échoue -> clientGone=true ; les callbacks suivants
|
||||
// court-circuitent (ClientGoneException sur sendEvent/sendHeartbeat, early-return
|
||||
// sur le callback d'erreur). Chaque étape est isolée car ClientGoneException
|
||||
// (privée) se propage hors des callbacks — comme en prod où elle remonte au
|
||||
// pipeline amont pour stopper le Brain.
|
||||
doAnswer(inv -> {
|
||||
Consumer<CampaignImportProgress> onProgress = inv.getArgument(2);
|
||||
Runnable onHeartbeat = inv.getArgument(3);
|
||||
Consumer<CampaignImportProposal> onDone = inv.getArgument(5);
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
|
||||
// 1) Termine proprement le flux (event "done" + complete()).
|
||||
onDone.accept(new CampaignImportProposal(List.of(), List.of()));
|
||||
// 2) Envoi post-complete : send échoue -> catch -> clientGone=true.
|
||||
try { onProgress.accept(progress()); } catch (RuntimeException ignored) { }
|
||||
// 3) clientGone=true -> sendHeartbeat lève ClientGoneException (branche garde).
|
||||
try { onHeartbeat.run(); } catch (RuntimeException ignored) { }
|
||||
// 4) clientGone=true -> sendEvent lève ClientGoneException (branche garde).
|
||||
try { onProgress.accept(progress()); } catch (RuntimeException ignored) { }
|
||||
// 5) clientGone=true -> le callback d'erreur prend l'early-return (pas d'envoi).
|
||||
onError.accept(new RuntimeException("tardif"));
|
||||
return null;
|
||||
}).when(service).importStructureStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "campagne.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
SseEmitter emitter = controller.importStream("camp-1", file);
|
||||
|
||||
assertNotNull(emitter);
|
||||
verify(service).importStructureStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ChapterDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -34,13 +36,18 @@ class ChapterControllerTest {
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private ArcRepository arcRepository;
|
||||
@Autowired private ChapterRepository chapterRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
|
||||
private String arcId;
|
||||
private String playthroughId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
String campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
arcId = arcRepository.save(Arc.builder().campaignId(campaignId).name("A").order(0).build()).getId();
|
||||
// playthroughId REEL (id numerique) : l'enrichissement du statut le parse.
|
||||
playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campaignId).name("Table").description("").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -106,4 +113,52 @@ class ChapterControllerTest {
|
||||
mockMvc.perform(delete("/api/chapters/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// getById avec ?playthroughId= : branche d'enrichissement du statut.
|
||||
// Le playthrough est inexistant -> snapshot vide -> statut NOT_STARTED, mais la branche est couverte.
|
||||
@Test
|
||||
void getById_withPlaythroughId_enrichesStatus() throws Exception {
|
||||
Chapter saved = chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch").order(0).build());
|
||||
mockMvc.perform(get("/api/chapters/{id}", saved.getId()).param("playthroughId", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.progressionStatus").value("NOT_STARTED"));
|
||||
}
|
||||
|
||||
// getAll avec ?playthroughId= : branche d'enrichissement sur la liste.
|
||||
@Test
|
||||
void getAll_withPlaythroughId_enrichesStatus() throws Exception {
|
||||
chapterRepository.save(Chapter.builder().arcId(arcId).name("A").order(0).build());
|
||||
mockMvc.perform(get("/api/chapters").param("playthroughId", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].progressionStatus").value("NOT_STARTED"));
|
||||
}
|
||||
|
||||
// deletion-impact : chapitre existant -> 200 avec le compte de scènes (0 ici).
|
||||
@Test
|
||||
void deletionImpact_returns200_whenExists() throws Exception {
|
||||
Chapter saved = chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch").order(0).build());
|
||||
mockMvc.perform(get("/api/chapters/{id}/deletion-impact", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.scenes").value(0));
|
||||
}
|
||||
|
||||
// deletion-impact : chapitre inexistant -> 404.
|
||||
@Test
|
||||
void deletionImpact_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/chapters/{id}/deletion-impact", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// update sur id inexistant : le service lève IllegalArgumentException -> 400.
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
ChapterDTO dto = new ChapterDTO();
|
||||
dto.setName("new");
|
||||
dto.setArcId(arcId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/chapters/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.CharacterDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/** Tests d'intégration CRUD du CharacterController (PJ liés à un Playthrough). */
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class CharacterControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private CharacterRepository characterRepository;
|
||||
|
||||
private String playthroughId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
String campId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campId).name("Table").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
CharacterDTO dto = new CharacterDTO();
|
||||
dto.setName("Aragorn");
|
||||
dto.setPlaythroughId(playthroughId);
|
||||
mockMvc.perform(post("/api/characters")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Aragorn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Character saved = characterRepository.save(
|
||||
Character.builder().playthroughId(playthroughId).name("PJ").order(0).build());
|
||||
mockMvc.perform(get("/api/characters/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("PJ"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/characters/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByPlaythrough_returnsArray() throws Exception {
|
||||
characterRepository.save(Character.builder().playthroughId(playthroughId).name("A").order(0).build());
|
||||
mockMvc.perform(get("/api/characters/playthrough/{playthroughId}", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
/** Recherche enrichie : le campaignId est résolu via le Playthrough. */
|
||||
@Test
|
||||
void search_returnsEnrichedResult() throws Exception {
|
||||
characterRepository.save(Character.builder().playthroughId(playthroughId).name("Legolas").order(0).build());
|
||||
mockMvc.perform(get("/api/characters/search").param("q", "Legolas"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].name").value("Legolas"))
|
||||
.andExpect(jsonPath("$[0].campaignId").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
Character saved = characterRepository.save(
|
||||
Character.builder().playthroughId(playthroughId).name("old").order(0).build());
|
||||
CharacterDTO dto = new CharacterDTO();
|
||||
dto.setName("new");
|
||||
dto.setPlaythroughId(playthroughId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/characters/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
CharacterDTO dto = new CharacterDTO();
|
||||
dto.setName("x");
|
||||
dto.setPlaythroughId(playthroughId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/characters/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Character saved = characterRepository.save(
|
||||
Character.builder().playthroughId(playthroughId).name("X").order(0).build());
|
||||
mockMvc.perform(delete("/api/characters/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.infrastructure.updates.UpdateCheckService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link ConfigController}.
|
||||
* <p>
|
||||
* GET /api/config renvoie {demoMode, updateCheckEnabled}. Le service de mise a
|
||||
* jour est mocke pour piloter la valeur de updateCheckEnabled sans dependre de
|
||||
* la configuration reelle (Watchtower/registry indisponibles en test).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class ConfigControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@MockBean private UpdateCheckService updates;
|
||||
|
||||
@Test
|
||||
void getPublicConfig_returns200_updateCheckEnabledTrue() throws Exception {
|
||||
when(updates.isEnabled()).thenReturn(true);
|
||||
mockMvc.perform(get("/api/config"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.updateCheckEnabled").value(true))
|
||||
.andExpect(jsonPath("$.demoMode").value(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPublicConfig_returns200_updateCheckEnabledFalse() throws Exception {
|
||||
when(updates.isEnabled()).thenReturn(false);
|
||||
mockMvc.perform(get("/api/config"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.updateCheckEnabled").value(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Enemy;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/** Tests d'intégration CRUD du EnemyController (bestiaire de campagne). */
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class EnemyControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private EnemyRepository enemyRepository;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
}
|
||||
|
||||
/** Requête = record EnemyRequest(name, level, folder, ..., campaignId, order). */
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
EnemyController.EnemyRequest req = new EnemyController.EnemyRequest(
|
||||
"Gobelin", "FP 1", "Humanoïdes", null, null,
|
||||
Map.of(), Map.of(), Map.of(), campaignId, null);
|
||||
mockMvc.perform(post("/api/enemies")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Gobelin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Enemy saved = enemyRepository.save(Enemy.builder().campaignId(campaignId).name("E").order(0).build());
|
||||
mockMvc.perform(get("/api/enemies/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("E"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/enemies/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByCampaign_returnsArray() throws Exception {
|
||||
enemyRepository.save(Enemy.builder().campaignId(campaignId).name("A").order(0).build());
|
||||
mockMvc.perform(get("/api/enemies/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_returnsArray() throws Exception {
|
||||
enemyRepository.save(Enemy.builder().campaignId(campaignId).name("Dragon").order(0).build());
|
||||
mockMvc.perform(get("/api/enemies/search").param("q", "Dragon"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
Enemy saved = enemyRepository.save(Enemy.builder().campaignId(campaignId).name("old").order(0).build());
|
||||
EnemyController.EnemyRequest req = new EnemyController.EnemyRequest(
|
||||
"new", null, null, null, null,
|
||||
Map.of(), Map.of(), Map.of(), campaignId, 0);
|
||||
mockMvc.perform(put("/api/enemies/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
EnemyController.EnemyRequest req = new EnemyController.EnemyRequest(
|
||||
"x", null, null, null, null,
|
||||
Map.of(), Map.of(), Map.of(), campaignId, 0);
|
||||
mockMvc.perform(put("/api/enemies/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Enemy saved = enemyRepository.save(Enemy.builder().campaignId(campaignId).name("X").order(0).build());
|
||||
mockMvc.perform(delete("/api/enemies/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,43 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportProgress;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportResult;
|
||||
import com.loremind.domain.gamesystemcontext.ports.RulesImportException;
|
||||
import com.loremind.domain.gamesystemcontext.ports.RulesPdfImporter;
|
||||
import com.loremind.infrastructure.web.dto.gamesystemcontext.GameSystemDTO;
|
||||
import com.loremind.infrastructure.web.dto.shared.TemplateFieldDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
@@ -32,6 +52,29 @@ class GameSystemControllerTest {
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
|
||||
@MockBean private RulesPdfImporter rulesPdfImporter;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Tache de l'import streame executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
/** Cree un GameSystem minimal via l'API et renvoie son id. */
|
||||
private String createGameSystem(String name) throws Exception {
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
dto.setName(name);
|
||||
MvcResult posted = mockMvc.perform(post("/api/game-systems")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
return objectMapper.readValue(
|
||||
posted.getResponse().getContentAsString(), GameSystemDTO.class).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_persistsCharacterAndNpcTemplates() throws Exception {
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
@@ -105,4 +148,228 @@ class GameSystemControllerTest {
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().is4xxClientError());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_persistsEnemyTemplate() throws Exception {
|
||||
GameSystemDTO dto = new GameSystemDTO();
|
||||
dto.setName("Bestiaire");
|
||||
dto.setEnemyTemplate(List.of(
|
||||
new TemplateFieldDTO("Niveau", "NUMBER", null),
|
||||
new TemplateFieldDTO("Tactique", "TEXT", null)));
|
||||
|
||||
mockMvc.perform(post("/api/game-systems")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.enemyTemplate.length()").value(2))
|
||||
.andExpect(jsonPath("$.enemyTemplate[0].name").value("Niveau"))
|
||||
.andExpect(jsonPath("$.enemyTemplate[1].type").value("TEXT"));
|
||||
}
|
||||
|
||||
// --- CRUD : lecture / recherche / suppression ---------------------------
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
String id = createGameSystem("Lisible");
|
||||
mockMvc.perform(get("/api/game-systems/{id}", id))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(id))
|
||||
.andExpect(jsonPath("$.name").value("Lisible"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/game-systems/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAll_returnsArray() throws Exception {
|
||||
createGameSystem("Systeme A");
|
||||
mockMvc.perform(get("/api/game-systems"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_returnsMatching() throws Exception {
|
||||
createGameSystem("Dragonbane Unique");
|
||||
mockMvc.perform(get("/api/game-systems/search").param("q", "Dragonbane"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[?(@.name == 'Dragonbane Unique')]").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204_thenGone() throws Exception {
|
||||
String id = createGameSystem("A supprimer");
|
||||
mockMvc.perform(delete("/api/game-systems/{id}", id))
|
||||
.andExpect(status().isNoContent());
|
||||
mockMvc.perform(get("/api/game-systems/{id}", id))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- Import de regles (PDF) : multipart ---------------------------------
|
||||
|
||||
@Test
|
||||
void importRules_returns200_withSections() throws Exception {
|
||||
when(rulesPdfImporter.importRules(any(), any()))
|
||||
.thenReturn(new RulesImportResult(Map.of("Combat", "## Combat\n- d20"), 5, 1));
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
mockMvc.perform(multipart("/api/game-systems/import-rules").file(file))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.pageCount").value(5))
|
||||
.andExpect(jsonPath("$.ocrPageCount").value(1))
|
||||
.andExpect(jsonPath("$.sections.Combat").value("## Combat\n- d20"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_returns400_whenFileEmpty() throws Exception {
|
||||
MockMultipartFile empty = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[0]);
|
||||
mockMvc.perform(multipart("/api/game-systems/import-rules").file(empty))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRules_returns502_whenBrainFails() throws Exception {
|
||||
when(rulesPdfImporter.importRules(any(), any()))
|
||||
.thenThrow(new RulesImportException("Brain injoignable"));
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
mockMvc.perform(multipart("/api/game-systems/import-rules").file(file))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
|
||||
// --- Import de regles streame (SSE) -------------------------------------
|
||||
|
||||
@Test
|
||||
void importRulesStream_emitsProgressThenDone() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<RulesImportProgress> onProgress = inv.getArgument(2);
|
||||
Consumer<RulesImportResult> onDone = inv.getArgument(5);
|
||||
onProgress.accept(new RulesImportProgress(1, 2, 5, 0, List.of("Combat")));
|
||||
onDone.accept(new RulesImportResult(Map.of("Combat", "## Combat"), 5, 0));
|
||||
return null;
|
||||
}).when(rulesPdfImporter).importRulesStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(file))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("progress")))
|
||||
.andExpect(content().string(containsString("done")))
|
||||
.andExpect(content().string(containsString("Combat")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRulesStream_emptyFile_emitsError() throws Exception {
|
||||
MockMultipartFile empty = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[0]);
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(empty))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("vide")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRulesStream_brainError_emitsError() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
onError.accept(new RuntimeException("structuration KO"));
|
||||
return null;
|
||||
}).when(rulesPdfImporter).importRulesStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(file))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")))
|
||||
.andExpect(content().string(containsString("structuration KO")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Couvre {@code sendImportHeartbeat} (callback onHeartbeat, arg 3) ET la branche
|
||||
* "status" de {@code sendImportEvent} (callback onStatus, arg 4) : un import qui
|
||||
* envoie un keepalive et un message de statut avant de produire son resultat.
|
||||
*/
|
||||
@Test
|
||||
void importRulesStream_emitsHeartbeatAndStatus_thenDone() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Runnable onHeartbeat = inv.getArgument(3);
|
||||
Consumer<String> onStatus = inv.getArgument(4);
|
||||
Consumer<RulesImportResult> onDone = inv.getArgument(5);
|
||||
// Keepalive (commentaire SSE, ignore par le front) -> sendImportHeartbeat.
|
||||
onHeartbeat.run();
|
||||
// Message de statut lisible -> sendImportEvent(..., "status", ...).
|
||||
onStatus.accept("Fournisseur sature, nouvelle tentative...");
|
||||
onDone.accept(new RulesImportResult(Map.of("Combat", "## Combat"), 5, 0));
|
||||
return null;
|
||||
}).when(rulesPdfImporter).importRulesStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(file))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
// Le commentaire keepalive est present dans le flux brut.
|
||||
.andExpect(content().string(containsString("keepalive")))
|
||||
// L'event "status" et son message sont serialises.
|
||||
.andExpect(content().string(containsString("status")))
|
||||
.andExpect(content().string(containsString("Fournisseur sature")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Couvre la branche onStatus avec un message null : le controleur substitue une
|
||||
* chaine vide ({@code status != null ? status : ""}) sans planter.
|
||||
*/
|
||||
@Test
|
||||
void importRulesStream_nullStatus_emitsEmptyStatus() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<String> onStatus = inv.getArgument(4);
|
||||
Consumer<RulesImportResult> onDone = inv.getArgument(5);
|
||||
onStatus.accept(null);
|
||||
onDone.accept(new RulesImportResult(Map.of("Combat", "## Combat"), 5, 0));
|
||||
return null;
|
||||
}).when(rulesPdfImporter).importRulesStreaming(
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
MvcResult result = mockMvc.perform(
|
||||
multipart("/api/game-systems/import-rules/stream").file(file))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("status")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.application.gamesystemcontext.GameSystemService;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportProgress;
|
||||
import com.loremind.domain.gamesystemcontext.RulesImportResult;
|
||||
import com.loremind.infrastructure.web.mapper.GameSystemMapper;
|
||||
import com.loremind.infrastructure.web.mapper.TemplateFieldMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Test UNITAIRE pur (sans Spring) de {@link GameSystemController} dédié au code
|
||||
* défensif de déconnexion du navigateur de l'import streamé, INTESTABLE via MockMvc
|
||||
* (un envoi SSE après {@code complete()} y remonte en ServletException au lieu
|
||||
* d'exécuter la branche). Voir {@link CampaignImportControllerUnitTest} pour le détail
|
||||
* de l'approche — même séquence : complete -> send échoue -> {@code clientGone=true}
|
||||
* -> les callbacks suivants empruntent les branches {@code ClientGoneException}.
|
||||
*/
|
||||
class GameSystemControllerUnitTest {
|
||||
|
||||
private final GameSystemService service = mock(GameSystemService.class);
|
||||
private final TaskExecutor inlineExecutor = Runnable::run;
|
||||
private final GameSystemController controller = new GameSystemController(
|
||||
service, mock(GameSystemMapper.class), mock(TemplateFieldMapper.class),
|
||||
inlineExecutor, new ObjectMapper());
|
||||
|
||||
private static RulesImportProgress progress() {
|
||||
return new RulesImportProgress(1, 1, 0, 0, List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRulesStream_clientDisconnect_exercisesDefensiveBranches() throws Exception {
|
||||
doAnswer(inv -> {
|
||||
Consumer<RulesImportProgress> onProgress = inv.getArgument(2);
|
||||
Runnable onHeartbeat = inv.getArgument(3);
|
||||
Consumer<RulesImportResult> onDone = inv.getArgument(5);
|
||||
Consumer<Throwable> onError = inv.getArgument(6);
|
||||
|
||||
// 1) Termine le flux (event "done" + complete()).
|
||||
onDone.accept(new RulesImportResult(Map.of(), 0, 0));
|
||||
// 2) Envoi post-complete : send échoue -> catch -> clientGone=true.
|
||||
try { onProgress.accept(progress()); } catch (RuntimeException ignored) { }
|
||||
// 3) clientGone=true -> sendImportHeartbeat lève ClientGoneException.
|
||||
try { onHeartbeat.run(); } catch (RuntimeException ignored) { }
|
||||
// 4) clientGone=true -> sendImportEvent lève ClientGoneException.
|
||||
try { onProgress.accept(progress()); } catch (RuntimeException ignored) { }
|
||||
// 5) clientGone=true -> callback d'erreur en early-return.
|
||||
onError.accept(new RuntimeException("tardif"));
|
||||
return null;
|
||||
}).when(service).importRulesFromPdfStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "regles.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
SseEmitter emitter = controller.importRulesStream(file);
|
||||
|
||||
assertNotNull(emitter);
|
||||
verify(service).importRulesFromPdfStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.images.ImageService;
|
||||
import com.loremind.domain.images.Image;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link ImageController} (Shared Kernel images).
|
||||
* <p>
|
||||
* Le {@link ImageService} est mocke : il orchestre sinon MinIO (binaire) +
|
||||
* Postgres (metadonnees) via ses deux ports. On evite ainsi tout acces a MinIO,
|
||||
* indisponible en test, tout en couvrant le mapping HTTP du controleur
|
||||
* (upload / metadata / content streaming / delete + cas 400 / 404).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class ImageControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@MockBean private ImageService imageService;
|
||||
|
||||
private Image sampleImage() {
|
||||
return Image.builder()
|
||||
.id("img-1")
|
||||
.filename("portrait.png")
|
||||
.contentType("image/png")
|
||||
.sizeBytes(3)
|
||||
.storageKey("images/img-1.png")
|
||||
.uploadedAt(LocalDateTime.of(2026, 1, 1, 12, 0))
|
||||
.build();
|
||||
}
|
||||
|
||||
private MockMultipartFile pngFile(byte[] bytes) {
|
||||
return new MockMultipartFile("file", "portrait.png", "image/png", bytes);
|
||||
}
|
||||
|
||||
// --- POST /api/images --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void upload_returns200_withMetadata() throws Exception {
|
||||
when(imageService.upload(eq("portrait.png"), eq("image/png"), any(InputStream.class), anyLong()))
|
||||
.thenReturn(sampleImage());
|
||||
|
||||
mockMvc.perform(multipart("/api/images").file(pngFile(new byte[]{1, 2, 3})))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value("img-1"))
|
||||
.andExpect(jsonPath("$.filename").value("portrait.png"))
|
||||
.andExpect(jsonPath("$.contentType").value("image/png"))
|
||||
.andExpect(jsonPath("$.sizeBytes").value(3))
|
||||
.andExpect(jsonPath("$.url").value("/api/images/img-1/content"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void upload_returns400_whenEmpty() throws Exception {
|
||||
mockMvc.perform(multipart("/api/images").file(pngFile(new byte[0])))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void upload_returns400_whenServiceRejects() throws Exception {
|
||||
// Validation metier (MIME non autorise, taille...) -> IllegalArgumentException.
|
||||
when(imageService.upload(any(), any(), any(InputStream.class), anyLong()))
|
||||
.thenThrow(new IllegalArgumentException("Type de fichier non supporte."));
|
||||
|
||||
mockMvc.perform(multipart("/api/images")
|
||||
.file(new MockMultipartFile("file", "evil.exe", "application/octet-stream",
|
||||
new byte[]{1, 2, 3})))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
// --- GET /api/images/{id} ----------------------------------------------
|
||||
|
||||
@Test
|
||||
void getMetadata_returns200() throws Exception {
|
||||
when(imageService.getById("img-1")).thenReturn(Optional.of(sampleImage()));
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}", "img-1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value("img-1"))
|
||||
.andExpect(jsonPath("$.url").value("/api/images/img-1/content"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMetadata_returns404_whenMissing() throws Exception {
|
||||
when(imageService.getById("nope")).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}", "nope"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- GET /api/images/{id}/content --------------------------------------
|
||||
|
||||
@Test
|
||||
void getContent_returns200_withBinary() throws Exception {
|
||||
byte[] data = {10, 20, 30};
|
||||
when(imageService.getById("img-1")).thenReturn(Optional.of(sampleImage()));
|
||||
when(imageService.downloadById("img-1"))
|
||||
.thenReturn(Optional.of(new ByteArrayInputStream(data)));
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}/content", "img-1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string("Content-Type", "image/png"))
|
||||
.andExpect(header().string("Cross-Origin-Resource-Policy", "cross-origin"))
|
||||
.andExpect(content().bytes(data));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getContent_returns404_whenMetadataMissing() throws Exception {
|
||||
when(imageService.getById("nope")).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}/content", "nope"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getContent_returns404_whenBinaryLost() throws Exception {
|
||||
// Metadonnees presentes mais binaire absent (incoherence) -> 404.
|
||||
when(imageService.getById("img-1")).thenReturn(Optional.of(sampleImage()));
|
||||
when(imageService.downloadById("img-1")).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(get("/api/images/{id}/content", "img-1"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- DELETE /api/images/{id} -------------------------------------------
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
mockMvc.perform(delete("/api/images/{id}", "img-1"))
|
||||
.andExpect(status().isNoContent());
|
||||
verify(imageService).deleteById("img-1");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.ItemCatalog;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerationException;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerator;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogRepository;
|
||||
import com.loremind.infrastructure.web.controller.ItemCatalogController.GenerateRequest;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ItemCatalogDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link ItemCatalogController} (CRUD + recherche +
|
||||
* generation IA d'un catalogue d'objets).
|
||||
* <p>
|
||||
* Le port {@link ItemCatalogGenerator} (client du Brain) est mocke : sinon
|
||||
* l'endpoint /generate ferait un vrai appel reseau au service IA (indisponible
|
||||
* en test). Les repos reels servent aux fixtures.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class ItemCatalogControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private ItemCatalogRepository catalogRepository;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
|
||||
@MockBean private ItemCatalogGenerator generator;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(
|
||||
Campaign.builder().name("Camp").description("desc").build()).getId();
|
||||
}
|
||||
|
||||
private ItemCatalogDTO dto(String name) {
|
||||
ItemCatalogDTO dto = new ItemCatalogDTO();
|
||||
dto.setName(name);
|
||||
dto.setDescription("Une boutique");
|
||||
dto.setIcon("store");
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setOrder(0);
|
||||
return dto;
|
||||
}
|
||||
|
||||
// --- POST / -------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
mockMvc.perform(post("/api/item-catalogs")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto("Echoppe"))))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Echoppe"))
|
||||
.andExpect(jsonPath("$.campaignId").value(campaignId));
|
||||
}
|
||||
|
||||
// --- GET /{id} ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
ItemCatalog saved = catalogRepository.save(ItemCatalog.builder()
|
||||
.name("Tresor").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/item-catalogs/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Tresor"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/item-catalogs/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- GET /campaign/{campaignId} -----------------------------------------
|
||||
|
||||
@Test
|
||||
void getByCampaign_returnsArray() throws Exception {
|
||||
catalogRepository.save(ItemCatalog.builder()
|
||||
.name("A").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/item-catalogs/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].name").value("A"));
|
||||
}
|
||||
|
||||
// --- PUT /{id} ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
ItemCatalog saved = catalogRepository.save(ItemCatalog.builder()
|
||||
.name("old").campaignId(campaignId).order(0).build());
|
||||
ItemCatalogDTO dto = dto("new");
|
||||
mockMvc.perform(put("/api/item-catalogs/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
// Le service leve IllegalArgumentException -> GlobalExceptionHandler -> 400.
|
||||
mockMvc.perform(put("/api/item-catalogs/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto("x"))))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
// --- DELETE /{id} -------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
ItemCatalog saved = catalogRepository.save(ItemCatalog.builder()
|
||||
.name("X").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(delete("/api/item-catalogs/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- GET /search --------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void search_returnsArray() throws Exception {
|
||||
catalogRepository.save(ItemCatalog.builder()
|
||||
.name("Forge de Naheulbeuk").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/item-catalogs/search").param("q", "Forge"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
// --- POST /generate -----------------------------------------------------
|
||||
|
||||
@Test
|
||||
void generate_returns200() throws Exception {
|
||||
when(generator.generate(any(), any())).thenReturn(
|
||||
new ItemCatalogGenerator.GeneratedCatalog(
|
||||
"Boutique magique",
|
||||
"Objets enchantes",
|
||||
List.of(CatalogItem.builder().name("Potion").price("50 po").build())));
|
||||
|
||||
GenerateRequest req = new GenerateRequest(campaignId, "une boutique de magie");
|
||||
mockMvc.perform(post("/api/item-catalogs/generate")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Boutique magique"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns502_whenBrainUnreachable() throws Exception {
|
||||
when(generator.generate(any(), any()))
|
||||
.thenThrow(new ItemCatalogGenerationException("Brain injoignable"));
|
||||
|
||||
GenerateRequest req = new GenerateRequest(campaignId, "boutique");
|
||||
mockMvc.perform(post("/api/item-catalogs/generate")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.licensing.ChannelSwitcherService;
|
||||
import com.loremind.application.licensing.LicenseService;
|
||||
import com.loremind.application.licensing.LicenseService.InstallException;
|
||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
||||
import com.loremind.domain.licensing.LicenseStatus;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link LicenseController} (gestion licence Patreon).
|
||||
* <p>
|
||||
* {@code /api/license/**} exige le role ADMIN (HTTP Basic) : chaque requete porte
|
||||
* l'entete d'auth construite a partir des identifiants de test (cf.
|
||||
* src/test/resources/application.properties). Sans cet entete, la securite
|
||||
* renverrait 401.
|
||||
* <p>
|
||||
* Les deux services applicatifs sont mockes : {@link LicenseService} (qui appelle
|
||||
* sinon le relais OAuth distant + verification JWT) et {@link ChannelSwitcherService}
|
||||
* (qui ecrit sinon dans un volume partage avec le sidecar). Aucun acces reseau ni
|
||||
* fichier reel.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class LicenseControllerTest {
|
||||
|
||||
/** Identifiants definis dans src/test/resources/application.properties. */
|
||||
private static final String ADMIN_AUTH = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("test-admin:test-admin-password".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@MockBean private LicenseService licenseService;
|
||||
@MockBean private ChannelSwitcherService channelSwitcher;
|
||||
|
||||
private LicenseSnapshot validSnapshot() {
|
||||
return new LicenseSnapshot(
|
||||
LicenseStatus.VALID, "user-42", "tier-1", "li-xyz",
|
||||
Instant.now().plusSeconds(3600), Instant.now(), true, true);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Valeurs par defaut neutres ; chaque test surcharge ce dont il a besoin.
|
||||
when(licenseService.isLicensingEnabled()).thenReturn(true);
|
||||
when(licenseService.getCurrentSnapshot()).thenReturn(validSnapshot());
|
||||
}
|
||||
|
||||
// --- Securite ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getStatus_returns401_withoutAuth() throws Exception {
|
||||
mockMvc.perform(get("/api/license"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
// --- GET /api/license --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getStatus_returns200() throws Exception {
|
||||
mockMvc.perform(get("/api/license").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.enabled").value(true))
|
||||
.andExpect(jsonPath("$.status").value("VALID"))
|
||||
.andExpect(jsonPath("$.patreonUserId").value("user-42"));
|
||||
}
|
||||
|
||||
// --- GET /api/license/connect-url --------------------------------------
|
||||
|
||||
@Test
|
||||
void getConnectUrl_returns200() throws Exception {
|
||||
when(licenseService.buildConnectUrl()).thenReturn("https://relay/oauth?x=1");
|
||||
mockMvc.perform(get("/api/license/connect-url").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.url").value("https://relay/oauth?x=1"));
|
||||
}
|
||||
|
||||
// --- POST /api/license/install -----------------------------------------
|
||||
|
||||
@Test
|
||||
void install_returns200_onValidJwt() throws Exception {
|
||||
when(licenseService.installToken("good-jwt")).thenReturn(validSnapshot());
|
||||
mockMvc.perform(post("/api/license/install")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"jwt\":\"good-jwt\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value("VALID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void install_returns400_whenJwtMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/license/install")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"jwt\":\"\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error").value("missing jwt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void install_returns400_whenInstallFails() throws Exception {
|
||||
when(licenseService.installToken("bad-jwt"))
|
||||
.thenThrow(new InstallException("Invalid JWT: signature"));
|
||||
mockMvc.perform(post("/api/license/install")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"jwt\":\"bad-jwt\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error").value("Invalid JWT: signature"));
|
||||
}
|
||||
|
||||
// --- DELETE /api/license -----------------------------------------------
|
||||
|
||||
@Test
|
||||
void disconnect_returns204() throws Exception {
|
||||
mockMvc.perform(delete("/api/license").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- POST /api/license/refresh -----------------------------------------
|
||||
|
||||
@Test
|
||||
void refresh_returns200() throws Exception {
|
||||
mockMvc.perform(post("/api/license/refresh").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value("VALID"));
|
||||
}
|
||||
|
||||
// --- PUT /api/license/beta-channel -------------------------------------
|
||||
|
||||
@Test
|
||||
void setBetaChannel_returns200() throws Exception {
|
||||
when(licenseService.setBetaChannelEnabled(eq(false))).thenReturn(validSnapshot());
|
||||
mockMvc.perform(put("/api/license/beta-channel")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"enabled\":false}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value("VALID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBetaChannel_returns409_whenNoLicense() throws Exception {
|
||||
when(licenseService.setBetaChannelEnabled(anyBoolean()))
|
||||
.thenThrow(new IllegalStateException("No license installed"));
|
||||
mockMvc.perform(put("/api/license/beta-channel")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"enabled\":true}"))
|
||||
.andExpect(status().isConflict())
|
||||
.andExpect(jsonPath("$.error").value("No license installed"));
|
||||
}
|
||||
|
||||
// --- GET /api/license/channel ------------------------------------------
|
||||
|
||||
@Test
|
||||
void getChannel_returns200() throws Exception {
|
||||
when(channelSwitcher.getCurrentChannel()).thenReturn(ChannelSwitcherService.Channel.STABLE);
|
||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
||||
when(channelSwitcher.getLastResult()).thenReturn(null);
|
||||
mockMvc.perform(get("/api/license/channel").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.currentChannel").value("stable"))
|
||||
.andExpect(jsonPath("$.switcherAvailable").value(true));
|
||||
}
|
||||
|
||||
// --- POST /api/license/channel/switch ----------------------------------
|
||||
|
||||
@Test
|
||||
void switchChannel_returns400_whenChannelMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error").value("missing channel"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns400_whenChannelInvalid() throws Exception {
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"nightly\"}"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns403_whenBetaWithoutLicense() throws Exception {
|
||||
// Snapshot EXPIRED -> pas d'acces beta.
|
||||
when(licenseService.getCurrentSnapshot()).thenReturn(new LicenseSnapshot(
|
||||
LicenseStatus.EXPIRED, null, null, null, null, null, false, false));
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"beta\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns503_whenSwitcherUnavailable() throws Exception {
|
||||
// Licence VALID (autorise beta) mais sidecar absent.
|
||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(false);
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"beta\"}"))
|
||||
.andExpect(status().isServiceUnavailable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns202_onSuccess() throws Exception {
|
||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
||||
when(channelSwitcher.requestSwitch(ChannelSwitcherService.Channel.STABLE))
|
||||
.thenReturn("cmd-1");
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"stable\"}"))
|
||||
.andExpect(status().isAccepted())
|
||||
.andExpect(jsonPath("$.id").value("cmd-1"))
|
||||
.andExpect(jsonPath("$.channel").value("stable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChannel_returns500_whenWriteFails() throws Exception {
|
||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
||||
doThrow(new IOException("disk full"))
|
||||
.when(channelSwitcher).requestSwitch(ChannelSwitcherService.Channel.STABLE);
|
||||
mockMvc.perform(post("/api/license/channel/switch")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"channel\":\"stable\"}"))
|
||||
.andExpect(status().isInternalServerError());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Notebook;
|
||||
import com.loremind.domain.campaigncontext.NotebookSource;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookChatStreamer;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookException;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookIndexer;
|
||||
import com.loremind.domain.campaigncontext.ports.NotebookRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link NotebookController} (atelier RAG).
|
||||
* <p>
|
||||
* Les ports vers le Brain sont mockes : {@link NotebookIndexer} (indexation des
|
||||
* sources) et {@link NotebookChatStreamer} (chat ancre streame), sinon chaque test
|
||||
* ferait un vrai appel HTTP au Brain (indisponible en test).
|
||||
* <p>
|
||||
* Le {@code TaskExecutor} ("applicationTaskExecutor") est egalement mocke pour
|
||||
* executer la tache du chat stream EN LIGNE (synchrone) : tous les events SSE sont
|
||||
* ainsi ecrits avant le retour du controleur, ce qui rend les assertions sur le
|
||||
* flux deterministes (pas de course entre threads).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class NotebookControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private NotebookRepository notebookRepository;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
|
||||
@MockBean private NotebookIndexer indexer;
|
||||
@MockBean private NotebookChatStreamer chatStreamer;
|
||||
@MockBean(name = "applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(
|
||||
Campaign.builder().name("C").description("").build()).getId();
|
||||
// Tache du chat stream executee en ligne -> events SSE deterministes.
|
||||
doAnswer(inv -> { ((Runnable) inv.getArgument(0)).run(); return null; })
|
||||
.when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private Notebook persistNotebook() {
|
||||
return notebookRepository.save(
|
||||
Notebook.builder().campaignId(campaignId).name("Atelier").build());
|
||||
}
|
||||
|
||||
// --- Notebooks (CRUD) ---
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
var req = new NotebookController.CreateRequest(campaignId, "Mon atelier");
|
||||
mockMvc.perform(post("/api/notebooks")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").exists())
|
||||
.andExpect(jsonPath("$.name").value("Mon atelier"))
|
||||
.andExpect(jsonPath("$.campaignId").value(campaignId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_blankName_fallsBackToDefault() throws Exception {
|
||||
var req = new NotebookController.CreateRequest(campaignId, " ");
|
||||
mockMvc.perform(post("/api/notebooks")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Nouvel atelier"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listByCampaign_returnsArray() throws Exception {
|
||||
persistNotebook();
|
||||
mockMvc.perform(get("/api/notebooks/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].campaignId").value(campaignId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returns200_withSourcesAndMessages() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
mockMvc.perform(get("/api/notebooks/{id}", nb.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(nb.getId()))
|
||||
.andExpect(jsonPath("$.name").value("Atelier"))
|
||||
.andExpect(jsonPath("$.sources").isArray())
|
||||
.andExpect(jsonPath("$.messages").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/notebooks/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rename_returns200() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
var req = new NotebookController.RenameRequest("Renomme");
|
||||
mockMvc.perform(put("/api/notebooks/{id}", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Renomme"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
mockMvc.perform(delete("/api/notebooks/{id}", nb.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- Sources ---
|
||||
|
||||
@Test
|
||||
void addSource_returns200_andIndexes() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
when(indexer.index(any(), any(), any()))
|
||||
.thenReturn(new NotebookIndexer.IndexResult(12, 3, 0));
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "livre.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
mockMvc.perform(multipart("/api/notebooks/{id}/sources", nb.getId()).file(file))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.filename").value("livre.pdf"))
|
||||
.andExpect(jsonPath("$.status").value("READY"))
|
||||
.andExpect(jsonPath("$.chunkCount").value(12))
|
||||
.andExpect(jsonPath("$.pageCount").value(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addSource_returns502_whenBrainFails() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
when(indexer.index(any(), any(), any()))
|
||||
.thenThrow(new NotebookException("Brain injoignable"));
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file", "livre.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||
|
||||
mockMvc.perform(multipart("/api/notebooks/{id}/sources", nb.getId()).file(file))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSource_returns204() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
NotebookSource src = notebookRepository.saveSource(NotebookSource.builder()
|
||||
.notebookId(nb.getId()).filename("s.pdf").status("READY").build());
|
||||
mockMvc.perform(delete("/api/notebooks/sources/{sourceId}", src.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- Conversation : vider (archiver) + archives ---
|
||||
|
||||
@Test
|
||||
void clearChat_returns204() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
mockMvc.perform(post("/api/notebooks/{id}/chat/clear", nb.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearChat_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/notebooks/{id}/chat/clear", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listArchives_returnsArray() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
mockMvc.perform(get("/api/notebooks/{id}/chat/archives", nb.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
// --- Chat ancre streame (SSE) ---
|
||||
|
||||
@Test
|
||||
void chatStream_happyPath_streamsTokenThenDone() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
// Le streamer mocke joue : 1 token puis fin.
|
||||
doAnswer(inv -> {
|
||||
java.util.function.Consumer<String> onToken = inv.getArgument(5);
|
||||
Runnable onDone = inv.getArgument(7);
|
||||
onToken.accept("Bonjour");
|
||||
onDone.run();
|
||||
return null;
|
||||
}).when(chatStreamer).stream(any(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean(),
|
||||
any(), any(), any(), any(), any());
|
||||
|
||||
var req = new NotebookController.ChatRequest("Salut ?", false, null, null);
|
||||
MvcResult result = mockMvc.perform(post("/api/notebooks/{id}/chat/stream", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Bonjour")))
|
||||
.andExpect(content().string(containsString("done")));
|
||||
|
||||
// La reponse de l'assistant a ete persistee a la fin du stream.
|
||||
boolean persisted = notebookRepository.findMessagesByNotebookId(nb.getId()).stream()
|
||||
.anyMatch(m -> "assistant".equals(m.getRole()) && "Bonjour".equals(m.getContent()));
|
||||
org.junit.jupiter.api.Assertions.assertTrue(persisted, "reponse assistant persistee");
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_emptyMessage_emitsError() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
var req = new NotebookController.ChatRequest(" ", false, null, null);
|
||||
MvcResult result = mockMvc.perform(post("/api/notebooks/{id}/chat/stream", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("error")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_streamerError_emitsError() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
doAnswer(inv -> {
|
||||
java.util.function.Consumer<Throwable> onError = inv.getArgument(8);
|
||||
onError.accept(new RuntimeException("boom"));
|
||||
return null;
|
||||
}).when(chatStreamer).stream(any(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean(),
|
||||
any(), any(), any(), any(), any());
|
||||
|
||||
var req = new NotebookController.ChatRequest("Salut ?", false, null, null);
|
||||
MvcResult result = mockMvc.perform(post("/api/notebooks/{id}/chat/stream", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("boom")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_returns404_whenMissing() throws Exception {
|
||||
var req = new NotebookController.ChatRequest("Salut ?", false, null, null);
|
||||
mockMvc.perform(post("/api/notebooks/{id}/chat/stream", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatStream_deepMode_emitsSourcesAndProgress() throws Exception {
|
||||
Notebook nb = persistNotebook();
|
||||
// Source PRETE -> remontee par readySourceIds, donc selectionnable via sourceIds.
|
||||
NotebookSource src = notebookRepository.saveSource(NotebookSource.builder()
|
||||
.notebookId(nb.getId()).filename("s.pdf").status("READY").build());
|
||||
|
||||
// Le streamer mocke joue, en mode approfondi : sources -> progress -> token -> fin.
|
||||
doAnswer(inv -> {
|
||||
java.util.function.Consumer<String> onSourcesJson = inv.getArgument(4);
|
||||
java.util.function.Consumer<String> onToken = inv.getArgument(5);
|
||||
java.util.function.Consumer<NotebookChatStreamer.Progress> onProgress = inv.getArgument(6);
|
||||
Runnable onDone = inv.getArgument(7);
|
||||
onSourcesJson.accept("{\"sources\":[{\"source_id\":\"" + src.getId() + "\",\"page\":1}]}");
|
||||
onProgress.accept(new NotebookChatStreamer.Progress(1, 3));
|
||||
onToken.accept("Reponse");
|
||||
onDone.run();
|
||||
return null;
|
||||
}).when(chatStreamer).stream(any(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean(),
|
||||
any(), any(), any(), any(), any());
|
||||
|
||||
// deep=true + sourceIds (filtrage) + archiveIds non nuls (branche buildArchiveContext).
|
||||
var req = new NotebookController.ChatRequest(
|
||||
"Analyse complete ?", true,
|
||||
java.util.List.of(src.getId()), java.util.List.of("2020-01-01T00:00"));
|
||||
MvcResult result = mockMvc.perform(post("/api/notebooks/{id}/chat/stream", nb.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("sources")))
|
||||
.andExpect(content().string(containsString("progress")))
|
||||
.andExpect(content().string(containsString("Reponse")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Npc;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/** Tests d'intégration CRUD du NpcController. */
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class NpcControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private NpcRepository npcRepository;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
NpcDTO dto = new NpcDTO();
|
||||
dto.setName("Gandalf");
|
||||
dto.setCampaignId(campaignId);
|
||||
mockMvc.perform(post("/api/npcs")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Gandalf"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Npc saved = npcRepository.save(Npc.builder().campaignId(campaignId).name("N").order(0).build());
|
||||
mockMvc.perform(get("/api/npcs/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("N"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/npcs/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByCampaign_returnsArray() throws Exception {
|
||||
npcRepository.save(Npc.builder().campaignId(campaignId).name("A").order(0).build());
|
||||
mockMvc.perform(get("/api/npcs/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_returnsArray() throws Exception {
|
||||
npcRepository.save(Npc.builder().campaignId(campaignId).name("Frodon").order(0).build());
|
||||
mockMvc.perform(get("/api/npcs/search").param("q", "Frodon"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByLore_returnsArray() throws Exception {
|
||||
mockMvc.perform(get("/api/npcs/lore/{loreId}", "lore-1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
Npc saved = npcRepository.save(Npc.builder().campaignId(campaignId).name("old").order(0).build());
|
||||
NpcDTO dto = new NpcDTO();
|
||||
dto.setName("new");
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/npcs/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
NpcDTO dto = new NpcDTO();
|
||||
dto.setName("x");
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setOrder(0);
|
||||
mockMvc.perform(put("/api/npcs/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Npc saved = npcRepository.save(Npc.builder().campaignId(campaignId).name("X").order(0).build());
|
||||
mockMvc.perform(delete("/api/npcs/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.generationcontext.GeneratePageValuesUseCase;
|
||||
import com.loremind.domain.generationcontext.ports.AiProviderException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link PageGenerationController} (generation IA de Page).
|
||||
* <p>
|
||||
* Le use case {@link GeneratePageValuesUseCase} est mocke : il orchestre l'appel
|
||||
* au Brain (AiProvider), indisponible en test. On verifie le mapping des
|
||||
* exceptions du use case vers les codes HTTP :
|
||||
* <ul>
|
||||
* <li>OK -> 200 + {@code {values:{...}}}</li>
|
||||
* <li>IllegalArgumentException (page introuvable) -> 404</li>
|
||||
* <li>AiProviderException (Brain HS) -> 502</li>
|
||||
* <li>IllegalStateException "aucun champ" -> 422</li>
|
||||
* <li>IllegalStateException autre (incoherence BDD) -> 500</li>
|
||||
* </ul>
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class PageGenerationControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@MockBean private GeneratePageValuesUseCase generatePageValuesUseCase;
|
||||
|
||||
@Test
|
||||
void generate_returns200_withSuggestions() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("p1")))
|
||||
.thenReturn(Map.of("nom", "Aldric", "race", "Elfe"));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "p1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.values.nom").value("Aldric"))
|
||||
.andExpect(jsonPath("$.values.race").value("Elfe"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns404_whenPageMissing() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("missing")))
|
||||
.thenThrow(new IllegalArgumentException("Page non trouvée"));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "missing"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns502_whenBrainDown() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("p1")))
|
||||
.thenThrow(new AiProviderException("Brain unreachable"));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "p1"))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns422_whenTemplateHasNoFields() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("p1")))
|
||||
.thenThrow(new IllegalStateException("Le template 'X' n'a aucun champ texte à générer."));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "p1"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns500_whenBddInconsistent() throws Exception {
|
||||
when(generatePageValuesUseCase.execute(eq("p1")))
|
||||
.thenThrow(new IllegalStateException("Template introuvable (id=t1)"));
|
||||
|
||||
mockMvc.perform(post("/api/pages/{id}/generate", "p1"))
|
||||
.andExpect(status().isInternalServerError());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.Session;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.domain.playcontext.ports.SessionRepository;
|
||||
import com.loremind.infrastructure.web.dto.playcontext.PlaythroughDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration du PlaythroughController.
|
||||
* Fixture parente : Campaign (un Playthrough référence une campagne).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class PlaythroughControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private SessionRepository sessionRepository;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
}
|
||||
|
||||
private Playthrough savePlaythrough() {
|
||||
return playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campaignId).name("Partie").description("d").build());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
PlaythroughDTO dto = new PlaythroughDTO();
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setName("Table du vendredi");
|
||||
dto.setDescription("desc");
|
||||
mockMvc.perform(post("/api/playthroughs")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Table du vendredi"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_returns400_whenCampaignMissing() throws Exception {
|
||||
PlaythroughDTO dto = new PlaythroughDTO();
|
||||
dto.setCampaignId("999999999");
|
||||
dto.setName("X");
|
||||
mockMvc.perform(post("/api/playthroughs")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Playthrough p = savePlaythrough();
|
||||
mockMvc.perform(get("/api/playthroughs/{id}", p.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Partie"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/playthroughs/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_byCampaign_returnsArray() throws Exception {
|
||||
savePlaythrough();
|
||||
mockMvc.perform(get("/api/playthroughs").param("campaignId", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_withoutCampaign_returnsEmptyArray() throws Exception {
|
||||
savePlaythrough();
|
||||
mockMvc.perform(get("/api/playthroughs"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
Playthrough p = savePlaythrough();
|
||||
PlaythroughDTO dto = new PlaythroughDTO();
|
||||
dto.setName("Renommée");
|
||||
dto.setDescription("nouvelle desc");
|
||||
mockMvc.perform(put("/api/playthroughs/{id}", p.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Renommée"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
PlaythroughDTO dto = new PlaythroughDTO();
|
||||
dto.setName("X");
|
||||
mockMvc.perform(put("/api/playthroughs/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
Playthrough p = savePlaythrough();
|
||||
mockMvc.perform(delete("/api/playthroughs/{id}", p.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_returns400_whenMissing() throws Exception {
|
||||
mockMvc.perform(delete("/api/playthroughs/{id}", "999999999"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_returns200() throws Exception {
|
||||
Playthrough p = savePlaythrough();
|
||||
sessionRepository.save(Session.builder()
|
||||
.name("S").playthroughId(p.getId())
|
||||
.startedAt(java.time.LocalDateTime.now()).build());
|
||||
mockMvc.perform(get("/api/playthroughs/{id}/deletion-impact", p.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.sessions").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/playthroughs/{id}/deletion-impact", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughFlagRepository;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.infrastructure.web.dto.playcontext.PlaythroughFlagDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration de {@link PlaythroughFlagController}.
|
||||
* Couvre les 3 endpoints : list (GET), setFlag (PUT), deleteFlag (DELETE).
|
||||
* Les flags sont indexés par playthroughId : on crée une campagne puis un playthrough en fixture.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class PlaythroughFlagControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private PlaythroughFlagRepository flagRepository;
|
||||
|
||||
private String playthroughId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Chaîne de fixtures : campaign -> playthrough
|
||||
String campId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campId).name("Table").description("").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsEmptyArray_whenNoFlags() throws Exception {
|
||||
mockMvc.perform(get("/api/playthroughs/{pid}/flags", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsExistingFlags() throws Exception {
|
||||
// Pré-positionne un flag via le repo réel
|
||||
flagRepository.setFlag(playthroughId, "porte_ouverte", true);
|
||||
mockMvc.perform(get("/api/playthroughs/{pid}/flags", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].name").value("porte_ouverte"))
|
||||
.andExpect(jsonPath("$[0].value").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setFlag_returns200_andEcho() throws Exception {
|
||||
PlaythroughFlagDTO body = new PlaythroughFlagDTO("dragon_vaincu", true);
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/flags/{name}", playthroughId, "dragon_vaincu")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(body)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("dragon_vaincu"))
|
||||
.andExpect(jsonPath("$.value").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setFlag_false_returns200() throws Exception {
|
||||
PlaythroughFlagDTO body = new PlaythroughFlagDTO("ignore", false);
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/flags/{name}", playthroughId, "ignore")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(body)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.value").value(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFlag_returns204() throws Exception {
|
||||
flagRepository.setFlag(playthroughId, "a_supprimer", true);
|
||||
mockMvc.perform(delete("/api/playthroughs/{pid}/flags/{name}", playthroughId, "a_supprimer"))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFlag_returns204_whenAbsent() throws Exception {
|
||||
// deleteFlag est idempotent : pas d'erreur même si le flag n'existe pas
|
||||
mockMvc.perform(delete("/api/playthroughs/{pid}/flags/{name}", playthroughId, "inexistant"))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ProgressionStatus;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.domain.playcontext.ports.QuestProgressionRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration de {@link QuestProgressionController}.
|
||||
* Couvre list (GET, map chapterId->status) et setStatus (PUT) avec :
|
||||
* - statut valide IN_PROGRESS / COMPLETED
|
||||
* - statut vide/null => NOT_STARTED (suppression de ligne)
|
||||
* - statut invalide => 400 (badRequest renvoyé directement par le contrôleur)
|
||||
* <p>
|
||||
* Le {@code chapterId} doit être un id de Chapter REEL (clé numérique) : on crée
|
||||
* donc la chaîne campaign -> arc -> chapter en fixture.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class QuestProgressionControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private ArcRepository arcRepository;
|
||||
@Autowired private ChapterRepository chapterRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private QuestProgressionRepository repo;
|
||||
|
||||
private String playthroughId;
|
||||
private String chapterId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Chaîne de fixtures : campaign -> playthrough (+ arc -> chapter pour un chapterId reel).
|
||||
String campId = campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||
String arcId = arcRepository.save(Arc.builder().campaignId(campId).name("A").order(0).build()).getId();
|
||||
chapterId = chapterRepository.save(Chapter.builder().arcId(arcId).name("Ch").order(0).build()).getId();
|
||||
playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campId).name("Table").description("").build()).getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsEmptyMap_whenNoProgressions() throws Exception {
|
||||
mockMvc.perform(get("/api/playthroughs/{pid}/quest-progressions", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_returnsStatusMap() throws Exception {
|
||||
// Pré-positionne une progression explicite via le repo réel.
|
||||
repo.setStatus(playthroughId, chapterId, ProgressionStatus.IN_PROGRESS);
|
||||
mockMvc.perform(get("/api/playthroughs/{pid}/quest-progressions", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$['" + chapterId + "']").value("IN_PROGRESS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setStatus_inProgress_returns204() throws Exception {
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/quest-progressions/{cid}", playthroughId, chapterId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(
|
||||
new QuestProgressionController.SetStatusRequest("IN_PROGRESS"))))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setStatus_completed_returns204() throws Exception {
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/quest-progressions/{cid}", playthroughId, chapterId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(
|
||||
new QuestProgressionController.SetStatusRequest("COMPLETED"))))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setStatus_nullStatus_returns204_asNotStarted() throws Exception {
|
||||
// status null => NOT_STARTED (branche : pas de parsing)
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/quest-progressions/{cid}", playthroughId, chapterId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(
|
||||
new QuestProgressionController.SetStatusRequest(null))))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setStatus_blankStatus_returns204_asNotStarted() throws Exception {
|
||||
// status vide => NOT_STARTED (branche isBlank)
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/quest-progressions/{cid}", playthroughId, chapterId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(
|
||||
new QuestProgressionController.SetStatusRequest(" "))))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setStatus_invalidStatus_returns400() throws Exception {
|
||||
// valeur d'enum inconnue => IllegalArgumentException attrapée => badRequest direct
|
||||
mockMvc.perform(put("/api/playthroughs/{pid}/quest-progressions/{cid}", playthroughId, chapterId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(
|
||||
new QuestProgressionController.SetStatusRequest("NOPE"))))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.RandomTable;
|
||||
import com.loremind.domain.campaigncontext.RandomTableEntry;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.RandomTableGenerationException;
|
||||
import com.loremind.domain.campaigncontext.ports.RandomTableGenerator;
|
||||
import com.loremind.domain.campaigncontext.ports.RandomTableRepository;
|
||||
import com.loremind.infrastructure.web.controller.RandomTableController.GenerateRequest;
|
||||
import com.loremind.infrastructure.web.controller.RandomTableController.ImproviseRequest;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.RandomTableDTO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link RandomTableController} (CRUD + recherche +
|
||||
* generation IA d'une table + improvisation narrative).
|
||||
* <p>
|
||||
* Le port {@link RandomTableGenerator} (client du Brain) est mocke : sinon les
|
||||
* endpoints /generate et /improvise feraient un vrai appel reseau au service IA
|
||||
* (indisponible en test). Les repos reels servent aux fixtures.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class RandomTableControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private RandomTableRepository tableRepository;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
|
||||
@MockBean private RandomTableGenerator generator;
|
||||
|
||||
private String campaignId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
campaignId = campaignRepository.save(
|
||||
Campaign.builder().name("Camp").description("desc").build()).getId();
|
||||
}
|
||||
|
||||
private RandomTableDTO dto(String name) {
|
||||
RandomTableDTO dto = new RandomTableDTO();
|
||||
dto.setName(name);
|
||||
dto.setDescription("Rencontres aleatoires");
|
||||
dto.setDiceFormula("1d20");
|
||||
dto.setIcon("dice");
|
||||
dto.setCampaignId(campaignId);
|
||||
dto.setOrder(0);
|
||||
return dto;
|
||||
}
|
||||
|
||||
// --- POST / -------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void create_returns200() throws Exception {
|
||||
mockMvc.perform(post("/api/random-tables")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto("Rencontres"))))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Rencontres"))
|
||||
.andExpect(jsonPath("$.diceFormula").value("1d20"));
|
||||
}
|
||||
|
||||
// --- GET /{id} ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
RandomTable saved = tableRepository.save(RandomTable.builder()
|
||||
.name("Butin").diceFormula("1d6").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/random-tables/{id}", saved.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Butin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/random-tables/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- GET /campaign/{campaignId} -----------------------------------------
|
||||
|
||||
@Test
|
||||
void getByCampaign_returnsArray() throws Exception {
|
||||
tableRepository.save(RandomTable.builder()
|
||||
.name("A").diceFormula("1d20").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/random-tables/campaign/{campaignId}", campaignId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$[0].name").value("A"));
|
||||
}
|
||||
|
||||
// --- PUT /{id} ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void update_returns200() throws Exception {
|
||||
RandomTable saved = tableRepository.save(RandomTable.builder()
|
||||
.name("old").diceFormula("1d20").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(put("/api/random-tables/{id}", saved.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto("new"))))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_returns400_whenMissing() throws Exception {
|
||||
// Le service leve IllegalArgumentException -> GlobalExceptionHandler -> 400.
|
||||
mockMvc.perform(put("/api/random-tables/{id}", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(dto("x"))))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
// --- DELETE /{id} -------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void delete_returns204() throws Exception {
|
||||
RandomTable saved = tableRepository.save(RandomTable.builder()
|
||||
.name("X").diceFormula("1d20").campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(delete("/api/random-tables/{id}", saved.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
// --- GET /search --------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void search_returnsArray() throws Exception {
|
||||
tableRepository.save(RandomTable.builder()
|
||||
.name("Complications urbaines").diceFormula("1d20")
|
||||
.campaignId(campaignId).order(0).build());
|
||||
mockMvc.perform(get("/api/random-tables/search").param("q", "Complications"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
// --- POST /generate -----------------------------------------------------
|
||||
|
||||
@Test
|
||||
void generate_returns200() throws Exception {
|
||||
when(generator.generate(any(), any(), any())).thenReturn(
|
||||
new RandomTableGenerator.GeneratedTable(
|
||||
"Rencontres en foret",
|
||||
"Que croisez-vous ?",
|
||||
List.of(RandomTableEntry.builder()
|
||||
.minRoll(1).maxRoll(10).label("Gobelins").build())));
|
||||
|
||||
GenerateRequest req = new GenerateRequest(campaignId, "rencontres en foret", "1d20");
|
||||
mockMvc.perform(post("/api/random-tables/generate")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Rencontres en foret"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generate_returns502_whenBrainUnreachable() throws Exception {
|
||||
when(generator.generate(any(), any(), any()))
|
||||
.thenThrow(new RandomTableGenerationException("Brain injoignable"));
|
||||
|
||||
GenerateRequest req = new GenerateRequest(campaignId, "rencontres", "1d20");
|
||||
mockMvc.perform(post("/api/random-tables/generate")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
|
||||
// --- POST /improvise ----------------------------------------------------
|
||||
|
||||
@Test
|
||||
void improvise_returns200() throws Exception {
|
||||
when(generator.improvise(any(), any(), any(), any()))
|
||||
.thenReturn("Les gobelins surgissent des fourres...");
|
||||
|
||||
ImproviseRequest req = new ImproviseRequest(
|
||||
campaignId, "Rencontres", "Gobelins", "3 gobelins armes");
|
||||
mockMvc.perform(post("/api/random-tables/improvise")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.narration").value("Les gobelins surgissent des fourres..."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void improvise_returns502_whenBrainUnreachable() throws Exception {
|
||||
when(generator.improvise(any(), any(), any(), any()))
|
||||
.thenThrow(new RandomTableGenerationException("Brain injoignable"));
|
||||
|
||||
ImproviseRequest req = new ImproviseRequest(
|
||||
campaignId, "Rencontres", "Gobelins", "3 gobelins");
|
||||
mockMvc.perform(post("/api/random-tables/improvise")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadGateway());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.Session;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.domain.playcontext.ports.SessionRepository;
|
||||
import com.loremind.infrastructure.web.controller.SessionController.RenameSessionRequest;
|
||||
import com.loremind.infrastructure.web.controller.SessionController.StartSessionRequest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration du SessionController.
|
||||
* Chaîne de fixtures : Campaign -> Playthrough (une session appartient à une partie).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class SessionControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private SessionRepository sessionRepository;
|
||||
|
||||
private String playthroughId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
String campaignId = campaignRepository.save(
|
||||
Campaign.builder().name("C").description("").build()).getId();
|
||||
playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campaignId).name("Partie").build()).getId();
|
||||
}
|
||||
|
||||
private Session saveSession() {
|
||||
return sessionRepository.save(Session.builder()
|
||||
.name("Session test")
|
||||
.playthroughId(playthroughId)
|
||||
.startedAt(LocalDateTime.now())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startSession_returns200() throws Exception {
|
||||
StartSessionRequest req = new StartSessionRequest(playthroughId);
|
||||
mockMvc.perform(post("/api/sessions")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.playthroughId").value(playthroughId))
|
||||
.andExpect(jsonPath("$.active").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startSession_returns400_whenPlaythroughMissing() throws Exception {
|
||||
StartSessionRequest req = new StartSessionRequest("999999999");
|
||||
mockMvc.perform(post("/api/sessions")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSessions_all_returnsArray() throws Exception {
|
||||
saveSession();
|
||||
mockMvc.perform(get("/api/sessions"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSessions_byPlaythrough_returnsArray() throws Exception {
|
||||
saveSession();
|
||||
mockMvc.perform(get("/api/sessions").param("playthroughId", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getActive_global_returnsActive() throws Exception {
|
||||
saveSession();
|
||||
mockMvc.perform(get("/api/sessions/active"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.active").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getActive_byPlaythrough_returnsActive() throws Exception {
|
||||
saveSession();
|
||||
mockMvc.perform(get("/api/sessions/active").param("playthroughId", playthroughId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.playthroughId").value(playthroughId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getActive_returns204_whenNone() throws Exception {
|
||||
// Session terminée -> aucune active
|
||||
sessionRepository.save(Session.builder()
|
||||
.name("ended").playthroughId(playthroughId)
|
||||
.startedAt(LocalDateTime.now().minusHours(2))
|
||||
.endedAt(LocalDateTime.now().minusHours(1))
|
||||
.build());
|
||||
mockMvc.perform(get("/api/sessions/active").param("playthroughId", playthroughId))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns200() throws Exception {
|
||||
Session s = saveSession();
|
||||
mockMvc.perform(get("/api/sessions/{id}", s.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Session test"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getById_returns404_whenMissing() throws Exception {
|
||||
mockMvc.perform(get("/api/sessions/{id}", "999999999"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endSession_returns200() throws Exception {
|
||||
Session s = saveSession();
|
||||
mockMvc.perform(post("/api/sessions/{id}/end", s.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.active").value(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void endSession_returns400_whenMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/sessions/{id}/end", "999999999"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameSession_returns200() throws Exception {
|
||||
Session s = saveSession();
|
||||
RenameSessionRequest req = new RenameSessionRequest("Nouveau nom");
|
||||
mockMvc.perform(patch("/api/sessions/{id}", s.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Nouveau nom"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameSession_returns400_whenBlankName() throws Exception {
|
||||
Session s = saveSession();
|
||||
RenameSessionRequest req = new RenameSessionRequest(" ");
|
||||
mockMvc.perform(patch("/api/sessions/{id}", s.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSession_returns204() throws Exception {
|
||||
Session s = saveSession();
|
||||
mockMvc.perform(delete("/api/sessions/{id}", s.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSession_returns400_whenMissing() throws Exception {
|
||||
mockMvc.perform(delete("/api/sessions/{id}", "999999999"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.playcontext.EntryType;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.Session;
|
||||
import com.loremind.domain.playcontext.SessionEntry;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.domain.playcontext.ports.SessionEntryRepository;
|
||||
import com.loremind.domain.playcontext.ports.SessionRepository;
|
||||
import com.loremind.infrastructure.web.controller.SessionEntryController.EntryRequest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'intégration du SessionEntryController (endpoints imbriqués sous une Session).
|
||||
* Chaîne de fixtures : Campaign -> Playthrough -> Session.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
class SessionEntryControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
@Autowired private CampaignRepository campaignRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
@Autowired private SessionRepository sessionRepository;
|
||||
@Autowired private SessionEntryRepository entryRepository;
|
||||
|
||||
private String sessionId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
String campaignId = campaignRepository.save(
|
||||
Campaign.builder().name("C").description("").build()).getId();
|
||||
String playthroughId = playthroughRepository.save(
|
||||
Playthrough.builder().campaignId(campaignId).name("Partie").build()).getId();
|
||||
sessionId = sessionRepository.save(Session.builder()
|
||||
.name("Session")
|
||||
.playthroughId(playthroughId)
|
||||
.startedAt(LocalDateTime.now())
|
||||
.build()).getId();
|
||||
}
|
||||
|
||||
private SessionEntry saveEntry() {
|
||||
return entryRepository.save(SessionEntry.builder()
|
||||
.sessionId(sessionId)
|
||||
.type(EntryType.NOTE)
|
||||
.content("Contenu initial")
|
||||
.occurredAt(LocalDateTime.now())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getEntries_returnsArray() throws Exception {
|
||||
saveEntry();
|
||||
mockMvc.perform(get("/api/sessions/{sessionId}/entries", sessionId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEntry_returns200() throws Exception {
|
||||
EntryRequest req = new EntryRequest(EntryType.EVENT, "Combat gagné", LocalDateTime.now());
|
||||
mockMvc.perform(post("/api/sessions/{sessionId}/entries", sessionId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.content").value("Combat gagné"))
|
||||
.andExpect(jsonPath("$.type").value("EVENT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEntry_defaultsTypeToNote_whenNull() throws Exception {
|
||||
EntryRequest req = new EntryRequest(null, "Note sans type", null);
|
||||
mockMvc.perform(post("/api/sessions/{sessionId}/entries", sessionId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.type").value("NOTE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEntry_returns400_whenSessionMissing() throws Exception {
|
||||
EntryRequest req = new EntryRequest(EntryType.NOTE, "x", null);
|
||||
mockMvc.perform(post("/api/sessions/{sessionId}/entries", "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEntry_returns400_whenContentBlank() throws Exception {
|
||||
EntryRequest req = new EntryRequest(EntryType.NOTE, " ", null);
|
||||
mockMvc.perform(post("/api/sessions/{sessionId}/entries", sessionId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateEntry_returns200() throws Exception {
|
||||
SessionEntry e = saveEntry();
|
||||
EntryRequest req = new EntryRequest(EntryType.DICE_ROLL, "Jet modifié", LocalDateTime.now());
|
||||
mockMvc.perform(put("/api/sessions/{sessionId}/entries/{entryId}", sessionId, e.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.content").value("Jet modifié"))
|
||||
.andExpect(jsonPath("$.type").value("DICE_ROLL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateEntry_returns400_whenMissing() throws Exception {
|
||||
EntryRequest req = new EntryRequest(EntryType.NOTE, "x", null);
|
||||
mockMvc.perform(put("/api/sessions/{sessionId}/entries/{entryId}", sessionId, "999999999")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(req)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteEntry_returns204() throws Exception {
|
||||
SessionEntry e = saveEntry();
|
||||
mockMvc.perform(delete("/api/sessions/{sessionId}/entries/{entryId}", sessionId, e.getId()))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteEntry_returns400_whenMissing() throws Exception {
|
||||
mockMvc.perform(delete("/api/sessions/{sessionId}/entries/{entryId}", sessionId, "999999999"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Verifie le blocage des endpoints sensibles de {@link SettingsController} quand
|
||||
* {@code app.demo-mode=true} : lecture/ecriture des settings et gestion des modeles
|
||||
* Ollama (pull/delete) doivent renvoyer 403, sans jamais toucher le Brain.
|
||||
* <p>
|
||||
* Les requetes sont authentifiees en ADMIN (sinon la securite renverrait 401 avant
|
||||
* d'atteindre le garde demo). Ce test valide donc aussi que le
|
||||
* {@code GlobalExceptionHandler} propage le statut declare par le
|
||||
* {@link org.springframework.web.server.ResponseStatusException} (403), sans l'ecraser en 500.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@TestPropertySource(properties = "app.demo-mode=true")
|
||||
class SettingsControllerDemoModeTest {
|
||||
|
||||
private static final String ADMIN_AUTH = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("test-admin:test-admin-password".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
void getSettings_returns403() throws Exception {
|
||||
mockMvc.perform(get("/api/settings").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateSettings_returns403() throws Exception {
|
||||
mockMvc.perform(put("/api/settings")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"theme\":\"light\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pullOllamaModel_returns403() throws Exception {
|
||||
mockMvc.perform(post("/api/settings/models/ollama/pull")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"llama3\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteOllamaModel_returns403() throws Exception {
|
||||
mockMvc.perform(delete("/api/settings/models/ollama/{name}", "llama3")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Couvre le pull streamé d'un modèle Ollama de {@link SettingsController}
|
||||
* (POST /api/settings/models/ollama/pull). Cet endpoint BYPASS le RestTemplate
|
||||
* (donc {@link SettingsControllerTest} ne peut pas le couvrir via MockRestServiceServer) :
|
||||
* il ouvre un {@code java.net.http.HttpClient} directement vers le Brain et relaie
|
||||
* le NDJSON chunk par chunk.
|
||||
* <p>
|
||||
* On démarre donc un vrai mini serveur HTTP local (JDK {@link HttpServer}) qui imite
|
||||
* la réponse NDJSON du Brain, et on pointe {@code brain.base-url} dessus via
|
||||
* {@link DynamicPropertySource}. Cela exerce tout le corps streamé : sérialisation
|
||||
* {@code toJson} du body, envoi HTTP/1.1, en-tête d'auth interne, boucle de lecture/relai.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class SettingsControllerPullTest {
|
||||
|
||||
/** Identifiants ADMIN (cf. src/test/resources/application.properties) — endpoint sous /api/settings/**. */
|
||||
private static final String ADMIN_AUTH = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("test-admin:test-admin-password".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
private static HttpServer stubBrain;
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@DynamicPropertySource
|
||||
static void brainStub(DynamicPropertyRegistry registry) throws IOException {
|
||||
stubBrain = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
stubBrain.createContext("/models/ollama/pull", exchange -> {
|
||||
// On consomme la requête (le body JSON sérialisé par le controller) puis on
|
||||
// renvoie un flux NDJSON de progression, comme le ferait le Brain/Ollama.
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
byte[] body = ("{\"status\":\"pulling manifest\"}\n"
|
||||
+ "{\"status\":\"success\"}\n").getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/x-ndjson");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
stubBrain.start();
|
||||
int port = stubBrain.getAddress().getPort();
|
||||
registry.add("brain.base-url", () -> "http://127.0.0.1:" + port);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopStub() {
|
||||
if (stubBrain != null) {
|
||||
stubBrain.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pullOllamaModel_streamsBrainNdjson() throws Exception {
|
||||
// Body avec des valeurs de types variés (String/Number/Boolean/null) pour
|
||||
// exercer toutes les branches du sérialiseur maison toJson(...).
|
||||
String body = "{\"name\":\"llama3\",\"n\":3,\"insecure\":true,\"opt\":null}";
|
||||
|
||||
MvcResult result = mockMvc.perform(post("/api/settings/models/ollama/pull")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(body))
|
||||
.andExpect(request().asyncStarted())
|
||||
.andReturn();
|
||||
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("pulling manifest")))
|
||||
.andExpect(content().string(containsString("success")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.client.MockRestServiceServer;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
|
||||
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
|
||||
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
|
||||
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link SettingsController} (proxy fin vers le Brain).
|
||||
* <p>
|
||||
* Le {@link RestTemplate} (@Primary {@code brainRestTemplate}, celui injecte dans
|
||||
* le controller) est instrumente avec {@link MockRestServiceServer} : on intercepte
|
||||
* les appels sortants vers le Brain et on renvoie des reponses canned, sans reseau.
|
||||
* Cela verifie le contrat de proxy (methode, chemin, body relaye, reponse propagee).
|
||||
* <p>
|
||||
* {@code /api/settings/**} exige le role ADMIN (HTTP Basic) : chaque requete porte
|
||||
* donc l'entete d'auth construite a partir des identifiants de test. Le blocage
|
||||
* {@code app.demo-mode} est couvert par {@link SettingsControllerDemoModeTest}.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class SettingsControllerTest {
|
||||
|
||||
/** Identifiants definis dans src/test/resources/application.properties. */
|
||||
private static final String ADMIN_AUTH = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("test-admin:test-admin-password".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@Autowired private RestTemplate restTemplate;
|
||||
|
||||
private MockRestServiceServer brain;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
brain = MockRestServiceServer.createServer(restTemplate);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSettings_forwardsToBrain_andReturnsBody() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/settings")))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess("{\"theme\":\"dark\"}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(get("/api/settings").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.theme").value("dark"));
|
||||
brain.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateSettings_forwardsPatchBody() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/settings")))
|
||||
.andExpect(method(HttpMethod.PUT))
|
||||
.andExpect(content().json("{\"theme\":\"light\"}"))
|
||||
.andRespond(withSuccess("{\"theme\":\"light\"}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(put("/api/settings")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"theme\":\"light\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.theme").value("light"));
|
||||
brain.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listOllamaModels_forwards() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/models/ollama")))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess("{\"models\":[]}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(get("/api/settings/models/ollama").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.models").isArray());
|
||||
brain.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOllamaModelInfo_forwardsPostBody() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/models/ollama/info")))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(content().json("{\"name\":\"llama3\"}"))
|
||||
.andRespond(withSuccess("{\"size\":123}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(post("/api/settings/models/ollama/info")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"llama3\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size").value(123));
|
||||
brain.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteOllamaModel_forwardsWithNameInPath() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/models/ollama/llama3")))
|
||||
.andExpect(method(HttpMethod.DELETE))
|
||||
.andRespond(withSuccess("{\"deleted\":true}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(delete("/api/settings/models/ollama/{name}", "llama3")
|
||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.deleted").value(true));
|
||||
brain.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listOneMinModels_forwards() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/models/onemin")))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess("{\"models\":[]}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(get("/api/settings/models/onemin").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk());
|
||||
brain.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listOpenRouterModels_forwards() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/models/openrouter")))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess("{\"models\":[]}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(get("/api/settings/models/openrouter").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk());
|
||||
brain.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listMistralModels_forwards() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/models/mistral")))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess("{\"models\":[]}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(get("/api/settings/models/mistral").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk());
|
||||
brain.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listGeminiModels_forwards() throws Exception {
|
||||
brain.expect(requestTo(endsWith("/models/gemini")))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess("{\"models\":[]}", MediaType.APPLICATION_JSON));
|
||||
|
||||
mockMvc.perform(get("/api/settings/models/gemini").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk());
|
||||
brain.verify();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.infrastructure.updates.UpdateCheckService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Verifie le verrouillage de {@link UpdatesController} quand {@code app.demo-mode=true} :
|
||||
* check / check-beta / apply doivent renvoyer 403 (garde demo), jamais 401/200.
|
||||
* <p>
|
||||
* Les requetes sont authentifiees en ADMIN (sinon la securite renverrait 401 avant
|
||||
* d'atteindre le garde demo). Le {@code GlobalExceptionHandler} doit propager le
|
||||
* statut du {@link org.springframework.web.server.ResponseStatusException} (403).
|
||||
* Contexte distinct (fichier separe) car la valeur demo-mode est injectee a la
|
||||
* construction du controleur — meme convention que SettingsControllerDemoModeTest.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@TestPropertySource(properties = "app.demo-mode=true")
|
||||
class UpdatesControllerDemoModeTest {
|
||||
|
||||
private static final String ADMIN_AUTH = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("test-admin:test-admin-password".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@MockBean private UpdateCheckService updates;
|
||||
|
||||
@Test
|
||||
void check_returns403_inDemoMode() throws Exception {
|
||||
mockMvc.perform(get("/api/admin/updates/check").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkBeta_returns403_inDemoMode() throws Exception {
|
||||
mockMvc.perform(get("/api/admin/updates/check-beta").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void apply_returns403_inDemoMode() throws Exception {
|
||||
mockMvc.perform(post("/api/admin/updates/apply").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.infrastructure.updates.UpdateCheckService;
|
||||
import com.loremind.infrastructure.updates.UpdateCheckService.BetaStatus;
|
||||
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatus;
|
||||
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatusKind;
|
||||
import com.loremind.infrastructure.updates.UpdateCheckService.UpdateStatus;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link UpdatesController} (endpoints admin).
|
||||
* <p>
|
||||
* Le {@link UpdateCheckService} est mocke : c'est un port externe (registry +
|
||||
* Watchtower). Aucun appel reseau reel. La classe externe couvre le mode normal
|
||||
* (demo off) ; la classe imbriquee {@link DemoMode} force {@code app.demo-mode=true}
|
||||
* pour verifier le verrouillage 403.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class UpdatesControllerTest {
|
||||
|
||||
/** Identifiants admin definis dans src/test/resources/application.properties. */
|
||||
private static final String ADMIN_AUTH = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("test-admin:test-admin-password".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@MockBean private UpdateCheckService updates;
|
||||
|
||||
private UpdateStatus sampleUpdate() {
|
||||
return new UpdateStatus(true, true, false, "1.0.0",
|
||||
List.of(new ImageStatus("img", "1.0.0", "1.1.0", ImageStatusKind.UPDATE_AVAILABLE)),
|
||||
Instant.now());
|
||||
}
|
||||
|
||||
private BetaStatus sampleBeta() {
|
||||
return new BetaStatus(true, false, false, List.of(), Instant.now(), null);
|
||||
}
|
||||
|
||||
// --- GET /check ---------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void check_returns200() throws Exception {
|
||||
when(updates.check()).thenReturn(sampleUpdate());
|
||||
mockMvc.perform(get("/api/admin/updates/check").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.enabled").value(true))
|
||||
.andExpect(jsonPath("$.updateAvailable").value(true));
|
||||
}
|
||||
|
||||
// --- GET /check-beta ----------------------------------------------------
|
||||
|
||||
@Test
|
||||
void checkBeta_returns200() throws Exception {
|
||||
when(updates.checkBeta()).thenReturn(sampleBeta());
|
||||
mockMvc.perform(get("/api/admin/updates/check-beta").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.enabled").value(true));
|
||||
}
|
||||
|
||||
// --- POST /apply --------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void apply_returns202_whenEnabledAndTriggered() throws Exception {
|
||||
when(updates.isEnabled()).thenReturn(true);
|
||||
mockMvc.perform(post("/api/admin/updates/apply").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isAccepted())
|
||||
.andExpect(jsonPath("$.status").value("triggered"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void apply_returns503_whenNotConfigured() throws Exception {
|
||||
when(updates.isEnabled()).thenReturn(false);
|
||||
mockMvc.perform(post("/api/admin/updates/apply").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isServiceUnavailable())
|
||||
.andExpect(jsonPath("$.error").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void apply_returns502_whenWatchtowerUnreachable() throws Exception {
|
||||
when(updates.isEnabled()).thenReturn(true);
|
||||
doThrow(new RuntimeException("connect timeout")).when(updates).apply();
|
||||
mockMvc.perform(post("/api/admin/updates/apply").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||
.andExpect(status().isBadGateway())
|
||||
.andExpect(jsonPath("$.error").exists());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Tests d'integration pour {@link VersionController}.
|
||||
* <p>
|
||||
* Endpoint trivial : GET /api/version renvoie {"version": "..."}.
|
||||
* En test, {@code BuildProperties} peut etre absent (pas de build Maven) :
|
||||
* le controleur retombe alors sur "dev". On verifie seulement que la cle
|
||||
* "version" est presente et non vide.
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class VersionControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
void getVersion_returns200_withVersionKey() throws Exception {
|
||||
mockMvc.perform(get("/api/version"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.version").exists())
|
||||
.andExpect(jsonPath("$.version").isNotEmpty());
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,15 @@ spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.show-sql=false
|
||||
|
||||
# Pool Hikari volontairement minuscule en test : la suite cree de nombreux
|
||||
# contextes Spring distincts (combinaisons de @MockBean / @TestPropertySource),
|
||||
# tous gardes en cache simultanement. Avec le pool par defaut (10), on epuisait
|
||||
# les connexions Postgres ("remaining connection slots are reserved"). 2 par
|
||||
# contexte suffit (tests sequentiels) et borne le total bien sous max_connections.
|
||||
spring.datasource.hikari.maximum-pool-size=2
|
||||
spring.datasource.hikari.minimum-idle=0
|
||||
spring.datasource.hikari.idle-timeout=10000
|
||||
|
||||
# Credentials admin factices pour satisfaire le fail-closed de SecurityConfig.
|
||||
admin.username=test-admin
|
||||
admin.password=test-admin-password
|
||||
|
||||
35
web/package-lock.json
generated
35
web/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "loremind-web",
|
||||
"version": "0.13.0-beta",
|
||||
"version": "0.14.0-beta",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "loremind-web",
|
||||
"version": "0.13.0-beta",
|
||||
"version": "0.14.0-beta",
|
||||
"dependencies": {
|
||||
"@angular/animations": "^21.2.16",
|
||||
"@angular/common": "^21.2.16",
|
||||
@@ -16,6 +16,8 @@
|
||||
"@angular/platform-browser": "^21.2.16",
|
||||
"@angular/platform-browser-dynamic": "^21.2.16",
|
||||
"@angular/router": "^21.2.16",
|
||||
"@ngx-translate/core": "^18.0.0",
|
||||
"@ngx-translate/http-loader": "^18.0.0",
|
||||
"dompurify": "^3.4.1",
|
||||
"lucide-angular": "^1.0.0",
|
||||
"marked": "^18.0.2",
|
||||
@@ -4486,6 +4488,35 @@
|
||||
"webpack": "^5.54.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@ngx-translate/core": {
|
||||
"version": "18.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@ngx-translate/core/-/core-18.0.0.tgz",
|
||||
"integrity": "sha512-Z9u9AXaeuyeHHimivvJQvhal/LJNB+5tlH+FimSU4QQ61FrtRDqgyn6nfFbc6Cb+59NDZdsh4QeTJyPCldFUwA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@angular/common": ">=18",
|
||||
"@angular/core": ">=18",
|
||||
"rxjs": ">=7"
|
||||
}
|
||||
},
|
||||
"node_modules/@ngx-translate/http-loader": {
|
||||
"version": "18.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@ngx-translate/http-loader/-/http-loader-18.0.0.tgz",
|
||||
"integrity": "sha512-p6QpNcU3rkCYjHbKVIadcYtml/Njpr0aLp8neJ4uJWQ4Xm9f09bIePhOjdjAFHupTptKqKrG1J2gSi3RSwgYeA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@angular/common": ">=18",
|
||||
"@angular/core": ">=18",
|
||||
"@ngx-translate/core": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "loremind-web",
|
||||
"version": "0.13.0-beta",
|
||||
"version": "0.14.0-beta",
|
||||
"description": "LoreMind Frontend - Angular",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
@@ -23,6 +23,8 @@
|
||||
"@angular/platform-browser": "^21.2.16",
|
||||
"@angular/platform-browser-dynamic": "^21.2.16",
|
||||
"@angular/router": "^21.2.16",
|
||||
"@ngx-translate/core": "^18.0.0",
|
||||
"@ngx-translate/http-loader": "^18.0.0",
|
||||
"dompurify": "^3.4.1",
|
||||
"lucide-angular": "^1.0.0",
|
||||
"marked": "^18.0.2",
|
||||
|
||||
49
web/scripts/i18n-merge.mjs
Normal file
49
web/scripts/i18n-merge.mjs
Normal file
@@ -0,0 +1,49 @@
|
||||
// Fusionne les fragments de traduction par fonctionnalité dans les fichiers
|
||||
// centraux fr.json / en.json.
|
||||
//
|
||||
// Chaque agent de traduction écrit un fragment dédié sous
|
||||
// src/assets/i18n/fragments/<feature>.<lang>.json contenant uniquement SON
|
||||
// namespace (clé de premier niveau distincte de common/language/settings).
|
||||
// Ce script deep-merge tous ces fragments dans fr.json / en.json — c'est le
|
||||
// SEUL endroit qui écrit les fichiers centraux, ce qui évite tout conflit
|
||||
// d'écriture entre agents parallèles.
|
||||
//
|
||||
// Usage : node scripts/i18n-merge.mjs
|
||||
import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const i18nDir = join(here, '..', 'src', 'assets', 'i18n');
|
||||
const fragDir = join(i18nDir, 'fragments');
|
||||
|
||||
const isObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
function deepMerge(target, source) {
|
||||
for (const key of Object.keys(source)) {
|
||||
if (isObject(source[key]) && isObject(target[key])) {
|
||||
deepMerge(target[key], source[key]);
|
||||
} else {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
for (const lang of ['fr', 'en']) {
|
||||
const basePath = join(i18nDir, `${lang}.json`);
|
||||
const base = JSON.parse(readFileSync(basePath, 'utf8'));
|
||||
|
||||
if (existsSync(fragDir)) {
|
||||
const fragments = readdirSync(fragDir)
|
||||
.filter((f) => f.endsWith(`.${lang}.json`))
|
||||
.sort();
|
||||
for (const frag of fragments) {
|
||||
const data = JSON.parse(readFileSync(join(fragDir, frag), 'utf8'));
|
||||
deepMerge(base, data);
|
||||
}
|
||||
}
|
||||
|
||||
writeFileSync(basePath, JSON.stringify(base, null, 2) + '\n', 'utf8');
|
||||
console.log(`✓ ${lang}.json mis à jour`);
|
||||
}
|
||||
@@ -1,58 +1,58 @@
|
||||
<div class="arc-create-page">
|
||||
|
||||
<div class="page-header">
|
||||
<h1>Créer un nouvel arc narratif</h1>
|
||||
<h1>{{ 'arcCreate.title' | translate }}</h1>
|
||||
</div>
|
||||
|
||||
<form [formGroup]="form" (ngSubmit)="submit()" class="arc-form">
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-create-name">Nom de l'arc *</label>
|
||||
<label for="arc-create-name">{{ 'arcCreate.nameLabel' | translate }}</label>
|
||||
<input
|
||||
id="arc-create-name"
|
||||
type="text"
|
||||
formControlName="name"
|
||||
placeholder="Ex: L'Ombre du Nord"
|
||||
[placeholder]="'arcCreate.namePlaceholder' | translate"
|
||||
[class.invalid]="form.get('name')?.invalid && form.get('name')?.touched"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>Structure de l'arc</label>
|
||||
<label>{{ 'arcCreate.structureLabel' | translate }}</label>
|
||||
<div class="arc-type-choice">
|
||||
<label class="arc-type-option" [class.selected]="form.get('type')?.value === 'LINEAR'">
|
||||
<input type="radio" formControlName="type" value="LINEAR" />
|
||||
<span class="arc-type-title">Linéaire</span>
|
||||
<span class="arc-type-desc">Chapitres joués dans l'ordre — narration séquentielle classique.</span>
|
||||
<span class="arc-type-title">{{ 'arcCreate.linearTitle' | translate }}</span>
|
||||
<span class="arc-type-desc">{{ 'arcCreate.linearDesc' | translate }}</span>
|
||||
</label>
|
||||
<label class="arc-type-option" [class.selected]="form.get('type')?.value === 'HUB'">
|
||||
<input type="radio" formControlName="type" value="HUB" />
|
||||
<span class="arc-type-title">Hub</span>
|
||||
<span class="arc-type-desc">Quêtes parallèles débloquées par des conditions — type sandbox (ex : Phandalin / Icespire Peak).</span>
|
||||
<span class="arc-type-title">{{ 'arcCreate.hubTitle' | translate }}</span>
|
||||
<span class="arc-type-desc">{{ 'arcCreate.hubDesc' | translate }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-create-description">Description</label>
|
||||
<label for="arc-create-description">{{ 'common.description' | translate }}</label>
|
||||
<textarea
|
||||
id="arc-create-description"
|
||||
formControlName="description"
|
||||
placeholder="Décrivez l'arc narratif principal..."
|
||||
[placeholder]="'arcCreate.descriptionPlaceholder' | translate"
|
||||
rows="5">
|
||||
</textarea>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>Icône</label>
|
||||
<label>{{ 'arcCreate.iconLabel' | translate }}</label>
|
||||
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn-primary" [disabled]="form.invalid">
|
||||
Créer l'arc
|
||||
{{ 'arcCreate.submit' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">{{ 'common.cancel' | translate }}</button>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angula
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin } from 'rxjs';
|
||||
import { LucideAngularModule, BookOpen } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
@@ -21,7 +22,7 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-create',
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, IconPickerComponent],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, IconPickerComponent, TranslatePipe],
|
||||
templateUrl: './arc-create.component.html',
|
||||
styleUrls: ['./arc-create.component.scss']
|
||||
})
|
||||
@@ -43,7 +44,8 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
private npcService: NpcService,
|
||||
private randomTableService: RandomTableService,
|
||||
private enemyService: EnemyService,
|
||||
private layoutService: LayoutService
|
||||
private layoutService: LayoutService,
|
||||
private translate: TranslateService
|
||||
) {
|
||||
this.form = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
@@ -66,7 +68,7 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
}).subscribe(({ campaign, allCampaigns, treeData }) => {
|
||||
this.existingArcCount = treeData.arcs.length;
|
||||
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -2,24 +2,24 @@
|
||||
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h1>{{ arc?.name || 'Arc' }}</h1>
|
||||
<p class="subtitle">Arc narratif</p>
|
||||
<h1>{{ arc?.name || ('arcEdit.fallbackTitle' | translate) }}</h1>
|
||||
<p class="subtitle">{{ 'arcEdit.subtitle' | translate }}</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button type="button" class="btn-ai"
|
||||
(click)="toggleChat()"
|
||||
[class.active]="chatOpen"
|
||||
title="Ouvrir l'Assistant IA pour dialoguer autour de cet arc">
|
||||
[title]="'arcEdit.aiAssistantTitle' | translate">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
{{ 'arcEdit.aiAssistant' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">{{ 'common.cancel' | translate }}</button>
|
||||
<button type="button" class="btn-danger" (click)="delete()">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
{{ 'common.delete' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary" (click)="submit()" [disabled]="form.invalid">
|
||||
Sauvegarder
|
||||
{{ 'common.save' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -28,118 +28,118 @@
|
||||
|
||||
<!-- Illustrations (galerie editable, rendu editorial) -->
|
||||
<div class="field">
|
||||
<label>Illustrations</label>
|
||||
<label>{{ 'arcEdit.illustrationsLabel' | translate }}</label>
|
||||
<app-image-gallery
|
||||
[imageIds]="illustrationImageIds"
|
||||
[editable]="true"
|
||||
[layout]="'EDITORIAL'"
|
||||
(imageIdsChange)="illustrationImageIds = $event">
|
||||
</app-image-gallery>
|
||||
<small class="field-hint">Ambiances, portraits, visuels evocateurs de l'arc. JPEG, PNG, WebP ou GIF, 10 Mo max.</small>
|
||||
<small class="field-hint">{{ 'arcEdit.illustrationsHint' | translate }}</small>
|
||||
</div>
|
||||
|
||||
<!-- Cartes & plans -->
|
||||
<div class="field">
|
||||
<label>Cartes & plans</label>
|
||||
<label>{{ 'arcEdit.mapsLabel' | translate }}</label>
|
||||
<app-image-gallery
|
||||
[imageIds]="mapImageIds"
|
||||
[editable]="true"
|
||||
[layout]="'MAPS'"
|
||||
(imageIdsChange)="mapImageIds = $event">
|
||||
</app-image-gallery>
|
||||
<small class="field-hint">Cartes regionales et plans utiles aux joueurs pour situer l'action.</small>
|
||||
<small class="field-hint">{{ 'arcEdit.mapsHint' | translate }}</small>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-edit-name">Titre de l'arc *</label>
|
||||
<label for="arc-edit-name">{{ 'arcEdit.nameLabel' | translate }}</label>
|
||||
<input
|
||||
id="arc-edit-name"
|
||||
type="text"
|
||||
formControlName="name"
|
||||
placeholder="Ex: L'Ombre du Nord"
|
||||
[placeholder]="'arcEdit.namePlaceholder' | translate"
|
||||
[class.invalid]="form.get('name')?.invalid && form.get('name')?.touched"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-edit-description">Synopsis de l'arc</label>
|
||||
<label for="arc-edit-description">{{ 'arcEdit.synopsisLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="arc-edit-description"
|
||||
formControlName="description"
|
||||
placeholder="Décrivez l'histoire principale de cet arc narratif..."
|
||||
[placeholder]="'arcEdit.synopsisPlaceholder' | translate"
|
||||
rows="5">
|
||||
</textarea>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>Structure de l'arc</label>
|
||||
<label>{{ 'arcEdit.structureLabel' | translate }}</label>
|
||||
<div class="arc-type-choice">
|
||||
<label class="arc-type-option" [class.selected]="form.get('type')?.value === 'LINEAR'">
|
||||
<input type="radio" formControlName="type" value="LINEAR" />
|
||||
<span class="arc-type-title">Linéaire</span>
|
||||
<span class="arc-type-desc">Chapitres joués dans l'ordre — narration séquentielle.</span>
|
||||
<span class="arc-type-title">{{ 'arcEdit.linearTitle' | translate }}</span>
|
||||
<span class="arc-type-desc">{{ 'arcEdit.linearDesc' | translate }}</span>
|
||||
</label>
|
||||
<label class="arc-type-option" [class.selected]="form.get('type')?.value === 'HUB'">
|
||||
<input type="radio" formControlName="type" value="HUB" />
|
||||
<span class="arc-type-title">Hub</span>
|
||||
<span class="arc-type-desc">Quêtes parallèles débloquées par des conditions (sandbox).</span>
|
||||
<span class="arc-type-title">{{ 'arcEdit.hubTitle' | translate }}</span>
|
||||
<span class="arc-type-desc">{{ 'arcEdit.hubDesc' | translate }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>Icône</label>
|
||||
<label>{{ 'arcEdit.iconLabel' | translate }}</label>
|
||||
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
|
||||
</div>
|
||||
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="arc-edit-themes">Thèmes principaux</label>
|
||||
<label for="arc-edit-themes">{{ 'arcEdit.themesLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="arc-edit-themes"
|
||||
formControlName="themes"
|
||||
placeholder="Quels sont les thèmes explorés dans cet arc ? (trahison, rédemption...)"
|
||||
[placeholder]="'arcEdit.themesPlaceholder' | translate"
|
||||
rows="4">
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="arc-edit-stakes">Enjeux globaux</label>
|
||||
<label for="arc-edit-stakes">{{ 'arcEdit.stakesLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="arc-edit-stakes"
|
||||
formControlName="stakes"
|
||||
placeholder="Quels sont les enjeux majeurs de cet arc pour les personnages ?"
|
||||
[placeholder]="'arcEdit.stakesPlaceholder' | translate"
|
||||
rows="4">
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-edit-gm-notes">Notes et planification du MJ</label>
|
||||
<label for="arc-edit-gm-notes">{{ 'arcEdit.gmNotesLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="arc-edit-gm-notes"
|
||||
formControlName="gmNotes"
|
||||
placeholder="Vos notes sur la direction de l'arc, les twists prévus, les révélations importantes..."
|
||||
[placeholder]="'arcEdit.gmNotesPlaceholder' | translate"
|
||||
rows="5">
|
||||
</textarea>
|
||||
<small class="field-hint">Ces notes sont privées et ne seront pas exportées vers FoundryVTT.</small>
|
||||
<small class="field-hint">{{ 'arcEdit.gmNotesHint' | translate }}</small>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-edit-rewards">Récompenses et progression</label>
|
||||
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="arc-edit-rewards"
|
||||
formControlName="rewards"
|
||||
placeholder="Quelles récompenses les joueurs obtiendront-ils ? Objets, niveaux, connaissances, contacts..."
|
||||
[placeholder]="'arcEdit.rewardsPlaceholder' | translate"
|
||||
rows="4">
|
||||
</textarea>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-edit-resolution">Dénouement prévu</label>
|
||||
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="arc-edit-resolution"
|
||||
formControlName="resolution"
|
||||
placeholder="Comment cet arc devrait-il se terminer ? Quelles sont les issues possibles ?"
|
||||
[placeholder]="'arcEdit.resolutionPlaceholder' | translate"
|
||||
rows="4">
|
||||
</textarea>
|
||||
</div>
|
||||
@@ -147,7 +147,7 @@
|
||||
<!-- ===== Pages Lore associées (phase B2 cross-context) ===== -->
|
||||
@if (loreId) {
|
||||
<div class="field">
|
||||
<label>Pages Lore associées</label>
|
||||
<label>{{ 'arcEdit.relatedPagesLabel' | translate }}</label>
|
||||
<app-lore-link-picker
|
||||
[value]="relatedPageIds"
|
||||
[availablePages]="availablePages"
|
||||
@@ -155,7 +155,7 @@
|
||||
(valueChange)="relatedPageIds = $event">
|
||||
</app-lore-link-picker>
|
||||
<small class="field-hint">
|
||||
Liez cet arc à des PNJ, lieux ou éléments du Lore. Cliquez sur un chip pour ouvrir la page associée.
|
||||
{{ 'arcEdit.relatedPagesHint' | translate }}
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
@@ -163,8 +163,7 @@
|
||||
@if (!loreId) {
|
||||
<div class="field lore-hint">
|
||||
<small class="field-hint">
|
||||
💡 Cette campagne n'est associée à aucun univers. Associez-la à un Lore dans l'écran de la campagne
|
||||
pour pouvoir lier cet arc à des pages du Lore (PNJ, lieux, etc.).
|
||||
{{ 'arcEdit.noLoreHint' | translate }}
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
@@ -179,7 +178,7 @@
|
||||
entityType="arc"
|
||||
[entityId]="arcId"
|
||||
[isOpen]="chatOpen"
|
||||
welcomeMessage="Je vois cet arc. Demande-moi d'enrichir ses thèmes, ses enjeux ou son dénouement."
|
||||
[welcomeMessage]="'arcEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { LucideAngularModule, Trash2, Sparkles } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
@@ -34,7 +35,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-edit',
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, TranslatePipe],
|
||||
templateUrl: './arc-edit.component.html',
|
||||
styleUrls: ['./arc-edit.component.scss']
|
||||
})
|
||||
@@ -46,11 +47,13 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
|
||||
/** État drawer chat IA (b5.7 — intégration Campagne). */
|
||||
chatOpen = false;
|
||||
readonly chatQuickSuggestions = [
|
||||
'Propose 3 thèmes majeurs pour cet arc',
|
||||
'Imagine des enjeux qui mettent la pression sur les joueurs',
|
||||
'Suggère un dénouement en deux actes'
|
||||
get chatQuickSuggestions(): string[] {
|
||||
return [
|
||||
this.translate.instant('arcEdit.chatSuggestion1'),
|
||||
this.translate.instant('arcEdit.chatSuggestion2'),
|
||||
this.translate.instant('arcEdit.chatSuggestion3')
|
||||
];
|
||||
}
|
||||
|
||||
toggleChat(): void { this.chatOpen = !this.chatOpen; }
|
||||
|
||||
@@ -83,7 +86,8 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
private pageService: PageService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {
|
||||
this.form = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
@@ -149,7 +153,7 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
resolution: arc.resolution ?? ''
|
||||
});
|
||||
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -178,10 +182,10 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
|
||||
delete(): void {
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer l\'arc',
|
||||
message: `Supprimer l'arc "${this.arc?.name}" ?`,
|
||||
details: ['Cette action est irréversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('arcEdit.deleteTitle'),
|
||||
message: this.translate.instant('arcEdit.deleteMessage', { name: this.arc?.name }),
|
||||
details: [this.translate.instant('arcEdit.irreversible')],
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -9,17 +9,17 @@
|
||||
{{ arc.name }}
|
||||
</h1>
|
||||
<p class="view-subtitle">
|
||||
{{ arc.type === 'HUB' ? 'Arc en hub (quêtes non linéaires)' : 'Arc narratif' }}
|
||||
{{ (arc.type === 'HUB' ? 'arcView.subtitleHub' : 'arcView.subtitleLinear') | translate }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="view-actions">
|
||||
<button type="button" class="btn-primary" (click)="editMode()">
|
||||
<lucide-icon [img]="Pencil" [size]="14"></lucide-icon>
|
||||
Modifier
|
||||
{{ 'common.edit' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-danger" (click)="deleteArc()" title="Supprimer l'arc et tout son contenu">
|
||||
<button type="button" class="btn-danger" (click)="deleteArc()" [title]="'arcView.deleteTitle' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
{{ 'common.delete' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -32,7 +32,7 @@
|
||||
<!-- Cartes & plans -->
|
||||
@if ((arc.mapImageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> Cartes & plans</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> {{ 'arcView.mapsTitle' | translate }}</h2>
|
||||
<app-image-gallery [imageIds]="arc.mapImageIds ?? []" [layout]="'MAPS'"></app-image-gallery>
|
||||
</section>
|
||||
}
|
||||
@@ -40,10 +40,10 @@
|
||||
Le statut effectif et les actions de jeu vivent dans l'écran d'une Partie. -->
|
||||
@if (arc.type === 'HUB') {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> Quêtes du hub (scénario)</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> {{ 'arcView.hubQuestsTitle' | translate }}</h2>
|
||||
@if (hubQuests.length === 0) {
|
||||
<p class="view-section-empty">
|
||||
Aucune quête pour ce hub. Créez-en une pour démarrer.
|
||||
{{ 'arcView.hubQuestsEmpty' | translate }}
|
||||
</p>
|
||||
}
|
||||
@if (hubQuests.length > 0) {
|
||||
@@ -66,7 +66,7 @@
|
||||
@if ((q.prerequisites?.length ?? 0) > 0) {
|
||||
<div class="hub-quest-card-locked-hint">
|
||||
<lucide-icon [img]="AlertCircle" [size]="13"></lucide-icon>
|
||||
<span>{{ q.prerequisites!.length }} condition(s) de déblocage</span>
|
||||
<span>{{ 'arcView.unlockConditions' | translate:{ n: q.prerequisites!.length } }}</span>
|
||||
<ul class="hub-quest-card-prereq-list">
|
||||
@for (p of q.prerequisites; track p) {
|
||||
<li>{{ describePrerequisite(p) }}</li>
|
||||
@@ -81,45 +81,45 @@
|
||||
</section>
|
||||
}
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">📜</span> Synopsis</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">📜</span> {{ 'arcView.synopsisTitle' | translate }}</h2>
|
||||
@if (arc.description?.trim()) {
|
||||
<p class="view-section-body">{{ arc.description }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
<p class="view-section-empty">{{ 'arcView.notProvided' | translate }}</p>
|
||||
}
|
||||
</section>
|
||||
<div class="view-row">
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">✨</span> Thèmes principaux</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">✨</span> {{ 'arcView.themesTitle' | translate }}</h2>
|
||||
@if (arc.themes?.trim()) {
|
||||
<p class="view-section-body">{{ arc.themes }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
<p class="view-section-empty">{{ 'arcView.notProvided' | translate }}</p>
|
||||
}
|
||||
</section>
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">⚖️</span> Enjeux globaux</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">⚖️</span> {{ 'arcView.stakesTitle' | translate }}</h2>
|
||||
@if (arc.stakes?.trim()) {
|
||||
<p class="view-section-body">{{ arc.stakes }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
<p class="view-section-empty">{{ 'arcView.notProvided' | translate }}</p>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎁</span> Récompenses et progression</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎁</span> {{ 'arcView.rewardsTitle' | translate }}</h2>
|
||||
@if (arc.rewards?.trim()) {
|
||||
<p class="view-section-body">{{ arc.rewards }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
<p class="view-section-empty">{{ 'arcView.notProvided' | translate }}</p>
|
||||
}
|
||||
</section>
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎬</span> Dénouement prévu</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎬</span> {{ 'arcView.resolutionTitle' | translate }}</h2>
|
||||
@if (arc.resolution?.trim()) {
|
||||
<p class="view-section-body">{{ arc.resolution }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
<p class="view-section-empty">{{ 'arcView.notProvided' | translate }}</p>
|
||||
}
|
||||
</section>
|
||||
<!-- Notes MJ (bloc privé rouge discret) -->
|
||||
@@ -127,7 +127,7 @@
|
||||
<section class="view-section view-section--private">
|
||||
<h2 class="view-section-title">
|
||||
<span class="view-section-icon">🔒</span>
|
||||
Notes et planification du MJ
|
||||
{{ 'arcView.gmNotesTitle' | translate }}
|
||||
</h2>
|
||||
<p class="view-section-body">{{ arc.gmNotes }}</p>
|
||||
</section>
|
||||
@@ -135,7 +135,7 @@
|
||||
<!-- Pages Lore liées (chips cliquables) -->
|
||||
@if (loreId && (arc.relatedPageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔗</span> Pages Lore associées</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔗</span> {{ 'arcView.relatedPagesTitle' | translate }}</h2>
|
||||
<div class="view-chips">
|
||||
@for (relId of arc.relatedPageIds; track relId) {
|
||||
<a class="view-chip"
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { LucideAngularModule, Pencil, Trash2, AlertCircle } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { resolveCampaignIcon } from '../../campaign-icons';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
@@ -26,7 +27,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-view',
|
||||
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent],
|
||||
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe],
|
||||
templateUrl: './arc-view.component.html',
|
||||
styleUrls: ['./arc-view.component.scss']
|
||||
})
|
||||
@@ -65,7 +66,8 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
private pageService: PageService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -111,7 +113,7 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
list.forEach(c => { if (c.id) this.allChaptersById[c.id] = c; })
|
||||
);
|
||||
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -119,11 +121,11 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
describePrerequisite(p: Prerequisite): string {
|
||||
switch (p.kind) {
|
||||
case 'QUEST_COMPLETED':
|
||||
return `Quête « ${this.allChaptersById[p.questId]?.name ?? '?'} » terminée`;
|
||||
return this.translate.instant('arcView.prereqQuestCompleted', { name: this.allChaptersById[p.questId]?.name ?? '?' });
|
||||
case 'SESSION_REACHED':
|
||||
return `Session ${p.minSessionNumber} atteinte`;
|
||||
return this.translate.instant('arcView.prereqSessionReached', { n: p.minSessionNumber });
|
||||
case 'FLAG_SET':
|
||||
return `Fait : ${p.flagName}`;
|
||||
return this.translate.instant('arcView.prereqFlagSet', { flag: p.flagName });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,7 +137,7 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
titleOfRelated(pageId: string): string {
|
||||
return this.availablePages.find(p => p.id === pageId)?.title ?? '(page supprimée)';
|
||||
return this.availablePages.find(p => p.id === pageId)?.title ?? this.translate.instant('arcView.deletedPage');
|
||||
}
|
||||
|
||||
editMode(): void {
|
||||
@@ -153,20 +155,24 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
this.campaignService.getArcDeletionImpact(arc.id!).subscribe({
|
||||
next: impact => {
|
||||
const parts: string[] = [];
|
||||
if (impact.chapters > 0) parts.push(`${impact.chapters} chapitre${impact.chapters > 1 ? 's' : ''}`);
|
||||
if (impact.scenes > 0) parts.push(`${impact.scenes} scène${impact.scenes > 1 ? 's' : ''}`);
|
||||
if (impact.chapters > 0) {
|
||||
parts.push(this.translate.instant(impact.chapters > 1 ? 'arcView.chaptersPlural' : 'arcView.chaptersSingular', { n: impact.chapters }));
|
||||
}
|
||||
if (impact.scenes > 0) {
|
||||
parts.push(this.translate.instant(impact.scenes > 1 ? 'arcView.scenesPlural' : 'arcView.scenesSingular', { n: impact.scenes }));
|
||||
}
|
||||
|
||||
const details: string[] = [];
|
||||
if (parts.length) {
|
||||
details.push(`Cette action supprimera aussi : ${parts.join(', ')}.`);
|
||||
details.push(this.translate.instant('arcView.deleteCascade', { parts: parts.join(', ') }));
|
||||
}
|
||||
details.push('Cette action est irréversible.');
|
||||
details.push(this.translate.instant('arcView.irreversible'));
|
||||
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer l\'arc',
|
||||
message: `Supprimer l'arc "${arc.name}" ?`,
|
||||
title: this.translate.instant('arcView.deleteConfirmTitle'),
|
||||
message: this.translate.instant('arcView.deleteConfirmMessage', { name: arc.name }),
|
||||
details,
|
||||
confirmLabel: 'Supprimer',
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Observable, forkJoin, of } from 'rxjs';
|
||||
import { switchMap, map } from 'rxjs/operators';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { CampaignService } from '../services/campaign.service';
|
||||
import { CharacterService } from '../services/character.service';
|
||||
import { NpcService } from '../services/npc.service';
|
||||
@@ -92,7 +93,7 @@ export function loadCampaignTreeData(
|
||||
);
|
||||
}
|
||||
|
||||
export function buildCampaignTree(campaignId: string, data: CampaignTreeData): TreeItem[] {
|
||||
export function buildCampaignTree(campaignId: string, data: CampaignTreeData, translate: TranslateService): TreeItem[] {
|
||||
// Tri FR avec `numeric: true` pour que "1. Intro", "2. Voyage", "10. Final" soient
|
||||
// classés 1, 2, 10 (et pas 1, 10, 2). `sensitivity: 'base'` ignore la casse.
|
||||
const byName = (a: { name: string }, b: { name: string }) =>
|
||||
@@ -140,7 +141,7 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
|
||||
const npcsNode: TreeItem = {
|
||||
id: 'npcs-root',
|
||||
label: 'PNJ',
|
||||
label: translate.instant('campaignTree.npcs'),
|
||||
iconKey: 'c-drama',
|
||||
children: npcChildren,
|
||||
meta: sortedNpcs.length ? String(sortedNpcs.length) : undefined,
|
||||
@@ -149,10 +150,10 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
route: `/campaigns/${campaignId}/npcs`,
|
||||
// Porte le header de section "Personnages" (les PJ ayant migré vers la Partie).
|
||||
// Le filet au-dessus est masqué par CSS si c'est le tout premier item de la sidebar.
|
||||
sectionHeaderBefore: 'Personnages',
|
||||
sectionHeaderBefore: translate.instant('campaignTree.sectionCharacters'),
|
||||
createActions: [{
|
||||
id: 'new-npc',
|
||||
label: 'Nouveau PNJ',
|
||||
label: translate.instant('campaignTree.newNpc'),
|
||||
route: `/campaigns/${campaignId}/npcs/create`,
|
||||
actionIcon: 'plus'
|
||||
}]
|
||||
@@ -216,7 +217,7 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
route: `/campaigns/${campaignId}/arcs/${arc.id}/chapters/${ch.id}`,
|
||||
createActions: [{
|
||||
id: `new-scene-${ch.id}`,
|
||||
label: 'Nouvelle scène',
|
||||
label: translate.instant('campaignTree.newScene'),
|
||||
route: `/campaigns/${campaignId}/arcs/${arc.id}/chapters/${ch.id}/scenes/create`,
|
||||
actionIcon: 'plus'
|
||||
}]
|
||||
@@ -228,12 +229,12 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
iconKey: arc.icon ?? undefined,
|
||||
children: chapterItems,
|
||||
route: `/campaigns/${campaignId}/arcs/${arc.id}`,
|
||||
sectionHeaderBefore: idx === 0 ? 'Narration' : undefined,
|
||||
sectionHeaderBefore: idx === 0 ? translate.instant('campaignTree.sectionNarration') : undefined,
|
||||
|
||||
createActions: [{
|
||||
id: `new-chapter-${arc.id}`,
|
||||
// Dans un arc hub, un "chapitre" est présenté comme une "quête".
|
||||
label: arc.type === 'HUB' ? 'Nouvelle quête' : 'Nouveau chapitre',
|
||||
label: arc.type === 'HUB' ? translate.instant('campaignTree.newQuest') : translate.instant('campaignTree.newChapter'),
|
||||
route: `/campaigns/${campaignId}/arcs/${arc.id}/chapters/create`,
|
||||
actionIcon: 'plus'
|
||||
}]
|
||||
@@ -250,14 +251,14 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
|
||||
const tablesNode: TreeItem = {
|
||||
id: 'random-tables-root',
|
||||
label: 'Tables aléatoires',
|
||||
label: translate.instant('campaignTree.randomTables'),
|
||||
iconKey: 'dice',
|
||||
children: tableItems,
|
||||
meta: tableItems.length ? String(tableItems.length) : undefined,
|
||||
sectionHeaderBefore: 'Outils',
|
||||
sectionHeaderBefore: translate.instant('campaignTree.sectionTools'),
|
||||
createActions: [{
|
||||
id: 'new-random-table',
|
||||
label: 'Nouvelle table',
|
||||
label: translate.instant('campaignTree.newTable'),
|
||||
route: `/campaigns/${campaignId}/random-tables/create`,
|
||||
actionIcon: 'plus'
|
||||
}]
|
||||
@@ -266,7 +267,7 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
// Lien simple vers les ateliers (la liste se charge sur sa page — pas de fetch ici).
|
||||
const notebooksNode: TreeItem = {
|
||||
id: 'notebooks-root',
|
||||
label: 'Ateliers (IA + PDF)',
|
||||
label: translate.instant('campaignTree.notebooks'),
|
||||
iconKey: 'book-open',
|
||||
route: `/campaigns/${campaignId}/notebooks`
|
||||
};
|
||||
@@ -274,7 +275,7 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
// Catalogues d'objets (boutiques, butins…) → page de liste (outil).
|
||||
const catalogsNode: TreeItem = {
|
||||
id: 'item-catalogs-root',
|
||||
label: 'Catalogues d\'objets',
|
||||
label: translate.instant('campaignTree.itemCatalogs'),
|
||||
iconKey: 'package',
|
||||
route: `/campaigns/${campaignId}/item-catalogs`
|
||||
};
|
||||
@@ -284,14 +285,14 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
// Libellé → page de liste ; chevron → arbre dépliable (dossiers → fiches).
|
||||
const enemiesNode: TreeItem = {
|
||||
id: 'enemies-root',
|
||||
label: 'Ennemis',
|
||||
label: translate.instant('campaignTree.enemies'),
|
||||
iconKey: 'skull',
|
||||
children: enemyChildren,
|
||||
meta: sortedEnemies.length ? String(sortedEnemies.length) : undefined,
|
||||
route: `/campaigns/${campaignId}/enemies`,
|
||||
createActions: [{
|
||||
id: 'new-enemy',
|
||||
label: 'Nouvel ennemi',
|
||||
label: translate.instant('campaignTree.newEnemy'),
|
||||
route: `/campaigns/${campaignId}/enemies/create`,
|
||||
actionIcon: 'plus'
|
||||
}]
|
||||
@@ -300,7 +301,7 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
// Importer un PDF de campagne → arborescence (outil, comme tables & ateliers).
|
||||
const importNode: TreeItem = {
|
||||
id: 'import-pdf-root',
|
||||
label: 'Importer un PDF',
|
||||
label: translate.instant('campaignTree.importPdf'),
|
||||
iconKey: 'file-up',
|
||||
route: `/campaigns/${campaignId}/import`
|
||||
};
|
||||
@@ -322,7 +323,8 @@ export function buildCampaignSidebarConfig(
|
||||
campaign: Campaign,
|
||||
allCampaigns: Campaign[],
|
||||
treeData: CampaignTreeData,
|
||||
campaignId: string
|
||||
campaignId: string,
|
||||
translate: TranslateService
|
||||
): SecondarySidebarConfig {
|
||||
const globalItems: GlobalItem[] = allCampaigns.map(c => ({
|
||||
id: c.id!, name: c.name, route: `/campaigns/${c.id}`
|
||||
@@ -331,13 +333,13 @@ export function buildCampaignSidebarConfig(
|
||||
title: campaign.name,
|
||||
// Titre cliquable → accueil de la campagne (raccourci depuis n'importe quelle sous-page).
|
||||
titleRoute: `/campaigns/${campaignId}`,
|
||||
items: buildCampaignTree(campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
items: buildCampaignTree(campaignId, treeData, translate),
|
||||
footerLabel: translate.instant('campaignTree.allCampaigns'),
|
||||
createActions: [
|
||||
{ id: 'create-arc', label: '+ Nouvel arc', variant: 'primary', route: `/campaigns/${campaignId}/arcs/create` }
|
||||
{ id: 'create-arc', label: translate.instant('campaignTree.newArc'), variant: 'primary', route: `/campaigns/${campaignId}/arcs/create` }
|
||||
],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackLabel: translate.instant('campaignTree.allCampaigns'),
|
||||
globalBackRoute: '/campaigns'
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="modal" (click)="$event.stopPropagation()">
|
||||
|
||||
<div class="modal-header">
|
||||
<h2>Créer une nouvelle Campagne</h2>
|
||||
<h2>{{ 'campaignCreate.title' | translate }}</h2>
|
||||
<button class="btn-close" (click)="onCancel()">
|
||||
<lucide-icon [img]="X" [size]="18"></lucide-icon>
|
||||
</button>
|
||||
@@ -11,54 +11,51 @@
|
||||
<form [formGroup]="form" (ngSubmit)="submit()">
|
||||
|
||||
<div class="field">
|
||||
<label for="campaign-name">Nom de la campagne *</label>
|
||||
<label for="campaign-name">{{ 'campaignCreate.nameLabel' | translate }}</label>
|
||||
<input
|
||||
id="campaign-name"
|
||||
type="text"
|
||||
formControlName="name"
|
||||
placeholder="Ex: L'Ombre du Nord, Les Héritiers Oubliés..."
|
||||
[placeholder]="'campaignCreate.namePlaceholder' | translate"
|
||||
[class.invalid]="form.get('name')?.invalid && form.get('name')?.touched"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="campaign-description">Description / Pitch</label>
|
||||
<label for="campaign-description">{{ 'campaignCreate.descriptionLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="campaign-description"
|
||||
formControlName="description"
|
||||
placeholder="Résumez l'intrigue principale de votre campagne..."
|
||||
[placeholder]="'campaignCreate.descriptionPlaceholder' | translate"
|
||||
rows="5"
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="campaign-player-count">Nombre de joueurs</label>
|
||||
<label for="campaign-player-count">{{ 'campaignCreate.playerCountLabel' | translate }}</label>
|
||||
<input id="campaign-player-count" type="number" formControlName="playerCount" min="1" />
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="campaign-lore">Univers associé</label>
|
||||
<label for="campaign-lore">{{ 'campaignCreate.loreLabel' | translate }}</label>
|
||||
<select id="campaign-lore" formControlName="loreId">
|
||||
<option value="">— Aucun univers (campagne libre) —</option>
|
||||
<option value="">{{ 'campaignCreate.noLoreOption' | translate }}</option>
|
||||
@for (lore of availableLores; track lore) {
|
||||
<option [value]="lore.id">{{ lore.name }}</option>
|
||||
}
|
||||
</select>
|
||||
<p class="hint">
|
||||
Optionnel. Si associée, vous pourrez lier arcs, chapitres et scènes aux pages du Lore.
|
||||
Laissez vide pour un one-shot ou si vous créerez le Lore plus tard.
|
||||
</p>
|
||||
<p class="hint">{{ 'campaignCreate.loreHint' | translate }}</p>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="campaign-game-system">Système de JDR</label>
|
||||
<label for="campaign-game-system">{{ 'campaignCreate.gameSystemLabel' | translate }}</label>
|
||||
@if (!creatingGameSystem) {
|
||||
<select id="campaign-game-system" formControlName="gameSystemId">
|
||||
<option value="">— Aucun (campagne générique) —</option>
|
||||
<option value="">{{ 'campaignCreate.noGameSystemOption' | translate }}</option>
|
||||
@for (gs of availableGameSystems; track gs) {
|
||||
<option [value]="gs.id">{{ gs.name }}</option>
|
||||
}
|
||||
<option [value]="CREATE_GAMESYSTEM_SENTINEL">+ Créer un nouveau système…</option>
|
||||
<option [value]="CREATE_GAMESYSTEM_SENTINEL">{{ 'campaignCreate.createGameSystemOption' | translate }}</option>
|
||||
</select>
|
||||
}
|
||||
|
||||
@@ -69,7 +66,7 @@
|
||||
type="text"
|
||||
[(ngModel)]="newGameSystemName"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
placeholder="Nom du nouveau système (ex: D&D 5e, Nimble, Maison)"
|
||||
[placeholder]="'campaignCreate.gameSystemNamePlaceholder' | translate"
|
||||
(keydown.enter)="$event.preventDefault(); submitCreateGameSystem()"
|
||||
(keydown.escape)="cancelCreateGameSystem()"
|
||||
autofocus
|
||||
@@ -79,50 +76,39 @@
|
||||
[disabled]="!newGameSystemName.trim() || creatingGameSystemInFlight"
|
||||
(click)="submitCreateGameSystem()">
|
||||
<lucide-icon [img]="Check" [size]="14"></lucide-icon>
|
||||
Créer
|
||||
{{ 'common.create' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-inline-secondary" (click)="cancelCreateGameSystem()">
|
||||
Annuler
|
||||
{{ 'common.cancel' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="hint">
|
||||
Création rapide — vous pourrez ajouter les règles, les templates de fiches PJ/PNJ
|
||||
et le reste depuis la section "Systèmes" plus tard.
|
||||
</p>
|
||||
<p class="hint">{{ 'campaignCreate.gameSystemCreateHint' | translate }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!creatingGameSystem) {
|
||||
<p class="hint">
|
||||
Optionnel. Si défini, l'IA injectera les règles du système (classes, combat, lore...)
|
||||
dans ses suggestions pour respecter les mécaniques du JDR.
|
||||
</p>
|
||||
<p class="hint">{{ 'campaignCreate.gameSystemHint' | translate }}</p>
|
||||
}
|
||||
@if (!creatingGameSystem) {
|
||||
<p class="hint hint-warning">
|
||||
⚠️ Le système de jeu choisi détermine aussi le <strong>template des fiches de PJ et PNJ</strong>.
|
||||
Le changer plus tard rendra les champs des fiches existantes invisibles
|
||||
(les données restent stockées mais ne s'afficheront qu'en revenant à l'ancien système).
|
||||
Choisissez bien dès le départ si possible.
|
||||
</p>
|
||||
<p class="hint hint-warning" [innerHTML]="'campaignCreate.gameSystemWarning' | translate"></p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="info-box">
|
||||
<p><strong>💡 Organisation :</strong> Votre campagne sera structurée en :</p>
|
||||
<p [innerHTML]="'campaignCreate.orgIntro' | translate"></p>
|
||||
<ul>
|
||||
<li><strong>Arcs</strong> - Les grandes phases narratives</li>
|
||||
<li><strong>Chapitres</strong> - Les segments d'un arc</li>
|
||||
<li><strong>Scènes</strong> - Les moments de jeu individuels</li>
|
||||
<li [innerHTML]="'campaignCreate.orgArcs' | translate"></li>
|
||||
<li [innerHTML]="'campaignCreate.orgChapters' | translate"></li>
|
||||
<li [innerHTML]="'campaignCreate.orgScenes' | translate"></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button type="submit" class="btn-primary" [disabled]="form.invalid">
|
||||
<lucide-icon [img]="BookCopy" [size]="16"></lucide-icon>
|
||||
Créer la campagne
|
||||
{{ 'campaignCreate.submit' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="onCancel()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="onCancel()">{{ 'common.cancel' | translate }}</button>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Component, EventEmitter, OnInit, Output } from '@angular/core';
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, BookCopy, X, Plus, Check } from 'lucide-angular';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
import { LoreService } from '../../../services/lore.service';
|
||||
import { Lore } from '../../../services/lore.model';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
@@ -22,7 +23,7 @@ export interface CampaignCreatePayload {
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-create',
|
||||
imports: [ReactiveFormsModule, FormsModule, LucideAngularModule],
|
||||
imports: [ReactiveFormsModule, FormsModule, LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './campaign-create.component.html',
|
||||
styleUrls: ['./campaign-create.component.scss']
|
||||
})
|
||||
|
||||
@@ -7,22 +7,22 @@
|
||||
<h1>{{ campaign.name }}</h1>
|
||||
<p class="description">{{ campaign.description }}</p>
|
||||
<div class="meta">
|
||||
<span class="badge">{{ campaign.playerCount || 0 }} joueurs</span>
|
||||
<span class="badge">{{ 'campaignDetail.players' | translate:{ n: campaign.playerCount || 0 } }}</span>
|
||||
<!-- Badge "Univers" : lien vers le Lore associé si présent -->
|
||||
@if (linkedLore) {
|
||||
<a
|
||||
class="badge badge-lore"
|
||||
[routerLink]="['/lore', linkedLore.id]"
|
||||
title="Ouvrir l'univers associé">
|
||||
[title]="'campaignDetail.openLinkedLore' | translate">
|
||||
<lucide-icon [img]="Globe" [size]="12"></lucide-icon>
|
||||
{{ linkedLore.name }}
|
||||
</a>
|
||||
}
|
||||
<!-- Campagne liée à un Lore qui n'existe plus (supprimé ailleurs) -->
|
||||
@if (campaign.loreId && !linkedLore) {
|
||||
<span class="badge badge-lore-missing" title="L'univers associé est introuvable">
|
||||
<span class="badge badge-lore-missing" [title]="'campaignDetail.loreMissingTitle' | translate">
|
||||
<lucide-icon [img]="Globe" [size]="12"></lucide-icon>
|
||||
Univers introuvable
|
||||
{{ 'campaignDetail.loreMissing' | translate }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
@@ -30,11 +30,11 @@
|
||||
<div class="header-actions">
|
||||
<button type="button" class="btn-secondary" (click)="startEdit()">
|
||||
<lucide-icon [img]="Pencil" [size]="14"></lucide-icon>
|
||||
Modifier
|
||||
{{ 'common.edit' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-danger" (click)="deleteCampaign()">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
{{ 'common.delete' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -43,34 +43,34 @@
|
||||
@if (editing) {
|
||||
<div class="detail-header edit-mode">
|
||||
<div class="field">
|
||||
<label>Nom</label>
|
||||
<label>{{ 'common.name' | translate }}</label>
|
||||
<input type="text" [(ngModel)]="editName" name="editName" required />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Description</label>
|
||||
<label>{{ 'common.description' | translate }}</label>
|
||||
<textarea [(ngModel)]="editDescription" name="editDescription" rows="3"></textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Univers associé</label>
|
||||
<label>{{ 'campaignDetail.loreLabel' | translate }}</label>
|
||||
<select [(ngModel)]="editLoreId" name="editLoreId">
|
||||
<option value="">— Aucun univers (campagne libre) —</option>
|
||||
<option value="">{{ 'campaignDetail.noLoreOption' | translate }}</option>
|
||||
@for (lore of availableLores; track lore) {
|
||||
<option [value]="lore.id">{{ lore.name }}</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Système de JDR</label>
|
||||
<label>{{ 'campaignDetail.gameSystemLabel' | translate }}</label>
|
||||
@if (!creatingGameSystem) {
|
||||
<select
|
||||
[(ngModel)]="editGameSystemId"
|
||||
name="editGameSystemId"
|
||||
(ngModelChange)="onEditGameSystemChange($event)">
|
||||
<option value="">— Aucun (générique) —</option>
|
||||
<option value="">{{ 'campaignDetail.noGameSystemOption' | translate }}</option>
|
||||
@for (gs of availableGameSystems; track gs) {
|
||||
<option [value]="gs.id">{{ gs.name }}</option>
|
||||
}
|
||||
<option [value]="CREATE_GAMESYSTEM_SENTINEL">+ Créer un nouveau système…</option>
|
||||
<option [value]="CREATE_GAMESYSTEM_SENTINEL">{{ 'campaignDetail.createGameSystemOption' | translate }}</option>
|
||||
</select>
|
||||
}
|
||||
@if (creatingGameSystem) {
|
||||
@@ -79,7 +79,7 @@
|
||||
type="text"
|
||||
[(ngModel)]="newGameSystemName"
|
||||
name="newGameSystemName"
|
||||
placeholder="Nom du nouveau système (ex: D&D 5e, Nimble, Maison)"
|
||||
[placeholder]="'campaignDetail.gameSystemNamePlaceholder' | translate"
|
||||
(keydown.enter)="$event.preventDefault(); submitCreateGameSystem()"
|
||||
(keydown.escape)="cancelCreateGameSystem()"
|
||||
autofocus
|
||||
@@ -89,10 +89,10 @@
|
||||
[disabled]="!newGameSystemName.trim() || creatingGameSystemInFlight"
|
||||
(click)="submitCreateGameSystem()">
|
||||
<lucide-icon [img]="Check" [size]="14"></lucide-icon>
|
||||
Créer
|
||||
{{ 'common.create' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-inline-secondary" (click)="cancelCreateGameSystem()">
|
||||
Annuler
|
||||
{{ 'common.cancel' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -100,10 +100,10 @@
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button type="button" class="btn-primary" (click)="saveEdit()" [disabled]="!editName.trim()">
|
||||
Sauvegarder
|
||||
{{ 'common.save' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancelEdit()">
|
||||
Annuler
|
||||
{{ 'common.cancel' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -111,7 +111,7 @@
|
||||
@if (!editing) {
|
||||
<section class="detail-section personas-section">
|
||||
<div class="section-header">
|
||||
<h2>Personnages</h2>
|
||||
<h2>{{ 'campaignDetail.charactersTitle' | translate }}</h2>
|
||||
</div>
|
||||
<!-- Les PJ ne sont plus rattachés à la campagne mais à une Partie (Playthrough) :
|
||||
ils se gèrent depuis la page d'une Partie. Ici on ne liste que les PNJ
|
||||
@@ -121,14 +121,14 @@
|
||||
<div class="subsection-header">
|
||||
<h3>
|
||||
<lucide-icon [img]="Drama" [size]="16"></lucide-icon>
|
||||
Personnages non-joueurs
|
||||
{{ 'campaignDetail.npcTitle' | translate }}
|
||||
@if (npcs.length > 0) {
|
||||
<span class="count-badge">{{ npcs.length }}</span>
|
||||
}
|
||||
</h3>
|
||||
<button class="btn-add" (click)="createNpc()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
Nouveau PNJ
|
||||
{{ 'campaignDetail.newNpc' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
@if (npcs.length > 0) {
|
||||
@@ -146,10 +146,10 @@
|
||||
}
|
||||
@if (npcs.length === 0) {
|
||||
<div class="empty-state empty-state--compact">
|
||||
<p>Aucun PNJ pour le moment.</p>
|
||||
<p>{{ 'campaignDetail.noNpc' | translate }}</p>
|
||||
<button class="btn-add-first" (click)="createNpc()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
Créer votre premier PNJ
|
||||
{{ 'campaignDetail.createFirstNpc' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
@@ -159,11 +159,11 @@
|
||||
@if (!editing) {
|
||||
<section class="detail-section arcs-section">
|
||||
<div class="section-header">
|
||||
<h2>Arcs narratifs</h2>
|
||||
<h2>{{ 'campaignDetail.arcsTitle' | translate }}</h2>
|
||||
<div class="section-header-actions">
|
||||
<button class="btn-add" (click)="createArc()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
Nouvel arc
|
||||
{{ 'campaignDetail.newArc' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -173,7 +173,7 @@
|
||||
<div class="arc-card" (click)="openArc(arc)">
|
||||
<lucide-icon [img]="Swords" [size]="24" class="arc-icon"></lucide-icon>
|
||||
<span class="arc-name">{{ arc.name }}</span>
|
||||
<span class="arc-meta">{{ chapterCountByArc[arc.id!] || 0 }} chapitres</span>
|
||||
<span class="arc-meta">{{ 'campaignDetail.chapters' | translate:{ n: chapterCountByArc[arc.id!] || 0 } }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@@ -181,10 +181,10 @@
|
||||
@if (arcs.length === 0) {
|
||||
<div class="empty-state">
|
||||
<lucide-icon [img]="Swords" [size]="40" class="empty-icon"></lucide-icon>
|
||||
<p>Aucun arc narratif pour le moment.</p>
|
||||
<p>{{ 'campaignDetail.noArc' | translate }}</p>
|
||||
<button class="btn-add-first" (click)="createArc()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
Créer votre premier arc
|
||||
{{ 'campaignDetail.createFirstArc' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
@@ -196,11 +196,11 @@
|
||||
<div class="section-header">
|
||||
<h2>
|
||||
<lucide-icon [img]="Dices" [size]="18"></lucide-icon>
|
||||
Mes parties
|
||||
{{ 'campaignDetail.playthroughsTitle' | translate }}
|
||||
</h2>
|
||||
<button class="btn-add" [disabled]="newPlaythroughInFlight" (click)="createPlaythrough()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
Nouvelle partie
|
||||
{{ 'campaignDetail.newPlaythrough' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
@if (playthroughs.length > 0) {
|
||||
@@ -221,7 +221,7 @@
|
||||
}
|
||||
@if (playthroughs.length === 0) {
|
||||
<div class="empty-state empty-state--compact">
|
||||
<p>Aucune partie. Créez-en une pour démarrer une session avec une table.</p>
|
||||
<p>{{ 'campaignDetail.noPlaythrough' | translate }}</p>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, Dices, Drama, Check, Play, Upload, Sparkles } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
import { catchError, switchMap, filter, map } from 'rxjs/operators';
|
||||
@@ -28,7 +29,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-detail',
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink],
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe],
|
||||
templateUrl: './campaign-detail.component.html',
|
||||
styleUrls: ['./campaign-detail.component.scss']
|
||||
})
|
||||
@@ -101,7 +102,8 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
private playthroughService: PlaythroughService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -216,7 +218,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
createPlaythrough(): void {
|
||||
if (!this.campaign || this.newPlaythroughInFlight) return;
|
||||
this.newPlaythroughInFlight = true;
|
||||
const defaultName = `Nouvelle partie ${this.playthroughs.length + 1}`;
|
||||
const defaultName = this.translate.instant('campaignDetail.defaultPlaythroughName', { n: this.playthroughs.length + 1 });
|
||||
this.playthroughService.create({
|
||||
campaignId: this.campaign.id!,
|
||||
name: defaultName
|
||||
@@ -275,7 +277,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private showLayout(allCampaigns: Campaign[], data: CampaignTreeData): void {
|
||||
this.layoutService.show(buildCampaignSidebarConfig(this.campaign!, allCampaigns, data, this.campaign!.id!));
|
||||
this.layoutService.show(buildCampaignSidebarConfig(this.campaign!, allCampaigns, data, this.campaign!.id!, this.translate));
|
||||
}
|
||||
|
||||
// ─────────────── Édition / suppression de la Campagne ───────────────
|
||||
@@ -352,16 +354,14 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
if (gameSystemChanged && hasSheets) {
|
||||
const count = this.npcs.length;
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Changer le systeme de jeu ?',
|
||||
message:
|
||||
`Vous etes sur le point de changer le systeme de jeu de cette campagne. ` +
|
||||
`Cela change egalement le template des fiches de PJ et PNJ.`,
|
||||
title: this.translate.instant('campaignDetail.gameSystemChange.title'),
|
||||
message: this.translate.instant('campaignDetail.gameSystemChange.message'),
|
||||
details: [
|
||||
`${count} fiche(s) existante(s) sont liees au template du systeme actuel.`,
|
||||
`Leurs champs ne s'afficheront plus avec le nouveau systeme.`,
|
||||
`Les donnees restent stockees : revenir a l'ancien systeme les rendra a nouveau visibles.`
|
||||
this.translate.instant('campaignDetail.gameSystemChange.detailSheets', { n: count }),
|
||||
this.translate.instant('campaignDetail.gameSystemChange.detailFields'),
|
||||
this.translate.instant('campaignDetail.gameSystemChange.detailStored')
|
||||
],
|
||||
confirmLabel: 'Changer quand meme',
|
||||
confirmLabel: this.translate.instant('campaignDetail.gameSystemChange.confirm'),
|
||||
variant: 'warning'
|
||||
}).then(ok => { if (ok) this.persistEdit(newGameSystemId); });
|
||||
return;
|
||||
@@ -400,20 +400,20 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
this.campaignService.getCampaignDeletionImpact(campaign.id!).subscribe({
|
||||
next: impact => {
|
||||
const parts: string[] = [];
|
||||
if (impact.arcs > 0) parts.push(`${impact.arcs} arc${impact.arcs > 1 ? 's' : ''}`);
|
||||
if (impact.chapters > 0) parts.push(`${impact.chapters} chapitre${impact.chapters > 1 ? 's' : ''}`);
|
||||
if (impact.scenes > 0) parts.push(`${impact.scenes} scène${impact.scenes > 1 ? 's' : ''}`);
|
||||
if (impact.playthroughs > 0) parts.push(`${impact.playthroughs} partie${impact.playthroughs > 1 ? 's' : ''} (avec ses PJ, sessions, faits)`);
|
||||
if (impact.arcs > 0) parts.push(this.translate.instant(impact.arcs > 1 ? 'campaignDetail.delete.arcsPlural' : 'campaignDetail.delete.arcs', { n: impact.arcs }));
|
||||
if (impact.chapters > 0) parts.push(this.translate.instant(impact.chapters > 1 ? 'campaignDetail.delete.chaptersPlural' : 'campaignDetail.delete.chapters', { n: impact.chapters }));
|
||||
if (impact.scenes > 0) parts.push(this.translate.instant(impact.scenes > 1 ? 'campaignDetail.delete.scenesPlural' : 'campaignDetail.delete.scenes', { n: impact.scenes }));
|
||||
if (impact.playthroughs > 0) parts.push(this.translate.instant(impact.playthroughs > 1 ? 'campaignDetail.delete.playthroughsPlural' : 'campaignDetail.delete.playthroughs', { n: impact.playthroughs }));
|
||||
|
||||
const details: string[] = [];
|
||||
if (parts.length) details.push(`Sera aussi supprime : ${parts.join(', ')}.`);
|
||||
details.push('Cette action est irreversible.');
|
||||
if (parts.length) details.push(this.translate.instant('campaignDetail.delete.alsoDeletes', { items: parts.join(', ') }));
|
||||
details.push(this.translate.instant('campaignDetail.delete.irreversible'));
|
||||
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer la campagne ?',
|
||||
message: `Supprimer definitivement la campagne "${campaign.name}" ?`,
|
||||
title: this.translate.instant('campaignDetail.delete.title'),
|
||||
message: this.translate.instant('campaignDetail.delete.message', { name: campaign.name }),
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
details,
|
||||
confirmLabel: 'Supprimer',
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -3,13 +3,10 @@
|
||||
<div class="page-header">
|
||||
<button type="button" class="btn-back" (click)="cancel()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour à la campagne
|
||||
{{ 'campaignImport.back' | translate }}
|
||||
</button>
|
||||
<h1>Importer un PDF de campagne</h1>
|
||||
<p class="subtitle">
|
||||
L'IA propose une arborescence arc → chapitre → scène. Vous la révisez et l'ajustez
|
||||
avant de créer quoi que ce soit.
|
||||
</p>
|
||||
<h1>{{ 'campaignImport.title' | translate }}</h1>
|
||||
<p class="subtitle">{{ 'campaignImport.subtitle' | translate }}</p>
|
||||
</div>
|
||||
|
||||
<!-- Étape 1 : upload (masqué une fois en revue) -->
|
||||
@@ -18,7 +15,7 @@
|
||||
<input #pdfInput type="file" accept="application/pdf,.pdf" hidden (change)="onPdfSelected($event)" />
|
||||
<button type="button" class="btn-primary big" [disabled]="importing" (click)="pdfInput.click()">
|
||||
<lucide-icon [img]="Upload" [size]="16"></lucide-icon>
|
||||
{{ importing ? 'Import en cours…' : 'Choisir un PDF de campagne' }}
|
||||
{{ (importing ? 'campaignImport.importing' : 'campaignImport.choosePdf') | translate }}
|
||||
</button>
|
||||
<!-- Progression live -->
|
||||
@if (importing) {
|
||||
@@ -36,7 +33,7 @@
|
||||
}
|
||||
@if (importCounts) {
|
||||
<p class="import-counts">
|
||||
Trouvé jusqu'ici : {{ importCounts.arcs }} arc(s) · {{ importCounts.chapters }} chapitre(s) · {{ importCounts.scenes }} scène(s) · {{ importCounts.npcs }} PNJ
|
||||
{{ 'campaignImport.foundSoFar' | translate:{ arcs: importCounts.arcs, chapters: importCounts.chapters, scenes: importCounts.scenes, npcs: importCounts.npcs } }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
@@ -52,12 +49,7 @@
|
||||
<section class="review-area">
|
||||
<div class="review-header">
|
||||
<p class="review-summary">
|
||||
À créer : <strong>{{ arcCount }}</strong> nouvel(s) arc(s),
|
||||
<strong>{{ chapterCount }}</strong> chapitre(s),
|
||||
<strong>{{ sceneCount }}</strong> scène(s)@if (npcs.length > 0) {<span>,
|
||||
<strong>{{ npcCount }}</strong> PNJ</span>}.
|
||||
Les éléments <em>« déjà présent »</em> (grisés) sont affichés pour situer les ajouts ;
|
||||
ils ne seront pas recréés. Modifiez les nouveaux, puis créez.
|
||||
<span [innerHTML]="'campaignImport.summaryToCreate' | translate:{ arcs: arcCount, chapters: chapterCount, scenes: sceneCount }"></span>@if (npcs.length > 0) {<span [innerHTML]="'campaignImport.summaryNpcs' | translate:{ npcs: npcCount }"></span>}<span [innerHTML]="'campaignImport.summaryHint' | translate"></span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="tree">
|
||||
@@ -70,12 +62,12 @@
|
||||
</button>
|
||||
<lucide-icon [img]="Swords" [size]="16" class="node-icon"></lucide-icon>
|
||||
<input type="text" class="node-name" [(ngModel)]="arc.name" [name]="'arc-' + ai"
|
||||
[readonly]="arc.existing" placeholder="Nom de l'arc" />
|
||||
[readonly]="arc.existing" [placeholder]="'campaignImport.arcNamePlaceholder' | translate" />
|
||||
@if (arc.existing) {
|
||||
<span class="badge-existing">déjà présent</span>
|
||||
<span class="badge-existing">{{ 'campaignImport.alreadyPresent' | translate }}</span>
|
||||
}
|
||||
@if (!arc.existing) {
|
||||
<button type="button" class="btn-remove" (click)="removeArc(ai)" title="Supprimer l'arc">
|
||||
<button type="button" class="btn-remove" (click)="removeArc(ai)" [title]="'campaignImport.removeArc' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
@@ -84,16 +76,16 @@
|
||||
<div class="node-body">
|
||||
@if (!arc.existing) {
|
||||
<div class="arc-type-toggle">
|
||||
<span class="toggle-label">Type :</span>
|
||||
<span class="toggle-label">{{ 'campaignImport.typeLabel' | translate }}</span>
|
||||
<button type="button" class="type-btn" [class.active]="arc.type === 'LINEAR'"
|
||||
(click)="setArcType(arc, 'LINEAR')">Linéaire</button>
|
||||
(click)="setArcType(arc, 'LINEAR')">{{ 'campaignImport.typeLinear' | translate }}</button>
|
||||
<button type="button" class="type-btn" [class.active]="arc.type === 'HUB'"
|
||||
(click)="setArcType(arc, 'HUB')">Hub (quêtes)</button>
|
||||
(click)="setArcType(arc, 'HUB')">{{ 'campaignImport.typeHub' | translate }}</button>
|
||||
</div>
|
||||
}
|
||||
@if (!arc.existing) {
|
||||
<textarea class="node-desc" [(ngModel)]="arc.description" [name]="'arc-desc-' + ai"
|
||||
rows="2" placeholder="Synopsis de l'arc (optionnel)"></textarea>
|
||||
rows="2" [placeholder]="'campaignImport.arcSynopsisPlaceholder' | translate"></textarea>
|
||||
}
|
||||
<!-- Chapitres -->
|
||||
@for (chapter of arc.chapters; track chapter; let ci = $index) {
|
||||
@@ -104,12 +96,12 @@
|
||||
</button>
|
||||
<lucide-icon [img]="BookOpen" [size]="14" class="node-icon"></lucide-icon>
|
||||
<input type="text" class="node-name" [(ngModel)]="chapter.name" [name]="'chap-' + ai + '-' + ci"
|
||||
[readonly]="chapter.existing" placeholder="Nom du chapitre" />
|
||||
[readonly]="chapter.existing" [placeholder]="'campaignImport.chapterNamePlaceholder' | translate" />
|
||||
@if (chapter.existing) {
|
||||
<span class="badge-existing">déjà présent</span>
|
||||
<span class="badge-existing">{{ 'campaignImport.alreadyPresent' | translate }}</span>
|
||||
}
|
||||
@if (!chapter.existing) {
|
||||
<button type="button" class="btn-remove" (click)="removeChapter(arc, ci)" title="Supprimer le chapitre">
|
||||
<button type="button" class="btn-remove" (click)="removeChapter(arc, ci)" [title]="'campaignImport.removeChapter' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="13"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
@@ -118,7 +110,7 @@
|
||||
<div class="node-body">
|
||||
@if (!chapter.existing) {
|
||||
<textarea class="node-desc" [(ngModel)]="chapter.description" [name]="'chap-desc-' + ai + '-' + ci"
|
||||
rows="2" placeholder="Synopsis du chapitre (optionnel)"></textarea>
|
||||
rows="2" [placeholder]="'campaignImport.chapterSynopsisPlaceholder' | translate"></textarea>
|
||||
}
|
||||
<!-- Scènes -->
|
||||
@for (scene of chapter.scenes; track scene; let si = $index) {
|
||||
@@ -129,60 +121,60 @@
|
||||
<div class="scene-fields">
|
||||
<input type="text" class="node-name" [(ngModel)]="scene.name"
|
||||
[name]="'scene-' + ai + '-' + ci + '-' + si" [readonly]="scene.existing"
|
||||
placeholder="Nom de la scène" />
|
||||
[placeholder]="'campaignImport.sceneNamePlaceholder' | translate" />
|
||||
@if (!scene.existing) {
|
||||
<input type="text" class="node-desc-inline" [(ngModel)]="scene.description"
|
||||
[name]="'scene-desc-' + ai + '-' + ci + '-' + si" placeholder="Synopsis (optionnel)" />
|
||||
[name]="'scene-desc-' + ai + '-' + ci + '-' + si" [placeholder]="'campaignImport.synopsisOptionalPlaceholder' | translate" />
|
||||
}
|
||||
</div>
|
||||
@if (scene.existing) {
|
||||
<span class="badge-existing">déjà présent</span>
|
||||
<span class="badge-existing">{{ 'campaignImport.alreadyPresent' | translate }}</span>
|
||||
}
|
||||
@if (!scene.existing) {
|
||||
<button type="button" class="btn-details" (click)="toggleDetails(scene)"
|
||||
title="Narration joueurs, notes MJ, pièces">
|
||||
[title]="'campaignImport.detailsTitle' | translate">
|
||||
<lucide-icon [img]="scene.detailsOpen ? ChevronDown : ChevronRight" [size]="12"></lucide-icon>
|
||||
Détails@if (scene.rooms.length) {
|
||||
<span> · {{ scene.rooms.length }} pièce(s)</span>
|
||||
{{ 'campaignImport.details' | translate }}@if (scene.rooms.length) {
|
||||
<span> {{ 'campaignImport.roomsCount' | translate:{ n: scene.rooms.length } }}</span>
|
||||
}
|
||||
</button>
|
||||
}
|
||||
@if (!scene.existing) {
|
||||
<button type="button" class="btn-remove" (click)="removeScene(chapter, si)" title="Supprimer la scène">
|
||||
<button type="button" class="btn-remove" (click)="removeScene(chapter, si)" [title]="'campaignImport.removeScene' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="13"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@if (scene.detailsOpen && !scene.existing) {
|
||||
<div class="scene-details">
|
||||
<label class="field-label">À lire aux joueurs</label>
|
||||
<label class="field-label">{{ 'campaignImport.playerNarrationLabel' | translate }}</label>
|
||||
<textarea class="node-desc" [(ngModel)]="scene.playerNarration"
|
||||
[name]="'scene-pn-' + ai + '-' + ci + '-' + si" rows="3"
|
||||
placeholder="Texte d'encadré lu aux joueurs (optionnel)"></textarea>
|
||||
<label class="field-label">Notes MJ</label>
|
||||
[placeholder]="'campaignImport.playerNarrationPlaceholder' | translate"></textarea>
|
||||
<label class="field-label">{{ 'campaignImport.gmNotesLabel' | translate }}</label>
|
||||
<textarea class="node-desc" [(ngModel)]="scene.gmNotes"
|
||||
[name]="'scene-gm-' + ai + '-' + ci + '-' + si" rows="3"
|
||||
placeholder="Secrets, développement, conséquences (optionnel)"></textarea>
|
||||
[placeholder]="'campaignImport.gmNotesPlaceholder' | translate"></textarea>
|
||||
<!-- Pièces (donjon) : vide = scène narrative classique -->
|
||||
<span class="field-label">Pièces (lieu explorable)</span>
|
||||
<span class="field-label">{{ 'campaignImport.roomsLabel' | translate }}</span>
|
||||
<div class="rooms">
|
||||
@for (room of scene.rooms; track room; let ri = $index) {
|
||||
<div class="room-row">
|
||||
<input type="text" class="room-name" [(ngModel)]="room.name"
|
||||
[name]="'room-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Pièce" />
|
||||
[name]="'room-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.roomPlaceholder' | translate" />
|
||||
<input type="text" class="room-field" [(ngModel)]="room.description"
|
||||
[name]="'room-desc-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Description" />
|
||||
[name]="'room-desc-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'common.description' | translate" />
|
||||
<input type="text" class="room-field" [(ngModel)]="room.enemies"
|
||||
[name]="'room-en-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Ennemis" />
|
||||
[name]="'room-en-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.enemiesPlaceholder' | translate" />
|
||||
<input type="text" class="room-field" [(ngModel)]="room.loot"
|
||||
[name]="'room-loot-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Trésor" />
|
||||
<button type="button" class="btn-remove" (click)="removeRoom(scene, ri)" title="Supprimer la pièce">
|
||||
[name]="'room-loot-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.lootPlaceholder' | translate" />
|
||||
<button type="button" class="btn-remove" (click)="removeRoom(scene, ri)" [title]="'campaignImport.removeRoom' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="12"></lucide-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
<button type="button" class="btn-add-inline" (click)="addRoom(scene)">
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Pièce
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> {{ 'campaignImport.room' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -190,32 +182,29 @@
|
||||
</div>
|
||||
}
|
||||
<button type="button" class="btn-add-inline" (click)="addScene(chapter)">
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Scène
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> {{ 'campaignImport.scene' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<button type="button" class="btn-add-inline" (click)="addChapter(arc)">
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Chapitre
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> {{ 'campaignImport.chapter' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<button type="button" class="btn-add" (click)="addArc()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> Ajouter un arc
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> {{ 'campaignImport.addArc' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- PNJ détectés dans le PDF : revue par cases à cocher -->
|
||||
@if (npcs.length > 0) {
|
||||
<div class="npc-review">
|
||||
<h3>PNJ et créatures détectés ({{ npcs.length }})</h3>
|
||||
<p class="hint">
|
||||
Cochez ceux à créer dans la campagne (description issue du livre).
|
||||
Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.
|
||||
</p>
|
||||
<h3>{{ 'campaignImport.npcReviewTitle' | translate:{ n: npcs.length } }}</h3>
|
||||
<p class="hint">{{ 'campaignImport.npcReviewHint' | translate }}</p>
|
||||
<ul class="npc-list">
|
||||
@for (npc of npcs; track npc.name) {
|
||||
<li class="npc-row" [class.npc-existing]="npc.existing">
|
||||
@@ -223,7 +212,7 @@
|
||||
<input type="checkbox" [(ngModel)]="npc.selected" [disabled]="npc.existing">
|
||||
<strong>{{ npc.name }}</strong>
|
||||
@if (npc.existing) {
|
||||
<em class="npc-tag">déjà présent</em>
|
||||
<em class="npc-tag">{{ 'campaignImport.alreadyPresent' | translate }}</em>
|
||||
}
|
||||
</label>
|
||||
@if (npc.description) {
|
||||
@@ -241,9 +230,9 @@
|
||||
<div class="review-actions">
|
||||
<button type="button" class="btn-primary" [disabled]="applying || !hasNewContent" (click)="apply()">
|
||||
<lucide-icon [img]="Check" [size]="16"></lucide-icon>
|
||||
{{ applying ? 'Création…' : 'Créer dans la campagne' }}
|
||||
{{ (applying ? 'campaignImport.creating' : 'campaignImport.createInCampaign') | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">{{ 'common.cancel' | translate }}</button>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
LucideAngularModule, ArrowLeft, Upload, Plus, Trash2,
|
||||
ChevronDown, ChevronRight, Swords, BookOpen, MapPin, Check
|
||||
} from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { CampaignImportService } from '../../../services/campaign-import.service';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
@@ -53,7 +54,7 @@ interface NpcNode { name: string; description: string; selected: boolean; existi
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-campaign-import',
|
||||
imports: [FormsModule, LucideAngularModule],
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './campaign-import.component.html',
|
||||
styleUrls: ['./campaign-import.component.scss']
|
||||
})
|
||||
@@ -109,12 +110,13 @@ export class CampaignImportComponent implements OnInit {
|
||||
private randomTableService: RandomTableService,
|
||||
private enemyService: EnemyService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private pageTitle: PageTitleService
|
||||
private pageTitle: PageTitleService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.campaignId = this.route.snapshot.paramMap.get('campaignId')!;
|
||||
this.pageTitle.set('Importer une campagne');
|
||||
this.pageTitle.set(this.translate.instant('campaignImport.pageTitle'));
|
||||
this.campaignSidebar.show(this.campaignId);
|
||||
|
||||
// Pré-chargement de l'arborescence existante (pour fusionner à la revue).
|
||||
@@ -138,7 +140,7 @@ export class CampaignImportComponent implements OnInit {
|
||||
this.reviewing = false;
|
||||
this.importError = null;
|
||||
this.applyError = null;
|
||||
this.importPhase = 'Extraction du texte…';
|
||||
this.importPhase = this.translate.instant('campaignImport.phaseExtracting');
|
||||
this.importProgress = null;
|
||||
this.importStatus = null;
|
||||
this.importCounts = null;
|
||||
@@ -150,10 +152,10 @@ export class CampaignImportComponent implements OnInit {
|
||||
// Un morceau vient d'aboutir : le message d'attente est obsolète.
|
||||
this.importStatus = null;
|
||||
if (ev.total === 0) {
|
||||
this.importPhase = 'Extraction du texte…';
|
||||
this.importPhase = this.translate.instant('campaignImport.phaseExtracting');
|
||||
this.importProgress = null;
|
||||
} else {
|
||||
this.importPhase = `Analyse de la campagne… (${ev.current}/${ev.total})`;
|
||||
this.importPhase = this.translate.instant('campaignImport.phaseAnalyzing', { current: ev.current, total: ev.total });
|
||||
this.importProgress = { current: ev.current, total: ev.total };
|
||||
this.importCounts = {
|
||||
arcs: ev.arcCount, chapters: ev.chapterCount,
|
||||
@@ -168,7 +170,7 @@ export class CampaignImportComponent implements OnInit {
|
||||
this.importProgress = null;
|
||||
this.importStatus = null;
|
||||
if ((ev.arcs ?? []).length === 0 && (ev.npcs ?? []).length === 0) {
|
||||
this.importError = "Aucune structure narrative détectée dans ce PDF.";
|
||||
this.importError = this.translate.instant('campaignImport.errorNoStructure');
|
||||
this.reviewing = false;
|
||||
} else {
|
||||
this.tree = this.buildMergedTree(ev.arcs ?? []);
|
||||
@@ -181,7 +183,9 @@ export class CampaignImportComponent implements OnInit {
|
||||
this.importing = false;
|
||||
this.importPhase = '';
|
||||
this.importProgress = null;
|
||||
this.importError = err?.message ? `Échec de l'import : ${err.message}` : "Échec de l'import du PDF.";
|
||||
this.importError = err?.message
|
||||
? this.translate.instant('campaignImport.errorImportDetail', { message: err.message })
|
||||
: this.translate.instant('campaignImport.errorImport');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -413,7 +417,7 @@ export class CampaignImportComponent implements OnInit {
|
||||
next: () => this.router.navigate(['/campaigns', this.campaignId]),
|
||||
error: () => {
|
||||
this.applying = false;
|
||||
this.applyError = "Échec de la création. La campagne existe-t-elle toujours ?";
|
||||
this.applyError = this.translate.instant('campaignImport.errorApply');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
<div class="campaigns-hero">
|
||||
<lucide-icon [img]="Map" [size]="56" class="hero-icon"></lucide-icon>
|
||||
<h1>Vos Campagnes</h1>
|
||||
<p class="hero-subtitle">Rejoignez une campagne ou créez-en de nouvelles</p>
|
||||
<h1>{{ 'campaigns.heroTitle' | translate }}</h1>
|
||||
<p class="hero-subtitle">{{ 'campaigns.heroSubtitle' | translate }}</p>
|
||||
</div>
|
||||
|
||||
<div class="campaigns-grid">
|
||||
@@ -11,14 +11,14 @@
|
||||
@for (campaign of campaigns; track campaign) {
|
||||
<div class="campaign-card" (click)="navigateToDetail(campaign.id!)">
|
||||
<div class="card-header">
|
||||
<span class="status-badge en-cours">En cours</span>
|
||||
<span class="card-date">{{ campaign.playerCount }} joueurs</span>
|
||||
<span class="status-badge en-cours">{{ 'campaigns.statusInProgress' | translate }}</span>
|
||||
<span class="card-date">{{ 'campaigns.players' | translate:{ n: campaign.playerCount || 0 } }}</span>
|
||||
</div>
|
||||
<h2>{{ campaign.name }}</h2>
|
||||
<p class="card-description">{{ campaign.description }}</p>
|
||||
<div class="card-stats">
|
||||
<span>⚔️ {{ campaign.arcCount || 0 }} arcs</span>
|
||||
<span>📖 {{ campaign.chapterCount || 0 }} chapitres</span>
|
||||
<span>⚔️ {{ 'campaigns.arcs' | translate:{ n: campaign.arcCount || 0 } }}</span>
|
||||
<span>📖 {{ 'campaigns.chapters' | translate:{ n: campaign.chapterCount || 0 } }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -27,13 +27,13 @@
|
||||
<div class="new-icon">
|
||||
<lucide-icon [img]="Plus" [size]="20"></lucide-icon>
|
||||
</div>
|
||||
<h2>Nouvelle Campagne</h2>
|
||||
<p class="card-description">Créez une nouvelle aventure</p>
|
||||
<h2>{{ 'campaigns.newCampaign' | translate }}</h2>
|
||||
<p class="card-description">{{ 'campaigns.newCampaignSubtitle' | translate }}</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<p class="tip">💡 Astuce : Organisez vos arcs et chapitres pour ne rien oublier de vos aventures</p>
|
||||
<p class="tip">{{ 'campaigns.tip' | translate }}</p>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { Router } from '@angular/router';
|
||||
import { LucideAngularModule, Map, Plus } from 'lucide-angular';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
import { CampaignService } from '../services/campaign.service';
|
||||
import { LayoutService } from '../services/layout.service';
|
||||
import { Campaign } from '../services/campaign.model';
|
||||
@@ -9,7 +10,7 @@ import { CampaignCreateComponent, CampaignCreatePayload } from './campaign/campa
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaigns',
|
||||
imports: [LucideAngularModule, CampaignCreateComponent],
|
||||
imports: [LucideAngularModule, CampaignCreateComponent, TranslatePipe],
|
||||
templateUrl: './campaigns.component.html',
|
||||
styleUrls: ['./campaigns.component.scss']
|
||||
})
|
||||
|
||||
@@ -1,45 +1,45 @@
|
||||
<div class="chapter-create-page">
|
||||
|
||||
<div class="page-header">
|
||||
<h1>{{ isHub ? 'Créer une nouvelle quête' : 'Créer un nouveau chapitre' }}</h1>
|
||||
<h1>{{ (isHub ? 'chapterCreate.titleQuest' : 'chapterCreate.titleChapter') | translate }}</h1>
|
||||
@if (arcName) {
|
||||
<p class="arc-ref">{{ isHub ? 'Hub' : 'Arc' }} : {{ arcName }}</p>
|
||||
<p class="arc-ref">{{ (isHub ? 'chapterCreate.hub' : 'chapterCreate.arc') | translate }} : {{ arcName }}</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<form [formGroup]="form" (ngSubmit)="submit()" class="chapter-form">
|
||||
|
||||
<div class="field">
|
||||
<label for="chapter-create-name">{{ isHub ? 'Nom de la quête *' : 'Nom du chapitre *' }}</label>
|
||||
<label for="chapter-create-name">{{ (isHub ? 'chapterCreate.nameQuestLabel' : 'chapterCreate.nameChapterLabel') | translate }}</label>
|
||||
<input
|
||||
id="chapter-create-name"
|
||||
type="text"
|
||||
formControlName="name"
|
||||
[placeholder]="isHub ? 'Ex: Sauver le marchand disparu' : 'Ex: Chapitre 1: Les Disparitions'"
|
||||
[placeholder]="(isHub ? 'chapterCreate.namePlaceholderQuest' : 'chapterCreate.namePlaceholderChapter') | translate"
|
||||
[class.invalid]="form.get('name')?.invalid && form.get('name')?.touched"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="chapter-create-description">Description</label>
|
||||
<label for="chapter-create-description">{{ 'common.description' | translate }}</label>
|
||||
<textarea
|
||||
id="chapter-create-description"
|
||||
formControlName="description"
|
||||
[placeholder]="isHub ? 'Décrivez cette quête...' : 'Décrivez ce chapitre...'"
|
||||
[placeholder]="(isHub ? 'chapterCreate.descPlaceholderQuest' : 'chapterCreate.descPlaceholderChapter') | translate"
|
||||
rows="5">
|
||||
</textarea>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>Icône</label>
|
||||
<label>{{ 'chapterCreate.icon' | translate }}</label>
|
||||
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn-primary" [disabled]="form.invalid">
|
||||
{{ isHub ? 'Créer la quête' : 'Créer le chapitre' }}
|
||||
{{ (isHub ? 'chapterCreate.createQuest' : 'chapterCreate.createChapter') | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">{{ 'common.cancel' | translate }}</button>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angula
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin } from 'rxjs';
|
||||
import { LucideAngularModule } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
@@ -20,7 +21,7 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-chapter-create',
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, IconPickerComponent],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, IconPickerComponent, TranslatePipe],
|
||||
templateUrl: './chapter-create.component.html',
|
||||
styleUrls: ['./chapter-create.component.scss']
|
||||
})
|
||||
@@ -45,7 +46,8 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
|
||||
private npcService: NpcService,
|
||||
private randomTableService: RandomTableService,
|
||||
private enemyService: EnemyService,
|
||||
private layoutService: LayoutService
|
||||
private layoutService: LayoutService,
|
||||
private translate: TranslateService
|
||||
) {
|
||||
this.form = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
@@ -70,7 +72,7 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
|
||||
this.isHub = currentArc?.type === 'HUB';
|
||||
this.existingChapterCount = treeData.chaptersByArc[this.arcId]?.length ?? 0;
|
||||
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -2,24 +2,24 @@
|
||||
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h1>{{ chapter?.name || 'Chapitre' }}</h1>
|
||||
<p class="subtitle">Chapitre</p>
|
||||
<h1>{{ chapter?.name || ('chapterEdit.chapter' | translate) }}</h1>
|
||||
<p class="subtitle">{{ 'chapterEdit.chapter' | translate }}</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button type="button" class="btn-ai"
|
||||
(click)="toggleChat()"
|
||||
[class.active]="chatOpen"
|
||||
title="Ouvrir l'Assistant IA pour dialoguer autour de ce chapitre">
|
||||
[title]="'chapterEdit.aiAssistantTitle' | translate">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
{{ 'chapterEdit.aiAssistant' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">{{ 'common.cancel' | translate }}</button>
|
||||
<button type="button" class="btn-danger" (click)="delete()">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
{{ 'common.delete' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary" (click)="submit()" [disabled]="form.invalid">
|
||||
Sauvegarder
|
||||
{{ 'common.save' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -30,13 +30,10 @@
|
||||
comme arc linéaire (= chapitre conditionnel). Vide = disponible d'emblée. -->
|
||||
<div class="hub-section">
|
||||
<h2 class="hub-section-title">
|
||||
{{ parentArc?.type === 'HUB' ? '🗺️ Conditions de déblocage de la quête' : '🔒 Conditions de déblocage du chapitre' }}
|
||||
{{ (parentArc?.type === 'HUB' ? 'chapterEdit.unlockTitleQuest' : 'chapterEdit.unlockTitleChapter') | translate }}
|
||||
</h2>
|
||||
<small class="field-hint">
|
||||
Définition du scénario : toutes les conditions doivent être remplies (ET) pour que
|
||||
{{ parentArc?.type === 'HUB' ? 'la quête' : 'ce chapitre' }} soit débloqué(e) dans une Partie.
|
||||
Laissez vide pour qu'il soit disponible dès le départ. La progression et l'état des
|
||||
faits se gèrent dans l'écran de la Partie, pas ici.
|
||||
{{ (parentArc?.type === 'HUB' ? 'chapterEdit.unlockHintQuest' : 'chapterEdit.unlockHintChapter') | translate }}
|
||||
</small>
|
||||
<app-prerequisite-editor
|
||||
[prerequisites]="prerequisites"
|
||||
@@ -48,81 +45,81 @@
|
||||
|
||||
<!-- Illustrations (galerie editable, rendu editorial) -->
|
||||
<div class="field">
|
||||
<label>Illustrations</label>
|
||||
<label>{{ 'chapterEdit.illustrations' | translate }}</label>
|
||||
<app-image-gallery
|
||||
[imageIds]="illustrationImageIds"
|
||||
[editable]="true"
|
||||
[layout]="'EDITORIAL'"
|
||||
(imageIdsChange)="illustrationImageIds = $event">
|
||||
</app-image-gallery>
|
||||
<small class="field-hint">Portraits, ambiances, scenes marquantes du chapitre.</small>
|
||||
<small class="field-hint">{{ 'chapterEdit.illustrationsHint' | translate }}</small>
|
||||
</div>
|
||||
|
||||
<!-- Cartes & plans -->
|
||||
<div class="field">
|
||||
<label>Cartes & plans</label>
|
||||
<label>{{ 'chapterEdit.maps' | translate }}</label>
|
||||
<app-image-gallery
|
||||
[imageIds]="mapImageIds"
|
||||
[editable]="true"
|
||||
[layout]="'MAPS'"
|
||||
(imageIdsChange)="mapImageIds = $event">
|
||||
</app-image-gallery>
|
||||
<small class="field-hint">Cartes regionales, plans de donjon, schemas utiles a la table.</small>
|
||||
<small class="field-hint">{{ 'chapterEdit.mapsHint' | translate }}</small>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="chapter-edit-name">Titre du chapitre *</label>
|
||||
<label for="chapter-edit-name">{{ 'chapterEdit.nameLabel' | translate }}</label>
|
||||
<input
|
||||
id="chapter-edit-name"
|
||||
type="text"
|
||||
formControlName="name"
|
||||
placeholder="Ex: Chapitre 1: Les Disparitions"
|
||||
[placeholder]="'chapterEdit.namePlaceholder' | translate"
|
||||
[class.invalid]="form.get('name')?.invalid && form.get('name')?.touched"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="chapter-edit-description">Synopsis du chapitre</label>
|
||||
<label for="chapter-edit-description">{{ 'chapterEdit.synopsisLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="chapter-edit-description"
|
||||
formControlName="description"
|
||||
placeholder="Décrivez brièvement ce qui se passe dans ce chapitre..."
|
||||
[placeholder]="'chapterEdit.synopsisPlaceholder' | translate"
|
||||
rows="5">
|
||||
</textarea>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>Icône</label>
|
||||
<label>{{ 'chapterEdit.icon' | translate }}</label>
|
||||
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="chapter-edit-gm-notes">Notes du Maître de Jeu</label>
|
||||
<label for="chapter-edit-gm-notes">{{ 'chapterEdit.gmNotesLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="chapter-edit-gm-notes"
|
||||
formControlName="gmNotes"
|
||||
placeholder="Vos notes privées sur le déroulement du chapitre, les événements clés, les rebondissements..."
|
||||
[placeholder]="'chapterEdit.gmNotesPlaceholder' | translate"
|
||||
rows="6">
|
||||
</textarea>
|
||||
<small class="field-hint">Ces notes sont privées et ne seront pas exportées vers FoundryVTT.</small>
|
||||
<small class="field-hint">{{ 'chapterEdit.gmNotesHint' | translate }}</small>
|
||||
</div>
|
||||
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="chapter-edit-player-objectives">Objectifs des joueurs</label>
|
||||
<label for="chapter-edit-player-objectives">{{ 'chapterEdit.playerObjectivesLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="chapter-edit-player-objectives"
|
||||
formControlName="playerObjectives"
|
||||
placeholder="Que doivent accomplir les joueurs dans ce chapitre ?"
|
||||
[placeholder]="'chapterEdit.playerObjectivesPlaceholder' | translate"
|
||||
rows="4">
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="chapter-edit-narrative-stakes">Enjeux narratifs</label>
|
||||
<label for="chapter-edit-narrative-stakes">{{ 'chapterEdit.narrativeStakesLabel' | translate }}</label>
|
||||
<textarea
|
||||
id="chapter-edit-narrative-stakes"
|
||||
formControlName="narrativeStakes"
|
||||
placeholder="Quels sont les enjeux dramatiques ?"
|
||||
[placeholder]="'chapterEdit.narrativeStakesPlaceholder' | translate"
|
||||
rows="4">
|
||||
</textarea>
|
||||
</div>
|
||||
@@ -131,7 +128,7 @@
|
||||
<!-- ===== Pages Lore associées (B2 cross-context) ===== -->
|
||||
@if (loreId) {
|
||||
<div class="field">
|
||||
<label>Pages Lore associées</label>
|
||||
<label>{{ 'chapterEdit.relatedPages' | translate }}</label>
|
||||
<app-lore-link-picker
|
||||
[value]="relatedPageIds"
|
||||
[availablePages]="availablePages"
|
||||
@@ -139,7 +136,7 @@
|
||||
(valueChange)="relatedPageIds = $event">
|
||||
</app-lore-link-picker>
|
||||
<small class="field-hint">
|
||||
Liez ce chapitre à des PNJ, lieux ou éléments du Lore qui y apparaissent.
|
||||
{{ 'chapterEdit.relatedPagesHint' | translate }}
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
@@ -147,8 +144,7 @@
|
||||
@if (!loreId) {
|
||||
<div class="field">
|
||||
<small class="field-hint">
|
||||
💡 Cette campagne n'est associée à aucun univers. Associez-la à un Lore dans l'écran de la campagne
|
||||
pour pouvoir lier ce chapitre à des pages du Lore.
|
||||
{{ 'chapterEdit.noLoreHint' | translate }}
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
@@ -163,7 +159,7 @@
|
||||
entityType="chapter"
|
||||
[entityId]="chapterId"
|
||||
[isOpen]="chatOpen"
|
||||
welcomeMessage="Je vois ce chapitre. Demande-moi d'étoffer ses objectifs, ses enjeux ou sa scène d'ouverture."
|
||||
[welcomeMessage]="'chapterEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { LucideAngularModule, Trash2, Sparkles } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
@@ -41,7 +42,8 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
AiChatDrawerComponent,
|
||||
ImageGalleryComponent,
|
||||
IconPickerComponent,
|
||||
PrerequisiteEditorComponent
|
||||
PrerequisiteEditorComponent,
|
||||
TranslatePipe
|
||||
],
|
||||
templateUrl: './chapter-edit.component.html',
|
||||
styleUrls: ['./chapter-edit.component.scss']
|
||||
@@ -53,11 +55,7 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
selectedIcon: string | null = null;
|
||||
|
||||
chatOpen = false;
|
||||
readonly chatQuickSuggestions = [
|
||||
'Propose des objectifs clairs pour les joueurs dans ce chapitre',
|
||||
'Imagine 2 tensions narratives qui relancent l\'intérêt en milieu de chapitre',
|
||||
'Suggère une scène d\'ouverture marquante'
|
||||
];
|
||||
readonly chatQuickSuggestions: string[];
|
||||
|
||||
toggleChat(): void { this.chatOpen = !this.chatOpen; }
|
||||
|
||||
@@ -98,7 +96,8 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private campaignFlagService: CampaignFlagService
|
||||
private campaignFlagService: CampaignFlagService,
|
||||
private translate: TranslateService
|
||||
) {
|
||||
this.form = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
@@ -107,6 +106,11 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
playerObjectives: [''],
|
||||
narrativeStakes: ['']
|
||||
});
|
||||
this.chatQuickSuggestions = [
|
||||
this.translate.instant('chapterEdit.chatSuggestion1'),
|
||||
this.translate.instant('chapterEdit.chatSuggestion2'),
|
||||
this.translate.instant('chapterEdit.chatSuggestion3')
|
||||
];
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -169,7 +173,7 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
narrativeStakes: chapter.narrativeStakes ?? ''
|
||||
});
|
||||
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -200,10 +204,10 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
||||
|
||||
delete(): void {
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer le chapitre',
|
||||
message: `Supprimer le chapitre "${this.chapter?.name}" ?`,
|
||||
details: ['Cette action est irréversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('chapterEdit.deleteTitle'),
|
||||
message: this.translate.instant('chapterEdit.deleteMessage', { name: this.chapter?.name }),
|
||||
details: [this.translate.instant('chapterEdit.irreversible')],
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -2,18 +2,18 @@
|
||||
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h1>{{ chapter?.name || 'Chapitre' }} — Carte</h1>
|
||||
<p class="subtitle">Organigramme des scènes et de leurs branches narratives</p>
|
||||
<h1>{{ 'chapterGraph.title' | translate:{ name: chapter?.name || ('chapterGraph.chapter' | translate) } }}</h1>
|
||||
<p class="subtitle">{{ 'chapterGraph.subtitle' | translate }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour au chapitre
|
||||
{{ 'chapterGraph.back' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (scenes.length === 0) {
|
||||
<div class="graph-empty">
|
||||
<p>Ce chapitre n'a aucune scène. Créez-en pour voir apparaître la carte.</p>
|
||||
<p>{{ 'chapterGraph.empty' | translate }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
</g>
|
||||
</svg>
|
||||
<small class="graph-hint">
|
||||
💡 Cliquez sur une scène pour l'ouvrir, ou glissez-la pour réorganiser la carte. Les scènes non reliées au point d'entrée (scène d'ordre 1) apparaissent en bas.
|
||||
{{ 'chapterGraph.hint' | translate }}
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Component, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/co
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin } from 'rxjs';
|
||||
import { LucideAngularModule, ArrowLeft } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
@@ -22,7 +23,7 @@ interface GraphEdge { key: string; label: string; x1: number; y1: number; x2: nu
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-chapter-graph',
|
||||
imports: [RouterModule, LucideAngularModule],
|
||||
imports: [RouterModule, LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './chapter-graph.component.html',
|
||||
styleUrls: ['./chapter-graph.component.scss']
|
||||
})
|
||||
@@ -74,7 +75,8 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
private randomTableService: RandomTableService,
|
||||
private enemyService: EnemyService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService
|
||||
private pageTitleService: PageTitleService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -96,7 +98,7 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
}).subscribe(({ campaign, allCampaigns, chapter, scenes, treeData }) => {
|
||||
this.chapter = chapter;
|
||||
this.scenes = scenes;
|
||||
this.pageTitleService.set(`${chapter.name} — Carte`);
|
||||
this.pageTitleService.set(this.translate.instant('chapterGraph.title', { name: chapter.name }));
|
||||
this.buildGraph();
|
||||
|
||||
const globalItems: GlobalItem[] = allCampaigns.map((c: Campaign) => ({
|
||||
@@ -104,11 +106,11 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
||||
}));
|
||||
this.layoutService.show({
|
||||
title: campaign.name,
|
||||
items: buildCampaignTree(this.campaignId, treeData),
|
||||
footerLabel: 'Toutes les campagnes',
|
||||
items: buildCampaignTree(this.campaignId, treeData, this.translate),
|
||||
footerLabel: this.translate.instant('chapterGraph.allCampaigns'),
|
||||
createActions: [],
|
||||
globalItems,
|
||||
globalBackLabel: 'Toutes les campagnes',
|
||||
globalBackLabel: this.translate.instant('chapterGraph.allCampaigns'),
|
||||
globalBackRoute: '/campaigns'
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,29 +9,29 @@
|
||||
{{ chapter.name }}
|
||||
</h1>
|
||||
<p class="view-subtitle">
|
||||
{{ parentArc?.type === 'HUB' ? 'Quête (Hub)' : 'Chapitre' }}
|
||||
{{ (parentArc?.type === 'HUB' ? 'chapterView.questHub' : 'chapterView.chapter') | translate }}
|
||||
@if ((chapter.prerequisites?.length ?? 0) > 0) {
|
||||
<span class="cond-badge"
|
||||
title="Ce chapitre a des conditions de déblocage : il se débloque en Partie quand elles sont remplies.">
|
||||
[title]="'chapterView.conditionalBadgeTitle' | translate">
|
||||
<lucide-icon [img]="Lock" [size]="12"></lucide-icon>
|
||||
Conditionnel
|
||||
{{ 'chapterView.conditional' | translate }}
|
||||
</span>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
<div class="view-actions">
|
||||
<button type="button" class="btn-secondary" (click)="openGraph()"
|
||||
title="Voir l'organigramme des scènes et de leurs branches">
|
||||
[title]="'chapterView.mapTitle' | translate">
|
||||
<lucide-icon [img]="Network" [size]="14"></lucide-icon>
|
||||
Carte du chapitre
|
||||
{{ 'chapterView.map' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary" (click)="editMode()">
|
||||
<lucide-icon [img]="Pencil" [size]="14"></lucide-icon>
|
||||
Modifier
|
||||
{{ 'common.edit' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-danger" (click)="deleteChapter()" title="Supprimer le chapitre et ses scènes">
|
||||
<button type="button" class="btn-danger" (click)="deleteChapter()" [title]="'chapterView.deleteTitle' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
{{ 'common.delete' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -39,7 +39,7 @@
|
||||
OU dès qu'un chapitre linéaire porte des conditions. -->
|
||||
@if (parentArc?.type === 'HUB' || (chapter.prerequisites?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔒</span> Conditions de déblocage</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔒</span> {{ 'chapterView.unlockConditions' | translate }}</h2>
|
||||
@if ((chapter.prerequisites?.length ?? 0) > 0) {
|
||||
<ul class="view-section-body">
|
||||
@for (p of chapter.prerequisites; track p) {
|
||||
@@ -47,17 +47,13 @@
|
||||
}
|
||||
</ul>
|
||||
<small class="view-section-empty">
|
||||
Pendant une partie, {{ parentArc?.type === 'HUB' ? 'la quête' : 'ce chapitre' }} se débloque
|
||||
dès que toutes ces conditions sont remplies. Le toggle des faits se fait dans l'écran
|
||||
« Faits » de la Partie.
|
||||
{{ (parentArc?.type === 'HUB' ? 'chapterView.unlockHintQuest' : 'chapterView.unlockHintChapter') | translate }}
|
||||
</small>
|
||||
} @else {
|
||||
<p class="view-section-empty">
|
||||
Aucune condition — cette quête est disponible dès le début dans chaque Partie.
|
||||
{{ 'chapterView.noConditionQuest' | translate }}
|
||||
</p>
|
||||
<p class="view-section-empty">
|
||||
Cliquez sur <strong>Modifier</strong> pour ajouter des conditions
|
||||
(« quête précédente terminée », « à partir de la session N », « quand un fait est vrai »).
|
||||
<p class="view-section-empty" [innerHTML]="'chapterView.noConditionEdit' | translate">
|
||||
</p>
|
||||
}
|
||||
</section>
|
||||
@@ -71,33 +67,33 @@
|
||||
<!-- Cartes & plans -->
|
||||
@if ((chapter.mapImageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> Cartes & plans</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> {{ 'chapterView.maps' | translate }}</h2>
|
||||
<app-image-gallery [imageIds]="chapter.mapImageIds ?? []" [layout]="'MAPS'"></app-image-gallery>
|
||||
</section>
|
||||
}
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">📖</span> Synopsis</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">📖</span> {{ 'chapterView.synopsis' | translate }}</h2>
|
||||
@if (chapter.description?.trim()) {
|
||||
<p class="view-section-body">{{ chapter.description }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
<p class="view-section-empty">{{ 'chapterView.notProvided' | translate }}</p>
|
||||
}
|
||||
</section>
|
||||
<div class="view-row">
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎯</span> Objectifs des joueurs</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎯</span> {{ 'chapterView.playerObjectives' | translate }}</h2>
|
||||
@if (chapter.playerObjectives?.trim()) {
|
||||
<p class="view-section-body">{{ chapter.playerObjectives }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
<p class="view-section-empty">{{ 'chapterView.notProvided' | translate }}</p>
|
||||
}
|
||||
</section>
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">⚡</span> Enjeux narratifs</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">⚡</span> {{ 'chapterView.narrativeStakes' | translate }}</h2>
|
||||
@if (chapter.narrativeStakes?.trim()) {
|
||||
<p class="view-section-body">{{ chapter.narrativeStakes }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
<p class="view-section-empty">{{ 'chapterView.notProvided' | translate }}</p>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
@@ -105,14 +101,14 @@
|
||||
<section class="view-section view-section--private">
|
||||
<h2 class="view-section-title">
|
||||
<span class="view-section-icon">🔒</span>
|
||||
Notes du Maître de Jeu
|
||||
{{ 'chapterView.gmNotes' | translate }}
|
||||
</h2>
|
||||
<p class="view-section-body">{{ chapter.gmNotes }}</p>
|
||||
</section>
|
||||
}
|
||||
@if (loreId && (chapter.relatedPageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔗</span> Pages Lore associées</h2>
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔗</span> {{ 'chapterView.relatedPages' | translate }}</h2>
|
||||
<div class="view-chips">
|
||||
@for (relId of chapter.relatedPageIds; track relId) {
|
||||
<a class="view-chip"
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { LucideAngularModule, Pencil, Network, Trash2, Lock } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { resolveCampaignIcon } from '../../campaign-icons';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
@@ -25,7 +26,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-chapter-view',
|
||||
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent],
|
||||
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe],
|
||||
templateUrl: './chapter-view.component.html',
|
||||
styleUrls: ['./chapter-view.component.scss']
|
||||
})
|
||||
@@ -57,7 +58,8 @@ export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
private pageService: PageService,
|
||||
private layoutService: LayoutService,
|
||||
private pageTitleService: PageTitleService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -101,23 +103,26 @@ export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
list.forEach(c => { if (c.id) this.allChaptersById[c.id] = c; })
|
||||
);
|
||||
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));
|
||||
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
|
||||
});
|
||||
}
|
||||
|
||||
describePrerequisite(p: Prerequisite): string {
|
||||
switch (p.kind) {
|
||||
case 'QUEST_COMPLETED':
|
||||
return `Quête « ${this.allChaptersById[p.questId]?.name ?? '?'} » terminée`;
|
||||
return this.translate.instant('chapterView.prereqQuestCompleted', {
|
||||
name: this.allChaptersById[p.questId]?.name ?? '?'
|
||||
});
|
||||
case 'SESSION_REACHED':
|
||||
return `Session ${p.minSessionNumber} atteinte`;
|
||||
return this.translate.instant('chapterView.prereqSessionReached', { n: p.minSessionNumber });
|
||||
case 'FLAG_SET':
|
||||
return `Fait : ${p.flagName}`;
|
||||
return this.translate.instant('chapterView.prereqFlagSet', { flag: p.flagName });
|
||||
}
|
||||
}
|
||||
|
||||
titleOfRelated(pageId: string): string {
|
||||
return this.availablePages.find(p => p.id === pageId)?.title ?? '(page supprimée)';
|
||||
return this.availablePages.find(p => p.id === pageId)?.title
|
||||
?? this.translate.instant('chapterView.deletedPage');
|
||||
}
|
||||
|
||||
editMode(): void {
|
||||
@@ -143,15 +148,16 @@ export class ChapterViewComponent implements OnInit, OnDestroy {
|
||||
next: impact => {
|
||||
const details: string[] = [];
|
||||
if (impact.scenes > 0) {
|
||||
details.push(`Cette action supprimera aussi : ${impact.scenes} scène${impact.scenes > 1 ? 's' : ''}.`);
|
||||
const key = impact.scenes > 1 ? 'chapterView.deleteScenesPlural' : 'chapterView.deleteScenes';
|
||||
details.push(this.translate.instant(key, { n: impact.scenes }));
|
||||
}
|
||||
details.push('Cette action est irréversible.');
|
||||
details.push(this.translate.instant('chapterView.irreversible'));
|
||||
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer le chapitre',
|
||||
message: `Supprimer le chapitre "${chapter.name}" ?`,
|
||||
title: this.translate.instant('chapterView.deleteChapterTitle'),
|
||||
message: this.translate.instant('chapterView.deleteChapterMessage', { name: chapter.name }),
|
||||
details,
|
||||
confirmLabel: 'Supprimer',
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
<div class="ce-header">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour à la campagne
|
||||
{{ 'characterEdit.backToCampaign' | translate }}
|
||||
</button>
|
||||
<div class="header-row">
|
||||
<h1>
|
||||
<lucide-icon [img]="User" [size]="22"></lucide-icon>
|
||||
{{ characterId ? 'Éditer la fiche' : 'Nouveau personnage' }}
|
||||
{{ (characterId ? 'characterEdit.titleEdit' : 'characterEdit.titleNew') | translate }}
|
||||
</h1>
|
||||
@if (characterId) {
|
||||
<button
|
||||
@@ -16,9 +16,9 @@
|
||||
class="btn-ai"
|
||||
(click)="toggleChat()"
|
||||
[class.active]="chatOpen"
|
||||
title="Ouvrir l'Assistant IA pour dialoguer autour de ce PJ">
|
||||
[title]="'characterEdit.aiAssistantTitle' | translate">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
{{ 'characterEdit.aiAssistant' | translate }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@@ -27,32 +27,32 @@
|
||||
<div class="ce-form">
|
||||
|
||||
<div class="field">
|
||||
<label for="character-name">Nom du personnage *</label>
|
||||
<label for="character-name">{{ 'characterEdit.nameLabel' | translate }}</label>
|
||||
<input
|
||||
id="character-name"
|
||||
type="text"
|
||||
[(ngModel)]="name"
|
||||
name="name"
|
||||
placeholder="Ex: Thorin le Grand-Hache, Lyra l'Errante..."
|
||||
[placeholder]="'characterEdit.namePlaceholder' | translate"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field-row image-row">
|
||||
<div class="field portrait-field">
|
||||
<label>Portrait</label>
|
||||
<label>{{ 'characterEdit.portrait' | translate }}</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="portraitImageId"
|
||||
aspectRatio="1 / 1"
|
||||
hint="Carre conseille (400×400)."
|
||||
[hint]="'characterEdit.portraitHint' | translate"
|
||||
(imageIdChange)="portraitImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
<div class="field header-field">
|
||||
<label>Bandeau / Header</label>
|
||||
<label>{{ 'characterEdit.header' | translate }}</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="headerImageId"
|
||||
aspectRatio="3 / 1"
|
||||
hint="Format paysage conseille (1200×400)."
|
||||
[hint]="'characterEdit.headerHint' | translate"
|
||||
(imageIdChange)="headerImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
@@ -73,9 +73,9 @@
|
||||
<div class="actions">
|
||||
<button type="button" class="btn-primary" [disabled]="!name.trim()" (click)="submit()">
|
||||
<lucide-icon [img]="Save" [size]="16"></lucide-icon>
|
||||
{{ characterId ? 'Enregistrer' : 'Créer' }}
|
||||
{{ (characterId ? 'common.save' : 'common.create') | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="back()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="back()">{{ 'common.cancel' | translate }}</button>
|
||||
<span class="spacer"></span>
|
||||
@if (characterId) {
|
||||
<button
|
||||
@@ -83,7 +83,7 @@
|
||||
class="btn-danger"
|
||||
(click)="deleteCharacter()">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
{{ 'common.delete' | translate }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@@ -98,7 +98,7 @@
|
||||
entityType="character"
|
||||
[entityId]="characterId"
|
||||
[isOpen]="chatOpen"
|
||||
welcomeMessage="Je vois cette fiche de personnage. Demande-moi de proposer stats, backstory, équipement ou objectifs personnels."
|
||||
[welcomeMessage]="'characterEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Component, OnInit } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, Save, ArrowLeft, User, Trash2, Sparkles } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
@@ -26,7 +27,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-character-edit',
|
||||
imports: [FormsModule, LucideAngularModule, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent],
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent],
|
||||
templateUrl: './character-edit.component.html',
|
||||
styleUrls: ['./character-edit.component.scss']
|
||||
})
|
||||
@@ -38,11 +39,13 @@ export class CharacterEditComponent implements OnInit {
|
||||
readonly Sparkles = Sparkles;
|
||||
|
||||
chatOpen = false;
|
||||
readonly chatQuickSuggestions = [
|
||||
'Propose une backstory coherente avec l\'univers',
|
||||
'Suggere 3 objectifs personnels pour ce personnage',
|
||||
'Aide-moi a equilibrer les stats de combat'
|
||||
get chatQuickSuggestions(): string[] {
|
||||
return [
|
||||
this.translate.instant('characterEdit.chatSuggestion1'),
|
||||
this.translate.instant('characterEdit.chatSuggestion2'),
|
||||
this.translate.instant('characterEdit.chatSuggestion3')
|
||||
];
|
||||
}
|
||||
|
||||
toggleChat(): void { this.chatOpen = !this.chatOpen; }
|
||||
|
||||
@@ -67,7 +70,8 @@ export class CharacterEditComponent implements OnInit {
|
||||
private campaignService: CampaignService,
|
||||
private gameSystemService: GameSystemService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -144,10 +148,10 @@ export class CharacterEditComponent implements OnInit {
|
||||
deleteCharacter(): void {
|
||||
if (!this.characterId) return;
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer la fiche ?',
|
||||
message: `Supprimer la fiche de "${this.name}" ?`,
|
||||
details: ['Cette action est irreversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('characterEdit.deleteTitle'),
|
||||
message: this.translate.instant('characterEdit.deleteMessage', { name: this.name }),
|
||||
details: [this.translate.instant('characterEdit.irreversible')],
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok || !this.characterId) return;
|
||||
|
||||
@@ -2,18 +2,18 @@
|
||||
<div class="cv-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour
|
||||
{{ 'common.back' | translate }}
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
@if (characterId) {
|
||||
<button class="btn-ai" (click)="toggleChat()" [class.active]="chatOpen">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
{{ 'characterView.aiAssistant' | translate }}
|
||||
</button>
|
||||
}
|
||||
<button class="btn-edit" (click)="edit()">
|
||||
<lucide-icon [img]="Edit3" [size]="14"></lucide-icon>
|
||||
Editer
|
||||
{{ 'common.edit' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LucideAngularModule, ArrowLeft, Edit3, Sparkles } from 'lucide-angular';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
@@ -17,7 +18,7 @@ import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-dr
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-character-view',
|
||||
imports: [LucideAngularModule, PersonaViewComponent, AiChatDrawerComponent],
|
||||
imports: [LucideAngularModule, TranslatePipe, PersonaViewComponent, AiChatDrawerComponent],
|
||||
templateUrl: './character-view.component.html',
|
||||
styleUrls: ['./character-view.component.scss']
|
||||
})
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
<div class="ne-header">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour aux ennemis
|
||||
{{ 'enemyEdit.backToEnemies' | translate }}
|
||||
</button>
|
||||
<div class="header-row">
|
||||
<h1>
|
||||
<lucide-icon [img]="Skull" [size]="22"></lucide-icon>
|
||||
{{ enemyId ? 'Éditer l\'ennemi' : 'Nouvel ennemi' }}
|
||||
{{ (enemyId ? 'enemyEdit.titleEdit' : 'enemyEdit.titleNew') | translate }}
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
@@ -16,36 +16,36 @@
|
||||
<div class="ne-form">
|
||||
|
||||
<div class="field">
|
||||
<label for="enemy-name">Nom de l'ennemi *</label>
|
||||
<label for="enemy-name">{{ 'enemyEdit.nameLabel' | translate }}</label>
|
||||
<input
|
||||
id="enemy-name"
|
||||
type="text"
|
||||
[(ngModel)]="name"
|
||||
name="name"
|
||||
placeholder="Ex: Balor, Gobelin chef de guerre, Liche…"
|
||||
[placeholder]="'enemyEdit.namePlaceholder' | translate"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field-row image-row">
|
||||
<div class="field">
|
||||
<label for="enemy-level">Niveau / FP</label>
|
||||
<label for="enemy-level">{{ 'enemyEdit.level' | translate }}</label>
|
||||
<input
|
||||
id="enemy-level"
|
||||
type="text"
|
||||
[(ngModel)]="level"
|
||||
name="level"
|
||||
placeholder="Ex: 5, FP 8, Boss…"
|
||||
[placeholder]="'enemyEdit.levelPlaceholder' | translate"
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="enemy-folder">Dossier</label>
|
||||
<label for="enemy-folder">{{ 'enemyEdit.folder' | translate }}</label>
|
||||
<input
|
||||
id="enemy-folder"
|
||||
type="text"
|
||||
[(ngModel)]="folder"
|
||||
name="folder"
|
||||
list="enemy-folders"
|
||||
placeholder="Ex: Démons, Humanoïdes… (vide = non classé)"
|
||||
[placeholder]="'enemyEdit.folderPlaceholder' | translate"
|
||||
/>
|
||||
<datalist id="enemy-folders">
|
||||
@for (f of existingFolders; track f) {
|
||||
@@ -57,20 +57,20 @@
|
||||
|
||||
<div class="field-row image-row">
|
||||
<div class="field portrait-field">
|
||||
<label>Portrait</label>
|
||||
<label>{{ 'enemyEdit.portrait' | translate }}</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="portraitImageId"
|
||||
aspectRatio="1 / 1"
|
||||
hint="Carre conseille (400×400)."
|
||||
[hint]="'enemyEdit.portraitHint' | translate"
|
||||
(imageIdChange)="portraitImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
<div class="field header-field">
|
||||
<label>Bandeau / Header</label>
|
||||
<label>{{ 'enemyEdit.header' | translate }}</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="headerImageId"
|
||||
aspectRatio="3 / 1"
|
||||
hint="Format paysage conseille (1200×400)."
|
||||
[hint]="'enemyEdit.headerHint' | translate"
|
||||
(imageIdChange)="headerImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
@@ -91,9 +91,9 @@
|
||||
<div class="actions">
|
||||
<button type="button" class="btn-primary" [disabled]="!name.trim()" (click)="submit()">
|
||||
<lucide-icon [img]="Save" [size]="16"></lucide-icon>
|
||||
{{ enemyId ? 'Enregistrer' : 'Créer' }}
|
||||
{{ (enemyId ? 'common.save' : 'common.create') | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="back()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="back()">{{ 'common.cancel' | translate }}</button>
|
||||
<span class="spacer"></span>
|
||||
@if (enemyId) {
|
||||
<button
|
||||
@@ -101,7 +101,7 @@
|
||||
class="btn-danger"
|
||||
(click)="deleteEnemy()">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
{{ 'common.delete' | translate }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Component, OnInit } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, Save, ArrowLeft, Skull, Trash2 } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { EnemyService } from '../../../services/enemy.service';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
@@ -19,7 +20,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-enemy-edit',
|
||||
imports: [FormsModule, LucideAngularModule, DynamicFieldsFormComponent, SingleImagePickerComponent],
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe, DynamicFieldsFormComponent, SingleImagePickerComponent],
|
||||
templateUrl: './enemy-edit.component.html',
|
||||
styleUrls: ['./enemy-edit.component.scss']
|
||||
})
|
||||
@@ -52,7 +53,8 @@ export class EnemyEditComponent implements OnInit {
|
||||
private campaignService: CampaignService,
|
||||
private gameSystemService: GameSystemService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -143,10 +145,10 @@ export class EnemyEditComponent implements OnInit {
|
||||
deleteEnemy(): void {
|
||||
if (!this.enemyId) return;
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer la fiche ?',
|
||||
message: `Supprimer la fiche de "${this.name}" ?`,
|
||||
details: ['Cette action est irreversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('enemyEdit.deleteTitle'),
|
||||
message: this.translate.instant('enemyEdit.deleteMessage', { name: this.name }),
|
||||
details: [this.translate.instant('enemyEdit.irreversible')],
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok || !this.enemyId) return;
|
||||
|
||||
@@ -1,25 +1,24 @@
|
||||
<div class="sbl-page">
|
||||
<div class="sbl-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> {{ 'common.back' | translate }}
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-create" (click)="create()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> Nouvel ennemi
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> {{ 'enemyList.create' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<header class="sbl-header">
|
||||
<h1><lucide-icon [img]="Skull" [size]="22"></lucide-icon> Ennemis</h1>
|
||||
<h1><lucide-icon [img]="Skull" [size]="22"></lucide-icon> {{ 'enemyList.title' | translate }}</h1>
|
||||
<p class="sbl-hint">
|
||||
Le bestiaire de la campagne : monstres et créatures avec leur fiche (pilotée par le
|
||||
template Ennemi du système de jeu), classés par dossier (Démons, Humanoïdes…).
|
||||
{{ 'enemyList.hint' | translate }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div class="sbl-list">
|
||||
@if (total === 0) {
|
||||
<p class="empty">Aucun ennemi pour l'instant.</p>
|
||||
<p class="empty">{{ 'enemyList.empty' | translate }}</p>
|
||||
}
|
||||
@for (g of groups; track g.folder) {
|
||||
@if (g.folder) {
|
||||
@@ -29,16 +28,16 @@
|
||||
<span class="sbl-folder-count">{{ g.enemies.length }}</span>
|
||||
</h2>
|
||||
} @else if (groups.length > 1) {
|
||||
<h2 class="sbl-folder sbl-folder--none">Non classés</h2>
|
||||
<h2 class="sbl-folder sbl-folder--none">{{ 'enemyList.unclassified' | translate }}</h2>
|
||||
}
|
||||
@for (e of g.enemies; track e.id) {
|
||||
<button class="sbl-item" (click)="open(e)">
|
||||
<lucide-icon [img]="Skull" [size]="16"></lucide-icon>
|
||||
<span class="sbl-item-name">{{ e.name }}</span>
|
||||
@if (e.level) {
|
||||
<span class="sbl-item-level">Niv. {{ e.level }}</span>
|
||||
<span class="sbl-item-level">{{ 'enemyList.levelShort' | translate:{ level: e.level } }}</span>
|
||||
}
|
||||
<span class="sbl-del" (click)="remove(e, $event)" title="Supprimer">
|
||||
<span class="sbl-del" (click)="remove(e, $event)" [title]="'common.delete' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LucideAngularModule, ArrowLeft, Plus, Trash2, Skull, Folder } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { EnemyService } from '../../../services/enemy.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { Enemy } from '../../../services/enemy.model';
|
||||
@@ -19,7 +20,7 @@ interface FolderGroup {
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-enemy-list',
|
||||
imports: [LucideAngularModule],
|
||||
imports: [LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './enemy-list.component.html',
|
||||
styleUrls: ['./enemy-list.component.scss']
|
||||
})
|
||||
@@ -40,7 +41,8 @@ export class EnemyListComponent implements OnInit {
|
||||
private router: Router,
|
||||
private service: EnemyService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -91,9 +93,9 @@ export class EnemyListComponent implements OnInit {
|
||||
remove(e: Enemy, ev: Event): void {
|
||||
ev.stopPropagation();
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer l\'ennemi',
|
||||
message: `Supprimer « ${e.name} » ?`,
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('enemyList.deleteTitle'),
|
||||
message: this.translate.instant('enemyList.deleteMessage', { name: e.name }),
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
<div class="nv-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour
|
||||
{{ 'common.back' | translate }}
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-edit" (click)="edit()">
|
||||
<lucide-icon [img]="Edit3" [size]="14"></lucide-icon>
|
||||
Editer
|
||||
{{ 'common.edit' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { LucideAngularModule, ArrowLeft, Edit3 } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { EnemyService } from '../../../services/enemy.service';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
@@ -17,7 +18,7 @@ import { PersonaViewComponent } from '../../../shared/persona-view/persona-view.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-enemy-view',
|
||||
imports: [LucideAngularModule, PersonaViewComponent],
|
||||
imports: [LucideAngularModule, TranslatePipe, PersonaViewComponent],
|
||||
templateUrl: './enemy-view.component.html',
|
||||
styleUrls: ['./enemy-view.component.scss']
|
||||
})
|
||||
@@ -39,7 +40,8 @@ export class EnemyViewComponent implements OnInit, OnDestroy {
|
||||
private service: EnemyService,
|
||||
private campaignService: CampaignService,
|
||||
private gameSystemService: GameSystemService,
|
||||
private campaignSidebar: CampaignSidebarService
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -78,7 +80,7 @@ export class EnemyViewComponent implements OnInit, OnDestroy {
|
||||
/** Sous-titre de la fiche : niveau + dossier (« Niveau 8 · Démons »). */
|
||||
get subtitle(): string {
|
||||
const parts: string[] = [];
|
||||
if (this.enemy?.level) parts.push(`Niveau ${this.enemy.level}`);
|
||||
if (this.enemy?.level) parts.push(this.translate.instant('enemyView.levelLong', { level: this.enemy.level }));
|
||||
if (this.enemy?.folder) parts.push(this.enemy.folder);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
<div class="ice-page">
|
||||
<div class="ice-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> {{ 'common.back' | translate }}
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-save" (click)="save()" [disabled]="saving">
|
||||
<lucide-icon [img]="Save" [size]="14"></lucide-icon>
|
||||
{{ saving ? 'Enregistrement…' : 'Enregistrer' }}
|
||||
{{ (saving ? 'common.saving' : 'common.save') | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<h1>{{ catalogId ? 'Éditer le catalogue' : 'Nouveau catalogue d\'objets' }}</h1>
|
||||
<h1>{{ (catalogId ? 'itemCatalogEdit.editTitle' : 'itemCatalogEdit.createTitle') | translate }}</h1>
|
||||
|
||||
@if (errorMessage) {
|
||||
<div class="error">{{ errorMessage }}</div>
|
||||
}
|
||||
|
||||
<div class="form-row">
|
||||
<label for="ic-name">Nom *</label>
|
||||
<input id="ic-name" type="text" [(ngModel)]="name" placeholder="Ex: Échoppe de l'armurier nain">
|
||||
<label for="ic-name">{{ 'itemCatalogEdit.nameLabel' | translate }}</label>
|
||||
<input id="ic-name" type="text" [(ngModel)]="name" [placeholder]="'itemCatalogEdit.namePlaceholder' | translate">
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label for="ic-desc">Description</label>
|
||||
<textarea id="ic-desc" rows="2" [(ngModel)]="description" placeholder="À quoi sert ce catalogue / cette boutique ?"></textarea>
|
||||
<label for="ic-desc">{{ 'common.description' | translate }}</label>
|
||||
<textarea id="ic-desc" rows="2" [(ngModel)]="description" [placeholder]="'itemCatalogEdit.descriptionPlaceholder' | translate"></textarea>
|
||||
</div>
|
||||
|
||||
<!-- Génération IA -->
|
||||
<div class="ai-box">
|
||||
<div class="ai-title"><lucide-icon [img]="Sparkles" [size]="15"></lucide-icon> Générer avec l'IA</div>
|
||||
<p class="ai-hint">Décris la boutique/le butin ; l'IA propose les objets (revois-les avant d'enregistrer). Contextualisé avec ta campagne.</p>
|
||||
<div class="ai-title"><lucide-icon [img]="Sparkles" [size]="15"></lucide-icon> {{ 'itemCatalogEdit.aiTitle' | translate }}</div>
|
||||
<p class="ai-hint">{{ 'itemCatalogEdit.aiHint' | translate }}</p>
|
||||
<textarea rows="2" [(ngModel)]="aiPrompt"
|
||||
placeholder="Ex: boutique d'alchimiste dans une cité portuaire, objets exotiques"></textarea>
|
||||
[placeholder]="'itemCatalogEdit.aiPlaceholder' | translate"></textarea>
|
||||
<div class="ai-actions">
|
||||
<button class="btn-ai" (click)="generateWithAI()" [disabled]="generating">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ generating ? 'Génération…' : 'Générer' }}
|
||||
{{ (generating ? 'common.generating' : 'common.generate') | translate }}
|
||||
</button>
|
||||
@if (aiError) {
|
||||
<span class="ai-error">{{ aiError }}</span>
|
||||
@@ -44,33 +44,33 @@
|
||||
</div>
|
||||
|
||||
<div class="items-head">
|
||||
<h2>Objets</h2>
|
||||
<h2>{{ 'itemCatalogEdit.itemsTitle' | translate }}</h2>
|
||||
<button class="btn-mini" (click)="addItem()">
|
||||
<lucide-icon [img]="Plus" [size]="13"></lucide-icon> Ajouter
|
||||
<lucide-icon [img]="Plus" [size]="13"></lucide-icon> {{ 'common.add' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="item-row head">
|
||||
<span class="c-name">Nom</span>
|
||||
<span class="c-price">Prix</span>
|
||||
<span class="c-cat">Catégorie</span>
|
||||
<span class="c-desc">Description</span>
|
||||
<span class="c-name">{{ 'common.name' | translate }}</span>
|
||||
<span class="c-price">{{ 'itemCatalogEdit.priceLabel' | translate }}</span>
|
||||
<span class="c-cat">{{ 'itemCatalogEdit.categoryLabel' | translate }}</span>
|
||||
<span class="c-desc">{{ 'common.description' | translate }}</span>
|
||||
<span class="c-del"></span>
|
||||
</div>
|
||||
|
||||
@for (it of items; track it; let i = $index) {
|
||||
<div class="item-row">
|
||||
<input class="c-name" type="text" [(ngModel)]="it.name" placeholder="Objet">
|
||||
<input class="c-price" type="text" [(ngModel)]="it.price" placeholder="50 po">
|
||||
<input class="c-cat" type="text" [(ngModel)]="it.category" placeholder="Armes">
|
||||
<input class="c-desc" type="text" [(ngModel)]="it.description" placeholder="Effet / détails">
|
||||
<button class="c-del btn-del" (click)="removeItem(i)" title="Supprimer">
|
||||
<input class="c-name" type="text" [(ngModel)]="it.name" [placeholder]="'itemCatalogEdit.itemNamePlaceholder' | translate">
|
||||
<input class="c-price" type="text" [(ngModel)]="it.price" [placeholder]="'itemCatalogEdit.itemPricePlaceholder' | translate">
|
||||
<input class="c-cat" type="text" [(ngModel)]="it.category" [placeholder]="'itemCatalogEdit.itemCategoryPlaceholder' | translate">
|
||||
<input class="c-desc" type="text" [(ngModel)]="it.description" [placeholder]="'itemCatalogEdit.itemDescriptionPlaceholder' | translate">
|
||||
<button class="c-del btn-del" (click)="removeItem(i)" [title]="'common.delete' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (items.length === 0) {
|
||||
<p class="empty-hint">Aucun objet — clique « Ajouter ».</p>
|
||||
<p class="empty-hint">{{ 'itemCatalogEdit.emptyHint' | translate }}</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -2,10 +2,12 @@ import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { LucideAngularModule, ArrowLeft, Save, Plus, Trash2, Sparkles } from 'lucide-angular';
|
||||
import { ItemCatalogService } from '../../../services/item-catalog.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { ItemCatalog, CatalogItem, ItemCatalogCreate } from '../../../services/item-catalog.model';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
|
||||
/**
|
||||
* Création/édition d'un catalogue d'objets (boutique, butin…).
|
||||
@@ -14,7 +16,7 @@ import { ItemCatalog, CatalogItem, ItemCatalogCreate } from '../../../services/i
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-item-catalog-edit',
|
||||
imports: [FormsModule, LucideAngularModule],
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './item-catalog-edit.component.html',
|
||||
styleUrls: ['./item-catalog-edit.component.scss']
|
||||
})
|
||||
@@ -43,7 +45,8 @@ export class ItemCatalogEditComponent implements OnInit {
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private service: ItemCatalogService,
|
||||
private campaignSidebar: CampaignSidebarService
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -76,7 +79,7 @@ export class ItemCatalogEditComponent implements OnInit {
|
||||
|
||||
generateWithAI(): void {
|
||||
if (!this.campaignId) return;
|
||||
if (!this.aiPrompt.trim()) { this.aiError = 'Décris le catalogue à générer.'; return; }
|
||||
if (!this.aiPrompt.trim()) { this.aiError = this.translate.instant('itemCatalogEdit.aiPromptRequired'); return; }
|
||||
this.generating = true;
|
||||
this.aiError = '';
|
||||
this.service.generate(this.campaignId, this.aiPrompt.trim()).subscribe({
|
||||
@@ -88,14 +91,14 @@ export class ItemCatalogEditComponent implements OnInit {
|
||||
},
|
||||
error: (err) => {
|
||||
this.generating = false;
|
||||
this.aiError = err?.error?.message || 'Échec de la génération IA. Réessaie ou reformule.';
|
||||
this.aiError = err?.error?.message || this.translate.instant('itemCatalogEdit.aiError');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
save(): void {
|
||||
if (!this.campaignId) return;
|
||||
if (!this.name.trim()) { this.errorMessage = 'Le nom est requis.'; return; }
|
||||
if (!this.name.trim()) { this.errorMessage = this.translate.instant('itemCatalogEdit.nameRequired'); return; }
|
||||
this.saving = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
@@ -141,7 +144,7 @@ export class ItemCatalogEditComponent implements OnInit {
|
||||
|
||||
private fail(err: unknown): void {
|
||||
this.saving = false;
|
||||
this.errorMessage = 'Échec de l\'enregistrement.';
|
||||
this.errorMessage = this.translate.instant('itemCatalogEdit.saveError');
|
||||
console.error('ItemCatalog save failed', err);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,32 +1,31 @@
|
||||
<div class="icl-page">
|
||||
<div class="icl-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> {{ 'common.back' | translate }}
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-create" (click)="create()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> Nouveau catalogue
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> {{ 'itemCatalogList.newCatalog' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<header class="icl-header">
|
||||
<h1><lucide-icon [img]="Package" [size]="22"></lucide-icon> Catalogues d'objets</h1>
|
||||
<h1><lucide-icon [img]="Package" [size]="22"></lucide-icon> {{ 'itemCatalogList.title' | translate }}</h1>
|
||||
<p class="icl-hint">
|
||||
Boutiques, butins, trésors… à remplir à la main ou via l'IA. Consultables en session
|
||||
quand les joueurs visitent une échoppe.
|
||||
{{ 'itemCatalogList.hint' | translate }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div class="icl-list">
|
||||
@if (catalogs.length === 0) {
|
||||
<p class="empty">Aucun catalogue pour l'instant.</p>
|
||||
<p class="empty">{{ 'itemCatalogList.empty' | translate }}</p>
|
||||
}
|
||||
@for (c of catalogs; track c) {
|
||||
<button class="icl-item" (click)="open(c)">
|
||||
<lucide-icon [img]="Package" [size]="16"></lucide-icon>
|
||||
<span class="icl-item-name">{{ c.name }}</span>
|
||||
<span class="icl-item-count">{{ c.items.length }} objet(s)</span>
|
||||
<span class="icl-del" (click)="remove(c, $event)" title="Supprimer">
|
||||
<span class="icl-item-count">{{ 'itemCatalogList.itemCount' | translate:{ n: c.items.length } }}</span>
|
||||
<span class="icl-del" (click)="remove(c, $event)" [title]="'common.delete' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ItemCatalogService } from '../../../services/item-catalog.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { ItemCatalog } from '../../../services/item-catalog.model';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
|
||||
/**
|
||||
* Liste des catalogues d'objets d'une campagne + création.
|
||||
@@ -13,7 +14,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-item-catalog-list',
|
||||
imports: [LucideAngularModule],
|
||||
imports: [LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './item-catalog-list.component.html',
|
||||
styleUrls: ['./item-catalog-list.component.scss']
|
||||
})
|
||||
@@ -31,7 +32,8 @@ export class ItemCatalogListComponent implements OnInit {
|
||||
private router: Router,
|
||||
private service: ItemCatalogService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -60,9 +62,9 @@ export class ItemCatalogListComponent implements OnInit {
|
||||
remove(c: ItemCatalog, ev: Event): void {
|
||||
ev.stopPropagation();
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer le catalogue',
|
||||
message: `Supprimer « ${c.name} » ?`,
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('itemCatalogList.deleteTitle'),
|
||||
message: this.translate.instant('itemCatalogList.deleteMessage', { name: c.name }),
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
<div class="ic-page">
|
||||
<div class="ic-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> {{ 'common.back' | translate }}
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-edit" (click)="edit()">
|
||||
<lucide-icon [img]="Edit3" [size]="14"></lucide-icon> Éditer
|
||||
<lucide-icon [img]="Edit3" [size]="14"></lucide-icon> {{ 'common.edit' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
<header class="ic-header">
|
||||
@@ -17,7 +17,7 @@
|
||||
</header>
|
||||
@if (catalog.items.length === 0) {
|
||||
<p class="ic-empty">
|
||||
Aucun objet — édite le catalogue pour en ajouter.
|
||||
{{ 'itemCatalogView.empty' | translate }}
|
||||
</p>
|
||||
}
|
||||
@for (g of groups; track g) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { LucideAngularModule, ArrowLeft, Edit3, Package } from 'lucide-angular';
|
||||
import { ItemCatalogService } from '../../../services/item-catalog.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { ItemCatalog, CatalogItem } from '../../../services/item-catalog.model';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
|
||||
interface ItemGroup { category: string; items: CatalogItem[]; }
|
||||
|
||||
@@ -14,7 +15,7 @@ interface ItemGroup { category: string; items: CatalogItem[]; }
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-item-catalog-view',
|
||||
imports: [LucideAngularModule],
|
||||
imports: [LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './item-catalog-view.component.html',
|
||||
styleUrls: ['./item-catalog-view.component.scss']
|
||||
})
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
@if (status !== 'created' && needsArc) {
|
||||
<div class="nac-targets">
|
||||
<label>
|
||||
Arc
|
||||
{{ 'notebookActionCard.arc' | translate }}
|
||||
<select [(ngModel)]="selectedArcId" (ngModelChange)="syncChapter()">
|
||||
@for (a of arcs; track a) {
|
||||
<option [value]="a.id">{{ a.name }}</option>
|
||||
@@ -22,7 +22,7 @@
|
||||
</label>
|
||||
@if (needsChapter) {
|
||||
<label>
|
||||
Chapitre
|
||||
{{ 'notebookActionCard.chapter' | translate }}
|
||||
<select [(ngModel)]="selectedChapterId">
|
||||
@for (c of targetChapters; track c) {
|
||||
<option [value]="c.id">{{ c.name }}</option>
|
||||
@@ -35,7 +35,7 @@
|
||||
|
||||
@if (needsArc && arcs.length === 0) {
|
||||
<p class="nac-warn">
|
||||
Crée d'abord un arc {{ needsChapter ? 'et un chapitre ' : '' }}dans la campagne pour pouvoir y rattacher cet élément.
|
||||
{{ (needsChapter ? 'notebookActionCard.warnArcChapter' : 'notebookActionCard.warnArc') | translate }}
|
||||
</p>
|
||||
}
|
||||
|
||||
@@ -43,12 +43,12 @@
|
||||
@if (status !== 'created') {
|
||||
<button class="nac-create" (click)="create()" [disabled]="!canCreate">
|
||||
<lucide-icon [img]="Plus" [size]="13"></lucide-icon>
|
||||
{{ status === 'creating' ? 'Création…' : 'Créer dans la campagne' }}
|
||||
{{ (status === 'creating' ? 'notebookActionCard.creating' : 'notebookActionCard.createInCampaign') | translate }}
|
||||
</button>
|
||||
}
|
||||
@if (status === 'created') {
|
||||
<button class="nac-open" (click)="openCreated()">
|
||||
<lucide-icon [img]="Check" [size]="13"></lucide-icon> Créé — ouvrir
|
||||
<lucide-icon [img]="Check" [size]="13"></lucide-icon> {{ 'notebookActionCard.createdOpen' | translate }}
|
||||
<lucide-icon [img]="ExternalLink" [size]="12"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
|
||||
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { LucideAngularModule, Plus, Check, Drama, Clapperboard, BookText, GitBranch, Dices, ExternalLink } from 'lucide-angular';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
@@ -15,7 +16,7 @@ import { NotebookAction } from '../../../services/notebook-action.model';
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-notebook-action-card',
|
||||
imports: [FormsModule, LucideAngularModule],
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './notebook-action-card.component.html',
|
||||
styleUrls: ['./notebook-action-card.component.scss']
|
||||
})
|
||||
@@ -42,7 +43,8 @@ export class NotebookActionCardComponent implements OnInit {
|
||||
private campaignService: CampaignService,
|
||||
private npcService: NpcService,
|
||||
private tableService: RandomTableService,
|
||||
private router: Router
|
||||
private router: Router,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -52,11 +54,11 @@ export class NotebookActionCardComponent implements OnInit {
|
||||
|
||||
get typeLabel(): string {
|
||||
switch (this.action.type) {
|
||||
case 'npc': return 'PNJ';
|
||||
case 'scene': return 'Scène';
|
||||
case 'chapter': return 'Chapitre';
|
||||
case 'arc': return 'Arc';
|
||||
case 'table': return 'Table aléatoire';
|
||||
case 'npc': return this.translate.instant('notebookActionCard.typeNpc');
|
||||
case 'scene': return this.translate.instant('notebookActionCard.typeScene');
|
||||
case 'chapter': return this.translate.instant('notebookActionCard.typeChapter');
|
||||
case 'arc': return this.translate.instant('notebookActionCard.typeArc');
|
||||
case 'table': return this.translate.instant('notebookActionCard.typeTable');
|
||||
default: return this.action.type;
|
||||
}
|
||||
}
|
||||
@@ -200,7 +202,7 @@ export class NotebookActionCardComponent implements OnInit {
|
||||
|
||||
private fail(err: unknown): void {
|
||||
this.status = 'error';
|
||||
this.errorMsg = (err as { error?: { message?: string } })?.error?.message || 'Échec de la création.';
|
||||
this.errorMsg = (err as { error?: { message?: string } })?.error?.message || this.translate.instant('notebookActionCard.createError');
|
||||
}
|
||||
|
||||
openCreated(): void {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="nbd-page">
|
||||
<div class="nbd-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Ateliers
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> {{ 'notebookDetail.backToList' | translate }}
|
||||
</button>
|
||||
<input class="nbd-title" [(ngModel)]="detail.name" (blur)="rename()" (keyup.enter)="rename()">
|
||||
</div>
|
||||
@@ -10,10 +10,10 @@
|
||||
<!-- Sources -->
|
||||
<aside class="nbd-sources">
|
||||
<div class="nbd-sources-head">
|
||||
<h3><lucide-icon [img]="FileText" [size]="15"></lucide-icon> Sources</h3>
|
||||
<h3><lucide-icon [img]="FileText" [size]="15"></lucide-icon> {{ 'notebookDetail.sources' | translate }}</h3>
|
||||
<label class="btn-upload" [class.disabled]="uploading">
|
||||
<lucide-icon [img]="Upload" [size]="13"></lucide-icon>
|
||||
{{ uploading ? 'Indexation…' : 'Ajouter un PDF' }}
|
||||
{{ (uploading ? 'notebookDetail.indexing' : 'notebookDetail.addPdf') | translate }}
|
||||
<input type="file" accept="application/pdf" hidden (change)="onFile($event)" [disabled]="uploading">
|
||||
</label>
|
||||
</div>
|
||||
@@ -23,7 +23,7 @@
|
||||
@if (readySourceCount > 1) {
|
||||
<p class="nbd-sources-hint"
|
||||
[class.partial]="selectedSourceIds.size < readySourceCount">
|
||||
{{ selectedSourceIds.size }}/{{ readySourceCount }} source(s) utilisée(s) par le chat et l'analyse approfondie
|
||||
{{ 'notebookDetail.sourcesUsed' | translate:{ selected: selectedSourceIds.size, total: readySourceCount } }}
|
||||
</p>
|
||||
}
|
||||
@for (s of sources; track s) {
|
||||
@@ -34,9 +34,9 @@
|
||||
class="nbd-source-check"
|
||||
[checked]="isSelected(s)"
|
||||
(change)="toggleSource(s)"
|
||||
[title]="isSelected(s)
|
||||
? 'Source utilisée par le chat — décocher pour l\'exclure'
|
||||
: 'Source ignorée par le chat — cocher pour l\'inclure'" />
|
||||
[title]="(isSelected(s)
|
||||
? 'notebookDetail.sourceIncludedTitle'
|
||||
: 'notebookDetail.sourceExcludedTitle') | translate" />
|
||||
} @else {
|
||||
<lucide-icon
|
||||
[img]="s.status === 'FAILED' ? AlertCircle : Loader"
|
||||
@@ -48,24 +48,24 @@
|
||||
<div class="nbd-source-name">{{ s.filename }}</div>
|
||||
<div class="nbd-source-meta">
|
||||
@if (s.status === 'READY') {
|
||||
<span>{{ s.pageCount }} p. · {{ s.chunkCount }} extraits</span>
|
||||
<span>{{ 'notebookDetail.sourceMeta' | translate:{ pages: s.pageCount, chunks: s.chunkCount } }}</span>
|
||||
}
|
||||
@if (s.status === 'INDEXING') {
|
||||
<span>indexation en cours…</span>
|
||||
<span>{{ 'notebookDetail.indexingInProgress' | translate }}</span>
|
||||
}
|
||||
@if (s.status === 'FAILED') {
|
||||
<span>échec de l'indexation</span>
|
||||
<span>{{ 'notebookDetail.indexingFailed' | translate }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<button class="nbd-source-del" (click)="removeSource(s)" title="Supprimer">
|
||||
<button class="nbd-source-del" (click)="removeSource(s)" [title]="'common.delete' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="13"></lucide-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
@if (sources.length === 0 && !uploading) {
|
||||
<p class="nbd-empty">
|
||||
Ajoute un PDF source pour commencer à discuter avec.
|
||||
{{ 'notebookDetail.sourcesEmpty' | translate }}
|
||||
</p>
|
||||
}
|
||||
</aside>
|
||||
@@ -76,32 +76,32 @@
|
||||
@if (viewingArchive) {
|
||||
<span class="nbd-archive-banner">
|
||||
<lucide-icon [img]="History" [size]="13"></lucide-icon>
|
||||
Archive du {{ archiveLabel(viewingArchive) }} — lecture seule
|
||||
{{ 'notebookDetail.archiveBanner' | translate:{ label: archiveLabel(viewingArchive) } }}
|
||||
</span>
|
||||
<button type="button" class="nbd-chat-btn" (click)="closeArchive()">
|
||||
<lucide-icon [img]="X" [size]="13"></lucide-icon>
|
||||
Revenir au chat
|
||||
{{ 'notebookDetail.backToChat' | translate }}
|
||||
</button>
|
||||
} @else {
|
||||
@if (referencedArchiveIds.size > 0) {
|
||||
<span class="nbd-ref-badge"
|
||||
title="Le contenu de ces archives est injecté comme référence dans chaque question">
|
||||
[title]="'notebookDetail.refBadgeTitle' | translate">
|
||||
<lucide-icon [img]="History" [size]="12"></lucide-icon>
|
||||
{{ referencedArchiveIds.size }} archive(s) en référence
|
||||
{{ 'notebookDetail.refBadge' | translate:{ n: referencedArchiveIds.size } }}
|
||||
</span>
|
||||
}
|
||||
<span class="nbd-chat-head-spacer"></span>
|
||||
<button type="button" class="nbd-chat-btn" (click)="toggleArchives()"
|
||||
[class.active]="archivesOpen"
|
||||
title="Conversations archivées (lecture seule + référence)">
|
||||
[title]="'notebookDetail.archivesBtnTitle' | translate">
|
||||
<lucide-icon [img]="History" [size]="13"></lucide-icon>
|
||||
Archives
|
||||
{{ 'notebookDetail.archives' | translate }}
|
||||
</button>
|
||||
<button type="button" class="nbd-chat-btn nbd-chat-btn--danger" (click)="clearChat()"
|
||||
[disabled]="sending || messages.length === 0"
|
||||
title="Vider la conversation (le fil actuel est archivé, pas supprimé)">
|
||||
[title]="'notebookDetail.clearBtnTitle' | translate">
|
||||
<lucide-icon [img]="Eraser" [size]="13"></lucide-icon>
|
||||
Vider
|
||||
{{ 'notebookDetail.clear' | translate }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@@ -109,12 +109,9 @@
|
||||
@if (archivesOpen && !viewingArchive) {
|
||||
<div class="nbd-archives">
|
||||
@if (archives.length === 0) {
|
||||
<p class="nbd-empty">Aucune conversation archivée pour l'instant — « Vider » archive le fil courant ici.</p>
|
||||
<p class="nbd-empty">{{ 'notebookDetail.archivesEmpty' | translate }}</p>
|
||||
} @else {
|
||||
<p class="nbd-archives-help">
|
||||
Cochez une archive pour l'utiliser comme <strong>référence</strong> dans le chat ;
|
||||
cliquez sur son nom pour la relire.
|
||||
</p>
|
||||
<p class="nbd-archives-help" [innerHTML]="'notebookDetail.archivesHelp' | translate"></p>
|
||||
}
|
||||
@for (a of archives; track a.archivedAt) {
|
||||
<div class="nbd-archive-row" [class.referenced]="isReferenced(a)">
|
||||
@@ -123,9 +120,9 @@
|
||||
class="nbd-archive-check"
|
||||
[checked]="isReferenced(a)"
|
||||
(change)="toggleReference(a)"
|
||||
[title]="isReferenced(a)
|
||||
? 'Archive utilisée comme référence — décocher pour la retirer'
|
||||
: 'Utiliser cette archive comme référence dans le chat'" />
|
||||
[title]="(isReferenced(a)
|
||||
? 'notebookDetail.archiveRefOnTitle'
|
||||
: 'notebookDetail.archiveRefOffTitle') | translate" />
|
||||
<button type="button" class="nbd-archive-item" (click)="openArchive(a)">
|
||||
<lucide-icon [img]="History" [size]="13"></lucide-icon>
|
||||
{{ archiveLabel(a) }}
|
||||
@@ -143,7 +140,7 @@
|
||||
@if (m.role === 'assistant') {
|
||||
<lucide-icon [img]="Sparkles" [size]="12"></lucide-icon>
|
||||
}
|
||||
{{ m.role === 'user' ? 'Vous' : 'IA' }}
|
||||
{{ (m.role === 'user' ? 'notebookDetail.roleUser' : 'notebookDetail.roleAi') | translate }}
|
||||
</div>
|
||||
@if (m.role === 'assistant') {
|
||||
<div class="nbd-msg-content md" [innerHTML]="m.content | markdown"></div>
|
||||
@@ -155,9 +152,9 @@
|
||||
} @else {
|
||||
@if (messages.length === 0) {
|
||||
<p class="nbd-empty">
|
||||
Pose une question sur ta source, ou demande une adaptation pour ta campagne.
|
||||
{{ 'notebookDetail.chatEmpty' | translate }}
|
||||
@if (!hasReadySource()) {
|
||||
<span><br>(Ajoute d'abord une source indexée pour des réponses ancrées.)</span>
|
||||
<span [innerHTML]="'notebookDetail.chatEmptyNoSource' | translate"></span>
|
||||
}
|
||||
</p>
|
||||
}
|
||||
@@ -167,14 +164,14 @@
|
||||
@if (m.role === 'assistant') {
|
||||
<lucide-icon [img]="Sparkles" [size]="12"></lucide-icon>
|
||||
}
|
||||
{{ m.role === 'user' ? 'Vous' : 'IA' }}
|
||||
{{ (m.role === 'user' ? 'notebookDetail.roleUser' : 'notebookDetail.roleAi') | translate }}
|
||||
</div>
|
||||
@if (m.role === 'assistant') {
|
||||
@if (parsedOf(m); as p) {
|
||||
@if (sending && deepProgress && !p.text) {
|
||||
<div class="nbd-deep-progress">
|
||||
<lucide-icon [img]="Layers" [size]="13"></lucide-icon>
|
||||
Analyse approfondie du document… {{ deepProgress.current }}/{{ deepProgress.total }}
|
||||
{{ 'notebookDetail.deepProgress' | translate:{ current: deepProgress.current, total: deepProgress.total } }}
|
||||
</div>
|
||||
}
|
||||
@if (p.text) {
|
||||
@@ -192,7 +189,7 @@
|
||||
</app-notebook-action-card>
|
||||
}
|
||||
@if (sourcesLabel(m); as label) {
|
||||
<div class="nbd-msg-sources" title="Pages de la source utilisées pour ancrer cette réponse">
|
||||
<div class="nbd-msg-sources" [title]="'notebookDetail.sourcesPagesTitle' | translate">
|
||||
📖 {{ label }}
|
||||
</div>
|
||||
}
|
||||
@@ -207,14 +204,14 @@
|
||||
@if (!viewingArchive) {
|
||||
<div class="nbd-input">
|
||||
<textarea [(ngModel)]="draft" rows="2"
|
||||
placeholder="Demande une adaptation, un résumé, un PNJ inspiré de la source…"
|
||||
[placeholder]="'notebookDetail.draftPlaceholder' | translate"
|
||||
(keydown.enter)="$event.preventDefault(); send()"></textarea>
|
||||
<button class="btn-deep" (click)="send(true)" [disabled]="sending || !draft.trim()"
|
||||
title="Analyse approfondie : lit TOUT le document (plus lent, exhaustif). Idéal pour « liste tous les… »">
|
||||
[title]="'notebookDetail.deepBtnTitle' | translate">
|
||||
<lucide-icon [img]="Layers" [size]="15"></lucide-icon>
|
||||
</button>
|
||||
<button class="btn-send" (click)="send()" [disabled]="sending || !draft.trim()"
|
||||
title="Réponse rapide (recherche ciblée dans le document)">
|
||||
[title]="'notebookDetail.sendBtnTitle' | translate">
|
||||
<lucide-icon [img]="Send" [size]="15"></lucide-icon>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -16,6 +16,7 @@ import { loadCampaignTreeData } from '../../campaign-tree.helper';
|
||||
import { NotebookActionCardComponent } from '../notebook-action-card/notebook-action-card.component';
|
||||
import { MarkdownPipe } from '../../../shared/markdown.pipe';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
|
||||
/**
|
||||
* Atelier (workspace) : sources indexées (gauche) + chat ancré RAG (droite).
|
||||
@@ -23,7 +24,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-notebook-detail',
|
||||
imports: [FormsModule, LucideAngularModule, NotebookActionCardComponent, MarkdownPipe],
|
||||
imports: [FormsModule, LucideAngularModule, NotebookActionCardComponent, MarkdownPipe, TranslatePipe],
|
||||
templateUrl: './notebook-detail.component.html',
|
||||
styleUrls: ['./notebook-detail.component.scss']
|
||||
})
|
||||
@@ -68,7 +69,8 @@ export class NotebookDetailComponent implements OnInit {
|
||||
private characterService: CharacterService,
|
||||
private npcService: NpcService,
|
||||
private enemyService: EnemyService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -208,7 +210,7 @@ export class NotebookDetailComponent implements OnInit {
|
||||
next: () => { this.uploading = false; this.reloadSources(); },
|
||||
error: (err) => {
|
||||
this.uploading = false;
|
||||
this.uploadError = err?.error?.message || 'Échec de l\'indexation. Réessaie ou vérifie le modèle d\'embedding.';
|
||||
this.uploadError = err?.error?.message || this.translate.instant('notebookDetail.uploadError');
|
||||
this.reloadSources();
|
||||
}
|
||||
});
|
||||
@@ -232,10 +234,10 @@ export class NotebookDetailComponent implements OnInit {
|
||||
clearChat(): void {
|
||||
if (this.sending || this.messages.length === 0) return;
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Vider la conversation',
|
||||
message: 'Repartir d\'une conversation vierge ?',
|
||||
details: ['Le fil actuel est archivé (pas supprimé) : il restera consultable via « Archives ».'],
|
||||
confirmLabel: 'Vider',
|
||||
title: this.translate.instant('notebookDetail.clearTitle'),
|
||||
message: this.translate.instant('notebookDetail.clearMessage'),
|
||||
details: [this.translate.instant('notebookDetail.clearDetail')],
|
||||
confirmLabel: this.translate.instant('notebookDetail.clear'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
@@ -287,10 +289,11 @@ export class NotebookDetailComponent implements OnInit {
|
||||
/** Libellé d'une archive : date du clear + nb d'échanges. */
|
||||
archiveLabel(a: NotebookArchive): string {
|
||||
const date = new Date(a.archivedAt);
|
||||
const locale = this.translate.getCurrentLang() === 'en' ? 'en-US' : 'fr-FR';
|
||||
const when = isNaN(date.getTime())
|
||||
? a.archivedAt
|
||||
: date.toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short' });
|
||||
return `${when} · ${a.messages.length} message(s)`;
|
||||
: date.toLocaleString(locale, { dateStyle: 'short', timeStyle: 'short' });
|
||||
return this.translate.instant('notebookDetail.archiveLabel', { when, n: a.messages.length });
|
||||
}
|
||||
|
||||
// --- Chat ---
|
||||
|
||||
@@ -1,36 +1,35 @@
|
||||
<div class="nbl-page">
|
||||
<div class="nbl-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> {{ 'common.back' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<header class="nbl-header">
|
||||
<h1><lucide-icon [img]="BookOpen" [size]="22"></lucide-icon> Ateliers d'adaptation</h1>
|
||||
<h1><lucide-icon [img]="BookOpen" [size]="22"></lucide-icon> {{ 'notebookList.title' | translate }}</h1>
|
||||
<p class="nbl-hint">
|
||||
Discute avec l'IA à partir d'un PDF source (recherche dans le document) pour adapter
|
||||
son contenu à ta campagne. La source et la conversation sont conservées.
|
||||
{{ 'notebookList.hint' | translate }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div class="nbl-create">
|
||||
<input type="text" [(ngModel)]="newName" placeholder="Nom de l'atelier (ex: Adaptation du module X)"
|
||||
<input type="text" [(ngModel)]="newName" [placeholder]="'notebookList.namePlaceholder' | translate"
|
||||
(keyup.enter)="create()">
|
||||
<button class="btn-create" (click)="create()" [disabled]="creating">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
{{ creating ? 'Création…' : 'Nouvel atelier' }}
|
||||
{{ (creating ? 'common.creating' : 'notebookList.newNotebook') | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="nbl-list">
|
||||
@if (notebooks.length === 0) {
|
||||
<p class="empty">Aucun atelier pour l'instant.</p>
|
||||
<p class="empty">{{ 'notebookList.empty' | translate }}</p>
|
||||
}
|
||||
@for (nb of notebooks; track nb) {
|
||||
<button class="nbl-item" (click)="open(nb)">
|
||||
<lucide-icon [img]="BookOpen" [size]="16"></lucide-icon>
|
||||
<span class="nbl-item-name">{{ nb.name }}</span>
|
||||
<span class="nbl-del" (click)="remove(nb, $event)" title="Supprimer">
|
||||
<span class="nbl-del" (click)="remove(nb, $event)" [title]="'common.delete' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { NotebookService } from '../../../services/notebook.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { Notebook } from '../../../services/notebook.model';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
|
||||
/**
|
||||
* Liste des ateliers (notebooks) d'une campagne + création.
|
||||
@@ -14,7 +15,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-notebook-list',
|
||||
imports: [FormsModule, LucideAngularModule],
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './notebook-list.component.html',
|
||||
styleUrls: ['./notebook-list.component.scss']
|
||||
})
|
||||
@@ -34,7 +35,8 @@ export class NotebookListComponent implements OnInit {
|
||||
private router: Router,
|
||||
private service: NotebookService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -55,7 +57,7 @@ export class NotebookListComponent implements OnInit {
|
||||
create(): void {
|
||||
if (this.creating) return;
|
||||
this.creating = true;
|
||||
this.service.create(this.campaignId, this.newName.trim() || 'Nouvel atelier').subscribe({
|
||||
this.service.create(this.campaignId, this.newName.trim() || this.translate.instant('notebookList.defaultName')).subscribe({
|
||||
next: (nb) => this.router.navigate(['/campaigns', this.campaignId, 'notebooks', nb.id]),
|
||||
error: () => this.creating = false
|
||||
});
|
||||
@@ -68,9 +70,9 @@ export class NotebookListComponent implements OnInit {
|
||||
remove(nb: Notebook, ev: Event): void {
|
||||
ev.stopPropagation();
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer l\'atelier',
|
||||
message: `Supprimer « ${nb.name} » et ses sources indexées ?`,
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('notebookList.deleteTitle'),
|
||||
message: this.translate.instant('notebookList.deleteMessage', { name: nb.name }),
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
<div class="ne-header">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour à la campagne
|
||||
{{ 'npcEdit.backToCampaign' | translate }}
|
||||
</button>
|
||||
<div class="header-row">
|
||||
<h1>
|
||||
<lucide-icon [img]="Drama" [size]="22"></lucide-icon>
|
||||
{{ npcId ? 'Éditer le PNJ' : 'Nouveau PNJ' }}
|
||||
{{ (npcId ? 'npcEdit.titleEdit' : 'npcEdit.titleNew') | translate }}
|
||||
</h1>
|
||||
@if (npcId) {
|
||||
<button
|
||||
@@ -16,9 +16,9 @@
|
||||
class="btn-ai"
|
||||
(click)="toggleChat()"
|
||||
[class.active]="chatOpen"
|
||||
title="Ouvrir l'Assistant IA pour dialoguer autour de ce PNJ">
|
||||
[title]="'npcEdit.aiAssistantTitle' | translate">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
{{ 'npcEdit.aiAssistant' | translate }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@@ -27,25 +27,25 @@
|
||||
<div class="ne-form">
|
||||
|
||||
<div class="field">
|
||||
<label for="npc-name">Nom du PNJ *</label>
|
||||
<label for="npc-name">{{ 'npcEdit.nameLabel' | translate }}</label>
|
||||
<input
|
||||
id="npc-name"
|
||||
type="text"
|
||||
[(ngModel)]="name"
|
||||
name="name"
|
||||
placeholder="Ex: Borin le forgeron, Dame Elara, Kael l'aubergiste..."
|
||||
[placeholder]="'npcEdit.namePlaceholder' | translate"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="npc-folder">Dossier</label>
|
||||
<label for="npc-folder">{{ 'npcEdit.folder' | translate }}</label>
|
||||
<input
|
||||
id="npc-folder"
|
||||
type="text"
|
||||
[(ngModel)]="folder"
|
||||
name="folder"
|
||||
list="npc-folders"
|
||||
placeholder="Ex: Bard's Gate, Faction des Pipers… (laisser vide = non classé)"
|
||||
[placeholder]="'npcEdit.folderPlaceholder' | translate"
|
||||
/>
|
||||
<datalist id="npc-folders">
|
||||
@for (f of existingFolders; track f) {
|
||||
@@ -56,20 +56,20 @@
|
||||
|
||||
<div class="field-row image-row">
|
||||
<div class="field portrait-field">
|
||||
<label>Portrait</label>
|
||||
<label>{{ 'npcEdit.portrait' | translate }}</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="portraitImageId"
|
||||
aspectRatio="1 / 1"
|
||||
hint="Carre conseille (400×400)."
|
||||
[hint]="'npcEdit.portraitHint' | translate"
|
||||
(imageIdChange)="portraitImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
<div class="field header-field">
|
||||
<label>Bandeau / Header</label>
|
||||
<label>{{ 'npcEdit.header' | translate }}</label>
|
||||
<app-single-image-picker
|
||||
[imageId]="headerImageId"
|
||||
aspectRatio="3 / 1"
|
||||
hint="Format paysage conseille (1200×400)."
|
||||
[hint]="'npcEdit.headerHint' | translate"
|
||||
(imageIdChange)="headerImageId = $event">
|
||||
</app-single-image-picker>
|
||||
</div>
|
||||
@@ -90,23 +90,23 @@
|
||||
<!-- Pages de Lore liées (uniquement si la campagne est rattachée à un Lore) -->
|
||||
@if (loreId) {
|
||||
<div class="field">
|
||||
<label>Pages de Lore liées</label>
|
||||
<label>{{ 'npcEdit.relatedPages' | translate }}</label>
|
||||
<app-lore-link-picker
|
||||
[value]="relatedPageIds"
|
||||
[availablePages]="lorePages"
|
||||
[loreId]="loreId"
|
||||
(valueChange)="relatedPageIds = $event">
|
||||
</app-lore-link-picker>
|
||||
<p class="hint">Reliez ce PNJ aux pages de l'univers (sa ville, sa faction, sa région…). Ces liens apparaissent dans le graphe du Lore.</p>
|
||||
<p class="hint">{{ 'npcEdit.relatedPagesHint' | translate }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="actions">
|
||||
<button type="button" class="btn-primary" [disabled]="!name.trim()" (click)="submit()">
|
||||
<lucide-icon [img]="Save" [size]="16"></lucide-icon>
|
||||
{{ npcId ? 'Enregistrer' : 'Créer' }}
|
||||
{{ (npcId ? 'common.save' : 'common.create') | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="back()">Annuler</button>
|
||||
<button type="button" class="btn-secondary" (click)="back()">{{ 'common.cancel' | translate }}</button>
|
||||
<span class="spacer"></span>
|
||||
@if (npcId) {
|
||||
<button
|
||||
@@ -114,7 +114,7 @@
|
||||
class="btn-danger"
|
||||
(click)="deleteNpc()">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
{{ 'common.delete' | translate }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@@ -129,7 +129,7 @@
|
||||
entityType="npc"
|
||||
[entityId]="npcId"
|
||||
[isOpen]="chatOpen"
|
||||
welcomeMessage="Je vois cette fiche de PNJ. Demande-moi de proposer apparence, motivations, secrets, ou répliques signatures."
|
||||
[welcomeMessage]="'npcEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Component, OnInit } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, Save, ArrowLeft, Drama, Trash2, Sparkles } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GameSystemService } from '../../../services/game-system.service';
|
||||
@@ -24,7 +25,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-npc-edit',
|
||||
imports: [FormsModule, LucideAngularModule, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent, LoreLinkPickerComponent],
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent, LoreLinkPickerComponent],
|
||||
templateUrl: './npc-edit.component.html',
|
||||
styleUrls: ['./npc-edit.component.scss']
|
||||
})
|
||||
@@ -36,11 +37,13 @@ export class NpcEditComponent implements OnInit {
|
||||
readonly Sparkles = Sparkles;
|
||||
|
||||
chatOpen = false;
|
||||
readonly chatQuickSuggestions = [
|
||||
'Propose une apparence et une posture marquantes',
|
||||
'Suggere 2 motivations et un secret pour ce PNJ',
|
||||
'Imagine 3 repliques signatures qui le caracterisent'
|
||||
get chatQuickSuggestions(): string[] {
|
||||
return [
|
||||
this.translate.instant('npcEdit.chatSuggestion1'),
|
||||
this.translate.instant('npcEdit.chatSuggestion2'),
|
||||
this.translate.instant('npcEdit.chatSuggestion3')
|
||||
];
|
||||
}
|
||||
|
||||
toggleChat(): void { this.chatOpen = !this.chatOpen; }
|
||||
|
||||
@@ -74,7 +77,8 @@ export class NpcEditComponent implements OnInit {
|
||||
private gameSystemService: GameSystemService,
|
||||
private pageService: PageService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -174,10 +178,10 @@ export class NpcEditComponent implements OnInit {
|
||||
deleteNpc(): void {
|
||||
if (!this.npcId) return;
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer la fiche ?',
|
||||
message: `Supprimer la fiche de "${this.name}" ?`,
|
||||
details: ['Cette action est irreversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('npcEdit.deleteTitle'),
|
||||
message: this.translate.instant('npcEdit.deleteMessage', { name: this.name }),
|
||||
details: [this.translate.instant('npcEdit.irreversible')],
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok || !this.npcId) return;
|
||||
|
||||
@@ -1,25 +1,24 @@
|
||||
<div class="sbl-page">
|
||||
<div class="sbl-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> {{ 'common.back' | translate }}
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-create" (click)="create()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> Nouveau PNJ
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> {{ 'npcList.create' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<header class="sbl-header">
|
||||
<h1><lucide-icon [img]="Drama" [size]="22"></lucide-icon> PNJ</h1>
|
||||
<h1><lucide-icon [img]="Drama" [size]="22"></lucide-icon> {{ 'npcList.title' | translate }}</h1>
|
||||
<p class="sbl-hint">
|
||||
Tous les personnages non-joueurs de la campagne, classés par dossier.
|
||||
Le champ « Dossier » de chaque fiche pilote le classement.
|
||||
{{ 'npcList.hint' | translate }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div class="sbl-list">
|
||||
@if (total === 0) {
|
||||
<p class="empty">Aucun PNJ pour l'instant.</p>
|
||||
<p class="empty">{{ 'npcList.empty' | translate }}</p>
|
||||
}
|
||||
@for (g of groups; track g.folder) {
|
||||
@if (g.folder) {
|
||||
@@ -29,13 +28,13 @@
|
||||
<span class="sbl-folder-count">{{ g.npcs.length }}</span>
|
||||
</h2>
|
||||
} @else if (groups.length > 1) {
|
||||
<h2 class="sbl-folder sbl-folder--none">Non classés</h2>
|
||||
<h2 class="sbl-folder sbl-folder--none">{{ 'npcList.unclassified' | translate }}</h2>
|
||||
}
|
||||
@for (n of g.npcs; track n.id) {
|
||||
<button class="sbl-item" (click)="open(n)">
|
||||
<lucide-icon [img]="Drama" [size]="16"></lucide-icon>
|
||||
<span class="sbl-item-name">{{ n.name }}</span>
|
||||
<span class="sbl-del" (click)="remove(n, $event)" title="Supprimer">
|
||||
<span class="sbl-del" (click)="remove(n, $event)" [title]="'common.delete' | translate">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LucideAngularModule, ArrowLeft, Plus, Trash2, Drama, Folder } from 'lucide-angular';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { NpcService } from '../../../services/npc.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { Npc } from '../../../services/npc.model';
|
||||
@@ -20,7 +21,7 @@ interface FolderGroup {
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-npc-list',
|
||||
imports: [LucideAngularModule],
|
||||
imports: [LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './npc-list.component.html',
|
||||
styleUrls: ['./npc-list.component.scss']
|
||||
})
|
||||
@@ -41,7 +42,8 @@ export class NpcListComponent implements OnInit {
|
||||
private router: Router,
|
||||
private service: NpcService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
private confirmDialog: ConfirmDialogService,
|
||||
private translate: TranslateService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -92,10 +94,10 @@ export class NpcListComponent implements OnInit {
|
||||
remove(n: Npc, ev: Event): void {
|
||||
ev.stopPropagation();
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer la fiche',
|
||||
message: `Supprimer la fiche de « ${n.name} » ?`,
|
||||
details: ['Cette action est irréversible.'],
|
||||
confirmLabel: 'Supprimer',
|
||||
title: this.translate.instant('npcList.deleteTitle'),
|
||||
message: this.translate.instant('npcList.deleteMessage', { name: n.name }),
|
||||
details: [this.translate.instant('npcList.irreversible')],
|
||||
confirmLabel: this.translate.instant('common.delete'),
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
|
||||
@@ -2,18 +2,18 @@
|
||||
<div class="nv-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
Retour
|
||||
{{ 'common.back' | translate }}
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
@if (npcId) {
|
||||
<button class="btn-ai" (click)="toggleChat()" [class.active]="chatOpen">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
{{ 'npcView.aiAssistant' | translate }}
|
||||
</button>
|
||||
}
|
||||
<button class="btn-edit" (click)="edit()">
|
||||
<lucide-icon [img]="Edit3" [size]="14"></lucide-icon>
|
||||
Editer
|
||||
{{ 'common.edit' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
<section class="nv-lore-links">
|
||||
<h2 class="nv-lore-links-title">
|
||||
<lucide-icon [img]="Link2" [size]="14"></lucide-icon>
|
||||
Pages de Lore liées
|
||||
{{ 'npcView.relatedPages' | translate }}
|
||||
</h2>
|
||||
<div class="nv-lore-chips">
|
||||
@for (pageId of npc!.relatedPageIds; track pageId) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user