CreditRollover.psm1
|
Set-StrictMode -Version Latest function Get-CreditRollover { <# .SYNOPSIS Month-by-month credit balance with a first-in-first-out rollover length you choose. .DESCRIPTION The CSV needs a header row with the columns month (yyyy-MM), credits_granted and credits_used (non-negative whole numbers). Header matching is trimmed and case-insensitive; extra columns are ignored. Months must be consecutive and ascending; a gap, a duplicate or a wrong order throws and names the data row (counted after the header from 1). Model: each month's grant is a batch that can be used in that month and in RolloverMonths more months. Use takes credits from the oldest unexpired batch first. Use above the available balance is recorded as short (not an error). At the end of a month the batches whose last usable month is that month expire with whatever is left. RolloverMonths 0 means credits expire at the end of the month they are granted. Returns one object per month (Month, Available, Used, Short, Expired, Closing) and each object also carries Summary (Granted, Used, Short, Expired, Closing), Batches (the batches still holding credits: GrantedMonth, Remaining, LastUsableMonth) and Report. The text report is also written to the console unless -Quiet is given. .PARAMETER RolloverMonths Whole number of extra months a grant stays usable after its own month. Default 12, set by you. .EXAMPLE Get-CreditRollover -Path sample.csv -RolloverMonths 1 #> [CmdletBinding()] param( [Parameter(Mandatory)][string]$Path, [int]$RolloverMonths = 12, [switch]$Quiet ) if ($RolloverMonths -lt 0) { throw "-RolloverMonths must be 0 or more (got $RolloverMonths)" } 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([char]0xFEFF).Trim().ToLowerInvariant()] = $p } foreach ($need in 'month', 'credits_granted', 'credits_used') { 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() } } $monthText = { param([long]$idx) ('{0:0000}-{1:00}' -f [math]::Floor($idx / 12), (($idx % 12) + 1)) } # Parse and validate every row first. $parsed = New-Object System.Collections.Generic.List[object] $n = 0 $prev = $null foreach ($r in $rows) { $n++ $m = & $get $r 'month' if ($m -notmatch '^(\d{4})-(0[1-9]|1[0-2])$') { throw "row ${n}: bad month '$m' (use yyyy-MM)" } $idx = [long]$Matches[1] * 12 + [long]$Matches[2] - 1 $vals = @{} foreach ($col in 'credits_granted', 'credits_used') { $t = & $get $r $col if ($t -notmatch '^\d{1,15}$') { throw "row ${n}: bad number '$t' in $col (use a whole number, 0 or more)" } $vals[$col] = [long]::Parse($t, $inv) } if ($null -ne $prev) { if ($idx -eq $prev) { throw "row ${n}: duplicate month '$m'" } if ($idx -lt $prev) { throw "row ${n}: month '$m' is out of order (months must ascend)" } if ($idx -gt $prev + 1) { throw "row ${n}: gap before month '$m' (months must be consecutive)" } } $prev = $idx $parsed.Add([pscustomobject]@{ Idx = $idx; Granted = $vals['credits_granted']; Used = $vals['credits_used'] }) } # Simulate. Batches stay in grant order, oldest first. $batches = New-Object System.Collections.Generic.List[object] $monthsOut = New-Object System.Collections.Generic.List[object] $tot = @{ Granted = [long]0; Used = [long]0; Short = [long]0; Expired = [long]0 } foreach ($p in $parsed) { $batches.Add([pscustomobject]@{ Idx = $p.Idx; Remaining = $p.Granted; Last = $p.Idx + $RolloverMonths }) $available = [long]0 foreach ($b in $batches) { $available += $b.Remaining } $need = $p.Used foreach ($b in $batches) { if ($need -le 0) { break } $take = [math]::Min($need, $b.Remaining) $b.Remaining -= $take $need -= $take } $short = $need $expired = [long]0 $keep = New-Object System.Collections.Generic.List[object] foreach ($b in $batches) { if ($b.Last -le $p.Idx) { $expired += $b.Remaining } else { $keep.Add($b) } } $batches = $keep $closing = [long]0 foreach ($b in $batches) { $closing += $b.Remaining } $tot.Granted += $p.Granted; $tot.Used += $p.Used; $tot.Short += $short; $tot.Expired += $expired $monthsOut.Add([pscustomobject]@{ Month = (& $monthText $p.Idx); Available = $available; Used = $p.Used; Short = $short; Expired = $expired; Closing = $closing }) } $finalClosing = if ($monthsOut.Count) { $monthsOut[$monthsOut.Count - 1].Closing } else { 0 } $summary = [pscustomobject]@{ Granted = $tot.Granted; Used = $tot.Used; Short = $tot.Short; Expired = $tot.Expired; Closing = $finalClosing } $open = @() foreach ($b in $batches) { if ($b.Remaining -gt 0) { $open += [pscustomobject]@{ GrantedMonth = (& $monthText $b.Idx); Remaining = $b.Remaining; LastUsableMonth = (& $monthText $b.Last) } } } $lines = New-Object System.Collections.Generic.List[string] $lines.Add("Months read: $($parsed.Count)") $lines.Add("RolloverMonths: $RolloverMonths (set by you)") $lines.Add('') $fmt = '{0,-8} {1,9} {2,6} {3,6} {4,8} {5,8}' $lines.Add(($fmt -f 'month', 'available', 'used', 'short', 'expired', 'closing')) foreach ($o in $monthsOut) { $lines.Add(($fmt -f $o.Month, $o.Available, $o.Used, $o.Short, $o.Expired, $o.Closing)) } $lines.Add('') $lines.Add("Totals: granted $($summary.Granted), used $($summary.Used), short $($summary.Short), expired $($summary.Expired), closing $($summary.Closing)") if ($open.Count -eq 0) { $lines.Add('Batches still holding credits: none') } else { $lines.Add('Batches still holding credits:') foreach ($b in $open) { $lines.Add(('{0} remaining {1} last usable {2}' -f $b.GrantedMonth, $b.Remaining, $b.LastUsableMonth)) } } $report = $lines -join [Environment]::NewLine if (-not $Quiet) { Write-Host $report } foreach ($o in $monthsOut) { $o | Add-Member -NotePropertyName Summary -NotePropertyValue $summary $o | Add-Member -NotePropertyName Batches -NotePropertyValue $open $o | Add-Member -NotePropertyName Report -NotePropertyValue $report } $monthsOut.ToArray() } Export-ModuleMember -Function Get-CreditRollover |