function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Thiago Barbosa 1Thiago Barbosa 1 

How to coverage this methods in class?(bold)

public with sharing class MassReassignOpportunitiesController {
    public ApexPages.StandardSetController optySetController;
    public String filterId {get;set;}
    public String ErrorMsg {get;set;}
    public String optyQueryString;
    public List<cOpty> optyList {get;set;}
    public list<Opportunity> optyToUpdateList {get;set;}
    public Opportunity searchRecord {get;set;}
    public Reassign_Helper__c helperRecord{get;set;}
    public boolean isSuccess{get;set;}
    public boolean searchPerformed{get;set;}
    public boolean tooManyResults{get;set;}
    public boolean isLightning {get;set;}
    public Map<String, String> mapErros {get; set;}
    public Integer optyListSize {get{return optylist.size();}}
    public list<SelectOption> listviewoptions {
        get{
            List<SelectOption> tempList = new List<SelectOption>();
            tempList.add(new selectOption('None',System.Label.NoViewSelection));
            if (optySetController<>null)tempList.addAll(optySetController.getListViewOptions());
            return tempList;
        }
    }
    
    
    @AuraEnabled
	public static List<ListView> getListViews() {
    	List<ListView> listviews = [SELECT Id, Name FROM ListView WHERE SobjectType = 'Opportunity'];
    	return listviews;
}
    
    
    
    
    
 @AuraEnabled 
 public static List<account> getAccount(String searchKeyWord) {
  String searchKey = searchKeyWord + '%';
  List < Account > returnList = new List < Account > ();
  List < Account > lstOfAccount = [select id, Name from account where Name LIKE: searchKey];
 
  for (Account acc: lstOfAccount) {
     returnList.add(acc);
     }
  return returnList;
 }
    
 
    
 
    
    @AuraEnabled
    public static List <User> getUsersName(String searchKeyWord) { 
        String searchKey = searchKeyWord + '%';
        List <User> returnList = new List <User> ();
        List <User> lstOfUser = [select id, Name from User where Name LIKE: searchKey];
        
        for (User usr: lstOfUser) {
            returnList.add(usr);
        }
        return returnList;
    }
    
    
   
    
    @AuraEnabled
    public static Map<string, object> newrefreshOptyListBySearch(String jsonOpp, String accountId, String userId){
        MassReassignOpportunitiesController controller = new MassReassignOpportunitiesController();
        Map<string, object> objReturn = new Map<string, object>();
        
        try{
            controller.searchRecord =  new Opportunity();
            controller.helperRecord = new Reassign_Helper__c();
            controller.mapErros = new Map<String, String>();
            Map<String, object> mapaSearch = (Map<String, object>)JSON.deserializeUntyped(jsonOpp);
            controller.searchRecord.Name = !String.isEmpty((String)mapaSearch.get('Name'))?(String)mapaSearch.get('Name'): null;
            controller.searchRecord.StageName = !String.isEmpty((String)mapaSearch.get('StageName'))?(String)mapaSearch.get('StageName'): null;
            controller.searchRecord.AccountId = !String.isEmpty((String)accountId) ? accountId : null;
            controller.searchRecord.OwnerId = !String.isEmpty((String)userId) ? userId : null;
            controller.helperRecord.BI_BR_CNPJ_CPF__c = !String.isEmpty((String)mapaSearch.get('BI_BR_CNPJ_CPF__c'))?(String)mapaSearch.get('BI_BR_CNPJ_CPF__c'): null;
            controller.helperRecord.BI_BR_Identificador__c = !String.isEmpty((String)mapaSearch.get('BI_BR_Numero_da_oportunidade__c'))?(String)mapaSearch.get('BI_BR_Numero_da_oportunidade__c'): null;
            controller.helperRecord.From__c = mapaSearch.get('From__c') != '' ? Date.valueOf((String)mapaSearch.get('From__c')): null;
            controller.helperRecord.To__c = mapaSearch.get('To__c') !='' ? Date.valueOf((String)mapaSearch.get('To__c')):null;        
            controller.helperRecord.closedDate_From__c = mapaSearch.get('ClosedDate_From__c') != '' ?Date.valueOf((String)mapaSearch.get('ClosedDate_From__c')):null;
            controller.helperRecord.closedDate_To__c = mapaSearch.get('ClosedDate_To__c') != '' ?Date.valueOf((String)mapaSearch.get('ClosedDate_To__c')):null;
            
            controller.refreshOptyListBySearch();
            List<Opportunity> lstOpp = new List<Opportunity>();
            for(cOpty Acc : controller.optyList){
                lstOpp.add(acc.oOpty);
            }
            if(lstOpp.size() == 0){
               controller.mapErros.put('Não existem Dados para serem exibidos', 'info'); 
            }
            objReturn.put('table', lstOpp);
        }catch(Exception e){
            controller.mapErros.put(e.getMessage(), 'error');
        }
        objReturn.put('mensagem' , controller.mapErros);
        
        return objReturn;
    }
     
    @AuraEnabled
    public static Map<String, object> newAssign(String userId, List<Opportunity> lstOpport){
        MassReassignOpportunitiesController controller = new MassReassignOpportunitiesController();
        Map<String, object> objReturnAssign = new Map<String, object>();
        try{
        controller.searchRecord = new Opportunity();
        controller.helperRecord = new Reassign_Helper__c();
        
        Map<String, object> mapaAssign = new Map<String, object>();
        controller.helperRecord.Assign_to__c = !String.isEmpty((String)userId) ? userId : null;
        
            for(Opportunity opp : lstOpport){
                opp.OwnerId = userId;
                cOpty pt = new cOpty(opp);
                pt.selected = true;            
                controller.optyList.add(pt);
            } 
                
       
        
        controller.Assign();            
        }catch(exception e){
            controller.mapErros.put(e.getMessage(), 'error');
        } 
        
        objReturnAssign.put('mensagemErro', controller.mapErros);

        return objReturnAssign;
    }






public MassReassignOpportunitiesController(){
    //Variable Init
    optyQueryString = 'SELECT name,StageName,Ownerid, Owner.Name, CloseDate from Opportunity where isDeleted=false';
    optyList = new List<cOpty>();
    optySetController = new ApexPages.Standardsetcontroller(Database.getQueryLocator(optyQueryString+' limit 1000'));
    filterId = listviewoptions[0].getValue();
    searchRecord = new Opportunity();
    helperRecord = new Reassign_Helper__c();
    isSuccess = true;
    searchPerformed = false;
    tooManyResults = false;
	isLightning = false;
    mapErros = new Map<String, String>();
    //Apply the default filter
    //refreshOptyList();
}

/*========================================
Applies the View filter to the Opty List
==========================================*/ 
public void refreshOptyList(){
    list<Opportunity> testList = new list<Opportunity>();
    
    optyList.clear();
    tooManyResults = false;
    if (filterId <> null && filterId<> 'None'){
        optySetController.setFilterId(filterId);
        testList = (list<Opportunity>)optySetController.getRecords();
        searchPerformed = true;
    }else searchPerformed = false;
    

    
    Integer counter = 0;
    
    for (Opportunity opty:testList){
        optyList.add(new cOpty(Opty));
        counter++;
        if (counter == 999){
            tooManyResults = true;
            break;
        }
        
    }
    
}
    
   
    
    
    @AuraEnabled
    public static Map<String, object> newrefreshOptyList(String filterId){
      MassReassignOpportunitiesController controller = new MassReassignOpportunitiesController();
      controller.filterId = filterId;
      controller.refreshOptyList();
      
      
      Map<string, object> objReturn = new Map<String, object>();
      
       
        
     List<Opportunity> lstOpp = new List<Opportunity>();
            for(cOpty Acc : controller.optyList){
                lstOpp.add(acc.oOpty);
            }   
        	objReturn.put('lSelectTable', lstOpp);
        
        return objReturn;
    }

public void refreshOptyListBySearch(){
    optyList.clear();
    
    //resultList = new List<cResult>();
    //Systemdebug
    String userFilterQuery = '';
    if (searchRecord.Name<>null)    userFilterQuery = ' and Name like \'%'+searchRecord.Name+'%\'';
    if (searchRecord.Type<>null)    userFilterQuery += ' and Type = \''+searchRecord.type+'\'';
    
    if (searchRecord.StageName<>null)   userFilterQuery += ' and StageName = \''+searchRecord.StageName+'\'';
    if (searchRecord.AccountId<>null)   userFilterQuery += ' and AccountId = \''+searchRecord.AccountId+'\'';
    if (searchRecord.OwnerId<>null)   userFilterQuery += ' and OwnerId = \''+searchRecord.OwnerId+'\'';
    if (helperRecord.BI_BR_CNPJ_CPF__c<>null)   userFilterQuery += ' and BI_BR_CNPJ_CPF__c = \''+helperRecord.BI_BR_CNPJ_CPF__c+'\'';
    if (helperRecord.BI_BR_Identificador__c<>null)   userFilterQuery += ' and BI_BR_Numero_da_oportunidade__c = \''+helperRecord.BI_BR_Identificador__c+'\'';
    if (helperRecord.From__c<>null){
        DateTime startDate = DateTime.newInstance(helperRecord.From__c, Time.newInstance(0, 0, 0, 0));
        userFilterQuery += ' and CreatedDate >= '+startDate.format('yyyy-MM-dd')+'T00:00:00Z';
        
    }
    if (helperRecord.To__c<>null){
        DateTime endDate = DateTime.newInstance(helperRecord.to__c, Time.newInstance(0, 0, 0, 0));
        userFilterQuery += ' and CreatedDate <= '+endDate.format('yyyy-MM-dd')+'T00:00:00Z';
        
    }
    if (helperRecord.closedDate_From__c<>null){
        DateTime startDate = DateTime.newInstance(helperRecord.closedDate_From__c, Time.newInstance(0, 0, 0, 0));
        userFilterQuery += ' and CloseDate >= '+startDate.format('yyyy-MM-dd');
        
    }
    if (helperRecord.closedDate_To__c<>null){
        DateTime endDate = DateTime.newInstance(helperRecord.closedDate_to__c, Time.newInstance(0, 0, 0, 0));
        userFilterQuery += ' and CloseDate <= '+endDate.format('yyyy-MM-dd');
        
    }
    
    
    String optyQueryString = optyQueryString +  userFilterQuery ;
    optyQueryString += ' order by Name limit 1000';
    
    List<Sobject> sortedResults= new List<SObject>();
   
    try{
        sortedResults = Database.query(optyQueryString);
        searchPerformed = true;
    }catch (Exception e){
        if(!isLightning){
           mapErros.put(e.getMessage(), 'error');
        }else
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
    }
    
    
    for (SObject foundObject:sortedResults){
        Opportunity opty = (Opportunity)foundObject;
        optyList.add(new cOpty(opty)); 
    }
    
}

/*===============================================
Assign the selected opportunities to a new owner
=================================================*/
public void Assign(){     
    list<Opportunity> optyToUpdateList = new list<Opportunity>();
    list<Task> taskToUpdateList = new list<Task>();
    list<Event> eventToUpdateList = new List<Event>();
    isSuccess = true;
    for (cOpty opty:optyList){
        if (opty.selected && opty.oOpty.StageName != 'F1 - Ganha')
            if(opty.oOpty.CloseDate < Date.today()) 
            	if(!isLightning){
                    
                	mapErros.put('Os registros com data de fechamento estimado anterior a data atual não foram alterados.', 'warning');
                }else{
            		ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.warning, 'Os registros com data de fechamento estimado anterior a data atual não foram alterados.'));
                }
        else optyToUpdateList.add(new Opportunity(id=opty.oOpty.id, OwnerId=helperRecord.Assign_to__c));
        if (opty.selected && opty.oOpty.StageName == 'F1 - Ganha')
            if(!isLightning){
                mapErros.put('Os registros em fase F1 - Ganha não foram alterados.', 'warning');
            }else{
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.warning, 'Os registros em fase F1 - Ganha não foram alterados.'));
            }
            }
    
    //We also need to reassign the open activities to the new owner
    //To do so, we first loop on all the opportunities to retrieve their Open Activities
    //Then we loop through the Task or Events and reassign them
    for(Opportunity tempOpty:[select id,(select id,isTask from OpenActivities order by ActivityDate DESC, LastModifiedDate DESC limit 500) from Opportunity where id in :optyToUpdateList]){
        for (OpenActivity tempActivity:tempOpty.OpenActivities){
            if (tempActivity.IsTask) taskToUpdateList.add(new Task(id=tempActivity.id,ownerId=helperRecord.Assign_to__c));
            else EventToUpdateList.add(new Event(id=tempActivity.id,ownerId=helperRecord.Assign_to__c));
        }
    }
    
    if (optyToUpdateList.size()+taskToUpdateList.size()+eventToUpdateList.size()>=10000) {
        if(!isLightning){
		 mapErros.put(System.Label.TooManyRowsError,'error');
        }else{
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.TooManyRowsError));
        }
    }else{
        try
        {
            update optyToUpdateList;
        }catch (Exception e)
        {
            if(!isLightning){
                mapErros.put(e.getMessage(), 'error');
            }else{
            	ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
            	isSuccess = false;
            }
        }
        
        try
        {
            if (taskToUpdateList.size()>0) update taskToUpdateList;
            if (eventToUpdateList.size()>0) update eventToUpdateList;
        }catch (Exception e)
        {
            if(!isLightning){
                mapErros.put(e.getMessage(), 'error');
            }else{
            	ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
            	isSuccess = false;
            }
        }
        
        // Update the search results
        integer n=optyList.size();
        for (integer i=n-1;i>=0;i--){
            if (optyList[i].selected) optyList.remove(i);
        }
        
        //Display success menssage
        if(isSuccess)
            if(!isLightning){
            mapErros.put(System.Label.AssignSuccessSummary, 'success');
            }else{
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, System.Label.AssignSuccessSummary));
            }
            }
    
}

