Trigger to find duplicate case by subject and closing it automatically with existing case comments

Apex Class:

public class CommonVariables {
    public Static Boolean caseRepeatCheck = true;
}

Sample Trigger:

trigger CaseTrigger on Case (after insert) {
    if(CommonVariables.caseRepeatCheck) {
        CommonVariables.caseRepeatCheck = false;
        Set<String> caseSubs = new Set<String>();
        Set<Id> caseIds = new Set<Id>();
        List<Case> listCases = new List<Case>();
        List<Case> listUpdateCases = new List<Case>();
        List<CaseComment> listCaseComm = new List<CaseComment>();
        List<CaseComment> listInsertCaseComm = new List<CaseComment>();
        Map<String, Id> mapCasSubId = new Map<String, Id>();
        Map<Id, CaseComment> mapCaseIdCasComm = new Map<Id, CaseComment>();
        
        for(Case cas : trigger.new) {
            caseSubs.add(cas.Subject);
            caseIds.add(cas.Id);
        }
        
        listCases = [SELECT Id, Subject, Description FROM Case WHERE Subject IN : caseSubs AND Id NOT IN : caseIds AND Status = 'Closed'];
            
        if(listCases.size() > 0) {
            caseIds = new Set<Id>();
            for(Case cas : listCases) {
                mapCasSubId.put(cas.Subject, cas.Id);
                caseIds.add(cas.Id);
            } 
             
            listCaseComm = [SELECT Id, CommentBody, ParentId FROM CaseComment WHERE ParentId IN : caseIds];       
                    
            for(CaseComment casComm : listCaseComm) {
                mapCaseIdCasComm.put(casComm.ParentId, casComm);
            }                  
            
            for(Case cas : trigger.new) {
                if(mapCasSubId.containsKey(cas.Subject)) {
                    listUpdateCases.add(new Case(Id = cas.Id, Status = 'Closed'));
                    listInsertCaseComm.add(new CaseComment(ParentId = cas.Id, CommentBody = mapCaseIdCasComm.get(mapCasSubId.get(cas.Subject)).CommentBody));
                }
            }
            
            if(listUpdateCases.size() > 0) {
                update listUpdateCases;
            }
            
            if(listInsertCaseComm.size() > 0) {
                insert listInsertCaseComm;
            }
        }
    }
}

1 comment:

  1. Hi Infallible techie team ,

    I have tried your code but i cudnt see any duplicate cases getting identified and closing automatically

    ReplyDelete