Private/Plan.ps1

# Change plans: staged operations -> validated, explained before/after per object, with visibility impact. Nothing here writes to Intune.

function Get-STMTagMaps {
    $byId = @{}; $byName = @{}
    foreach ($t in @($script:STM.Tags)) {
        $byId[$t.Id] = $t
        $k = $t.Name.ToLowerInvariant()
        if (-not $byName.ContainsKey($k)) { $byName[$k] = [System.Collections.Generic.List[string]]::new() }
        $byName[$k].Add($t.Id)
    }
    return @{ ById = $byId; ByName = $byName }
}

function Resolve-STMTagTokens {
    # Accepts ids or display names (case-insensitive). Returns @{ Ids; Errors }.
    param([string[]]$Tokens)
    $maps = Get-STMTagMaps
    $ids = [System.Collections.Generic.List[string]]::new(); $errors = [System.Collections.Generic.List[string]]::new()
    foreach ($raw in @($Tokens)) {
        $t = "$raw".Trim()
        if (-not $t) { continue }
        if ($maps.ById.ContainsKey($t)) { $ids.Add($t); continue }
        $k = $t.ToLowerInvariant()
        if ($k -eq 'default' -and $maps.ById.ContainsKey('0')) { $ids.Add('0'); continue }
        if ($maps.ByName.ContainsKey($k)) {
            $m = @($maps.ByName[$k])
            if ($m.Count -gt 1) { $errors.Add("Scope tag name '$t' matches several tags ($($m -join ', ')); use the tag id"); continue }
            $ids.Add($m[0]); continue
        }
        $errors.Add("Scope tag '$t' does not exist in this tenant")
    }
    return @{ Ids = @($ids | Sort-Object -Unique); Errors = @($errors) }
}

function Get-STMTagName {
    param([string]$Id)
    $t = @($script:STM.Tags) | Where-Object { $_.Id -eq $Id } | Select-Object -First 1
    if ($t) { return $t.Name }
    if ($Id -eq '0') { return 'Default' }
    return "Unknown tag $Id"
}

function Get-STMProtectedTagProblem {
    param($Protected)
    if (-not ($Protected.Missing.Count -or $Protected.Ambiguous.Count)) { return '' }
    $m = "Protected scope tag(s) not resolvable: missing [$($Protected.Missing -join ', ')] ambiguous [$($Protected.Ambiguous -join ', ')]"
    if ($script:STM.Settings.ProtectedTagMissingBehavior -eq 'Block') { return "$m. Applying is blocked until this is fixed (setting ProtectedTagMissingBehavior = Block)." }
    return "$m. Objects carrying it cannot be recognised as protected (setting ProtectedTagMissingBehavior = Warn)."
}

function Get-STMProtectedTagIds {
    # Objects already carrying a protected tag are never changed (for example PAW-Protected).
    $names = @($script:STM.Settings.ProtectedScopeTagNames | Where-Object { $_ })
    $ids = @(); $missing = @(); $ambiguous = @()
    foreach ($n in $names) {
        $m = @($script:STM.Tags | Where-Object { $_.Name -ieq $n })
        if ($m.Count -eq 0) { $missing += $n }
        elseif ($m.Count -gt 1) { $ambiguous += $n }
        else { $ids += $m[0].Id }
    }
    return @{ Ids = $ids; Missing = $missing; Ambiguous = $ambiguous }
}

function Test-STMVisible {
    # A role assignment sees an object when they share a scope tag. Untagged objects carry Default (0).
    # An assignment with no scope tags behaves as if it had all of them (Microsoft Learn, scope tags).
    param([string[]]$AssignmentTags, [string[]]$ObjectTags)
    if (-not @($AssignmentTags).Count) { return $true }
    $obj = if (@($ObjectTags).Count) { $ObjectTags } else { @('0') }
    foreach ($t in $AssignmentTags) { if ($obj -contains $t) { return $true } }
    return $false
}

function Get-STMVisibilityImpact {
    param([string[]]$Before, [string[]]$After)
    $lost = @(); $gained = @(); $seenAfter = 0
    foreach ($a in @($script:STM.RoleAssignments)) {
        if (-not @($a.TagIds).Count) { continue }
        $vb = Test-STMVisible -AssignmentTags $a.TagIds -ObjectTags $Before
        $va = Test-STMVisible -AssignmentTags $a.TagIds -ObjectTags $After
        $label = if ($a.Name) { "$($a.Name) ($($a.RoleName))" } else { "$($a.RoleName) assignment $($a.Id)" }
        if ($vb -and -not $va) { $lost += $label }
        if ($va -and -not $vb) { $gained += $label }
        if ($va) { $seenAfter++ }
    }
    return @{ Lost = $lost; Gained = $gained; ScopedAssignmentsAfter = $seenAfter }
}