/*==================================================
Inner class helping identify selected opportunities
====================================================*/
public class cOpty{
    public Opportunity oOpty {get;set;}
    public Boolean selected {get;set;}
    
    public cOpty(Opportunity oOpty){
        this.oOpty = oOpty;
        selected = false;
    }
    
}

/*public static testmethod void testReassign(){
RecordType RecId = [SELECT Id FROM RecordType WHERE DeveloperName = 'BI_Clientes' and SobjectType = 'Account' LIMIT 1];

Account testAccount = new Account();
testAccount.Name = 'test';
testAccount.BI_Tipo_de_identificador_fiscal__c = 'CNPIJ';
testAccount.BI_No_Identificador_fiscal__c = '12345678';
testAccount.RecordTypeId = RecId.id;
insert testAccount;

BI_BR_Adabas__c Adabas = BI_DataLoad.getAdabas();
Adabas.BI_BR_ID_Externo__c = 'VALE0000';
insert Adabas;

BI_BR_Atendimento_Comercial_e_Carteira__c Scarteira = BI_DataLoad.getAtendimentoComercialECarteira(Adabas.Id, testAccount.Id);
insert Scarteira;

Opportunity testOpty = new Opportunity();
testOpty.StageName = 'Discover';
testOpty.CloseDate = System.today()+1;
testOpty.AccountId = testAccount.Id;
testOpty.Name = 'testOpty';
testOpty.Type = 'testType';
testOpty.BI_BR_Adabas__c = Adabas.ID;
testOpty.BI_BR_Duracao_do_contrato_em_meses__c = '18';
insert testOpty;

MassReassignOpportunitiesController controller = new MassReassignOpportunitiesController();
controller.refreshOptyList();
controller.filterId = controller.listviewoptions[1].getValue();
controller.refreshOptyList();
controller.searchRecord.stageName = 'Discover';
controller.helperRecord.ClosedDate_From__c = System.today();
controller.helperRecord.ClosedDate_To__c = System.today()+2;
controller.helperRecord.From__c = System.today();
controller.helperRecord.To__c = System.today()+1;
controller.searchRecord.Type = 'testType';
controller.refreshOptyListBySearch();

System.assert(controller.optyList.size()>0);

controller.optyList[0].selected = true;
controller.helperRecord.Assign_to__c = UserInfo.getUserId();
controller.Assign();
}*/

}