• nilesh walke 6
  • NEWBIE
  • 5 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 3
    Replies
 @RemoteAction
  global static List<SObject> getRecords(Map<String, Object> paramatersMap ){
    List<Sobject> records = new List<Sobject>();
    
    return records;
  }
  
  
  @RemoteAction
  global static List<SObject> getCollabGroupMemberIds(Map<String, Object> paramatersMap ){
    String groupId = (String)paramatersMap.get('groupId');
    List<Id>groupIds = new List<Id>();
    List<Sobject> records;
    
    try{
      if(!String.isBlank(groupId)){
        groupIds.add(Id.valueOf(groupId));
        String query = '';
        query = 'SELECT MemberId,Member.Email FROM CollaborationGroupMember WHERE CollaborationGroupId IN :groupIds AND Member.IsActive=true WITH SECURITY_ENFORCED';
        records = Database.query(query.escapeHtml4());
      }
    }
    catch(Exception e){
      System.debug(e.getMessage()+ ' - line no: '+e.getLineNumber());
    }
    return records;
  }
  
  @RemoteAction
  global static Map<String, Id> uploadAttachment(Map<String, Object> attributeMap){
    Map<String, Id> returnMap = new Map<String, Id>();
    String[] attachmentIdArray = new String[]{};
    GNT__EmailQueue__c emailObj;
    Attachment attachment = new Attachment();
    String content = (String)attributeMap.get('AttachmentBody');
    String attachmentId = (String)attributeMap.get('AttachmentId');
    Boolean isUploadDone = (Boolean)attributeMap.get('UploadDone');
    String EmailQueueIdStr = (String)attributeMap.get('EmailQueueId');
    String parentId = (String)attributeMap.get('ParentId');
    Id EmailQueueId = (Id)attributeMap.get('EmailQueueId');
    System.debug('attachId----'+attachmentId);
    if(String.isNotEmpty(attachmentId)){
      attachment = [SELECT Id,Body FROM Attachment WHERE Id =:attachmentId WITH SECURITY_ENFORCED];
      String newBody = '';
      Blob AttachmentBlob = attachment.Body;
      if(AttachmentBlob != null) {
        newBody = EncodingUtil.base64Encode(AttachmentBlob);
      }
      newBody += content;
      //attch.Body = Blob.valueOf(newBody);
      if(Schema.sObjectType.Attachment.fields.Body.isCreateable() && Schema.sObjectType.Attachment.fields.Body.isupdateable()){
        attachment.Body = EncodingUtil.base64Decode(newBody);
      }
      if(Schema.sObjectType.Attachment.isCreateable() && Schema.sObjectType.Attachment.isupdateable()){
        upsert attachment;
      }
      returnMap.put('AttchId', attachment.Id);
      System.debug('New Attachment----'+attachment.Id);
    }else{
      if(content !=null){
        String[] base64result = safeSplit(content,',');
        System.debug('Attachment Size --->'+base64result.size());
        if(base64result !=null && base64result.size() > 1){
          
          System.debug('Attachment Body3--->'+base64result[1]);
          if(Schema.sObjectType.Attachment.fields.Body.isCreateable()){
            attachment.Body = EncodingUtil.base64Decode(base64result[1]);
          }
          System.debug('base64Decode3-->'+attachment.Body);
          if(Schema.sObjectType.Attachment.fields.Name.isCreateable()){
            attachment.Name = (String)attributeMap.get('AttachmentName');
          }
          if(Schema.sObjectType.Attachment.fields.ParentId.isCreateable()){
            attachment.ParentId = (Id)attributeMap.get('EmailQueueId');
          }
          if(Schema.sObjectType.Attachment.isCreateable()){
            insert attachment;
          }
          returnMap.put('AttchId', attachment.Id);
          System.debug('New Attachment----'+attachment.Id);
        }
      
      }
    }
    
    if(isUploadDone){
      emailObj  =  getEmailQueueDetails(EmailQueueIdStr);
      attachmentIdArray = getAttachmentIdOnEmailQueueforId(EmailQueueId);
      System.debug('GNT__EmailQueue__c Update...'+emailObj);
      System.debug('Attachment Array Id..'+attachmentIdArray);
      Boolean sendACopyToMe = (Boolean)attributeMap.get('sendACopyToMe');
      // add to address, cc address, Bcc address in map, GNT__Subject__c and email body
      String toAddress =(String)attributeMap.get('toAddress');
      
      String ccAddress =(String)attributeMap.get('ccAddress');
      
      String subject =(String)attributeMap.get('GNT__Subject__c');
      
      String emailBody=(String)attributeMap.get('body');
      
      String bccAddress = '';
      if(sendACopyToMe){
        bccAddress = UserInfo.getUserEmail();
      }
      
      sendEMail(emailObj, parentId, sendACopyToMe, attachmentIdArray, toAddress, ccAddress, bccAddress, subject, emailBody);
    }
    return  returnMap;
  }
  
  
 global with sharing class SystemEmailCompCtrl {
 public boolean isExternal {
    get {
      User user = [SELECT ContactId FROM User WHERE Id =:UserInfo.getUserId() AND IsActive=true WITH SECURITY_ENFORCED];
      if(user.ContactId != null){
        return true;
      }else {
        return false;
      }
    }
  }
  
  public boolean isAttachmentEnabled {
    get {
      return GNT.KeyValueStoreHelper.getBooleanValue('EnableEmailAttachment',true) == null ? false : GNT.KeyValueStoreHelper.getBooleanValue('EnableEmailAttachment',true);
    }
  }
  
  global class ResultWrapper{
    public Id id;
    public String name;
    public String email;
    public String collaborationType;
    public Integer memberCount;
    public String objType;
    public ResultWrapper(Sobject sobj,Boolean isGroup){
      this.id = (Id)sobj.get('Id');
      String strId = String.valueof(Id);
      if(strId.startsWith('005')){
        this.objType = 'User';
      }else {
        this.objType = 'Contact';
      }
      
      this.name = (String)sobj.get('Name');
      if(isGroup){
        this.collaborationType = (String)sobj.get('CollaborationType');
        this.memberCount = (Integer)sobj.get('MemberCount');
      }
      else{
        this.email = (String)sobj.get('Email');
      }
    }
  }
  
  @RemoteAction
  global static List<ResultWrapper> getRecordsNew(Map<String, Object> paramatersMap ){
    System.debug('In getRecordsNew::');
    String searchString = (String)paramatersMap.get('searchString');
    String objectApiName = (String)paramatersMap.get('objectApiName');
    String fieldToDisplay = (String)paramatersMap.get('fieldToDisplay');
    String fieldBindToTarget = (String)paramatersMap.get('fieldBindToTarget');
    String fieldToFilter = (String)paramatersMap.get('fieldToFilter');
    String selectedRecordIds = (String)paramatersMap.get('selectedRecordIds');
    
    
    String searchType = (String)paramatersMap.get('searchType');
    Boolean isExternalUser = false;
    if(searchType.trim().equals('External')){
      isExternalUser = true;
    }
    List<Sobject> records;
    List<ResultWrapper> resultWrappers = new List<ResultWrapper>();
    try{
      
      List<String> lstSelectedRecordIds = selectedRecordIds.split(',');
      Set<String> filteredRecordIds = new Set<String>();
      if(lstSelectedRecordIds.size()>0){
        filteredRecordIds.addall(lstSelectedRecordIds);
      }
      
      if(filteredRecordIds.size()>0){
        System.debug('filteredRecordIds::'+filteredRecordIds);
        
        // segrgate ids as user or contact ids
        List<Id>filteredUserIds = new List<Id>();
        List<Id>filteredContactIds = new List<Id>();
        for (String filteredRecordId : filteredRecordIds) {
          System.debug('filteredRecordId::'+filteredRecordId);
          if(filteredRecordId.startsWith('005')){
            filteredUserIds.add(filteredRecordId);
          }
          if(filteredRecordId.startsWith('003')){
            filteredContactIds.add(filteredRecordId);
          }
        }
        Set<String>filteredEmails = new Set<String>();
        List<User>filteredUserDetails = filteredUserIds.size()>0 ? [SELECT Email FROM User WHERE Id IN:filteredUserIds WITH SECURITY_ENFORCED] : null;
        List<Contact>filteredContactDetails = filteredContactIds.size()>0 ? [SELECT Email FROM Contact WHERE Id IN:filteredContactIds WITH SECURITY_ENFORCED] : null;
        if(filteredUserDetails != null && filteredUserDetails.size()>0){
          for(User user : filteredUserDetails){
            filteredEmails.add(user.Email);
          }
        }
        if(filteredContactDetails != null && filteredContactDetails.size()>0){
          for(Contact contact : filteredContactDetails){
            filteredEmails.add(contact.Email);
          }
        }
        system.debug('filteredEmails::'+filteredEmails);
      }
      String userQuery = '';
      
            if(objectApiName.toLowercase() == 'contact'){
        String contactQuery = 'SELECT Id,Name,Email FROM Contact WHERE Id NOT IN :filteredRecordIds AND '+fieldToFilter+' LIKE \'%'+string.escapeSingleQuotes(searchString)+'%\' AND Email != NULL WITH SECURITY_ENFORCED';
        List<Sobject> contacts = Database.query(contactQuery.escapeHtml4());
        for(Integer count=0;count<contacts.size();count++){
          resultWrappers.add(new ResultWrapper(contacts[count],false));
        }
      }
    }
    catch(Exception e){
      System.debug(e.getMessage()+ ' - line no: '+e.getLineNumber());
    }
    
    return resultWrappers;
  }
public without sharing class EmailQueueTriggerHelper extends GNT.TriggerHelper{
    public static boolean skipAll = false;
    public override void processAfterUpdate() {
        if (skipAll == false) {
            systemEmailHelper();
        }
    }
    public static void systemEmailHelper(){
        //as we have written this code in after update we need to 1st get those records from by SQOL and then only we can do DML operation on those records.
        //For the same writen dynamic query as we need to clone new values, so to avoid adding all flieds every time used dynamic query
        sObjectType objType = Schema.getGlobalDescribe().get('GNT__EmailQueue__c');
        Map<String,Schema.SObjectField> mfields = objType.getDescribe().fields.getMap();
        String fields = '';
        for (SObjectField field : mfields.values()) {
          fields += field + ',';
        }
        fields = fields.removeEnd(',');
        Set<Id> setEmailId = new Set<Id>();
        for(GNT__EmailQueue__c obj : (List<GNT__EmailQueue__c>)Trigger.new){
            setEmailId.add(obj.id);
        }
        String query4Queue = 'SELECT '+fields+' FROM GNT__EmailQueue__c where Id IN :setEmailId';
        List<GNT__EmailQueue__c> lstEmailQueues = Database.query(query4Queue);
    
        List<GNT__EmailQueue__c> lstEmailsToSplit = new List<GNT__EmailQueue__c>(); //1st we will select records which we need to split email ids
        List<GNT__EmailQueue__c> lstEmailsToUpdatewithClone = new List<GNT__EmailQueue__c>();
        Map<Id,GNT__EmailQueue__c> mapEmails = new map<Id,GNT__EmailQueue__c>();
        for(GNT__EmailQueue__c obj : lstEmailQueues){
            GNT__EmailQueue__c oldRec = (GNT__EmailQueue__c)trigger.oldMap.get(obj.Id);
            if(obj.GNT__ToEmails__c.contains(',') && obj.GNT__Status__c =='Processed' && oldRec.GNT__Status__c=='Queued' && obj.IsClone__c == false){
                
                obj.isClone__c= true;
                lstEmailsToSplit.add(obj);
                mapEmails.put(obj.Id,obj);
            }else{
                obj.ToAddress__c = obj.GNT__ToEmails__c;
                obj.isClone__c= true;
                lstEmailsToUpdatewithClone.add(obj);
            }
        }
        List<GNT__EmailQueue__c> lstEmailsToInsert = new List<GNT__EmailQueue__c>();
        if(lstEmailsToSplit.size()>0){
            map<Id,List<String>> mapEmailRecordsWthMultiEmails = new map<Id,List<String>>();
            for(GNT__EmailQueue__c obj : lstEmailsToSplit){
                mapEmailRecordsWthMultiEmails.put(obj.id,obj.GNT__ToEmails__c.split(','));
            }
            
            for(Id obj : mapEmailRecordsWthMultiEmails.keySet()){ 
                List<String> lstEmails = mapEmailRecordsWthMultiEmails.get(obj);
                if(lstEmails.size()>0){
                    for(String str : lstEmails){
                        GNT__EmailQueue__c newRec1 = mapEmails.get(obj);
                        GNT__EmailQueue__c newRec = newRec1.clone(false, false, false, false);
                        newRec.id = null;
                        newRec.ToAddress__c = str;
                        newRec.isClone__c= true;
                        lstEmailsToInsert.add(newRec);
                    }
                }
            }
        }
        List<GNT__EmailQueue__c> lstToUpsrtEmails = new List<GNT__EmailQueue__c>();
        if(lstEmailsToInsert.size()>0){
            lstToUpsrtEmails.addAll(lstEmailsToInsert);
        }
        if(lstEmailsToUpdatewithClone.size()>0){
            lstToUpsrtEmails.addAll(lstEmailsToUpdatewithClone);
        }
        if(lstToUpsrtEmails.size()>0){
            lstToUpsrtEmails.addAll(lstEmailsToSplit);
        }
        if(lstToUpsrtEmails.size()>0){
            skipAll = true;
            upsert lstToUpsrtEmails;
            skipAll = false;
        }
    }
}
global with sharing class ReviewStepValidationHelper { 

    public ReviewStepValidationHelper(){}
    
    global static List<String> validateReviewSteps(List<Id> stepIds, Boolean validateSteps, Boolean validateWeights, Boolean validateReviewers) {
        return validateSteps([SELECT Id, Name, StepNumber__c, Weight__c,
                             (SELECT Id, Name, Required__c, PanelName__c, MinimumNumberOfReviewers__c, EndDate__c, Weight__c, DueInDays__c FROM Review_Panels__r) 
                             FROM ReviewStep__c WHERE Id IN: stepIds AND Template__c = false ORDER BY StepNumber__c], 
                             validateSteps,
                             validateWeights,
                             validateReviewers
                            );
    }    
    global static List<String> validateProgramTemplates(Id programId, Boolean validateSteps, Boolean validateWeights, Boolean validateReviewers) {
        return validateSteps([SELECT Id, Name, StepNumber__c, Weight__c,
                             (SELECT Id, Name, Required__c, PanelName__c, MinimumNumberOfReviewers__c, EndDate__c, Weight__c, DueInDays__c FROM Review_Panels__r) 
                             FROM ReviewStep__c WHERE Program__c =: programId AND Template__c = true ORDER BY StepNumber__c],
                             validateSteps,
                             validateWeights,
                             validateReviewers
                            );
    }
    
    global static List<String> validateAnnouncementTemplates(Id announcementId, Boolean validateSteps, Boolean validateWeights, Boolean validateReviewers) {
        return validateSteps([SELECT Id, Name, StepNumber__c, Weight__c,
                             (SELECT Id, Name, Required__c, PanelName__c, MinimumNumberOfReviewers__c, EndDate__c, Weight__c, DueInDays__c FROM Review_Panels__r) 
                             FROM ReviewStep__c WHERE Announcement__c =: announcementId AND Template__c = true ORDER BY StepNumber__c],
                             validateSteps,
                             validateWeights,
                             validateReviewers
                            );
    }
    
    global static List<String> validateAnnouncementSteps(Id announcementId, Boolean validateSteps, Boolean validateWeights, Boolean validateReviewers) {
        return validateSteps([SELECT Id, Name, StepNumber__c, Weight__c,
                             (SELECT Id, Name, Required__c, PanelName__c, MinimumNumberOfReviewers__c, EndDate__c, Weight__c, DueInDays__c FROM Review_Panels__r) 
                             FROM ReviewStep__c WHERE Announcement__c =: announcementId AND Template__c = false ORDER BY StepNumber__c],
                             validateSteps,
                             validateWeights,
                             validateReviewers
                            );
    }
    
    global static List<String> validateSteps(List<ReviewStep__c> steps, Boolean validateSteps, Boolean validateWeights, Boolean validateReviewers) {
        List<String> errors = new List<String>();
        try{
            List<Id> stepIds = new List<Id>();
            Set<Id> weightedPanels = new Set<Id>();
            Map<Id, String> panelNameMap = new Map<Id, String>();
            Integer stepNumber = 0;
            Boolean hasStepError = false;
            Boolean weightError = false;
            String stepName = '';
            Decimal weight;
            Decimal stepWeight = 0;
            for(ReviewStep__c step: steps) {
                if(validateSteps) {
                    if(step.StepNumber__c != stepNumber + 1) {
                        hasStepError = true;
                    } else {
                        stepNumber += 1;
                    }
                }
                stepName = step.Name;
                stepWeight += step.Weight__c;
                stepIds.add(step.Id);
                weight = 0;
                if(step.Review_Panels__r.size() > 0) {
                    for(ReviewPanel__c rp: step.Review_Panels__r) {
                        if(rp.Weight__c > 0) {
                            weightedPanels.add(rp.Id);
                            weight += rp.Weight__c;
                        }
                        if(validateReviewers) {
                            /*
                            if(rp.ReviewersCount__c < 1 && rp.Required__c){    // MinimumNumberOfReviewers__c
                                errors.add(step.Name + ' - ' + rp.PanelName__c + ': This panel is required and must have a minimum of 1 reviewer.');
                            }*/
                            //if(rp.ReviewersCount__c < rp.MinimumNumberOfReviewers__c){
                            //    errors.add('Setup Tab - ' + step.Name + ' - ' + rp.PanelName__c + ': This form only has ' + rp.ReviewersCount__c + ' of the required ' + rp.MinimumNumberOfReviewers__c + ' reviewers.');
                            //}
                            if(rp.EndDate__c == null && rp.DueInDays__c == null){
                                errors.add('Setup Tab - ' + step.Name + ' - ' + rp.PanelName__c + ': A value for the Due in Days field is required.');
                            } else if(rp.EndDate__c != null && rp.EndDate__c < System.TODAY()) {
                                errors.add('Setup Tab - ' + step.Name + ' - ' + rp.PanelName__c + ': The form due date(' + rp.EndDate__c + ') cannot be before the current date.');
                            }
                        }
                        panelNameMap.put(rp.Id, step.Name + ' - ' + rp.PanelName__c);
                    }
                } else if(validateSteps && step.Name != 'Funding Decision Memo'){
                    errors.add('Setup Tab - ' + step.Name + ': At least one form is required for this review step.');
                }
                if(weight != 0 && weight != 100 && validateWeights) {
                    if(step.Weight__c != 0) {
                        errors.add('Setup Tab - ' + step.Name + ': The total Review Form weight must equal 100% for a weighted step. It is currently ' + weight + '%.');
                    } else {
                        errors.add('Setup Tab - ' + step.Name + ': The total Review Form weight must equal 100% or 0%. It is currently ' + weight + '%.');
                    }
                } else if(step.Weight__c != 0 && weight != 100 && validateWeights) {
                    errors.add('Setup Tab - ' + step.Name + ': The total Review Form weight must equal 100% for a weighted step. It is currently ' + weight + '%.');
                }
            }
            System.debug('errors 1: '+errors);
            if(validateSteps) {
                if(validateWeights && stepWeight != 100) {
                    errors.add('Setup Tab - The total Review Step weight must equal 100%. It is currently ' + stepWeight + '%.');
                }
                if(hasStepError) {
                    errors.add('Setup Tab - Sequence of Review step must start from 1 and have no gaps.');
                }
                if(stepName != 'Funding Decision Memo') {
                    errors.add('Setup Tab - The Funding Decision Memo must always be the final step in the review process');
                }
            }
            System.debug('errors 2: '+errors);
            if(validateWeights) {
                List<ReviewPanelCategory__c> categories = [SELECT Id, Name, Weight__c, ReviewPanel__c, ReviewPanel__r.PanelName__c, ReviewPanel__r.ReviewStep__r.Name, (SELECT MaxScore__c FROM ReviewCategoryQuestions__r) FROM ReviewPanelCategory__c WHERE ReviewPanel__r.ReviewStep__c IN: stepIds];
                Map<Id, Decimal> weightMap = new Map<Id, Decimal>();
                Decimal maxScore;
                Boolean invalidScore;
                Set<Id> panelsWithCategories = new Set<Id>();
                for(ReviewPanelCategory__c category: categories) {
                    panelsWithCategories.add(category.ReviewPanel__c);
                    invalidScore = false;
                    if(!weightMap.containsKey(category.ReviewPanel__c)) {
                        weightMap.put(category.ReviewPanel__c, 0);
                    }
                    weightMap.put(category.ReviewPanel__c, weightMap.get(category.ReviewPanel__c) + category.Weight__c);
                    maxScore = 0;
                    for(ReviewPanelCategoryQuestion__c question: category.ReviewCategoryQuestions__r) {
                        maxScore += question.MaxScore__c;
                        if(question.MaxScore__c != 0 && category.Weight__c == 0) {
                            invalidScore = true;
                        }
                    }
                    if(invalidScore) {
                        errors.add('Setup Tab - ' + category.ReviewPanel__r.ReviewStep__r.Name + ' - ' + category.ReviewPanel__r.PanelName__c + ': A score cannot be associated to a question in the ' + category.Name + ' section because it does not have a weight.');
                    }
                    if(maxScore == 0 && category.Weight__c != 0) {
                        errors.add('Setup Tab - ' + category.ReviewPanel__r.ReviewStep__r.Name + ' - ' + category.ReviewPanel__r.PanelName__c + ': A score must be associated to at least one question in the ' + category.Name + ' section because it is weighted.');
                    }
                }
                System.debug('errors 3: '+errors);
                for(Id key: panelNameMap.keySet()) {
                    if(!panelsWithCategories.contains(key)) {
                        errors.add('Setup Tab - ' + panelNameMap.get(key) + ': At least one section must be added to this form.');
                    }
                }
                if(weightMap.size() > 0) {
                    for(Id key: weightMap.keySet()) {
                        if(weightMap.get(key) != 100 && weightMap.get(key) != 0) {
                            errors.add('Setup Tab - ' + panelNameMap.get(key) + ': The total section weight must equal 100% or 0%. It is currently ' + weightMap.get(key) + '%.');
                        }
                        if(weightedPanels.contains(key) && weightMap.get(key) == 0) {
                            errors.add('Setup Tab - ' + panelNameMap.get(key) + ': A weighted form must contain weighted sections.');
                        }
                    }
                } else {
                    for(Id panelId: weightedPanels) {
                        errors.add('Setup Tab - ' + panelNameMap.get(panelId) + ': A weighted form must contain weighted sections.');
                    }
                }
                System.debug('errors 4: '+errors);
            }
            System.debug('errors 5: '+errors);
            return errors;
        } catch(Exception e) {
            errors.add(e.getMessage());
            return errors;
        }
    }
 global with sharing class SystemEmailCompCtrl {
 public boolean isExternal {
    get {
      User user = [SELECT ContactId FROM User WHERE Id =:UserInfo.getUserId() AND IsActive=true WITH SECURITY_ENFORCED];
      if(user.ContactId != null){
        return true;
      }else {
        return false;
      }
    }
  }
  
  public boolean isAttachmentEnabled {
    get {
      return GNT.KeyValueStoreHelper.getBooleanValue('EnableEmailAttachment',true) == null ? false : GNT.KeyValueStoreHelper.getBooleanValue('EnableEmailAttachment',true);
    }
  }
  
  global class ResultWrapper{
    public Id id;
    public String name;
    public String email;
    public String collaborationType;
    public Integer memberCount;
    public String objType;
    public ResultWrapper(Sobject sobj,Boolean isGroup){
      this.id = (Id)sobj.get('Id');
      String strId = String.valueof(Id);
      if(strId.startsWith('005')){
        this.objType = 'User';
      }else {
        this.objType = 'Contact';
      }
      
      this.name = (String)sobj.get('Name');
      if(isGroup){
        this.collaborationType = (String)sobj.get('CollaborationType');
        this.memberCount = (Integer)sobj.get('MemberCount');
      }
      else{
        this.email = (String)sobj.get('Email');
      }
    }
  }
  
  @RemoteAction
  global static List<ResultWrapper> getRecordsNew(Map<String, Object> paramatersMap ){
    System.debug('In getRecordsNew::');
    String searchString = (String)paramatersMap.get('searchString');
    String objectApiName = (String)paramatersMap.get('objectApiName');
    String fieldToDisplay = (String)paramatersMap.get('fieldToDisplay');
    String fieldBindToTarget = (String)paramatersMap.get('fieldBindToTarget');
    String fieldToFilter = (String)paramatersMap.get('fieldToFilter');
    String selectedRecordIds = (String)paramatersMap.get('selectedRecordIds');
    
    
    String searchType = (String)paramatersMap.get('searchType');
    Boolean isExternalUser = false;
    if(searchType.trim().equals('External')){
      isExternalUser = true;
    }
    List<Sobject> records;
    List<ResultWrapper> resultWrappers = new List<ResultWrapper>();
    try{
      
      List<String> lstSelectedRecordIds = selectedRecordIds.split(',');
      Set<String> filteredRecordIds = new Set<String>();
      if(lstSelectedRecordIds.size()>0){
        filteredRecordIds.addall(lstSelectedRecordIds);
      }
      
      if(filteredRecordIds.size()>0){
        System.debug('filteredRecordIds::'+filteredRecordIds);
        
        // segrgate ids as user or contact ids
        List<Id>filteredUserIds = new List<Id>();
        List<Id>filteredContactIds = new List<Id>();
        for (String filteredRecordId : filteredRecordIds) {
          System.debug('filteredRecordId::'+filteredRecordId);
          if(filteredRecordId.startsWith('005')){
            filteredUserIds.add(filteredRecordId);
          }
          if(filteredRecordId.startsWith('003')){
            filteredContactIds.add(filteredRecordId);
          }
        }
        Set<String>filteredEmails = new Set<String>();
        List<User>filteredUserDetails = filteredUserIds.size()>0 ? [SELECT Email FROM User WHERE Id IN:filteredUserIds WITH SECURITY_ENFORCED] : null;
        List<Contact>filteredContactDetails = filteredContactIds.size()>0 ? [SELECT Email FROM Contact WHERE Id IN:filteredContactIds WITH SECURITY_ENFORCED] : null;
        if(filteredUserDetails != null && filteredUserDetails.size()>0){
          for(User user : filteredUserDetails){
            filteredEmails.add(user.Email);
          }
        }
        if(filteredContactDetails != null && filteredContactDetails.size()>0){
          for(Contact contact : filteredContactDetails){
            filteredEmails.add(contact.Email);
          }
        }
        system.debug('filteredEmails::'+filteredEmails);
      }
      String userQuery = '';
      
            if(objectApiName.toLowercase() == 'contact'){
        String contactQuery = 'SELECT Id,Name,Email FROM Contact WHERE Id NOT IN :filteredRecordIds AND '+fieldToFilter+' LIKE \'%'+string.escapeSingleQuotes(searchString)+'%\' AND Email != NULL WITH SECURITY_ENFORCED';
        List<Sobject> contacts = Database.query(contactQuery.escapeHtml4());
        for(Integer count=0;count<contacts.size();count++){
          resultWrappers.add(new ResultWrapper(contacts[count],false));
        }
      }
    }
    catch(Exception e){
      System.debug(e.getMessage()+ ' - line no: '+e.getLineNumber());
    }
    
    return resultWrappers;
  }
public without sharing class EmailQueueTriggerHelper extends GNT.TriggerHelper{
    public static boolean skipAll = false;
    public override void processAfterUpdate() {
        if (skipAll == false) {
            systemEmailHelper();
        }
    }
    public static void systemEmailHelper(){
        //as we have written this code in after update we need to 1st get those records from by SQOL and then only we can do DML operation on those records.
        //For the same writen dynamic query as we need to clone new values, so to avoid adding all flieds every time used dynamic query
        sObjectType objType = Schema.getGlobalDescribe().get('GNT__EmailQueue__c');
        Map<String,Schema.SObjectField> mfields = objType.getDescribe().fields.getMap();
        String fields = '';
        for (SObjectField field : mfields.values()) {
          fields += field + ',';
        }
        fields = fields.removeEnd(',');
        Set<Id> setEmailId = new Set<Id>();
        for(GNT__EmailQueue__c obj : (List<GNT__EmailQueue__c>)Trigger.new){
            setEmailId.add(obj.id);
        }
        String query4Queue = 'SELECT '+fields+' FROM GNT__EmailQueue__c where Id IN :setEmailId';
        List<GNT__EmailQueue__c> lstEmailQueues = Database.query(query4Queue);
    
        List<GNT__EmailQueue__c> lstEmailsToSplit = new List<GNT__EmailQueue__c>(); //1st we will select records which we need to split email ids
        List<GNT__EmailQueue__c> lstEmailsToUpdatewithClone = new List<GNT__EmailQueue__c>();
        Map<Id,GNT__EmailQueue__c> mapEmails = new map<Id,GNT__EmailQueue__c>();
        for(GNT__EmailQueue__c obj : lstEmailQueues){
            GNT__EmailQueue__c oldRec = (GNT__EmailQueue__c)trigger.oldMap.get(obj.Id);
            if(obj.GNT__ToEmails__c.contains(',') && obj.GNT__Status__c =='Processed' && oldRec.GNT__Status__c=='Queued' && obj.IsClone__c == false){
                
                obj.isClone__c= true;
                lstEmailsToSplit.add(obj);
                mapEmails.put(obj.Id,obj);
            }else{
                obj.ToAddress__c = obj.GNT__ToEmails__c;
                obj.isClone__c= true;
                lstEmailsToUpdatewithClone.add(obj);
            }
        }
        List<GNT__EmailQueue__c> lstEmailsToInsert = new List<GNT__EmailQueue__c>();
        if(lstEmailsToSplit.size()>0){
            map<Id,List<String>> mapEmailRecordsWthMultiEmails = new map<Id,List<String>>();
            for(GNT__EmailQueue__c obj : lstEmailsToSplit){
                mapEmailRecordsWthMultiEmails.put(obj.id,obj.GNT__ToEmails__c.split(','));
            }
            
            for(Id obj : mapEmailRecordsWthMultiEmails.keySet()){ 
                List<String> lstEmails = mapEmailRecordsWthMultiEmails.get(obj);
                if(lstEmails.size()>0){
                    for(String str : lstEmails){
                        GNT__EmailQueue__c newRec1 = mapEmails.get(obj);
                        GNT__EmailQueue__c newRec = newRec1.clone(false, false, false, false);
                        newRec.id = null;
                        newRec.ToAddress__c = str;
                        newRec.isClone__c= true;
                        lstEmailsToInsert.add(newRec);
                    }
                }
            }
        }
        List<GNT__EmailQueue__c> lstToUpsrtEmails = new List<GNT__EmailQueue__c>();
        if(lstEmailsToInsert.size()>0){
            lstToUpsrtEmails.addAll(lstEmailsToInsert);
        }
        if(lstEmailsToUpdatewithClone.size()>0){
            lstToUpsrtEmails.addAll(lstEmailsToUpdatewithClone);
        }
        if(lstToUpsrtEmails.size()>0){
            lstToUpsrtEmails.addAll(lstEmailsToSplit);
        }
        if(lstToUpsrtEmails.size()>0){
            skipAll = true;
            upsert lstToUpsrtEmails;
            skipAll = false;
        }
    }
}