BusinessDays.psm1

Set-StrictMode -Version Latest

function ConvertTo-BdDate([string]$Text) {
    $d = [datetime]::MinValue
    $ok = [datetime]::TryParseExact($Text, 'yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture,
        [System.Globalization.DateTimeStyles]::None, [ref]$d)
    if ($ok) { $d.Date } else { $null }
}

function Get-BusinessDays {
<#
.SYNOPSIS
Count business days (Monday to Friday, minus a holiday list you supply) from a start date to an end date for each CSV row.
.DESCRIPTION
The CSV needs a header row with the columns item_id, start_on and end_on (header matching is case-insensitive; dates are
yyyy-MM-dd). Business days from start_on (exclusive) to end_on (inclusive) = the number of dates in that range that fall
on Monday to Friday and are not in the holiday list. Calendar days = end_on minus start_on in whole days. The same day gives 0.
The weekend is always Saturday and Sunday; there is no other calendar.
-HolidaysPath is an optional CSV with the column holiday_on (yyyy-MM-dd) that you supply. Duplicate holiday dates are
counted once and the number of duplicate rows is reported. A holiday on a weekend changes nothing.
-MaxBusinessDays is an optional integer >= 0 that you set: items with more business days than that are marked 'over'.
The summary has the items, total business days, median (1 decimal; mean of the two middle values for an even count),
p90 (nearest rank: the ceil(0.9 * n)-th smallest), the longest item (ties: item id ascending) and, when
-MaxBusinessDays is given, the count and share (1 decimal) of items over it.
Returns one object per row in file order (ItemId, StartOn, EndOn, CalendarDays, BusinessDays, Over); each carries Summary
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, a bad date or an end before the start (the data row number is
named; holiday errors name the file line, the header being line 1), a duplicate or empty item_id, or a negative
-MaxBusinessDays. Data rows are counted after the header, starting at 1.
.EXAMPLE
Get-BusinessDays -Path sample.csv -HolidaysPath sample-holidays.csv -MaxBusinessDays 5
#>

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

    $inv = [System.Globalization.CultureInfo]::InvariantCulture
    $hasMax = $PSBoundParameters.ContainsKey('MaxBusinessDays')
    if ($hasMax -and $MaxBusinessDays -lt 0) { throw '-MaxBusinessDays must be 0 or more' }
    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "file not found: $Path" }

    # Holidays
    $holidays = New-Object 'System.Collections.Generic.HashSet[datetime]'
    $holidayRows = 0
    if ($PSBoundParameters.ContainsKey('HolidaysPath')) {
        if (-not (Test-Path -LiteralPath $HolidaysPath -PathType Leaf)) { throw "holidays file not found: $HolidaysPath" }
        $hrows = @(Import-Csv -LiteralPath $HolidaysPath)
        $hnames = @{}
        $hcols = @()
        if ($hrows.Count -gt 0) { $hcols = @($hrows[0].PSObject.Properties.Name) }
        else {
            $first = Get-Content -LiteralPath $HolidaysPath -TotalCount 1
            if ($first) { $hcols = @($first -split ',') }
        }
        foreach ($p in $hcols) { $hnames[$p.Trim().ToLowerInvariant()] = $p }
        if (-not $hnames.ContainsKey('holiday_on')) { throw 'missing column in holidays file: holiday_on' }
        $hn = 0
        foreach ($h in $hrows) {
            $hn++
            $v = $h.PSObject.Properties[$hnames['holiday_on']].Value
            $t = if ($null -eq $v) { '' } else { ([string]$v).Trim() }
            $d = ConvertTo-BdDate $t
            if ($null -eq $d) { throw "holidays file line $($hn + 1): bad date '$t' (use yyyy-MM-dd)" }
            $holidayRows++
            [void]$holidays.Add($d)
        }
    }
    # Only weekday holidays can change a count; keep a sorted array for range checks
    $weekdayHolidays = @($holidays | Where-Object { $_.DayOfWeek -ne [System.DayOfWeek]::Saturday -and $_.DayOfWeek -ne [System.DayOfWeek]::Sunday })

    # Items
    $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', 'start_on', 'end_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() }
    }

    $seen = New-Object 'System.Collections.Generic.HashSet[string]'
    $items = New-Object System.Collections.Generic.List[object]
    $n = 0
    foreach ($r in $rows) {
        $n++
        $id = & $get $r 'item_id'
        if ($id -eq '') { throw "row ${n}: empty item_id" }
        if (-not $seen.Add($id.ToLowerInvariant())) { throw "row ${n}: duplicate item_id '$id'" }
        $sText = & $get $r 'start_on'
        $eText = & $get $r 'end_on'
        $s = ConvertTo-BdDate $sText
        if ($null -eq $s) { throw "row ${n}: bad start_on '$sText' (use yyyy-MM-dd)" }
        $e = ConvertTo-BdDate $eText
        if ($null -eq $e) { throw "row ${n}: bad end_on '$eText' (use yyyy-MM-dd)" }
        if ($e -lt $s) { throw "row ${n}: end_on $eText is before start_on $sText" }
        $cal = [int]($e - $s).TotalDays
        # whole weeks hold 5 weekdays each; the remaining 0 to 6 days are checked one by one
        $bd = 5 * [math]::Floor($cal / 7)
        $rem = $cal % 7
        for ($i = 1; $i -le $rem; $i++) {
            $dow = $s.AddDays($i).DayOfWeek
            if ($dow -ne [System.DayOfWeek]::Saturday -and $dow -ne [System.DayOfWeek]::Sunday) { $bd++ }
        }
        foreach ($h in $weekdayHolidays) { if ($h -gt $s -and $h -le $e) { $bd-- } }
        $bd = [int]$bd
        $over = $hasMax -and ($bd -gt $MaxBusinessDays)
        $items.Add([pscustomobject]@{
            ItemId = $id; StartOn = $sText; EndOn = $eText; CalendarDays = $cal; BusinessDays = $bd; Over = [bool]$over
        })
    }

    # Summary
    $count = $items.Count
    $sorted = @($items | ForEach-Object { $_.BusinessDays } | Sort-Object)
    $total = ($sorted | Measure-Object -Sum).Sum
    if ($count % 2 -eq 1) { $median = [decimal]$sorted[($count - 1) / 2] }
    else { $median = ([decimal]$sorted[$count / 2 - 1] + [decimal]$sorted[$count / 2]) / 2 }
    $p90Rank = [int][math]::Floor((9 * $count + 9) / 10)   # ceil(0.9 * n) with integers
    $p90 = $sorted[$p90Rank - 1]
    $longest = $items | Sort-Object -Property @{ Expression = { $_.BusinessDays }; Descending = $true },
        @{ Expression = { $_.ItemId.ToLowerInvariant() }; Descending = $false } | Select-Object -First 1
    $overCount = @($items | Where-Object { $_.Over }).Count
    $overShare = $null
    if ($hasMax) { $overShare = [math]::Round([decimal]100 * $overCount / $count, 1, [System.MidpointRounding]::AwayFromZero) }
    $summary = [pscustomobject]@{
        Items = $count; TotalBusinessDays = [int]$total; Median = [math]::Round($median, 1, [System.MidpointRounding]::AwayFromZero)
        P90 = [int]$p90; LongestItem = $longest.ItemId; LongestBusinessDays = $longest.BusinessDays
        MaxBusinessDays = $(if ($hasMax) { $MaxBusinessDays } else { $null })
        ItemsOver = $(if ($hasMax) { $overCount } else { $null }); ItemsOverShare = $overShare
        HolidayRows = $holidayRows; HolidayDates = $holidays.Count; HolidayDuplicates = ($holidayRows - $holidays.Count)
    }

    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add("Rows read: $count")
    if ($PSBoundParameters.ContainsKey('HolidaysPath')) {
        $lines.Add("Holidays: $($holidays.Count) distinct dates from $holidayRows rows, repeated rows counted once: $($summary.HolidayDuplicates)")
    }
    else { $lines.Add('Holidays: none given') }
    $lines.Add('Weekend: Saturday and Sunday')
    $lines.Add('')
    $fmt = '{0,-10} {1,10} {2,10} {3,9} {4,10} {5,5}'
    $lines.Add(($fmt -f 'item', 'start_on', 'end_on', 'calendar', 'business', 'flag'))
    foreach ($it in $items) {
        $lines.Add(($fmt -f $it.ItemId, $it.StartOn, $it.EndOn, $it.CalendarDays, $it.BusinessDays, $(if ($it.Over) { 'over' } else { '' })).TrimEnd())
    }
    $lines.Add('')
    $lines.Add("Items: $count")
    $lines.Add("Total business days: $($summary.TotalBusinessDays)")
    $lines.Add('Median: ' + $summary.Median.ToString('0.0', $inv))
    $lines.Add("p90 (nearest rank): $($summary.P90)")
    $lines.Add("Longest: $($summary.LongestItem) ($($summary.LongestBusinessDays) business days)")
    if ($hasMax) {
        $lines.Add("Over $MaxBusinessDays business days: $overCount of $count (" + $overShare.ToString('0.0', $inv) + '%)')
    }
    $report = $lines -join [Environment]::NewLine
    if (-not $Quiet) { Write-Host $report }

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

Export-ModuleMember -Function Get-BusinessDays