2 Commits
Author SHA1 Message Date
marcoandClaude Opus 4.8 bd73a9c3b2 v0.1.31 — Policy-Konsolidierung, Geraete-Export nach Gruppe, Gruppen-in-Gruppen
Build & Release MSI / build-msi (push) Canceled after 0s
- Policies zusammenfuehren (Settings Catalog -> eine neue Policy, Konfliktaufloesung)
- Geraete-Tab: Gruppen-Filter (Live-Suche) + CSV-Export der angezeigten Liste
- Group Management: bestehende Gruppen als Mitglied hinzufuegen (verschachtelt)
- Fix: Geraete "Invalid Date" (ISO-Normalisierung) + Datums-/Spalten-Sortierung
- Doku (README/CHANGELOG) + Version-Bump 0.1.31

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-11 09:01:02 +02:00
marcoandClaude Opus 4.8 446c53f409 v0.1.30 — Policy-Bulk-Import gehaertet, macOS-Apps, Gruppen-Suche & Direkt-Zuweisung
Build & Release MSI / build-msi (push) Canceled after 0s
- Bulk-Import von Policies (Batches + Fortschritt, Fehler-Isolierung)
- Export/Import-Treue via Raw-JSON (-OutputType Json), null-Collections-Strip,
  Settings-Catalog-Reparatur + Korruptions-Erkennung, Git-Resolver
