feat(settings): sections visuelles IA/Notifications/Défauts agents — suppression du CRUD clé/valeur (Fixes #79)

- SettingsPage refondue : plus de création/édition clé/valeur arbitraire,
  chaque domaine a sa section dédiée (pattern StorageSettingsSection)
- NotificationSettingsSection : ntfy (baseUrl, token) + email SMTP (from,
  host, port, user, password, SSL) — secrets masqués, redaction API respectée
- AiSettingsSection : URLs CodeProject.AI/Ollama + toggle détection IA
- AgentDefaultsSection : niveau de log global (select), rétention logs,
  intervalle heartbeat, DSN Sentry
- Seed #80 étendu : ai.detection.enabled, log.level, log.retentionDays,
  heartbeat.interval.seconds, sentry.dsn (idempotent, catégories cohérentes)
- Tests bUnit : 12 tests (4 page + 8 sections) — rendu, PUT par clé, secrets
  redactés invisibles ; 221 tests Web verts
This commit is contained in:
Arnaud Dartois committed 2026-08-12 10:46:09 +02:00
1 parent a07a0cae52
commit d527f3ccc9
9 files changed
+648 -758

No files matched your search

@@ -9,650 +9,40 @@
<i class="fas fa-cog mr-2"></i>
Configuration
</MudText>
<MudTooltip Text="Ajouter un nouveau paramètre">
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)" Class="mr-2">
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Nouveau
</MudButton>
</MudTooltip>
<MudTooltip Text="Forcer le rechargement de la configuration sur tous les agents">
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Color="Color.Info" OnClick="@ReloadAllConfig" aria-label="Recharger la configuration" />
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Color="Color.Info" OnClick="ReloadAllConfig"
Disabled="@_reloading" aria-label="Recharger la configuration" />
</MudTooltip>
</div>
@* Search + Category filter *@
<MudPaper Elevation="1" Class="pa-4 mb-4" Style="border-radius: var(--hmd-radius-md);">
<MudGrid>
<MudItem xs="12" sm="6">
<MudTextField @bind-Value="_searchQuery" Label="Rechercher par clé ou valeur"
Variant="Variant.Outlined" Immediate="true" Class="mb-0"
Placeholder="Ex: detection, heartbeat, log..."
Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" />
</MudItem>
<MudItem xs="12" sm="4">
<MudSelect @bind-Value="_categoryFilter" Label="Catégorie" Variant="Variant.Outlined"
Class="mb-0" Clearable="true">
<MudSelectItem T="string" Value="@null">Toutes les catégories</MudSelectItem>
@foreach (var cat in _availableCategories)
{
<MudSelectItem Value="@cat" @key="cat">@cat</MudSelectItem>
}
</MudSelect>
</MudItem>
<MudItem xs="12" sm="2" Class="d-flex align-center">
<MudButton Variant="Variant.Text" OnClick="@ResetFilters" Class="mb-0">
<MudIcon Icon="@Icons.Material.Filled.Clear" Size="Size.Small" Class="mr-1" /> Effacer
</MudButton>
</MudItem>
</MudGrid>
</MudPaper>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
Chaque domaine est configuré via sa section dédiée. Les modifications sont enregistrées immédiatement
et propagées aux agents (bouton <strong>Recharger</strong> en haut à droite pour forcer la notification).
</MudText>
@* ── Section Stockage dédiée (config visuelle) ───────────────────── *@
<StorageSettingsSection />
@if (_loading)
{
<MudPaper Elevation="1" Class="pa-4" Style="border-radius: var(--hmd-radius-md);">
<MudSkeleton Width="200px" Height="24px" />
<MudSkeleton Width="100%" Height="40px" Class="mt-2" />
<MudSkeleton Width="100%" Height="40px" Class="mt-1" />
<MudSkeleton Width="100%" Height="40px" Class="mt-1" />
</MudPaper>
}
else if (_error)
{
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
<MudText>Erreur lors du chargement de la configuration.</MudText>
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadSettings" Class="mt-2">
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
</MudButton>
</MudAlert>
}
else if (_settings is null || _settings.Count == 0)
{
<MudPaper Class="pa-8 text-center" Style="border-radius: var(--hmd-radius-lg);">
<MudIcon Icon="@Icons.Material.Filled.Settings" Size="Size.Large" Color="Color.Secondary" />
<MudText Typo="Typo.h6" Color="Color.Secondary" Class="mt-4">Aucun paramètre configuré</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
Créez votre premier paramètre pour commencer à personnaliser la configuration.
</MudText>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)">
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Nouveau paramètre
</MudButton>
</MudPaper>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-2">
@_filteredSettings.Sum(g => g.Value.Count) paramètre(s) affiché(s)
@if (!string.IsNullOrEmpty(_searchQuery) || _categoryFilter is not null)
{
<text>(filtrés)</text>
}
</MudText>
@foreach (var category in _filteredSettings)
{
<div class="settings-category mb-4" @key="category.Key">
<div class="d-flex align-center mb-2 mt-2">
<MudText Typo="Typo.h6" Class="flex-grow-1">
<MudIcon Icon="@GetCategoryIcon(category.Key)" Size="Size.Small" Class="mr-1" />
@category.Key
</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined">@category.Value.Count</MudChip>
</div>
<MudGrid>
@foreach (var setting in category.Value)
{
<MudItem xs="12" sm="6" lg="4" @key="setting.Key">
<MudPaper Elevation="1" Class="pa-4 settings-card" Style="border-radius: var(--hmd-radius-lg); height: 100%;">
<div class="d-flex align-center mb-2">
<MudIcon Icon="@GetTypeIcon(setting.ValueType)" Size="Size.Small"
Color="@GetTypeColorEnum(setting.ValueType)" Class="mr-2" />
<div class="flex-grow-1">
<MudText Typo="Typo.body1" Class="font-weight-medium settings-label">
@(setting.Description ?? HumanizeKey(setting.Key))
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="settings-key">
@setting.Key
</MudText>
</div>
<MudTooltip Text="Supprimer">
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" aria-label="Supprimer"
Color="Color.Error" OnClick="@(() => ConfirmDelete(setting))" />
</MudTooltip>
</div>
@switch (setting.ValueType.ToLowerInvariant())
{
case "boolean":
case "bool":
<div class="d-flex align-center">
<MudSwitch T="bool"
Value="@(setting.Value?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)"
ValueChanged="@(v => SaveBoolInline(setting, v))"
Color="Color.Primary" Class="flex-grow-1" />
<MudText Typo="Typo.body2" Color="Color.Primary" Class="font-weight-medium">
@(setting.Value?.Equals("true", StringComparison.OrdinalIgnoreCase) == true ? "Activé" : "Désactivé")
</MudText>
</div>
break;
case "number":
case "int":
case "integer":
case "double":
<MudTextField T="string" Value="@setting.Value" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveInline(setting, v))"
Label="Valeur" Type="InputType.Number" />
break;
case "select":
case "dropdown":
<MudSelect T="string" Value="@setting.Value" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveInline(setting, v))" Label="Valeur">
@foreach (var opt in (setting.AllowedValues ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
<MudSelectItem Value="@opt" @key="opt">@opt</MudSelectItem>
}
</MudSelect>
break;
default:
<MudTextField T="string" Value="@setting.Value" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveInline(setting, v))" Label="Valeur" />
break;
}
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2 d-flex align-center">
<MudIcon Icon="@Icons.Material.Filled.Schedule" Size="Size.Small" Class="mr-1" />
@setting.UpdatedAt.ToString("g")
</MudText>
</MudPaper>
</MudItem>
}
</MudGrid>
</div>
}
}
@* ─── Dialog: Créer un paramètre ──────────────────────────────────── *@
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
<MudDialog @bind-Visible="_showCreate">
<TitleContent><MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Nouveau paramètre
</MudText></TitleContent>
<DialogContent>
<form @onsubmit="CreateSetting" method="post">
<MudTextField @bind-Value="_createKey" Label="Clé *" Variant="Variant.Outlined"
Class="mb-4" Required="true" Immediate="true"
Placeholder="Ex: detection.threshold" />
<MudTextField @bind-Value="_createValue" Label="Valeur *" Variant="Variant.Outlined"
Class="mb-4" Required="true" Immediate="true" />
<MudTextField @bind-Value="_createDescription" Label="Description" Variant="Variant.Outlined"
Class="mb-4" Immediate="true" />
<MudTextField @bind-Value="_createCategory" Label="Catégorie" Variant="Variant.Outlined"
Class="mb-4" Immediate="true" HelperText="Ex: General, Detection, Recording..."
Placeholder="General" />
<MudText Typo="Typo.body2" Class="mb-2">Type de valeur</MudText>
<MudSelect @bind-Value="_createValueType" Label="Type" Variant="Variant.Outlined" Class="mb-4">
<MudSelectItem Value="@("string")">string</MudSelectItem>
<MudSelectItem Value="@("boolean")">boolean</MudSelectItem>
<MudSelectItem Value="@("number")">number</MudSelectItem>
<MudSelectItem Value="@("select")">select</MudSelectItem>
</MudSelect>
@if (_createValueType == "select")
{
<MudTextField @bind-Value="_createAllowedValues" Label="Valeurs autorisées (séparées par des virgules)"
Variant="Variant.Outlined" Class="mb-4" Immediate="true"
HelperText="Ex: valeur1,valeur2,valeur3" />
}
<MudSwitch T="bool" @bind-Value="_createAgentScoped" Color="Color.Tertiary"
Label="Exposé aux agents"
HelperText="Visible et modifiable sur chaque agent (hérité par défaut, surchargeable)" Class="mb-4" />
@if (!string.IsNullOrEmpty(_createError))
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_createError</MudAlert>
}
<MudButton Variant="Variant.Filled" Color="Color.Primary" ButtonType="ButtonType.Submit"
Disabled="@_saving" Class="hidden">
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
Créer
</MudButton>
</form>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _showCreate = false)">Annuler</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@CreateSetting" Disabled="@_saving">
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
Créer
</MudButton>
</DialogActions>
</MudDialog>
@* ─── Dialog: Modifier un paramètre ───────────────────────────────── *@
<MudOverlay Visible="@_showEdit" OnClick="@(() => _showEdit = false)" />
<MudDialog @bind-Visible="_showEdit">
<TitleContent><MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Edit" Class="mr-1" /> @_editSetting!.Key
</MudText></TitleContent>
<DialogContent>
<form @onsubmit="SaveEdit" method="post">
@if (_editSetting!.ValueType.ToLowerInvariant() is "boolean" or "bool")
{
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-2">Valeur</MudText>
<MudSwitch T="bool" @bind-Value="_editBoolValue" Color="Color.Primary" />
}
else if (_editSetting!.ValueType.ToLowerInvariant() is "number" or "int" or "integer")
{
<MudTextField @bind-Value="_editStringValue" Label="Valeur *" Variant="Variant.Outlined"
InputType="InputType.Number" Class="mb-4" Required="true" Immediate="true" />
}
else if (_editSetting!.ValueType.ToLowerInvariant() is "select" or "dropdown"
&& !string.IsNullOrEmpty(_editSetting.AllowedValues))
{
<MudText Typo="Typo.body2" Class="mb-2">Valeur</MudText>
<MudSelect @bind-Value="_editStringValue" Label="Valeur" Variant="Variant.Outlined" Class="mb-4">
@foreach (var opt in _editAllowedOptions)
{
<MudSelectItem Value="@opt" @key="opt">@opt</MudSelectItem>
}
</MudSelect>
}
else
{
<MudTextField @bind-Value="_editStringValue" Label="Valeur *" Variant="Variant.Outlined"
Class="mb-4" Required="true" Immediate="true" />
}
<MudTextField @bind-Value="_editDescription" Label="Description" Variant="Variant.Outlined"
Class="mb-4" Immediate="true" />
<MudTextField @bind-Value="_editCategory" Label="Catégorie" Variant="Variant.Outlined"
Class="mb-4" Immediate="true" />
<MudText Typo="Typo.body2" Class="mb-2">Type de valeur</MudText>
<MudSelect @bind-Value="_editValueType" Label="Type" Variant="Variant.Outlined" Class="mb-4">
<MudSelectItem Value="@("string")">string</MudSelectItem>
<MudSelectItem Value="@("boolean")">boolean</MudSelectItem>
<MudSelectItem Value="@("number")">number</MudSelectItem>
<MudSelectItem Value="@("select")">select</MudSelectItem>
</MudSelect>
@if (_editValueType == "select")
{
<MudTextField @bind-Value="_editAllowedValues" Label="Valeurs autorisées (séparées par des virgules)"
Variant="Variant.Outlined" Class="mb-4" Immediate="true"
HelperText="Ex: valeur1,valeur2,valeur3" />
}
@if (!string.IsNullOrEmpty(_editError))
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_editError</MudAlert>
}
<MudButton Variant="Variant.Filled" Color="Color.Primary" ButtonType="ButtonType.Submit"
Disabled="@_saving" Class="hidden">
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
Enregistrer
</MudButton>
</form>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@CloseEdit">Annuler</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@SaveEdit" Disabled="@_saving">
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
Enregistrer
</MudButton>
</DialogActions>
</MudDialog>
@* ─── Dialog: Confirmer la suppression ────────────────────────────── *@
<MudOverlay Visible="@_showDeleteConfirm" OnClick="@(() => _showDeleteConfirm = false)" />
<MudDialog @bind-Visible="_showDeleteConfirm">
<TitleContent><MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Delete" Color="Color.Error" Class="mr-1" /> Confirmer la suppression
</MudText></TitleContent>
<DialogContent>
<MudAlert Severity="Severity.Warning" Class="mb-4">
Êtes-vous sûr de vouloir supprimer le paramètre <strong>@_deleteTarget!.Key</strong> ?
@if (_deleteTarget.Description is not null)
{
<br /><MudText Typo="Typo.body2" Color="Color.Secondary">@_deleteTarget.Description</MudText>
}
<br /><MudText Typo="Typo.body2" Color="Color.Warning" Class="mt-2">
<MudIcon Icon="@Icons.Material.Filled.Warning" Size="Size.Small" Class="mr-1" />
Cette action est irréversible. Les agents seront notifiés du changement en temps réel.
</MudText>
</MudAlert>
@if (!string.IsNullOrEmpty(_deleteError))
{
<MudAlert Severity="Severity.Error" Class="mt-2">@_deleteError</MudAlert>
}
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _showDeleteConfirm = false)">Annuler</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@DeleteSetting" Disabled="@_saving">
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
Supprimer
</MudButton>
</DialogActions>
</MudDialog>
<NotificationSettingsSection />
<AiSettingsSection />
<AgentDefaultsSection />
@code {
private List<AppSettingItem>? _settings;
private Dictionary<string, List<AppSettingItem>> _groupedSettings = new();
private Dictionary<string, List<AppSettingItem>> _filteredSettings = new();
private List<string> _availableCategories = [];
private bool _loading = true;
private bool _error;
private bool _saving;
// Search / Filter
private string _searchQuery = "";
private string? _categoryFilter;
// Edit state
private AppSettingItem? _editSetting;
private bool _showEdit;
private string _editStringValue = "";
private bool _editBoolValue;
private string _editDescription = "";
private string _editCategory = "";
private string _editValueType = "";
private string _editAllowedValues = "";
private string[] _editAllowedOptions = [];
private string _editError = "";
// Create state
private bool _showCreate;
private string _createKey = "";
private string _createValue = "";
private string _createDescription = "";
private string _createCategory = "General";
private string _createValueType = "string";
private string _createAllowedValues = "";
private bool _createAgentScoped = true;
private string _createError = "";
// Delete state
private AppSettingItem? _deleteTarget;
private bool _showDeleteConfirm;
private string _deleteError = "";
// Track switch states for display
private Dictionary<string, bool> _switches = new();
protected override async Task OnInitializedAsync() => await LoadSettings();
private async Task LoadSettings()
{
_loading = true;
_error = false;
try
{
_settings = await Api.GetSettingsAsync();
_switches.Clear();
foreach (var s in _settings)
{
if (s.ValueType.ToLowerInvariant() is "boolean" or "bool")
_switches[s.Key] = bool.TryParse(s.Value, out var b) && b;
}
_groupedSettings = _settings
.GroupBy(s => string.IsNullOrEmpty(s.Category) ? "General" : s.Category)
.OrderBy(g => g.Key)
.ToDictionary(g => g.Key, g => g.ToList());
_availableCategories = [.. _groupedSettings.Keys.OrderBy(x => x)];
ApplyFilters();
}
catch {
_error = true;
Snackbar.Add(UiErrors.OperationFailed(), Severity.Error);
}
finally { _loading = false; }
}
private void ApplyFilters()
{
var query = _searchQuery?.Trim().ToLowerInvariant() ?? "";
_filteredSettings = _groupedSettings
.Where(g => _categoryFilter is null || g.Key == _categoryFilter)
.ToDictionary(g => g.Key, g =>
{
if (string.IsNullOrEmpty(query)) return g.Value;
return g.Value.Where(s =>
s.Key.Contains(query, StringComparison.OrdinalIgnoreCase) ||
(s.Value?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false) ||
(s.Description?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false)
).ToList();
})
.Where(g => g.Value.Count > 0)
.ToDictionary(g => g.Key, g => g.Value);
}
private void ResetFilters()
{
_searchQuery = "";
_categoryFilter = null;
ApplyFilters();
}
private static Color GetTypeColorEnum(string valueType) => valueType.ToLowerInvariant() switch
{
"boolean" or "bool" => Color.Success,
"number" or "int" or "integer" or "double" => Color.Info,
"select" or "dropdown" => Color.Warning,
_ => Color.Secondary
};
private static string GetTypeIcon(string valueType) => valueType.ToLowerInvariant() switch
{
"boolean" or "bool" => Icons.Material.Filled.ToggleOn,
"number" or "int" or "integer" or "double" => Icons.Material.Filled.Tag,
"select" or "dropdown" => Icons.Material.Filled.ArrowDropDownCircle,
_ => Icons.Material.Filled.TextFields
};
private static string GetCategoryIcon(string category) => category.ToLowerInvariant() switch
{
"general" or "general" => Icons.Material.Filled.Settings,
"detection" => Icons.Material.Filled.Visibility,
"recording" => Icons.Material.Filled.Videocam,
"logging" or "log" => Icons.Material.Filled.BugReport,
"network" => Icons.Material.Filled.Wifi,
"storage" => Icons.Material.Filled.Storage,
"notification" or "notifications" => Icons.Material.Filled.Notifications,
_ => Icons.Material.Filled.Folder
};
private static string HumanizeKey(string key)
{
var parts = key.Split('.', '_', '-');
return string.Join(' ', parts.Select(p => p.Length <= 2
? p.ToUpperInvariant()
: char.ToUpperInvariant(p[0]) + p[1..]));
}
// ─── Create ───────────────────────────────────────────────────────
private async Task CreateSetting()
{
if (string.IsNullOrWhiteSpace(_createKey) || string.IsNullOrWhiteSpace(_createValue))
{ _createError = "Les champs Clé et Valeur sont requis"; return; }
_saving = true;
_createError = "";
try
{
var allowedValues = _createValueType == "select" && !string.IsNullOrWhiteSpace(_createAllowedValues)
? _createAllowedValues
: null;
var result = await Api.CreateSettingAsync(new CreateAppSettingRequest(
_createKey.Trim(),
_createValue.Trim(),
string.IsNullOrWhiteSpace(_createCategory) ? "General" : _createCategory.Trim(),
string.IsNullOrWhiteSpace(_createDescription) ? null : _createDescription.Trim(),
_createValueType,
allowedValues,
_createAgentScoped
));
if (!result.IsSuccessStatusCode)
{
var body = await result.Content.ReadAsStringAsync();
_createError = $"Erreur : {result.StatusCode} — {body}";
return;
}
_showCreate = false;
_createKey = ""; _createValue = ""; _createDescription = "";
_createCategory = "General"; _createValueType = "string"; _createAllowedValues = "";
Snackbar.Add("Paramètre créé avec succès — notifié aux agents en temps réel", Severity.Success);
await LoadSettings();
}
catch { _createError = UiErrors.OperationFailed(); }
finally { _saving = false; }
}
// ─── Edit ─────────────────────────────────────────────────────────
private void OpenEdit(AppSettingItem setting)
{
_editSetting = setting;
_editStringValue = setting.Value;
_editBoolValue = bool.TryParse(setting.Value, out var b) && b;
_editDescription = setting.Description ?? "";
_editCategory = setting.Category;
_editValueType = setting.ValueType;
_editAllowedValues = setting.AllowedValues ?? "";
_editAllowedOptions = (setting.AllowedValues ?? "")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
_editError = "";
_showEdit = true;
}
private void CloseEdit()
{
_showEdit = false;
_editSetting = null;
}
private async Task SaveEdit()
{
if (_editSetting is null) return;
_saving = true;
_editError = "";
try
{
var newValue = _editSetting!.ValueType.ToLowerInvariant() is "boolean" or "bool"
? _editBoolValue.ToString().ToLowerInvariant()
: _editStringValue.Trim();
var allowedValues = _editValueType == "select" && !string.IsNullOrWhiteSpace(_editAllowedValues)
? _editAllowedValues
: null;
var result = await Api.UpdateSettingAsync(_editSetting!.Key, new UpdateAppSettingRequest(
newValue,
string.IsNullOrWhiteSpace(_editDescription) ? null : _editDescription.Trim(),
string.IsNullOrWhiteSpace(_editCategory) ? null : _editCategory.Trim(),
_editValueType,
allowedValues
));
if (!result.IsSuccessStatusCode)
{
var body = await result.Content.ReadAsStringAsync();
_editError = $"Erreur : {result.StatusCode} — {body}";
return;
}
Snackbar.Add("Paramètre mis à jour — notifié aux agents en temps réel", Severity.Success);
CloseEdit();
await LoadSettings();
}
catch { _editError = UiErrors.OperationFailed(); }
finally { _saving = false; }
}
// ─── Inline edit (table) ─────────────────────────────────────────
private async Task SaveInline(AppSettingItem setting, string value)
{
try
{
var result = await Api.UpdateSettingAsync(setting.Key, new UpdateAppSettingRequest(
value?.Trim() ?? "",
string.IsNullOrWhiteSpace(setting.Description) ? null : setting.Description.Trim(),
string.IsNullOrWhiteSpace(setting.Category) ? null : setting.Category.Trim(),
setting.ValueType,
string.IsNullOrWhiteSpace(setting.AllowedValues) ? null : setting.AllowedValues
));
if (result.IsSuccessStatusCode)
{
Snackbar.Add($"« {setting.Key} » mis à jour — notifié aux agents", Severity.Success);
await LoadSettings();
}
else
{
var body = await result.Content.ReadAsStringAsync();
Snackbar.Add($"Erreur : {result.StatusCode} — {body}", Severity.Error);
}
}
catch {
Snackbar.Add(UiErrors.OperationFailed(), Severity.Error);
}
}
private async Task SaveBoolInline(AppSettingItem setting, bool value)
=> await SaveInline(setting, value.ToString().ToLowerInvariant());
// ─── Delete ───────────────────────────────────────────────────────
private void ConfirmDelete(AppSettingItem setting)
{
_deleteTarget = setting;
_deleteError = "";
_showDeleteConfirm = true;
}
private async Task DeleteSetting()
{
if (_deleteTarget is null) return;
_saving = true;
_deleteError = "";
try
{
var result = await Api.DeleteSettingAsync(_deleteTarget!.Key);
if (!result.IsSuccessStatusCode)
{
var body = await result.Content.ReadAsStringAsync();
_deleteError = $"Erreur : {result.StatusCode} — {body}";
return;
}
_showDeleteConfirm = false;
Snackbar.Add("Paramètre supprimé — rechargement config envoyé aux agents", Severity.Success);
_deleteTarget = null;
await LoadSettings();
}
catch { _deleteError = UiErrors.OperationFailed(); }
finally { _saving = false; }
}
// ─── Reload ───────────────────────────────────────────────────────
private bool _reloading;
private async Task ReloadAllConfig()
{
_saving = true;
_reloading = true;
try
{
var result = await Api.ReloadAllConfigAsync();
if (result.IsSuccessStatusCode)
Snackbar.Add("Configuration rechargée sur tous les agents en temps réel", Severity.Success);
else
Snackbar.Add($"Erreur lors du rechargement : {result.StatusCode}", Severity.Error);
await Api.ReloadAllConfigAsync();
Snackbar.Add("Configuration rechargée — les agents seront notifiés", Severity.Success);
}
catch {
Snackbar.Add(UiErrors.OperationFailed(), Severity.Error);
catch (Exception ex)
{
Snackbar.Add($"Échec du rechargement : {ex.Message}", Severity.Error);
}
finally
{
_reloading = false;
}
finally { _saving = false; }
}
}
@@ -0,0 +1,126 @@
@namespace Heimdall.Web.Components.Settings
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
<MudPaper Elevation="1" Class="pa-4 mb-4" Style="border-radius: var(--hmd-radius-lg);">
<div class="d-flex align-center mb-3">
<MudText Typo="Typo.h6" Class="flex-grow-1">
<i class="fas fa-microchip mr-2"></i> Défauts agents
</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined" Color="Color.Primary">Globaux</MudChip>
</div>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">
Valeurs par défaut appliquées à tous les agents. Chaque agent peut les surcharger individuellement.
</MudText>
<MudText Typo="Typo.subtitle2" Class="mb-2">
<i class="fas fa-list mr-1" style="color: var(--mud-palette-primary);"></i> Logs
</MudText>
<MudGrid>
<MudItem xs="12" md="6">
<MudSelect T="string" Label="Niveau de log global" Variant="Variant.Outlined"
Value="@(GetValue("log.level") ?? "info")"
ValueChanged="OnLogLevelChanged" Immediate="true"
HelperText="Appliqué à chaud aux agents (règle de niveau partagée).">
<MudSelectItem Value="@("trace")">Trace</MudSelectItem>
<MudSelectItem Value="@("debug")">Debug</MudSelectItem>
<MudSelectItem Value="@("info")">Info</MudSelectItem>
<MudSelectItem Value="@("warn")">Warn</MudSelectItem>
<MudSelectItem Value="@("error")">Error</MudSelectItem>
</MudSelect>
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Rétention des logs agents (jours)" Variant="Variant.Outlined"
Type="InputType.Number"
Value="@GetValue("log.retentionDays")"
ValueChanged="OnRetentionChanged"
HelperText="Durée de conservation des logs remontés par les agents." />
</MudItem>
</MudGrid>
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">
<i class="fas fa-heartbeat mr-1" style="color: var(--mud-palette-primary);"></i> Heartbeat
</MudText>
<MudGrid>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Intervalle de heartbeat (secondes)" Variant="Variant.Outlined"
Type="InputType.Number"
Value="@GetValue("heartbeat.interval.seconds")"
ValueChanged="OnHeartbeatChanged"
HelperText="Fréquence de la remontée d'état des agents vers le central." />
</MudItem>
</MudGrid>
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">
<i class="fas fa-bug mr-1" style="color: var(--mud-palette-primary);"></i> Diagnostic
</MudText>
<MudGrid>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="DSN Sentry / GlitchTip" Variant="Variant.Outlined"
Type="InputType.Password"
Value="@SecretValue("sentry.dsn")"
ValueChanged="OnSentryDsnChanged"
Placeholder="•••••••• (déjà configuré)"
HelperText="Endpoint de remontée d'erreurs. Nécessite un redémarrage pour être pris en compte." />
</MudItem>
</MudGrid>
</MudPaper>
@code {
private List<AppSettingItem> _settings = [];
protected override async Task OnInitializedAsync()
{
try
{
_settings = await Api.GetSettingsAsync();
}
catch
{
_settings = [];
}
}
private string? GetValue(string key)
=> _settings.FirstOrDefault(s => s.Key == key)?.Value;
private string SecretValue(string key)
{
var v = GetValue(key);
return v is null or "" or "***REDACTED***" ? string.Empty : v;
}
private Task OnLogLevelChanged(string v) => SaveValueAsync("log.level", v);
private Task OnRetentionChanged(string v) => SaveValueAsync("log.retentionDays", v);
private Task OnHeartbeatChanged(string v) => SaveValueAsync("heartbeat.interval.seconds", v);
private Task OnSentryDsnChanged(string v) => SaveValueAsync("sentry.dsn", v);
private async Task SaveValueAsync(string key, string? value)
{
value ??= string.Empty;
var existing = _settings.FirstOrDefault(s => s.Key == key);
try
{
if (existing is null)
{
await Api.CreateSettingAsync(new CreateAppSettingRequest(
Key: key, Value: value,
Category: "agent",
Description: key, ValueType: "string", AllowedValues: null, AgentScoped: true));
}
else
{
await Api.UpdateSettingAsync(key, new UpdateAppSettingRequest(
Value: value, Description: existing.Description ?? key,
Category: "agent", ValueType: "string", AllowedValues: null, AgentScoped: null));
}
_settings = await Api.GetSettingsAsync();
Snackbar.Add($"Paramètre {key} mis à jour", Severity.Success);
}
catch (Exception ex)
{
Snackbar.Add($"Échec de la mise à jour : {ex.Message}", Severity.Error);
}
}
}
@@ -0,0 +1,90 @@
@namespace Heimdall.Web.Components.Settings
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
<MudPaper Elevation="1" Class="pa-4 mb-4" Style="border-radius: var(--hmd-radius-lg);">
<div class="d-flex align-center mb-3">
<MudText Typo="Typo.h6" Class="flex-grow-1">
<i class="fas fa-brain mr-2"></i> Intelligence artificielle
</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined" Color="Color.Primary">Détection</MudChip>
</div>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">
Moteurs d'analyse utilisés par les agents pour la détection d'objets et de personnes.
</MudText>
<MudGrid>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="URL CodeProject.AI" Variant="Variant.Outlined"
Value="@GetValue("ai.cpaiUrl")"
ValueChanged="OnCpaiUrlChanged"
HelperText="Endpoint CodeProject.AI (ex : http://cpai:32168)." />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="URL Ollama" Variant="Variant.Outlined"
Value="@GetValue("ai.ollamaUrl")"
ValueChanged="OnOllamaUrlChanged"
HelperText="Endpoint Ollama pour l'inférence locale (ex : http://ollama:11434)." />
</MudItem>
<MudItem xs="12">
<MudSwitch T="bool"
Value="@(GetValue("ai.detection.enabled")?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)"
ValueChanged="OnDetectionEnabledChanged"
Color="Color.Primary"
Label="Détection IA activée"
HelperText="Défaut global appliqué aux agents. Une modification nécessite le rechargement de la configuration des agents." />
</MudItem>
</MudGrid>
</MudPaper>
@code {
private List<AppSettingItem> _settings = [];
protected override async Task OnInitializedAsync()
{
try
{
_settings = await Api.GetSettingsAsync();
}
catch
{
_settings = [];
}
}
private string? GetValue(string key)
=> _settings.FirstOrDefault(s => s.Key == key)?.Value;
private Task OnCpaiUrlChanged(string v) => SaveValueAsync("ai.cpaiUrl", v);
private Task OnOllamaUrlChanged(string v) => SaveValueAsync("ai.ollamaUrl", v);
private Task OnDetectionEnabledChanged(bool v) => SaveValueAsync("ai.detection.enabled", v ? "true" : "false");
private async Task SaveValueAsync(string key, string? value)
{
value ??= string.Empty;
var existing = _settings.FirstOrDefault(s => s.Key == key);
try
{
if (existing is null)
{
await Api.CreateSettingAsync(new CreateAppSettingRequest(
Key: key, Value: value,
Category: "ai",
Description: key, ValueType: "string", AllowedValues: null, AgentScoped: true));
}
else
{
await Api.UpdateSettingAsync(key, new UpdateAppSettingRequest(
Value: value, Description: existing.Description ?? key,
Category: "ai", ValueType: "string", AllowedValues: null, AgentScoped: null));
}
_settings = await Api.GetSettingsAsync();
Snackbar.Add($"Paramètre {key} mis à jour", Severity.Success);
}
catch (Exception ex)
{
Snackbar.Add($"Échec de la mise à jour : {ex.Message}", Severity.Error);
}
}
}
@@ -0,0 +1,151 @@
@namespace Heimdall.Web.Components.Settings
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
<MudPaper Elevation="1" Class="pa-4 mb-4" Style="border-radius: var(--hmd-radius-lg);">
<div class="d-flex align-center mb-3">
<MudText Typo="Typo.h6" Class="flex-grow-1">
<i class="fas fa-bell mr-2"></i> Notifications
</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined" Color="Color.Primary">ntfy + Email</MudChip>
</div>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">
Canaux de notification utilisés pour les alertes de détection, les digests et les événements système.
</MudText>
<MudText Typo="Typo.subtitle2" Class="mb-2">
<i class="fas fa-paper-plane mr-1" style="color: var(--mud-palette-primary);"></i> ntfy
</MudText>
<MudGrid>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Serveur ntfy" Variant="Variant.Outlined"
Value="@GetValue("ntfy.baseUrl")"
ValueChanged="OnBaseUrlChanged"
HelperText="URL de base du serveur ntfy (ex : https://ntfy.sh)." />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Token d'accès" Variant="Variant.Outlined"
Type="InputType.Password"
Value="@SecretValue("ntfy.token")"
ValueChanged="OnTokenChanged"
Placeholder="•••••••• (déjà configuré)"
HelperText="Token optionnel pour les serveurs ntfy authentifiés." />
</MudItem>
</MudGrid>
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">
<i class="fas fa-envelope mr-1" style="color: var(--mud-palette-primary);"></i> Email SMTP
</MudText>
<MudGrid>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Adresse expéditrice" Variant="Variant.Outlined"
Value="@GetValue("email.fromAddress")"
ValueChanged="OnFromAddressChanged"
HelperText="Adresse « De » des emails envoyés." />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Nom expéditeur" Variant="Variant.Outlined"
Value="@GetValue("email.fromName")"
ValueChanged="OnFromNameChanged" />
</MudItem>
<MudItem xs="12" md="4">
<MudTextField T="string" Label="Serveur SMTP" Variant="Variant.Outlined"
Value="@GetValue("email.smtpHost")"
ValueChanged="OnSmtpHostChanged"
HelperText="Ex : smtp.gmail.com" />
</MudItem>
<MudItem xs="6" md="2">
<MudTextField T="string" Label="Port SMTP" Variant="Variant.Outlined"
Type="InputType.Number"
Value="@GetValue("email.smtpPort")"
ValueChanged="OnSmtpPortChanged" />
</MudItem>
<MudItem xs="12" md="3">
<MudTextField T="string" Label="Utilisateur SMTP" Variant="Variant.Outlined"
Value="@GetValue("email.username")"
ValueChanged="OnUsernameChanged" />
</MudItem>
<MudItem xs="12" md="3">
<MudTextField T="string" Label="Mot de passe SMTP" Variant="Variant.Outlined"
Type="InputType.Password"
Value="@SecretValue("email.password")"
ValueChanged="OnPasswordChanged"
Placeholder="•••••••• (déjà configuré)" />
</MudItem>
<MudItem xs="12">
<MudSwitch T="bool"
Value="@(GetValue("email.useSsl")?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)"
ValueChanged="OnUseSslChanged"
Color="Color.Primary"
Label="Utiliser SSL/TLS"
HelperText="Active le chiffrement TLS lors de la connexion SMTP." />
</MudItem>
</MudGrid>
</MudPaper>
@code {
private List<AppSettingItem> _settings = [];
protected override async Task OnInitializedAsync()
{
try
{
_settings = await Api.GetSettingsAsync();
}
catch
{
// API indisponible (ex : test) — on reste sur les défauts.
_settings = [];
}
}
private string? GetValue(string key)
=> _settings.FirstOrDefault(s => s.Key == key)?.Value;
// Les secrets sont redactés par l'API (***REDACTED***) : afficher vide avec
// un placeholder pour ne pas laisser croire que la valeur est vide.
private string SecretValue(string key)
{
var v = GetValue(key);
return v is null or "" or "***REDACTED***" ? string.Empty : v;
}
private Task OnBaseUrlChanged(string v) => SaveValueAsync("ntfy.baseUrl", v);
private Task OnTokenChanged(string v) => SaveValueAsync("ntfy.token", v);
private Task OnFromAddressChanged(string v) => SaveValueAsync("email.fromAddress", v);
private Task OnFromNameChanged(string v) => SaveValueAsync("email.fromName", v);
private Task OnSmtpHostChanged(string v) => SaveValueAsync("email.smtpHost", v);
private Task OnSmtpPortChanged(string v) => SaveValueAsync("email.smtpPort", v);
private Task OnUsernameChanged(string v) => SaveValueAsync("email.username", v);
private Task OnPasswordChanged(string v) => SaveValueAsync("email.password", v);
private Task OnUseSslChanged(bool v) => SaveValueAsync("email.useSsl", v ? "true" : "false");
private async Task SaveValueAsync(string key, string? value)
{
value ??= string.Empty;
var existing = _settings.FirstOrDefault(s => s.Key == key);
try
{
if (existing is null)
{
await Api.CreateSettingAsync(new CreateAppSettingRequest(
Key: key, Value: value,
Category: "integrations",
Description: key, ValueType: "string", AllowedValues: null, AgentScoped: true));
}
else
{
await Api.UpdateSettingAsync(key, new UpdateAppSettingRequest(
Value: value, Description: existing.Description ?? key,
Category: "integrations", ValueType: "string", AllowedValues: null, AgentScoped: null));
}
_settings = await Api.GetSettingsAsync();
Snackbar.Add($"Paramètre {key} mis à jour", Severity.Success);
}
catch (Exception ex)
{
Snackbar.Add($"Échec de la mise à jour : {ex.Message}", Severity.Error);
}
}
}
+13 -1
View File
@@ -254,13 +254,20 @@ public partial class Program {
["email.useSsl"] = Environment.GetEnvironmentVariable("EMAIL__USE_SSL") ?? "true",
["ai.cpaiUrl"] = Environment.GetEnvironmentVariable("CPAI_URL"),
["ai.ollamaUrl"] = Environment.GetEnvironmentVariable("OLLAMA_URL"),
["ai.detection.enabled"] = Environment.GetEnvironmentVariable("AI__DETECTION__ENABLED") ?? "true",
["log.level"] = Environment.GetEnvironmentVariable("LOG__LEVEL") ?? "info",
["log.retentionDays"] = Environment.GetEnvironmentVariable("LOG__RETENTION_DAYS") ?? "7",
["heartbeat.interval.seconds"] = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS") ?? "30",
["sentry.dsn"] = Environment.GetEnvironmentVariable("SENTRY_DSN"),
};
foreach (var (key, value) in integrationDefaults)
{
if (await groupDb.AppSettings.AnyAsync(s => s.Key == key))
continue;
groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting(
key, value ?? string.Empty, "integrations",
key, value ?? string.Empty,
key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal)
? "integrations" : key.StartsWith("ai.", StringComparison.Ordinal) ? "ai" : "agent",
key switch
{
"ntfy.baseUrl" => "Serveur ntfy (URL de base)",
@@ -274,6 +281,11 @@ public partial class Program {
"email.useSsl" => "Utiliser SSL/TLS pour SMTP",
"ai.cpaiUrl" => "URL CodeProject.AI",
"ai.ollamaUrl" => "URL Ollama",
"ai.detection.enabled" => "Détection IA activée par défaut",
"log.level" => "Niveau de log global (agents + central)",
"log.retentionDays" => "Rétention des logs agents (jours)",
"heartbeat.interval.seconds" => "Intervalle de heartbeat des agents (secondes)",
"sentry.dsn" => "DSN Sentry/GlitchTip (diagnostic)",
_ => key
}));
}
@@ -9,164 +9,51 @@ namespace Heimdall.Web.Tests.Components.Pages;
public class SettingsPageTests : PageTestBase
{
private static readonly Guid SettingId = Guid.NewGuid();
private static AppSettingItem Setting(
string key = "detection.threshold",
string value = "0.8",
string category = "Detection",
string valueType = "number",
string? description = "Seuil de détection") =>
new(SettingId, key, value, description, category, valueType, null, DateTime.UtcNow.AddDays(-1));
[Fact]
public void SettingsPage_AfficheParametresParCategorie()
{
Handler.OnGet("api/settings", new List<AppSettingItem>
{
Setting(),
Setting("heartbeat.interval", "30", "Heartbeat", "number", "Intervalle heartbeat")
});
LoginAs();
var cut = RenderPage<SettingsPage>();
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("detection.threshold");
cut.Markup.ShouldContain("0.8");
cut.Markup.ShouldContain("heartbeat.interval");
cut.Markup.ShouldContain("Detection");
cut.Markup.ShouldContain("Heartbeat");
cut.Markup.ShouldContain("paramètre(s) affiché(s)");
});
}
[Fact]
public void SettingsPage_AucunParametre_AfficheMessage()
public void SettingsPage_AfficheLesSectionsVisuelles()
{
Handler.OnGet("api/settings", new List<AppSettingItem>());
LoginAs();
var cut = RenderPage<SettingsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucun paramètre configuré"));
}
[Fact]
public void SettingsPage_ErreurChargement_AfficheAlerte()
{
Handler.OnGet("api/settings", System.Net.HttpStatusCode.InternalServerError);
LoginAs();
var cut = RenderPage<SettingsPage>();
cut.WaitForAssertion(() =>
cut.Markup.ShouldContain("Erreur lors du chargement de la configuration."));
}
[Fact]
public async Task SettingsPage_CreerParametre_AfficheSucces()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting() });
Handler.On(HttpMethod.Post, "api/settings", System.Net.HttpStatusCode.OK);
LoginAs();
var cut = RenderPage<SettingsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("detection.threshold"));
cut.FindAll("button").Single(b => b.TextContent.Contains("Nouveau")).Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Clé *"));
// Dialog create : [0]=clé, [1]=valeur (Immediate=true → Input)
// Le champ recherche de la page décale les index globaux → cibler le dialog
var dialogInputs = cut.FindAll(".mud-dialog input");
dialogInputs[0].Input("recording.retention");
dialogInputs[1].Input("7");
// Find+Submit dans InvokeAsync (handler périmé sinon, flaky CI).
await cut.InvokeAsync(() => cut.Find("form").Submit());
cut.WaitForAssertion(() =>
{
var snackbar = Services.GetRequiredService<ISnackbar>();
snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "")
.ShouldContain(m => m.Contains("Paramètre créé", StringComparison.OrdinalIgnoreCase));
// Plus de CRUD clé/valeur : chaque domaine a sa section dédiée
cut.Markup.ShouldContain("Stockage");
cut.Markup.ShouldContain("Notifications");
cut.Markup.ShouldContain("Intelligence artificielle");
cut.Markup.ShouldContain("Défauts agents");
});
}
[Fact]
public void SettingsPage_CreerParametre_ChampsManquants_AfficheErreur()
public void SettingsPage_PasDeChampCleLibre()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting() });
Handler.OnGet("api/settings", new List<AppSettingItem>());
LoginAs();
var cut = RenderPage<SettingsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("detection.threshold"));
cut.FindAll("button").Single(b => b.TextContent.Contains("Nouveau")).Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Clé *"));
cut.Find("form").Submit();
cut.WaitForAssertion(() =>
cut.Markup.ShouldContain("Les champs Clé et Valeur sont requis"));
}
[Fact]
public void SettingsPage_ModifierParametre_AfficheSucces()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting("log.level", "info", "Logging", "string", "Niveau de log") });
Handler.On(HttpMethod.Put, "api/settings/", System.Net.HttpStatusCode.OK);
LoginAs();
var cut = RenderPage<SettingsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("log.level"));
// Édition inline : le champ texte de la carte sauvegarde directement (pas de dialog)
cut.FindAll(".settings-card .mud-input input")[0].Change("debug");
cut.WaitForAssertion(() =>
{
var snackbar = Services.GetRequiredService<ISnackbar>();
snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "")
.ShouldContain(m => m.Contains("mis à jour", StringComparison.OrdinalIgnoreCase));
});
}
[Fact]
public void SettingsPage_SupprimerParametre_ConfirmeEtSupprime()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting("log.level", "info", "Logging", "string") });
Handler.On(HttpMethod.Delete, "api/settings/", System.Net.HttpStatusCode.OK);
LoginAs();
var cut = RenderPage<SettingsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("log.level"));
// Icon-buttons : [0]=refresh (header), [1]=delete (carte)
cut.FindAll("button.mud-icon-button")[1].Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Confirmer la suppression"));
cut.FindAll("button").Single(b => b.TextContent.Trim() == "Supprimer").Click();
cut.WaitForAssertion(() =>
{
var snackbar = Services.GetRequiredService<ISnackbar>();
snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "")
.ShouldContain(m => m.Contains("Paramètre supprimé", StringComparison.OrdinalIgnoreCase));
// L'exigence produit : plus aucun champ « Clé » libre dans l'UI
cut.Markup.ShouldNotContain("Clé *");
cut.Markup.ShouldNotContain("Nouveau paramètre");
});
}
[Fact]
public void SettingsPage_RechargerConfig_AfficheSucces()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting() });
Handler.OnGet("api/settings", new List<AppSettingItem>());
Handler.On(HttpMethod.Post, "api/settings/reload", System.Net.HttpStatusCode.OK);
LoginAs();
var cut = RenderPage<SettingsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("detection.threshold"));
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Configuration"));
// Le refresh est le premier MudIconButton (header, avant la table)
// Le refresh est le seul MudIconButton de la page (header)
cut.FindAll("button.mud-icon-button")[0].Click();
cut.WaitForAssertion(() =>
@@ -176,4 +63,16 @@ public class SettingsPageTests : PageTestBase
.ShouldContain(m => m.Contains("Configuration rechargée", StringComparison.OrdinalIgnoreCase));
});
}
[Fact]
public void SettingsPage_ApiIndisponible_LaPageRendSansCrash()
{
Handler.OnGet("api/settings", System.Net.HttpStatusCode.InternalServerError);
LoginAs();
var cut = RenderPage<SettingsPage>();
// Les sections gèrent leur propre échec de chargement (défauts) — pas de crash global
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Stockage"));
}
}
@@ -0,0 +1,79 @@
using Bunit;
using Heimdall.Web.Components.Settings;
using Heimdall.Web.Services;
using Heimdall.Web.Tests.Components.Pages;
using Microsoft.Extensions.DependencyInjection;
using MudBlazor;
using Shouldly;
namespace Heimdall.Web.Tests.Components.Settings;
public class AgentDefaultsSectionTests : PageTestBase
{
private static AppSettingItem Setting(string key, string value) =>
new(Guid.NewGuid(), key, value, key, "agent", "string", null, DateTime.UtcNow.AddDays(-1));
[Fact]
public void AgentDefaults_AfficheChampsLogsHeartbeatEtDiagnostic()
{
Handler.OnGet("api/settings", new List<AppSettingItem>
{
Setting("log.level", "info"),
Setting("log.retentionDays", "7"),
Setting("heartbeat.interval.seconds", "30"),
Setting("sentry.dsn", "***REDACTED***"),
});
LoginAs();
var cut = Render<AgentDefaultsSection>();
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("Niveau de log global");
cut.Markup.ShouldContain("Rétention des logs agents");
cut.Markup.ShouldContain("Intervalle de heartbeat");
cut.Markup.ShouldContain("DSN Sentry / GlitchTip");
});
}
[Fact]
public void AgentDefaults_ModifieRetention_AppellePutAvecBonneCle()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting("log.retentionDays", "7") });
Handler.On(HttpMethod.Put, "api/settings/log.retentionDays", System.Net.HttpStatusCode.OK);
LoginAs();
var cut = Render<AgentDefaultsSection>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("7"));
// Inputs : [0]=select log.level (readonly), [1]=rétention
cut.FindAll("input")[1].Change("14");
cut.WaitForAssertion(() =>
{
Handler.Requests.ShouldContain(r =>
r.Method == HttpMethod.Put &&
r.RequestUri!.AbsolutePath.Contains("log.retentionDays", StringComparison.OrdinalIgnoreCase));
});
}
[Fact]
public void AgentDefaults_ModifieHeartbeat_AppellePutAvecBonneCle()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting("heartbeat.interval.seconds", "30") });
Handler.On(HttpMethod.Put, "api/settings/heartbeat.interval.seconds", System.Net.HttpStatusCode.OK);
LoginAs();
var cut = Render<AgentDefaultsSection>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("30"));
cut.FindAll("input")[2].Change("45");
cut.WaitForAssertion(() =>
{
Handler.Requests.ShouldContain(r =>
r.Method == HttpMethod.Put &&
r.RequestUri!.AbsolutePath.Contains("heartbeat.interval.seconds", StringComparison.OrdinalIgnoreCase));
});
}
}
@@ -0,0 +1,58 @@
using Bunit;
using Heimdall.Web.Components.Settings;
using Heimdall.Web.Services;
using Heimdall.Web.Tests.Components.Pages;
using Microsoft.Extensions.DependencyInjection;
using MudBlazor;
using Shouldly;
namespace Heimdall.Web.Tests.Components.Settings;
public class AiSettingsSectionTests : PageTestBase
{
private static AppSettingItem Setting(string key, string value) =>
new(Guid.NewGuid(), key, value, key, "ai", "string", null, DateTime.UtcNow.AddDays(-1));
[Fact]
public void AiSection_AfficheChampsIA()
{
Handler.OnGet("api/settings", new List<AppSettingItem>
{
Setting("ai.cpaiUrl", "http://cpai:32168"),
Setting("ai.ollamaUrl", "http://ollama:11434"),
Setting("ai.detection.enabled", "true"),
});
LoginAs();
var cut = Render<AiSettingsSection>();
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("URL CodeProject.AI");
cut.Markup.ShouldContain("URL Ollama");
cut.Markup.ShouldContain("http://cpai:32168");
cut.Markup.ShouldContain("http://ollama:11434");
cut.Markup.ShouldContain("Détection IA activée");
});
}
[Fact]
public void AiSection_ModifieCpaiUrl_AppellePutAvecBonneCle()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting("ai.cpaiUrl", "http://cpai:32168") });
Handler.On(HttpMethod.Put, "api/settings/ai.cpaiUrl", System.Net.HttpStatusCode.OK);
LoginAs();
var cut = Render<AiSettingsSection>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("http://cpai:32168"));
cut.FindAll("input")[0].Change("http://cpai:32169");
cut.WaitForAssertion(() =>
{
Handler.Requests.ShouldContain(r =>
r.Method == HttpMethod.Put &&
r.RequestUri!.AbsolutePath.Contains("ai.cpaiUrl", StringComparison.OrdinalIgnoreCase));
});
}
}
@@ -0,0 +1,85 @@
using Bunit;
using Heimdall.Web.Components.Settings;
using Heimdall.Web.Services;
using Heimdall.Web.Tests.Components.Pages;
using Microsoft.Extensions.DependencyInjection;
using MudBlazor;
using Shouldly;
namespace Heimdall.Web.Tests.Components.Settings;
public class NotificationSettingsSectionTests : PageTestBase
{
private static AppSettingItem Setting(string key, string value) =>
new(Guid.NewGuid(), key, value, key, "integrations", "string", null, DateTime.UtcNow.AddDays(-1));
[Fact]
public void NotificationSection_AfficheChampsNtfyEtEmail()
{
Handler.OnGet("api/settings", new List<AppSettingItem>
{
Setting("ntfy.baseUrl", "https://ntfy.sh"),
Setting("ntfy.token", "tok123"),
Setting("email.fromAddress", "alertes@heimdall.local"),
Setting("email.smtpHost", "smtp.gmail.com"),
Setting("email.useSsl", "true"),
});
LoginAs();
var cut = Render<NotificationSettingsSection>();
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("Serveur ntfy");
cut.Markup.ShouldContain("Token d'accès");
cut.Markup.ShouldContain("Adresse expéditrice");
cut.Markup.ShouldContain("Serveur SMTP");
cut.Markup.ShouldContain("https://ntfy.sh");
cut.Markup.ShouldContain("smtp.gmail.com");
cut.Markup.ShouldContain("Utiliser SSL/TLS");
});
}
[Fact]
public async Task NotificationSection_ModifieBaseUrl_AppellePutAvecBonneCle()
{
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting("ntfy.baseUrl", "https://ntfy.sh") });
Handler.On(HttpMethod.Put, "api/settings/ntfy.baseUrl", System.Net.HttpStatusCode.OK);
LoginAs();
var cut = Render<NotificationSettingsSection>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("https://ntfy.sh"));
// Inputs texte : [0]=ntfy.baseUrl (les 8 champs texte viennent avant le switch)
cut.FindAll("input")[0].Change("https://ntfy.tordais.cc");
cut.WaitForAssertion(() =>
{
Handler.Requests.ShouldContain(r =>
r.Method == HttpMethod.Put &&
r.RequestUri!.AbsolutePath.Contains("ntfy.baseUrl", StringComparison.OrdinalIgnoreCase));
});
}
[Fact]
public void NotificationSection_SecretRedacte_ChampVideAvecPlaceholder()
{
Handler.OnGet("api/settings", new List<AppSettingItem>
{
Setting("ntfy.baseUrl", "https://ntfy.sh"),
Setting("ntfy.token", "***REDACTED***"),
Setting("email.password", "***REDACTED***"),
});
LoginAs();
var cut = Render<NotificationSettingsSection>();
cut.WaitForAssertion(() =>
{
// Le champ token ne doit PAS exposer la valeur redactée
cut.FindAll("input")[1].GetAttribute("value").ShouldBe(string.Empty);
// Le champ mot de passe SMTP non plus (7e champ texte)
cut.FindAll("input")[7].GetAttribute("value").ShouldBe(string.Empty);
});
}
}