How to update the Case Owner to Chat agent when the Chat is accepted using Trigger in Salesforce?

How to update the Case Owner to Chat agent when the Chat is accepted using Trigger in Salesforce?

We can use a trigger on the AgentWork entity to update the Case Owner to Chat agent when the Chat is accepted in Salesforce.

Sample Trigger:

trigger AgentWork on AgentWork ( after update ) {
    
    Set < Id > setChatTranscriptIds = new Set < Id >();
    Map < Id, Id > mapChatIdAgentId = new Map < Id, Id >();
    
    for ( AgentWork objAW : trigger.new ) {
    
        /*
            Checking whether the Work Item routed is Chat and the status is Opened.
            Status Opened means the agent has accepted the Chat.
        */
        if ( objAW.Status == 'Opened' && String.valueOf( objAW.WorkItemId ).startsWith( '570' ) ) {
        
            setChatTranscriptIds.add( objAW.WorkItemId );
            mapChatIdAgentId.put( objAW.WorkItemId, objAW.UserId );
        
        }
    
    }
    
    if ( setChatTranscriptIds.size() > 0 ) {
    
        List < Case > listCases = new List < Case >();
    
        for ( LiveChatTranscript objLCT : [ SELECT Id, CaseId FROM LiveChatTranscript WHERE Id IN: setChatTranscriptIds ] ) {
            
            if ( String.isNotBlank( objLCT.CaseId ) ) {
            
                /*
                    Updating Case Owner to Chat Agent
                */
                listCases.add( new Case(
                    Id = objLCT.CaseId,
                    OwnerId = mapChatIdAgentId.get( objLCT.CaseId )
                ) );
            
            }
        
        }
        
        if ( listCases.size() > 0 ) {
        
            update listCases;
            
        }
    
    }

}

Output: 

Leave a Reply