TouchRecency.psm1

Set-StrictMode -Version Latest

function Get-TouchRecency {
<#
.SYNOPSIS
Show how long ago each account was last touched.
.DESCRIPTION
The CSV needs a header row with the columns account, channel and touched_on (yyyy-mm-dd); header matching is
case-insensitive. Accounts and channels are trimmed and matched case-insensitively; the first spelling seen is
displayed. -Today is required (yyyy-mm-dd) and the function never reads the clock, so the same file and the same
-Today always give the same output. Days are whole calendar days: days since last touch = Today minus the latest
touch date of the account. An account is 'recent' when that number is at most -StaleDays (default 30, set by you) and
'stale' otherwise.
Per account: touches, distinct channels, last touch date, days since last touch and state. The table is sorted by days
since last touch, largest first, then by account. Totals: accounts, recent, stale, share stale (1 decimal) and the
median days since last touch (1 decimal; for an even count the mean of the two middle values). Then the touches per
channel with their share of all touches (1 decimal, half up), sorted by count (largest first) then name.
Returns one object per account in table order (Account, Touches, Channels, LastTouch, DaysSinceLastTouch, State). Each
object also carries Today, StaleDays, Totals (Accounts, Recent, Stale, ShareStale, MedianDays), ChannelMix
(Channel, Touches, Share) 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 account or channel (the data row number is named),
a bad date (row named), a touch dated after Today (row named), a bad or missing Today and StaleDays below 0. Data rows
are counted after the header, starting at 1.
.EXAMPLE
Get-TouchRecency -Path sample.csv -Today 2026-01-15 -StaleDays 30
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Path,
        [Parameter(Mandatory)][string]$Today,
        [int]$StaleDays = 30,
        [switch]$Quiet
    )

    $inv = [System.Globalization.CultureInfo]::InvariantCulture
    $parseDate = {
        param([string]$text)
        $d = [datetime]::MinValue
        if ($text -notmatch '^\d{4}-\d{2}-\d{2}$') { return $null }
        if (-not [datetime]::TryParseExact($text, 'yyyy-MM-dd', $inv, [System.Globalization.DateTimeStyles]::None, [ref]$d)) { return $null }
        $d
    }
    $todayDate = & $parseDate $Today.Trim()
    if ($null -eq $todayDate) { throw "bad Today (use yyyy-mm-dd): '$Today'" }
    if ($StaleDays -lt 0) { throw "StaleDays must be 0 or more (got $StaleDays)" }
    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 'account', 'channel', 'touched_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() }
    }
    $pct = {
        param([double]$part, [double]$whole)
        [math]::Round(100.0 * $part / $whole, 1, [System.MidpointRounding]::AwayFromZero)
    }
    $pctText = { param($v) $v.ToString('0.0', $inv) + '%' }

    $acc = [ordered]@{}   # lowercased account -> state
    $chan = [ordered]@{}  # lowercased channel -> @{ Channel; Touches }
    $n = 0
    foreach ($r in $rows) {
        $n++
        $a = & $get $r 'account'
        $c = & $get $r 'channel'
        $t = & $get $r 'touched_on'
        if ($a -eq '') { throw "row ${n}: empty account" }
        if ($c -eq '') { throw "row ${n}: empty channel" }
        $d = & $parseDate $t
        if ($null -eq $d) { throw "row ${n}: bad date (use yyyy-mm-dd): '$t'" }
        if ($d -gt $todayDate) { throw "row ${n}: touch dated $t is after today ($($todayDate.ToString('yyyy-MM-dd', $inv)))" }
        $ak = $a.ToLowerInvariant()
        $ck = $c.ToLowerInvariant()
        if (-not $acc.Contains($ak)) { $acc[$ak] = @{ Account = $a; Touches = 0; Last = $d; Channels = @{} } }
        $s = $acc[$ak]
        $s.Touches++
        if ($d -gt $s.Last) { $s.Last = $d }
        $s.Channels[$ck] = $true
        if (-not $chan.Contains($ck)) { $chan[$ck] = @{ Channel = $c; Touches = 0 } }
        $chan[$ck].Touches++
    }

    $list = New-Object System.Collections.Generic.List[object]
    foreach ($k in $acc.Keys) {
        $s = $acc[$k]
        $days = [int]($todayDate - $s.Last).TotalDays
        $state = if ($days -le $StaleDays) { 'recent' } else { 'stale' }
        $list.Add([pscustomobject]@{
            Account = $s.Account; Touches = $s.Touches; Channels = $s.Channels.Count
            LastTouch = $s.Last.ToString('yyyy-MM-dd', $inv); DaysSinceLastTouch = $days; State = $state
        })
    }
    $list.Sort([Comparison[object]] {
        param($x, $y)
        $c = $y.DaysSinceLastTouch.CompareTo($x.DaysSinceLastTouch)
        if ($c -ne 0) { return $c }
        [string]::CompareOrdinal($x.Account.ToLowerInvariant(), $y.Account.ToLowerInvariant())
    })

    $recent = @($list | Where-Object { $_.State -eq 'recent' }).Count
    $stale = $list.Count - $recent
    $shareStale = & $pct $stale $list.Count
    $sorted = @($list | ForEach-Object { $_.DaysSinceLastTouch } | Sort-Object)
    $mid = [int][math]::Floor($sorted.Count / 2)
    $median = if ($sorted.Count % 2 -eq 1) { [double]$sorted[$mid] } else { ([double]$sorted[$mid - 1] + [double]$sorted[$mid]) / 2.0 }
    $median = [math]::Round($median, 1, [System.MidpointRounding]::AwayFromZero)
    $totals = [pscustomobject]@{ Accounts = $list.Count; Recent = $recent; Stale = $stale; ShareStale = $shareStale; MedianDays = $median }

    $mix = New-Object System.Collections.Generic.List[object]
    foreach ($k in $chan.Keys) {
        $mix.Add([pscustomobject]@{ Channel = $chan[$k].Channel; Touches = $chan[$k].Touches; Share = (& $pct $chan[$k].Touches $n) })
    }
    $mix.Sort([Comparison[object]] {
        param($x, $y)
        $c = $y.Touches.CompareTo($x.Touches)
        if ($c -ne 0) { return $c }
        [string]::CompareOrdinal($x.Channel.ToLowerInvariant(), $y.Channel.ToLowerInvariant())
    })

    $w = 7
    foreach ($o in $list) { if ($o.Account.Length -gt $w) { $w = $o.Account.Length } }
    $cw = 7
    foreach ($o in $mix) { if ($o.Channel.Length -gt $cw) { $cw = $o.Channel.Length } }
    $todayText = $todayDate.ToString('yyyy-MM-dd', $inv)
    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add("Today: $todayText Stale after: $StaleDays days (set by you)")
    $lines.Add("Touches read: $n")
    $lines.Add('')
    $fmt = "{0,-$w} {1,7} {2,8} {3,10} {4,10} {5,6}"
    $lines.Add(($fmt -f 'account', 'touches', 'channels', 'last touch', 'days since', 'state'))
    foreach ($o in $list) { $lines.Add(($fmt -f $o.Account, $o.Touches, $o.Channels, $o.LastTouch, $o.DaysSinceLastTouch, $o.State)) }
    $lines.Add('')
    $lines.Add("Accounts: $($totals.Accounts) recent: $recent stale: $stale share stale: $(& $pctText $shareStale)")
    $lines.Add("Median days since last touch: $($median.ToString('0.0', $inv))")
    $lines.Add('')
    $cfmt = "{0,-$cw} {1,7} {2,7}"
    $lines.Add(($cfmt -f 'channel', 'touches', 'share'))
    foreach ($o in $mix) { $lines.Add(($cfmt -f $o.Channel, $o.Touches, (& $pctText $o.Share))) }
    $report = $lines -join [Environment]::NewLine
    if (-not $Quiet) { Write-Host $report }

    $out = foreach ($o in $list) {
        $o | Add-Member -NotePropertyName Today -NotePropertyValue $todayText
        $o | Add-Member -NotePropertyName StaleDays -NotePropertyValue $StaleDays
        $o | Add-Member -NotePropertyName Totals -NotePropertyValue $totals
        $o | Add-Member -NotePropertyName ChannelMix -NotePropertyValue $mix.ToArray()
        $o | Add-Member -NotePropertyName Report -NotePropertyValue $report
        $o
    }
    @($out)
}

Export-ModuleMember -Function Get-TouchRecency