OptionCost.psm1

Set-StrictMode -Version Latest

function Get-OptionCost {
<#
.SYNOPSIS
Compare the cost of several options over the same number of months.
.DESCRIPTION
The CSV needs a header row with the columns option, setup_cost, monthly_cost and months_to_first_output (header
matching is case-insensitive). setup_cost and monthly_cost are non-negative numbers in any currency you choose (the
tool adds none). months_to_first_output is a non-negative whole number: your own assumption of how many months pass
before the option produces anything. Every figure is an assumption you supply; the tool says nothing about quality or fit.
Per option: total cost = setup_cost + monthly_cost * Months; average cost per month = total / Months; productive
months = max(0, Months - months_to_first_output); cost per productive month = total / productive months ('n/a' when
productive months is 0). Money is shown with 2 decimals (rounded half up). The table is sorted by total cost, lowest
first, then by option name. After it come the option with the lowest total and the option with the lowest cost per
productive month (ties by name).
Returns one object per option in table order (Option, SetupCost, MonthlyCost, MonthsToFirstOutput, TotalCost,
AveragePerMonth, ProductiveMonths, CostPerProductiveMonth as a number or $null). Each object also carries Months,
LowestTotal, LowestCostPerProductiveMonth (an option name or $null) 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 option name (the data row number is named), a bad
number (the data row number and column are named), a duplicate option (named) or Months below 1. Data rows are counted
after the header, starting at 1.
.EXAMPLE
Get-OptionCost -Path sample.csv -Months 12
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Path,
        [int]$Months = 12,
        [switch]$Quiet
    )

    if ($Months -lt 1) { throw "Months must be 1 or more (got $Months)" }
    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 'option', 'setup_cost', 'monthly_cost', 'months_to_first_output') {
        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() }
    }
    $money = {
        param([decimal]$v) $v.ToString('0.00', $inv)
    }
    $round2 = { param([decimal]$v) [math]::Round($v, 2, [System.MidpointRounding]::AwayFromZero) }
    $parseMoney = {
        param($text, $n, $col)
        $d = [decimal]0
        $styles = [System.Globalization.NumberStyles]::AllowLeadingSign -bor [System.Globalization.NumberStyles]::AllowDecimalPoint
        if (-not [decimal]::TryParse($text, $styles, $inv, [ref]$d)) { throw "row ${n}: bad number in ${col}: '$text'" }
        if ($d -lt 0) { throw "row ${n}: ${col} must not be negative: '$text'" }
        $d
    }

    $seen = New-Object 'System.Collections.Generic.HashSet[string]'
    $list = New-Object System.Collections.Generic.List[object]
    $n = 0
    foreach ($r in $rows) {
        $n++
        $name = & $get $r 'option'
        if ($name -eq '') { throw "row ${n}: empty option" }
        if (-not $seen.Add($name.ToLowerInvariant())) { throw "row ${n}: duplicate option '$name'" }
        $setup = & $parseMoney (& $get $r 'setup_cost') $n 'setup_cost'
        $monthly = & $parseMoney (& $get $r 'monthly_cost') $n 'monthly_cost'
        $mt = & $get $r 'months_to_first_output'
        $first = 0
        if ($mt -notmatch '^\d+$' -or -not [int]::TryParse($mt, [ref]$first)) {
            throw "row ${n}: months_to_first_output must be a whole number of 0 or more: '$mt'"
        }
        $total = $setup + $monthly * $Months
        $productive = [math]::Max(0, $Months - $first)
        $perProd = $null
        if ($productive -gt 0) { $perProd = & $round2 ($total / $productive) }
        $list.Add([pscustomobject]@{
            Option = $name; SetupCost = $setup; MonthlyCost = $monthly; MonthsToFirstOutput = $first
            TotalCost = (& $round2 $total); AveragePerMonth = (& $round2 ($total / $Months))
            ProductiveMonths = $productive; CostPerProductiveMonth = $perProd
            RawTotal = $total; RawPerProd = $(if ($productive -gt 0) { $total / $productive } else { $null })
        })
    }

    $byTotal = New-Object 'System.Collections.Generic.List[object]' (, $list)
    $byTotal.Sort([Comparison[object]] {
        param($x, $y)
        $c = $x.RawTotal.CompareTo($y.RawTotal)
        if ($c -ne 0) { return $c }
        [string]::CompareOrdinal($x.Option.ToLowerInvariant(), $y.Option.ToLowerInvariant())
    })
    $lowTotal = $byTotal[0]
    $lowProd = $null
    foreach ($o in $byTotal) {
        if ($null -eq $o.RawPerProd) { continue }
        if ($null -eq $lowProd) { $lowProd = $o; continue }
        $c = $o.RawPerProd.CompareTo($lowProd.RawPerProd)
        if ($c -lt 0 -or ($c -eq 0 -and [string]::CompareOrdinal($o.Option.ToLowerInvariant(), $lowProd.Option.ToLowerInvariant()) -lt 0)) { $lowProd = $o }
    }

    $w = 6
    foreach ($o in $byTotal) { if ($o.Option.Length -gt $w) { $w = $o.Option.Length } }
    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add("Options: $($byTotal.Count) over $Months months (set by you)")
    $lines.Add('')
    $fmt = "{0,-$w} {1,12} {2,12} {3,12} {4,14} {5,13} {6,10} {7,19}"
    $lines.Add(($fmt -f 'option', 'setup', 'monthly', 'first output', 'total', 'avg per month', 'productive', 'per productive month'))
    foreach ($o in $byTotal) {
        $pp = if ($null -eq $o.CostPerProductiveMonth) { 'n/a' } else { & $money $o.CostPerProductiveMonth }
        $lines.Add(($fmt -f $o.Option, (& $money $o.SetupCost), (& $money $o.MonthlyCost), $o.MonthsToFirstOutput, (& $money $o.TotalCost), (& $money $o.AveragePerMonth), $o.ProductiveMonths, $pp))
    }
    $lines.Add('')
    $lines.Add("Lowest total cost: $($lowTotal.Option) ($(& $money $lowTotal.TotalCost))")
    if ($null -eq $lowProd) { $lines.Add('Lowest cost per productive month: n/a (no option has a productive month)') }
    else { $lines.Add("Lowest cost per productive month: $($lowProd.Option) ($(& $money $lowProd.CostPerProductiveMonth))") }
    $report = $lines -join [Environment]::NewLine
    if (-not $Quiet) { Write-Host $report }

    $lowProdName = if ($null -eq $lowProd) { $null } else { $lowProd.Option }
    $out = foreach ($o in $byTotal) {
        $res = [pscustomobject]@{
            Option = $o.Option; SetupCost = $o.SetupCost; MonthlyCost = $o.MonthlyCost; MonthsToFirstOutput = $o.MonthsToFirstOutput
            TotalCost = $o.TotalCost; AveragePerMonth = $o.AveragePerMonth; ProductiveMonths = $o.ProductiveMonths
            CostPerProductiveMonth = $o.CostPerProductiveMonth
        }
        $res | Add-Member -NotePropertyName Months -NotePropertyValue $Months
        $res | Add-Member -NotePropertyName LowestTotal -NotePropertyValue $lowTotal.Option
        $res | Add-Member -NotePropertyName LowestCostPerProductiveMonth -NotePropertyValue $lowProdName
        $res | Add-Member -NotePropertyName Report -NotePropertyValue $report
        $res
    }
    @($out)
}

Export-ModuleMember -Function Get-OptionCost