Public/Send-ADUsersToBB.ps1

Function Send-ADUsersToBB {
    <#
    .SYNOPSIS
        Get the user information from the pipeline that is already converted to a GoBright object, and send it to the GoBright system
    .DESCRIPTION
        The pipeline should contain the converted user information
    .PARAMETER BrightBookingApiUrl
        Address of the GoBright API, e.g.: https://t1b.gobright.cloud/ (please get this from the 'General Settings' page of the portal)
    .PARAMETER BrightBookingApiKey
        API key of the user to use to process the import
    .PARAMETER BrightBookingIntegrationName
        Name of the integration to link the users to
    .PARAMETER UserRoleNameForNewUsers
        Name of the GoBright userrole to link new users to
    .PARAMETER DeactivateExistingUsersInSameIntegrationThatAreNotLoaded
        Deactivate users that exist in the platform in the same integration but are not loaded anymore from AD (e.g. because they are not anymore in the group you filter on)
    .PARAMETER ProcessingModeToPlatform
        By default the command will wait until the synchronization is processed by the platform and the result is known, and the result will be shown.
        Use the value "FireAndForget" if you want to fire the contents to the platform and not want to wait for the result. Please note that because of throttling you still have to wait untill the processing is finished and the new set is allowed before you can start a new synchronization
    .EXAMPLE
        Get-ADUsersForBB -Filter * | Convert-ADUsersToBBUserExport | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get all users in the Active Directory and let GoBright process it directly
    .EXAMPLE
        Get-ADUsersForBB -Filter * -SearchBase "OU=Office,DC=Company,DC=com" | Convert-ADUsersToBBUserExport | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get the users in the Active Directory, which are member of the given group and let GoBright process it directly
    .EXAMPLE
        Get-ADUsersForBB -Filter { memberOf -RecursiveMatch "CN=Administrators,DC=Company,DC=com" } -SearchBase "OU=Office,DC=Company,DC=com" | Convert-ADUsersToBBUserExport -ADUserPincodePropertyName PersonnelNumber | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get the users in the Active Directory, which in the specified SearchBase path, and use the custom property 'PersonnelNumber' as pincode and let GoBright process it directly
    .LINK
        https://support.gobright.com/
    #>


    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
        [System.Object[]]$pipelineConvertedADUsers,

        [Parameter(Mandatory = $True)]
        [string]$BrightBookingApiUrl,

        [Parameter(Mandatory = $True)]
        [string]$BrightBookingApiKey,

        [Parameter(Mandatory = $True)]
        [string]$BrightBookingIntegrationName,
       
        [Parameter(Mandatory = $False)]
        [string]$UserRoleNameForNewUsers,
      
        [Parameter(Mandatory = $False)]
        [bool]$SyncIncludesUserNFCId,
      
        [Parameter(Mandatory = $False)]
        [bool]$SyncIncludesUserPincode,
      
        [switch]$DeactivateExistingUsersInSameIntegrationThatAreNotLoaded
    )
    
    Begin {
        $convertedUsers = @()
    }

    Process {
        Foreach ($user in $pipelineConvertedADUsers) {
            $convertedUsers += $user
        }
    }
    
    End {
        Write-Output ""
        $countConvertedUsers = $convertedUsers | Measure-Object | Select-Object -ExpandProperty Count;        
        Write-Output "Will process $countConvertedUsers users from retreived data..."
                
        Write-Output ""
        Write-Output "Connecting to the GoBright API..."
        Write-Output ""
        
        # get an access token
        $access_token = Get-BBAccessToken -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiKey $BrightBookingApiKey
        
        # check if we can start a new session at all
        $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $false -ValidateCanStartNew $true
        
        # get the user roles from the API
        $userroles = Get-BBUserRole -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token
        
        If ($DeactivateExistingUsersInSameIntegrationThatAreNotLoaded.IsPresent -eq $True) {
            # get active users to compare
            $resturi = [System.Uri]::new([System.Uri]::new($BrightBookingApiUrl), "/api/users/synchronize-get-data")        

            $GetQueryParameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
            $GetQueryParameters['integrationname'] = $BrightBookingIntegrationName
                    
            $GetRequest = [System.UriBuilder]($resturi)
            $GetRequest.Query = $GetQueryParameters.ToString()

            $GetHdrs = @{}
            $GetHdrs.Add("Authorization", "Bearer " + $access_token)
            
            $usersViewForSync = $null
            Try {
                Write-Output "Getting comparison data (this might take a while)..."            
                $response = Invoke-WebRequest -TimeoutSec 1200 -Uri $GetRequest.Uri -Method Get -Headers $GetHdrs -UseBasicParsing
                        
                If ($response.StatusCode -eq 200 -or $response.StatusCode -eq 201) {                
                    $usersViewForSync = ConvertFrom-Json $([String]::new($response.Content))
                    # will proceed below...
                }
                Else {
                    throw "Could not get comparison data, unexpected statuscode $response.StatusCode"
                }
            } 
            Catch {
                $statusCode = $_.Exception.Response.StatusCode.Value__
                $responseText = $_.ErrorDetails.Message
                
                Try {
                    If ($responseText) {
                        $jsonresponse = $responseText | ConvertFrom-Json
                        If ($jsonresponse.SyncRoot) {
                            $statusMessage = $jsonresponse.SyncRoot | Select-Object * | Format-List | Out-String
                        }
                        Else {
                            $statusMessage = $responseText
                        }
                    }
                } 
                Catch {
                    $statusMessage = $responseText
                }
                
                # we want to use write-output, so it can be catched easily in to e.g. a file, but this means we need a special way of setting the color for error output
                # save the current color
                $outputOriginalForegroundColor = $host.UI.RawUI.ForegroundColor
                $outputOriginalBackgroundColor = $host.UI.RawUI.BackgroundColor
                # set the new color
                $host.UI.RawUI.ForegroundColor = 'Red'
                $host.UI.RawUI.BackgroundColor = 'Yellow'
        
                Write-Output "Could not get comparison data"
                Write-Output "Statuscode: $statusCode"
                If ($statusMessage) {
                    Write-Output "Statusdetails:"
                    $statusMessage = $statusMessage.Trim()
                    Write-Output $statusMessage
                }
                
                # restore the original color
                $host.UI.RawUI.ForegroundColor = $outputOriginalForegroundColor
                $host.UI.RawUI.BackgroundColor = $outputOriginalBackgroundColor
                
                throw "Could not get comparison data"
            }
            
            ##
            # process comparison
            Write-Output "Comparing..."
            
            If ($usersViewForSync) {
                If ($usersViewForSync.ActiveUsersInIntegration) {
                    $amountToBeDeactivated = 0;
                    # compare to get the users which are now not in the resultset from AD, and are still active in the platform -> so must be disabled
                    Foreach ($activeUserInIntegration in $usersViewForSync.ActiveUsersInIntegration) {
                        $activeUserInIntegrationFound = $false;
                        # exists this one in the $convertedUsers?
                        Foreach ($convertedUser in $convertedUsers) {
                            $found = ((-Not [string]::IsNullOrEmpty($convertedUser.UniqueImportID)) -And ($convertedUser.UniqueImportID -ceq $activeUserInIntegration.UUI)) -Or ((-Not [string]::IsNullOrEmpty($convertedUser.EmailAddress)) -And ($convertedUser.EmailAddress -eq $activeUserInIntegration.EA));
                            
                            If ($found) {
                                $activeUserInIntegrationFound = $true;
                                Break;
                            }                        
                        }
                        
                        If (-Not $activeUserInIntegrationFound) {
                            # should be disabled
                            $outputUserPropertiesHash = [ordered]@{
                                EmailAddress   = $activeUserInIntegration.EA                            
                                UniqueImportID = $activeUserInIntegration.UII
                                Active         = $false
                            }

                            $outputUser = New-Object PSObject -Property $outputUserPropertiesHash
                            $convertedUsers += $outputUser
                            
                            $amountToBeDeactivated++;
                        }
                    }
                    
                    Write-Output "Will deactivate $amountToBeDeactivated users..."
                }
            }
        }
        Else {
            Write-Output "Skipping checking for deactivation of users that exist in the platform but are not loaded anymore from AD (e.g. because they are not anymore in the group you filter on). Please use the -DeactivateExistingUsersInSameIntegrationThatAreNotLoaded switch parameter to enable deactivation checking."
        }
        Write-Output ""
        
        # do additional preprocessing for users
        $preprocessedUsers = @()
        Foreach ($convertedUser in $convertedUsers) {
            # translate the mapped roles, and remove the property (because it should not be tranfered to the CSV, only the translated value should)
            $mappedUserroleIds = @()
            If ($convertedUser.UserMappedRoles) {
                Foreach ($convertedUserMappedRole in $convertedUser.UserMappedRoles) {
                    # map to an userroleid
                    # search in the userdefined roles
                    $userroleId = ($userroles | Where-Object { $_.IsUserDefined -and $_.Name -eq $convertedUserMappedRole.RoleName } | Select-Object Id).Id;

                    If (-not $userroleId) { 
                        # if not found, search all roles
                        $userroleId = ($userroles | Where-Object { $_.Name -eq $convertedUserMappedRole.RoleName } | Select-Object Id).Id;
                    }
                    
                    If ($userroleId) { 
                        # only add if not already in, nobody like duplicates
                        If (-not ($mappedUserroleIds -contains $userroleId)) {
                            $mappedUserroleIds += $userroleId
                        }
                    }
                    Else {
                        Write-Error " - Role '$($convertedUserMappedRole.RoleName)' not found via API, user $($convertedUser.EmailAddress) cannot be mapped correctly, check the names of the roles in the mapping, they probably do not match the role names in the portal"
                    }
                }
            }
            # remove the UserMappedRoles property
            $convertedUser = $convertedUser | Select-Object -Property * -ExcludeProperty UserMappedRoles
            # add the RoleIds property
            $mappedUserroleIdsAsString = $mappedUserroleIds -join ","
            $convertedUser | Add-Member RoleIdsOrNames $mappedUserroleIdsAsString -Force
            
            $preprocessedUsers += $convertedUser
        }
        
        # generate the csv file contents, generate to string
        $csvtext = $preprocessedUsers | ConvertTo-Csv -NoTypeInformation | Out-String        
        
        # post stuff to the api
        $resturi = [System.Uri]::new([System.Uri]::new($BrightBookingApiUrl), "/api/users/batch-import-csv/schedule")            

        $QueryParameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
        $QueryParameters['integrationname'] = $BrightBookingIntegrationName
        $QueryParameters['userrolename'] = $UserRoleNameForNewUsers
                
        If ($SyncIncludesUserPincode) {
            Write-Output "Sync does include user pincodes..."
            $QueryParameters['syncincludesuserpincode'] = "true"                
        }
        Else {
            $QueryParameters['syncincludesuserpincode'] = "false"                
        }
        
        If ($SyncIncludesUserNFCId) {
            Write-Output "Sync does include user NFC ids..."
            $QueryParameters['syncincludesusernfcid'] = "true"                
        }
        Else {
            $QueryParameters['syncincludesusernfcid'] = "false"                
        }
        
        $Request = [System.UriBuilder]($resturi)
        $Request.Query = $QueryParameters.ToString()

        # convert the text so the encoding is correct to handle special characters
        $body = [System.Text.Encoding]::UTF8.GetBytes($csvtext)

        $hdrs = @{}
        $hdrs.Add("Authorization", "Bearer " + $access_token)
        
        Try {
            Write-Output ""
            Write-Output "Starting processing users in GoBright..."    
            Write-Output ""
            
            $response = Invoke-WebRequest -TimeoutSec 1200 -Uri $Request.Uri -Method Post -Body $body -ContentType 'application/text' -Headers $hdrs -UseBasicParsing
        
            If ($response.StatusCode -eq 200 -or $response.StatusCode -eq 201) {
                Write-Output "Succesfully started user synchronization to GoBright, we will now wait for the result (this will take a while)"
                Write-Output ""
                Write-Output "Processing..."

                # wait for processing finished
                $keepprocessing = $true
                $waitseconds = 30
                $totalwaitedseconds = 0
                While ($keepprocessing) {
                    Start-Sleep -Seconds $waitseconds
                    $totalwaitedseconds = $totalwaitedseconds + $waitseconds

                    $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $false
                    If ($status.IsCurrentlyProcessing) {
                        Write-Output "Processing..."

                        If ($waitseconds -lt 60) {
                            $waitseconds = $waitseconds + 5;
                        }
                    }
                    Else {
                        # finished processing
                        Break
                    }
                }
                
                Write-Output "Processing..."
                Write-Output ""
                # sleep another 32 seconds to overcome the 30 sec limit that is neccessary to do a next call to satisfy the 30sec window (doing 2 sec extra for clockskew)
                Start-Sleep -Seconds 32

                # get the result status
                $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $true

                If ($status.LastResult.Succeeded) {
                    Write-Output "Finished synchronizing users to GoBright successfully"
                }
                Else {
                    Write-Error "Synchronizing users to GoBright failed"
                }
                Write-Output "Results:"
                Write-Output $(' Succeeded : {0}' -f $status.LastResult.Succeeded)
                Write-Output $(' Created : {0}' -f $status.LastResult.AmountCreated)
                Write-Output $(' Updated : {0}' -f $status.LastResult.AmountUpdated)
                Write-Output $(' Not needed to process : {0} (already up to date, or because duplicate)' -f $status.LastResult.AmountExcludedInPreProcessing)
                Write-Output $(' Ignored : {0} (because invalid)' -f $status.LastResult.AmountIgnored)
                Foreach ($ignoredUser in $status.LastResult.IgnoredUsers) {
                    Write-Output $(' - Ignored user: {0}' -f $ignoredUser.Identifier)
                    Write-Output $(' - Validation errors:')
                    Foreach ($validationError in $ignoredUser.ValidationErrors) {
                        Write-Output $(' -> Property: {0}' -f $validationError.Property)
                        Write-Output $(' -> ErrorCode: {0}' -f $validationError.ErrorCode)
                        Write-Output $(' -> Value: {0}' -f $validationError.Value)
                    }
                }
                
                If ((-not $status.LastResult.Succeeded) -or ($status.LastResult.AmountIgnored -gt 0)) {
                    Throw "Processing the synchronization failed."
                }
            }
            Else {
                Write-Output "Could not start synchronization of users to GoBright , unexpected statuscode $response.StatusCode"
            }
        } 
        Catch {
            $statusCode = $_.Exception.Response.StatusCode.Value__
            $responseText = $_.ErrorDetails.Message
            
            Try {
                If ($responseText) {
                    $jsonresponse = $responseText | ConvertFrom-Json
                    If ($jsonresponse.SyncRoot) {
                        $statusMessage = $jsonresponse.SyncRoot | Select-Object * | Format-List | Out-String
                    }
                    Else {
                        $statusMessage = $responseText
                    }
                }
            } 
            Catch {
                $statusMessage = $responseText
            }
            
            # we want to use write-output, so it can be catched easily in to e.g. a file, but this means we need a special way of setting the color for error output
            # save the current color
            $outputOriginalForegroundColor = $host.UI.RawUI.ForegroundColor
            $outputOriginalBackgroundColor = $host.UI.RawUI.BackgroundColor
            # set the new color
            $host.UI.RawUI.ForegroundColor = 'Black'
            $host.UI.RawUI.BackgroundColor = 'Yellow'
    
            Write-Output "Synchronizing users to GoBright failed, please check the user data you have selected from your AD"
            Write-Output "Statuscode: $statusCode"
            If ($statusMessage) {
                Write-Output "Statusdetails:"
                $statusMessage = $statusMessage.Trim()
                Write-Output $statusMessage
            }
            
            # restore the original color
            $host.UI.RawUI.ForegroundColor = $outputOriginalForegroundColor
            $host.UI.RawUI.BackgroundColor = $outputOriginalBackgroundColor
            
            Throw "Synchronizing users failed"
        }
    }
}