#------------------------------------------------------------------------------------------------------------------------------------
#  Script:   Portal Software Request - Script 1
#  Author:   www.xapity.com
#  Date:     03-Dec-2016
#  Version:  1.0
#  Comments: Used in a Xapity PowerShell Activity to process a Portal Software Request
#            Script 1:
#                *  updates Service Request Title
#                *  updates Review Activity Title
#                *  adds Portal Approver to Review Activity as the reviewer
#
#------------------------------------------------------------------------------------------------------------------------------------

Import-Module SMLets -Force
#------------------------------------------------------------------------------------------------------------------------------------
#Define the Classes and Relationships that are required 
#       Note: $ParentID is a variable supplied by Xapity PowerShell and does not need to be defined
#------------------------------------------------------------------------------------------------------------------------------------
$ParentClass = Get-SCSMClass System.WorkItem.ServiceRequest$
$ParentObject = Get-SCSMObject -Class $ParentClass -Filter "ID -eq $ParentID"

$ReviewClass = Get-SCSMClass System.WorkItem.Activity.ReviewActivity$
$ReviewActivityClass = Get-SCSMClass -Name System.Workitem.Activity.ReviewActivity$
$ReviewerClass = Get-SCSMClass -Name System.Reviewer$
$ReviewActivityHasReviewer = Get-SCSMRelationshipClass -Name System.ReviewActivityHasReviewer$
$ReviewerIsUser = Get-SCSMRelationshipClass -Name System.ReviewerIsUser$
$ReviewApproverClass = Get-SCSMRelationshipClass -Name System.WorkItemRelatesToConfigItem 
#------------------------------------------------------------------------------------------------------------------------------------
#Function used to add comment to SR
#------------------------------------------------------------------------------------------------------------------------------------
function Add-ActionComment {
    param (
            [parameter(Mandatory=$true,Position=0)][Alias('Id')]$ParentWorkItemID,
            [parameter(Mandatory=$true,Position=1)][Alias('ActionType')][String]$ActionTypeData,
            [parameter(Mandatory=$true,Position=2)][Alias('Title')][String]$AddTitle,
            [parameter(Mandatory=$true,Position=3)][Alias('Comment')][String]$AddComment,
            [parameter(Mandatory=$true,Position=4)][Alias('EnteredBy')][String]$AddEnteredBy
          )

    #Check what type of WorkItem and set variables 
    If ($ParentWorkItemID -like "SR*") {
    $WorkItemClass = Get-SCSMClass System.WorkItem.ServiceRequest$
    $WorkItemTypeProjection = "System.WorkItem.ServiceRequestProjection" }

    ElseIf ($ParentWorkItemID -like "IR*") {
    $WorkItemClass = Get-SCSMClass System.WorkItem.Incident$
    $WorkItemTypeProjection = "Xapity.ActionLog.TypeProjection.Incident"}

    ElseIf ($ParentWorkItemID -like "PR*") {
    $WorkItemClass = Get-SCSMClass System.WorkItem.Problem$
    $WorkItemTypeProjection = "Xapity.ActionLog.TypeProjection.Problem"}

    Switch($ActionTypeData) 
    {
        EmailSent {$ActionType = "System.WorkItem.ActionLogEnum.EmailSent"}
        FileAttached {$ActionType = "System.WorkItem.ActionLogEnum.FileAttached"}
        FileDeleted {$ActionType = "System.WorkItem.ActionLogEnum.FileDeleted"}
        RecordAssigned {$ActionType = "System.WorkItem.ActionLogEnum.RecordAssigned"}
        RecordClosed {$ActionType = "System.WorkItem.ActionLogEnum.RecordClosed"}
        RecordDispatched {$ActionType = "System.WorkItem.ActionLogEnum.RecordDispatched"}
        RecordEscalated {$ActionType = "System.WorkItem.ActionLogEnum.RecordEscalated"}
        RecordOpened {$ActionType = "System.WorkItem.ActionLogEnum.RecordOpened"}
        Reopened {$ActionType = "System.WorkItem.ActionLogEnum.Reopened"}
        Resolved {$ActionType = "System.WorkItem.ActionLogEnum.Resolved"}
        SurveyCompleted {$ActionType = "System.WorkItem.ActionLogEnum.SurveyCompleted"}
        TaskExecuted {$ActionType = "System.WorkItem.ActionLogEnum.TaskExecuted"}
        TemplateApplied {$ActionType = "System.WorkItem.ActionLogEnum.TemplateApplied"}
     }


    $WorkItemObject = Get-SCSMObject -Class $WorkItemClass -Filter "Id -eq $ParentWorkItemID" 
    $NewGUID = ([guid]::NewGuid()).ToString()
    $Projection = @{__CLASS = $ProjectionClass;
                    __SEED = $WorkItemObject;
                    ActionLog = @{__CLASS = "System.WorkItem.TroubleTicket.ActionLog";
                                          __OBJECT = @{Id = $NewGUID;
                                                       DisplayName = $NewGUID;
                                                       ActionType = $ActionType;
                                                       Title = $AddTitle;
                                                       Description = $AddComment;
                                                       EnteredBy  = $AddEnteredBy;
                                                       EnteredDate = (Get-Date).ToUniversalTime();
                                                       IsPrivate = $false;
                                                      }
                                         }
                   }
    New-SCSMObjectProjection -Type $WorkItemTypeProjection -Projection $Projection
}

