Weedu.psm1

$script:hostUrl= $null;
$script:sessionVar = $null;
$script:logonUser = $null;

function ConvertTo-PlainText([securestring]$secure) {
    return [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure));
}

function Connect-Weedu {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Benutzername,
        [Parameter(Mandatory=$true)]
        [securestring]$Kennwort,
        [Parameter(Mandatory = $true, HelpMessage = "Url zu welcher die Verbindung hergestellt werden soll. Bsp.: https://akad-de.test-weedu.ch")]
        [string]$HostUrl
    )
    process{
        $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$($Benutzername):$(ConvertTo-PlainText $Kennwort)"));
        $basicAuthValue = "Basic $encodedCreds";
            
        $Headers = @{
            Accept = "application/json, text/javascript, */*"
            Authorization = $basicAuthValue                
        };

        try {
            $response = Invoke-WebRequest -Uri "$($HostUrl)/sts/authentication" -Method POST -Headers $Headers -SessionVariable session;
        } catch [System.Net.WebException] {
            $response = New-Object Microsoft.PowerShell.Commands.WebResponseObject $_.Exception.Response;
        }

        $script:logonUser = $response.Headers["X-Weedu-Portal-UserId"];

        if($response.StatusCode -eq 200 -and $script:logonUser) {
            $script:sessionVar = $session;
            $script:hostUrl = $HostUrl.TrimEnd("/");
            Write-Information "Login als $script:logonUser an $script:hostUrl erfolgreich" -InformationAction Continue;
        } else {
            $script:sessionVar = $null;
            $script:hostUrl = $null;
            Write-Error "Login Fehlgeschlagen, bitte erneut versuchen";
        }
    }
}

function Disconnect-Weedu {
    process {
        $script:sessionVar = $null;
        $script:hostUrl = $null;
    }
}

function Invoke-Weedu {
    param(
        [Parameter(Mandatory=$true, HelpMessage = "URI ohne Host f�r Weedu-Request, kann Platzhalter enthalten: {0}")]
        [string]$Uri,
        [Parameter(HelpMessage = "Ersetzungen f�r Platzhalter der URI")]
        [object[]]$UriParams,
        [string]$Method = "GET",
        [object]$Body,
        [switch]$StatusOnly
    )
    process{
        if (!$script:sessionVar) {
            Write-Error "Weedu Anmeldung ist erforderlich: Connect-Weedu";
            break;
        }
        if ($UriParams) {
            $Uri = [string]::Format($Uri, [array]($UriParams | ForEach-Object { if ([string]::IsNullOrEmpty($_)) { "" } else { [uri]::EscapeDataString([System.Convert]::ToString($_, [cultureinfo]::InvariantCulture)) }}));
        }
        $Uri = "$($script:hostUrl)/$($Uri.TrimStart("/"))";

        $Headers = @{
            Accept = "application/json, text/javascript, */*"
        }

        try {
            if ($Body) {
                $Body = [System.Text.Encoding]::UTF8.GetBytes(($Body | ConvertTo-JSON));
                $response = Invoke-WebRequest -Uri $Uri -Method $Method -Headers $Headers -WebSession $script:sessionVar -Body $Body -ContentType "application/json; charset=utf-8";
            } else {
                $response = Invoke-WebRequest -Uri $Uri -Method $Method -Headers $Headers -WebSession $script:sessionVar;
            }
        } catch [System.Net.WebException] {
            $response = New-Object Microsoft.PowerShell.Commands.WebResponseObject $_.Exception.Response;
        }
        Write-Verbose "Weedu-Request: $Method $Uri => $($result.StatusCode) $($result.StatusDescription)";

        if ($StatusOnly) {
            $result = $response.StatusCode;
        } else {
            $responseContentType = $response.Headers.'Content-Type'.Split(";")[0].Trim();

            switch ($responseContentType) {
                "application/json" {
                    $result = $response.Content | ConvertFrom-Json;
                }
                "text/xml" {
                    $result = [xml]$response.Content;
                }
                default {
                    $result = $response.Content;
                }
            }

            if ($response.StatusCode -ge 300) {
                Write-Error -Message "Weedu-Request $Method $Uri nicht erfolgreich: $($result.StatusCode) $($result.StatusDescription)" -TargetObject $result;
                break;
            }
        }
        return $result;
    }    
}

