JobChanges.psm1

Set-StrictMode -Version Latest

function Read-JcSnapshot([string]$Path, [string]$Label) {
    if ([string]::IsNullOrWhiteSpace($Path)) { throw "-${Label}Path is required" }
    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "$Label file not found: $Path" }
    $rows = @(Import-Csv -LiteralPath $Path)
    if ($rows.Count -eq 0) { throw "$Label file has no data rows: $Path" }
    $names = @{}
    foreach ($p in $rows[0].PSObject.Properties.Name) { $names[$p.Trim().ToLowerInvariant()] = $p }
    foreach ($need in 'contact_id', 'company', 'title') {
        if (-not $names.ContainsKey($need)) { throw "$Label file is missing column: $need" }
    }
    $map = @{}
    $n = 0
    foreach ($r in $rows) {
        $n++
        $vals = @{}
        foreach ($c in 'contact_id', 'company', 'title') {
            $v = $r.PSObject.Properties[$names[$c]].Value
            $vals[$c] = if ($null -eq $v) { '' } else { ([string]$v).Trim() }
        }
        $id = $vals['contact_id']
        if ($id -eq '') { throw "$Label file row ${n}: empty contact_id" }
        $key = $id.ToLowerInvariant()
        if ($map.ContainsKey($key)) { throw "$Label file row ${n}: duplicate contact_id '$id'" }
        $map[$key] = [pscustomobject]@{ Id = $id; Company = $vals['company']; Title = $vals['title'] }
    }
    $map
}

function Get-JcNorm([string]$Text) { (($Text -replace '\s+', ' ').Trim()).ToLowerInvariant() }