#------------------------------------------------------------------------------------------------------------------------------------
#Update the title with the software that was chosen on the Portal
#------------------------------------------------------------------------------------------------------------------------------------
$AppendedSRTitle = $ParentObject.Title + $ParentObject.SRString
$ParentObject | Set-SCSMObject -Property Title -Value $AppendedSRTitle

#------------------------------------------------------------------------------------------------------------------------------------
#Get all Review Activities
#------------------------------------------------------------------------------------------------------------------------------------
$ReviewActivities = Get-SCSMRelatedObject -SMObject $ParentObject -Depth Recursive | ?{$_.TypeName -like "System.WorkItem.Activity.ReviewActivity*"}

#------------------------------------------------------------------------------------------------------------------------------------
#Loop through each of the activities and update the approver
#Filter using Review Activity Tag (class extension to Review Activities)
#------------------------------------------------------------------------------------------------------------------------------------
foreach ($Activity in $ReviewActivities)
    {  
    $SRComment = ""
    If ($Activity.ReviewActivityTag.DisplayName -like "*Copy Portal Approver*") #this is a Work Item tag so that we know exactly which RA to target
        { 
        $Reviewer = $null 
        $ReviewObject = Get-SCSMObject -Class $ReviewClass -Filter "ID -eq $($Activity.ID)"

        #Update the Review Activity Title 
        $AppendedRATitle = $ReviewObject.Title + "["+ $ParentObject.ID + "]: " + $AppendedSRTitle
        $ReviewObject | Set-SCSMObject -Property Title -Value $AppendedRATitle
 
        $SoftwareApprover = Get-SCSMRelatedObject -Relationship $ReviewApproverClass -SMObject $ReviewObject

        $ReviewerOptions = @{ReviewerID = "{0}"; Mustvote = $false; Veto = $false}
        $Reviewer = New-SCSMObject -Class $ReviewerClass -PropertyHashtable $ReviewerOptions -NoCommit

        $RAStep1 = New-SCSMRelationshipObject -Relationship $ReviewActivityHasReviewer -Source $ReviewObject -Target $Reviewer -NoCommit
        $RAStep2 = New-SCSMRelationshipObject -Relationship $ReviewerIsUser -Source $Reviewer -Target $SoftwareApprover -NoCommit
        $RAStep1.Commit()
        $RAStep2.Commit()


        Write-host "Added Approver: $($SoftwareApprover.DisplayName) to $($Activity.ID)"
        $SRComment = "Added Appover: $($SoftwareApprover.DisplayName) to $($Activity.ID)`r"
        } #End IF Copy Portal Approver

        #Add Action comment to Parent SR
        Add-ActionComment -Id $ParentID -ActionType "TaskExecuted"  -Title "Approver Copied to RA" -Comment $SRComment -EnteredBy "PowerShell Activity"

    } #End Foreach Activity in ReviewActivities
#------------------------------------------------------------------------------------------------------------------------------------
Write-host "Script Complete"
#------------------------------------------------------------------------------------------------------------------------------------