function Merge-STMOperation {
    param([string[]]$Current, [string]$Mode, [string[]]$TagIds)
    switch ($Mode) {
        'Add' { return @(@($Current) + @($TagIds) | Where-Object { $_ } | Sort-Object -Unique) }
        'Remove' { return @(@($Current) | Where-Object { $TagIds -notcontains $_ } | Sort-Object -Unique) }
        'Replace' { return @(@($TagIds) | Where-Object { $_ } | Sort-Object -Unique) }
    }
    throw "Mode must be Add, Remove or Replace (got '$Mode')"
}

function ConvertTo-STMMode {
    param([string]$Mode)
    switch -Regex ("$Mode".Trim()) {
        '^(?i)add$' { 'Add' }
        '^(?i)(remove|delete)$' { 'Remove' }
        '^(?i)(replace|set)$' { 'Replace' }
        default { $null }
    }
}

function New-STMPlan {
    <#
      Operations: objects with Type, Id, Mode (Add|Remove|Replace), Tags (ids or names), optional Note and Source.
      Several operations on one object apply in order. Objects missing from the loaded inventory are read live.
    #>

    param(
        [Parameter(Mandatory)][object[]]$Operations,
        [switch]$AllowNoExplicitTags,
        [switch]$OverrideCap,
        [string]$OverrideReason,
        [string]$Title
    )
    if (-not $script:STM.Tags) { [void](Update-STMScopeTags) }
    $planIssues = [System.Collections.Generic.List[string]]::new()
    $planWarnings = [System.Collections.Generic.List[string]]::new()
    # Visibility analysis needs the role assignments; load them if this session has not yet.
    if (-not $script:STM.RoleAssignmentsLoadedAt) {
        try { [void](Update-STMRoleAssignments) }
        catch { $planWarnings.Add("Intune role assignments could not be read, so visibility changes are not shown: $($_.Exception.Message)") }
    }
    $protected = Get-STMProtectedTagIds
    $protectedMsg = Get-STMProtectedTagProblem -Protected $protected
    if ($protectedMsg) {
        if ($script:STM.Settings.ProtectedTagMissingBehavior -eq 'Block') { $planIssues.Add($protectedMsg) } else { $planWarnings.Add($protectedMsg) }
    }

    # Group operations per object, keeping order.
    $order = [System.Collections.Generic.List[string]]::new(); $ops = @{}
    foreach ($op in $Operations) {
        $type = [string](Get-STMProp $op 'Type'); $id = ([string](Get-STMProp $op 'Id')).Trim()
        $key = "$type|$id"
        if (-not $ops.ContainsKey($key)) { $ops[$key] = [System.Collections.Generic.List[object]]::new(); $order.Add($key) }
        $ops[$key].Add($op)
    }

    # Read objects that are not in the loaded inventory.
    $missingRefs = @(foreach ($k in $order) {
        if (-not $script:STM.Inventory.ContainsKey($k)) {
            $p = $k.Split('|', 2)
            if ((Get-STMTypeRegistry).key -contains $p[0] -and $p[1]) { @{ Type = $p[0]; Id = $p[1] } }
        }
    })
    $live = @{}
    if ($missingRefs.Count) { $live = Get-STMLiveObject -Refs $missingRefs }

    $items = [System.Collections.Generic.List[object]]::new()
    foreach ($key in $order) {
        $parts = $key.Split('|', 2); $type = $parts[0]; $id = $parts[1]
        $issues = [System.Collections.Generic.List[string]]::new(); $warnings = [System.Collections.Generic.List[string]]::new()
        $notes = @($ops[$key] | ForEach-Object { [string](Get-STMProp $_ 'Note') } | Where-Object { $_ } | Sort-Object -Unique)
        $sources = @($ops[$key] | ForEach-Object { [string](Get-STMProp $_ 'Source') } | Where-Object { $_ } | Sort-Object -Unique)
        $def = Get-STMTypeRegistry | Where-Object { $_.key -eq $type } | Select-Object -First 1
        $row = $null
        if (-not $def) { $issues.Add("Unknown object type '$type'") }
        elseif (-not $id) { $issues.Add('Object id is empty') }
        elseif ($script:STM.Inventory.ContainsKey($key)) { $row = $script:STM.Inventory[$key] }
        elseif ($live.ContainsKey($key) -and $live[$key].Row) { $row = $live[$key].Row }
        else {
            $err = if ($live.ContainsKey($key)) { $live[$key].Error } else { '' }
            $issues.Add("Object not found or not visible to you ($err)")
        }

        $before = @(); $after = @()
        if ($row) {
            $before = @($row.TagIds)
            if (-not $row.TagsKnown) { $issues.Add('Graph did not return scope tags for this object; reload its tags before changing them') }
            if (-not $row.Supported) { $issues.Add("Not supported: $($row.Note)") }
            elseif ($row.Note) { $warnings.Add($row.Note) }
            if ($script:STM.AppOnly -and $def.PSObject.Properties['writeScope'] -and $def.writeScope -and -not (Test-STMAppHasWrite -Permission ([string]$def.writeScope))) { $issues.Add("The app registration lacks the $($def.writeScope) application permission, so it cannot change this object") }
            if ($def.status -eq 'LabVerify') { $warnings.Add("$($def.label): write path not yet verified on a live tenant; change one object first and check it in the Intune admin center") }
            $after = $before
            foreach ($op in $ops[$key]) {
                $mode = ConvertTo-STMMode -Mode ([string](Get-STMProp $op 'Mode'))
                if (-not $mode) { $issues.Add("Mode '$(Get-STMProp $op 'Mode')' is not Add, Remove or Replace"); continue }
                $tok = @(Get-STMProp $op 'Tags')
                if ($tok.Count -eq 1 -and "$($tok[0])" -match ';') { $tok = "$($tok[0])" -split ';' }
                $res = Resolve-STMTagTokens -Tokens $tok
                foreach ($e in $res.Errors) { $issues.Add($e) }
                if ($mode -ne 'Replace' -and -not $res.Ids.Count -and -not $res.Errors.Count) { $issues.Add("$mode needs at least one scope tag") }
                $after = @(Merge-STMOperation -Current $after -Mode $mode -TagIds $res.Ids | Where-Object { "$_" -ne '' })
            }
            $hit = @($before | Where-Object { $protected.Ids -contains $_ })
            if ($hit.Count) { $issues.Add("Protected: already carries $((($hit | ForEach-Object { Get-STMTagName $_ }) -join ', ')); never changed by this tool") }
            $adds = @($after | Where-Object { $before -notcontains $_ -and $protected.Ids -contains $_ })
            if ($adds.Count) { $issues.Add("Adds protected tag $((($adds | ForEach-Object { Get-STMTagName $_ }) -join ', ')); protected tags are assigned outside this tool, because this tool could not change or roll back the object afterwards") }
            if ($after.Count -eq 0 -and -not $AllowNoExplicitTags) { $issues.Add('Change would leave no scope tags. Intune would fall back to Default, and scoped admins may not be able to do this. Allow it explicitly if intended.') }
            if ($after.Count -gt 100) { $issues.Add("Result has $($after.Count) scope tags; Intune allows at most 100 per object") }
            if ($before -contains '0' -and $after -notcontains '0' -and $after.Count) { $warnings.Add('Removes Default: admins scoped only to Default lose this object') }
            if ($type -eq 'ManagedDevice') {
                $grpTags = @($script:STM.Tags | Where-Object { $_.AssignedGroupIds.Count } | ForEach-Object { $_.Id })
                $diff = @(@($after | Where-Object { $before -notcontains $_ }) + @($before | Where-Object { $after -notcontains $_ }))
                $touched = @($diff | Where-Object { $grpTags -contains $_ })
                if ($touched.Count) { $warnings.Add("Tag(s) $((($touched | ForEach-Object { Get-STMTagName $_ }) -join ', ')) are assigned to groups; Intune re-applies group-based device tags and overwrites manual ones") }
            }
        }
        $added = @($after | Where-Object { $before -notcontains $_ }); $removed = @($before | Where-Object { $after -notcontains $_ })
        $vis = Get-STMVisibilityImpact -Before $before -After $after
        if ($row -and $added.Count + $removed.Count -gt 0 -and @($script:STM.RoleAssignments | Where-Object { @($_.TagIds).Count }).Count -gt 0 -and $vis.ScopedAssignmentsAfter -eq 0) {
            $warnings.Add('After this change no scoped Intune role assignment can see the object; only Intune and Global Administrators will')
        }
        foreach ($l in $vis.Lost) { $warnings.Add("Loses visibility: $l") }
        $state = if ($issues.Count) { 'Blocked' } elseif ($added.Count + $removed.Count -eq 0) { 'NoChange' } else { 'Ready' }
        $items.Add([pscustomobject][ordered]@{
            Key = $key; Type = $type; TypeLabel = if ($def) { $def.label } else { $type }; Id = $id
            Name = if ($row) { $row.Name } else { '' }; Platform = if ($row) { $row.Platform } else { '' }
            ODataType = if ($row) { $row.ODataType } else { '' }
            Before = $before; After = $after; Added = $added; Removed = $removed
            BeforeNames = @($before | ForEach-Object { Get-STMTagName $_ }); AfterNames = @($after | ForEach-Object { Get-STMTagName $_ })
            State = $state; Issues = @($issues); Warnings = @($warnings)
            VisibilityLost = $vis.Lost; VisibilityGained = $vis.Gained
            Note = ($notes -join '; '); Source = ($sources -join '; ')
        })
    }
    $ready = @($items | Where-Object State -eq 'Ready').Count
    $cap = [int]$script:STM.Settings.MaxChangesPerRun
    $capExceeded = $cap -gt 0 -and $ready -gt $cap
    if ($capExceeded -and -not $OverrideCap) { $planIssues.Add("$ready changes exceed the per-run cap of $cap. Split the change or override the cap with a reason.") }
    if ($OverrideCap -and $capExceeded -and -not $OverrideReason) { $planIssues.Add('Overriding the cap needs a reason (kept in the change record)') }

    $id = '{0}-{1}' -f [DateTime]::UtcNow.ToString('yyyyMMdd-HHmmss'), ([guid]::NewGuid().ToString('N').Substring(0, 6))
    $plan = [pscustomobject][ordered]@{
        PlanId = $id
        Title = if ($Title) { $Title } else { "Scope tag change $id" }
        CreatedUtc = [DateTime]::UtcNow.ToString('o')
        Tenant = $script:STM.TenantId
        Author = $script:STM.Account
        Tool = "IntuneScopeTagManager $($script:STM.Version)"
        AllowNoExplicitTags = [bool]$AllowNoExplicitTags
        OverrideCap = [bool]$OverrideCap; OverrideReason = $OverrideReason
        Summary = [ordered]@{
            Objects = $items.Count; Ready = $ready
            NoChange = @($items | Where-Object State -eq 'NoChange').Count
            Blocked = @($items | Where-Object State -eq 'Blocked').Count
            WithWarnings = @($items | Where-Object { $_.Warnings.Count }).Count
            VisibilityChanges = @($items | Where-Object { $_.VisibilityLost.Count -or $_.VisibilityGained.Count }).Count
            Cap = $cap; CapExceeded = $capExceeded
        }
        PlanIssues = @($planIssues)
        PlanWarnings = @($planWarnings)
        CanApply = ($ready -gt 0 -and $planIssues.Count -eq 0)
        Items = @($items)
        Hash = ''
    }
    $plan.Hash = Get-STMPlanHash -Plan $plan
    $script:STM.Plans[$id] = $plan
    return $plan
}