function Get-JobChanges {
<#
.SYNOPSIS
Compare two snapshots of a contact list and show which contacts have a different company or title.
.DESCRIPTION
Both CSVs need a header row with the columns contact_id, company and title (header matching is case-insensitive).
Rows are matched by contact_id (trimmed, case-insensitive). Company and title are compared as text: trimmed, inner
whitespace collapsed to one space, case-insensitive. States for ids present in both files: 'company changed' (the
company differs), 'title changed' (same company, different title) and 'unchanged'; ids in one file only are
'only in old' or 'only in new'.
The report gives the ids in old, in new and matched, the count of each state with its share of the matched ids
(1 decimal; the 'only in' counts have no share), then up to 20 company changes and up to 20 title changes sorted by id.
It compares two text snapshots only. A change may be a real move, a renamed company or an edited record, so it proves
nothing about a person. It reads no outside data.
Returns one object per contact id found in either file, sorted by id (ContactId, State, OldCompany, NewCompany, OldTitle,
NewTitle); each carries Summary and Report. The text report is also written to the console unless -Quiet is given.
Throws on a missing -OldPath or -NewPath, a missing file, a missing column, no data rows in either file, an empty
contact_id or a duplicate contact_id inside one file (the file and id are named).
.EXAMPLE
Get-JobChanges -OldPath sample-old.csv -NewPath sample-new.csv
#>

    [CmdletBinding()]
    param(
        [string]$OldPath,
        [string]$NewPath,
        [switch]$Quiet
    )

    $inv = [System.Globalization.CultureInfo]::InvariantCulture
    $old = Read-JcSnapshot $OldPath 'Old'
    $new = Read-JcSnapshot $NewPath 'New'

    $keys = New-Object 'System.Collections.Generic.List[string]'
    foreach ($k in $old.Keys) { $keys.Add($k) }
    foreach ($k in $new.Keys) { if (-not $old.ContainsKey($k)) { $keys.Add($k) } }
    $arr = $keys.ToArray()
    [array]::Sort($arr, [System.StringComparer]::Ordinal)

    $objs = New-Object System.Collections.Generic.List[object]
    $c = @{ 'company changed' = 0; 'title changed' = 0; 'unchanged' = 0; 'only in old' = 0; 'only in new' = 0 }
    foreach ($k in $arr) {
        $o = $old[$k]; $nw = $new[$k]
        if ($null -eq $nw) { $state = 'only in old' }
        elseif ($null -eq $o) { $state = 'only in new' }
        elseif ((Get-JcNorm $o.Company) -ne (Get-JcNorm $nw.Company)) { $state = 'company changed' }
        elseif ((Get-JcNorm $o.Title) -ne (Get-JcNorm $nw.Title)) { $state = 'title changed' }
        else { $state = 'unchanged' }
        $c[$state]++
        $objs.Add([pscustomobject]@{
            ContactId = $(if ($o) { $o.Id } else { $nw.Id }); State = $state
            OldCompany = $(if ($o) { $o.Company } else { $null }); NewCompany = $(if ($nw) { $nw.Company } else { $null })
            OldTitle = $(if ($o) { $o.Title } else { $null }); NewTitle = $(if ($nw) { $nw.Title } else { $null })
        })
    }
    $matched = $c['company changed'] + $c['title changed'] + $c['unchanged']
    $share = {
        param($count)
        if ($matched -eq 0) { $null } else { [math]::Round([decimal]100 * $count / $matched, 1, [System.MidpointRounding]::AwayFromZero) }
    }
    $shareText = { param($v) if ($null -eq $v) { 'n/a' } else { $v.ToString('0.0', $inv) + '%' } }
    $summary = [pscustomobject]@{
        InOld = $old.Count; InNew = $new.Count; Matched = $matched
        CompanyChanged = $c['company changed']; CompanyChangedShare = (& $share $c['company changed'])
        TitleChanged = $c['title changed']; TitleChangedShare = (& $share $c['title changed'])
        Unchanged = $c['unchanged']; UnchangedShare = (& $share $c['unchanged'])
        OnlyInOld = $c['only in old']; OnlyInNew = $c['only in new']
    }

    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add("Ids in old: $($old.Count)")
    $lines.Add("Ids in new: $($new.Count)")
    $lines.Add("Matched ids: $matched")
    $lines.Add('')
    $fmt = '{0,-16} {1,5} {2,8}'
    $lines.Add(($fmt -f 'state', 'count', 'share'))
    $lines.Add(($fmt -f 'company changed', $summary.CompanyChanged, (& $shareText $summary.CompanyChangedShare)))
    $lines.Add(($fmt -f 'title changed', $summary.TitleChanged, (& $shareText $summary.TitleChangedShare)))
    $lines.Add(($fmt -f 'unchanged', $summary.Unchanged, (& $shareText $summary.UnchangedShare)))
    $lines.Add(($fmt -f 'only in old', $summary.OnlyInOld, '').TrimEnd())
    $lines.Add(($fmt -f 'only in new', $summary.OnlyInNew, '').TrimEnd())
    $lines.Add('(share = share of matched ids)')
    $cc = @($objs | Where-Object { $_.State -eq 'company changed' })
    $tc = @($objs | Where-Object { $_.State -eq 'title changed' })
    $lines.Add('')
    if ($cc.Count -eq 0) { $lines.Add('Company changes: none') }
    else {
        $lines.Add("Company changes: $($cc.Count) (first $([math]::Min(20, $cc.Count)) shown)")
        foreach ($x in ($cc | Select-Object -First 20)) {
            $lines.Add("$($x.ContactId) company: $($x.OldCompany) > $($x.NewCompany) title: $($x.OldTitle) > $($x.NewTitle)")
        }
    }
    $lines.Add('')
    if ($tc.Count -eq 0) { $lines.Add('Title changes: none') }
    else {
        $lines.Add("Title changes: $($tc.Count) (first $([math]::Min(20, $tc.Count)) shown)")
        foreach ($x in ($tc | Select-Object -First 20)) {
            $lines.Add("$($x.ContactId) title: $($x.OldTitle) > $($x.NewTitle)")
        }
    }
    $report = $lines -join [Environment]::NewLine
    if (-not $Quiet) { Write-Host $report }

    foreach ($x in $objs) {
        $x | Add-Member -NotePropertyName Summary -NotePropertyValue $summary
        $x | Add-Member -NotePropertyName Report -NotePropertyValue $report
    }
    $objs.ToArray()
}

Export-ModuleMember -Function Get-JobChanges