lib/Tasks.ps1

function Get-TMTask {
    <#
    .SYNOPSIS
    Gets one or more Tasks from TransitionManager using optional filters
 
    .DESCRIPTION
    This function gets one or more Tasks from TransitionManager by Id, Number,
    Task Spec Id, Status, Asset Name, Asset Type, Action Name, or Category.
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used
 
    .PARAMETER TMEvent
    The TMEvent object representing the Event to use as a filter for the Tasks retrieved
 
    .PARAMETER Id
    One or more Task Ids to filter by
 
    .PARAMETER TaskNumber
    One or more Task numbers to filter by
 
    .PARAMETER TaskSpecId
    One or more Task spec Ids to filter by
 
    .PARAMETER Status
    One or more Statuses to filter by
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated
 
    .PARAMETER AssetName
    One or more Asset names to filter by
 
    .PARAMETER AssetType
    One or more Asset types to filter by
 
    .PARAMETER ActionName
    One or more Action names to filter by
 
    .PARAMETER Category
    One or more Task categories to filter by
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .EXAMPLE
    $TMEvent = Get-TMEvent -TMSession $ProfileName -Name $EventName -ProjectId $ProjectId
    Get-TMTask -TMSession $ProfileName -Status 'Completed', 'Ready' -Event $TMEvent
 
    .OUTPUTS
    One or more TMTask objects representing the results of the filtered search
    #>


    [OutputType([TMTask[]])]
    [CmdletBinding(DefaultParameterSetName = 'All')]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $false, Position = 1)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId = $TMSessions[$TMSession].UserContext.Project.Id,

        [Parameter(Mandatory = $false)]
        [Alias('Event')]
        [TMEvent]$TMEvent,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ById')]
        [Int[]]$Id,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByTaskNumber')]
        [Alias('Number')]
        [Int[]]$TaskNumber,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByTaskSpec')]
        [Alias('TaskSpec')]
        [Int[]]$TaskSpecId,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByStatus')]
        [ArgumentCompleter({ [TMTask]::ValidStatuses })]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [String[]]$Status,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByAssetName')]
        [String[]]$AssetName,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByAssetType')]
        [String[]]$AssetType,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByActionName')]
        [String[]]$ActionName,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByCategory')]
        [String[]]$Category,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )


    begin {
        function Get-FilteredTasksAPI($SessionConfig, $JsonBody) {
            $TaskList = [System.Collections.Generic.List[TMTask]]::new()
            $RestSplat = @{
                Uri        = "https://$($SessionConfig.TMServer)/tdstm/api/task?rows=1000&page=1"
                Method     = 'GET'
                WebSession = $SessionConfig.TMRestSession
                Body       = $JsonBody
            }
            $Response = Invoke-RestMethod @RestSplat

            ## Assign the Rows variable based on what TM provides back
            if ($Response.PSObject.Properties.Name -contains 'rows') {
                $Rows = $Response.rows
            }
            elseif ($Response.PSObject.Properties.Name -contains 'records') {
                $Rows = $Response.records
            }
            elseif ($Response.PSObject.Properties.Name -contains 'tasks') {
                $Rows = $Response.tasks
            }
            foreach ($Row in $Rows) {
                try {
                    $TaskList.Add([TMTask]::new($Row))
                }
                catch {
                    Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                }
            }

            if ($Response.total -gt 1) {
                for ($i = 2; $i -le $Response.total; $i++) {
                    $RestSplat.Uri = "https://$($TMSessionConfig.TMServer)/tdstm/api/task?rows=1000&page=$i"
                    $Response = Invoke-RestMethod @RestSplat

                    ## Assign the Rows variable based on what TM provides back
                    if ($Response.PSObject.Properties.Name -contains 'rows') {
                        $Rows = $Response.rows
                    }
                    elseif ($Response.PSObject.Properties.Name -contains 'records') {
                        $Rows = $Response.records
                    }
                    elseif ($Response.PSObject.Properties.Name -contains 'tasks') {
                        $Rows = $Response.tasks
                    }

                    foreach ($Row in $Rows) {
                        try {
                            $TaskList.Add([TMTask]::new($Row))
                        }
                        catch {
                            Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                        }
                    }
                }
            }

            # ## TM v6.0.2.1 is currently not honoring Event filteing by name on the API. Remove any that shouldn't be there
            if ($TMEvent -and $TMSessionConfig.TMVersion -ge '6.0.2.1') {

                $UnfilteredTaskList = $TaskList
                $TaskList = [System.Collections.Generic.List[TMTask]]::new()
                foreach($Task in $UnfilteredTaskList){
                    if($Task.Event.Name -eq $TMEvent.name){
                        $TaskList.Add($Task)
                    }
                }
            }
            , $TaskList
        }


        function Get-FilteredTasksWS($SessionConfig, [Hashtable]$Filter) {
            $TaskList = [System.Collections.Generic.List[TMTask]]::new()

            $FilterStrings = @()
            foreach ($Key in $Filter.Keys) {
                $FilterStrings += "$($Key)=$([System.Web.HttpUtility]::UrlEncode($Filter.$Key))"
            }
            $WebRequestSplat = @{
                Uri        = "https://$($SessionConfig.TMServer)/tdstm/ws/task?" + ($FilterStrings -join '&')
                Method     = "GET"
                WebSession = $SessionConfig.TMWebSession
            }
            $Response = Invoke-WebRequest @WebRequestSplat
            if ($Response.StatusCode -in 200, 204) {
                $ResponseContent = $Response.Content | ConvertFrom-Json
                foreach ($Row in $ResponseContent.data) {
                    try {
                        $TaskList.Add([TMTask]::new($Row))
                    }
                    catch {
                        Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                    }
                }
            }

            , $TaskList
        }

        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id

        # $Tasks = [System.Collections.ArrayList]::new()
        $Tasks = [System.Collections.Generic.List[TMTask]]::new()

        # Determine which endpoint to hit based on the TM version and REST session and set up the base filters
        # REST = REST API
        # WS50 = Web Services using ATE
        # WS47 = Web Services without ATE
        if ($TMSessionConfig.TMRestSession -and $Api) {
            $Endpoint = 'REST'
            $Filters = @{
                project = $ProjectId
            }

            if ($TMEvent) {
                $Filters.event = @{name = $TMEvent.Name }
            }

            ## Wrap the request with the right syntax for Newer API version requirements
            if ($TMSessionConfig.TMVersion -ge '6.0.1.2') {
                $Filters = @{filter = $Filters; project = $ProjectId  }
            }
        }
        else {
            $Endpoint = $TMSessionConfig.TMVersion -like '4.*' ? 'WS47' : 'WS50'
            $Filters = @{
                projectId = $ProjectId
            }

            if ($TMEvent) {
                $Filters.moveEvent = $TMEvent.Id
            }
        }
    }

    process {
        switch ($PSCmdlet.ParameterSetName) {
            'ById' {
                switch ($Endpoint) {
                    'REST' {
                        $Id | ForEach-Object {
                            $RestSplat = @{
                                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($_)?project=$($ProjectId)"
                                Method     = 'GET'
                                WebSession = $TMSessionConfig.TMRestSession
                            }
                            $Response = Invoke-RestMethod @RestSplat
                            $Tasks.Add([TMTask]::new($Response))
                        }
                    }
                    {  $_ -in 'WS50',  'WS47'  } {
                        $Id | ForEach-Object {
                            $WebRequestSplat = @{
                                Uri               = "https://$($TMSessionConfig.TMServer)/tdstm/assetEntity/showComment?id=$($_)"
                                Method         = 'GET'
                                WebSession = $TMSessionConfig.TMWebSession
                            }
                            $Response = Invoke-WebRequest @WebRequestSplat
                            if ($Response.StatusCode -in 200, 204) {
                                $ResponseContent = $Response.Content | ConvertFrom-Json
                                $Tasks.Add([TMTask]::new($ResponseContent.assetComment))
                            }
                        }
                    }
                }
            }

            'ByTaskNumber' {
                switch ($Endpoint) {
                    'REST' {
                        $TaskNumber | ForEach-Object {
                            $Filters.taskNumber = $_
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.taskNumber = $TaskNumber -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $TaskNumber | ForEach-Object {
                            $Filters.taskNumber = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByTaskSpec' {
                switch ($Endpoint) {
                    {  $_ -in 'REST', 'WS50'  } {

                        # Because the WS endpoint is being hit, make sure there is a projectId filter instead of project
                        $Filters.Remove('project')
                        $Filters.projectId = $ProjectId
                        $Filters.taskSpec = $TaskSpecId -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $TaskSpecId | ForEach-Object {
                            $Filters.taskSpec = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByStatus' {
                switch ($Endpoint) {
                    'REST' {
                        $Status | ForEach-Object {
                            $Filters.status = $_
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.status = $Status -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $Status | ForEach-Object {
                            $Filters.status = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByAssetName' {
                switch ($Endpoint) {
                    'REST' {
                        $AssetName | ForEach-Object {
                            $Filters.asset = @{ name = $_ }
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.assetName = $AssetName -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $AssetName | ForEach-Object {
                            $Filters.assetName = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByAssetType' {
                switch ($Endpoint) {
                    'REST' {
                        $AssetType | ForEach-Object {
                            $Filters.asset = @{name = $_ }
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.assetName = $AssetType -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $AssetType | ForEach-Object {
                            $Filters.assetName = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByActionName' {
                switch ($Endpoint) {
                    'REST' {
                        $ActionName | ForEach-Object {
                            $Filters.action = @{name = $_ }
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.apiAction = $ActionName -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $ActionName | ForEach-Object {
                            $Filters.apiAction = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByCategory' {
                switch ($Endpoint) {
                    'REST' {
                        $Category | ForEach-Object {
                            $Filters.category = @{name = $_ }
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.category = $Category -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $ActionName | ForEach-Object {
                            $Filters.category = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            default {
                switch ($Endpoint) {
                    'REST' {
                        $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                    }
                    { $_ -in 'WS50', 'WS47' } {
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                }

            }
        }

        $Tasks
    }
}


function Update-TMTask {
    <#
    .SYNOPSIS
    Updates a Task in TransitionManager
 
    .DESCRIPTION
    This function will update a Task in TransitionManager using a TMTask object that represents
    the desired changes
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Task
    The TMTask object representing the required changes
 
    .PARAMETER Note
    A note to be added to the updated Task
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .PARAMETER Passthru
    Switch indicating that the Task should be returned after being updated
 
    .EXAMPLE
    # Get an existing Task from TransitionManager
    $Task = Get-TMTask -TMSession TMAD50 -TaskNumber 1
 
    # Change the Action associated with the Task
    $Task.Action.Id = 175
 
    # Remove the user assignment
    $Task.AssignedTo.Id = 0
 
    # Set the Task's status to Pending
    $Task.Status = 'Pending'
 
    # Change the Asset associated with the Task
    $Task.Asset.Id = 232053
 
    # Use the updated TMTask object to commit the changes to TransitionManager
    Update-TMTask -TMSession TMAD50 -Task $Task
 
    .OUTPUTS
    If the Passthru switch was provided, then a TMTask object is returned. Otherwise, none
 
    .NOTES
    Below are the available Task properties that can be updated along with the associated
    TMTask property to be changed:
 
    Action: TMTask.Action.Id
    Asset: TMTask.Asset.Id
    Event: TMTask.Event.Id
    AssignedTo: TMTask.AssignedTo.Id
    Category: TMTask.Category
    Title: TMTask.Title
    HardAssigned: TMTask.HardAssigned
    InstructionsLink: TMTask.InstructionsLink
    PercentageComplete: TMTask.PercentageComplete
    Priority: TMTask.Priority
    Team: TMTask.Team
    Status: TMTask.Status
    SendNotification: TMTask.SendNotification
    Project: TMTask.Project.Id
    predecessors: TMTask.Predecessors
    successors: TMTask.Successors
    #>


    [CmdletBinding()]
    [Alias('Set-TMTask')]
    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            ParameterSetName = 'ByObject')]
        [Alias('InputObject')]
        [TMTask]$Task,

        [Parameter(Mandatory = $false)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru
    )


    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }
    }

    process {
        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri                = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($Task.Id)"
                Method             = 'PUT'
                WebSession         = $TMSessionConfig.TMRestSession
                SkipHttpErrorCheck = $true
                StatusCodeVariable = 'StatusCode'
                Body               = ($Task.GetApiUpdateObject($Note) | ConvertTo-Json -Depth 3 -Compress)
            }

            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                if ($StatusCode -in 200, 204) {
                    if ($Passthru) {
                        [TMTask]::new($Response)
                    }
                }
                elseif (-not [String]::IsNullOrWhiteSpace($Response)) {
                    throw $Response
                }
                else {
                    throw "The response status code $StatusCode does not indicate success."
                }
            }
            catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri         = "https://$($TMSessionConfig.TMServer)/tdstm/ws/task/saveTask"
                Method         = 'POST'
                WebSession     = $TMSessionConfig.TMWebSession
                Body         = ($Task.GetWSUpdateObject() | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -in 200, 204) {
                    if (-not [String]::IsNullOrWhiteSpace($Note)) {
                        Add-TMTaskNote -TMSession $TMSession -Id $Task.Id -Note $Note
                    }
                    if ($Passthru) {
                        try {
                            [TMTask]::new(($Response.Content | ConvertFrom-Json).data.assetComment)
                        }
                        catch {
                            Write-Warning "Update was successful, but the updated Task could not be returned. Use Get-TMTask to retrieve the updated Task object."
                        }
                    }
                }
                else {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        }
    }
}


function New-TMTask {
    <#
    .SYNOPSIS
    Creates a new Task in TransitionManager
 
    .DESCRIPTION
    This function will create a new Task in TransitionManager either by using the specified
    properties or by using a TMTask object
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Task
    A TMTask object representing the new Task to be created
 
    .PARAMETER Title
    The title of the new Task
 
    .PARAMETER EventId
    The Id of the Event in which to place the new Task
 
    .PARAMETER ProjectId
    The Id of the TransitionManager project in which to place the new Task. If this is not provided,
    the project from the TMSession will be used
 
    .PARAMETER Status
    The status of the new Task
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated
 
    .PARAMETER Team
    The team to be assigned to the new Task
 
    .PARAMETER Priority
    The priority of the new Task
 
    .PARAMETER InstructionsLink
    The instructions link to place on the new Task
 
    .PARAMETER Duration
    The duration of the new task
 
    .PARAMETER SendNotification
    Indicates if the new Task should send notifications
 
    .PARAMETER Category
    The category of the new Task
 
    .PARAMETER AssignedToId
    The Id of the person that should be assigned to the new Task
 
    .PARAMETER AssetId
    The Id of the Asset to be associated with the new Task
 
    .PARAMETER ActionId
    The Id of the Action to be associated with the new Task
 
    .PARAMETER Predecessor
    One or more Task Ids that will be linked as a predecessor on the new Task
 
    .PARAMETER Successor
    One or more Task Ids that will be linked as a succecessor on the new Task
 
    .PARAMETER Note
    A note to be added to the new Task
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .PARAMETER Passthru
    Switch indicating that the new Task should be returned after creation
 
    .EXAMPLE
    $NewTaskSplat = @{
        TMSession = "TMAD60"
        Title = "Test Task - w/ Dependencies"
        EventId = 460
        ProjectId = 6269
        Status = "Ready"
        Team = 'SYS_ADMIN'
        AssignedToId = 6246
        AssetId = 232053
        Successor = 369638, 411521
        Predecessor = 411702
        Note = "This was created via PowerShell"
        Passthru = $true
        ActionId = 178
    }
    New-TMTask @NewTaskSplat
 
    .EXAMPLE
    This example gets an existing task and then changes the associated Action
    and Title as well as removes all predecessors
 
    $Task = Get-TMTask -TMSession TMAD50 -Id $NewTask.id
    $Task.Action.Id = 177
    $Task.Title = "Copy of $($NewTask.TaskNumber)"
    $Task.Predecessors = @()
    New-TMTask -TMSession TMAD50 -Task $Task -Note "This task was created as a modified copy of $($Task.Id)"
 
 
    .OUTPUTS
    If the Passthru switch was provided, then a TMTask object is returned. Otherwise, none
    #>


    [CmdletBinding(DefaultParameterSetName = 'ByProperty')]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            ParameterSetName = 'ByObject')]
        [Alias('InputObject')]
        [TMTask]$Task,

        [Parameter(Mandatory = $true,
            ParameterSetName = 'ByProperty')]
        [String]$Title,

        [Parameter(Mandatory = $true,
            ParameterSetName = 'ByProperty')]
        [Int]$EventId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ArgumentCompleter( { [TMTask]::ValidStatuses } )]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [String]$Status = 'Pending',

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [String]$Team,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ValidateRange(1, 5)]
        [Int]$Priority = 3,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [String]$InstructionsLink,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$Duration = 0,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Bool]$SendNotification = $false,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ArgumentCompleter( { [TMTask]::ValidCategories } )]
        [ValidateScript( { $_ -in [TMTask]::ValidCategories } )]
        [String]$Category = 'general',

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$AssignedToId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$AssetId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$ActionId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int[]]$Predecessor,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int[]]$Successor,

        [Parameter(Mandatory = $false)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru
    )


    begin {

        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id
    }

    process {
        if ($PSCmdlet.ParameterSetName -eq 'ByObject') {
            $Title = $Task.Title
            $EventId = $Task.Event.Id
            $ProjectId = $Task.Project.Id
            $Status = $Task.Status
            $Team = $Task.Team
            $Priority = $Task.Priority
            $InstructionsLink = $Task.InstructionsLink
            $Category = $Task.Category
            $AssignedToId = $Task.AssignedTo.Id
            $AssetId = $Task.Asset.Id
            $ActionId = $Task.Action.Id
            $Predecessor = $Task.Predecessors.TaskId
            $Successor = $Task.Successors.TaskId
            $SendNotification = $Task.SendNotification
            $Duration = $Task.Duration
        }

        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"

            Write-Verbose "Forming web request body"
            $Body = @{
                title            = $Title
                event            = @{ id = $EventId }
                project          = $ProjectId
                status           = $Status
                priority         = $Priority
                category         = $Category
                action           = @{ id = $ActionId }
                role             = $Team
                duration         = $Duration
                instructionsLink = $InstructionsLink
                assignedTo       = $AssignedToId
                asset            = @{ id = $AssetId }
                note             = $Note
                sendNotification = $SendNotification ? 1 : 0
                predecessors     = @()
                successors       = @()
            }
            if ($null -ne $Predecessor) {
                $Predecessor | ForEach-Object {
                    $Body.predecessors += @{
                        id     = -1
                        taskId = $_
                    }
                }
            }
            if ($null -ne $Successor) {
                $Successor | ForEach-Object {
                    $Body.successors += @{
                        id     = -1
                        taskId = $_
                    }
                }
            }
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task"
                Method     = 'POST'
                WebSession = $TMSessionConfig.TMRestSession
                Body       = ($Body | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                if ($Passthru) {
                    [TMTask]::new($Response)
                }
            }
            catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            $Body = @{
                comment          = $Title
                status           = $Status
                assignedTo       = $AssignedToId
                apiAction        = $ActionId
                apiActionId      = $ActionId
                category         = $Category
                assetEntity      = $AssetId
                moveEvent        = $EventId
                priority         = $Priority
                role             = $Team
                sendNotification = $SendNotification ? 1 : 0
                instructionsLink = $InstructionsLink
                duration         = $Duration
                durationScale    = "M"
                durationLocked   = 0
                manageDependency = 0
                taskDependency   = @()
                taskSuccessor    = @()
            }

            if ($null -ne $Predecessor) {
                $Predecessor | ForEach-Object {
                    $Body.taskDependency += "-1_$($_)"
                }
                $Body.manageDependency = 1
            }
            if ($null -ne $Successor) {
                $Successor | ForEach-Object {
                    $Body.taskSuccessor += "-1_$($_)"
                }
                $Body.manageDependency = 1
            }

            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/ws/task/saveTask"
                Method     = 'POST'
                WebSession = $TMSessionConfig.TMWebSession
                Body       = ($Body | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -in 200, 204) {
                    if ($Passthru) {
                        try {
                            [TMTask]::new(($Response.Content | ConvertFrom-Json).data.assetComment)
                        }
                        catch {
                            Write-Warning "Update was successful, but the updated Task could not be returned. Use Get-TMTask to retrieve the updated Task object."
                        }
                    }
                }
                else {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
    }
}


function Remove-TMTask {
    <#
    .SYNOPSIS
    Deletes a Task from TransitionManager
 
    .DESCRIPTION
    This function will delete one or more of the specified Tasks from TransitionManager
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Id
    The Id of the task to be deleted
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .EXAMPLE
    Remove-TMTask -Id 587434
 
    .EXAMPLE
    Get-TMTask -Id 129874, 458696 | Remove-TMTask
 
    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true)]
        [Int[]]$Id,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }
    }

    process {
        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            foreach ($TaskId in $Id) {
                Write-Verbose "Forming web request parameters"
                $RestSplat = @{
                    Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($Id)"
                    Method     = 'DELETE'
                    WebSession = $TMSessionConfig.TMRestSession
                }
                Write-Debug "Web Request Parameters:"
                Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
                Write-Verbose "Invoking REST method"
                try {
                    $Response = Invoke-RestMethod @RestSplat
                    Write-Debug "Response:"
                    Write-Debug ($Response | ConvertTo-Json -Depth 10)
                }
                catch {
                    throw "Error while deleting task: $($_.Exception.Message)"
                }
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/ws/asset/comment/$($Id)"
                Method     = 'DELETE'
                WebSession = $TMSessionConfig.TMWebSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        }
    }
}


function Set-TMTaskStatus {
    <#
    .SYNOPSIS
    Sets the status of a TransitionManager Task
 
    .DESCRIPTION
    This function will set/update the status of the specified Task in TransitionManager
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Id
    The Id of Task on which the status will be set
 
    .PARAMETER Status
    The new status to set on the task
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated
 
    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .EXAMPLE
    Set-TMTaskStatus -TMSession TMAD50 -Id 411521 -Status Ready
 
    .EXAMPLE
    Get-TMTask -TaskNumber 189, 2569 | Set-TMTaskStatus -Status Ready
 
    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('TaskId')]
        [Int]$Id,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ArgumentCompleter({ [TMTask]::ValidStatuses })]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [Alias('State')]
        [String]$Status,

        [Parameter(Mandatory = $false)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id
    }

    process {
        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($Id)/updateStatus?status=$Status&project=$ProjectId"
                Method     = 'POST'
                WebSession = $TMSessionConfig.TMRestSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                Write-Debug "Response:"
                Write-Debug ($Response | ConvertTo-Json -Depth 10)
            }
            catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/assetEntity/updateComment"
                Method     = 'POST'
                WebSession = $TMSessionConfig.TMWebSession
                Body       = (@{
                        id     = $Id
                        status = $Status
                    } | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
    }
}


function Add-TMTaskNote {
    <#
    .SYNOPSIS
    Adds a note to the specified Task
 
    .DESCRIPTION
    This function will add the specified note to a TransitionManager Task
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Id
    The Id of the Task to which the note should be added
 
    .PARAMETER Note
    The note to be added
 
    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .EXAMPLE
    Add-TMTaskNote -TMSession TMAD50 -Id 12356 -Note "This task was updated via PowerShell"
 
    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('TaskId')]
        [Int]$Id,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id
    }

    process {
        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($Id)/addNote"
                Method     = 'POST'
                Body       = (@{
                        note    = $Note
                        project = $ProjectId
                    } | ConvertTo-Json)
                WebSession = $TMSessionConfig.TMRestSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                Write-Debug "Response:"
                Write-Debug ($Response | ConvertTo-Json -Depth 10)
            }
            catch {
                throw "Error while adding task note: $($_.Exception.Message)"
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/ws/task/$($Id)/addNote"
                Method     = 'POST'
                Body       = (@{
                        note = $Note
                    } | ConvertTo-Json)
                WebSession = $TMSessionConfig.TMWebSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while adding task note: $($_.Exception.Message)"
            }
        }
    }
}