diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index d4ddebf..942f932 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -40,6 +40,9 @@ jobs: outputs: web_changed: ${{ steps.filter.outputs.web }} db_changed: ${{ steps.filter.outputs.db }} + unit_changed: ${{ steps.filter.outputs.unit }} + docker_changed: ${{ steps.filter.outputs.docker }} + sonar_changed: ${{ steps.filter.outputs.sonar }} deps_changed: ${{ steps.filter.outputs.deps }} steps: - uses: https://forgejo.tordais.cc/actions/checkout@v4 @@ -98,6 +101,24 @@ jobs: echo "db=false" >> "$GITHUB_OUTPUT" fi + if echo "$CHANGED" | grep -qE '^src/Heimdall\.Domain/|^src/Heimdall\.Application/|^tests/Heimdall\.Domain\.Tests/|^tests/Heimdall\.Application\.Tests/|^tests/Heimdall\.Agent\.Tests/|^tests/Heimdall\.Api\.Tests/'; then + echo "unit=true" >> "$GITHUB_OUTPUT" + else + echo "unit=false" >> "$GITHUB_OUTPUT" + fi + + if echo "$CHANGED" | grep -qE '^docker/|^Dockerfile|^\.dockerignore'; then + echo "docker=true" >> "$GITHUB_OUTPUT" + else + echo "docker=false" >> "$GITHUB_OUTPUT" + fi + + if echo "$CHANGED" | grep -qE 'sonar|SonarQube|sonarqube'; then + echo "sonar=true" >> "$GITHUB_OUTPUT" + else + echo "sonar=false" >> "$GITHUB_OUTPUT" + fi + if echo "$CHANGED" | grep -qE '\.csproj$|\.slnx$|Directory\.Build\.props$'; then echo "deps=true" >> "$GITHUB_OUTPUT" else @@ -110,7 +131,7 @@ jobs: build: name: Build + Format runs-on: debian-12 - timeout-minutes: 15 + timeout-minutes: 30 steps: - uses: https://forgejo.tordais.cc/actions/checkout@v4 with: @@ -139,9 +160,9 @@ jobs: shell: bash run: dotnet format Heimdall.slnx whitespace --verify-no-changes --no-restore - # Réduire l'artifact : ne garder que le runtime linux-x64 (seul utilisé en CI). - # Sans RID, bin/ contient ~520 MB de runtimes multi-plateforme inutiles → artifact - # de 809 MB qui sature les runners (flaky 'context deadline exceeded'). + # Réduire l'artifact : ne garder que bin/Release (pas obj/Release) et le + # runtime linux-x64. Sans ces optimisations, l'artifact dépasse 700 MB et + # le daemon Docker/runner timeout pendant l'upload (context deadline exceeded). - name: Réduire build (garder runtime linux-x64) shell: bash run: | @@ -160,9 +181,7 @@ jobs: name: build-output path: | src/**/bin/Release/ - src/**/obj/Release/ tests/**/bin/Release/ - tests/**/obj/Release/ retention-days: 1 # ───────────────────────────────────────────────────────────────────────── @@ -170,7 +189,8 @@ jobs: # ───────────────────────────────────────────────────────────────────────── test-unit: name: Tests unitaires - needs: [build] + needs: [build, changes] + if: needs.changes.outputs.unit_changed == 'true' || needs.changes.outputs.deps_changed == 'true' runs-on: debian-12 timeout-minutes: 15 outputs: @@ -279,155 +299,13 @@ jobs: echo "EOF" } >> "$GITHUB_OUTPUT" - # ───────────────────────────────────────────────────────────────────────── - # TESTS DB — Infrastructure (parallèle avec Integration) - # ───────────────────────────────────────────────────────────────────────── - test-db-infra: - name: Tests DB (Infrastructure) - needs: [build, changes] - if: needs.changes.outputs.db_changed == 'true' - runs-on: debian-12 - timeout-minutes: 15 - outputs: - summary: ${{ steps.gen-summary.outputs.summary }} - steps: - - uses: https://forgejo.tordais.cc/actions/checkout@v4 - - - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 - with: - dotnet-version: '10.0' - - - name: Download build artifacts - uses: https://forgejo.tordais.cc/actions/download-artifact@v3 - with: - name: build-output - - - name: Start PostgreSQL - shell: bash - run: | - set -euo pipefail - apt-get -qq update - apt-get install -y -qq --no-install-recommends postgresql-15 postgresql-client-15 - PGDATA=/tmp/pgdata - rm -rf "$PGDATA" - su - postgres -c "/usr/lib/postgresql/15/bin/initdb -D $PGDATA --auth=trust --no-locale --encoding=UTF8" - su - postgres -c "echo -e 'host all all 127.0.0.1/32 md5\nhost all all ::1/128 md5' >> $PGDATA/pg_hba.conf" - su - postgres -c "/usr/lib/postgresql/15/bin/pg_ctl -D $PGDATA -l /tmp/pgdata.log start" - for i in $(seq 1 15); do - su - postgres -c "/usr/lib/postgresql/15/bin/pg_isready -h localhost" > /dev/null 2>&1 && break - sleep 1 - done - su - postgres -c "psql -c \"CREATE USER app WITH PASSWORD 'password';\"" 2>/dev/null || true - su - postgres -c "psql -c \"CREATE DATABASE heimdall_infra_$\$ OWNER app;\"" 2>/dev/null || true - PGPASSWORD=password psql -U app -d heimdall_infra_$\$ -h localhost -c "SELECT 1" > /dev/null - echo "PostgreSQL prêt (infra)" - - - name: Run Infrastructure tests - shell: bash - env: - DATABASE_URL: Host=localhost;Port=5432;Database=heimdall_infra_$\$;Username=app;Password=password - run: | - set -euo pipefail - mkdir -p /tmp/coverage - LOG=/tmp/Heimdall.Infrastructure.Tests.log - dotnet test tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj --no-build -c Release --nologo --blame-hang-timeout 180s \ - -p:CollectCoverage=true -p:CoverletOutputFormat=cobertura \ - -p:CoverletOutput=/tmp/coverage/Infrastructure/ > "$LOG" 2>&1 || { - tail -40 "$LOG" | sed 's/^/ /' - exit 1 - } - grep -h -E "(Passed!|Failed!|Failed:|error CS)" "$LOG" 2>/dev/null || true - - - name: Générer le résumé - id: gen-summary - if: always() - shell: bash - run: | - SUMMARY=$(python3 scripts/ci/parse_test_log.py /tmp/*.log --coverage-dir /tmp/coverage 2>/dev/null || true) - { - echo "summary<> "$GITHUB_OUTPUT" - - # ───────────────────────────────────────────────────────────────────────── - # TESTS DB — Integration (parallèle avec Infrastructure) - # ───────────────────────────────────────────────────────────────────────── - test-db-integration: - name: Tests DB (Integration) - needs: [build, changes] - if: needs.changes.outputs.db_changed == 'true' - runs-on: debian-12 - timeout-minutes: 20 - outputs: - summary: ${{ steps.gen-summary.outputs.summary }} - steps: - - uses: https://forgejo.tordais.cc/actions/checkout@v4 - - - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 - with: - dotnet-version: '10.0' - - - name: Download build artifacts - uses: https://forgejo.tordais.cc/actions/download-artifact@v3 - with: - name: build-output - - - name: Start PostgreSQL - shell: bash - run: | - set -euo pipefail - apt-get -qq update - apt-get install -y -qq --no-install-recommends postgresql-15 postgresql-client-15 - PGDATA=/tmp/pgdata - rm -rf "$PGDATA" - su - postgres -c "/usr/lib/postgresql/15/bin/initdb -D $PGDATA --auth=trust --no-locale --encoding=UTF8" - su - postgres -c "echo -e 'host all all 127.0.0.1/32 md5\nhost all all ::1/128 md5' >> $PGDATA/pg_hba.conf" - su - postgres -c "/usr/lib/postgresql/15/bin/pg_ctl -D $PGDATA -l /tmp/pgdata.log start" - for i in $(seq 1 15); do - su - postgres -c "/usr/lib/postgresql/15/bin/pg_isready -h localhost" > /dev/null 2>&1 && break - sleep 1 - done - su - postgres -c "psql -c \"CREATE USER app WITH PASSWORD 'password';\"" 2>/dev/null || true - su - postgres -c "psql -c \"CREATE DATABASE heimdall_integ_$\$ OWNER app;\"" 2>/dev/null || true - PGPASSWORD=password psql -U app -d heimdall_integ_$\$ -h localhost -c "SELECT 1" > /dev/null - echo "PostgreSQL prêt (integration)" - - - name: Run Integration tests - shell: bash - env: - DATABASE_URL: Host=localhost;Port=5432;Database=heimdall_integ_$\$;Username=app;Password=password - ASPNETCORE_ENVIRONMENT: Testing - run: | - set -euo pipefail - mkdir -p /tmp/coverage - LOG=/tmp/Heimdall.IntegrationTests.log - dotnet test tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj --no-build -c Release --nologo --blame-hang-timeout 180s \ - -p:CollectCoverage=true -p:CoverletOutputFormat=cobertura \ - -p:CoverletOutput=/tmp/coverage/Integration/ > "$LOG" 2>&1 || { - tail -40 "$LOG" | sed 's/^/ /' - exit 1 - } - grep -h -E "(Passed!|Failed!|Failed:|error CS)" "$LOG" 2>/dev/null || true - - - name: Générer le résumé - id: gen-summary - if: always() - shell: bash - run: | - SUMMARY=$(python3 scripts/ci/parse_test_log.py /tmp/*.log --coverage-dir /tmp/coverage 2>/dev/null || true) - { - echo "summary<> "$GITHUB_OUTPUT" - # ───────────────────────────────────────────────────────────────────────── # SONARQUBE — analyse (non bloquant, gate en warning) # ───────────────────────────────────────────────────────────────────────── sonar: name: SonarQube - needs: [build] + needs: [build, changes] + if: needs.changes.outputs.sonar_changed == 'true' || needs.changes.outputs.deps_changed == 'true' || needs.changes.outputs.db_changed == 'true' || needs.changes.outputs.unit_changed == 'true' || needs.changes.outputs.web_changed == 'true' runs-on: debian-12 timeout-minutes: 40 steps: @@ -647,7 +525,8 @@ jobs: # ───────────────────────────────────────────────────────────────────────── docker-pr: name: Docker PR - if: github.event_name == 'pull_request' + needs: [build, changes] + if: needs.changes.outputs.docker_changed == 'true' || needs.changes.outputs.deps_changed == 'true' runs-on: debian-12 timeout-minutes: 30 steps: @@ -762,7 +641,7 @@ jobs: post-summary: name: Résumé tests (PR) if: always() && github.event_name == 'pull_request' - needs: [changes, test-unit, test-web, test-db-infra, test-db-integration] + needs: [changes, build, test-unit, test-web] runs-on: debian-12 timeout-minutes: 10 steps: @@ -774,19 +653,34 @@ jobs: FORGEJO_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }} + R_BUILD: ${{ needs.build.result }} + R_UNIT: ${{ needs.test-unit.result }} + R_WEB: ${{ needs.test-web.result }} S_UNIT: ${{ needs.test-unit.outputs.summary }} S_WEB: ${{ needs.test-web.outputs.summary }} - S_DB: ${{ needs.test-db-infra.outputs.summary }} + WEB_SKIPPED: ${{ needs.changes.outputs.web_changed }} DB_SKIPPED: ${{ needs.changes.outputs.db_changed }} run: | + # Petit helper : convertit un result (success/failure/skipped) en émoji + emoji() { + case "$1" in + success) echo "✅" ;; + failure|cancelled) echo "❌" ;; + skipped) echo "⏭️ " ;; + *) echo "❔" ;; + esac + } { echo "## Tests unitaires" echo "" - if [ -n "$S_UNIT" ]; then - echo "$S_UNIT" + if [ "$R_UNIT" = "failure" ]; then + echo "$(emoji "$R_UNIT") **Job en échec**" + printf '%s\n' "$S_UNIT" + elif [ -n "$S_UNIT" ]; then + echo "$(emoji "$R_UNIT")$S_UNIT" else - echo "_Pas de résultats (job skippé)_" + echo "_Pas de résultats_" fi echo "" echo "---" @@ -794,24 +688,18 @@ jobs: echo "## Tests Web (bUnit)" echo "" if [ "$WEB_SKIPPED" = "false" ]; then - echo "_Skippé (aucun changement IHM)_" - elif [ -n "$S_WEB" ]; then + echo "⏭️ _Skippé (aucun changement IHM)_" + elif [ "$R_WEB" = "failure" ]; then + echo "$(emoji "$R_WEB") **Job en échec**" echo "$S_WEB" + elif [ -n "$S_WEB" ]; then + echo "$(emoji "$R_WEB")$S_WEB" else echo "_Pas de résultats_" fi echo "" echo "---" echo "" - echo "## Tests DB (Infrastructure)" - echo "" - if [ "$DB_SKIPPED" = "false" ]; then - echo "_Skippé (aucun changement DB/Domain)_" - elif [ -n "$S_DB" ]; then - echo "$S_DB" - else - echo "_Pas de résultats_" - fi } > /tmp/full-summary.md python3 scripts/ci/post_comment.py "$(cat /tmp/full-summary.md)" "Résumé des tests" @@ -822,7 +710,7 @@ jobs: name: ci runs-on: debian-12 if: always() - needs: [build, test-unit, test-web, test-db-infra, test-db-integration, sonar, docker, dependency-check, post-summary] + needs: [build, test-unit, test-web, sonar, docker, dependency-check, post-summary] steps: - name: Vérifier les résultats shell: bash @@ -831,7 +719,6 @@ jobs: echo " build: ${{ needs.build.result }}" echo " test-unit: ${{ needs.test-unit.result }}" echo " test-web: ${{ needs.test-web.result }}" - echo " test-db: ${{ needs.test-db.result }}" echo " sonar: ${{ needs.sonar.result }}" echo " docker: ${{ needs.docker.result }}" echo " dependency-check: ${{ needs.dependency-check.result }}" @@ -839,7 +726,7 @@ jobs: # Échouer si un job critique a échoué (sonar et dependency-check sont non-bloquants) if [[ "${{ needs.build.result }}" == "failure" ]] || \ [[ "${{ needs.test-unit.result }}" == "failure" ]] || \ - [[ "${{ needs.test-web.result }}" == "failure" ]]; then + [[ "${{ needs.test-web.result }}" == "failure" ]] || \ echo "❌ Un job critique a échoué" exit 1 fi diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent index c12da8d..ea42063 100644 --- a/docker/Dockerfile.agent +++ b/docker/Dockerfile.agent @@ -18,6 +18,9 @@ COPY src/ src/ RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release -o /app -p:Version=$VERSION +# Modèle YOLOv8n pré-converti en ONNX et committé dans le repo (voir models/) +# (ultralytics ne distribue plus d'.onnx prêt ; torch/OpenCV s'installent mal en +# CI — trop lent + deps libGL/libxcb absentes. On committe le .onnx une fois.) FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime WORKDIR /app @@ -27,12 +30,8 @@ ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false ENV ASPNETCORE_URLS=http://+:8080 COPY --from=build /app . - -# Download YOLOv8n ONNX model (spec §16: yolov8n, ~6MB) -ARG YOLO_MODEL_URL=https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov8n.onnx -RUN mkdir -p models && \ - wget -q -O models/yolov8n.onnx "$YOLO_MODEL_URL" && \ - echo "YOLOv8n model downloaded: $(du -sh models/yolov8n.onnx | cut -f1)" +# Modèle YOLOv8n ONNX committé dans le repo (contexte de build = racine repo) +COPY models/yolov8n.onnx models/yolov8n.onnx HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:8080/healthz || exit 1 diff --git a/models/yolov8n.onnx b/models/yolov8n.onnx new file mode 100644 index 0000000..8823bde Binary files /dev/null and b/models/yolov8n.onnx differ diff --git a/scripts/ci/parse_test_log.py b/scripts/ci/parse_test_log.py index 74870a7..69ea1f8 100755 --- a/scripts/ci/parse_test_log.py +++ b/scripts/ci/parse_test_log.py @@ -5,7 +5,14 @@ Usage: parse_test_log.py ... [--coverage-dir ] Lit les fichiers de log (générés par les jobs CI) et les rapports coverage -cobertura (optionnel) ; sort le markdown sur stdout. Vide si rien trouvé. +cobertura (optionnel) ; sort le markdown sur stdout. + +Comportement : +- Si des tests ont tourné : tableau agrégé (Passed/Failed/Skipped/Total) + + liste des tests échoués nommément (si l'info est dans le log). +- Si AUCUN test n'a tourné : message explicite signalant un échec avant + l'exécution (et non plus une sortie vide silencieuse qui faisait afficher + « Pas de résultats » au récap PR). """ import glob import os @@ -20,53 +27,60 @@ if "--coverage-dir" in args: del args[i:i + 2] logs = [a for a in args if os.path.isfile(a)] -results = [] # (projet, passed, failed, skipped, total, status) -error_lines = [] +results = [] # (projet, failed, passed, skipped, total, status) +error_lines = [] # erreurs de compilation +failed_tests = [] # noms des tests échoués + for f in sorted(logs): try: with open(f, errors="replace") as fh: content = fh.read() except OSError: continue - # Pattern 1: "Passed! - Failed: 0, Passed: 225, Skipped: 0, Total: 225, ... - X.dll (net10.0)" + + # --- Comptes agrégés (Pattern 1 : avec nom de DLL) --- for m in re.finditer( - r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)[^:]*-\s*([\w.]+)\.dll", + r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)[^:]*-[^:]*\[?\s*([\w.]+)\.dll", content, ): results.append((m.group(6), m.group(2), m.group(3), m.group(4), m.group(5), m.group(1))) - # Pattern 2: "Passed! - Failed: 0, Passed: 225, Skipped: 0, Total: 225" (without dll name) - if not results: - for m in re.finditer( - r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)", - content, - ): - # Try to find the DLL name on the same line - line_start = content.rfind("\n", 0, m.start()) + 1 - line_end = content.find("\n", m.end()) - line = content[line_start:line_end] if line_end > 0 else content[line_start:] - dll_match = re.search(r"-\s*([\w.]+)\.dll", line) - proj = dll_match.group(1) if dll_match else "unknown" - results.append((proj, m.group(2), m.group(3), m.group(4), m.group(5), m.group(1))) - # Pattern 3: look for "Passed!" lines with test counts (alternative format) + + # --- Comptes agrégés (Pattern 2 : sans nom de DLL) --- for m in re.finditer( - r"Passed!\s*-\s*Failed:\s*(\d+),\s*Passed:\s*(\d+),\s*Skipped:\s*(\d+),\s*Total:\s*(\d+)", + r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)", content, ): - # Check if we already have this result - total = m.group(4) - passed = m.group(2) - if not any(r[4] == total and r[2] == passed for r in results): - proj_match = re.search(r"-\s*([\w.]+)\.dll", content[m.end():m.end()+200]) - proj = proj_match.group(1) if proj_match else "unknown" - results.append((proj, m.group(1), m.group(2), m.group(3), m.group(4), "Passed!" if m.group(1) == "0" else "Failed!")) + tot, passed = m.group(5), m.group(3) + if any(r[4] == tot and r[2] == passed for r in results): + continue + line_start = content.rfind("\n", 0, m.start()) + 1 + line_end = content.find("\n", m.end()) + line = content[line_start:line_end] if line_end > 0 else content[line_start:] + dll_match = re.search(r"-\s*([\w.]+)\.dll", line) + proj = dll_match.group(1) if dll_match else "unknown" + results.append((proj, m.group(2), m.group(3), m.group(4), m.group(5), m.group(1))) + + # --- Erreurs de compilation --- for m in re.finditer(r"error CS\d+:\s*(.+)", content): error_lines.append(m.group(1).strip()[:120]) -if not results and not error_lines: - print("") + # --- Noms des tests échoués : lignes commençant par "Failed " --- + # (le compteur « Failed! » porte un '!' collé, donc pas de collision avec ce pattern) + for m in re.finditer(r"^\s*Failed\s+([A-Za-z_][\w.]*\.\w[\w.]*)\s", content, re.MULTILINE): + name = m.group(1).strip() + if name not in failed_tests: + failed_tests.append(name) + +if not results and not error_lines and not failed_tests: + # Aucune exécution de test détectée : le job a échoué AVANT de lancer dotnet test, + # ou il a été skippé. On le dit explicitement plutôt que de sortir vide. + if logs: + print("_⚠️ Le job n'a produit aucun résultat de test (échec avant l'exécution ou build/DB en amont). Voir le log du job CI._") + else: + print("_⚠️ Aucun log de test produit par ce job._") sys.exit(0) -# Deduplicate results by project name +# Dédupliquer par projet seen = set() unique_results = [] for r in results: @@ -85,9 +99,18 @@ if results: failed_total = sum(int(r[1]) for r in results) passed_total = sum(int(r[2]) for r in results) if failed_total: - out.append(f"\n**⚠️ {failed_total} test(s) en échec** — voir le détail dans le job CI.") + out.append(f"\n**❌ {failed_total} test(s) en échec** — {passed_total} passent.") else: out.append(f"\n**✅ {passed_total} tests passent.**") + +# Liste nominative des tests échoués +if failed_tests: + out.append("\n**Tests en échec :**") + for name in failed_tests[:40]: + out.append(f"- ❌ `{name}`") + if len(failed_tests) > 40: + out.append(f"\n_… et {len(failed_tests) - 40} autre(s) (voir log)_") + if error_lines: out.append("\n**Erreurs de compilation détectées :**") for e in error_lines[:10]: diff --git a/src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs index 15c1769..8eb14f4 100644 --- a/src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs @@ -35,8 +35,6 @@ public class UpdateCameraCommandHandler : IRequestHandler +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("20260828180904_AddAnalysisJobsAndUserCameras")] + partial class AddAnalysisJobsAndUserCameras + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .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("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KernelVersion") + .HasColumnType("text"); + + 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.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("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.AppRole", 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.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.AppUser", 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("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("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("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("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("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + 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("RecordingId") + .HasColumnType("uuid"); + + 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.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.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.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.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("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("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.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.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("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.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.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + 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.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.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.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("User"); + }); + + 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.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + 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.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserGroups"); + + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + 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/20260828180904_AddAnalysisJobsAndUserCameras.cs b/src/Heimdall.Infrastructure/Migrations/20260828180904_AddAnalysisJobsAndUserCameras.cs new file mode 100644 index 0000000..8ec97c0 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260828180904_AddAnalysisJobsAndUserCameras.cs @@ -0,0 +1,145 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddAnalysisJobsAndUserCameras : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "AutoUpdateEnabled", + table: "sites", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.CreateTable( + name: "analysis_jobs", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + CameraId = table.Column(type: "uuid", nullable: false), + AssignedAgentId = table.Column(type: "uuid", nullable: true), + JobType = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + Status = table.Column(type: "character varying(30)", maxLength: 30, nullable: false), + Priority = table.Column(type: "integer", nullable: false), + SiteId = table.Column(type: "uuid", nullable: false), + RequiresGpu = table.Column(type: "boolean", nullable: false), + RequiredCpuCores = table.Column(type: "integer", nullable: false, defaultValue: 0), + RequiredMemoryMb = table.Column(type: "bigint", nullable: false, defaultValue: 0L), + MaxExecutionTime = table.Column(type: "bigint", nullable: false, defaultValue: 3000000000L), + RetryCount = table.Column(type: "integer", nullable: false, defaultValue: 0), + MaxRetries = table.Column(type: "integer", nullable: false, defaultValue: 3), + ParametersJson = table.Column(type: "jsonb", nullable: true), + ResultJson = table.Column(type: "jsonb", nullable: true), + ErrorMessage = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false), + DispatchedAt = table.Column(type: "timestamp with time zone", nullable: true), + StartedAt = table.Column(type: "timestamp with time zone", nullable: true), + CompletedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_analysis_jobs", x => x.Id); + table.ForeignKey( + name: "FK_analysis_jobs_agents_AssignedAgentId", + column: x => x.AssignedAgentId, + principalTable: "agents", + principalColumn: "Id", + onDelete: ReferentialAction.SetNull); + table.ForeignKey( + name: "FK_analysis_jobs_cameras_CameraId", + column: x => x.CameraId, + principalTable: "cameras", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "user_cameras", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + CameraId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_user_cameras", x => new { x.UserId, x.CameraId }); + table.ForeignKey( + name: "FK_user_cameras_cameras_CameraId", + column: x => x.CameraId, + principalTable: "cameras", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_user_cameras_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_camera_events_MetadataJson", + table: "camera_events", + column: "MetadataJson") + .Annotation("Npgsql:IndexMethod", "gin") + .Annotation("Npgsql:IndexOperators", new[] { "jsonb_path_ops" }); + + migrationBuilder.CreateIndex( + name: "ix_analysis_jobs_agent_workload", + table: "analysis_jobs", + columns: new[] { "AssignedAgentId", "Status" }, + filter: "\"AssignedAgentId\" IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "ix_analysis_jobs_camera", + table: "analysis_jobs", + column: "CameraId"); + + migrationBuilder.CreateIndex( + name: "ix_analysis_jobs_pending", + table: "analysis_jobs", + columns: new[] { "Status", "Priority", "CreatedAt" }); + + migrationBuilder.CreateIndex( + name: "ix_analysis_jobs_timeout", + table: "analysis_jobs", + columns: new[] { "Status", "DispatchedAt" }); + + migrationBuilder.CreateIndex( + name: "IX_user_cameras_CameraId", + table: "user_cameras", + column: "CameraId"); + + migrationBuilder.CreateIndex( + name: "IX_user_cameras_UserId", + table: "user_cameras", + column: "UserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "analysis_jobs"); + + migrationBuilder.DropTable( + name: "user_cameras"); + + migrationBuilder.DropIndex( + name: "IX_camera_events_MetadataJson", + table: "camera_events"); + + migrationBuilder.DropColumn( + name: "AutoUpdateEnabled", + table: "sites"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index eec4b0c..06d9c53 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -17,7 +17,7 @@ namespace Heimdall.Infrastructure.Migrations { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "10.0.11") + .HasAnnotation("ProductVersion", "10.0.8") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); @@ -291,6 +291,105 @@ namespace Heimdall.Infrastructure.Migrations 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("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") @@ -992,9 +1091,11 @@ namespace Heimdall.Infrastructure.Migrations modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => { b.Property("Id") - .ValueGeneratedOnAdd() .HasColumnType("uuid"); + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + b.Property("AgentId") .HasColumnType("uuid"); @@ -1029,9 +1130,6 @@ namespace Heimdall.Infrastructure.Migrations b.Property("MetadataJson") .HasColumnType("jsonb"); - b.Property("OccurredAt") - .HasColumnType("timestamp with time zone"); - b.Property("ParentEventId") .HasColumnType("uuid"); @@ -1068,6 +1166,11 @@ namespace Heimdall.Infrastructure.Migrations 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"); @@ -1083,7 +1186,7 @@ namespace Heimdall.Infrastructure.Migrations b.HasIndex("CameraId", "Type"); - b.ToTable("camera_events"); + b.ToTable("camera_events", (string)null); }); modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => @@ -1523,6 +1626,9 @@ namespace Heimdall.Infrastructure.Migrations .HasMaxLength(500) .HasColumnType("character varying(500)"); + b.Property("AutoUpdateEnabled") + .HasColumnType("boolean"); + b.Property("CreatedAt") .ValueGeneratedOnAdd() .HasColumnType("timestamp with time zone") @@ -1654,6 +1760,23 @@ namespace Heimdall.Infrastructure.Migrations 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.UserGroup", b => { b.Property("UserId") @@ -1962,6 +2085,24 @@ namespace Heimdall.Infrastructure.Migrations 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") @@ -2138,6 +2279,25 @@ namespace Heimdall.Infrastructure.Migrations 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.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("User"); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => { b.HasOne("Heimdall.Domain.Entities.Group", "Group") diff --git a/src/Heimdall.Web/Components/Pages/Admin/AllAgentsPage.razor b/src/Heimdall.Web/Components/Pages/Admin/AllAgentsPage.razor index 1a1d2ba..8173e81 100644 --- a/src/Heimdall.Web/Components/Pages/Admin/AllAgentsPage.razor +++ b/src/Heimdall.Web/Components/Pages/Admin/AllAgentsPage.razor @@ -64,7 +64,16 @@ else @foreach (var agent in _agents) { - +
+ +
+ + + +
+
} @@ -79,6 +88,30 @@ else } } +@* ─── Delete Confirmation Dialog ─── *@ + + + + + + Confirmer la suppression + + + + Supprimer l'agent @_confirmDeleteName ? + + Les caméras associées seront désassignées mais pas supprimées. + + + + Annuler + + Supprimer + + + + @code { private IReadOnlyList? _agents; private List _agentStats = []; @@ -89,6 +122,12 @@ else private int _total; private string _search = ""; + // Delete agent + private bool _confirmDeleteShow; + private Guid _confirmDeleteId; + private string _confirmDeleteName = ""; + private bool _deleting; + [Inject] private NavigationManager Nav { get; set; } = null!; protected override async Task OnInitializedAsync() @@ -187,4 +226,34 @@ else _refreshCts?.Cancel(); _refreshCts?.Dispose(); } + + // ─── Delete Agent ───────────────────────────────────────────── + + private void ConfirmDeleteAgent(Guid id, string name) + { + _confirmDeleteId = id; + _confirmDeleteName = name; + _confirmDeleteShow = true; + } + + private async Task ExecuteDeleteAgentAsync() + { + _deleting = true; + try + { + _confirmDeleteShow = false; + var error = await Api.DeleteAgentAsync(_confirmDeleteId); + if (error is null) + { + Snackbar.Add($"Agent \"{_confirmDeleteName}\" supprimé", Severity.Success); + await LoadData(); + } + else + { + Snackbar.Add(error, Severity.Error); + } + } + catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } + finally { _deleting = false; } + } } diff --git a/src/Heimdall.Web/Components/Pages/AgentDetail.razor b/src/Heimdall.Web/Components/Pages/AgentDetail.razor index ac491ac..7a804ce 100644 --- a/src/Heimdall.Web/Components/Pages/AgentDetail.razor +++ b/src/Heimdall.Web/Components/Pages/AgentDetail.razor @@ -712,6 +712,14 @@ else OnClick="@(() => Nav.NavigateTo("/admin/agents"))"> ← Tous les agents + + + + Supprimer + + } @@ -738,6 +746,29 @@ else +@* ─── Delete Agent Confirmation Dialog ─── *@ + + + + + Confirmer la suppression + + + + Supprimer l'agent @_agent?.Name ? + + Les caméras associées seront désassignées mais pas supprimées. + + + + Annuler + + Supprimer + + + + @* ─── Add / Edit Dialog ─── *@ @@ -795,6 +826,10 @@ else private string _deletingKey = string.Empty; private bool _deleting; + // Delete agent + private bool _confirmDeleteAgentVisible; + private bool _deletingAgent; + // Logs private IReadOnlyList? _logs; private bool _logsLoading; @@ -872,6 +907,27 @@ else catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } } + private async Task ExecuteDeleteAgentAsync() + { + _deletingAgent = true; + try + { + _confirmDeleteAgentVisible = false; + var error = await Api.DeleteAgentAsync(Id); + if (error is null) + { + Snackbar.Add($"Agent \"{_agent?.Name}\" supprimé", Severity.Success); + Nav.NavigateTo("/admin/agents"); + } + else + { + Snackbar.Add(error, Severity.Error); + } + } + catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } + finally { _deletingAgent = false; } + } + /// Returns the effective value for a global setting key (override wins). private string EffectiveValue(string key, string globalValue) => _settings.FirstOrDefault(s => s.Key == key)?.Value ?? globalValue; diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index eaaf8a6..3d3b790 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -573,6 +573,18 @@ public class HeimdallApiClient $"api/agents?page={page}&pageSize={pageSize}", Json); } + /// + /// Supprime un agent par son identifiant (soft-delete + désassignation des caméras). + /// + /// null en cas de succès, sinon le message d'erreur du serveur. + public async Task DeleteAgentAsync(Guid id) + { + var client = CreateClient(); + var response = await client.DeleteAsync($"api/agents/{id}"); + if (response.IsSuccessStatusCode) return null; + return await ReadErrorMessageAsync(response); + } + /// Get agent-specific KPIs for the dashboard. public async Task> GetAgentStatsAsync() { diff --git a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs index 97aee17..7984f43 100644 --- a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs +++ b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs @@ -1,5 +1,8 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; +using Heimdall.Application.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace Heimdall.IntegrationTests.Factories; @@ -30,5 +33,23 @@ public class HeimdallWebApplicationFactory : WebApplicationFactory builder.UseSetting("Jwt:RefreshKey", "ThisIsATestRefreshKeyThatIsAlso32Bytes!"); builder.UseSetting("Jwt:Issuer", "heimdall-test"); builder.UseSetting("Jwt:Audience", "heimdall-test"); + + // Stub HIBP: integration tests must never depend on an external breach-check + // API nor on a test password that happens not to be in the HIBP database + // (that made `api/auth/register` return 400: "password has appeared in a + // data breach"). Force "not breached" in tests only — production code path + // (HaveIBeenPwnedBreachChecker) is untouched. + builder.ConfigureServices(services => + { + services.RemoveAll(); + services.AddScoped(); + }); } } + +/// Test-only stub: never flags a password as breached. Avoids network + HIBP flakiness. +internal sealed class NoopPasswordBreachChecker : IPasswordBreachChecker +{ + public Task IsPasswordBreachedAsync(string password, CancellationToken ct = default) + => Task.FromResult(false); +} diff --git a/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailTests.cs index 1f6e6b7..84da926 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailTests.cs @@ -120,6 +120,43 @@ public class AgentDetailTests : PageTestBase cut.WaitForAssertion(() => Handler.Requests.Any(r => r.Method == HttpMethod.Delete - && r.RequestUri!.AbsolutePath.Contains($"api/settings/agent/{AgentId}/overrides")).ShouldBeTrue()); + && r.RequestUri!.AbsolutePath.Contains($"/api/settings/agent/{AgentId}/overrides")).ShouldBeTrue()); + } + + [Fact] + public void AgentDetail_BoutonSupprimer_Present() + { + Handler.OnGet($"/api/settings/agent/{AgentId}/overrides", new List()); + Handler.OnGet("api/settings", new List()); + Handler.OnGet($"/api/agents/{AgentId}", Agent()); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, AgentId)); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("agent-01")); + + // Le bouton Supprimer est présent dans la zone d'actions du bas + cut.Markup.ShouldContain("Supprimer"); + } + + [Fact] + public void AgentDetail_Supprimer_OuvreDialogConfirmation() + { + Handler.OnGet($"/api/settings/agent/{AgentId}/overrides", new List()); + Handler.OnGet("api/settings", new List()); + Handler.OnGet($"/api/agents/{AgentId}", Agent()); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, AgentId)); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("agent-01")); + + // Cliquer sur "Supprimer" ouvre le dialog de confirmation + cut.FindAll("button").Single(b => b.TextContent.Contains("Supprimer") + && b.TextContent.Trim() != "Supprimer le réglage").Click(); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Confirmer la suppression"); + cut.Markup.ShouldContain("désassignées"); + }); } } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/AllAgentsPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/AllAgentsPageTests.cs index c770f16..5135c1a 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/AllAgentsPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/AllAgentsPageTests.cs @@ -140,4 +140,72 @@ public class AllAgentsPageTests : PageTestBase && r.RequestUri!.PathAndQuery.Contains("api/agents") && r.RequestUri.Query.Contains("page=2")).ShouldBeTrue()); } + + [Fact] + public void AllAgentsPage_Supprimer_BoutonPresent() + { + Handler.OnGet("api/agents", new PagedData( + [Agent("Agent-1"), Agent("Agent-2", "Site Beta")], 2, 1, 20)); + Handler.OnGet("api/stats/agent-stats", Stats()); + LoginAs(); + + var cut = RenderPage(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Agent-1")); + // Les boutons supprimer sont présents (2 agents = 2 boutons) + var deleteButtons = cut.FindAll("[aria-label=\"Supprimer l'agent\"]"); + deleteButtons.Count.ShouldBe(2); + } + + [Fact] + public void AllAgentsPage_Supprimer_OuvreDialogConfirmation() + { + var agent = Agent("Agent-Test"); + Handler.OnGet("api/agents", new PagedData([agent], 1, 1, 20)); + Handler.OnGet("api/stats/agent-stats", Stats()); + LoginAs(); + + var cut = RenderPage(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Agent-Test")); + + // Cliquer sur le bouton supprimer ouvre le dialog + cut.Find("[aria-label=\"Supprimer l'agent\"]").Click(); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Confirmer la suppression"); + cut.Markup.ShouldContain("Agent-Test"); + cut.Markup.ShouldContain("désassignées"); + }); + } + + [Fact] + public void AllAgentsPage_Supprimer_ConfirmationEnvoieDeleteEtRecharge() + { + var agent = Agent("Agent-Del"); + Handler.OnGet("api/agents", new PagedData([agent], 1, 1, 20)); + Handler.OnGet("api/stats/agent-stats", Stats()); + Handler.On(HttpMethod.Delete, "api/agents", System.Net.HttpStatusCode.OK); + // Après suppression, la liste est rechargée vide + Handler.OnGet("api/agents", new PagedData([], 0, 1, 20)); + LoginAs(); + + var cut = RenderPage(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Agent-Del")); + + // Ouvrir le dialog + cut.Find("[aria-label=\"Supprimer l'agent\"]").Click(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Confirmer la suppression")); + + // Cliquer "Supprimer" dans le dialog (dernier bouton avec ce texte) + var dialogButtons = cut.FindAll("button"); + dialogButtons.Where(b => b.TextContent.Trim() == "Supprimer").Last().Click(); + + cut.WaitForAssertion(() => + { + // Le DELETE a bien été envoyé + Handler.Requests.Any(r => r.Method == HttpMethod.Delete + && r.RequestUri!.PathAndQuery.Contains("api/agents")).ShouldBeTrue(); + }); + } }