From 5b1255ad807f5a82353a6fa365755d6412f6128f Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 21:19:00 +0100 Subject: [PATCH] Fix camera access and related UI issues (#311) Co-authored-by: Arnaud Dartois --- skills/api-key-localization/SKILL.md | 25 + skills/camera-access-nullable-select/SKILL.md | 17 + skills/dashboard-welcome-punctuation/SKILL.md | 28 + skills/site-camera-credentials/SKILL.md | 32 + skills/site-create-permission/SKILL.md | 17 + .../SKILL.md | 16 + .../UserCameraAccessConfiguration.cs | 11 +- ...3912_AllowSiteWideCameraAccess.Designer.cs | 2906 +++++++++++++++++ ...0261108123912_AllowSiteWideCameraAccess.cs | 79 + .../Migrations/AppDbContextModelSnapshot.cs | 23 +- .../Components/Pages/CameraAccessPanel.razor | 8 +- .../Components/Pages/Dashboard.razor | 2 +- .../Components/Pages/SitesPage.razor | 20 +- .../Components/Pages/SnapshotsPage.razor | 31 +- .../Controllers/SitesController.cs | 42 + .../Localization/SharedResources.fr.resx | 16 +- .../Localization/SharedResources.resx | 16 +- tests/Heimdall.E2E.Tests/E2ETestBase.cs | 24 +- .../Pages/UserManagementTests.cs | 148 + .../Controllers/SitesControllerTests.cs | 56 + .../Components/Pages/AllAgentsPageTests.cs | 1 + .../Components/Pages/ApiKeysPageTests.cs | 90 + .../Components/Pages/CamerasPageTests.cs | 56 + .../Components/Pages/DashboardTests.cs | 26 + .../Components/Pages/SiteDetailTests.cs | 18 + .../Components/Pages/SitesPageTests.cs | 14 + .../Components/Pages/SnapshotsPageTests.cs | 23 + .../Services/HeimdallApiClientTests.cs | 26 + 28 files changed, 3731 insertions(+), 40 deletions(-) create mode 100644 skills/api-key-localization/SKILL.md create mode 100644 skills/camera-access-nullable-select/SKILL.md create mode 100644 skills/dashboard-welcome-punctuation/SKILL.md create mode 100644 skills/site-camera-credentials/SKILL.md create mode 100644 skills/site-create-permission/SKILL.md create mode 100644 skills/snapshot-gallery-responsive-filters/SKILL.md create mode 100644 src/Heimdall.Infrastructure/Migrations/20261108123912_AllowSiteWideCameraAccess.Designer.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261108123912_AllowSiteWideCameraAccess.cs create mode 100644 tests/Heimdall.Web.Tests/Components/Pages/ApiKeysPageTests.cs diff --git a/skills/api-key-localization/SKILL.md b/skills/api-key-localization/SKILL.md new file mode 100644 index 0000000..578378b --- /dev/null +++ b/skills/api-key-localization/SKILL.md @@ -0,0 +1,25 @@ +--- +name: api-key-localization +description: Maintain and verify French and English localization for Heimdall's API key administration page and dialogs. +--- + +# API key localization + +The API key administration UI is `src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor`. Its text comes from `AdminApiKeys_*` entries in `src/Heimdall.Web/Localization/SharedResources.*.resx` through `UiText`; the active culture is selected by `UiLanguageService`. + +## Updating strings + +1. Keep every `AdminApiKeys_*` key present in the neutral resource and localized resources. Use `SharedResources.en.resx` as the English wording reference and translate all visible create, one-time-secret, revoke, validation, helper, and empty-state copy in `SharedResources.fr.resx`. +2. Replace placeholder values that repeat a key suffix (such as `ExpiryHelp`) with actual English fallback copy in `SharedResources.resx` and an actual French translation in `SharedResources.fr.resx`. Check the related `AdminAllAgents_EmptyDescription` entry when auditing the French admin empty states. +3. Preserve formatting tokens such as `{0}` in interpolated resource values and preserve the API date format when translating optional date labels. +4. Add or update focused bUnit tests under `tests/Heimdall.Web.Tests/Components/Pages/`. Render the page with `PageTestBase`, serve an empty API key list via `api/api-keys`, and assert the French empty-state description and create-dialog labels with key-suffix placeholders absent. For other dialogs, exercise the corresponding UI action and assert the rendered localized text. + +## Acceptance + +Run the focused tests with: + +```sh +dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore --filter 'FullyQualifiedName~ApiKeysPageTests|FullyQualifiedName~AllAgentsPageTests' +``` + +The acceptance evidence should record the command and result. A test run blocked by shared-runner contention is not a pass; rerun it when the runner is available. This localization-only change does not need a disposable Compose acceptance recipe because it changes no runtime behavior or deployment configuration. diff --git a/skills/camera-access-nullable-select/SKILL.md b/skills/camera-access-nullable-select/SKILL.md new file mode 100644 index 0000000..3fe5fe6 --- /dev/null +++ b/skills/camera-access-nullable-select/SKILL.md @@ -0,0 +1,17 @@ +--- +name: camera-access-nullable-select +description: Keep nullable camera-access grant selectors type-consistent in the Heimdall Blazor UI and verify site-wide and camera-specific grants. +--- + +# Camera access nullable selectors + +The grant form in `src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor` stores the selected site and camera as `Guid?` because the form supports an unset selection. Keep each corresponding `MudSelect` and all of its `MudSelectItem` children explicitly typed as `Guid?`; cast non-nullable model IDs with `(Guid?)` in each item value. A plain `Guid` item can compile yet fail at runtime when MudBlazor dispatches the option click to its nullable parent. + +When editing this form, preserve the two grant modes: site-wide grants save a site ID and null camera ID, while camera-specific grants save both IDs. Validate both selection interactions and the serialized saved grants. + +## Acceptance workflow + +1. Run the focused Web tests with `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore` and build `src/Heimdall.Web/Heimdall.Web.csproj` using the SDK pinned in `global.json`. +2. For behavior changes, follow [the disposable Compose recipe](../compose-disposable-recipe/SKILL.md): build the changed source using unique local image tags and isolated credentials, project, ports, network, and volumes. +3. Bootstrap an isolated administrator, use a real browser/UI-capable test to select a site-wide option and a camera option, and verify the saved grants contain respectively a null and non-null camera ID with no `InvalidCastException`. +4. Tear down only that Compose project. Verify its containers, volumes, and networks are absent; remove and verify absence of only the recipe's exact locally built tags, preserving shared base images. diff --git a/skills/dashboard-welcome-punctuation/SKILL.md b/skills/dashboard-welcome-punctuation/SKILL.md new file mode 100644 index 0000000..4f59079 --- /dev/null +++ b/skills/dashboard-welcome-punctuation/SKILL.md @@ -0,0 +1,28 @@ +--- +name: dashboard-welcome-punctuation +description: Keep Heimdall's localized dashboard greeting punctuation consistent across its route aliases. +--- + +# Dashboard welcome punctuation + +`Dashboard.razor` serves both `/` and `/dashboard`. The `WelcomeUser` resource +owns the punctuation at the end of the localized greeting (French and English +currently both end in a comma); the Razor markup must add only a space before +the display name. + +## Change and acceptance workflow + +1. Inspect `Dashboard.razor` and the `WelcomeUser` values in + `SharedResources.fr.resx` and `SharedResources.en.resx` before changing the + greeting. Keep one punctuation owner instead of composing punctuation in + both places. +2. In `DashboardTests`, render the component with `UiLanguageService` set to + each supported language and assert the rendered greeting contains exactly + the expected localized punctuation and display name. +3. Since `/` and `/dashboard` are aliases on the same component, verify both + route templates remain declared on the component and exercise this same + rendering assertion for the shared output. +4. Run the focused web test project. For behavior changes, also run the + disposable Compose acceptance recipe from + `compose-disposable-recipe/SKILL.md`, using unique project resources and + removing only recipe-owned image tags during cleanup. diff --git a/skills/site-camera-credentials/SKILL.md b/skills/site-camera-credentials/SKILL.md new file mode 100644 index 0000000..bdf47e7 --- /dev/null +++ b/skills/site-camera-credentials/SKILL.md @@ -0,0 +1,32 @@ +--- +name: site-camera-credentials +description: Maintain the per-site camera credential API and its Site Detail and Cameras page flows. +--- + +# Site camera credentials + +The Web client calls `api/sites/{id}/credentials` from both `SiteDetail.razor` +and `CamerasPage.razor`. Keep the GET, POST, and DELETE endpoints in +`SitesController` aligned with those client paths. Apply the existing +`Site.Read` or `Site.Write` policy and the global site resource-access filter +to every credential route. + +Credential passwords are write-only. `SiteCredentialResponse` contains only +the credential ID, site ID, label, username, and timestamps; never return, +render, or log the stored password. Use the Application handlers and EF Core +through the existing application context for persistence. + +## Change and acceptance workflow + +1. Verify the client path and controller route agree for all three methods. +2. Test a site with no credentials and a site with a credential in both + `/sites/{id}` and `/sites/{id}/cameras`; distinguish a failed request from + a normal empty list. +3. Exercise add/list/delete with synthetic credentials. Assert the response + and list never contain the submitted password. +4. Verify unauthenticated requests are rejected and users without access to + the site receive a forbidden response. +5. Run focused Web and PostgreSQL integration tests, then follow + `compose-disposable-recipe` with an isolated Central/PostgreSQL project. + Record exact project resources and local image tags, and verify their + removal after teardown. diff --git a/skills/site-create-permission/SKILL.md b/skills/site-create-permission/SKILL.md new file mode 100644 index 0000000..9fe3109 --- /dev/null +++ b/skills/site-create-permission/SKILL.md @@ -0,0 +1,17 @@ +--- +name: site-create-permission +description: Keep the Sites page site-creation controls aligned with Heimdall's Site.Write permission. +--- + +# Site creation permission in the Sites page + +`AuthState` resolves role permissions into `Permissions`; check creation with `Auth.HasPermission("Site.Write")` in `SitesPage.razor`. Render both the create affordance and its overlay/dialog only when that permission exists, and route the button through a guarded open method so an event cannot set the dialog visible after access changes. + +The API remains the enforcement boundary. Do not remove or weaken its `Site.Write` authorization policy as part of this UI behavior. + +## Acceptance workflow + +1. Add a focused bUnit test using `PageTestBase.LoginAs("Viewer")`; assert the create button and dialog fields/actions are absent after page load. +2. Keep an authorized creation test using an authorized role; exercise opening the dialog and completing a successful create response. +3. Run the focused test with `dotnet test tests/Heimdall.Web.Tests --filter FullyQualifiedName~SitesPageTests`. +4. For behavior acceptance, run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md`, record its isolated project/tag and cleanup evidence on the Gitea issue. UI component tests do not prove API authorization or field deployment behavior. diff --git a/skills/snapshot-gallery-responsive-filters/SKILL.md b/skills/snapshot-gallery-responsive-filters/SKILL.md new file mode 100644 index 0000000..c55f325 --- /dev/null +++ b/skills/snapshot-gallery-responsive-filters/SKILL.md @@ -0,0 +1,16 @@ +--- +name: snapshot-gallery-responsive-filters +description: Keep the Heimdall snapshot gallery's search, event type, and load controls usable on phone widths while preserving the desktop row. +--- + +# Snapshot gallery responsive filters + +The snapshot filter controls are owned by `src/Heimdall.Web/Components/Pages/SnapshotsPage.razor`. Keep them together in `.snapshot-filters`: its desktop grid uses three columns for search, event type, and load, and its 600 px breakpoint stacks those controls. Use `minmax(0, ...)` tracks and controls without fixed minimum widths so the page can shrink to a 320 px viewport. + +## Acceptance workflow + +1. Read Gitea issue [#285](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues/285) and retain its criteria for 390 px, narrower phone widths, and desktop. +2. Update the `SnapshotsPageTests` bUnit coverage to check that search, event type, and load remain inside the filter layout and that the desktop and phone grid rules remain present without the old 300 px/180 px minimums. +3. Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SnapshotsPageTests`. +4. For behavior changes, follow `skills/compose-disposable-recipe/SKILL.md` and record the disposable acceptance result, cleanup verification, and any browser viewport evidence on issue #285. A bUnit structure/CSS assertion does not by itself measure rendered document width; use a browser at 390 px and 320 px when available. +5. Keep issue #285 open until its desktop, 390 px, narrow-screen, and operational acceptance evidence is complete. diff --git a/src/Heimdall.Infrastructure/Data/Configurations/UserCameraAccessConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/UserCameraAccessConfiguration.cs index 3d71825..b1c9c7c 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/UserCameraAccessConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/UserCameraAccessConfiguration.cs @@ -11,7 +11,16 @@ public class UserCameraAccessConfiguration : IEntityTypeConfiguration new { eca.UserId, eca.SiteId, eca.CameraId }); + builder.HasKey(eca => eca.Id); + + // A site-wide grant has a null CameraId, so it cannot participate in + // a primary key. Keep duplicate protection with two partial indexes. + builder.HasIndex(eca => new { eca.UserId, eca.SiteId }) + .IsUnique() + .HasFilter("\"CameraId\" IS NULL"); + builder.HasIndex(eca => new { eca.UserId, eca.SiteId, eca.CameraId }) + .IsUnique() + .HasFilter("\"CameraId\" IS NOT NULL"); builder.HasOne() .WithMany() diff --git a/src/Heimdall.Infrastructure/Migrations/20261108123912_AllowSiteWideCameraAccess.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261108123912_AllowSiteWideCameraAccess.Designer.cs new file mode 100644 index 0000000..5c213cd --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261108123912_AllowSiteWideCameraAccess.Designer.cs @@ -0,0 +1,2906 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261108123912_AllowSiteWideCameraAccess")] + partial class AllowSiteWideCameraAccess + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CpuVendor") + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskInventoryJson") + .HasColumnType("text"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuInventoryJson") + .HasColumnType("text"); + + b.Property("GpuLoadPercent") + .HasColumnType("double precision"); + + b.Property("GpuName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KernelVersion") + .HasColumnType("text"); + + b.Property("LastAppliedCameraConfigAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedCameraConfigVersion") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("VramMb") + .HasColumnType("bigint"); + + b.Property("VramUsageBytes") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CapturedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuTemperatureCelsius") + .HasColumnType("double precision"); + + b.Property("GpuUtilizationPercent") + .HasColumnType("double precision"); + + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CapturedAtUtc"); + + b.HasIndex("AgentId", "CapturedAtUtc") + .IsUnique(); + + b.HasIndex("SiteId", "CapturedAtUtc"); + + b.ToTable("agent_metric_samples", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AssignedAgentId") + .HasColumnType("uuid"); + + b.Property("AttemptId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DispatchedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("JobType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MaxExecutionTime") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(3000000000L); + + b.Property("MaxRetries") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(3); + + b.Property("ParametersJson") + .HasColumnType("jsonb"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("RequiredCpuCores") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("RequiredMemoryMb") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L); + + b.Property("RequiresGpu") + .HasColumnType("boolean"); + + b.Property("ResultJson") + .HasColumnType("jsonb"); + + b.Property("RetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId") + .HasDatabaseName("ix_analysis_jobs_camera"); + + b.HasIndex("AssignedAgentId", "Status") + .HasDatabaseName("ix_analysis_jobs_agent_workload") + .HasFilter("\"AssignedAgentId\" IS NOT NULL"); + + b.HasIndex("Status", "DispatchedAt") + .HasDatabaseName("ix_analysis_jobs_timeout"); + + b.HasIndex("Status", "Priority", "CreatedAt") + .HasDatabaseName("ix_analysis_jobs_pending"); + + b.ToTable("analysis_jobs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("EventRecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.HasIndex("StoragePolicyId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("ExecutionProfileJson") + .HasColumnType("text"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitCategory") + .HasColumnType("integer"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitIsPaired") + .HasColumnType("boolean"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitPort") + .HasColumnType("integer"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DetectionHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("IsSuppressed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("ParentEventId") + .HasColumnType("uuid"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("RecordingId") + .HasColumnType("uuid"); + + b.Property("SnapshotObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("SnapshotStorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageProvider") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SnapshotStorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("TrackId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id", "OccurredAt"); + + b.HasIndex("DetectionHash"); + + b.HasIndex("MetadataJson"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("MetadataJson"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("MetadataJson"), new[] { "jsonb_path_ops" }); + + b.HasIndex("OccurredAt"); + + b.HasIndex("ParentEventId"); + + b.HasIndex("RecordingId"); + + b.HasIndex("TrackId"); + + b.HasIndex("VehicleId"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.HasIndex("PersonId", "OccurredAt"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("GroupId", "CameraId") + .IsUnique(); + + b.ToTable("group_camera_accesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("PlateText") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.HasIndex("PlateText"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("PlateText"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("PlateText"), new[] { "gin_trgm_ops" }); + + b.HasIndex("VehicleId"); + + b.ToTable("license_plates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Consumed") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SecurityStamp") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Verifying") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("UserId"); + + b.ToTable("login_challenges", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FailureReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("CameraId", "CreatedAt"); + + b.ToTable("manual_snapshot_requests", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeliveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastErrorType") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("LeaseExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NotificationId") + .HasColumnType("uuid"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)"); + + b.Property("ServiceUrl") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("NotificationId", "Channel") + .IsUnique() + .HasDatabaseName("ux_notification_deliveries_notification_channel"); + + b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt") + .HasDatabaseName("ix_notification_deliveries_dispatch"); + + b.ToTable("notification_deliveries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DurationSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("StorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StorageLocationCaptured") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("StoragePath") + .IsUnique(); + + b.HasIndex("StoragePolicyId"); + + b.HasIndex("CameraId", "Timestamp"); + + b.ToTable("recordings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("AutoUpdateEnabled") + .HasColumnType("boolean"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FirstSeenAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LocalRoot") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("S3Bucket") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("character varying(256)"); + + b.Property("S3Endpoint") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("Provider") + .HasDatabaseName("ix_storage_destinations_provider"); + + b.ToTable("storage_destinations", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("RetentionDays") + .HasColumnType("integer"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.ToTable("storage_policies", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("UserId"); + + b.ToTable("user_cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("SiteId"); + + b.HasIndex("UserId", "SiteId") + .IsUnique() + .HasFilter("\"CameraId\" IS NULL"); + + b.HasIndex("UserId", "SiteId", "CameraId") + .IsUnique() + .HasFilter("\"CameraId\" IS NOT NULL"); + + b.ToTable("UserCameraAccesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Color") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LicensePlate") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Make") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("LicensePlate"); + + b.HasIndex("PersonId"); + + b.ToTable("vehicles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", null) + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "AssignedAgent") + .WithMany() + .HasForeignKey("AssignedAgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedAgent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Agent"); + + b.Navigation("Site"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany("GroupCameraAccesses") + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("GroupCameraAccesses") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.HasOne("Heimdall.Domain.Entities.Notification", null) + .WithMany() + .HasForeignKey("NotificationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + + b.Navigation("GroupCameraAccesses"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("GroupCameraAccesses"); + + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261108123912_AllowSiteWideCameraAccess.cs b/src/Heimdall.Infrastructure/Migrations/20261108123912_AllowSiteWideCameraAccess.cs new file mode 100644 index 0000000..6b24015 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261108123912_AllowSiteWideCameraAccess.cs @@ -0,0 +1,79 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AllowSiteWideCameraAccess : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropPrimaryKey( + name: "PK_UserCameraAccesses", + table: "UserCameraAccesses"); + + migrationBuilder.AlterColumn( + name: "CameraId", + table: "UserCameraAccesses", + type: "uuid", + nullable: true, + oldClrType: typeof(Guid), + oldType: "uuid"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserCameraAccesses", + table: "UserCameraAccesses", + column: "Id"); + + migrationBuilder.CreateIndex( + name: "IX_UserCameraAccesses_UserId_SiteId", + table: "UserCameraAccesses", + columns: new[] { "UserId", "SiteId" }, + unique: true, + filter: "\"CameraId\" IS NULL"); + + migrationBuilder.CreateIndex( + name: "IX_UserCameraAccesses_UserId_SiteId_CameraId", + table: "UserCameraAccesses", + columns: new[] { "UserId", "SiteId", "CameraId" }, + unique: true, + filter: "\"CameraId\" IS NOT NULL"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropPrimaryKey( + name: "PK_UserCameraAccesses", + table: "UserCameraAccesses"); + + migrationBuilder.DropIndex( + name: "IX_UserCameraAccesses_UserId_SiteId", + table: "UserCameraAccesses"); + + migrationBuilder.DropIndex( + name: "IX_UserCameraAccesses_UserId_SiteId_CameraId", + table: "UserCameraAccesses"); + + // Downgrade cannot preserve site-wide grants in the old schema. + // Setting NOT NULL without a default deliberately fails while any + // such grants exist; export/remove them before rolling back. + migrationBuilder.AlterColumn( + name: "CameraId", + table: "UserCameraAccesses", + type: "uuid", + nullable: false, + oldClrType: typeof(Guid), + oldType: "uuid", + oldNullable: true); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserCameraAccesses", + table: "UserCameraAccesses", + columns: new[] { "UserId", "SiteId", "CameraId" }); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 55fbfe5..88b6a25 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -2018,30 +2018,39 @@ namespace Heimdall.Infrastructure.Migrations modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => { - b.Property("UserId") + b.Property("Id") + .ValueGeneratedOnAdd() .HasColumnType("uuid"); - b.Property("SiteId") - .HasColumnType("uuid"); - - b.Property("CameraId") + b.Property("CameraId") .HasColumnType("uuid"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); - b.Property("Id") + b.Property("SiteId") .HasColumnType("uuid"); b.Property("UpdatedAt") .HasColumnType("timestamp with time zone"); - b.HasKey("UserId", "SiteId", "CameraId"); + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); b.HasIndex("CameraId"); b.HasIndex("SiteId"); + b.HasIndex("UserId", "SiteId") + .IsUnique() + .HasFilter("\"CameraId\" IS NULL"); + + b.HasIndex("UserId", "SiteId", "CameraId") + .IsUnique() + .HasFilter("\"CameraId\" IS NOT NULL"); + b.ToTable("UserCameraAccesses", (string)null); }); diff --git a/src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor b/src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor index 0d6ba0b..8828eb8 100644 --- a/src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor +++ b/src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor @@ -98,10 +98,10 @@ - + @foreach (var site in _availableSites) { - @site.Name + @site.Name } @@ -109,10 +109,10 @@ @if (_newAccessType == AccessType.CameraSpecific) { - + @foreach (var camera in _availableCameras) { - @camera.Name (@GetSiteName(camera.SiteId)) + @camera.Name (@GetSiteName(camera.SiteId)) } } diff --git a/src/Heimdall.Web/Components/Pages/Dashboard.razor b/src/Heimdall.Web/Components/Pages/Dashboard.razor index d4a96eb..6253a64 100644 --- a/src/Heimdall.Web/Components/Pages/Dashboard.razor +++ b/src/Heimdall.Web/Components/Pages/Dashboard.razor @@ -13,7 +13,7 @@ @Text["Dashboard"] - @Text["WelcomeUser"], @Auth.User?.DisplayName + @Text["WelcomeUser"] @Auth.User?.DisplayName diff --git a/src/Heimdall.Web/Components/Pages/SitesPage.razor b/src/Heimdall.Web/Components/Pages/SitesPage.razor index 43e7412..72526c7 100644 --- a/src/Heimdall.Web/Components/Pages/SitesPage.razor +++ b/src/Heimdall.Web/Components/Pages/SitesPage.razor @@ -2,6 +2,7 @@ @attribute [Authorize] @layout MainLayout @inject HeimdallApiClient Api +@inject AuthState Auth @inject ISnackbar Snackbar @inject UiText Text @inject UiLanguageService Language @@ -17,9 +18,12 @@
- - @Text["SitesPage_NewSite"] - + @if (CanCreateSite) + { + + @Text["SitesPage_NewSite"] + + }
@if (_loading) @@ -75,6 +79,8 @@ else } + @if (CanCreateSite) + { @Text["SitesPage_NewSite"] @@ -112,6 +118,7 @@ else + } @* ─── Confirm delete dialog ───────────────────────────────── *@ @@ -254,6 +261,13 @@ else @code { + private bool CanCreateSite => Auth.HasPermission("Site.Write"); + + private void OpenCreate() + { + if (CanCreateSite) + _showCreate = true; + } private IReadOnlyList? _sites; private bool _loading = true; private bool _error; diff --git a/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor b/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor index 9b84dbd..e214bb5 100644 --- a/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor +++ b/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor @@ -14,10 +14,10 @@ - +
- + Class="snapshot-filter-control" Style="width:100%;" Placeholder="@Text["SnapshotsPage_SearchPlaceholder"]" /> + @Text["SnapshotsPage_Motion"] @Text["SnapshotsPage_Person"] @Text["SnapshotsPage_Vehicle"] @@ -31,9 +31,32 @@ @Text["SnapshotsPage_Load"] - +
+ + @if (_loading) { diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index ffa1fc5..882cd95 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -161,6 +161,48 @@ public class SitesController : ControllerBase return Ok(result.Data); } + /// List the camera credential pool for a site. Passwords are never returned. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}/credentials")] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetCredentials(Guid id, CancellationToken ct) + { + var result = await _mediator.Send(new ListSiteCredentialsQuery(id), ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Add a camera credential to a site. The password is write-only. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)] + [HttpPost("{id:guid}/credentials")] + [ProducesResponseType(typeof(SiteCredentialResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] + public async Task AddCredential(Guid id, [FromBody] AddSiteCredentialRequest request, CancellationToken ct) + { + var result = await _mediator.Send( + new AddSiteCredentialCommand(id, request.Label, request.Username, request.Password), ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Delete a camera credential from a site. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)] + [HttpDelete("{id:guid}/credentials/{credentialId:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task DeleteCredential(Guid id, Guid credentialId, CancellationToken ct) + { + var result = await _mediator.Send(new DeleteSiteCredentialCommand(id, credentialId), ct); + return result.IsSuccess + ? NoContent() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + /// Delete a site (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)] [HttpDelete("{id:guid}")] diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 9dcebe2..25788ae 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -1312,7 +1312,7 @@ Supprimer cet agent - EmptyDescription + Aucun agent n'est actuellement enregistré sur un site. Créez un site et générez un jeton d'enregistrement pour connecter un agent. Aucun agent déployé @@ -1354,7 +1354,7 @@ Annuler - Copied + J'ai copié la clé Sélectionnez et copiez la clé avec Ctrl+C @@ -1387,16 +1387,16 @@ Aucune clé API - EmptyDescription + Aucune clé API n'est configurée. Créez une clé pour permettre aux agents de se connecter. Expire le - ExpiryHelp + Si ce champ est vide, la clé n'expire jamais. - ExpiryLabel + Date d'expiration (facultative — AAAA-MM-JJ) Date d'expiration invalide (format : YYYY-MM-DD) @@ -1429,7 +1429,7 @@ Préfixe - PrefixLabel + Préfixe : Réessayer @@ -1468,10 +1468,10 @@ Site - SiteIdHelp + Si un site est indiqué, l'agent pourra accéder uniquement à ce site. - SiteIdLabel + ID du site (facultatif — laissez vide pour une clé globale) Statut diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index bf1fd06..7aa7a7e 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -1312,7 +1312,7 @@ Supprimer cet agent - EmptyDescription + No agent is currently registered on any site. Create a site and generate a registration token to connect an agent. Aucun agent déployé @@ -1354,7 +1354,7 @@ Annuler - Copied + I copied the key Sélectionnez et copiez la clé avec Ctrl+C @@ -1387,16 +1387,16 @@ Aucune clé API - EmptyDescription + No API keys configured. Create a key to allow agents to connect. Expire le - ExpiryHelp + If blank, the key never expires. - ExpiryLabel + Expiration date (optional — YYYY-MM-DD) Date d'expiration invalide (format : YYYY-MM-DD) @@ -1429,7 +1429,7 @@ Préfixe - PrefixLabel + Prefix: Réessayer @@ -1468,10 +1468,10 @@ Site - SiteIdHelp + If specified, the agent can access only this site. - SiteIdLabel + Site ID (optional — leave blank for a global key) Statut diff --git a/tests/Heimdall.E2E.Tests/E2ETestBase.cs b/tests/Heimdall.E2E.Tests/E2ETestBase.cs index ac81274..6e0493b 100644 --- a/tests/Heimdall.E2E.Tests/E2ETestBase.cs +++ b/tests/Heimdall.E2E.Tests/E2ETestBase.cs @@ -19,6 +19,7 @@ namespace Heimdall.E2E.Tests; public abstract class E2ETestBase : IAsyncLifetime { private readonly string _connectionString; + private string? _externalBaseUrl; private WebApplication? _app; private int _port; private IPage? _page; @@ -31,7 +32,7 @@ public abstract class E2ETestBase : IAsyncLifetime } protected IPage Page => _page ?? throw new InvalidOperationException("Playwright not initialized"); - protected string BaseUrl => $"http://127.0.0.1:{_port}"; + protected string BaseUrl => _externalBaseUrl ?? $"http://127.0.0.1:{_port}"; protected WebApplication App => _app ?? throw new InvalidOperationException("App not initialized"); /// Seeded admin account (see Seed:AdminLogin/Seed:AdminPassword in-memory config). @@ -72,8 +73,10 @@ public abstract class E2ETestBase : IAsyncLifetime /// Logs in through the real Blazor UI. Navigates to /login, fills the form, /// submits, and waits for the redirect to the dashboard. /// - protected async Task LoginViaUiAsync(string email = AdminEmail, string password = AdminPassword) + protected async Task LoginViaUiAsync(string? email = null, string? password = null) { + email ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL") ?? AdminEmail; + password ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD") ?? AdminPassword; await GotoWithCircuitAsync("/login"); await Page.WaitForSelectorAsync("input[autocomplete='email']", new() { Timeout = 15000 }); @@ -82,15 +85,21 @@ public abstract class E2ETestBase : IAsyncLifetime await Page.ClickAsync("button:has-text('Se connecter')"); // After a successful login the app redirects to /dashboard - await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 }); + await Page.WaitForURLAsync("**/dashboard**", new() + { + Timeout = 20000, + WaitUntil = WaitUntilState.Commit + }); } /// /// Returns a JWT access token by calling the REST API directly (no browser). /// Used by tests that need an authenticated HTTP client (e.g. admin setup). /// - protected async Task LoginViaApiAsync(string email = AdminEmail, string password = AdminPassword) + protected async Task LoginViaApiAsync(string? email = null, string? password = null) { + email ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL") ?? AdminEmail; + password ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD") ?? AdminPassword; using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) }; var response = await http.PostAsJsonAsync("/api/auth/login", new { email, password }); response.EnsureSuccessStatusCode(); @@ -102,6 +111,13 @@ public abstract class E2ETestBase : IAsyncLifetime public virtual async Task InitializeAsync() { + _externalBaseUrl = Environment.GetEnvironmentVariable("HEIMDALL_E2E_BASE_URL")?.TrimEnd('/'); + if (!string.IsNullOrWhiteSpace(_externalBaseUrl)) + { + await StartPlaywrightAsync(); + return; + } + // Find a free TCP port using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 0)); diff --git a/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs b/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs index 5f35740..2c44ed3 100644 --- a/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs +++ b/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs @@ -125,6 +125,154 @@ public class UserManagementTests : E2ETestBase await Page.WaitForSelectorAsync("text=Après Modification", new() { Timeout = 15000 }); } + [Fact] + public async Task Admin_can_grant_site_wide_and_camera_access_without_nullable_select_cast() + { + if (string.Equals(Environment.GetEnvironmentVariable("HEIMDALL_E2E_BOOTSTRAP_ADMIN"), "true", + StringComparison.OrdinalIgnoreCase)) + { + var bootstrapEmail = Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL") + ?? throw new InvalidOperationException("HEIMDALL_E2E_ADMIN_EMAIL is required for external acceptance."); + var bootstrapPassword = Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD") + ?? throw new InvalidOperationException("HEIMDALL_E2E_ADMIN_PASSWORD is required for external acceptance."); + using var bootstrap = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + var bootstrapResponse = await bootstrap.PostAsJsonAsync("api/auth/bootstrap-admin", new + { + email = bootstrapEmail, + password = bootstrapPassword, + displayName = "Disposable Acceptance Admin" + }); + var bootstrapBody = await bootstrapResponse.Content.ReadAsStringAsync(); + bootstrapResponse.StatusCode.ShouldBe(HttpStatusCode.OK, + $"Bootstrap status={bootstrapResponse.StatusCode}; response={bootstrapBody}"); + // Bootstrap is performed through the supported one-time endpoint; + // the grant workflow below still logs in and operates through UI. + } + + var token = await LoginViaApiAsync(); + using var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + admin.DefaultRequestHeaders.Authorization = new("Bearer", token); + // The panel loads the first page of sites; use a sortable prefix so a + // shared E2E database with older fixtures still includes this site. + var siteName = $"000 Nullable select {Guid.NewGuid():N}"; + var siteResponse = await admin.PostAsJsonAsync("api/sites", new { name = siteName, timezone = "UTC" }); + siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var siteId = (await siteResponse.Content.ReadFromJsonAsync()) + .GetProperty("id").GetGuid(); + var listedSites = await admin.GetFromJsonAsync("api/sites?page=1&pageSize=20"); + listedSites.GetProperty("items").EnumerateArray().ShouldContain(site => + site.GetProperty("id").GetGuid() == siteId); + var cameraName = $"Nullable camera {Guid.NewGuid():N}"; + var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name = cameraName, + rtspUrl = $"rtsp://127.0.0.1/{Guid.NewGuid():N}" + }); + cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var cameraId = (await cameraResponse.Content.ReadFromJsonAsync()) + .GetProperty("id").GetGuid(); + + var email = $"nullable-select-{Guid.NewGuid():N}@heimdall.test"; + var userResponse = await admin.PostAsJsonAsync("api/users", new + { + email, + password = "NullableSelect123!", + displayName = "Nullable Select Viewer", + roles = new[] { "Viewer" } + }); + userResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var userId = (await userResponse.Content.ReadFromJsonAsync()) + .GetProperty("id").GetGuid(); + + var pageErrors = new List(); + Page.PageError += (_, error) => pageErrors.Add(error); + // Use the real login page so the browser cookie and Blazor circuit's + // in-memory API token are both initialized for grant saves. + await LoginViaUiAsync(); + await GotoWithCircuitAsync("/users"); + var userRow = Page.Locator($"tr:has-text('{email}')"); + await userRow.GetByRole(AriaRole.Button, new() { Name = "Gérer les caméras", Exact = true }).ClickAsync(); + await Page.Locator(".camera-access-panel").WaitForAsync(); + // Blazor Server executes HeimdallApiClient calls inside its circuit on + // the server, so api/sites is not a browser network response. The + // authenticated direct API list assertion above verifies its JSON data. + await Page.Locator(".camera-access-panel .mud-progress-circular").WaitForAsync( + new() { State = WaitForSelectorState.Detached, Timeout = 15000 }); + (await Page.Locator(".camera-access-panel .mud-alert-error").CountAsync()).ShouldBe(0); + + var form = Page.Locator(".camera-access-panel"); + var siteSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Site'))").First; + var accessTypeSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Type d’accès'))").First; + await siteSelect.ClickAsync(); + // MudSelect renders its option list in a page-level popover, outside + // .camera-access-panel; wait for the option after opening the popover. + var siteOption = Page.Locator(".mud-popover-open .mud-list-item") + .Filter(new() { HasText = siteName }); + try + { + await siteOption.WaitForAsync(new() { Timeout = 10000 }); + } + catch (TimeoutException) + { + var popoverTexts = await Page.Locator(".mud-popover-open").AllInnerTextsAsync(); + var loading = await Page.Locator(".camera-access-panel .mud-progress-circular").CountAsync(); + var alerts = await Page.Locator(".camera-access-panel .mud-alert").AllInnerTextsAsync(); + var gridText = await form.Locator(".mud-grid").InnerTextAsync(); + var selectorCount = await form.Locator(".mud-grid .mud-select").CountAsync(); + throw new Xunit.Sdk.XunitException($"Site option missing. Popovers=[{string.Join(" | ", popoverTexts)}], grid=[{gridText}], gridSelectors={selectorCount}, loading={loading}, alerts=[{string.Join(" | ", alerts)}]"); + } + await siteOption.ClickAsync(); + await form.GetByRole(AriaRole.Button, new() { Name = "Ajouter à la liste", Exact = true }).ClickAsync(); + await form.Locator(".mud-table").First.GetByText(siteName, new() { Exact = true }) + .WaitForAsync(new() { Timeout = 10000 }); + var unsavedNotice = form.GetByText("Les changements ne sont appliqués qu’après l’enregistrement.", + new() { Exact = true }); + await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 5000 }); + await form.GetByRole(AriaRole.Button, new() { Name = "Enregistrer les accès", Exact = true }).ClickAsync(); + await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 }); + var saveErrorText = string.Join(" | ", await form.Locator(".mud-alert").AllInnerTextsAsync()); + var siteGrantReadback = await admin.GetFromJsonAsync( + $"api/user-camera-access/user/{userId}"); + var siteGrantItems = siteGrantReadback.GetProperty("items").EnumerateArray().ToArray(); + siteGrantItems.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId + && grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null, + customMessage: $"Save errors=[{saveErrorText}], API returned count={siteGrantItems.Length}, site matches={siteGrantItems.Count(grant => grant.GetProperty("siteId").GetGuid() == siteId)}, null camera count={siteGrantItems.Count(grant => grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null)}"); + + await accessTypeSelect.ClickAsync(); + await Page.Locator(".mud-popover-open .mud-list-item") + .Filter(new() { HasText = "spécifique" }).ClickAsync(); + var cameraSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Caméra'))").First; + await cameraSelect.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 10000 }); + await siteSelect.ClickAsync(); + siteOption = Page.Locator(".mud-popover-open .mud-list-item") + .Filter(new() { HasText = siteName }); + await siteOption.ClickAsync(); + await cameraSelect.ClickAsync(); + var cameraOption = Page.Locator(".mud-popover-open .mud-list-item") + .Filter(new() { HasText = cameraName }); + await cameraOption.WaitForAsync(new() { Timeout = 10000 }); + await cameraOption.ClickAsync(); + await form.GetByRole(AriaRole.Button, new() { Name = "Ajouter à la liste", Exact = true }).ClickAsync(); + await form.Locator(".mud-table").Last.GetByText(cameraName, new() { Exact = false }) + .WaitForAsync(new() { Timeout = 10000 }); + unsavedNotice = form.GetByText("Les changements ne sont appliqués qu’après l’enregistrement.", + new() { Exact = true }); + await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 5000 }); + await form.GetByRole(AriaRole.Button, new() { Name = "Enregistrer les accès", Exact = true }).ClickAsync(); + await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 }); + + var saved = await admin.GetFromJsonAsync( + $"api/user-camera-access/user/{userId}"); + var grants = saved.GetProperty("items").EnumerateArray().ToArray(); + grants.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId + && grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null); + grants.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId + && grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.String + && grant.GetProperty("cameraId").GetGuid() == cameraId); + pageErrors.ShouldBeEmpty(); + } + [Fact] public async Task Admin_can_reset_user_password() { diff --git a/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs index 4daf290..7a0e2f4 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs @@ -1,4 +1,5 @@ using System.Net.Http.Json; +using System.Text.Json; using Heimdall.IntegrationTests.Factories; using Shouldly; @@ -6,6 +7,8 @@ namespace Heimdall.IntegrationTests.Controllers; public class SitesControllerTests : PostgresTestBase { + private static readonly JsonSerializerOptions WebJsonOptions = new(JsonSerializerDefaults.Web); + public SitesControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } [Fact] @@ -45,4 +48,57 @@ public class SitesControllerTests : PostgresTestBase var response = await client.GetAsync("api/sites?page=1&pageSize=10"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); } + + [Fact] + public async Task SiteCredentials_CanBeListedAddedAndDeleted_WithoutReturningPassword() + { + var client = await Factory.CreateAdminClientAsync(); + var siteResponse = await client.PostAsJsonAsync("api/sites", new + { + name = $"Credential Site {Guid.NewGuid():N}", + timezone = "UTC" + }); + var site = await siteResponse.Content.ReadFromJsonAsync(); + site.ShouldNotBeNull(); + + var viewer = await Factory.CreateViewerClientAsync(client); + (await viewer.GetAsync($"api/sites/{site.Id}/credentials")).StatusCode + .ShouldBe(System.Net.HttpStatusCode.Forbidden); + + var emptyResponse = await client.GetAsync($"api/sites/{site.Id}/credentials"); + emptyResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + (await emptyResponse.Content.ReadFromJsonAsync>()) + .ShouldBeEmpty(); + + const string submittedPassword = "synthetic-camera-password-only-for-test"; + var addResponse = await client.PostAsJsonAsync($"api/sites/{site.Id}/credentials", new + { + label = "Synthetic camera login", + username = "camera-test-user", + password = submittedPassword + }); + addResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var responseBody = await addResponse.Content.ReadAsStringAsync(); + responseBody.ShouldNotContain(submittedPassword); + var created = JsonSerializer.Deserialize(responseBody, WebJsonOptions); + created.ShouldNotBeNull(); + + var listResponse = await client.GetAsync($"api/sites/{site.Id}/credentials"); + var listed = await listResponse.Content.ReadFromJsonAsync>(); + listResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + listed.ShouldHaveSingleItem().Id.ShouldBe(created.Id); + + var deleteResponse = await client.DeleteAsync($"api/sites/{site.Id}/credentials/{created.Id}"); + deleteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.NoContent); + var afterDelete = await client.GetFromJsonAsync>( + $"api/sites/{site.Id}/credentials"); + afterDelete.ShouldBeEmpty(); + } + + [Fact] + public async Task SiteCredentials_RequireAuthentication() + { + var response = await Factory.CreateClient().GetAsync($"api/sites/{Guid.NewGuid()}/credentials"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/AllAgentsPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/AllAgentsPageTests.cs index 5135c1a..f4fc852 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/AllAgentsPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/AllAgentsPageTests.cs @@ -69,6 +69,7 @@ public class AllAgentsPageTests : PageTestBase cut.WaitForAssertion(() => { cut.Markup.ShouldContain("Aucun agent déployé"); + cut.Markup.ShouldContain("Aucun agent n'est actuellement enregistré sur un site."); cut.Markup.ShouldContain("Voir les sites"); }); } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/ApiKeysPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/ApiKeysPageTests.cs new file mode 100644 index 0000000..1a12457 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Components/Pages/ApiKeysPageTests.cs @@ -0,0 +1,90 @@ +using Bunit; +using Heimdall.Web.Components.Pages.Admin; +using Microsoft.Extensions.DependencyInjection; +using Heimdall.Web.Services; +using Shouldly; + +namespace Heimdall.Web.Tests.Components.Pages; + +public class ApiKeysPageTests : PageTestBase +{ + [Fact] + public void ApiKeyResources_AucunPlaceholderVideOuTechniqueEnFrancaisEtAnglais() + { + var language = new UiLanguageService(); + var text = new UiText(language); + var keys = new[] + { + "AdminApiKeys_SiteIdLabel", + "AdminApiKeys_SiteIdHelp", + "AdminApiKeys_ExpiryLabel", + "AdminApiKeys_ExpiryHelp", + "AdminAllAgents_EmptyDescription", + "AdminApiKeys_EmptyDescription" + }; + + foreach (var culture in new[] { "fr", "en" }) + { + language.SetLanguage(culture); + foreach (var key in keys) + { + var value = text[key].Trim(); + value.ShouldNotBeNullOrWhiteSpace(); + value.ShouldNotBe(key); + value.ShouldNotBe(key[(key.LastIndexOf('_') + 1)..]); + } + } + } + + [Fact] + public void ApiKeysPage_AucuneCle_AfficheLaDescriptionFrancaise() + { + Handler.OnGet("api/api-keys", Array.Empty()); + LoginAs(); + + var cut = RenderPage(); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Aucune clé API n'est configurée."); + cut.Markup.ShouldContain("Créez une clé pour permettre aux agents de se connecter."); + cut.Markup.ShouldNotContain("EmptyDescription"); + }); + } + + [Fact] + public async Task ApiKeysPage_DialogueCreation_AfficheLesLibellesFrancais() + { + Handler.OnGet("api/api-keys", Array.Empty()); + Handler.On(HttpMethod.Post, "api/api-keys", new CreateApiKeyResult( + Guid.NewGuid(), "hdm_test_secret", "hdm_test", null, null)); + LoginAs(); + + var cut = RenderPage(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Créer une clé")); + await cut.InvokeAsync(() => cut.FindAll("button").First(button => button.TextContent.Contains("Créer une clé")).Click()); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("ID du site (facultatif — laissez vide pour une clé globale)"); + cut.Markup.ShouldContain("Si un site est indiqué, l'agent pourra accéder uniquement à ce site."); + cut.Markup.ShouldContain("Date d'expiration (facultative — AAAA-MM-JJ)"); + cut.Markup.ShouldContain("Si ce champ est vide, la clé n'expire jamais."); + cut.Markup.ShouldNotContain("SiteIdLabel"); + cut.Markup.ShouldNotContain("ExpiryHelp"); + }); + + await cut.InvokeAsync(() => cut.FindAll("button").Single(button => button.TextContent.Trim() == "Créer").Click()); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Copiez cette clé maintenant."); + cut.Markup.ShouldContain("Elle ne sera plus jamais affichée."); + cut.Markup.ShouldContain("Préfixe :"); + cut.Markup.ShouldContain("J'ai copié la clé"); + cut.Markup.ShouldNotContain("Copied"); + }); + + Services.GetRequiredService().Language.ShouldBe("fr"); + } +} diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CamerasPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CamerasPageTests.cs index feae8e4..14583e0 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CamerasPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CamerasPageTests.cs @@ -25,6 +25,62 @@ public class CamerasPageTests : PageTestBase CreatedAt = DateTime.UtcNow.AddDays(-2) }; + [Fact] + public void CamerasPage_SansIdentifiants_AfficheEtatVideSansErreur() + { + Handler.OnGet($"api/sites/{SiteId}/credentials", Array.Empty()); + Handler.OnGet("api/cameras/by-site", new PagedData([], 0, 1, 100)); + Handler.OnGet("api/discovery/sites", Array.Empty()); + Handler.OnGet("api/agents/by-site", new PagedData([], 0, 1, 50)); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.SiteId, SiteId)); + + cut.FindAll(".mud-tab").Single(tab => tab.TextContent.Contains("Identifiants", StringComparison.Ordinal)).Click(); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Aucun identifiant déclaré"); + cut.Markup.ShouldNotContain("Une erreur est survenue"); + }); + } + + [Fact] + public async Task CamerasPage_AjouterIdentifiantDepuisSiteVide_AppelleApiEtAfficheSucces() + { + Handler.OnGet($"api/sites/{SiteId}/credentials", Array.Empty()); + Handler.OnGet("api/cameras/by-site", new PagedData([], 0, 1, 100)); + Handler.OnGet("api/discovery/sites", Array.Empty()); + Handler.OnGet("api/agents/by-site", new PagedData([], 0, 1, 50)); + Handler.On(HttpMethod.Post, $"api/sites/{SiteId}/credentials", new SiteCredentialItem + { + Id = Guid.NewGuid(), SiteId = SiteId, Label = "synthetic admin", Username = "camera-user", CreatedAt = DateTime.UtcNow + }); + LoginAs(); + + var cut = RenderPage(p => p.Add(page => page.SiteId, SiteId)); + cut.FindAll(".mud-tab").Single(tab => tab.TextContent.Contains("Identifiants", StringComparison.Ordinal)).Click(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucun identifiant déclaré")); + cut.FindAll("button").First(button => button.TextContent.Trim() == "Ajouter").Click(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Ajouter un identifiant caméra")); + + var inputs = cut.FindAll("input"); + inputs.Count.ShouldBeGreaterThanOrEqualTo(3); + inputs[0].Input("synthetic admin"); + inputs[1].Input("camera-user"); + inputs[2].Input("synthetic-only-password"); + await cut.InvokeAsync(() => cut.FindAll("div.mud-dialog-actions button") + .Single(button => button.TextContent.Trim() == "Ajouter") + .Click()); + + cut.WaitForAssertion(() => + { + Services.GetRequiredService().ShownSnackbars + .Select(message => message.Message?.ToString() ?? "") + .ShouldContain("Identifiant ajouté"); + }); + } + [Fact] public void CamerasPage_AfficheTuilesCameras() { diff --git a/tests/Heimdall.Web.Tests/Components/Pages/DashboardTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/DashboardTests.cs index 57136bf..c986c0b 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/DashboardTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/DashboardTests.cs @@ -4,6 +4,7 @@ using Heimdall.Web.Services; using Microsoft.Extensions.DependencyInjection; using MudBlazor; using Shouldly; +using System.Text.RegularExpressions; namespace Heimdall.Web.Tests.Components.Pages; @@ -91,6 +92,31 @@ public class DashboardTests : PageTestBase }); } + [Theory] + [InlineData("fr", "Bienvenue, Jean Dupont")] + [InlineData("en", "Welcome, Jean Dupont")] + public void DashboardPage_AfficheUneSeulePonctuationPourChaqueCulture(string language, string expected) + { + typeof(Dashboard).GetCustomAttributes(typeof(Microsoft.AspNetCore.Components.RouteAttribute), inherit: true) + .Cast() + .Select(route => route.Template) + .ShouldBe(["/", "/dashboard"]); + + SetupHappyPath(); + LoginAs("Admin", "Jean Dupont"); + Services.GetRequiredService().SetLanguage(language); + + var cut = RenderPage(); + var greeting = cut.FindComponent().Find("p"); + + cut.WaitForAssertion(() => + { + var text = Regex.Replace(greeting.TextContent, @"\s+", " ").Trim(); + text.ShouldBe(expected); + text.ShouldNotContain(",,"); + }); + } + [Fact] public void DashboardPage_AfficheSites() { diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs index 9b86bfc..7eb0563 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs @@ -13,6 +13,24 @@ public class SiteDetailTests : PageTestBase { private static readonly Guid SiteId = Guid.NewGuid(); + [Fact] + public void SiteDetail_SansIdentifiants_AfficheEtatVideSansAlerteDeChargement() + { + Handler.OnGet($"api/sites/{SiteId}/credentials", Array.Empty()); + Handler.OnGet("capacity/history", Array.Empty()); + Handler.OnGet("api/sites/", new SiteItem( + SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow)); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, SiteId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Aucun identifiant déclaré"); + cut.Markup.ShouldNotContain("Une erreur est survenue"); + }); + } + [Fact] public void SiteDetail_AfficheInformations() { diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SitesPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SitesPageTests.cs index ea8e7d6..0d8206e 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/SitesPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/SitesPageTests.cs @@ -14,6 +14,20 @@ public class SitesPageTests : PageTestBase private static SiteItem Site(string name = "Site Alpha") => new(SiteId, name, "1 rue de la Surveillance", "Europe/Paris", null, true, false, DateTime.UtcNow.AddDays(-5)); + [Fact] + public void SitesPage_SansSiteWrite_MasqueEtBloqueLaCreation() + { + Handler.OnGet("api/sites", new PagedData([], 0, 1, 20)); + LoginAs("Viewer"); + + var cut = RenderPage(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucun site.")); + cut.FindAll("button").ShouldNotContain(b => b.TextContent.Contains("Nouveau site")); + cut.Markup.ShouldNotContain("Nom du site"); + cut.Markup.ShouldNotContain("Créer"); + } + [Fact] public void SitesPage_AfficheListeDesSites() { diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SnapshotsPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SnapshotsPageTests.cs index 5ceb4bd..9bf5aae 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/SnapshotsPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/SnapshotsPageTests.cs @@ -57,6 +57,29 @@ public class SnapshotsPageTests : PageTestBase cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucune capture trouvée.")); } + [Fact] + public void SnapshotsPage_FiltresSAdaptentAuxPetitsEcransEtGardentLaRangeeDesktop() + { + Handler.OnGet("api/events", new EventPageResult([], 0, 1, 48)); + LoginAs(); + + var cut = RenderPage(); + + var filterLayout = cut.Find(".snapshot-filters"); + filterLayout.QuerySelector("input").ShouldNotBeNull(); + filterLayout.QuerySelector(".mud-select").ShouldNotBeNull(); + filterLayout.QuerySelector("button").ShouldNotBeNull(); + + // The desktop grid keeps all three controls on one row; the phone + // breakpoint stacks them and permits the controls to shrink to the + // available width (including 390 px and narrower viewports). + cut.Markup.ShouldContain("grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr) auto"); + cut.Markup.ShouldContain("@media (max-width: 600px)"); + cut.Markup.ShouldContain("grid-template-columns: minmax(0, 1fr)"); + cut.Markup.ShouldNotContain("min-width:300px"); + cut.Markup.ShouldNotContain("min-width:180px"); + } + [Fact] public async Task SnapshotsPage_Recherche_FiltreLesSnapshots() { diff --git a/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs index 8a3be13..73ea4cc 100644 --- a/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs +++ b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs @@ -159,6 +159,32 @@ public sealed class HeimdallApiClientTests : IDisposable Assert.False(result); } + [Fact] + public async Task SiteCredentials_ReadAddAndDelete_UseSiteScopedEndpoints() + { + SetAuthToken(); + var siteId = Guid.NewGuid(); + var credentialId = Guid.NewGuid(); + var item = new SiteCredentialItem + { + Id = credentialId, SiteId = siteId, Label = "Synthetic", Username = "camera-user" + }; + _handler.QueueResponse(HttpStatusCode.OK, new[] { item }); + var listed = await _sut.GetSiteCredentialsAsync(siteId); + Assert.Single(listed); + Assert.Equal(credentialId, listed[0].Id); + Assert.Contains($"api/sites/{siteId}/credentials", _handler.LastRequest!.RequestUri!.ToString()); + + _handler.QueueResponse(HttpStatusCode.OK, item); + var added = await _sut.AddSiteCredentialAsync(siteId, "Synthetic", "camera-user", "fake-password"); + Assert.Equal(credentialId, added!.Id); + Assert.Equal(HttpMethod.Post, _handler.LastRequest!.Method); + + _handler.QueueResponse(HttpStatusCode.NoContent); + Assert.True(await _sut.DeleteSiteCredentialAsync(siteId, credentialId)); + Assert.Contains($"api/sites/{siteId}/credentials/{credentialId}", _handler.LastRequest!.RequestUri!.ToString()); + } + [Fact] public async Task AddUserToGroupAsync_WhenSuccess_ReturnsTrue() {