Public/Invoke-Connector.ps1

<#
.SYNOPSIS
Imports configured SuccessFactors OData resources into IAM Core Connector Space.

.DESCRIPTION
Validates the configured resource definitions, authenticates to SuccessFactors, retrieves every
configured resource, generates stable external IDs, and emits connector objects. Resource
definitions may optionally emit deterministic derived outputs or protect the primary PerPerson
national ID before storage. An optional workforce-retention policy can consistently limit person,
employment, user, and job objects using EmpEmployment.endDate.

.PARAMETER ConnectorConfiguration
Connector configuration containing authentication settings and a resourcetypes JSON array.

.OUTPUTS
System.Collections.Hashtable. Source connector objects and any configured derived outputs.

.NOTES
The connector imports source rows losslessly unless an explicitly configured national-ID
protection or workforce-retention policy is enabled. Derived outputs never replace source rows.
Data-quality and projection policy otherwise belong in source-system validation and IAM Core sync
rules.
#>

function Invoke-Connector {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        $ConnectorConfiguration
    )

    $module = $ExecutionContext.SessionState.Module
    Write-ConnectorVerbose "Starting connector module '$($module.Name)' version '$($module.Version)'"

    $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
    $emittedCounts = [ordered]@{}

    try {
        $resourceTypes = @(ConvertFrom-SFResourceTypesConfiguration -ConnectorConfiguration $ConnectorConfiguration)
        $workforceRetentionDays = Get-SFWorkforceRetentionDay -ConnectorConfiguration $ConnectorConfiguration
        $asOfDate = [DateTimeOffset]::UtcNow

        $baseUrl = [string]$ConnectorConfiguration.configuration.baseurl
        $parsedBaseUrl = $null
        $sourceHost = if ([uri]::TryCreate($baseUrl, [UriKind]::Absolute, [ref]$parsedBaseUrl)) { $parsedBaseUrl.Host } else { 'an invalid base URL' }
        $authFlow = [string]$ConnectorConfiguration.configuration.authflow
        if ([string]::IsNullOrWhiteSpace($authFlow)) { $authFlow = 'Assertion' }
        $retention = if ($null -eq $workforceRetentionDays) { 'off' } else { "$workforceRetentionDays day(s)" }
        Send-ConnectorLog -Text (
            "Reading SuccessFactors $sourceHost (company $($ConnectorConfiguration.configuration.companyid), $authFlow auth) as of " +
            "$($asOfDate.UtcDateTime.ToString('yyyy-MM-dd')): $(@($resourceTypes | ForEach-Object { $_.Type }) -join ', '); " +
            "workforce retention $retention"
        ) | Out-Null

        Connect-SF -ConnectorConfiguration $ConnectorConfiguration
        Write-ConnectorVerbose "Connected successfully"

        if ($null -eq $workforceRetentionDays) {
            foreach ($resourceTypeConfiguration in $resourceTypes) {
                $resources = @(Get-SFConfiguredResource `
                    -ResourceTypeConfiguration $resourceTypeConfiguration `
                    -BaseUrl $baseUrl `
                    -AsOfDate $asOfDate)

                Write-SFResourceType `
                    -ResourceTypeConfiguration $resourceTypeConfiguration `
                    -Resources $resources `
                    -EmittedCounts $emittedCounts
            }
        }
        else {
            # Cross-resource retention must know every retained employment before it can safely
            # emit User, EmpJob, PerPerson, and PerPersonal snapshots.
            $resourcesByType = @{}
            foreach ($resourceTypeConfiguration in $resourceTypes) {
                $resourceType = [string]$resourceTypeConfiguration.Type
                $resourcesByType[$resourceType] = @(Get-SFConfiguredResource `
                    -ResourceTypeConfiguration $resourceTypeConfiguration `
                    -BaseUrl $baseUrl `
                    -AsOfDate $asOfDate)
            }

            $retainedResourcesByType = Select-SFWorkforceRetentionResource `
                -ResourcesByType $resourcesByType `
                -RetentionDays $workforceRetentionDays `
                -AsOfDate $asOfDate

            $droppedCounts = @(
                foreach ($resourceTypeConfiguration in $resourceTypes) {
                    $resourceType = [string]$resourceTypeConfiguration.Type
                    $droppedCount = @($resourcesByType[$resourceType]).Count - @($retainedResourcesByType[$resourceType]).Count
                    if ($droppedCount -gt 0) { "$droppedCount $resourceType" }
                }
            )
            $cutoffDate = $asOfDate.UtcDateTime.Date.AddDays(-$workforceRetentionDays).ToString('yyyy-MM-dd')
            $droppedText = if ($droppedCounts.Count -gt 0) { $droppedCounts -join ', ' } else { 'nothing' }
            Send-ConnectorLog -Text "Workforce retention left out employments ended before $($cutoffDate): dropped $droppedText row(s)" | Out-Null

            foreach ($resourceTypeConfiguration in $resourceTypes) {
                $resourceType = [string]$resourceTypeConfiguration.Type
                $resources = @($retainedResourcesByType[$resourceType])

                Write-SFResourceType `
                    -ResourceTypeConfiguration $resourceTypeConfiguration `
                    -Resources $resources `
                    -EmittedCounts $emittedCounts
            }
        }

        $emittedText = if ($emittedCounts.Count -gt 0) { @($emittedCounts.GetEnumerator() | ForEach-Object { "$($_.Value) $($_.Key)" }) -join ', ' } else { 'nothing' }
        Send-ConnectorLog -Text "Import finished in $([int]$stopwatch.Elapsed.TotalSeconds)s: emitted $emittedText" | Out-Null
    }
    catch {
        # Exception text can carry request URLs and offending field values; keep only the host.
        $reason = $_.Exception.Message -replace '(https?://[^/\s'']+)[^\s'']*', '$1' -replace "(?i)\bvalue '[^']*'", 'value'
        Send-ConnectorLog -Text "Import failed after $([int]$stopwatch.Elapsed.TotalSeconds)s: $reason" -Type Error | Out-Null
        throw
    }
}