FieldAgreement.psm1

Set-StrictMode -Version Latest

function Get-FieldAgreement {
<#
.SYNOPSIS
Compare the values two data vendors returned for the same records and fields.
.DESCRIPTION
The CSV needs a header row with the columns record_id, field, vendor_a and vendor_b (header matching is
case-insensitive). Each row is one field of one record, with the value each vendor returned; either value may be empty.
Values are compared after trimming and lowercasing. Per field the function counts: records, both filled, agree, differ,
only A filled, only B filled and neither filled. Agreement rate = agree / both filled, shown to 1 decimal
('n/a' when no record has both values). Field names are trimmed and matched case-insensitively; the first spelling seen
is displayed, in order of first appearance.
Returns one object per field (Field, Records, BothFilled, Agree, Differ, OnlyAFilled, OnlyBFilled, NeitherFilled,
AgreementRate as a number or $null, AgreementRateText). Each object also carries Overall (the same totals for the
whole file), Disagreements (the first 5 differing rows in file order: RecordId, Field, VendorA, VendorB) and Report.
The text report is also written to the console unless -Quiet is given.
Throws on a missing file, a missing column, no data rows, an empty record_id or field (the data row number is named)
or a duplicate (record_id, field) pair (named). Data rows are counted after the header, starting at 1.
.EXAMPLE
Get-FieldAgreement -Path sample.csv
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Path,
        [switch]$Quiet
    )

    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "file not found: $Path" }
    $inv = [System.Globalization.CultureInfo]::InvariantCulture
    $rows = @(Import-Csv -LiteralPath $Path)
    if ($rows.Count -eq 0) { throw 'CSV has no data rows' }
    $names = @{}
    foreach ($p in $rows[0].PSObject.Properties.Name) { $names[$p.Trim().ToLowerInvariant()] = $p }
    foreach ($need in 'record_id', 'field', 'vendor_a', 'vendor_b') {
        if (-not $names.ContainsKey($need)) { throw "missing column: $need" }
    }
    $get = {
        param($row, $col)
        $v = $row.PSObject.Properties[$names[$col]].Value
        if ($null -eq $v) { '' } else { ([string]$v).Trim() }
    }

    $stats = [ordered]@{}   # lowercased field -> counters
    $seen = New-Object 'System.Collections.Generic.HashSet[string]'
    $diffs = New-Object System.Collections.Generic.List[object]
    $total = @{ Records = 0; BothFilled = 0; Agree = 0; Differ = 0; OnlyAFilled = 0; OnlyBFilled = 0; NeitherFilled = 0 }
    $n = 0
    foreach ($r in $rows) {
        $n++
        $id = & $get $r 'record_id'
        $field = & $get $r 'field'
        $a = & $get $r 'vendor_a'
        $b = & $get $r 'vendor_b'
        if ($id -eq '') { throw "row ${n}: empty record_id" }
        if ($field -eq '') { throw "row ${n}: empty field" }
        $key = $field.ToLowerInvariant()
        $pair = $id.ToLowerInvariant() + [char]0 + $key
        if (-not $seen.Add($pair)) { throw "row ${n}: duplicate record_id '$id' for field '$field'" }
        if (-not $stats.Contains($key)) {
            $stats[$key] = @{ Field = $field; Records = 0; BothFilled = 0; Agree = 0; Differ = 0; OnlyAFilled = 0; OnlyBFilled = 0; NeitherFilled = 0 }
        }
        $s = $stats[$key]
        $s.Records++; $total.Records++
        $aFilled = ($a -ne '')
        $bFilled = ($b -ne '')
        if ($aFilled -and $bFilled) {
            $s.BothFilled++; $total.BothFilled++
            if ($a.ToLowerInvariant() -eq $b.ToLowerInvariant()) { $s.Agree++; $total.Agree++ }
            else {
                $s.Differ++; $total.Differ++
                $diffs.Add([pscustomobject]@{ RecordId = $id; Field = $s.Field; VendorA = $a; VendorB = $b })
            }
        }
        elseif ($aFilled) { $s.OnlyAFilled++; $total.OnlyAFilled++ }
        elseif ($bFilled) { $s.OnlyBFilled++; $total.OnlyBFilled++ }
        else { $s.NeitherFilled++; $total.NeitherFilled++ }
    }

    $rate = {
        param($c)
        if ($c.BothFilled -eq 0) { $null }
        else { [math]::Round(100.0 * $c.Agree / $c.BothFilled, 1, [System.MidpointRounding]::AwayFromZero) }
    }
    $rateText = { param($v) if ($null -eq $v) { 'n/a' } else { $v.ToString('0.0', $inv) + '%' } }
    $make = {
        param($label, $c)
        $rv = & $rate $c
        [pscustomobject]@{
            Field = $label; Records = $c.Records; BothFilled = $c.BothFilled; Agree = $c.Agree; Differ = $c.Differ
            OnlyAFilled = $c.OnlyAFilled; OnlyBFilled = $c.OnlyBFilled; NeitherFilled = $c.NeitherFilled
            AgreementRate = $rv; AgreementRateText = (& $rateText $rv)
        }
    }
    $overall = & $make 'overall' $total
    $firstDiffs = @($diffs | Select-Object -First 5)

    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add("Rows read: $n")
    $lines.Add('Fields: ' + $stats.Count)
    $lines.Add('')
    $fmt = '{0,-10} {1,7} {2,7} {3,6} {4,6} {5,7} {6,7} {7,8} {8,10}'
    $lines.Add(($fmt -f 'field', 'records', 'both', 'agree', 'differ', 'only A', 'only B', 'neither', 'agreement'))
    $objs = New-Object System.Collections.Generic.List[object]
    foreach ($k in $stats.Keys) {
        $o = & $make $stats[$k].Field $stats[$k]
        $objs.Add($o)
        $lines.Add(($fmt -f $o.Field, $o.Records, $o.BothFilled, $o.Agree, $o.Differ, $o.OnlyAFilled, $o.OnlyBFilled, $o.NeitherFilled, $o.AgreementRateText))
    }
    $lines.Add(($fmt -f 'overall', $overall.Records, $overall.BothFilled, $overall.Agree, $overall.Differ, $overall.OnlyAFilled, $overall.OnlyBFilled, $overall.NeitherFilled, $overall.AgreementRateText))
    $lines.Add('')
    if ($diffs.Count -eq 0) { $lines.Add('Disagreements: none') }
    else {
        $lines.Add("Disagreements: $($diffs.Count) (first $($firstDiffs.Count) shown)")
        foreach ($d in $firstDiffs) { $lines.Add(('{0} {1} A: {2} B: {3}' -f $d.RecordId, $d.Field, $d.VendorA, $d.VendorB)) }
    }
    $report = $lines -join [Environment]::NewLine
    if (-not $Quiet) { Write-Host $report }

    foreach ($o in $objs) {
        $o | Add-Member -NotePropertyName Overall -NotePropertyValue $overall
        $o | Add-Member -NotePropertyName Disagreements -NotePropertyValue $firstDiffs
        $o | Add-Member -NotePropertyName Report -NotePropertyValue $report
    }
    $objs.ToArray()
}

Export-ModuleMember -Function Get-FieldAgreement