JourneyPath.psm1

Set-StrictMode -Version Latest

function Get-JourneyPath {
<#
.SYNOPSIS
Summarise journeys from a touch-level CSV: conversion rate, touches per journey, common first touches, last touches and paths.
.DESCRIPTION
The CSV needs a header row with the columns journey_id, step (a whole number giving the order of the touch inside the
journey), channel and converted (yes or no, case-insensitive, the same value on every row of a journey). Header matching
is case-insensitive. Values are trimmed. Channel names are compared exactly as written (case-sensitive) and may not be empty.
The touches of each journey are sorted by step. A journey whose rows disagree on converted, a repeated step inside one
journey, a bad step, a bad converted value, a missing column, a missing file or a file without data rows throws; row errors
name the data row, counted after the header starting at 1.
The report lists, for converted journeys only, the 3 most common first touches, last touches and full paths
(written A > B > C). Ties are listed alphabetically. This is a count of paths, not an attribution model.
Returns one object with Journeys, Converted, ConversionRatePercent, AvgTouchesConverted, AvgTouchesNotConverted,
FirstTouches, LastTouches, Paths (each Name and Count), SingleTouchSharePercent and Report.
.EXAMPLE
Get-JourneyPath -Path sample.csv
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Path
    )

    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 'journey_id', 'step', 'channel', 'converted') {
        if (-not $names.ContainsKey($need)) { throw "missing column: $need" }
    }
    $idCol = $names['journey_id']; $stepCol = $names['step']; $chCol = $names['channel']; $convCol = $names['converted']

    $order = New-Object System.Collections.Generic.List[string]
    $touches = @{}
    $conv = @{}
    $n = 0
    foreach ($r in $rows) {
        $n++
        $id = ([string]$r.PSObject.Properties[$idCol].Value).Trim()
        if ($id -eq '') { throw "row ${n}: empty journey_id" }
        $sText = ([string]$r.PSObject.Properties[$stepCol].Value).Trim()
        $step = [long]0
        if ($sText -notmatch '^-?[0-9]{1,15}$' -or -not [long]::TryParse($sText, [System.Globalization.NumberStyles]::AllowLeadingSign, $inv, [ref]$step)) {
            throw "row ${n}: bad step '$sText' (expected a whole number)"
        }
        $ch = ([string]$r.PSObject.Properties[$chCol].Value).Trim()
        if ($ch -eq '') { throw "row ${n}: empty channel" }
        $cv = ([string]$r.PSObject.Properties[$convCol].Value).Trim().ToLowerInvariant()
        if ($cv -ne 'yes' -and $cv -ne 'no') { throw "row ${n}: bad converted '$cv' (expected yes or no)" }
        if (-not $touches.ContainsKey($id)) {
            $touches[$id] = New-Object 'System.Collections.Generic.Dictionary[long,string]'
            $conv[$id] = $cv
            $order.Add($id)
        }
        elseif ($conv[$id] -ne $cv) {
            throw "journey '$id' has mixed converted values (row $n)"
        }
        if ($touches[$id].ContainsKey($step)) { throw "row ${n}: journey '$id' repeats step $step" }
        $touches[$id][$step] = $ch
    }

    $firstCount = @{}; $lastCount = @{}; $pathCount = @{}
    $convTouches = 0; $nonTouches = 0; $convJ = 0; $nonJ = 0; $single = 0
    foreach ($id in $order) {
        $steps = @($touches[$id].Keys | Sort-Object)
        $seq = @(foreach ($s in $steps) { $touches[$id][[long]$s] })
        if ($conv[$id] -eq 'yes') {
            $convJ++; $convTouches += $seq.Count
            if ($seq.Count -eq 1) { $single++ }
            $firstCount[$seq[0]] = 1 + $(if ($firstCount.ContainsKey($seq[0])) { $firstCount[$seq[0]] } else { 0 })
            $lastCount[$seq[-1]] = 1 + $(if ($lastCount.ContainsKey($seq[-1])) { $lastCount[$seq[-1]] } else { 0 })
            $pk = $seq -join ' > '
            $pathCount[$pk] = 1 + $(if ($pathCount.ContainsKey($pk)) { $pathCount[$pk] } else { 0 })
        }
        else { $nonJ++; $nonTouches += $seq.Count }
    }

    function Get-Top([hashtable]$h, [int]$k) {
        $list = New-Object 'System.Collections.Generic.List[object]'
        foreach ($key in $h.Keys) { $list.Add([pscustomobject]@{ Name = [string]$key; Count = [int]$h[$key] }) }
        $list.Sort([System.Comparison[object]]{
            param($a, $b)
            if ($a.Count -ne $b.Count) { return $b.Count.CompareTo($a.Count) }
            [string]::CompareOrdinal($a.Name, $b.Name)
        })
        @($list | Select-Object -First $k)
    }

    $total = $order.Count
    $rate = [math]::Round(100.0 * $convJ / $total, 1, [System.MidpointRounding]::AwayFromZero)
    $avgC = $null; $avgN = $null; $singleShare = $null
    if ($convJ -gt 0) {
        $avgC = [math]::Round([double]$convTouches / $convJ, 1, [System.MidpointRounding]::AwayFromZero)
        $singleShare = [math]::Round(100.0 * $single / $convJ, 1, [System.MidpointRounding]::AwayFromZero)
    }
    if ($nonJ -gt 0) { $avgN = [math]::Round([double]$nonTouches / $nonJ, 1, [System.MidpointRounding]::AwayFromZero) }
    $top1 = Get-Top $firstCount 3
    $top2 = Get-Top $lastCount 3
    $top3 = Get-Top $pathCount 3

    $f1 = { param($v) if ($null -eq $v) { 'n/a' } else { ([double]$v).ToString('0.0', $inv) } }
    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add("Journeys: $total")
    $lines.Add("Converted journeys: $convJ ($(& $f1 $rate)%)")
    $lines.Add("Average touches, converted: $(& $f1 $avgC)")
    $lines.Add("Average touches, not converted: $(& $f1 $avgN)")
    $lines.Add("Single-touch share of converted journeys: $(if ($null -eq $singleShare) { 'n/a' } else { (& $f1 $singleShare) + '%' })")
    foreach ($sect in @(@('Top first touches (converted)', $top1), @('Top last touches (converted)', $top2), @('Top paths (converted)', $top3))) {
        $lines.Add($sect[0])
        if (@($sect[1]).Count -eq 0) { $lines.Add(' none') }
        foreach ($t in $sect[1]) { $lines.Add(" $($t.Count) $($t.Name)") }
    }

    [pscustomobject]@{
        Journeys                = $total
        Converted               = $convJ
        ConversionRatePercent   = $rate
        AvgTouchesConverted     = $avgC
        AvgTouchesNotConverted  = $avgN
        FirstTouches            = $top1
        LastTouches             = $top2
        Paths                   = $top3
        SingleTouchSharePercent = $singleShare
        Report                  = ($lines -join [Environment]::NewLine)
    }
}

Export-ModuleMember -Function Get-JourneyPath