TerritorySplit.psm1

function Split-Territory {
<#
.SYNOPSIS
Split a list of accounts into balanced territories, one per rep.
.DESCRIPTION
Greedy balancing: accounts (or, with -KeepTogether, whole groups such as a region) are sorted by weight, largest first, and each goes to the rep
with the smallest total so far. Ties go to the first rep in the list. Offline and deterministic. Returns one object per rep with the accounts and totals.
.EXAMPLE
Import-Csv accounts.csv | Split-Territory -Rep Ana,Ben,Cy -WeightProperty ARR -KeepTogether Region
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)][psobject]$Account,
        [Parameter(Mandatory)][string[]]$Rep,
        [string]$WeightProperty,
        [string]$NameProperty = 'Name',
        [string]$KeepTogether
    )
    begin { $all = New-Object System.Collections.Generic.List[object] }
    process { $all.Add($Account) }
    end {
        if ($Rep.Count -lt 1) { throw 'Give at least one rep.' }
        $units = New-Object System.Collections.Generic.List[object]
        function Weight($a) {
            if (-not $WeightProperty) { return [double]1 }
            $v = 0.0
            if (-not [double]::TryParse([string]$a.$WeightProperty, [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$v)) { throw "Weight '$($a.$WeightProperty)' on '$($a.$NameProperty)' is not a number." }
            return $v
        }
        if ($KeepTogether) {
            $groups = [ordered]@{}
            foreach ($a in $all) { $k = [string]$a.$KeepTogether; if (-not $groups.Contains($k)) { $groups[$k] = New-Object System.Collections.Generic.List[object] }; $groups[$k].Add($a) }
            foreach ($k in $groups.Keys) {
                $w = 0.0; foreach ($a in $groups[$k]) { $w += (Weight $a) }
                $units.Add([pscustomobject]@{ Key = $k; Weight = $w; Items = $groups[$k] })
            }
        } else {
            foreach ($a in $all) { $units.Add([pscustomobject]@{ Key = [string]$a.$NameProperty; Weight = (Weight $a); Items = @($a) }) }
        }
        $sorted = $units | Sort-Object -Property @{ Expression = 'Weight'; Descending = $true }, @{ Expression = 'Key'; Descending = $false }
        $totals = @{}; $bucket = @{}
        foreach ($r in $Rep) { $totals[$r] = 0.0; $bucket[$r] = New-Object System.Collections.Generic.List[object] }
        foreach ($u in $sorted) {
            $pick = $Rep[0]
            foreach ($r in $Rep) { if ($totals[$r] -lt $totals[$pick]) { $pick = $r } }
            $totals[$pick] += $u.Weight
            foreach ($i in $u.Items) { $bucket[$pick].Add($i) }
        }
        foreach ($r in $Rep) {
            [pscustomobject]@{ Rep = $r; Accounts = $bucket[$r].Count; Weight = $totals[$r]; Items = $bucket[$r].ToArray() }
        }
    }
}
function Measure-TerritoryBalance {
<#
.SYNOPSIS
Show how even a split is: smallest and largest territory weight and the spread between them as a percentage of the average.
.EXAMPLE
Import-Csv accounts.csv | Split-Territory -Rep Ana,Ben -WeightProperty ARR | Measure-TerritoryBalance
#>

    [CmdletBinding()]
    param([Parameter(Mandatory, ValueFromPipeline)][psobject]$Territory)
    begin { $t = New-Object System.Collections.Generic.List[object] }
    process { $t.Add($Territory) }
    end {
        $w = @($t | ForEach-Object { [double]$_.Weight })
        $avg = ($w | Measure-Object -Average).Average
        $min = ($w | Measure-Object -Minimum).Minimum; $max = ($w | Measure-Object -Maximum).Maximum
        [pscustomobject]@{ Territories = $t.Count; Min = $min; Max = $max; Average = $avg; SpreadPct = $(if ($avg -eq 0) { 0 } else { [math]::Round(($max - $min) / $avg * 100, 1) }) }
    }
}
Export-ModuleMember -Function Split-Territory, Measure-TerritoryBalance