FirstResponse.psm1
|
Set-StrictMode -Version Latest function Get-FirstResponse { <# .SYNOPSIS First-response times against an SLA, from a CSV of received and responded timestamps. .DESCRIPTION The CSV needs a header row with the columns item_id, received_at and responded_at (header matching is case-insensitive). Date-times are "yyyy-MM-dd HH:mm" and all of them are read as one and the same time zone; there is no business-hours logic. responded_at may be empty (no response yet). The clock is never read: -Now is required. Response time in hours = responded_at - received_at, shown to 1 decimal (rounded half up). A response before the receive time, a response after -Now or a receive time after -Now is an error naming the data row. States: "within SLA" (answered, response time <= SlaHours), "late" (answered, over SlaHours), "waiting" (no response, -Now minus received <= SlaHours) and "waiting - breached" (no response and over SlaHours). SlaHours is set by you (default 4, must be > 0). Statistics for the answered items: median (mean of the two middle values for an even count), p90 (nearest rank: the ceil(0.9 * n)-th smallest) and longest. The first 10 unanswered items are listed oldest first with the hours waiting. Returns one object per state (State, Items, Share, ShareText) and each carries Answered (count, median, p90 and longest in hours, or $null when nothing is answered), Unanswered (the first 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 item_id (trimmed, case-insensitive), a bad date-time (the data row is named), a bad -Now or SlaHours <= 0. Data rows are counted after the header, from 1. .EXAMPLE Get-FirstResponse -Path sample.csv -Now '2026-01-15 12:00' #> [CmdletBinding()] param( [Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Now, [decimal]$SlaHours = 4, [switch]$Quiet ) $inv = [System.Globalization.CultureInfo]::InvariantCulture $fmtDt = 'yyyy-MM-dd HH:mm' $parse = { param([string]$s) $d = [datetime]::MinValue if ([datetime]::TryParseExact($s, $fmtDt, $inv, [System.Globalization.DateTimeStyles]::None, [ref]$d)) { $d } else { $null } } if ($SlaHours -le 0) { throw "SlaHours must be greater than 0 (got $SlaHours)" } $nowDt = & $parse $Now.Trim() if ($null -eq $nowDt) { throw "bad -Now '$Now': use yyyy-MM-dd HH:mm" } 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 'item_id', 'received_at', 'responded_at') { 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() } } $slaMin = $SlaHours * 60 $seen = New-Object 'System.Collections.Generic.HashSet[string]' $counts = [ordered]@{ 'within SLA' = 0; 'late' = 0; 'waiting' = 0; 'waiting - breached' = 0 } $answered = New-Object System.Collections.Generic.List[decimal] $open = New-Object System.Collections.Generic.List[object] $n = 0 foreach ($r in $rows) { $n++ $id = & $get $r 'item_id' $rc = & $get $r 'received_at' $rs = & $get $r 'responded_at' if ($id -eq '') { throw "row ${n}: empty item_id" } if (-not $seen.Add($id.ToLowerInvariant())) { throw "row ${n}: duplicate item_id '$id'" } $recv = & $parse $rc if ($null -eq $recv) { throw "row ${n}: bad received_at '$rc' for item '$id' (use yyyy-MM-dd HH:mm)" } if ($recv -gt $nowDt) { throw "row ${n}: received_at '$rc' for item '$id' is after -Now" } if ($rs -eq '') { $mins = [decimal]($nowDt - $recv).TotalMinutes if ($mins -le $slaMin) { $counts['waiting']++ } else { $counts['waiting - breached']++ } $open.Add([pscustomobject]@{ ItemId = $id; ReceivedAt = $rc; Minutes = $mins }) } else { $resp = & $parse $rs if ($null -eq $resp) { throw "row ${n}: bad responded_at '$rs' for item '$id' (use yyyy-MM-dd HH:mm)" } if ($resp -lt $recv) { throw "row ${n}: responded_at '$rs' is before received_at '$rc' for item '$id'" } if ($resp -gt $nowDt) { throw "row ${n}: responded_at '$rs' for item '$id' is after -Now" } $mins = [decimal]($resp - $recv).TotalMinutes $answered.Add($mins) if ($mins -le $slaMin) { $counts['within SLA']++ } else { $counts['late']++ } } } $hours = { param([decimal]$m) [math]::Round($m / 60, 1, [System.MidpointRounding]::AwayFromZero) } $one = { param($v) ([decimal]$v).ToString('0.0', $inv) } $ans = $null if ($answered.Count -gt 0) { $sorted = @($answered | Sort-Object) $c = $sorted.Count if ($c % 2 -eq 1) { $med = $sorted[[int](($c - 1) / 2)] } else { $med = ($sorted[($c / 2) - 1] + $sorted[$c / 2]) / 2 } $rank = [int][math]::Floor((9 * $c + 9) / 10) $ans = [pscustomobject]@{ Count = $c MedianHours = (& $hours $med) P90Hours = (& $hours $sorted[$rank - 1]) LongestHours = (& $hours $sorted[$c - 1]) } } $unanswered = @($open | Sort-Object -Property @{ Expression = 'Minutes'; Descending = $true }, 'ItemId' | Select-Object -First 10 | ForEach-Object { [pscustomobject]@{ ItemId = $_.ItemId; ReceivedAt = $_.ReceivedAt; HoursWaiting = (& $hours $_.Minutes) } }) $lines = New-Object System.Collections.Generic.List[string] $lines.Add("Items: $n (now $($nowDt.ToString($fmtDt, $inv)), SLA $SlaHours hours)") $lines.Add('') $fmt = '{0,-19} {1,6} {2,7}' $lines.Add(($fmt -f 'state', 'items', 'share')) $objs = New-Object System.Collections.Generic.List[object] foreach ($k in $counts.Keys) { $share = [math]::Round(100 * [decimal]$counts[$k] / $n, 1, [System.MidpointRounding]::AwayFromZero) $o = [pscustomobject]@{ State = $k; Items = $counts[$k]; Share = $share; ShareText = ((& $one $share) + '%') } $objs.Add($o) $lines.Add(($fmt -f $o.State, $o.Items, $o.ShareText)) } $lines.Add('') if ($null -eq $ans) { $lines.Add('Answered: none') } else { $lines.Add("Answered: $($ans.Count). Median $(& $one $ans.MedianHours) hours, p90 $(& $one $ans.P90Hours) hours, longest $(& $one $ans.LongestHours) hours") } $lines.Add('') if ($open.Count -eq 0) { $lines.Add('Unanswered: none') } else { $lines.Add("Unanswered: $($open.Count) (first $($unanswered.Count) shown, oldest first)") foreach ($u in $unanswered) { $lines.Add(('{0} received {1} waiting {2} hours' -f $u.ItemId, $u.ReceivedAt, (& $one $u.HoursWaiting))) } } $report = $lines -join [Environment]::NewLine if (-not $Quiet) { Write-Host $report } foreach ($o in $objs) { $o | Add-Member -NotePropertyName Answered -NotePropertyValue $ans $o | Add-Member -NotePropertyName Unanswered -NotePropertyValue $unanswered $o | Add-Member -NotePropertyName Report -NotePropertyValue $report } $objs.ToArray() } Export-ModuleMember -Function Get-FirstResponse |