DormantContacts.psm1
|
Set-StrictMode -Version Latest function Get-DormantContacts { <# .SYNOPSIS Find dormant contacts from a CSV of contact ids, owners and last activity dates. .DESCRIPTION The CSV needs a header row with the columns contact_id, owner and last_activity_on (header matching is case-insensitive). last_activity_on is yyyy-MM-dd; empty means the contact was never active. The clock is never read: -Today (required, yyyy-MM-dd) is the date you measure from. Days since = Today minus last_activity_on, in whole calendar days; a date after Today is an error naming the data row. States: "active" (days <= DormantDays), "dormant" (days > DormantDays) and "never active" (empty date). DormantDays is set by you (default 90, must be >= 0). Age bands for the dated contacts (active and dormant together): 0 to 30, 31 to 90, 91 to 180, 181 to 365 and over 365 days. Per owner (trimmed, case-insensitive, first spelling shown; an empty owner is shown as (no owner)): contacts, dormant, never active and the share of that owner's contacts that are dormant (1 decimal), sorted by dormant count descending then owner. The 10 longest-dormant contacts are listed by days descending then contact_id. Returns one object per state (State, Contacts, Share, ShareText) and each carries Bands, Owners, LongestDormant (up to 10) 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 or duplicate contact_id (trimmed, case-insensitive), a bad date (the data row is named), a bad -Today or DormantDays < 0. Data rows are counted after the header, from 1. .EXAMPLE Get-DormantContacts -Path sample.csv -Today 2026-01-15 #> [CmdletBinding()] param( [Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Today, [int]$DormantDays = 90, [switch]$Quiet ) $inv = [System.Globalization.CultureInfo]::InvariantCulture $parse = { param([string]$s) $d = [datetime]::MinValue if ([datetime]::TryParseExact($s, 'yyyy-MM-dd', $inv, [System.Globalization.DateTimeStyles]::None, [ref]$d)) { $d } else { $null } } if ($DormantDays -lt 0) { throw "DormantDays must be 0 or more (got $DormantDays)" } $todayDt = & $parse $Today.Trim() if ($null -eq $todayDt) { throw "bad -Today '$Today': use yyyy-MM-dd" } if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "file not found: $Path" } $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 'contact_id', 'owner', 'last_activity_on') { 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() } } $bandNames = '0 to 30', '31 to 90', '91 to 180', '181 to 365', 'over 365' $bandCounts = @(0, 0, 0, 0, 0) $counts = [ordered]@{ 'active' = 0; 'dormant' = 0; 'never active' = 0 } $owners = [ordered]@{} $dormantList = New-Object System.Collections.Generic.List[object] $seen = New-Object 'System.Collections.Generic.HashSet[string]' $n = 0 foreach ($r in $rows) { $n++ $id = & $get $r 'contact_id' $owner = & $get $r 'owner' $last = & $get $r 'last_activity_on' if ($id -eq '') { throw "row ${n}: empty contact_id" } if (-not $seen.Add($id.ToLowerInvariant())) { throw "row ${n}: duplicate contact_id '$id'" } if ($owner -eq '') { $owner = '(no owner)' } $ok = $owner.ToLowerInvariant() if (-not $owners.Contains($ok)) { $owners[$ok] = @{ Owner = $owner; Contacts = 0; Dormant = 0; NeverActive = 0 } } $o = $owners[$ok] $o.Contacts++ if ($last -eq '') { $counts['never active']++; $o.NeverActive++; continue } $dt = & $parse $last if ($null -eq $dt) { throw "row ${n}: bad last_activity_on '$last' for contact '$id' (use yyyy-MM-dd)" } $days = [int]($todayDt - $dt).TotalDays if ($days -lt 0) { throw "row ${n}: last_activity_on '$last' for contact '$id' is after -Today" } if ($days -le 30) { $bandCounts[0]++ } elseif ($days -le 90) { $bandCounts[1]++ } elseif ($days -le 180) { $bandCounts[2]++ } elseif ($days -le 365) { $bandCounts[3]++ } else { $bandCounts[4]++ } if ($days -le $DormantDays) { $counts['active']++ } else { $counts['dormant']++; $o.Dormant++ $dormantList.Add([pscustomobject]@{ ContactId = $id; Owner = $o.Owner; LastActivityOn = $last; DaysSince = $days }) } } $pct = { param($a, $b) if ($b -eq 0) { [decimal]0 } else { [math]::Round(100 * [decimal]$a / $b, 1, [System.MidpointRounding]::AwayFromZero) } } $one = { param($v) ([decimal]$v).ToString('0.0', $inv) + '%' } $bands = @(for ($i = 0; $i -lt 5; $i++) { [pscustomobject]@{ Band = $bandNames[$i]; Contacts = $bandCounts[$i] } }) $ownerObjs = @($owners.Values | ForEach-Object { [pscustomobject]@{ Owner = $_.Owner; Contacts = $_.Contacts; Dormant = $_.Dormant; NeverActive = $_.NeverActive; DormantShare = (& $pct $_.Dormant $_.Contacts) } } | Sort-Object -Property @{ Expression = 'Dormant'; Descending = $true }, 'Owner') $longest = @($dormantList | Sort-Object -Property @{ Expression = 'DaysSince'; Descending = $true }, 'ContactId' | Select-Object -First 10) $lines = New-Object System.Collections.Generic.List[string] $lines.Add("Contacts: $n (today $($todayDt.ToString('yyyy-MM-dd', $inv)), dormant after $DormantDays days)") $lines.Add('') $fmt = '{0,-13} {1,8} {2,7}' $lines.Add(($fmt -f 'state', 'contacts', 'share')) $objs = New-Object System.Collections.Generic.List[object] foreach ($k in $counts.Keys) { $share = & $pct $counts[$k] $n $o = [pscustomobject]@{ State = $k; Contacts = $counts[$k]; Share = $share; ShareText = (& $one $share) } $objs.Add($o) $lines.Add(($fmt -f $o.State, $o.Contacts, $o.ShareText)) } $lines.Add('') $lines.Add('Age bands (days since last activity, dated contacts only)') foreach ($b in $bands) { $lines.Add(('{0,-11} {1,5}' -f $b.Band, $b.Contacts)) } $lines.Add('') $lines.Add('By owner') $ofmt = '{0,-10} {1,8} {2,8} {3,6} {4,14}' $lines.Add(($ofmt -f 'owner', 'contacts', 'dormant', 'never', 'share dormant')) foreach ($o in $ownerObjs) { $lines.Add(($ofmt -f $o.Owner, $o.Contacts, $o.Dormant, $o.NeverActive, (& $one $o.DormantShare))) } $lines.Add('') if ($dormantList.Count -eq 0) { $lines.Add('Longest dormant: none') } else { $lines.Add("Longest dormant ($($dormantList.Count) dormant, first $($longest.Count) shown)") foreach ($d in $longest) { $lines.Add(('{0} {1} last active {2} {3} days' -f $d.ContactId, $d.Owner, $d.LastActivityOn, $d.DaysSince)) } } $report = $lines -join [Environment]::NewLine if (-not $Quiet) { Write-Host $report } foreach ($o in $objs) { $o | Add-Member -NotePropertyName Bands -NotePropertyValue $bands $o | Add-Member -NotePropertyName Owners -NotePropertyValue $ownerObjs $o | Add-Member -NotePropertyName LongestDormant -NotePropertyValue $longest $o | Add-Member -NotePropertyName Report -NotePropertyValue $report } $objs.ToArray() } Export-ModuleMember -Function Get-DormantContacts |