diff --git a/src/Heimdall.Application/Services/INtfyService.cs b/src/Heimdall.Application/Services/INtfyService.cs index 7165ea1..f1b0397 100644 --- a/src/Heimdall.Application/Services/INtfyService.cs +++ b/src/Heimdall.Application/Services/INtfyService.cs @@ -3,4 +3,7 @@ namespace Heimdall.Application.Services; public interface INtfyService { Task SendNotificationAsync(string topic, string title, string message, int priority = 3, CancellationToken ct = default); + + /// Envoie une notification de test et indique si le serveur a accepté (retour HTTP 2xx). + Task SendTestAsync(string topic, string title, string message, CancellationToken ct = default); } diff --git a/src/Heimdall.Infrastructure/Services/NtfyService.cs b/src/Heimdall.Infrastructure/Services/NtfyService.cs index 5685703..11dac99 100644 --- a/src/Heimdall.Infrastructure/Services/NtfyService.cs +++ b/src/Heimdall.Infrastructure/Services/NtfyService.cs @@ -30,24 +30,7 @@ public class NtfyService : INtfyService { try { - var (baseUrl, authToken) = await ResolveConfigAsync(ct).ConfigureAwait(false); - - var client = _httpClientFactory.CreateClient("Ntfy"); - var requestUrl = $"{baseUrl.TrimEnd('/')}/{topic}"; - var payload = new { topic, title, message, priority }; - var json = JsonSerializer.Serialize(payload); - var content = new StringContent(json, Encoding.UTF8, "application/json"); - - if (!string.IsNullOrEmpty(authToken)) - client.DefaultRequestHeaders.Authorization = - new AuthenticationHeaderValue("Bearer", authToken); - - var response = await client.PostAsync(requestUrl, content, ct).ConfigureAwait(false); - if (!response.IsSuccessStatusCode) - { - var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); - _logger.LogWarning("ntfy returned {StatusCode} for topic {Topic}: {Body}", response.StatusCode, topic, body); - } + await SendCoreAsync(topic, title, message, priority, ct).ConfigureAwait(false); } catch (Exception ex) { @@ -55,6 +38,42 @@ public class NtfyService : INtfyService } } + public async Task SendTestAsync(string topic, string title, string message, CancellationToken ct = default) + { + try + { + var response = await SendCoreAsync(topic, title, message, 4, ct).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + _logger.LogWarning("ntfy test returned {StatusCode} for topic {Topic}: {Body}", response.StatusCode, topic, body); + } + return response.IsSuccessStatusCode; + } + catch (Exception ex) + { + _logger.LogError(ex, "ntfy test failed for topic {Topic}", topic); + return false; + } + } + + private async Task SendCoreAsync(string topic, string title, string message, int priority, CancellationToken ct) + { + var (baseUrl, authToken) = await ResolveConfigAsync(ct).ConfigureAwait(false); + + var client = _httpClientFactory.CreateClient("Ntfy"); + var requestUrl = $"{baseUrl.TrimEnd('/')}/{topic}"; + var payload = new { topic, title, message, priority }; + var json = JsonSerializer.Serialize(payload); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + if (!string.IsNullOrEmpty(authToken)) + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", authToken); + + return await client.PostAsync(requestUrl, content, ct).ConfigureAwait(false); + } + /// /// Source de vérité : AppSettings en base (ntfy.*), avec fallback /// config/appsettings puis env (migration douce, ticket #80). Relu à diff --git a/src/Heimdall.Web/Components/Pages/AgentDetail.razor b/src/Heimdall.Web/Components/Pages/AgentDetail.razor index 145706e..342ae82 100644 --- a/src/Heimdall.Web/Components/Pages/AgentDetail.razor +++ b/src/Heimdall.Web/Components/Pages/AgentDetail.razor @@ -149,8 +149,8 @@ else @(setting.Description ?? HumanizeAgentKey(setting.Key)) - - @setting.Key + + @(overridden ? "Valeur surchargée pour cet agent" : "Valeur globale appliquée") @if (overridden) diff --git a/src/Heimdall.Web/Components/Settings/AiSettingsSection.razor b/src/Heimdall.Web/Components/Settings/AiSettingsSection.razor index dc980bb..45781fe 100644 --- a/src/Heimdall.Web/Components/Settings/AiSettingsSection.razor +++ b/src/Heimdall.Web/Components/Settings/AiSettingsSection.razor @@ -36,10 +36,25 @@ HelperText="Défaut global appliqué aux agents. Une modification nécessite le rechargement de la configuration des agents." /> + +
+ + @(_testing ? "Test en cours…" : "Tester les moteurs IA") + +
+ @if (_testResult is not null) + { + + @_testResult.Status — @_testResult.Message + + } @code { private List _settings = []; + private bool _testing; + private TestActionResult? _testResult; protected override async Task OnInitializedAsync() { @@ -60,6 +75,24 @@ private Task OnOllamaUrlChanged(string v) => SaveValueAsync("ai.ollamaurl", v); private Task OnDetectionEnabledChanged(bool v) => SaveValueAsync("ai.detection.enabled", v ? "true" : "false"); + private async Task TestAiAsync() + { + _testing = true; + _testResult = null; + try + { + _testResult = await Api.TestAiAsync() ?? new TestActionResult(false, "Test impossible (API indisponible)."); + } + catch (Exception ex) + { + _testResult = new TestActionResult(false, $"Test impossible : {ex.Message}"); + } + finally + { + _testing = false; + } + } + private async Task SaveValueAsync(string key, string? value) { value ??= string.Empty; diff --git a/src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor b/src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor index fc4b0ce..aec8b9c 100644 --- a/src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor +++ b/src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor @@ -82,10 +82,29 @@ HelperText="Active le chiffrement TLS lors de la connexion SMTP." /> + +
+ + @(_testing ? "Test en cours…" : "Tester ntfy") + + + @(_testing ? "Test en cours…" : "Tester l'envoi email") + +
+ @if (_testResult is not null) + { + + @_testResult.Message + + } @code { private List _settings = []; + private bool _testing; + private TestActionResult? _testResult; protected override async Task OnInitializedAsync() { @@ -121,6 +140,42 @@ private Task OnPasswordChanged(string v) => SaveValueAsync("email.password", v); private Task OnUseSslChanged(bool v) => SaveValueAsync("email.usessl", v ? "true" : "false"); + private async Task TestNtfyAsync() + { + _testing = true; + _testResult = null; + try + { + _testResult = await Api.TestNtfyAsync() ?? new TestActionResult(false, "Test impossible (API indisponible)."); + } + catch (Exception ex) + { + _testResult = new TestActionResult(false, $"Test impossible : {ex.Message}"); + } + finally + { + _testing = false; + } + } + + private async Task TestEmailAsync() + { + _testing = true; + _testResult = null; + try + { + _testResult = await Api.TestEmailAsync() ?? new TestActionResult(false, "Test impossible (API indisponible)."); + } + catch (Exception ex) + { + _testResult = new TestActionResult(false, $"Test impossible : {ex.Message}"); + } + finally + { + _testing = false; + } + } + private async Task SaveValueAsync(string key, string? value) { value ??= string.Empty; diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs index c4010ff..899caa4 100644 --- a/src/Heimdall.Web/Controllers/SettingsController.cs +++ b/src/Heimdall.Web/Controllers/SettingsController.cs @@ -249,6 +249,77 @@ public class SettingsController : ControllerBase }); } + /// + /// Send a test email through the configured SMTP server (Admin only). + /// + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] + [HttpPost("email/test")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(object), StatusCodes.Status400BadRequest)] + public async Task TestEmail( + [FromServices] IEmailService emailService, + CancellationToken ct) + { + var settings = await _mediator.Send(new GetSettingsQuery(), ct); + if (!settings.IsSuccess) + return StatusCode(settings.StatusCode ?? 400, new { error = settings.Error }); + + var fromAddress = settings.Data!.FirstOrDefault(s => s.Key == "email.fromaddress")?.Value; + if (string.IsNullOrWhiteSpace(fromAddress)) + return BadRequest(new { error = "Adresse expéditrice non configurée (email.fromaddress)." }); + + try + { + await emailService.SendEmailAsync(fromAddress, "Heimdall — test de configuration", + "

✅ Configuration email OK

Ce message confirme que le serveur SMTP est joignable et que l'authentification fonctionne.

", ct); + return Ok(new { success = true, message = $"Email de test envoyé à {fromAddress}" }); + } + catch (Exception ex) + { + return Ok(new { success = false, message = $"Échec de l'envoi : {ex.Message}" }); + } + } + + /// + /// Send a test notification through the configured ntfy server (Admin only). + /// + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] + [HttpPost("ntfy/test")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + public async Task TestNtfy( + [FromServices] INtfyService ntfyService, + [FromBody] TestNtfyRequest? request, + CancellationToken ct) + { + var topic = string.IsNullOrWhiteSpace(request?.Topic) ? "heimdall-test" : request.Topic; + var ok = await ntfyService.SendTestAsync(topic, "Heimdall — test de configuration", + "✅ Notification ntfy reçue : le serveur est joignable et le token est accepté.", ct); + return Ok(new { success = ok, message = ok + ? $"Notification test envoyée sur le topic « {topic} »" + : "Échec de l'envoi ntfy (serveur injoignable ou rejet — voir les logs)." }); + } + + /// + /// Ping the configured AI backends (CodeProject.AI / Ollama) (Admin only). + /// + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] + [HttpPost("ai/test")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + public async Task TestAi( + [FromServices] Heimdall.Infrastructure.HealthChecks.AiHealthCheck aiHealthCheck, + CancellationToken ct) + { + var result = await aiHealthCheck.CheckHealthAsync(null!, ct); + return Ok(new + { + success = result.Status == Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Healthy, + status = result.Status.ToString(), + message = result.Description, + }); + } + + public sealed record TestNtfyRequest(string? Topic); + /// /// Broadcast a "ConfigReload" signal to all connected agents so they /// re-fetch their full configuration (Admin only). diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 355a4bd..94b4d97 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -504,6 +504,36 @@ public class HeimdallApiClient return await response.Content.ReadFromJsonAsync(); } + /// Send a test email (POST /api/settings/email/test). + public async Task TestEmailAsync() + { + var client = CreateClient(); + var response = await client.PostAsync("api/settings/email/test", null); + if (!response.IsSuccessStatusCode) + return null; + return await response.Content.ReadFromJsonAsync(); + } + + /// Send a test ntfy notification (POST /api/settings/ntfy/test). + public async Task TestNtfyAsync() + { + var client = CreateClient(); + var response = await client.PostAsync("api/settings/ntfy/test", null); + if (!response.IsSuccessStatusCode) + return null; + return await response.Content.ReadFromJsonAsync(); + } + + /// Ping the AI backends (POST /api/settings/ai/test). + public async Task TestAiAsync() + { + var client = CreateClient(); + var response = await client.PostAsync("api/settings/ai/test", null); + if (!response.IsSuccessStatusCode) + return null; + return await response.Content.ReadFromJsonAsync(); + } + public async Task ReloadAllConfigAsync() { var client = CreateClient(); @@ -706,6 +736,13 @@ public record StorageTestResult( [property: JsonPropertyName("healthy")] bool? Healthy ); +/// Résultat d'un test d'intégration (email / ntfy / IA). +public record TestActionResult( + [property: JsonPropertyName("success")] bool Success, + [property: JsonPropertyName("message")] string? Message, + [property: JsonPropertyName("status")] string? Status = null +); + // ─── Settings DTOs ───────────────────────────────────────────────── public record AppSettingItem( diff --git a/tests/Heimdall.Web.Tests/Components/Settings/AiSettingsSectionTests.cs b/tests/Heimdall.Web.Tests/Components/Settings/AiSettingsSectionTests.cs index bce4e89..3e3f2cf 100644 --- a/tests/Heimdall.Web.Tests/Components/Settings/AiSettingsSectionTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Settings/AiSettingsSectionTests.cs @@ -55,4 +55,26 @@ public class AiSettingsSectionTests : PageTestBase r.RequestUri!.AbsolutePath.Contains("ai.cpaiurl", StringComparison.OrdinalIgnoreCase)); }); } + + [Fact] + public void AiSection_TestMoteurs_AppelleEndpointEtAfficheStatut() + { + Handler.OnGet("api/settings", new List { Setting("ai.cpaiurl", "http://cpai:32168") }); + Handler.On(HttpMethod.Post, "api/settings/ai/test", + new { success = true, status = "Healthy", message = "CodeProject.AI reachable" }); + LoginAs(); + + var cut = Render(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Tester les moteurs IA")); + + cut.FindAll("button").Single(b => b.TextContent.Contains("Tester les moteurs IA")).Click(); + + cut.WaitForAssertion(() => + { + Handler.Requests.ShouldContain(r => + r.Method == HttpMethod.Post && + r.RequestUri!.AbsolutePath.Contains("ai/test", StringComparison.OrdinalIgnoreCase)); + cut.Markup.ShouldContain("CodeProject.AI reachable"); + }); + } } diff --git a/tests/Heimdall.Web.Tests/Components/Settings/NotificationSettingsSectionTests.cs b/tests/Heimdall.Web.Tests/Components/Settings/NotificationSettingsSectionTests.cs index 23e85f7..9e6682c 100644 --- a/tests/Heimdall.Web.Tests/Components/Settings/NotificationSettingsSectionTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Settings/NotificationSettingsSectionTests.cs @@ -82,4 +82,48 @@ public class NotificationSettingsSectionTests : PageTestBase cut.FindAll("input")[7].GetAttribute("value").ShouldBe(string.Empty); }); } + + [Fact] + public void NotificationSection_TestNtfy_AppelleEndpointEtAfficheSucces() + { + Handler.OnGet("api/settings", new List { Setting("ntfy.baseurl", "https://ntfy.sh") }); + Handler.On(HttpMethod.Post, "api/settings/ntfy/test", + new { success = true, message = "Notification test envoyée sur le topic « heimdall-test »" }); + LoginAs(); + + var cut = Render(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Tester ntfy")); + + cut.FindAll("button").Single(b => b.TextContent.Contains("Tester ntfy")).Click(); + + cut.WaitForAssertion(() => + { + Handler.Requests.ShouldContain(r => + r.Method == HttpMethod.Post && + r.RequestUri!.AbsolutePath.Contains("ntfy/test", StringComparison.OrdinalIgnoreCase)); + cut.Markup.ShouldContain("Notification test envoyée"); + }); + } + + [Fact] + public void NotificationSection_TestEmail_AppelleEndpointEtAfficheErreur() + { + Handler.OnGet("api/settings", new List { Setting("email.fromaddress", "a@b.c") }); + Handler.On(HttpMethod.Post, "api/settings/email/test", + new { success = false, message = "Échec de l'envoi : SMTP injoignable" }); + LoginAs(); + + var cut = Render(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Tester l'envoi email")); + + cut.FindAll("button").Single(b => b.TextContent.Contains("Tester l'envoi email")).Click(); + + cut.WaitForAssertion(() => + { + Handler.Requests.ShouldContain(r => + r.Method == HttpMethod.Post && + r.RequestUri!.AbsolutePath.Contains("email/test", StringComparison.OrdinalIgnoreCase)); + cut.Markup.ShouldContain("SMTP injoignable"); + }); + } }