function Invoke-WqlQuery{
    param(
        [Parameter(Mandatory=$true, HelpMessage = "WQL Abfrage. Bsp: Personen [ohne Aktionen]")]
        [string]$WQLAbfrage,
        [Parameter(Mandatory=$false, HelpMessage = "Default 1")]
        [int]$Page = 1,
        [Parameter(Mandatory=$false, HelpMessage = "Default 100")]
        [int]$PageSize = 100
    )
    process{
        if ($Page -le 0) {
            Write-Error "$($Page) ist kein gueltiger Wert fuer Page! Bitte ein Wert groesser 0 eingeben";
            break;
        }
        if ($PageSize -le 0) {
            Write-Error "$($PageSize) ist kein gueltiger Wert fuer PageSize! Bitte ein Wert groesser 0 eingeben";
            break;
        }
        $resultConverted = Invoke-Weedu -Uri "/index/Abfragen/IndexData?auswahlSpalte=false&wql={0}" -UriParams @($WQLAbfrage) -Method POST -Body ([PSCustomObject]@{ page=$Page; pageSize=$PageSize; });

        if ($resultConverted.total -eq 0 -or $resultConverted.result.data.count -eq 0) {
            Write-Warning "Die Abfrage lieferte keine Ergebnisse"
        } else {
            $elementVon = ($Page - 1) * $PageSize + 1;
            $elementBis = $Page * $PageSize;
            if ($elementBis -gt $resultConverted.result.data.count) {
                $elementBis = $resultConverted.result.data.count;
            }
            Write-Information "$elementVon - $elementBis von $($resultConverted.result.Total) Elementen" -InformationAction Continue;
        }                
        return $resultConverted.result.data;
    }    
}

function Set-PersonenMapping {
    param(
        [Parameter(Mandatory=$true, HelpMessage = "WeeduUid der Person")]
        [Guid]$PersonUid,
        [Parameter(Mandatory=$true, HelpMessage = "Nummer des AbacusMandanten")]
        [int]$MandantenNummer,
        [Parameter(Mandatory=$false)]
        [string]$KundenNummer,
        [Parameter(Mandatory=$false)]
        [string]$AdressNummer,
        [Parameter(Mandatory=$false)]
        [string]$ADLoginName
    )
    process{
        if([string]::IsnullOrEmpty($KundenNummer) -and [string]::IsnullOrEmpty($AdressNummer) -and [string]::IsnullOrEmpty($ADLoginName)) {
            Write-Error "KundenNummer/AdressNummer/AdLoginName, mindestens ein Parameter ist erforderlich.";
            break;
        }            
        
        $Body = New-Object PSObject
        if (-not [string]::IsnullOrEmpty($ADLoginName)) {
            $Body | Add-Member NoteProperty ADUserLogonName $($ADLoginName);
        }
        if (-not [string]::IsnullOrEmpty($AdressNummer)) {
            $Body | Add-Member NoteProperty AbacusAdressnummer $($AdressNummer);
        }            
        if (-not [string]::IsnullOrEmpty($KundenNummer)) {
            $Body | Add-Member NoteProperty AbacusKundennummer $($KundenNummer);
        }            

        return Invoke-Weedu -Uri "/rest/Personen/{0}/AbacusMandanten/{1}" -UriParams @($PersonUid, $MandantenNummer) -Method PUT -Body $Body;
    }    
}

Export-ModuleMember -function Connect-Weedu
Export-ModuleMember -function Disconnect-Weedu
Export-ModuleMember -function Invoke-Weedu
Export-ModuleMember -function Invoke-WqlQuery
Export-ModuleMember -function Set-PersonenMapping