function Get-STMPlanHash {
    # Fingerprint of what will be written, so a plan approved by change control can be checked before apply.
    param([Parameter(Mandatory)]$Plan)
    # Covers the plan's verdict and overrides too, so editing CanApply, the issues or the cap override in a saved plan is caught.
    $canon = (@($Plan.Items | Where-Object State -eq 'Ready' | Sort-Object Key | ForEach-Object { '{0}={1}>{2}' -f $_.Key, (@($_.Before) -join ','), (@($_.After) -join ',') }) -join "`n")
    $cap = if ($Plan.Summary) { Get-STMProp $Plan.Summary 'Cap' } else { '' }
    $head = 'v2|{0}|CanApply={1}|NoExplicit={2}|Override={3}|Reason={4}|Cap={5}|Issues={6}' -f $Plan.Tenant, [bool]$Plan.CanApply, [bool]$Plan.AllowNoExplicitTags, [bool]$Plan.OverrideCap, [string]$Plan.OverrideReason, $cap, ((@($Plan.PlanIssues) | Where-Object { $_ }) -join ' / ')
    $sha = [System.Security.Cryptography.SHA256]::Create()
    try { return ([BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes("$head`n$canon"))) -replace '-', '').ToLowerInvariant() }
    finally { $sha.Dispose() }
}