feat(settings): paramètres agent-scoped + configuration agent en cartes visuelles
- Flag AgentScoped sur AppSetting (entité + migration AddAgentScopedSetting + DTO + commandes Create/Update + validateurs + client Web) - Écran Configuration : toggle 'Exposé aux agents' à la création - AgentDetail : n'affiche que les globaux agent-scoped, par catégories en cartes visuelles avec badge Hérité (global) / Surchargé pour cet agent, édition inline → crée l'override, bouton restore → retour à la valeur globale. Tests bUnit (3) : héritage, surcharge, réinitialisation. - Tests validateur : aliases boolean/number/integer/dropdown
This commit is contained in:
1 parent
d697a94257
commit
0b55360ad2
12 files changed
+2201
-52
No files matched your search
@@ -13,7 +13,8 @@ public sealed record AppSettingDto(
|
||||
[property: JsonPropertyName("category")] string Category,
|
||||
[property: JsonPropertyName("valueType")] string ValueType,
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues,
|
||||
[property: JsonPropertyName("updatedAt")] DateTime UpdatedAt
|
||||
[property: JsonPropertyName("updatedAt")] DateTime UpdatedAt,
|
||||
[property: JsonPropertyName("agentScoped")] bool AgentScoped = true
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
@@ -36,7 +37,8 @@ public sealed record CreateAppSettingRequest(
|
||||
[property: JsonPropertyName("category")] string Category = "General",
|
||||
[property: JsonPropertyName("description")] string? Description = null,
|
||||
[property: JsonPropertyName("valueType")] string ValueType = "string",
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null,
|
||||
[property: JsonPropertyName("agentScoped")] bool AgentScoped = true
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
@@ -47,7 +49,8 @@ public sealed record UpdateAppSettingRequest(
|
||||
[property: JsonPropertyName("description")] string? Description = null,
|
||||
[property: JsonPropertyName("category")] string? Category = null,
|
||||
[property: JsonPropertyName("valueType")] string? ValueType = null,
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null,
|
||||
[property: JsonPropertyName("agentScoped")] bool? AgentScoped = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-3
@@ -12,7 +12,8 @@ public record CreateAppSettingCommand(
|
||||
string Category = "General",
|
||||
string? Description = null,
|
||||
string ValueType = "string",
|
||||
string? AllowedValues = null) : IRequest<ServiceResult<AppSettingDto>>;
|
||||
string? AllowedValues = null,
|
||||
bool AgentScoped = true) : IRequest<ServiceResult<AppSettingDto>>;
|
||||
|
||||
public class CreateAppSettingCommandHandler : IRequestHandler<CreateAppSettingCommand, ServiceResult<AppSettingDto>>
|
||||
{
|
||||
@@ -28,7 +29,7 @@ public class CreateAppSettingCommandHandler : IRequestHandler<CreateAppSettingCo
|
||||
if (exists)
|
||||
return ServiceResult<AppSettingDto>.Conflict($"Setting '{key}' already exists");
|
||||
|
||||
var setting = new AppSetting(key, request.Value, request.Category, request.Description);
|
||||
var setting = new AppSetting(key, request.Value, request.Category, request.Description, request.AgentScoped);
|
||||
setting.UpdateMetadata(null, null, request.ValueType, request.AllowedValues);
|
||||
|
||||
_db.AppSettings.Add(setting);
|
||||
@@ -38,5 +39,5 @@ public class CreateAppSettingCommandHandler : IRequestHandler<CreateAppSettingCo
|
||||
}
|
||||
|
||||
private static AppSettingDto Map(AppSetting s) => new(
|
||||
s.Id, s.Key, s.Value, s.Description, s.Category, s.ValueType, s.AllowedValues, s.UpdatedAt);
|
||||
s.Id, s.Key, s.Value, s.Description, s.Category, s.ValueType, s.AllowedValues, s.UpdatedAt, s.AgentScoped);
|
||||
}
|
||||
+4
-3
@@ -12,7 +12,8 @@ public record UpdateAppSettingCommand(
|
||||
string? Description = null,
|
||||
string? Category = null,
|
||||
string? ValueType = null,
|
||||
string? AllowedValues = null) : IRequest<ServiceResult<AppSettingDto>>;
|
||||
string? AllowedValues = null,
|
||||
bool? AgentScoped = null) : IRequest<ServiceResult<AppSettingDto>>;
|
||||
|
||||
public class UpdateAppSettingCommandHandler : IRequestHandler<UpdateAppSettingCommand, ServiceResult<AppSettingDto>>
|
||||
{
|
||||
@@ -27,12 +28,12 @@ public class UpdateAppSettingCommandHandler : IRequestHandler<UpdateAppSettingCo
|
||||
return ServiceResult<AppSettingDto>.NotFound($"Setting '{request.Key}' not found");
|
||||
|
||||
setting.UpdateValue(request.Value);
|
||||
setting.UpdateMetadata(request.Description, request.Category, request.ValueType, request.AllowedValues);
|
||||
setting.UpdateMetadata(request.Description, request.Category, request.ValueType, request.AllowedValues, request.AgentScoped);
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<AppSettingDto>.Success(Map(setting));
|
||||
}
|
||||
|
||||
private static AppSettingDto Map(AppSetting s) => new(
|
||||
s.Id, s.Key, s.Value, s.Description, s.Category, s.ValueType, s.AllowedValues, s.UpdatedAt);
|
||||
s.Id, s.Key, s.Value, s.Description, s.Category, s.ValueType, s.AllowedValues, s.UpdatedAt, s.AgentScoped);
|
||||
}
|
||||
@@ -26,18 +26,26 @@ public class AppSetting
|
||||
/// <summary>For select types, comma-separated allowed values.</summary>
|
||||
public string? AllowedValues { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// True when this setting is relevant for agents (exposed on the agent
|
||||
/// detail page, can be overridden per-agent). Global-only settings
|
||||
/// (server, UI) are hidden from agent views.
|
||||
/// </summary>
|
||||
public bool AgentScoped { get; private set; }
|
||||
|
||||
public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
|
||||
public DateTime UpdatedAt { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
private AppSetting() { } // EF Core
|
||||
|
||||
public AppSetting(string key, string value, string category = "General", string? description = null)
|
||||
public AppSetting(string key, string value, string category = "General", string? description = null, bool agentScoped = true)
|
||||
{
|
||||
Key = !string.IsNullOrWhiteSpace(key) ? key.Trim().ToLowerInvariant()
|
||||
: throw new ArgumentException("Key is required", nameof(key));
|
||||
Value = value ?? string.Empty;
|
||||
Category = category;
|
||||
Description = description;
|
||||
AgentScoped = agentScoped;
|
||||
}
|
||||
|
||||
public void UpdateValue(string value)
|
||||
@@ -46,12 +54,13 @@ public class AppSetting
|
||||
UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public void UpdateMetadata(string? description, string? category, string? valueType, string? allowedValues)
|
||||
public void UpdateMetadata(string? description, string? category, string? valueType, string? allowedValues, bool? agentScoped = null)
|
||||
{
|
||||
if (description is not null) Description = description;
|
||||
if (category is not null) Category = category;
|
||||
if (valueType is not null) ValueType = valueType;
|
||||
if (allowedValues is not null) AllowedValues = allowedValues;
|
||||
if (agentScoped is not null) AgentScoped = agentScoped.Value;
|
||||
UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
+1776
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddAgentScopedSetting : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "AgentScoped",
|
||||
table: "app_settings",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "AgentScoped",
|
||||
table: "app_settings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -245,6 +245,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("AgentScoped")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("AllowedValues")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)")
|
||||
|
||||
@@ -99,11 +99,11 @@ else
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
@* ─── Agent Settings Overrides ─── *@
|
||||
<SectionCard Title="Configuration spécifique"
|
||||
@* ─── Agent Settings (globals hérités + overrides) ─── *@
|
||||
<SectionCard Title="Configuration"
|
||||
Icon="@Icons.Material.Filled.Tune"
|
||||
Elevation="2"
|
||||
HelpText="Ces réglages prennent le pas sur la configuration globale pour cet agent uniquement. Envoyés en temps réel via SignalR.">
|
||||
HelpText="Paramètres globaux hérités par cet agent, modifiables pour ce site uniquement. Envoyés en temps réel via SignalR.">
|
||||
|
||||
@if (_settingsLoading)
|
||||
{
|
||||
@@ -116,48 +116,116 @@ else
|
||||
<MudButton OnClick="@LoadSettingsAsync" Size="Size.Small" Variant="Variant.Text" Class="ml-2">Réessayer</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else if (_settings.Count == 0)
|
||||
else if (_globalSettings.Count == 0 && _settings.Count == 0)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mb-4">
|
||||
Aucune configuration spécifique pour cet agent.
|
||||
Ajoutez un réglage pour surcharger la configuration globale.
|
||||
Aucun paramètre global exposé aux agents pour le moment.
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_settings" Hover="true" Dense="true" Class="mb-4">
|
||||
<ColGroup>
|
||||
<col style="width: 40%;" />
|
||||
<col style="width: 40%;" />
|
||||
<col style="width: 20%;" />
|
||||
</ColGroup>
|
||||
<HeaderContent>
|
||||
<MudTh>Clé</MudTh>
|
||||
<MudTh>Valeur</MudTh>
|
||||
<MudTh>Actions</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd><MudText Typo="Typo.body2">@context.Key</MudText></MudTd>
|
||||
<MudTd><MudText Typo="Typo.body2">@context.Value</MudText></MudTd>
|
||||
<MudTd>
|
||||
<MudTooltip Text="Modifier ce réglage (envoyé en temps réel via SignalR)">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small"
|
||||
OnClick="@(() => OpenEditDialog(context))" />
|
||||
</MudTooltip>
|
||||
<MudTooltip Text="Supprimer ce réglage">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Error"
|
||||
OnClick="@(() => ConfirmRemoveSetting(context))" />
|
||||
</MudTooltip>
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
@foreach (var category in _globalSettings.GroupBy(s => s.Category).OrderBy(g => g.Key))
|
||||
{
|
||||
<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="@GetAgentCategoryIcon(category.Key)" Size="Size.Small" Class="mr-1" />
|
||||
@category.Key
|
||||
</MudText>
|
||||
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined">@category.Count()</MudChip>
|
||||
</div>
|
||||
|
||||
<MudGrid>
|
||||
@foreach (var setting in category)
|
||||
{
|
||||
var overridden = IsOverridden(setting.Key);
|
||||
var effectiveValue = EffectiveValue(setting.Key, setting.Value);
|
||||
<MudItem xs="12" sm="6" lg="4" @key="setting.Key">
|
||||
<MudPaper Elevation="1" Class="pa-4 settings-card" Style="border-radius: 12px; height: 100%;">
|
||||
<div class="d-flex align-center mb-2">
|
||||
<MudIcon Icon="@GetAgentTypeIcon(setting.ValueType)" Size="Size.Small"
|
||||
Color="@GetAgentTypeColor(setting.ValueType)" Class="mr-2" />
|
||||
<div class="flex-grow-1">
|
||||
<MudText Typo="Typo.body1" Class="font-weight-medium settings-label">
|
||||
@(setting.Description ?? HumanizeAgentKey(setting.Key))
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="settings-key">
|
||||
@setting.Key
|
||||
</MudText>
|
||||
</div>
|
||||
@if (overridden)
|
||||
{
|
||||
<MudTooltip Text="Réinitialiser à la valeur globale">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Restore" Size="Size.Small"
|
||||
Color="Color.Warning" OnClick="@(() => ExecuteRemoveSettingByKey(setting.Key))" />
|
||||
</MudTooltip>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (overridden)
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small" Color="Color.Warning" Class="mb-2">
|
||||
Surchargé pour cet agent
|
||||
</MudChip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small" Color="Color.Info" Class="mb-2">
|
||||
Hérité (global)
|
||||
</MudChip>
|
||||
}
|
||||
|
||||
@switch (setting.ValueType.ToLowerInvariant())
|
||||
{
|
||||
case "boolean":
|
||||
case "bool":
|
||||
<div class="d-flex align-center">
|
||||
<MudSwitch T="bool"
|
||||
Value="@(effectiveValue?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)"
|
||||
ValueChanged="@(v => SaveGlobalOverrideBoolAsync(setting, v))"
|
||||
Color="Color.Primary" Class="flex-grow-1" />
|
||||
<MudText Typo="Typo.body2" Color="Color.Primary" Class="font-weight-medium">
|
||||
@(effectiveValue?.Equals("true", StringComparison.OrdinalIgnoreCase) == true ? "Activé" : "Désactivé")
|
||||
</MudText>
|
||||
</div>
|
||||
break;
|
||||
case "number":
|
||||
case "int":
|
||||
case "integer":
|
||||
case "double":
|
||||
<MudTextField T="string" Value="@effectiveValue" Variant="Variant.Outlined" Dense="true"
|
||||
ValueChanged="@(v => SaveGlobalOverrideAsync(setting, v))"
|
||||
Label="Valeur" Type="InputType.Number" />
|
||||
break;
|
||||
case "select":
|
||||
case "dropdown":
|
||||
<MudSelect T="string" Value="@effectiveValue" Variant="Variant.Outlined" Dense="true"
|
||||
ValueChanged="@(v => SaveGlobalOverrideAsync(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="@effectiveValue" Variant="Variant.Outlined" Dense="true"
|
||||
ValueChanged="@(v => SaveGlobalOverrideAsync(setting, v))" Label="Valeur" />
|
||||
break;
|
||||
}
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
}
|
||||
</MudGrid>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary"
|
||||
OnClick="@OpenAddDialog" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" />
|
||||
Ajouter un réglage
|
||||
</MudButton>
|
||||
@if (_settings.Count > 0)
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning" Class="mt-2">
|
||||
@_settings.Count réglage(s) surchargé(s) pour cet agent — la valeur globale est ignorée pour ces clés.
|
||||
</MudAlert>
|
||||
}
|
||||
</SectionCard>
|
||||
|
||||
<div class="d-flex gap-4 mt-4">
|
||||
@@ -237,6 +305,7 @@ else
|
||||
|
||||
// Settings
|
||||
private List<AgentSettingItem> _settings = [];
|
||||
private List<AppSettingItem> _globalSettings = [];
|
||||
private bool _settingsLoading;
|
||||
private bool _settingsError;
|
||||
private bool _saving;
|
||||
@@ -272,16 +341,54 @@ else
|
||||
_settingsLoading = true;
|
||||
try
|
||||
{
|
||||
_globalSettings = (await Api.GetSettingsAsync())
|
||||
.Where(s => s.AgentScoped)
|
||||
.OrderBy(s => s.Category)
|
||||
.ThenBy(s => s.Key)
|
||||
.ToList();
|
||||
_settings = await Api.GetAgentSettingsAsync(Id);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_settingsError = true;
|
||||
_settings = [];
|
||||
_globalSettings = [];
|
||||
}
|
||||
finally { _settingsLoading = false; }
|
||||
}
|
||||
|
||||
/// <summary>Returns the effective value for a global setting key (override wins).</summary>
|
||||
private string EffectiveValue(string key, string globalValue)
|
||||
=> _settings.FirstOrDefault(s => s.Key == key)?.Value ?? globalValue;
|
||||
|
||||
/// <summary>True when the agent overrides this global key.</summary>
|
||||
private bool IsOverridden(string key)
|
||||
=> _settings.Any(s => s.Key == key);
|
||||
|
||||
private async Task SaveGlobalOverrideAsync(AppSettingItem setting, string value)
|
||||
{
|
||||
_saving = true;
|
||||
try
|
||||
{
|
||||
var response = await Api.SetAgentSettingAsync(Id, new SetAgentSettingRequest(setting.Key, value));
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
Snackbar.Add($"« {setting.Key} » surchargé pour cet agent — envoyé en temps réel", Severity.Success);
|
||||
await LoadSettingsAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
var error = await response.Content.ReadAsStringAsync();
|
||||
Snackbar.Add($"Erreur : {error}", Severity.Error);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
|
||||
private async Task SaveGlobalOverrideBoolAsync(AppSettingItem setting, bool value)
|
||||
=> await SaveGlobalOverrideAsync(setting, value.ToString().ToLowerInvariant());
|
||||
|
||||
private void OpenAddDialog()
|
||||
{
|
||||
_editingSetting = null;
|
||||
@@ -351,6 +458,26 @@ else
|
||||
finally { _deleting = false; }
|
||||
}
|
||||
|
||||
private async Task ExecuteRemoveSettingByKey(string key)
|
||||
{
|
||||
_deleting = true;
|
||||
try
|
||||
{
|
||||
var response = await Api.RemoveAgentSettingAsync(Id, key);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
Snackbar.Add($"« {key} » réinitialisé à la valeur globale — agent notifié", Severity.Success);
|
||||
await LoadSettingsAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Erreur lors de la réinitialisation", Severity.Error);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
finally { _deleting = false; }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// No unmanaged resources to dispose
|
||||
@@ -378,4 +505,42 @@ else
|
||||
> 0 => $"{mb} Mo",
|
||||
_ => "-"
|
||||
};
|
||||
|
||||
// ─── Settings visual helpers ─────────────────────────────────────
|
||||
|
||||
private static Color GetAgentTypeColor(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 GetAgentTypeIcon(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 GetAgentCategoryIcon(string category) => category.ToLowerInvariant() switch
|
||||
{
|
||||
"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,
|
||||
"heartbeat" => Icons.Material.Filled.MonitorHeart,
|
||||
_ => Icons.Material.Filled.Settings
|
||||
};
|
||||
|
||||
private static string HumanizeAgentKey(string key)
|
||||
{
|
||||
var parts = key.Split('.', '_', '-');
|
||||
return string.Join(' ', parts.Select(p => p.Length <= 2
|
||||
? p.ToUpperInvariant()
|
||||
: char.ToUpperInvariant(p[0]) + p[1..]));
|
||||
}
|
||||
}
|
||||
@@ -205,6 +205,10 @@ else
|
||||
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>
|
||||
@@ -371,6 +375,7 @@ else
|
||||
private string _createCategory = "General";
|
||||
private string _createValueType = "string";
|
||||
private string _createAllowedValues = "";
|
||||
private bool _createAgentScoped = true;
|
||||
private string _createError = "";
|
||||
|
||||
// Delete state
|
||||
@@ -503,7 +508,8 @@ else
|
||||
string.IsNullOrWhiteSpace(_createCategory) ? "General" : _createCategory.Trim(),
|
||||
string.IsNullOrWhiteSpace(_createDescription) ? null : _createDescription.Trim(),
|
||||
_createValueType,
|
||||
allowedValues
|
||||
allowedValues,
|
||||
_createAgentScoped
|
||||
));
|
||||
|
||||
if (!result.IsSuccessStatusCode)
|
||||
|
||||
@@ -548,7 +548,8 @@ public record AppSettingItem(
|
||||
[property: JsonPropertyName("category")] string Category,
|
||||
[property: JsonPropertyName("valueType")] string ValueType,
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues,
|
||||
[property: JsonPropertyName("updatedAt")] DateTime UpdatedAt
|
||||
[property: JsonPropertyName("updatedAt")] DateTime UpdatedAt,
|
||||
[property: JsonPropertyName("agentScoped")] bool AgentScoped = true
|
||||
);
|
||||
|
||||
public record CreateAppSettingRequest(
|
||||
@@ -557,7 +558,8 @@ public record CreateAppSettingRequest(
|
||||
[property: JsonPropertyName("category")] string Category = "General",
|
||||
[property: JsonPropertyName("description")] string? Description = null,
|
||||
[property: JsonPropertyName("valueType")] string ValueType = "string",
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null,
|
||||
[property: JsonPropertyName("agentScoped")] bool AgentScoped = true
|
||||
);
|
||||
|
||||
public record UpdateAppSettingRequest(
|
||||
@@ -565,7 +567,8 @@ public record UpdateAppSettingRequest(
|
||||
[property: JsonPropertyName("description")] string? Description = null,
|
||||
[property: JsonPropertyName("category")] string? Category = null,
|
||||
[property: JsonPropertyName("valueType")] string? ValueType = null,
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null,
|
||||
[property: JsonPropertyName("agentScoped")] bool? AgentScoped = null
|
||||
);
|
||||
|
||||
// ─── Agent Settings DTOs ───────────────────────────────────────────
|
||||
|
||||
@@ -86,4 +86,32 @@ public class CreateAppSettingValidatorTests
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("boolean")]
|
||||
[InlineData("number")]
|
||||
[InlineData("integer")]
|
||||
[InlineData("dropdown")]
|
||||
public void AliasValueTypes_PassesValidation(string valueType)
|
||||
{
|
||||
var request = new CreateAppSettingRequest(
|
||||
Key: "test.alias",
|
||||
Value: "value",
|
||||
Category: "General",
|
||||
ValueType: valueType);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AgentScoped_Default_IsTrue()
|
||||
{
|
||||
var request = new CreateAppSettingRequest(
|
||||
Key: "test.agentscoped",
|
||||
Value: "value",
|
||||
Category: "General");
|
||||
|
||||
request.AgentScoped.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
using Bunit;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.Web.Components.Pages;
|
||||
using Heimdall.Web.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MudBlazor;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Components.Pages;
|
||||
|
||||
public class AgentDetailTests : PageTestBase
|
||||
{
|
||||
private static readonly Guid AgentId = Guid.NewGuid();
|
||||
|
||||
private static AgentItem Agent() => new()
|
||||
{
|
||||
Id = AgentId,
|
||||
SiteId = Guid.NewGuid(),
|
||||
SiteName = "Site Principal",
|
||||
Name = "agent-01",
|
||||
Hostname = "agent-01",
|
||||
Version = "1.0.0",
|
||||
Status = "Online",
|
||||
LastHeartbeat = DateTime.UtcNow,
|
||||
PublicIp = "10.0.0.5",
|
||||
CreatedAt = DateTime.UtcNow.AddDays(-5)
|
||||
};
|
||||
|
||||
private static AppSettingItem Setting(string key, string value, string category, string valueType, bool agentScoped = true, string? description = null) => new(
|
||||
Guid.NewGuid(), key, value, description, category, valueType, null, DateTime.UtcNow, agentScoped);
|
||||
|
||||
private static AgentSettingItem Override(string key, string value) => new(
|
||||
Guid.NewGuid(), AgentId, key, value, DateTime.UtcNow);
|
||||
|
||||
[Fact]
|
||||
public void AgentDetail_AfficheGlobauxHerites_AvecBadge()
|
||||
{
|
||||
// Ordre important : les routes spécifiques /settings AVANT api/agents/{id}
|
||||
// (RoutedHandler matche par Contains)
|
||||
Handler.OnGet($"api/settings/agent/{AgentId}/overrides", new List<AgentSettingItem>());
|
||||
Handler.OnGet("api/settings", new List<AppSettingItem>
|
||||
{
|
||||
Setting("detection.threshold", "0.7", "Detection", "number", true, "Seuil de détection"),
|
||||
Setting("recording.enabled", "true", "Recording", "boolean", true, "Enregistrement activé"),
|
||||
Setting("server.internal.port", "8080", "Server", "number", false, "Port interne (non agent)")
|
||||
});
|
||||
Handler.OnGet($"api/agents/{AgentId}", Agent());
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<AgentDetail>(p => p.Add(x => x.Id, AgentId));
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("agent-01"));
|
||||
|
||||
// Les globaux agent-scoped sont affichés avec leurs libellés
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Seuil de détection");
|
||||
cut.Markup.ShouldContain("Enregistrement activé");
|
||||
cut.Markup.ShouldContain("Hérité (global)");
|
||||
});
|
||||
|
||||
// Le setting non agent-scoped n'apparaît pas
|
||||
cut.Markup.ShouldNotContain("server.internal.port");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AgentDetail_ModifierGlobal_CreeSurcharge()
|
||||
{
|
||||
Handler.OnGet($"api/settings/agent/{AgentId}/overrides", new List<AgentSettingItem>());
|
||||
Handler.On(HttpMethod.Put, $"api/settings/agent/{AgentId}/overrides", System.Net.HttpStatusCode.OK);
|
||||
Handler.OnGet("api/settings", new List<AppSettingItem>
|
||||
{
|
||||
Setting("detection.threshold", "0.7", "Detection", "number", true, "Seuil de détection")
|
||||
});
|
||||
Handler.OnGet($"api/agents/{AgentId}", Agent());
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<AgentDetail>(p => p.Add(x => x.Id, AgentId));
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Seuil de détection"));
|
||||
|
||||
// Modifier la valeur dans la carte → crée un override
|
||||
cut.FindAll(".settings-card .mud-input input")[0].Change("0.9");
|
||||
cut.WaitForAssertion(() =>
|
||||
Handler.Requests.Any(r => r.Method == HttpMethod.Put
|
||||
&& r.RequestUri!.AbsolutePath.Contains($"api/settings/agent/{AgentId}/overrides")).ShouldBeTrue());
|
||||
|
||||
var put = Handler.Requests.First(r => r.Method == HttpMethod.Put
|
||||
&& r.RequestUri!.AbsolutePath.Contains($"api/settings/agent/{AgentId}/overrides"));
|
||||
put.RequestUri!.AbsolutePath.ShouldContain(AgentId.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AgentDetail_SurchargeExistante_AfficheBadgeEtReinitialise()
|
||||
{
|
||||
Handler.OnGet($"api/settings/agent/{AgentId}/overrides", new List<AgentSettingItem>
|
||||
{
|
||||
Override("detection.threshold", "0.9")
|
||||
});
|
||||
Handler.On(HttpMethod.Delete, $"api/settings/agent/{AgentId}/overrides", System.Net.HttpStatusCode.OK);
|
||||
Handler.OnGet("api/settings", new List<AppSettingItem>
|
||||
{
|
||||
Setting("detection.threshold", "0.7", "Detection", "number", true, "Seuil de détection")
|
||||
});
|
||||
Handler.OnGet($"api/agents/{AgentId}", Agent());
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<AgentDetail>(p => p.Add(x => x.Id, AgentId));
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Seuil de détection"));
|
||||
|
||||
// La carte affiche la valeur surchargée et le badge
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Surchargé pour cet agent");
|
||||
cut.Markup.ShouldContain("0.9");
|
||||
});
|
||||
|
||||
// Le bouton Restore (réinitialiser) déclenche le DELETE
|
||||
cut.FindAll("button.mud-icon-button").First(b =>
|
||||
b.QuerySelector("svg") is not null).Click();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
Handler.Requests.Any(r => r.Method == HttpMethod.Delete
|
||||
&& r.RequestUri!.AbsolutePath.Contains($"api/settings/agent/{AgentId}/overrides")).ShouldBeTrue());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user