- macOS-Apps in Liste/Suche + Plattform-Filter
- "Gruppe"-Tab durchsucht alle Gruppen (Live-Suche) statt nur Praefix-Gruppen
- Bestehende Gruppe(n) direkt an Apps zuweisen inkl. Mehrfachauswahl
- Fix: Add-GraphAppAssignment merged bestehende Zuweisungen (/assign ersetzt sonst
  die komplette Liste) -> kein Ueberschreiben mehr, ein Request fuer alle Ziele

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-03 09:03:22 +02:00
10 changed files with 1414 additions and 147 deletions
+38
View File
@@ -5,6 +5,44 @@ Versionierung folgt [Semantic Versioning](https://semver.org/lang/de/) — solan
---
## [0.1.31] - 2026-09-11
Policy-Konsolidierung, Geräte-Export nach Gruppe, Gruppen-in-Gruppen, Geräte-Fixes.
### Neu
- **Policies zusammenführen** (Settings Catalog): Mehrere Settings-Catalog-Policies zu **einer neuen** Policy vereinen. Gleiche Einstellungen werden einmal übernommen, **Konflikte** (gleiche `settingDefinitionId`, anderer Wert) werden vor dem Anlegen angezeigt und pro Konflikt aufgelöst. Button „Konsolidieren" im Policies-Tab (ab 2 gewählten Settings-Catalog-Policies). Neuer Endpoint `POST /api/policies/consolidate`.
- **Geräte nach Gruppe exportieren**: Im **Geräte**-Tab neuer **Gruppen-Filter** (Live-Suche) — die Liste zeigt nur die Geräte der Gruppen-User (inkl. verschachtelter Gruppen) — plus **CSV-Export** der aktuell angezeigten Liste. Kombinierbar mit Suche/OS/Compliance. Neuer Endpoint `GET /api/groups/{id}/devices/export`.
- **Gruppen zu Gruppen hinzufügen**: Im Group-Management-Tab „Benutzer | Gruppen hinzufügen" ein Umschalter **Benutzer / Gruppen** — eine bestehende Gruppe als Mitglied (verschachtelte Gruppe) zur gewählten Gruppe hinzufügen.
### Behoben
- **Geräte „Invalid Date"**: `lastSyncDateTime`/`enrolledDateTime` werden jetzt server-seitig als ISO 8601 normalisiert (`ConvertTo-IsoDate`) — vorher kam unter PowerShell 5.1 ein nicht parsbares Format an. Anzeige zusätzlich robust (ungültig → „—").
- **Geräte-Sortierung**: Die Spalten-Sortierung war komplett wirkungslos (Header-Feldnamen ≠ Item-Properties). Jetzt sortieren alle Spalten korrekt, **Datums-Spalten numerisch** nach Zeitstempel (Klick auf „Letzter Sync" / „Eingeschrieben").
---
## [0.1.30] - 2026-09-03
Policy-Bulk-Import gehärtet, macOS-Apps, Gruppen-Suche & Direkt-Zuweisung an Apps.
### Neu
- **Bulk-Import von Policies**: Mehrere Policy-Dateien (oder eine Bundle-Datei) auf einmal importieren. Läuft server-seitig in Batches à 5 mit Fortschrittsanzeige und Fehler-Isolierung pro Batch — umgeht das 180-s-Timeout einzelner Requests.
- **macOS-Apps** erscheinen jetzt in App-Liste und -Suche (DMG, PKG, LOB, Defender, Edge, M365, VPP) mit eigenen Typ-Labels. Neuer **Plattform-Filter** (Alle / Windows / macOS).
- **Gruppen-Suche** im Ziel-Panel: Der frühere „Abteilung"-Tab heißt jetzt **„Gruppe"** und durchsucht per Live-Suche **alle** Tenant-Gruppen (statt nur Präfix-Gruppen). Auswahl bleibt über mehrere Suchen erhalten.
- **Bestehende Gruppe(n) direkt einer App zuweisen**: Im Dialog „Zuweisung hinzufügen" neue Option „Bestehende Gruppe" (Required/Available) mit Gruppensuche und **Mehrfachauswahl** (Chips).
### Behoben
- **App-Zuweisung überschrieb bestehende Zuweisungen**: `Add-GraphAppAssignment` nutzte die `/assign`-Action mit nur einer Zuweisung — diese ersetzt aber die komplette Liste. Jetzt werden bestehende Zuweisungen geladen, neue gemergt (Duplikate übersprungen) und in **einem** Request geschickt. Behebt sowohl die Mehrfach-Zuweisung als auch stillen Verlust vorhandener Zuweisungen beim Einzel-Hinzufügen.
- **Policy-Export/-Import-Treue** (Windows PowerShell 5.1): Policy-Details werden als **rohes JSON** von Graph geholt (`-OutputType Json`), sonst skalarisierte der Hashtable-Modus Ein-Element-Collections (z. B. `printerNames`) → 400 beim Re-Import.
- **Configuration-Profile-Import**: `null`-Werte für nicht-nullbare Collections werden entfernt (400 `ModelValidationFailure`).
- **Settings-Catalog-Import**: Reparatur leerer/verstümmelter Collections (`[""]`, `{}`), Rettung stringifizierter `*TemplateReference`-Felder und **klarer Abbruch** bei irreparabel beschädigten Quelldateien (alte Exporte mit zu geringer JSON-Tiefe).
- **Git-Snapshot**: `git` wird jetzt auch über bekannte Installationsorte gefunden, falls es nicht im (veralteten) PATH des Server-Prozesses liegt.
---
## [0.1.29] - 2026-08-24
Geräte-Offboarding (v1).
+22 -9
View File
@@ -90,7 +90,7 @@ Schlaegt diese fehl, wird automatisch auf die **Read-Only-App-ID** (`clientIdRo`
- App-Zuweisung (Required / Available hinzufuegen und entfernen)
- Gruppen erstellen und loeschen
- Tab „Benutzer hinzufuegen" im Group Management
- Tab „Benutzer | Gruppen hinzufuegen" im Group Management
- Tab „CSV-Import" im Group Management
- Session-Ausfuehren-Button
- Alle Rename-/Delete-Buttons
@@ -132,10 +132,10 @@ App-Registrierung automatisch anlegt/konfiguriert:**
| Tab | Beschreibung |
|--------------------|-------------------------------------------------------------|
| App Management | Haupt-Ansicht: Apps laden, Gruppen zuweisen / entfernen |
| Group Management | Mitglieder anzeigen, exportieren, Benutzer hinzufuegen, CSV-Import |
| Group Management | Mitglieder anzeigen/exportieren, Benutzer **und Gruppen** hinzufuegen, CSV-Import |
| App Report | Installationszaehler pro App, Geraete-Export als CSV |
| Geräte | Geraete suchen, Detail-Panel, Aktionen (Sync, Wipe, …) |
| Policies | Policies exportieren (JSON-Download) und importieren (Neuanlage) |
| Geräte | Geraete suchen, Filter (auch nach **Gruppe**), CSV-Export, Detail-Panel, Aktionen (Sync, Wipe, …) |
| Policies | Policies exportieren/importieren (Neuanlage) und **zusammenfuehren** (Settings Catalog) |
---
@@ -148,10 +148,11 @@ App-Registrierung automatisch anlegt/konfiguriert:**
- Filter zum Einschraenken der Anzeige
- **Als CSV exportieren** laedt alle Mitglieder als `members-<Gruppe>-<Datum>.csv`
### Benutzer hinzufuegen *(nur Read/Write)*
### Benutzer | Gruppen hinzufuegen *(nur Read/Write)*
- Benutzer per Name, UPN oder E-Mail suchen
- Mehrere Benutzer auswaehlen und gemeinsam hinzufuegen
- Umschalter **Benutzer / Gruppen** oben im Tab
- Benutzer per Name, UPN oder E-Mail suchen — oder Gruppen per Name (verschachtelte Gruppen)
- Mehrere Eintraege auswaehlen und gemeinsam zur gewaehlten Gruppe hinzufuegen
### CSV-Import *(nur Read/Write)*
@@ -235,6 +236,16 @@ neu an. Unterstuetzte Typen:
> bekommen bei Bedarf einen Default-`scheduledActionsForRule`-Block, den Graph
> beim Anlegen zwingend verlangt.
### Konsolidieren *(nur Read/Write, nur Settings Catalog)*
- Mindestens zwei **Settings-Catalog**-Policies per Checkbox waehlen →
**„Konsolidieren"**
- Die Einstellungen werden zu **einer neuen** Policy vereint (Neuanlage) — gleiche
`settingDefinitionId` mit gleichem Wert wird einmal uebernommen
- **Konflikte** (gleiche Einstellung, unterschiedlicher Wert) werden vor dem
Anlegen angezeigt; pro Konflikt waehlst du, welche Policy gewinnt
- Voraussetzung: gleiche Plattform. Zuweisungen werden nicht uebernommen.
### Benoetigt Graph-Berechtigung
`DeviceManagementConfiguration.ReadWrite.All` (Import) bzw.
@@ -295,8 +306,9 @@ Intune Manager/
| POST | `/api/groups/resolve-upns` | Read | UPN-Liste → UserId + DisplayName |
| GET | `/api/groups/{id}/members` | Read | Mitglieder einer Gruppe |
| GET | `/api/groups/{id}/members/export` | Read | Mitglieder als CSV |
| POST | `/api/groups/{id}/members` | **Write** | Benutzer zur Gruppe hinzufuegen |
| DELETE | `/api/groups/{id}/members/{uid}` | **Write** | Benutzer aus Gruppe entfernen |
| POST | `/api/groups/{id}/members` | **Write** | Benutzer/Gruppen zur Gruppe hinzufuegen |
| DELETE | `/api/groups/{id}/members/{uid}` | **Write** | Benutzer/Gruppe aus Gruppe entfernen |
| GET | `/api/groups/{id}/devices/export` | Read+MDM | Geraete der Gruppen-User als CSV |
| GET | `/api/users?q=` | Read | Benutzer suchen |
| GET | `/api/apps` | Read | Apps laden (cached) |
| POST | `/api/apps/refresh` | Read | Apps neu laden |
@@ -311,6 +323,7 @@ Intune Manager/
| POST | `/api/policies/export` | Read+Cfg | Ausgewaehlte Policies als JSON exportieren |
| GET | `/api/policies/exports` | — | Server-Archiv der Exporte auflisten |
| POST | `/api/policies/import` | **Write** | Policies als Neuanlage importieren |
| POST | `/api/policies/consolidate` | **Write** | Settings-Catalog-Policies zusammenfuehren |
> **Read+MDM** = benoetigt zusaetzlich `DeviceManagementManagedDevices.Read.All`
> **Read+Cfg** = benoetigt `DeviceManagementConfiguration.Read.All` (Export) bzw. `.ReadWrite.All` (Import)
+1 -1
View File
@@ -189,7 +189,7 @@ $script:State = [pscustomobject]@{
Session = @() # geplante Zuweisungen
}
$script:ToolVersion = "0.1.29"
$script:ToolVersion = "0.1.31"
$script:BuildStamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host ""
+1 -1
View File
@@ -12,7 +12,7 @@ if (Test-Path "$x64Dotnet\dotnet.exe") {
$env:DOTNET_ROOT = "C:\Program Files\dotnet"
}
$version = "0.1.29"
$version = "0.1.31"
$src = "\\Mac\Home\ClaudePRJ\Intune Manager"
$stage = "$env:TEMP\IntuneManagerStage"
$installerDir = "$src\installer"
+169 -40
View File
@@ -58,6 +58,7 @@ function Invoke-ApiHandler {
"GET /api/policies/exports" { return Get-PolicyExportsEndpoint }
"POST /api/policies/import" { return Import-PoliciesEndpoint -Body $Body }
"POST /api/policies/assign" { return Invoke-PolicyAssignEndpoint -Body $Body }
"POST /api/policies/consolidate" { return Invoke-PolicyConsolidateEndpoint -Body $Body }
"POST /api/policies/git-snapshot" { return Invoke-PolicyGitSnapshotEndpoint }
"POST /api/pickfolder" { return Invoke-FolderPickerEndpoint -Body $Body }
@@ -71,6 +72,9 @@ function Invoke-ApiHandler {
if ($Method -eq "GET" -and $Path -match "^/api/groups/([^/]+)/members/export$") {
return Get-GroupMembersExportEndpoint -GroupId $matches[1]
}
if ($Method -eq "GET" -and $Path -match "^/api/groups/([^/]+)/devices/export$") {
return Get-GroupDevicesExportEndpoint -GroupId $matches[1]
}
if ($Method -eq "GET" -and $Path -match "^/api/groups/([^/]+)/members$") {
return Get-GroupMembersEndpoint -GroupId $matches[1]
@@ -1608,6 +1612,117 @@ function Get-GroupMembersExportEndpoint {
}
}
function Get-GroupDevicesExportEndpoint {
# Loest die User einer Gruppe (inkl. verschachtelter Untergruppen) auf und liefert
# deren Intune-Geraete (Geraete, deren PRIMAERER Benutzer in der Gruppe ist) fuer
# einen CSV-Export. Geraete werden per $batch ueber userId eq '<id>' geholt.
param([string]$GroupId)
$err = Test-Connected
if ($err) { return $err }
if ([string]::IsNullOrWhiteSpace($GroupId)) { return @{ __status = 400; error = "GroupId fehlt" } }
$groupName = $GroupId
try {
$g = Get-GraphGroupById -Id $GroupId -Property @("id","displayName")
if ($g.displayName) { $groupName = [string]$g.displayName }
} catch {
return @{ __status = 404; error = "Gruppe nicht gefunden: $($_.Exception.Message)" }
}
Write-Host "[GRP-DEV-EXPORT] Geraete-Export fuer Gruppe '$groupName' ($GroupId)" -ForegroundColor Cyan
$sw = [System.Diagnostics.Stopwatch]::StartNew()
# User aufloesen + deduplizieren (nur eindeutige Entra-User-Ids)
$allUsers = @(Resolve-GroupMembersWithNesting -GroupId $GroupId -GroupName $groupName)
$seen = @{}
$userIds = [System.Collections.Generic.List[string]]::new()
$userMap = @{} # userId -> @{ Upn; DisplayName } (aus den Gruppen-Mitgliedern)
foreach ($u in $allUsers) {
$uid = [string]$u.Id
if ($uid -and -not $seen.ContainsKey($uid)) {
$seen[$uid] = $true
$userIds.Add($uid)
$userMap[$uid] = @{ Upn = [string]$u.UserPrincipalName; DisplayName = [string]$u.DisplayName }
}
}
if ($userIds.Count -eq 0) {
return @{ ok = $true; groupId = $GroupId; groupName = $groupName; userCount = 0; items = @(); count = 0; resolvedMs = [int]$sw.ElapsedMilliseconds }
}
$select = 'id,deviceName,userDisplayName,userPrincipalName,operatingSystem,osVersion,complianceState,serialNumber,model,manufacturer,lastSyncDateTime,enrolledDateTime'
$batchSize = 20
$devSeen = @{}
$items = [System.Collections.Generic.List[object]]::new()
$ids = $userIds.ToArray()
$script:GrpDevErrors = @()
for ($i = 0; $i -lt $ids.Count; $i += $batchSize) {
$chunk = $ids[$i .. [Math]::Min($i + $batchSize - 1, $ids.Count - 1)]
$requests = @()
for ($j = 0; $j -lt $chunk.Count; $j++) {
# Kanonischer Weg: die managedDevices-Navigation des Users. Zuverlaessiger
# als $filter=userId eq '..' auf /deviceManagement/managedDevices.
$requests += @{ id = [string]($i + $j); method = 'GET'; url = "/users/$($chunk[$j])/managedDevices?`$select=$select" }
}
$body = @{ requests = $requests } | ConvertTo-Json -Depth 5 -Compress
try {
$resp = Invoke-MgGraphRequestRetry -Uri 'https://graph.microsoft.com/beta/$batch' -Method POST -Body $body -ContentType 'application/json'
foreach ($r in @($resp.responses)) {
if ([int]$r.status -ne 200) {
if (@($script:GrpDevErrors).Count -lt 3) {
$em = $null
try { $em = [string]$r.body.error.message } catch {}
$script:GrpDevErrors += "HTTP $($r.status)$(if ($em) { ": $em" })"
}
continue
}
# Batch-Request-Id -> Index in $ids -> Gruppen-User (fuer UPN/Name-Fallback,
# da managedDevice.userPrincipalName bei Graph oft leer ist).
$owner = $null
$reqIdx = -1; if ([int]::TryParse([string]$r.id, [ref]$reqIdx)) {
if ($reqIdx -ge 0 -and $reqIdx -lt $ids.Count) { $owner = $userMap[$ids[$reqIdx]] }
}
foreach ($d in @($r.body.value)) {
$did = [string]$d.id
if (-not $did -or $devSeen.ContainsKey($did)) { continue }
$devSeen[$did] = $true
$upn = if ($d.userPrincipalName) { [string]$d.userPrincipalName } elseif ($owner) { $owner.Upn } else { '' }
$udn = if ($d.userDisplayName) { [string]$d.userDisplayName } elseif ($owner) { $owner.DisplayName } else { '' }
$items.Add([pscustomobject]@{
Id = $did
DeviceName = [string]$d.deviceName
UserDisplayName = $udn
UserPrincipalName = $upn
OS = [string]$d.operatingSystem
OSVersion = [string]$d.osVersion
ComplianceState = [string]$d.complianceState
SerialNumber = [string]$d.serialNumber
Model = [string]$d.model
Manufacturer = [string]$d.manufacturer
LastSync = ConvertTo-IsoDate $d.lastSyncDateTime
EnrolledDateTime = ConvertTo-IsoDate $d.enrolledDateTime
})
}
}
} catch {
Write-Host " [GRP-DEV-EXPORT] Batch-Fehler: $($_.Exception.Message)" -ForegroundColor DarkYellow
}
}
$sw.Stop()
Write-Host " -> $($items.Count) Geraete fuer $($userIds.Count) User, $($sw.ElapsedMilliseconds)ms" -ForegroundColor Green
return @{
ok = $true
groupId = $GroupId
groupName = $groupName
userCount = $userIds.Count
items = @($items.ToArray())
count = $items.Count
resolvedMs = [int]$sw.ElapsedMilliseconds
errors = @($script:GrpDevErrors)
}
}
# ============================================================
# Users
# ============================================================
@@ -1728,12 +1843,12 @@ function Search-DevicesEndpoint {
OS = $d.operatingSystem
OSVersion = $d.osVersion
ComplianceState = $d.complianceState
LastSync = $d.lastSyncDateTime
LastSync = ConvertTo-IsoDate $d.lastSyncDateTime
ManagementState = $d.managementState
SerialNumber = $d.serialNumber
Model = $d.model
Manufacturer = $d.manufacturer
EnrolledDateTime = $d.enrolledDateTime
EnrolledDateTime = ConvertTo-IsoDate $d.enrolledDateTime
}
}
return @{ items = $items; count = $items.Count }
@@ -1758,12 +1873,12 @@ function Get-DeviceEndpoint {
OS = $d.operatingSystem
OSVersion = $d.osVersion
ComplianceState = $d.complianceState
LastSync = $d.lastSyncDateTime
LastSync = ConvertTo-IsoDate $d.lastSyncDateTime
ManagementState = $d.managementState
SerialNumber = $d.serialNumber
Model = $d.model
Manufacturer = $d.manufacturer
EnrolledDateTime = $d.enrolledDateTime
EnrolledDateTime = ConvertTo-IsoDate $d.enrolledDateTime
Imei = $d.imei
WiFiMac = $d.wiFiMacAddress
AzureADDeviceId = $d.azureADDeviceId
@@ -2805,23 +2920,29 @@ function Add-AppAssignmentEndpoint {
if ($intent -notin @("required","available")) {
return @{ __status = 400; error = "intent muss 'required' oder 'available' sein" }
}
$target = [string]$Body.target
if ([string]::IsNullOrWhiteSpace($target)) {
return @{ __status = 400; error = "target fehlt (ALL_USERS / ALL_DEVICES / <group-guid>)" }
# Ein ODER mehrere Ziele akzeptieren: 'targets' (Array) hat Vorrang, sonst 'target'.
$targets = @()
if ($Body.targets) { $targets = @($Body.targets | ForEach-Object { [string]$_ }) }
elseif ($Body.target) { $targets = @([string]$Body.target) }
$targets = @($targets | Where-Object { $_ -and $_.Trim() })
if ($targets.Count -eq 0) {
return @{ __status = 400; error = "target/targets fehlt (ALL_USERS / ALL_DEVICES / <group-guid>)" }
}
# Bei Group-Target: zumindest grobe Hex/GUID-Form pruefen damit wir keine
# Garbage an Graph schicken.
if ($target -notin @("ALL_USERS","ALL_DEVICES") -and $target -notmatch '^[0-9a-fA-F-]{8,}$') {
return @{ __status = 400; error = "Ungueltige target-GUID: $target" }
# Jedes Group-Target grob auf Hex/GUID-Form pruefen (keine Garbage an Graph).
foreach ($t in $targets) {
if ($t -notin @("ALL_USERS","ALL_DEVICES") -and $t -notmatch '^[0-9a-fA-F-]{8,}$') {
return @{ __status = 400; error = "Ungueltige target-GUID: $t" }
}
}
# App-Cache fuer logging
$cachedApp = $script:State.Apps | Where-Object { $_.AppId -eq $AppId } | Select-Object -First 1
$appName = if ($cachedApp) { $cachedApp.AppName } else { $AppId }
Write-Host "[ADD ASSIGN] $appName -> intent=$intent target=$target" -ForegroundColor Yellow
Write-Host "[ADD ASSIGN] $appName -> intent=$intent targets=$($targets -join ', ')" -ForegroundColor Yellow
try {
Add-GraphAppAssignment -AppId $AppId -Intent $intent -GroupId $target
# EIN Request fuer alle Ziele: bestehende Zuweisungen werden gemergt.
Add-GraphAppAssignment -AppId $AppId -Intent $intent -GroupId $targets
} catch {
$graphBody = $null
try { $graphBody = $_.ErrorDetails.Message } catch {}
@@ -2836,38 +2957,46 @@ function Add-AppAssignmentEndpoint {
return @{ __status = $status; error = $friendly; code = $details.Code; graph = $graphBody }
}
# Cache aktualisieren — neue Zuweisung im App-Eintrag ergaenzen
# Cache aktualisieren — neue Zuweisung(en) im App-Eintrag ergaenzen.
# (Das Frontend laedt danach ohnehin neu; das haelt die UI aber sofort konsistent.)
if ($cachedApp) {
$entry = if ($target -eq "ALL_USERS") {
@{ GroupId = "ALL_USERS"; GroupName = "All Users"; IsNative = $true }
} elseif ($target -eq "ALL_DEVICES") {
@{ GroupId = "ALL_DEVICES"; GroupName = "All Devices"; IsNative = $true }
} else {
# Group-Namen aus den geladenen Gruppen oder Graph nachschlagen
$groupName = $target
$lookup = @{}
foreach ($g in $script:State.Groups) { $lookup[$g.Id] = $g.DisplayName }
foreach ($g in $script:State.RpaGroups) { $lookup[$g.Id] = $g.DisplayName }
if ($lookup.ContainsKey($target)) { $groupName = $lookup[$target] }
else {
try {
$g = Get-GraphGroupById -Id $target -Property @("id","displayName")
if ($g.displayName) { $groupName = [string]$g.displayName }
} catch {}
$lookup = @{}
foreach ($g in $script:State.Groups) { $lookup[$g.Id] = $g.DisplayName }
foreach ($g in $script:State.RpaGroups) { $lookup[$g.Id] = $g.DisplayName }
foreach ($target in $targets) {
$entry = if ($target -eq "ALL_USERS") {
@{ GroupId = "ALL_USERS"; GroupName = "All Users"; IsNative = $true }
} elseif ($target -eq "ALL_DEVICES") {
@{ GroupId = "ALL_DEVICES"; GroupName = "All Devices"; IsNative = $true }
} else {
$groupName = $target
if ($lookup.ContainsKey($target)) { $groupName = $lookup[$target] }
else {
try {
$g = Get-GraphGroupById -Id $target -Property @("id","displayName")
if ($g.displayName) { $groupName = [string]$g.displayName }
} catch {}
}
@{ GroupId = $target; GroupName = $groupName; IsNative = $false }
}
$exists = if ($intent -eq "available") {
@($cachedApp.AvailableGroups | Where-Object { $_.GroupId -eq $entry.GroupId }).Count -gt 0
} else {
@($cachedApp.RequiredGroups | Where-Object { $_.GroupId -eq $entry.GroupId }).Count -gt 0
}
if ($exists) { continue }
if ($intent -eq "available") {
$cachedApp.AvailableGroups = @($cachedApp.AvailableGroups + $entry)
$cachedApp.AvailableCount = $cachedApp.AvailableGroups.Count
} else {
$cachedApp.RequiredGroups = @($cachedApp.RequiredGroups + $entry)
$cachedApp.RequiredCount = $cachedApp.RequiredGroups.Count
}
@{ GroupId = $target; GroupName = $groupName; IsNative = $false }
}
if ($intent -eq "available") {
$cachedApp.AvailableGroups = @($cachedApp.AvailableGroups + $entry)
$cachedApp.AvailableCount = $cachedApp.AvailableGroups.Count
} else {
$cachedApp.RequiredGroups = @($cachedApp.RequiredGroups + $entry)
$cachedApp.RequiredCount = $cachedApp.RequiredGroups.Count
}
}
Write-Host "[ADD ASSIGN] OK" -ForegroundColor Green
return @{ ok = $true; appId = $AppId; intent = $intent; target = $target }
Write-Host "[ADD ASSIGN] OK ($($targets.Count) Ziel(e))" -ForegroundColor Green
return @{ ok = $true; appId = $AppId; intent = $intent; targets = @($targets); count = $targets.Count }
}
function Remove-AppAssignmentEndpoint {
+71 -18
View File
@@ -33,7 +33,13 @@ function Invoke-MgGraphRequestRetry {
$Body,
[string]$ContentType,
[hashtable]$Headers,
[int]$MaxRetries = 3
[int]$MaxRetries = 3,
# Rohes JSON von Graph holen und selbst parsen. Noetig fuer Policy-Exporte:
# Invoke-MgGraphRequest liefert unter Windows PowerShell 5.1 im Hashtable-
# Modus Ein-Element-Collections als Skalar (z.B. printerNames), was beim
# Re-Import 400 "A 'StartArray' node was expected" ausloest. -OutputType Json
# umgeht das: ConvertFrom-Json bewahrt Arrays.
[switch]$AsRawJson
)
$attempt = 0
while ($true) {
@@ -42,6 +48,13 @@ function Invoke-MgGraphRequestRetry {
if ($PSBoundParameters.ContainsKey('Body') -and $null -ne $Body) { $params.Body = $Body }
if ($ContentType) { $params.ContentType = $ContentType }
if ($Headers) { $params.Headers = $Headers }
if ($AsRawJson) {
$params.OutputType = 'Json'
$raw = Invoke-MgGraphRequest @params
if ([string]::IsNullOrWhiteSpace([string]$raw)) { return $null }
if ($PSVersionTable.PSVersion.Major -ge 6) { return ($raw | ConvertFrom-Json -AsHashtable) }
return ($raw | ConvertFrom-Json)
}
return Invoke-MgGraphRequest @params
} catch {
$msg = $_.Exception.Message
@@ -64,11 +77,15 @@ function Invoke-MgGraphRequestRetry {
}
function Get-GraphPaged {
param([Parameter(Mandatory=$true)][string]$Uri)
param(
[Parameter(Mandatory=$true)][string]$Uri,
# An Invoke-MgGraphRequestRetry durchreichen: bewahrt Arrays fuer Exporte.
[switch]$AsRawJson
)
$results = @()
$next = $Uri
do {
$response = Invoke-MgGraphRequestRetry -Uri $next -Method GET
$response = Invoke-MgGraphRequestRetry -Uri $next -Method GET -AsRawJson:$AsRawJson
if ($response.value) { $results += $response.value }
$next = $response.'@odata.nextLink'
} while ($next)
@@ -376,21 +393,51 @@ function Add-GraphAppAssignment {
param(
[string]$AppId,
[string]$Intent, # "available" | "required"
[string]$GroupId # GUID oder "ALL_USERS" / "ALL_DEVICES"
[string[]]$GroupId # eine ODER mehrere: GUID(s) und/oder "ALL_USERS"/"ALL_DEVICES"
)
$target = switch ($GroupId) {
"ALL_USERS" { @{ "@odata.type" = "#microsoft.graph.allLicensedUsersAssignmentTarget" } }
"ALL_DEVICES" { @{ "@odata.type" = "#microsoft.graph.allDevicesAssignmentTarget" } }
default { @{ "@odata.type" = "#microsoft.graph.groupAssignmentTarget"; "groupId" = $GroupId } }
# WICHTIG: Die /assign-Action ERSETZT die komplette Zuweisungsliste der App.
# Ein einzelnes POST wuerde also alle bestehenden Zuweisungen loeschen. Daher:
# bestehende Zuweisungen laden, die neuen mergen (Duplikate ueberspringen) und
# den VOLLEN Satz in EINEM Request schicken. Das haelt mehrere neue Gruppen
# zusammen (kein Read-after-Write-Rennen) und bewahrt vorhandene Zuweisungen.
$newTargets = @()
foreach ($gid in @($GroupId)) {
if ([string]::IsNullOrWhiteSpace([string]$gid)) { continue }
$newTargets += switch ([string]$gid) {
"ALL_USERS" { @{ "@odata.type" = "#microsoft.graph.allLicensedUsersAssignmentTarget" } }
"ALL_DEVICES" { @{ "@odata.type" = "#microsoft.graph.allDevicesAssignmentTarget" } }
default { @{ "@odata.type" = "#microsoft.graph.groupAssignmentTarget"; "groupId" = [string]$gid } }
}
}
$body = @{
mobileAppAssignments = @(@{
"@odata.type" = "#microsoft.graph.mobileAppAssignment"
$existing = Get-GraphMobileAppAssignments -AppId $AppId
$assignments = @()
$seen = @{} # Schluessel intent|type|groupId -> Duplikate vermeiden
foreach ($a in $existing) {
$tgt = $a.target
if (-not $tgt) { continue }
$key = ([string]$a.intent) + '|' + ([string]$tgt.'@odata.type') + '|' + ([string]$tgt.groupId)
$seen[$key] = $true
$assignments += @{
'@odata.type' = '#microsoft.graph.mobileAppAssignment'
intent = [string]$a.intent
target = $tgt # inkl. evtl. Filter -> unveraendert beibehalten
settings = $a.settings # bestehende Assignment-Settings bewahren
}
}
foreach ($t in $newTargets) {
$key = $Intent + '|' + [string]$t['@odata.type'] + '|' + [string]$t['groupId']
if ($seen.ContainsKey($key)) { continue } # bereits (mit diesem Intent) zugewiesen
$seen[$key] = $true
$assignments += @{
'@odata.type' = '#microsoft.graph.mobileAppAssignment'
intent = $Intent
target = $target
target = $t
settings = $null
})
}
}
$body = @{ mobileAppAssignments = @($assignments) }
Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/assign" -Method POST -Body $body
}
@@ -827,16 +874,15 @@ function Remove-GraphMobileApp {
}
}
# Excluded App-Typen aus dem Original-Script
# Ausgeschlossene App-Typen: iOS/Android bleiben ausgeblendet (dieses Tool ist auf
# Windows + macOS ausgelegt). macOS-Typen sind bewusst NICHT mehr ausgeschlossen,
# damit Mac-Apps in Liste/Suche erscheinen.
$script:ExcludedAppTypes = @(
'#microsoft.graph.iosLobApp', '#microsoft.graph.iosStoreApp', '#microsoft.graph.iosVppApp',
'#microsoft.graph.managedIOSLobApp', '#microsoft.graph.managedIOSStoreApp',
'#microsoft.graph.androidLobApp', '#microsoft.graph.androidStoreApp', '#microsoft.graph.androidForWorkApp',
'#microsoft.graph.androidManagedStoreApp', '#microsoft.graph.androidManagedStoreWebApp',
'#microsoft.graph.managedAndroidLobApp', '#microsoft.graph.managedAndroidStoreApp',
'#microsoft.graph.macOSDmgApp', '#microsoft.graph.macOSLobApp', '#microsoft.graph.macOSMicrosoftDefenderApp',
'#microsoft.graph.macOSMicrosoftEdgeApp', '#microsoft.graph.macOSOfficeSuiteApp', '#microsoft.graph.macOSPkgApp',
'#microsoft.graph.macOsVppApp'
'#microsoft.graph.managedAndroidLobApp', '#microsoft.graph.managedAndroidStoreApp'
)
function Test-AppTypeAllowed {
@@ -858,6 +904,13 @@ function ConvertTo-AppFriendlyType {
'#microsoft.graph.windowsAppX' { 'APPX' }
'#microsoft.graph.windowsUniversalAppX' { 'APPX' }
'#microsoft.graph.windowsMobileMSI' { 'MSI' }
'#microsoft.graph.macOSDmgApp' { 'macOS DMG' }
'#microsoft.graph.macOSPkgApp' { 'macOS PKG' }
'#microsoft.graph.macOSLobApp' { 'macOS LOB' }
'#microsoft.graph.macOSMicrosoftDefenderApp' { 'macOS Defender' }
'#microsoft.graph.macOSMicrosoftEdgeApp' { 'macOS Edge' }
'#microsoft.graph.macOSOfficeSuiteApp' { 'macOS M365' }
'#microsoft.graph.macOsVppApp' { 'macOS VPP' }
default {
($Type -replace '#microsoft\.graph\.','')
}
+253 -10
View File
@@ -186,10 +186,12 @@ function Get-GraphPolicyDetail {
# Administrative Vorlagen: Basis-Objekt holen und die konfigurierten Werte
# (definitionValues inkl. Definition + Presentation-Werten) separat expandieren.
# -AsRawJson durchgaengig: bewahrt Ein-Element-Collections als Array (PS-5.1-
# Hashtable-Modus wuerde sie skalarisieren -> 400 beim Re-Import).
if ($cfg.Key -eq 'administrativetemplate') {
$base = Invoke-MgGraphRequestRetry -Uri "https://graph.microsoft.com/beta/deviceManagement/groupPolicyConfigurations/$Id" -Method GET
$base = Invoke-MgGraphRequestRetry -Uri "https://graph.microsoft.com/beta/deviceManagement/groupPolicyConfigurations/$Id" -Method GET -AsRawJson
$dvUri = "https://graph.microsoft.com/beta/deviceManagement/groupPolicyConfigurations/$Id/definitionValues?`$expand=definition(`$select=id,classType,displayName,policyType,version),presentationValues(`$expand=presentation)"
$dvs = @(Get-GraphPaged -Uri $dvUri)
$dvs = @(Get-GraphPaged -Uri $dvUri -AsRawJson)
if ($base -is [System.Collections.IDictionary]) { $base['definitionValues'] = $dvs }
else { $base | Add-Member -NotePropertyName definitionValues -NotePropertyValue $dvs -Force }
return $base
@@ -197,7 +199,7 @@ function Get-GraphPolicyDetail {
$uri = "https://graph.microsoft.com/beta/deviceManagement/$($cfg.Collection)/$Id"
if ($cfg.ExportExpand) { $uri += "?`$expand=$($cfg.ExportExpand)" }
return Invoke-MgGraphRequestRetry -Uri $uri -Method GET
return Invoke-MgGraphRequestRetry -Uri $uri -Method GET -AsRawJson
}
# PSCustomObject/Hashtable -> bereinigte Hashtable ohne Read-Only-Felder.
@@ -229,10 +231,23 @@ function ConvertTo-ImportBody {
function Repair-SettingsCatalogArrays {
param($Node)
$arrayKeys = @('settings','children','groupSettingCollectionValue','simpleSettingCollectionValue','values')
# *TemplateReference-Keys tragen ein Objekt ODER null. Ein alter Export mit zu
# geringer ConvertTo-Json-Tiefe hat solche (tief liegenden) Objekte zu ".ToString()"
# stringifiziert -> "System.Collections.Hashtable". Graph lehnt das ab
# ('Property settingValueTemplateReference ... does not match schema'). Der bloße
# String ist eindeutig korrupt und nicht rekonstruierbar -> auf null setzen; die
# (optionale) Template-Bindung entfaellt, die eigentlichen Werte bleiben erhalten.
$refKeys = @('settingInstanceTemplateReference','settingValueTemplateReference')
# Array-Property normalisieren: $null -> @() (Graph-Schema: Collections sind
# Nullable=False, ein 'children': null wird abgelehnt), Einzelobjekt -> @(obj).
# Inline (nicht als Funktion), sonst entpackt der Return ein Ein-Element-Array.
# Array-Property normalisieren — WICHTIG inline (Zuweisung, KEIN Funktions-
# Return): ein leeres Array aus einer Funktion zurueckzugeben entpackt PS zu
# $null, was zu 'children: {}' statt '[]' fuehrt. Als Zuweisung bleibt @() ein @().
# $null -> @() (Graph-Schema: Collections sind Nullable=False)
# Einzelobjekt -> @(obj) (Ein-Element-Array wurde vom Roundtrip skalarisiert)
# leere/Whitespace-STRING-Elemente entfernen: ein PS-JSON-Roundtrip macht aus
# einer leeren Collection [] teils ""/[""] -> Graph lehnt das als
# 'Property children ... does not match schema' ab. Diese Keys tragen nie bare
# Strings -> gefahrlos filtern; wird die Collection dadurch leer, bleibt [].
if ($Node -is [System.Collections.IDictionary]) {
$out = [ordered]@{}
foreach ($k in @($Node.Keys)) {
@@ -240,7 +255,9 @@ function Repair-SettingsCatalogArrays {
if ($k -in $arrayKeys) {
if ($null -eq $fixed) { $fixed = @() }
elseif (-not ($fixed -is [System.Collections.IList])) { $fixed = @($fixed) }
$fixed = @($fixed | Where-Object { -not (($_ -is [string]) -and [string]::IsNullOrWhiteSpace($_)) })
}
elseif ($k -in $refKeys -and ($fixed -is [string])) { $fixed = $null }
$out[$k] = $fixed
}
return $out
@@ -252,7 +269,9 @@ function Repair-SettingsCatalogArrays {
if ($p.Name -in $arrayKeys) {
if ($null -eq $fixed) { $fixed = @() }
elseif (-not ($fixed -is [System.Collections.IList])) { $fixed = @($fixed) }
$fixed = @($fixed | Where-Object { -not (($_ -is [string]) -and [string]::IsNullOrWhiteSpace($_)) })
}
elseif ($p.Name -in $refKeys -and ($fixed -is [string])) { $fixed = $null }
$out[$p.Name] = $fixed
}
return $out
@@ -267,6 +286,43 @@ function Repair-SettingsCatalogArrays {
return $Node
}
# Entfernt rekursiv alle Properties mit $null-Wert. Configuration Profiles
# exportieren nicht genutzte Collection-Properties als null; beim POST lehnt Graph
# null fuer 'Collection(...)[Nullable=False]' ab (400 ModelValidationFailure, z.B.
# 'defenderAdditionalGuardedFolders'). Weggelassene Properties belegt Graph mit
# Defaults -> sicheres Strippen. Array-Typen werden am Parent wieder in @()
# gewrappt, damit ein Ein-Element-Array beim Return nicht zum Skalar entpackt wird.
function Remove-PolicyNullProps {
param($Node)
if ($Node -is [System.Collections.IDictionary]) {
$out = @{}
foreach ($k in @($Node.Keys)) {
$v = $Node[$k]
if ($null -eq $v) { continue }
$fixed = Remove-PolicyNullProps $v
if (($v -is [System.Collections.IEnumerable]) -and -not ($v -is [string]) -and -not ($v -is [System.Collections.IDictionary])) {
$out[$k] = @($fixed)
} else { $out[$k] = $fixed }
}
return $out
}
if ($Node -is [System.Management.Automation.PSCustomObject]) {
$out = @{}
foreach ($p in $Node.PSObject.Properties) {
if ($null -eq $p.Value) { continue }
$fixed = Remove-PolicyNullProps $p.Value
if (($p.Value -is [System.Collections.IEnumerable]) -and -not ($p.Value -is [string]) -and -not ($p.Value -is [System.Collections.IDictionary])) {
$out[$p.Name] = @($fixed)
} else { $out[$p.Name] = $fixed }
}
return $out
}
if (($Node -is [System.Collections.IEnumerable]) -and -not ($Node -is [string])) {
return @($Node | ForEach-Object { Remove-PolicyNullProps $_ })
}
return $Node
}
function New-DefaultComplianceScheduledActions {
# Compliance Policies verlangen beim Anlegen mindestens einen
# scheduledActionsForRule-Block, sonst antwortet Graph mit 400.
@@ -320,6 +376,8 @@ function Import-GraphConfigurationProfile {
if (-not $body['@odata.type']) {
throw 'Configuration Profile benoetigt @odata.type fuer den Import.'
}
# null-Properties strippen: Graph lehnt null fuer nicht-nullbare Collections ab.
$body = Remove-PolicyNullProps $body
$json = $body | ConvertTo-Json -Depth 50
return Invoke-MgGraphRequestRetry -Uri 'https://graph.microsoft.com/beta/deviceManagement/deviceConfigurations' -Method POST -Body $json -ContentType 'application/json'
}
@@ -350,6 +408,17 @@ function Import-GraphSettingsCatalogPolicy {
$body['settings'] = @()
}
$json = $body | ConvertTo-Json -Depth 50
# Korruptions-Check: enthaelt der Payload noch stringifizierte .NET-Objekte
# ("System.Collections.Hashtable" / "System.Object[]"), stammt die Quelldatei aus
# einem alten Export mit zu geringer ConvertTo-Json-Tiefe. *TemplateReference
# (optionale Metadaten) wurde oben bereits gerettet; verbleibende Marker sitzen in
# WERT-tragenden Feldern (z.B. groupSettingCollectionValue) -> echte Konfiguration
# ist verloren und nicht rekonstruierbar. Klar abbrechen statt kaputt zu importieren.
if ($json -match 'System\.Collections\.Hashtable|System\.Object\[\]') {
throw 'Quelldatei beschaedigt: Teile der Konfiguration wurden von einem alten Export (zu geringe JSON-Tiefe) zu ".ToString()" verstuemmelt und sind nicht wiederherstellbar. Bitte die Policy neu aus Graph exportieren und die frische Datei importieren.'
}
return Invoke-MgGraphRequestRetry -Uri 'https://graph.microsoft.com/beta/deviceManagement/configurationPolicies' -Method POST -Body $json -ContentType 'application/json'
}
@@ -669,6 +738,161 @@ function Invoke-PolicyAssignEndpoint {
return @{ ok = $true; assignedCount = $ok; results = @($results) }
}
# ============================================================
# Settings-Catalog-Policies zu EINER neuen Policy zusammenfuehren
# ============================================================
# settingDefinitionId eines Settings-Elements (Wrapper { settingInstance, id }).
function Get-SettingDefinitionId {
param($SettingElement)
$si = Get-PolicyProp $SettingElement 'settingInstance'
if (-not $si) { $si = $SettingElement }
return [string](Get-PolicyProp $si 'settingDefinitionId')
}
# Kanonische, stabil sortierte JSON-Darstellung der settingInstance -> Wert-Vergleich
# fuer die Konflikt-Erkennung (gleiche Definition, unterschiedlicher Wert = Konflikt).
function Get-SettingCanonicalJson {
param($SettingElement)
$si = Get-PolicyProp $SettingElement 'settingInstance'
if (-not $si) { $si = $SettingElement }
return ((ConvertTo-StableObject $si) | ConvertTo-Json -Depth 50 -Compress)
}
# Body: { ids:[...], mode:"preview"|"create", name?, description?, resolutions?:{ <defId>:<sourceId> } }
# Nur Settings Catalog. Fuehrt die 'settings' mehrerer Policies zu einer neuen zusammen.
# Gleiche settingDefinitionId + gleicher Wert -> einmal uebernommen. Gleiche Definition,
# anderer Wert -> Konflikt: Default gewinnt die zuerst gewaehlte Policy, per 'resolutions'
# ueberschreibbar. Import erfolgt als Neuanlage (nie Ueberschreiben).
function Invoke-PolicyConsolidateEndpoint {
param($Body)
try { Assert-GraphConnected } catch { return @{ __status = 401; error = 'Nicht mit Microsoft Graph verbunden' } }
$ids = @(Get-PolicyProp $Body 'ids') | Where-Object { $_ }
if (@($ids).Count -lt 2) { return @{ __status = 400; error = 'Bitte mindestens zwei Settings-Catalog-Policies auswaehlen.' } }
$mode = [string](Get-PolicyProp $Body 'mode'); if (-not $mode) { $mode = 'preview' }
$resolutions = Get-PolicyProp $Body 'resolutions'
# Details laden (Reihenfolge = Auswahlreihenfolge = Default-Konfliktgewinner)
$sources = @()
foreach ($id in $ids) {
$detail = $null
try { $detail = Get-GraphPolicyDetail -Type 'settingscatalog' -Id ([string]$id) } catch {}
if (-not $detail) { return @{ __status = 400; error = "Policy $id konnte nicht geladen werden." } }
$sources += @{
id = [string]$id
name = [string](Get-PolicyProp $detail 'name')
platforms = [string](Get-PolicyProp $detail 'platforms')
technologies = [string](Get-PolicyProp $detail 'technologies')
settings = @(Get-PolicyProp $detail 'settings')
}
}
# Plattform muss uebereinstimmen - sonst kein sinnvoller Merge.
$platforms = @($sources | ForEach-Object { $_.platforms } | Where-Object { $_ } | Sort-Object -Unique)
if ($platforms.Count -gt 1) {
return @{ __status = 400; error = "Unterschiedliche Plattformen ($($platforms -join ', ')) - Zusammenfuehren nicht moeglich." }
}
$mergedPlatform = if ($platforms.Count -ge 1) { $platforms[0] } else { 'windows10' }
# Technologies vereinen (Union).
$techSet = [ordered]@{}
foreach ($s in $sources) { foreach ($t in ($s.technologies -split ',')) { $tt = $t.Trim(); if ($tt) { $techSet[$tt] = $true } } }
$mergedTech = (@($techSet.Keys) -join ','); if (-not $mergedTech) { $mergedTech = 'mdm' }
# Nach settingDefinitionId gruppieren (Reihenfolge der Definitionen beibehalten).
$groups = [ordered]@{}
foreach ($s in $sources) {
foreach ($el in @($s.settings)) {
if (-not $el) { continue }
$defId = Get-SettingDefinitionId $el
if (-not $defId) { continue }
if (-not $groups.Contains($defId)) { $groups[$defId] = @() }
$groups[$defId] += @{ sourceId = $s.id; sourceName = $s.name; element = $el; canon = (Get-SettingCanonicalJson $el) }
}
}
$mergedSettings = @()
$conflicts = @()
foreach ($defId in @($groups.Keys)) {
$entries = @($groups[$defId])
$distinct = @($entries | Group-Object -Property { $_.canon })
if ($distinct.Count -eq 1) {
$mergedSettings += $entries[0].element
continue
}
# Konflikt: Gewinner bestimmen (resolutions[defId] = sourceId, sonst erste Quelle).
$resSource = if ($resolutions) { [string](Get-PolicyProp $resolutions $defId) } else { '' }
$chosen = $null
if ($resSource) { $chosen = @($entries | Where-Object { $_.sourceId -eq $resSource })[0] }
if (-not $chosen) { $chosen = $entries[0] }
$mergedSettings += $chosen.element
$conflicts += @{
settingDefinitionId = $defId
chosenSourceId = $chosen.sourceId
variants = @($distinct | ForEach-Object {
@{
sourceIds = @($_.Group | ForEach-Object { $_.sourceId })
sourceNames = @($_.Group | ForEach-Object { $_.sourceName } | Select-Object -Unique)
}
})
}
}
if ($mode -ne 'create') {
return @{
ok = $true
mode = 'preview'
platform = $mergedPlatform
technologies = $mergedTech
totalSettings = @($mergedSettings).Count
conflictCount = @($conflicts).Count
conflicts = @($conflicts)
sources = @($sources | ForEach-Object { @{ id = $_.id; name = $_.name; settingCount = @($_.settings).Count } })
}
}
# --- create ---
if ($script:State.ReadOnly) { return @{ __status = 403; error = 'Read-Only-Modus: Zusammenfuehren ist deaktiviert.' } }
$name = [string](Get-PolicyProp $Body 'name')
if ([string]::IsNullOrWhiteSpace($name)) { return @{ __status = 400; error = 'Name fuer die neue Policy fehlt.' } }
$desc = [string](Get-PolicyProp $Body 'description')
# settings fuer den POST vorbereiten: Wrapper mit @odata.type, read-only 'id' weg,
# Arrays reparieren (gleiche Behandlung wie beim Import).
$outSettings = @()
foreach ($el in $mergedSettings) {
$si = Get-PolicyProp $el 'settingInstance'
if (-not $si) { $si = $el }
$outSettings += [ordered]@{
'@odata.type' = '#microsoft.graph.deviceManagementConfigurationSetting'
settingInstance = $si
}
}
$outSettings = @(Repair-SettingsCatalogArrays $outSettings)
$newBody = [ordered]@{
name = $name
description = $desc
platforms = $mergedPlatform
technologies = $mergedTech
templateReference = @{ templateFamily = 'none'; templateId = '' }
settings = $outSettings
}
$json = $newBody | ConvertTo-Json -Depth 50
if ($json -match 'System\.Collections\.Hashtable|System\.Object\[\]') {
return @{ __status = 500; error = 'Interner Serialisierungsfehler beim Zusammenfuehren (stringifizierte Objekte).' }
}
try {
$created = Invoke-MgGraphRequestRetry -Uri 'https://graph.microsoft.com/beta/deviceManagement/configurationPolicies' -Method POST -Body $json -ContentType 'application/json'
return @{ ok = $true; mode = 'create'; newId = [string](Get-PolicyProp $created 'id'); name = $name; settingsCount = @($outSettings).Count; conflictCount = @($conflicts).Count }
} catch {
$msg = $_.Exception.Message
try { if ($_.ErrorDetails.Message) { $msg = $_.ErrorDetails.Message } } catch {}
return @{ __status = 500; error = $msg }
}
}
# ============================================================
# Policy-Snapshot nach Git (voller Export, stabile Dateinamen)
# ============================================================
@@ -692,9 +916,27 @@ function ConvertTo-StableObject {
return $InputObject
}
# git muss nicht im PATH des Server-Prozesses liegen (haeufig, wenn der Server vor
# der Git-Installation gestartet wurde oder mit eingefrorener Umgebung laeuft).
# Erst PATH probieren, dann bekannte Installationsorte. Ergebnis wird gecacht.
function Get-GitExe {
if ($script:GitExe -and (Test-Path $script:GitExe)) { return $script:GitExe }
$cmd = Get-Command git -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($cmd) { $script:GitExe = $cmd.Source; return $script:GitExe }
$cands = @()
if ($env:ProgramFiles) { $cands += (Join-Path $env:ProgramFiles 'Git\cmd\git.exe') }
if (${env:ProgramFiles(x86)}) { $cands += (Join-Path ${env:ProgramFiles(x86)} 'Git\cmd\git.exe') }
if ($env:LOCALAPPDATA) { $cands += (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe') }
if ($env:LOCALAPPDATA) { $cands += (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Links\git.exe') }
foreach ($c in $cands) { if ($c -and (Test-Path $c)) { $script:GitExe = $c; return $c } }
return $null
}
function Invoke-Git {
param([Parameter(Mandatory=$true)][string]$RepoPath, [Parameter(Mandatory=$true)][string[]]$GitArgs)
$out = & git -C $RepoPath @GitArgs 2>&1
$exe = Get-GitExe
if (-not $exe) { return @{ exit = 9009; out = 'git nicht gefunden (weder im PATH noch an bekannten Installationsorten).' } }
$out = & $exe -C $RepoPath @GitArgs 2>&1
return @{ exit = $LASTEXITCODE; out = (@($out) -join "`n").Trim() }
}
@@ -717,9 +959,10 @@ function Invoke-PolicyGitSnapshotEndpoint {
return @{ __status = 400; error = 'Kein Git-Repo-Pfad konfiguriert (Einstellungen -> Policy-Backup).' }
}
# git verfuegbar?
try { $null = & git --version 2>&1; if ($LASTEXITCODE -ne 0) { throw 'x' } }
catch { return @{ __status = 500; error = 'git ist nicht installiert oder nicht im PATH.' } }
# git verfuegbar? (PATH + bekannte Installationsorte)
if (-not (Get-GitExe)) {
return @{ __status = 500; error = 'git ist nicht auffindbar (weder im PATH des Server-Prozesses noch an den Standard-Installationsorten). Ggf. Server nach der Git-Installation neu starten.' }
}
# Repo-Ordner + .git sicherstellen
if (-not (Test-Path $repo)) { New-Item -ItemType Directory -Path $repo -Force | Out-Null }
+656 -62
View File
@@ -11,7 +11,7 @@ const State = {
targets: [],
selectedTargetIds: new Set(),
apps: [],
appFilter: { search: '', preset: 'all', category: '', onlyMember: false, hideNative: false, modFrom: '', modTo: '' },
appFilter: { search: '', preset: 'all', platform: 'all', category: '', onlyMember: false, hideNative: false, modFrom: '', modTo: '' },
session: [],
membershipCache: new Map(),
loadedModes: new Set(),
@@ -432,6 +432,13 @@ document.querySelectorAll('.seg').forEach(seg => {
search.value = '';
search.focus();
try { search.setSelectionRange(0, 0); } catch {}
} else if (newMode === 'dept') {
// Gruppen-Modus: Live-Suche ueber ALLE Gruppen (min. 2 Zeichen), kein Praefix-Filter
search.placeholder = 'Gruppe suchen...';
hint.classList.remove('hidden');
search.value = '';
search.focus();
try { search.setSelectionRange(0, 0); } catch {}
} else {
search.placeholder = 'Filtern...';
hint.classList.add('hidden');
@@ -441,8 +448,9 @@ document.querySelectorAll('.seg').forEach(seg => {
renderTargets();
onTargetSelectionChange();
// Auto-Load nur wenn fuer diesen Mode noch nichts geladen wurde UND es kein User-Mode ist
if (State.connected && newMode !== 'user' && !State.loadedModes.has(newMode) && State.targets.length === 0) {
// Auto-Load nur fuer Listen-Modi (RPA). 'dept' (Gruppensuche) und 'user'
// laden erst bei Sucheingabe.
if (State.connected && newMode === 'rpa' && !State.loadedModes.has(newMode) && State.targets.length === 0) {
loadTargets({ silent: false });
}
});
@@ -461,6 +469,14 @@ document.getElementById('btnReloadTargets').addEventListener('click', () => {
return;
}
runUserSearch(term);
} else if (State.mode === 'dept') {
const term = document.getElementById('targetSearch').value;
if (!term || term.length < 2) {
document.getElementById('targetSearch').focus();
toast('Tippe mind. 2 Zeichen für die Gruppensuche', 'warn');
return;
}
runGroupSearch(term);
} else {
State.loadedModes.delete(State.mode);
loadTargets({ silent: false });
@@ -470,16 +486,20 @@ document.getElementById('btnReloadTargets').addEventListener('click', () => {
document.getElementById('targetSearch').addEventListener('input', e => {
if (State.mode === 'user') {
debouncedUserSearch(e.target.value);
} else if (State.mode === 'dept') {
debouncedGroupSearch(e.target.value);
} else {
renderTargets();
}
});
// Enter key triggers explicit user search
// Enter loest die Server-Suche sofort aus (Benutzer- und Gruppen-Modus)
document.getElementById('targetSearch').addEventListener('keydown', e => {
if (e.key === 'Enter' && State.mode === 'user') {
const term = e.target.value;
if (term && term.length >= 2) runUserSearch(term);
if (e.key !== 'Enter') return;
const term = e.target.value;
if (term && term.length >= 2) {
if (State.mode === 'user') runUserSearch(term);
else if (State.mode === 'dept') runGroupSearch(term);
}
});
@@ -576,6 +596,77 @@ async function runUserSearch(term) {
}
}
// ── Gruppen-Live-Suche: durchsucht ALLE Gruppen (nicht nur Praefix-Gruppen) ──
let groupSearchTimer = null;
let groupSearchAbort = null;
let groupSearchCache = { query: '', results: [] };
// Bereits ausgewaehlte Gruppen in ein neues Ergebnis mergen, damit die Auswahl
// (und die Namen in der Pinned-Leiste) ueber mehrere Suchen hinweg bestehen bleibt.
function mergeSelectedGroups(results) {
const ids = new Set(results.map(r => r.Id));
const keep = State.targets.filter(t => State.selectedTargetIds.has(t.Id) && !ids.has(t.Id));
return keep.length ? results.concat(keep) : results;
}
function debouncedGroupSearch(term) {
clearTimeout(groupSearchTimer);
const t = (term || '').trim();
if (t.length < 2) {
// Unter 2 Zeichen: nur die ausgewaehlten Gruppen stehen lassen (Auswahl behalten)
State.targets = State.targets.filter(x => State.selectedTargetIds.has(x.Id));
groupSearchCache = { query: '', results: [] };
renderTargets();
return;
}
// Optimistisch lokal verfeinern, wenn die neue Anfrage die vorige praezisiert
const lower = t.toLowerCase();
const cachedLower = groupSearchCache.query.toLowerCase();
if (cachedLower && lower.startsWith(cachedLower) && groupSearchCache.results.length > 0) {
const filtered = groupSearchCache.results.filter(g => (g.DisplayName || '').toLowerCase().includes(lower));
State.targets = mergeSelectedGroups(filtered);
renderTargets();
return;
}
groupSearchTimer = setTimeout(() => runGroupSearch(t), 220);
}
async function runGroupSearch(term) {
if (!State.connected) { toast('Bitte zuerst verbinden', 'warn'); return; }
if (groupSearchAbort) { try { groupSearchAbort.abort(); } catch {} }
groupSearchAbort = new AbortController();
const signal = groupSearchAbort.signal;
document.getElementById('targetList').innerHTML = `
<div class="skeleton">
<div class="sk-line med"></div>
<div class="sk-line short"></div>
<div class="sk-line med"></div>
</div>`;
try {
const resp = await fetch('/api/groups/search?q=' + encodeURIComponent(term), {
headers: { 'Content-Type': 'application/json' },
signal,
});
let data = {};
try { data = await resp.json(); } catch {}
if (signal.aborted) return;
if (!resp.ok) throw new Error(data.error || `HTTP ${resp.status}`);
const results = data.items || [];
groupSearchCache = { query: term, results: results.slice() };
State.targets = mergeSelectedGroups(results);
renderTargets();
onTargetSelectionChange();
if (results.length === 0) toast(`Keine Gruppen für "${term}" gefunden`, 'warn');
} catch (e) {
if (e.name === 'AbortError') return; // neue Suche laeuft schon
toast(e.message, 'err', 'Gruppensuche fehlgeschlagen');
renderTargets();
}
}
let loadTargetsInFlight = null; // welcher Mode laeuft gerade
async function loadTargets(opts = {}) {
@@ -589,12 +680,19 @@ async function loadTargets(opts = {}) {
}
return runUserSearch(term);
}
// 'dept' (Gruppen) ist suchbasiert — kein Listen-Load. Bei vorhandener Eingabe
// die Suche ausloesen, sonst nichts tun (auch beim Auto-Load nach Connect).
if (State.mode === 'dept') {
const term = document.getElementById('targetSearch').value;
if (term && term.length >= 2) return runGroupSearch(term);
return;
}
const requestedMode = State.mode;
if (loadTargetsInFlight === requestedMode) return; // gleiche Anfrage laeuft bereits
loadTargetsInFlight = requestedMode;
if (!opts.silent) setLoading('Lade ' + (requestedMode === 'rpa' ? 'RPA-Gruppen' : 'Abteilungen') + '...');
if (!opts.silent) setLoading('Lade ' + (requestedMode === 'rpa' ? 'RPA-Gruppen' : 'Gruppen') + '...');
document.getElementById('targetList').innerHTML = `
<div class="skeleton">
<div class="sk-line med"></div>
@@ -619,7 +717,7 @@ async function loadTargets(opts = {}) {
});
renderTargets();
onTargetSelectionChange();
if (!opts.silent) toast(`${res.count} ${requestedMode === 'rpa' ? 'RPA-Gruppen' : 'Abteilungen'} geladen`, 'ok');
if (!opts.silent) toast(`${res.count} ${requestedMode === 'rpa' ? 'RPA-Gruppen' : 'Gruppen'} geladen`, 'ok');
} catch (e) {
if (State.mode === requestedMode) {
toast(e.message, 'err', 'Laden fehlgeschlagen');
@@ -633,7 +731,8 @@ async function loadTargets(opts = {}) {
function getFilteredTargets() {
const q = document.getElementById('targetSearch').value.toLowerCase().trim();
if (!q || State.mode === 'user') return State.targets;
// 'user' und 'dept' werden serverseitig gesucht -> State.targets ist bereits das Ergebnis.
if (!q || State.mode === 'user' || State.mode === 'dept') return State.targets;
return State.targets.filter(t =>
(t.DisplayName || '').toLowerCase().includes(q) ||
(t.UserPrincipalName || '').toLowerCase().includes(q)
@@ -656,13 +755,17 @@ function renderTargets() {
}
if (filtered.length === 0) {
if (State.mode === 'user') {
if (State.mode === 'user' || State.mode === 'dept') {
const term = document.getElementById('targetSearch').value;
const isUser = State.mode === 'user';
const has2 = term && term.length >= 2;
list.innerHTML = emptyState({
title: term && term.length >= 2 ? 'Keine Treffer' : 'Benutzer suchen',
text: term && term.length >= 2
? `Keine Benutzer für "${escapeHtml(term)}" gefunden.`
: 'Tippe mind. 2 Zeichen — Name, UPN oder E-Mail.',
title: has2 ? 'Keine Treffer' : (isUser ? 'Benutzer suchen' : 'Gruppe suchen'),
text: has2
? `Keine ${isUser ? 'Benutzer' : 'Gruppen'} für "${escapeHtml(term)}" gefunden.`
: (isUser
? 'Tippe mind. 2 Zeichen — Name, UPN oder E-Mail.'
: 'Tippe mind. 2 Zeichen — durchsucht alle Gruppen im Tenant.'),
});
} else {
list.innerHTML = emptyState({
@@ -776,7 +879,7 @@ function renderPinnedTargets() {
}
wrap.classList.remove('hidden');
const modeLabels = { dept: 'Abt', rpa: 'RPA', user: 'User' };
const modeLabels = { dept: 'Grp', rpa: 'RPA', user: 'User' };
const chips = items.map(it => {
const isEmpty = it.hasMembers === false ? 'pin-empty' : '';
const title = `${it.name}${it.meta ? ' · ' + it.meta : ''} (${modeLabels[it.mode] || it.mode}) — Klick: zur Zeile springen, X: entfernen`;
@@ -865,6 +968,10 @@ document.getElementById('appFilter').addEventListener('change', e => {
State.appFilter.preset = e.target.value;
renderApps();
});
document.getElementById('appPlatformFilter')?.addEventListener('change', e => {
State.appFilter.platform = e.target.value;
renderApps();
});
document.getElementById('appCategoryFilter').addEventListener('change', e => {
State.appFilter.category = e.target.value;
renderApps();
@@ -1008,6 +1115,13 @@ function getFilteredApps() {
let list = State.apps.slice();
const f = State.appFilter;
if (f.search) list = list.filter(a => (a.AppName || '').toLowerCase().includes(f.search));
// Plattform-Filter ueber den rohen @odata.type: macOS-Typen enthalten "macos"
// (z.B. macOSDmgApp, macOsVppApp), alles uebrige ist Windows (iOS/Android sind
// bereits serverseitig ausgeschlossen).
if (f.platform && f.platform !== 'all') {
const isMac = a => (a.AppTypeRaw || '').toLowerCase().includes('macos');
list = f.platform === 'macos' ? list.filter(isMac) : list.filter(a => !isMac(a));
}
switch (f.preset) {
case 'none': list = list.filter(a => a.AvailableCount === 0 && a.RequiredCount === 0); break;
case 'available': list = list.filter(a => a.AvailableCount > 0 && a.RequiredCount === 0); break;
@@ -1694,6 +1808,12 @@ async function jumpToAppById(appId) {
// Suchfeld leeren damit die App garantiert sichtbar ist
const search = document.getElementById('appSearch');
if (search && search.value) { search.value = ''; State.appFilter.search = ''; }
// Plattform-Filter zuruecksetzen, sonst koennte die Ziel-App ausgeblendet sein
if (State.appFilter.platform !== 'all') {
State.appFilter.platform = 'all';
const pf = document.getElementById('appPlatformFilter');
if (pf) pf.value = 'all';
}
// WICHTIG: Wenn die App noch nicht expanded ist, muessen wir den DETAILS-
// FETCH triggern. Frueher haben wir nur expandedApps.add() gemacht — ohne
@@ -2156,7 +2276,7 @@ function toggleSession({ appId, groupId, groupName, type }) {
return;
}
if (allSel.length === 0) {
toast('Wähle erst Abteilungen oder Benutzer aus', 'warn');
toast('Wähle erst Gruppen oder Benutzer aus', 'warn');
return;
}
@@ -2441,7 +2561,7 @@ async function applyAssignments() {
document.getElementById('confirmText').innerHTML = `
<strong>${total}</strong> Vorgang${total === 1 ? '' : 'e'} wird ausgeführt:
<ul style="margin: 8px 0 0 18px; line-height: 1.6;">
${deptOps > 0 ? `<li><strong>${deptOps}</strong> auf Abteilungsgruppen</li>` : ''}
${deptOps > 0 ? `<li><strong>${deptOps}</strong> auf Gruppen</li>` : ''}
${userOps > 0 ? `<li><strong>${userOps}</strong> auf Einzelbenutzer</li>` : ''}
</ul>`;
openModal('modalConfirm');
@@ -2662,17 +2782,19 @@ function getCurrentCgMode() {
return el ? el.value : 'req-group';
}
// Modus -> { intent, isGroup, target } — single source of truth
// Modus -> { intent, isGroup, isExisting, target } — single source of truth
function cgModeMeta(mode) {
switch (mode) {
case 'req-group': return { intent: 'required', isGroup: true, target: null };
case 'req-allusers': return { intent: 'required', isGroup: false, target: 'ALL_USERS' };
case 'req-alldevices': return { intent: 'required', isGroup: false, target: 'ALL_DEVICES' };
case 'avail-group': return { intent: 'available', isGroup: true, target: null };
case 'avail-allusers': return { intent: 'available', isGroup: false, target: 'ALL_USERS' };
case 'avail-alldevices':return { intent: 'available', isGroup: false, target: 'ALL_DEVICES' };
case 'req-group': return { intent: 'required', isGroup: true, isExisting: false, target: null };
case 'req-existing': return { intent: 'required', isGroup: false, isExisting: true, target: null };
case 'req-allusers': return { intent: 'required', isGroup: false, isExisting: false, target: 'ALL_USERS' };
case 'req-alldevices': return { intent: 'required', isGroup: false, isExisting: false, target: 'ALL_DEVICES' };
case 'avail-group': return { intent: 'available', isGroup: true, isExisting: false, target: null };
case 'avail-existing': return { intent: 'available', isGroup: false, isExisting: true, target: null };
case 'avail-allusers': return { intent: 'available', isGroup: false, isExisting: false, target: 'ALL_USERS' };
case 'avail-alldevices':return { intent: 'available', isGroup: false, isExisting: false, target: 'ALL_DEVICES' };
}
return { intent: 'required', isGroup: true, target: null };
return { intent: 'required', isGroup: true, isExisting: false, target: null };
}
function openCreateGroupModal(appId, appName) {
@@ -2720,6 +2842,7 @@ function openCreateGroupModal(appId, appName) {
}
}
document.getElementById('cgAssignToApp').checked = true;
resetCgExisting();
applyCgModeUi();
openModal('modalCreateGroup');
}
@@ -2731,12 +2854,20 @@ function applyCgModeUi() {
const meta = cgModeMeta(mode);
const nameGroup = document.getElementById('cgGroupNameGroup');
const assignWrap = document.getElementById('cgAssignToAppWrap');
const existingGroup = document.getElementById('cgExistingGroup');
const createBtn = document.getElementById('cgCreate');
const intentLabel = meta.intent === 'available' ? 'Available' : 'Required';
if (meta.isGroup) {
if (meta.isExisting) {
// Bestehende Gruppe(n) suchen + zuweisen (Mehrfachauswahl)
nameGroup.hidden = true;
assignWrap.hidden = true;
if (existingGroup) existingGroup.hidden = false;
renderCgSelected(); // setzt Button-Label + disabled anhand der Auswahl
} else if (meta.isGroup) {
nameGroup.hidden = false;
assignWrap.hidden = false;
if (existingGroup) existingGroup.hidden = true;
document.getElementById('cgGroupName').value = suggestedGroupName(createGroupContext.appName, meta.intent);
document.querySelector('#cgAssignToAppWrap span').textContent =
`Gruppe direkt der App als ${intentLabel} zuweisen`;
@@ -2745,6 +2876,7 @@ function applyCgModeUi() {
} else {
nameGroup.hidden = true;
assignWrap.hidden = true;
if (existingGroup) existingGroup.hidden = true;
createBtn.disabled = false;
const tgtLbl = meta.target === 'ALL_USERS' ? 'All Users' : 'All Devices';
createBtn.textContent = `Als ${intentLabel} für ${tgtLbl} zuweisen`;
@@ -2755,6 +2887,110 @@ document.querySelectorAll('input[name="cgMode"]').forEach(r => {
r.addEventListener('change', applyCgModeUi);
});
// ── "Bestehende Gruppe" — Mehrfach-Suche + -Auswahl im Zuweisungs-Dialog ──
let cgExistingTimer = null;
let cgExistingAbort = null;
function cgSelectedGroups() {
if (!createGroupContext) return [];
if (!Array.isArray(createGroupContext.selectedGroups)) createGroupContext.selectedGroups = [];
return createGroupContext.selectedGroups;
}
function resetCgExisting() {
if (createGroupContext) createGroupContext.selectedGroups = [];
const s = document.getElementById('cgExistingSearch');
const r = document.getElementById('cgExistingResults');
if (s) s.value = '';
if (r) r.innerHTML = '';
renderCgSelected();
}
// Ausgewaehlte Gruppen als entfernbare Chips zeigen + Button-Status/Label setzen.
function renderCgSelected() {
const sel = document.getElementById('cgExistingSelected');
const groups = cgSelectedGroups();
if (sel) {
sel.className = 'cg-existing-chips';
sel.innerHTML = groups.length === 0
? '<span class="form-hint">Noch keine Gruppe ausgewählt.</span>'
: groups.map(g =>
`<span class="cg-chip" title="${escapeHtml(g.name)}">
<span class="cg-chip-name">${escapeHtml(g.name)}</span>
<button type="button" class="cg-chip-x" data-remove-id="${escapeHtml(g.id)}" aria-label="Entfernen">×</button>
</span>`).join('');
}
// Nur im "Bestehende Gruppe"-Modus den Erstellen/Zuweisen-Button steuern.
const meta = cgModeMeta(getCurrentCgMode());
if (meta.isExisting) {
const btn = document.getElementById('cgCreate');
const intentLabel = meta.intent === 'available' ? 'Available' : 'Required';
btn.disabled = groups.length === 0;
btn.textContent = groups.length > 1
? `${groups.length} Gruppen als ${intentLabel} zuweisen`
: `Als ${intentLabel} zuweisen`;
}
}
document.getElementById('cgExistingSearch')?.addEventListener('input', e => {
clearTimeout(cgExistingTimer);
const term = e.target.value.trim();
const results = document.getElementById('cgExistingResults');
if (term.length < 2) { if (results) results.innerHTML = ''; return; }
cgExistingTimer = setTimeout(() => runCgExistingSearch(term), 250);
});
async function runCgExistingSearch(term) {
const results = document.getElementById('cgExistingResults');
if (!results) return;
if (cgExistingAbort) { try { cgExistingAbort.abort(); } catch {} }
cgExistingAbort = new AbortController();
results.innerHTML = '<div class="cg-existing-empty">Suche…</div>';
try {
const resp = await fetch('/api/groups/search?q=' + encodeURIComponent(term), { signal: cgExistingAbort.signal });
let data = {}; try { data = await resp.json(); } catch {}
if (cgExistingAbort.signal.aborted) return;
if (!resp.ok) throw new Error(data.error || `HTTP ${resp.status}`);
const items = data.items || [];
if (items.length === 0) { results.innerHTML = '<div class="cg-existing-empty">Keine Treffer</div>'; return; }
const selIds = new Set(cgSelectedGroups().map(g => g.id));
results.innerHTML = items.map(g =>
`<button type="button" class="cg-existing-item${selIds.has(String(g.Id)) ? ' is-selected' : ''}" data-id="${escapeHtml(g.Id)}" data-name="${escapeHtml(g.DisplayName)}">
<span class="cg-existing-name">${escapeHtml(g.DisplayName)}</span>
${g.Description ? `<span class="cg-existing-desc">${escapeHtml(g.Description)}</span>` : ''}
</button>`).join('');
} catch (e) {
if (e.name === 'AbortError') return;
results.innerHTML = `<div class="cg-existing-empty">Fehler: ${escapeHtml(e.message)}</div>`;
}
}
// Ergebnis anklicken -> Auswahl togglen (Mehrfachauswahl)
document.getElementById('cgExistingResults')?.addEventListener('click', e => {
const btn = e.target.closest('.cg-existing-item');
if (!btn) return;
const id = btn.dataset.id, name = btn.dataset.name;
const groups = cgSelectedGroups();
const idx = groups.findIndex(g => g.id === id);
if (idx >= 0) { groups.splice(idx, 1); btn.classList.remove('is-selected'); }
else { groups.push({ id, name }); btn.classList.add('is-selected'); }
renderCgSelected();
});
// Chip entfernen -> Auswahl abwaehlen (und ggf. Ergebnis-Item entmarkieren)
document.getElementById('cgExistingSelected')?.addEventListener('click', e => {
const x = e.target.closest('[data-remove-id]');
if (!x) return;
const id = x.dataset.removeId;
const groups = cgSelectedGroups();
const idx = groups.findIndex(g => g.id === id);
if (idx >= 0) groups.splice(idx, 1);
document.querySelectorAll('.cg-existing-item').forEach(it => {
if (it.dataset.id === id) it.classList.remove('is-selected');
});
renderCgSelected();
});
document.getElementById('cgGroupName').addEventListener('input', () => {
clearTimeout(cgCheckTimer);
cgCheckTimer = setTimeout(checkGroupName, 400);
@@ -2793,6 +3029,30 @@ document.getElementById('cgCreate').addEventListener('click', async () => {
if (!createGroupContext) return;
const meta = cgModeMeta(getCurrentCgMode());
if (meta.isExisting) {
// Bestehende Gruppe(n) zuweisen — EIN Request mit allen Zielen. Das Backend
// mergt die neuen Gruppen mit den bestehenden Zuweisungen (die /assign-Action
// ersetzt sonst die komplette Liste -> nur die letzte Gruppe bliebe uebrig).
const groups = cgSelectedGroups();
if (groups.length === 0) { toast('Bitte zuerst mind. eine Gruppe auswählen', 'warn'); return; }
const intentLabel = meta.intent === 'available' ? 'Available' : 'Required';
setLoading(`Weise ${groups.length} Gruppe(n) als ${intentLabel} zu...`);
try {
await api(`/api/apps/${encodeURIComponent(createGroupContext.appId)}/assignments`, {
method: 'POST',
body: { intent: meta.intent, targets: groups.map(g => g.id) },
});
toast(`${groups.length} ${intentLabel}-Zuweisung(en) hinzugefügt`, 'ok');
closeModal('modalCreateGroup');
await loadApps(true);
} catch (e) {
toast(e.message, 'err', 'Zuweisung fehlgeschlagen');
} finally {
clearLoading();
}
return;
}
if (meta.isGroup) {
// Gruppe erstellen + zuweisen
const { prefix, suffix } = getNamingFor(meta.intent);
@@ -3057,6 +3317,7 @@ function membersTabLink(id, name) {
return `<a class="entra-link members-link" href="${url}" target="_blank" rel="noopener" title="Mitglieder von ${escapeHtml(name || 'Gruppe')} im Intune-Portal öffnen" onclick="event.stopPropagation()">${MEMBERS_ICON}</a>`;
}
function teamsChatLink(upn, name) {
// Microsoft-Teams Deep-Link: oeffnet IMMER den installierten Desktop-Client
// ueber den msteams:-Protocol-Handler. Web-Variante (https://) wird hier
@@ -3303,7 +3564,7 @@ function applyExpandedSelection(groupId) {
renderTargets();
onTargetSelectionChange();
toast(`${picked.length} Benutzer aus "${entry.name}" übernommen — Abteilungs-Auswahl bleibt erhalten`, 'ok');
toast(`${picked.length} Benutzer aus "${entry.name}" übernommen — Gruppen-Auswahl bleibt erhalten`, 'ok');
}
// (Alte Modal-Logik — unbenutzt, aber harmlos:)
@@ -4565,6 +4826,7 @@ const GexState = {
activeTab: 'export',
userSearchResults: [],
selectedUsers: new Map(),
addMode: 'user', // 'user' | 'group' — was im "Hinzufuegen"-Pane gesucht/addiert wird
};
function openGroupExportModal() {
@@ -4583,7 +4845,13 @@ function openGroupExportModal() {
document.getElementById('gexMembersTitle').textContent = 'Mitglieder';
document.getElementById('gexStats').textContent = '';
document.getElementById('gexExportBtn').disabled = true;
// Add-Tab zurücksetzen
// Add-Tab zurücksetzen (Modus auf Benutzer)
GexState.addMode = 'user';
document.querySelectorAll('.gex-addmode-btn').forEach(b => b.classList.toggle('active', b.dataset.addmode === 'user'));
const gexAddTitle = document.getElementById('gexAddSearchTitle');
if (gexAddTitle) gexAddTitle.textContent = 'Benutzer suchen';
const gexUS = document.getElementById('gexUserSearch');
if (gexUS) gexUS.placeholder = 'Name, UPN oder E-Mail…';
document.getElementById('gexUserSearch').value = '';
document.getElementById('gexUserResults').innerHTML = '<div class="gex-hint">Mindestens 2 Zeichen eingeben.</div>';
document.getElementById('gexSelectedUsers').innerHTML = '<div class="gex-hint">Noch keine Benutzer ausgewählt.</div>';
@@ -4961,14 +5229,49 @@ document.getElementById('gexUserSearch')?.addEventListener('input', e => {
async function _gexDoUserSearch(q) {
try {
const data = await api(`/api/users?q=${encodeURIComponent(q)}`);
GexState.userSearchResults = data.items || [];
if (GexState.addMode === 'group') {
// Gruppen suchen; die Zielgruppe selbst rausfiltern. UPN-Feld traegt zur
// Anzeige die Beschreibung bzw. "Gruppe" (nur fuers Rendering, Add nutzt Id).
const data = await api(`/api/groups/search?q=${encodeURIComponent(q)}`);
const targetId = GexState.selectedGroup ? GexState.selectedGroup.Id : null;
GexState.userSearchResults = (data.items || [])
.filter(g => g.Id !== targetId)
.map(g => ({ Id: g.Id, DisplayName: g.DisplayName, UserPrincipalName: g.Description || 'Gruppe', _isGroup: true }));
} else {
const data = await api(`/api/users?q=${encodeURIComponent(q)}`);
GexState.userSearchResults = data.items || [];
}
_gexRenderUserResults();
} catch (e) {
document.getElementById('gexUserResults').innerHTML = `<div class="gex-error">Suche fehlgeschlagen: ${escapeHtml(e.message)}</div>`;
}
}
// Umschalter Benutzer/Gruppen im "Hinzufuegen"-Pane.
document.querySelectorAll('.gex-addmode-btn').forEach(btn => {
btn.addEventListener('click', () => {
const mode = btn.dataset.addmode;
if (GexState.addMode === mode) return;
GexState.addMode = mode;
document.querySelectorAll('.gex-addmode-btn').forEach(b => b.classList.toggle('active', b === btn));
// Auswahl + Suche zuruecksetzen
GexState.selectedUsers.clear();
GexState.userSearchResults = [];
_gexRenderSelectedUsers();
_gexUpdateAddBtn();
const search = document.getElementById('gexUserSearch');
if (search) search.value = '';
const isGroup = mode === 'group';
const title = document.getElementById('gexAddSearchTitle');
if (title) title.textContent = isGroup ? 'Gruppen suchen' : 'Benutzer suchen';
if (search) search.placeholder = isGroup ? 'Gruppenname…' : 'Name, UPN oder E-Mail…';
document.getElementById('gexUserResults').innerHTML = '<div class="gex-hint">Mindestens 2 Zeichen eingeben.</div>';
const selHint = document.getElementById('gexSelectedUsers');
if (selHint) selHint.innerHTML = `<div class="gex-hint">Noch keine ${isGroup ? 'Gruppen' : 'Benutzer'} ausgewählt.</div>`;
if (search) search.focus();
});
});
function _gexRenderUserResults() {
const el = document.getElementById('gexUserResults');
if (!el) return;
@@ -5049,10 +5352,11 @@ document.getElementById('gexAddBtn')?.addEventListener('click', async () => {
method: 'POST',
body: { userIds },
});
const kindLbl = GexState.addMode === 'group' ? 'Gruppe(n)' : 'Benutzer';
if (data.errors > 0) {
toast(`${data.success} von ${data.total} hinzugefügt, ${data.errors} Fehler.`, 'warn');
} else {
toast(`${data.success} Benutzer zu „${GexState.selectedGroup.DisplayName}" hinzugefügt.`, 'ok');
toast(`${data.success} ${kindLbl} zu „${GexState.selectedGroup.DisplayName}" hinzugefügt.`, 'ok');
GexState.selectedUsers.clear();
_gexRenderSelectedUsers();
document.getElementById('gexUserSearch').value = '';
@@ -5465,12 +5769,14 @@ function notifyCsvImportGroupSelected(groupId, groupName) {
// Geräte-Tab
// ============================================================
const DevState = {
items: [],
items: [], // aktuell geladener Satz (bei Gruppe: alle Geraete der Gruppe)
filtered: [],
selected: null,
sortCol: 'deviceName',
sortAsc: true,
loaded: false
loaded: false,
groupId: null, // aktiver Gruppen-Filter (null = alle Geraete)
groupName: ''
};
async function devLoadAll() {
@@ -5483,38 +5789,97 @@ function devShowLoading(on) {
}
async function devFetch() {
const q = document.getElementById('devSearch').value.trim();
const os = document.getElementById('devOsFilter').value;
const cmp = document.getElementById('devComplianceFilter').value;
devShowLoading(true);
try {
const params = new URLSearchParams();
if (q) params.set('q', q);
if (os) params.set('os', os);
if (cmp) params.set('compliance', cmp);
const data = await api('/api/devices?' + params.toString());
DevState.items = data.items || [];
DevState.filtered = DevState.items;
devSort();
if (DevState.groupId) {
// Gruppen-Modus: alle Geraete der Gruppen-User holen, dann clientseitig filtern.
const data = await api(`/api/groups/${encodeURIComponent(DevState.groupId)}/devices/export`, { timeoutMs: 180000 });
DevState.items = data.items || [];
if (DevState.items.length === 0 && (data.errors || []).length) {
toast(`Graph-Fehler: ${data.errors[0]}`, 'err', 'Geräte');
}
devApplyClientFilters(); // sortiert + rendert
} else {
const q = document.getElementById('devSearch').value.trim();
const os = document.getElementById('devOsFilter').value;
const cmp = document.getElementById('devComplianceFilter').value;
const params = new URLSearchParams();
if (q) params.set('q', q);
if (os) params.set('os', os);
if (cmp) params.set('compliance', cmp);
const data = await api('/api/devices?' + params.toString());
DevState.items = data.items || [];
DevState.filtered = DevState.items;
devSort();
}
} catch (e) {
toast('Geräte konnten nicht geladen werden: ' + e, 'error');
toast('Geräte konnten nicht geladen werden: ' + (e.message || e), 'error');
} finally {
devShowLoading(false);
}
}
// Ein Geraet gegen die aktuellen UI-Filter pruefen (fuer den Gruppen-Modus,
// wo serverseitig nicht gefiltert wird).
function devPassesFilters(d, q, os, cmp) {
if (os && !(d.OS || '').toLowerCase().includes(os.toLowerCase())) return false;
if (cmp && (d.ComplianceState || '') !== cmp) return false;
if (q) {
const hay = `${d.DeviceName || ''} ${d.UserDisplayName || ''} ${d.UserPrincipalName || ''} ${d.SerialNumber || ''}`.toLowerCase();
if (!hay.includes(q)) return false;
}
return true;
}
function devApplyClientFilters() {
const q = document.getElementById('devSearch').value.trim().toLowerCase();
const os = document.getElementById('devOsFilter').value;
const cmp = document.getElementById('devComplianceFilter').value;
DevState.filtered = DevState.items.filter(d => devPassesFilters(d, q, os, cmp));
devSort();
}
// Filteraenderung: bei aktiver Gruppe nur clientseitig neu filtern (kein Re-Fetch),
// sonst serverseitig neu laden.
function devApplyFilters() {
devFetch();
if (DevState.groupId) devApplyClientFilters();
else devFetch();
}
// Header-data-col (Graph-Feldnamen) -> tatsaechliche Item-Property.
const DEV_COL_MAP = {
deviceName: 'DeviceName',
userDisplayName: 'UserDisplayName',
operatingSystem: 'OS',
complianceState: 'ComplianceState',
lastSyncDateTime: 'LastSync',
enrolledDateTime: 'EnrolledDateTime',
};
const DEV_DATE_COLS = new Set(['LastSync', 'EnrolledDateTime']);
function devFmtDate(iso) {
if (!iso) return '—';
const d = new Date(iso);
if (isNaN(d.getTime())) return '—';
return d.toLocaleDateString('de-DE') + ' ' +
d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
}
function devSort() {
const col = DevState.sortCol;
const asc = DevState.sortAsc;
const col = DEV_COL_MAP[DevState.sortCol] || DevState.sortCol;
const asc = DevState.sortAsc ? 1 : -1;
const isDate = DEV_DATE_COLS.has(col);
DevState.filtered.sort((a, b) => {
const av = (a[col] || '').toString().toLowerCase();
const bv = (b[col] || '').toString().toLowerCase();
return asc ? av.localeCompare(bv) : bv.localeCompare(av);
if (isDate) {
// Nach Zeitstempel sortieren; ungueltige/fehlende Daten ans Ende.
const at = Date.parse(a[col]); const bt = Date.parse(b[col]);
const av = isNaN(at) ? -Infinity : at;
const bv = isNaN(bt) ? -Infinity : bt;
return (av - bv) * asc;
}
const sa = (a[col] ?? '').toString().toLowerCase();
const sb = (b[col] ?? '').toString().toLowerCase();
return sa.localeCompare(sb, 'de', { numeric: true }) * asc;
});
devRender();
}
@@ -5523,6 +5888,8 @@ function devRender() {
const tbody = document.getElementById('devTableBody');
const empty = document.getElementById('devEmpty');
document.getElementById('devCount').textContent = DevState.filtered.length;
const expBtn = document.getElementById('btnDevExport');
if (expBtn) expBtn.disabled = DevState.filtered.length === 0;
if (DevState.filtered.length === 0) {
tbody.innerHTML = '';
@@ -5543,7 +5910,7 @@ function devRender() {
let html = '';
for (const d of DevState.filtered) {
const sync = d.LastSync ? new Date(d.LastSync).toLocaleDateString('de-DE') : '—';
const sync = devFmtDate(d.LastSync);
const cmpCls = d.ComplianceState === 'compliant' ? 'dev-badge-ok'
: d.ComplianceState === 'noncompliant' ? 'dev-badge-err' : 'dev-badge-unk';
const sel = DevState.selected && DevState.selected.Id === d.Id ? ' class="dev-row-selected"' : '';
@@ -5591,8 +5958,8 @@ function devRenderDetail(d) {
document.getElementById('devDetailName').textContent = d.DeviceName || '—';
document.getElementById('devDetailSub').textContent = `${d.Manufacturer || ''} ${d.Model || ''}`.trim() || '—';
const sync = d.LastSync ? new Date(d.LastSync).toLocaleString('de-DE') : '—';
const enrolled = d.EnrolledDateTime ? new Date(d.EnrolledDateTime).toLocaleDateString('de-DE') : '—';
const sync = devFmtDate(d.LastSync);
const enrolled = devFmtDate(d.EnrolledDateTime);
const storage = (d.TotalStorageGB != null)
? `${d.FreeStorageGB} GB frei / ${d.TotalStorageGB} GB gesamt` : null;
@@ -5727,10 +6094,104 @@ document.getElementById('devActions')?.addEventListener('click', async (e) => {
let devSearchDebounce = null;
document.getElementById('devSearch').addEventListener('input', () => {
clearTimeout(devSearchDebounce);
devSearchDebounce = setTimeout(devFetch, 400);
devSearchDebounce = setTimeout(devApplyFilters, 400);
});
document.getElementById('devOsFilter').addEventListener('change', devFetch);
document.getElementById('devComplianceFilter').addEventListener('change', devFetch);
document.getElementById('devOsFilter').addEventListener('change', devApplyFilters);
document.getElementById('devComplianceFilter').addEventListener('change', devApplyFilters);
// Gruppen-Filter (Live-Suche) + CSV-Export
let _devGroupTimer = null, _devGroupAbort = null;
document.getElementById('devGroupSearch')?.addEventListener('input', e => {
clearTimeout(_devGroupTimer);
const term = e.target.value.trim();
const results = document.getElementById('devGroupResults');
// Text geaendert -> aktiven Gruppen-Filter loesen (bis eine Gruppe gewaehlt wird)
if (DevState.groupId) {
DevState.groupId = null; DevState.groupName = '';
document.getElementById('devGroupClear').hidden = true;
devFetch();
}
if (term.length < 2) { if (results) { results.classList.add('hidden'); results.innerHTML = ''; } return; }
_devGroupTimer = setTimeout(() => devGroupSearch(term), 250);
});
async function devGroupSearch(term) {
const results = document.getElementById('devGroupResults');
if (!results) return;
if (_devGroupAbort) { try { _devGroupAbort.abort(); } catch {} }
_devGroupAbort = new AbortController();
results.classList.remove('hidden');
results.innerHTML = '<div class="cg-existing-empty">Suche…</div>';
try {
const resp = await fetch('/api/groups/search?q=' + encodeURIComponent(term), { signal: _devGroupAbort.signal });
let data = {}; try { data = await resp.json(); } catch {}
if (_devGroupAbort.signal.aborted) return;
if (!resp.ok) throw new Error(data.error || `HTTP ${resp.status}`);
const gs = data.items || [];
if (gs.length === 0) { results.innerHTML = '<div class="cg-existing-empty">Keine Treffer</div>'; return; }
results.innerHTML = gs.map(g =>
`<button type="button" class="cg-existing-item" data-gid="${escapeHtml(g.Id)}" data-gname="${escapeHtml(g.DisplayName)}">
<span class="cg-existing-name">${escapeHtml(g.DisplayName)}</span>
${g.Description ? `<span class="cg-existing-desc">${escapeHtml(g.Description)}</span>` : ''}
</button>`).join('');
} catch (e) {
if (e.name === 'AbortError') return;
results.innerHTML = `<div class="cg-existing-empty">Fehler: ${escapeHtml(e.message)}</div>`;
}
}
document.getElementById('devGroupResults')?.addEventListener('click', e => {
const btn = e.target.closest('.cg-existing-item');
if (!btn) return;
DevState.groupId = btn.dataset.gid;
DevState.groupName = btn.dataset.gname;
document.getElementById('devGroupSearch').value = btn.dataset.gname;
document.getElementById('devGroupClear').hidden = false;
document.getElementById('devGroupResults').classList.add('hidden');
devFetch();
});
document.getElementById('devGroupClear')?.addEventListener('click', () => {
DevState.groupId = null; DevState.groupName = '';
document.getElementById('devGroupSearch').value = '';
document.getElementById('devGroupClear').hidden = true;
document.getElementById('devGroupResults').classList.add('hidden');
devFetch();
});
// Klick ausserhalb schliesst die Ergebnisliste
document.addEventListener('click', e => {
const wrap = document.getElementById('devGroupWrap');
if (wrap && !wrap.contains(e.target)) {
document.getElementById('devGroupResults')?.classList.add('hidden');
}
});
function devExportCsv() {
const items = DevState.filtered || [];
if (items.length === 0) { toast('Keine Geräte zum Exportieren.', 'warn'); return; }
const header = ['DeviceName','UserDisplayName','UserPrincipalName','OS','OSVersion','ComplianceState','SerialNumber','Model','Manufacturer','LastSync','EnrolledDateTime'];
const rows = [header];
for (const d of items) {
rows.push([
d.DeviceName || '', d.UserDisplayName || '', d.UserPrincipalName || '',
d.OS || '', d.OSVersion || '', d.ComplianceState || '',
d.SerialNumber || '', d.Model || '', d.Manufacturer || '',
d.LastSync ? devFmtDate(d.LastSync) : '', d.EnrolledDateTime ? devFmtDate(d.EnrolledDateTime) : '',
]);
}
const csv = rows.map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(',')).join('\r\n');
const blob = new Blob(['' + csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const scope = DevState.groupName ? DevState.groupName.replace(/[^a-zA-Z0-9_-]/g, '_') : 'alle';
const a = Object.assign(document.createElement('a'), { href: url, download: `devices-${scope}-${new Date().toISOString().slice(0,10)}.csv` });
a.click();
URL.revokeObjectURL(url);
toast(`${items.length} Geräte exportiert${DevState.groupName ? ` (Gruppe „${DevState.groupName}")` : ''}.`, 'ok');
}
document.getElementById('btnDevExport')?.addEventListener('click', devExportCsv);
// Sortierung
document.querySelectorAll('#devTable th.sortable').forEach(th => {
@@ -5852,9 +6313,19 @@ function renderPolicies() {
}
function polUpdateSelCount() {
const n = PolState.selected.size;
const keys = [...PolState.selected];
const n = keys.length;
document.getElementById('polSelCount').textContent = n;
document.getElementById('btnPolExport').disabled = n === 0;
// Konsolidieren nur bei >=2 Policies UND alle vom Typ Settings Catalog.
const btnC = document.getElementById('btnPolConsolidate');
if (btnC) {
const allSc = n >= 2 && keys.every(k => k.startsWith('settingscatalog::'));
btnC.disabled = !allSc;
btnC.title = allSc
? 'Ausgewählte Settings-Catalog-Policies zu einer neuen Policy zusammenführen'
: 'Mindestens zwei Policies vom Typ „Settings Catalog" auswählen';
}
}
function polSyncCheckAll() {
@@ -5913,6 +6384,109 @@ async function polExportSelected() {
}
}
// =============================================================
// Policies konsolidieren (Settings Catalog -> eine neue Policy)
// =============================================================
let _polConsSelIds = []; // ausgewaehlte settingscatalog-Ids (Reihenfolge = Default-Gewinner)
let _polConsPreview = null; // Preview-Response
const _polConsResolutions = {}; // settingDefinitionId -> gewaehlte sourceId
async function openPolConsolidate() {
const keys = [...PolState.selected].filter(k => k.startsWith('settingscatalog::'));
if (keys.length < 2) { toast('Mindestens zwei Settings-Catalog-Policies auswählen.', 'warn'); return; }
_polConsSelIds = keys.map(k => k.slice('settingscatalog::'.length));
_polConsPreview = null;
Object.keys(_polConsResolutions).forEach(k => delete _polConsResolutions[k]);
document.getElementById('polConsSummary').innerHTML = '<span class="spinner" style="width:14px;height:14px;border-width:2px;"></span> Analysiere…';
document.getElementById('polConsConflicts').innerHTML = '';
document.getElementById('polConsName').value = '';
document.getElementById('polConsDesc').value = '';
document.getElementById('polConsConfirm').disabled = true;
document.getElementById('polConsInfo').textContent = '';
openModal('modalPolConsolidate');
try {
const res = await api('/api/policies/consolidate', { method: 'POST', body: { ids: _polConsSelIds, mode: 'preview' }, timeoutMs: 120000 });
_polConsPreview = res;
renderPolConsPreview(res);
} catch (e) {
document.getElementById('polConsSummary').innerHTML = `<span class="pol-cons-err">Analyse fehlgeschlagen: ${escapeHtml(e.message)}</span>`;
}
}
function polConsSourceName(id) {
const s = ((_polConsPreview && _polConsPreview.sources) || []).find(x => x.id === id);
return s ? s.name : id;
}
function renderPolConsPreview(res) {
const sources = res.sources || [];
document.getElementById('polConsSummary').innerHTML = `
<div><b>${sources.length}</b> Policies · Plattform <b>${escapeHtml(res.platform || '—')}</b></div>
<div><b>${res.totalSettings}</b> Einstellungen gesamt · <b class="${res.conflictCount ? 'pol-cons-warn' : ''}">${res.conflictCount}</b> Konflikt(e)</div>
<ul class="pol-cons-src">${sources.map(s => `<li>${escapeHtml(s.name)} <span class="muted">(${s.settingCount})</span></li>`).join('')}</ul>`;
const cWrap = document.getElementById('polConsConflicts');
const conflicts = res.conflicts || [];
if (conflicts.length === 0) {
cWrap.innerHTML = '<div class="form-hint ok">Keine Konflikte — alle gemeinsamen Einstellungen sind identisch.</div>';
} else {
cWrap.innerHTML = `<div class="pol-cons-conf-head">Konflikte — welcher Wert soll gewinnen?</div>` +
conflicts.map((c, ci) => {
_polConsResolutions[c.settingDefinitionId] = c.chosenSourceId; // Default merken
const opts = (c.variants || []).map(v => {
const sid = (v.sourceIds || [])[0];
const label = (v.sourceNames || []).join(', ') || polConsSourceName(sid);
const checked = sid === c.chosenSourceId ? 'checked' : '';
return `<label class="pol-cons-opt">
<input type="radio" name="polcons-${ci}" data-def="${escapeHtml(c.settingDefinitionId)}" data-src="${escapeHtml(sid)}" ${checked}>
<span>${escapeHtml(label)}</span>
</label>`;
}).join('');
return `<div class="pol-cons-conf">
<div class="pol-cons-def" title="${escapeHtml(c.settingDefinitionId)}">${escapeHtml(c.settingDefinitionId)}</div>
<div class="pol-cons-opts">${opts}</div>
</div>`;
}).join('');
cWrap.querySelectorAll('input[type="radio"][data-def]').forEach(r => {
r.addEventListener('change', () => { _polConsResolutions[r.dataset.def] = r.dataset.src; });
});
}
document.getElementById('polConsName').value = `Konsolidiert – ${sources.length ? sources[0].name : 'Policy'}`;
document.getElementById('polConsInfo').textContent = `${res.totalSettings} Einstellungen → 1 Policy`;
document.getElementById('polConsConfirm').disabled = false;
}
async function polDoConsolidate() {
if (!_polConsPreview) return;
const name = document.getElementById('polConsName').value.trim();
if (!name) { toast('Bitte einen Namen angeben.', 'warn'); return; }
const desc = document.getElementById('polConsDesc').value.trim();
const btn = document.getElementById('polConsConfirm');
btn.disabled = true;
setLoading('Führe Policies zusammen…');
try {
const res = await api('/api/policies/consolidate', {
method: 'POST',
body: { ids: _polConsSelIds, mode: 'create', name, description: desc, resolutions: _polConsResolutions },
timeoutMs: 180000,
});
toast(`Neue Policy „${res.name}" erstellt (${res.settingsCount} Einstellungen, ${res.conflictCount} Konflikt(e) aufgelöst).`, 'ok', 'Konsolidiert');
closeModal('modalPolConsolidate');
await loadPolicies();
} catch (e) {
toast('Zusammenführen fehlgeschlagen: ' + e.message, 'err');
btn.disabled = false;
} finally {
clearLoading();
}
}
document.getElementById('btnPolConsolidate')?.addEventListener('click', openPolConsolidate);
document.getElementById('polConsConfirm')?.addEventListener('click', polDoConsolidate);
// Datei-Inhalt -> Liste von Envelopes { exportType, policy, ... }
function polExtractEnvelopes(parsed, fileName) {
if (parsed && Array.isArray(parsed.policies)) return parsed.policies;
@@ -5968,10 +6542,30 @@ async function polDoImport() {
if (nn && nn !== polEnvName(env)) env.newName = nn; else delete env.newName;
});
closeModal('modalPolImport');
const envelopes = _polImportEnvelopes.slice();
const total = envelopes.length;
setLoading('Importiere Policies…');
try {
const res = await api('/api/policies/import', { method: 'POST', body: { policies: _polImportEnvelopes }, timeoutMs: 180000 });
const results = res.results || [];
// Sequenzieller Server-Import in kleinen Batches: umgeht die 180-s-Timeout-Wand
// eines einzelnen Requests bei vielen Policies und erlaubt Fortschrittsanzeige.
const BATCH = 5;
const loadingText = document.getElementById('loadingText');
const results = [];
for (let start = 0; start < total; start += BATCH) {
const chunk = envelopes.slice(start, start + BATCH);
if (loadingText && total > BATCH) {
loadingText.textContent = `Importiere Policies… (${start + 1}–${Math.min(start + chunk.length, total)} von ${total})`;
}
// Timeout pro Batch nach Batch-Größe skaliert (Anlegen + Retry je Policy).
try {
const res = await api('/api/policies/import', { method: 'POST', body: { policies: chunk }, timeoutMs: 30000 + chunk.length * 30000 });
if (res && res.results) results.push(...res.results);
} catch (be) {
// Batch-Fehler nicht den Gesamtimport abbrechen lassen — als fehlgeschlagen
// vermerken und mit dem nächsten Batch weitermachen.
chunk.forEach(env => results.push({ policyName: polEnvName(env), success: false, error: be.message }));
}
}
const ok = results.filter(r => r.success);
const fail = results.filter(r => !r.success);
if (fail.length) {
+82 -6
View File
@@ -126,7 +126,7 @@
<section class="panel panel-targets">
<div class="panel-head">
<div class="panel-title">
<h2>Abteilungen &amp; Benutzer</h2>
<h2>Gruppen &amp; Benutzer</h2>
<span id="targetCount" class="count-badge">0</span>
</div>
<button id="btnReloadTargets" class="icon-btn" title="Neu laden" aria-label="Neu laden">
@@ -135,7 +135,7 @@
</div>
<div class="mode-segment" role="tablist">
<button class="seg active" data-mode="dept" role="tab">Abteilung</button>
<button class="seg active" data-mode="dept" role="tab">Gruppe</button>
<button class="seg" data-mode="user" role="tab">Benutzer</button>
</div>
@@ -193,6 +193,11 @@
<option value="srcIntune">Nur Intune-Apps</option>
<!-- Vendor-Optionen werden dynamisch von rebuildVendorFilterOptions() ergaenzt -->
</select>
<select id="appPlatformFilter" class="select" title="Nach Plattform filtern">
<option value="all">Alle Plattformen</option>
<option value="windows">Windows</option>
<option value="macos">macOS</option>
</select>
<select id="appCategoryFilter" class="select" title="Nach App-Kategorie filtern">
<option value="">Alle Kategorien</option>
<!-- Kategorie-Optionen werden dynamisch von rebuildCategoryFilterOptions() befuellt -->
@@ -244,7 +249,7 @@
<div class="summary-section">
<div class="summary-section-title">Ausgewählte Empfänger</div>
<div class="summary-row sub">
<span class="muted">Abteilungsgruppen</span>
<span class="muted">Gruppen</span>
<span id="sumGroupsSel">0</span>
</div>
<div class="summary-row sub">
@@ -255,7 +260,7 @@
<div class="summary-section">
<div class="summary-section-title">Zuweisungen erhalten</div>
<div class="summary-row sub">
<span class="muted">Abteilungsgruppen</span>
<span class="muted">Gruppen</span>
<span id="sumGroupsOps">0</span>
</div>
<div class="summary-row sub">
@@ -292,7 +297,7 @@
<!-- Tab-Leiste -->
<div class="gex-tab-bar group-mgmt-tabs">
<button class="gex-tab active" data-tab="export">Mitglieder &amp; Export</button>
<button class="gex-tab gex-add-pane" data-tab="add">Benutzer hinzufügen</button>
<button class="gex-tab gex-add-pane" data-tab="add">Benutzer | Gruppen hinzufügen</button>
<button class="gex-tab gex-add-pane" data-tab="import">CSV-Import</button>
<button class="gex-tab" data-tab="user">Benutzer</button>
</div>
@@ -381,7 +386,11 @@
<!-- Rechte Spalte: Benutzer hinzufügen -->
<div class="gex-right hidden" id="gexPaneAdd">
<div class="gex-section-title">Benutzer suchen</div>
<div class="gex-addmode">
<button type="button" class="gex-addmode-btn active" data-addmode="user">Benutzer</button>
<button type="button" class="gex-addmode-btn" data-addmode="group">Gruppen</button>
</div>
<div class="gex-section-title" id="gexAddSearchTitle">Benutzer suchen</div>
<div class="search-wrap" style="margin-bottom:10px;">
<svg class="search-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>
<input type="search" id="gexUserSearch" class="input input-search" placeholder="Name, UPN oder E-Mail…" autocomplete="off">
@@ -487,6 +496,17 @@
<option value="noncompliant">Non-Compliant</option>
<option value="unknown">Unbekannt</option>
</select>
<div id="devGroupWrap" style="position:relative;">
<input type="search" id="devGroupSearch" placeholder="Nach Gruppe filtern…" autocomplete="off"
style="height:34px;padding:0 24px 0 10px;border:1px solid var(--hairline);border-radius:6px;background:var(--canvas);color:var(--ink);font-size:12.5px;width:200px;box-sizing:border-box;">
<button id="devGroupClear" type="button" title="Gruppen-Filter entfernen" hidden
style="position:absolute;right:6px;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--muted);cursor:pointer;font-size:16px;line-height:1;padding:0;">×</button>
<div id="devGroupResults" class="dev-group-results hidden"></div>
</div>
<button id="btnDevExport" class="btn btn-secondary btn-sm" disabled title="Angezeigte Geräte als CSV exportieren">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
CSV
</button>
</div>
<div class="dev-layout">
@@ -589,6 +609,10 @@
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><line x1="12" y1="3" x2="12" y2="9"/><line x1="12" y1="15" x2="12" y2="21"/><circle cx="12" cy="3" r="1"/><circle cx="12" cy="21" r="1"/></svg>
Git-Snapshot
</button>
<button class="btn btn-secondary btn-sm pol-write" id="btnPolConsolidate" disabled title="Ausgewählte Settings-Catalog-Policies zu einer neuen Policy zusammenführen">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 3v6a3 3 0 0 0 3 3h4a3 3 0 0 1 3 3v6"/><polyline points="3 7 7 3 11 7"/><polyline points="13 17 17 21 21 17"/></svg>
Konsolidieren
</button>
<button class="btn btn-primary btn-sm" id="btnPolExport" disabled title="Ausgewählte Policies als JSON exportieren">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
Export (<span id="polSelCount">0</span>)
@@ -711,6 +735,13 @@
<span class="cg-mode-desc">Neue Required-Gruppe nach Naming-Schema erstellen und zuweisen.</span>
</span>
</label>
<label class="cg-mode">
<input type="radio" name="cgMode" value="req-existing">
<span class="cg-mode-body">
<span class="cg-mode-title">Bestehende Gruppe</span>
<span class="cg-mode-desc">Eine vorhandene Entra-Gruppe als Required zuweisen.</span>
</span>
</label>
<label class="cg-mode">
<input type="radio" name="cgMode" value="req-allusers">
<span class="cg-mode-body">
@@ -739,6 +770,13 @@
<span class="cg-mode-desc">Neue Available-Gruppe nach Naming-Schema erstellen und zuweisen.</span>
</span>
</label>
<label class="cg-mode">
<input type="radio" name="cgMode" value="avail-existing">
<span class="cg-mode-body">
<span class="cg-mode-title">Bestehende Gruppe</span>
<span class="cg-mode-desc">Eine vorhandene Entra-Gruppe als Available zuweisen.</span>
</span>
</label>
<label class="cg-mode">
<input type="radio" name="cgMode" value="avail-allusers">
<span class="cg-mode-body">
@@ -762,6 +800,12 @@
<input type="text" id="cgGroupName" class="input">
<div id="cgStatus" class="form-hint"></div>
</div>
<div class="form-group" id="cgExistingGroup" hidden>
<label class="lbl" for="cgExistingSearch">Bestehende Gruppe suchen</label>
<input type="search" id="cgExistingSearch" class="input" placeholder="Gruppenname… (min. 2 Zeichen)" autocomplete="off">
<div id="cgExistingResults" class="cg-existing-results"></div>
<div id="cgExistingSelected" class="form-hint"></div>
</div>
<label class="check-chip" id="cgAssignToAppWrap">
<input type="checkbox" id="cgAssignToApp" checked>
<span>Gruppe direkt der App zuweisen</span>
@@ -875,6 +919,38 @@
</div>
</div>
<!-- MODAL: Policies konsolidieren (Settings Catalog) -->
<div id="modalPolConsolidate" class="modal hidden">
<div class="modal-backdrop" data-close></div>
<div class="modal-box modal-lg">
<div class="modal-head">
<h3>Policies zusammenführen</h3>
<button class="modal-close" data-close aria-label="Schließen">×</button>
</div>
<div class="modal-body">
<div class="form-hint" style="margin-bottom:12px;">
Die Einstellungen der ausgewählten <b>Settings-Catalog</b>-Policies werden zu
<b>einer neuen</b> Policy vereint (Neuanlage — die Originale bleiben unverändert).
</div>
<div id="polConsSummary" class="pol-cons-summary"></div>
<div id="polConsConflicts"></div>
<div class="form-group" style="margin-top:12px;">
<label class="lbl" for="polConsName">Name der neuen Policy</label>
<input type="text" id="polConsName" class="input" placeholder="z. B. Konsolidiert – Defender macOS">
</div>
<div class="form-group">
<label class="lbl" for="polConsDesc">Beschreibung (optional)</label>
<input type="text" id="polConsDesc" class="input">
</div>
</div>
<div class="modal-foot">
<span id="polConsInfo" class="muted" style="margin-right:auto;"></span>
<button class="btn btn-secondary" data-close>Abbrechen</button>
<button class="btn btn-primary" id="polConsConfirm" disabled>Zusammenführen</button>
</div>
</div>
</div>
<!-- MODAL: Policy-Zuweisung nach Import -->
<div id="modalPolAssign" class="modal hidden">
<div class="modal-backdrop" data-close></div>
+121
View File
@@ -1129,6 +1129,21 @@ a.target-link:hover {
}
.target-row:hover .entra-link,
.ex-member-row:hover .entra-link { opacity: 1; }
/* Gruppen-Filter-Dropdown im Geraete-Tab (nutzt .cg-existing-item fuer die Zeilen) */
.dev-group-results {
position: absolute;
z-index: 40;
top: 38px;
left: 0;
min-width: 220px;
max-height: 260px;
overflow-y: auto;
background: var(--canvas);
border: 1px solid var(--hairline);
border-radius: 6px;
box-shadow: 0 8px 24px rgba(0,0,0,0.28);
}
.entra-link:hover {
background: var(--surface-soft);
color: var(--brand-accent);
@@ -1327,6 +1342,7 @@ html[data-theme="dark"] .entra-link.teams-link:hover {
border-radius: var(--r-md);
}
.member-row {
display: flex;
align-items: center;
@@ -4020,6 +4036,67 @@ body.members-page {
color: var(--muted);
}
/* "Bestehende Gruppe" — Suchergebnis-Liste im Zuweisungs-Dialog */
.cg-existing-results {
margin-top: 8px;
max-height: 220px;
overflow-y: auto;
border: 1px solid var(--hairline-soft);
border-radius: var(--r-xs);
}
.cg-existing-results:empty { display: none; }
.cg-existing-item {
display: flex;
flex-direction: column;
gap: 2px;
width: 100%;
text-align: left;
padding: 8px 12px;
background: transparent;
border: none;
border-bottom: 1px solid var(--hairline-soft);
cursor: pointer;
color: inherit;
}
.cg-existing-item:last-child { border-bottom: none; }
.cg-existing-item:hover { background: var(--hover, rgba(127,127,127,0.08)); }
.cg-existing-item.is-selected { background: var(--accent-soft); }
.cg-existing-name { font-size: 13px; font-weight: 600; }
.cg-existing-desc { font-size: 11px; color: var(--muted); }
.cg-existing-empty { padding: 10px 12px; font-size: 12px; color: var(--muted); }
/* Ausgewaehlte Gruppen als Chips (Mehrfachauswahl) */
.cg-existing-chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 8px;
}
.cg-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 6px 3px 10px;
background: var(--accent-soft);
color: var(--brand-accent);
border-radius: 999px;
font-size: 12px;
font-weight: 600;
max-width: 100%;
}
.cg-chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 220px; }
.cg-chip-x {
border: none;
background: transparent;
color: inherit;
cursor: pointer;
font-size: 15px;
line-height: 1;
padding: 0 2px;
opacity: 0.75;
}
.cg-chip-x:hover { opacity: 1; }
.cg-mode {
display: flex;
align-items: flex-start;
@@ -4554,6 +4631,25 @@ html[data-theme="dark"] .numInputWrapper span.arrowDown {
flex-shrink: 0;
}
/* Umschalter Benutzer/Gruppen im "Hinzufuegen"-Pane */
.gex-addmode { display: flex; gap: 6px; margin-bottom: 12px; }
.gex-addmode-btn {
flex: 1;
padding: 6px 10px;
border: 1px solid var(--hairline);
border-radius: var(--r-sm, 6px);
background: var(--canvas);
color: var(--muted);
font-size: 12.5px;
font-weight: 600;
cursor: pointer;
}
.gex-addmode-btn.active {
background: var(--accent-soft);
color: var(--brand-accent);
border-color: var(--brand-accent);
}
.gex-tab {
padding: 10px 18px;
font-size: 13px;
@@ -5367,6 +5463,31 @@ body.read-only .app-row {
border: 1px solid var(--border);
border-radius: 6px;
}
/* Policies konsolidieren — Modal */
.pol-cons-summary { font-size: 13px; line-height: 1.6; }
.pol-cons-summary .pol-cons-warn { color: var(--pink, #e0567a); }
.pol-cons-err { color: var(--pink, #e0567a); font-size: 13px; }
.pol-cons-src { margin: 6px 0 0; padding-left: 18px; font-size: 12px; }
.pol-cons-src li { margin: 1px 0; }
.pol-cons-conf-head { margin: 14px 0 6px; font-weight: 600; font-size: 13px; }
.pol-cons-conf {
border: 1px solid var(--hairline-soft, var(--border));
border-radius: var(--r-xs, 6px);
padding: 8px 10px;
margin-bottom: 6px;
}
.pol-cons-def {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
color: var(--muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-bottom: 6px;
}
.pol-cons-opts { display: flex; flex-wrap: wrap; gap: 6px 16px; }
.pol-cons-opt { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; cursor: pointer; }
.pol-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.pol-table thead { position: sticky; top: 0; z-index: 2; background: var(--bg2); }
.pol-table th {