• Mayank.ms
  • NEWBIE
  • 165 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 26
    Questions
  • 80
    Replies

I need to get Opportunity Owner name In the  opp trigger. Can anyone help on this ?

here is my trigger code :

 

trigger PortalCallout on Opportunity (after insert,after update) {

    if(Trigger.IsInsert){
       for (Opportunity o : Trigger.new) {
           // make the asynchronous web service callout
           HttpResponse r= new Httpresponse();
           SendDataToPortal s = new SendDataToPortal();
           if(o.Subscriber_ID__c!=null && o.Client_ID__c!=null ){
               r = s.sendNotification(o.Subscriber_ID__c, o.Id, o.AccountId,o.Client_ID__c,'','','','','','','',o.Name,'','','','insert');
           } 
           //system.debug('r');
      }
    }
    if(Trigger.IsUpdate){
       for (Opportunity o : Trigger.new) {
                    // make the asynchronous web service callout
        HttpResponse r= new Httpresponse();
        SendDataToPortal s = new SendDataToPortal();
        String cdate = NULL;
        String isOppNameUpdated = 'false';
        String isCancelFldUpdated = 'false';
        String isOtherFldUpdated = 'false';
        //system.debug('r');
    
        /******************************** REPLACE SALESFORCE ADMIN UserID ON PRODUCTION ***********************************/
           if(userinfo.getUserId()!='005160000064dkRAAQ' &&  o.Subscriber_ID__c!=null && Trigger.OldMap.get(o.Id).Name!= o.Name){
               
               isOppNameUpdated = 'true';
           }
           
           if(userinfo.getUserId()!='005160000064dkRAAQ' &&  o.Subscriber_ID__c!=null && (Trigger.OldMap.get(o.Id).Cancellation_Reason__c!= o.Cancellation_Reason__c || Trigger.OldMap.get(o.Id).Cancellation_Date__c!=o.Cancellation_Date__c || Trigger.OldMap.get(o.Id).Cancellation_Feedback__c!=o.Cancellation_Feedback__c)){
               
               isCancelFldUpdated = 'true';
               cdate = string.valueof(o.Cancellation_Date__c);
           }
    
           if(userinfo.getUserId()!='005160000064dkRAAQ' && o.Subscriber_ID__c!=null && (Trigger.OldMap.get(o.Id).Accounting_Platform__c!= o.Accounting_Platform__c || Trigger.OldMap.get(o.Id).Order_Volume__c!= o.Order_Volume__c || Trigger.OldMap.get(o.Id).promo_code__c!= o.promo_code__c)) {
               isOtherFldUpdated='true';
               
           }
           if(isOppNameUpdated=='true' || isCancelFldUpdated=='true' || isOtherFldUpdated=='true'){
               r = s.sendNotification(o.Subscriber_ID__c, o.Id, o.AccountId,o.Client_ID__c, o.Cancellation_Reason__c,o.Order_Volume__c,o.Accounting_Platform__c,cdate,o.promo_code__c,o.Cancellation_Feedback__c,o.Susbcription_Status__c,o.Name,isOppNameUpdated,isCancelFldUpdated,isOtherFldUpdated,'update'); 
           }
    
        system.debug('r');
    
    }
  }

}

I have implemnted a trigger on custom object which hold the opportunity Id and Opportunity Name. I need to access  a custom field from oportunity object for which I used a SOQL query but not able to get coverage for that . so need help on this .

My Apex  Trigger :

trigger SendImplementaionStageOnPortal on Implementation__c (after update) { // TEST CLASS TestSendImplementationStageOnPortal
    if(Trigger.IsUpdate){
         for (Implementation__c imp : Trigger.new) {
                // make the asynchronous web service callout
                HttpResponse r= new Httpresponse();
                 SendDataToPortal s = new SendDataToPortal();
                 String ImpStage = NULL;

             /******************************** REPLACE SALESFORCE ADMIN UserID ON PRODUCTION ***********************************/
               
             if(imp.Opportunity_ID__c!=null && Trigger.OldMap.get(imp.Id).Stage__c!= imp.Stage__c && imp.Stage__c=='Complete'){
                   
                 //Query Opportunity
                List<Opportunity>lstOppts = [select Subscriber_id__c From Opportunity WHERE  Id=:imp.Opportunity_ID__c limit 1];
                if(lstOppts.size()>0){
                
                        System.debug('Subscriber_id__c-MY: '+ lstOppts[0].Subscriber_id__c);
                      // List<Account>lstAccounts = [select id,Name,(select id,FirstName,LastName FROM Contacts ) From Account WHERE Id =:lstOppts[0].id];
               
                 
                 ImpStage = string.valueof(imp.Stage__c);
                  //r = s.sendImplementaionData(lstOppts[0].Subscriber_id__c,imp.Stage__c); 
                   r = s.sendImplementaionData(lstOppts[0].Subscriber_id__c,'complete'); 
             }
             
               
            }
    }
}
}

 

My Apex Test Class :

@isTest
public class TestSendImplementationStageOnPortal {
    static testMethod void sendImplementaionDataTest() {  
        
        Account a = new Account(Name = 'SDToPortalImpTest',Type = 'Customer',TypeCustomerDate__c=Date.today());
        insert a;
        Contact newContact = new Contact(Lastname='testLastName', AccountId = a.Id ,Email='mayanks+test@webgility.com',phone ='56465464' , LeadSource='Inbound', Lead_Source_Detail__c = 'Website');
        insert newContact;
           String opportunityName = 'SDToPortalImpTest';
       
        Opportunity o1 = new Opportunity(AccountId=a.Id, name='OPP test1',Type ='New Business',Susbcription_Status__c = 'Active', Subscriber_ID__c =3651,Client_ID__c=1258, StageName='Closed Won',CloseDate = Date.today() );
        insert o1;
        OpportunityContactRole ocr1 = new OpportunityContactRole(OpportunityId = o1.Id, ContactId = newContact.Id, Role='Decision Maker',Isprimary=true );
        insert ocr1;
      
    
         Implementation__c imp = new Implementation__c(name='IMP test1',Opportunity_Name__c=o1.Id,Stage__c='New');
         insert imp;
          
        List<Opportunity> myList = new List<Opportunity>(); // Define a new list
          Opportunity opp = new Opportunity(Subscriber_id__c=3651,Id= imp.Opportunity_ID__c);
          myList.add(opp);
        
       //List<Opportunity>lstOppts = [select Subscriber_id__c From Opportunity WHERE  Id='0061F00000AOBTkQAP'];
       

        Test.StartTest(); 
        imp.Stage__c ='Complete';
        imp.Id='a1s1F0000017sCqQAI';
        imp.Opportunity_Name__c='0061F00000AOBTkQAP';
        update imp;
        
       List<Opportunity>lstOppts = [select Subscriber_id__c From Opportunity WHERE  Id=:imp.Opportunity_ID__c limit 1];
         System.assert(lstOppts != null);

         Test.StopTest();  
    }
}

Hello everyone,
I have created a trigger which will update Contact Object field(Most_recent_Opportunity_Stage__c) whenever opportunity status gets changed.
My trigger is working fine but associated Test class is not making 75% code coverage of Trigger. I am new to salesforce and not having much experince to build test class so please help me.

Here is my Trigger and associated test class :

Trigger :

trigger UpdateMostRecentOpportunityStageOfContact on Opportunity (after update) {
  Set<String> ContactIds = new Set<String>();
     Set<String> oppIds = new Set<String>();
     if(UpdateStageOnContactHandler.isFirstTime){
             UpdateStageOnContactHandler.isFirstTime=false;
    List<OpportunityContactRole> conList = new List<OpportunityContactRole>([select ContactId from OpportunityContactRole where IsPrimary = true and OpportunityId IN :Trigger.newMap.keySet() limit 1]);
     for(OpportunityContactRole c :conList)
       {
           ContactIds.add(c.ContactId);
       }    
    List<OpportunityContactRole> oppList =  new List<OpportunityContactRole>([select ContactId,opportunityId,CreatedDate from OpportunityContactRole where IsPrimary = true and ContactId =: ContactIds order by CreatedDate desc  limit 1]);
    for(OpportunityContactRole cr :oppList)
       {
           oppIds.add(cr.opportunityId);
       } 
    if(!oppIds.isEmpty()){
    Opportunity op = [select StageName from opportunity where Id =:oppIds limit 1]; 
    List<Contact> contactToUpdate = new List<Contact>();
    for(Opportunity opp : trigger.new){
           for(OpportunityContactRole c :oppList){ 
                if(opp.AccountId != null){
                 contactToUpdate.add(new Contact(Id = c.ContactId, Most_recent_Opportunity_Stage__c=op.StageName)); 
               }
           }    
       }
       if (contactToUpdate != null && !contactToUpdate.isEmpty())
        {
            Update contactToUpdate;
        } 
     }
   }      
 }


TEST Class :

@isTest
public class TestUpdateMostRecentopportunityStage {
   static testMethod void TestUpdateStageOnContactTest()
    {   
        Account a = new Account(Name = 'TestUpdateStageOnContactTest');
        a.Type = 'Prospect';
        insert a;

        Contact newContact1 = new Contact(Lastname='TestUpdateStageOnContactTest1', AccountId = a.Id ,Email='mayanks+test1@webgility.com' );
        insert newContact1;
        
        Contact newContact2 = new Contact(Lastname='TestUpdateStageOnContactTest2', AccountId = a.Id ,Email='mayanks+test2@webgility.com' );
        insert newContact2;
    
      
        Opportunity o1 = new Opportunity(AccountId=a.Id, name='OPP test1', StageName='Demo', CloseDate = Date.today() );
       insert o1;
        OpportunityContactRole ocr1 = new OpportunityContactRole(OpportunityId = o1.Id, ContactId = newContact1.Id, Role='Decision Maker',Isprimary=true );
        insert ocr1;
        
          Opportunity o2 = new Opportunity(AccountId=a.Id, name='OPP test2', StageName='Open', CloseDate = Date.today() );
       insert o2;
        OpportunityContactRole ocr2 = new OpportunityContactRole(OpportunityId = o2.Id, ContactId = newContact2.Id, Role='Decision Maker',Isprimary=true );
        insert ocr2;
        
          Test.StartTest();
        o1.stageName='Demo';
        update o1;
        newContact1.Most_recent_Opportunity_Stage__c='Demo';
        update newContact1;
        
         o2.stageName='Open';
        update o2;
        newContact2.Most_recent_Opportunity_Stage__c='Open';
        update newContact2;
        
        Test.StopTest();
         
      }   
}


Thanks,
Mayank

Hi, 
I have created a batch apex in which we creating a Case based on certain criteria. But I am getting the issue LIMIT_USAGE_FOR_NS and not execute my queries. So cany please help on it. How to execute each query. I am trying this on my sandbox

Batch apex class

global class CSMCaseCreation implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
       
        String query = 'select Id, AccountId, CloseDate, Last_Login_Date__c , Name,Susbcription_Status__c from opportunity where StageName = \'Closed Won\' and Susbcription_Status__c in (\'Active\',\'Expired\') and days_After_Closed_Date__c =30 and (Orders_Last_30d__c <10 OR Last_Login_Date__c < LAST_N_DAYS:10 OR Product_Stage__c < 11)'; 
            return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope)
    { 	List<Case> lstCasetoInsert = new List<Case>();
        LIST<Case> caseListToUpdate = new List<Case>();
        Set<Case> caseSet = new Set<Case>();
        List<Opportunity> lstOpp = new List<Opportunity>();
     
        for(Opportunity o :scope){
               	Case caseObj =CreateCase('Open SAVE TEAM case','RISK: Unhealthy - 30 days', o.Id, o.AccountId);
              	lstCasetoInsert.add(caseObj);
        }
     
       List<Opportunity> opp2 = new List<Opportunity>();
  		opp2= [select Id, AccountId, Storefront_Marketplace__c,CloseDate, Last_Login_Date__c , Name,Susbcription_Status__c from opportunity where StageName = 'Closed Won' and Susbcription_Status__c in ('Active','Expired') and days_After_Closed_Date__c =15 and Storefront_Marketplace__c='' and Product_Stage__c < 11 ];
            for(Opportunity o2 : opp2)
            {  
               	Case caseObj =CreateCase('Open CHURN RISK case','RISK - QB Not Connected', o2.Id, o2.AccountId);
              	lstCasetoInsert.add(caseObj);
            }
     
       List<Opportunity> opp3 = new List<Opportunity>();
  		opp3= [select Id, AccountId, CloseDate, Susbcription_Status__c from opportunity where Open_Ticket__c=true or Last_30_days_Ticket__c=true or Open_Ticket_More_than_1_day__c =true or Open_Ticket_2__c=true ];
     	system.debug('Ahmed1');
            for(Opportunity o3 : opp3)
            {  
               	Case caseObj =CreateCase('Open CHURN RISK case','RISK: Support Tickets', o3.Id, o3.AccountId);
              	lstCasetoInsert.add(caseObj);
             }
       List<Opportunity> opp4 = new List<Opportunity>();
  		opp4= [select Id,AccountId, CloseDate, Susbcription_Status__c from opportunity where StageName = 'Closed Won' and Susbcription_Status__c in ('Active','Expired') and ((Orders_Last_30d__c < 10) OR (QB_Last_30d__c !=0 and QB_Last_30d__c <= 10)) limit 10 ];
            for(Opportunity o4 : opp4)
            { 
               	Case caseObj =CreateCase('Open CHURN RISK case','RISK - No Orders Posted', o4.Id, o4.AccountId);
              	lstCasetoInsert.add(caseObj);
              
            }
       List<Opportunity> opp5 = new List<Opportunity>();
  		opp5= [select Id, AccountId, CloseDate, Susbcription_Status__c from opportunity where StageName = 'Closed Won' and Susbcription_Status__c in ('Active','Expired') and QB_Last_30d__c =0 limit 5 ];
            for(Opportunity o5 : opp5)
            {  
               	Case caseObj =CreateCase('Open SAVE TEAM case','RISK - No Orders Posted', o5.Id, o5.AccountId);
              	lstCasetoInsert.add(caseObj);
            }
 		List<Opportunity> opp6 = new List<Opportunity>();
  		opp6= [select Id, AccountId, CloseDate, Susbcription_Status__c from opportunity where StageName = 'Closed Won' and Susbcription_Status__c in ('Active','Expired') and days_After_Closed_Date__c = 30 and (Onboarding_Session_1_Complete__c =true OR Onboarding_Session_2_Complete__c=true) and Orders_Last_30d__c = 0 and QB_Last_30d__c =0 ];
            for(Opportunity o6 : opp6)
            {  
               	Case caseObj =CreateCase('Open CS Case','RISK: No Usage', o6.Id, o6.AccountId);
              	lstCasetoInsert.add(caseObj);
           }
		List<Opportunity> opp7 = new List<Opportunity>();     
		opp7= [select Id, AccountId, CloseDate, Last_Login_Date__c , Name,Susbcription_Status__c from opportunity where StageName = 'Closed Won' and Susbcription_Status__c in ('Active','Expired') and  days_After_Closed_Date__c =45 and (Orders_Last_30d__c <10 OR Last_Login_Date__c < LAST_N_DAYS:10 OR Product_Stage__c < 11) ];
            for(Opportunity o7 : opp7)
            {  
               	Case caseObj =CreateCase('Open SAVE TEAM case','SAVE TEAM', o7.Id, o7.AccountId);
              	lstCasetoInsert.add(caseObj);
            }
     	List<Opportunity> opp8 = new List<Opportunity>();
  		opp8= [select Id, AccountId, CloseDate, Susbcription_Status__c from opportunity where StageName = 'Closed Won' and Susbcription_Status__c in ('Active','Expired') and days_After_Closed_Date__c = 15 and Onboarding_Session_1_Complete__c =true and Onboarding_Session_2_Complete__c=true and QB_Last_30d__c =0 ];
            for(Opportunity o8 : opp8)
            {  
               	Case caseObj =CreateCase('Open CHURN RISK case','RISK - No Orders Posted', o8.Id, o8.AccountId);
              	lstCasetoInsert.add(caseObj);
            }
     	List<Opportunity> opp9 = new List<Opportunity>();
  		opp9= [select Id,Onboarding_Session_1_Complete__c , AccountId,days_After_Closed_Date__c , CloseDate, Susbcription_Status__c from opportunity where StageName = 'Closed Won' and Susbcription_Status__c in ('Active','Expired') and days_After_Closed_Date__c = 15 and (Onboarding_Session_1_Complete__c =true OR Onboarding_Session_2_Complete__c=true) and (Orders_Last_30d__c <10 OR Last_Login_Date__c < LAST_N_DAYS:10 OR Product_Stage__c < 11) ];
            for(Opportunity o9 : opp9)
            {  
               	Case caseObj =CreateCase('Open CS Case','RISK: Unhealthy - 15 days', o9.Id, o9.AccountId);
              	lstCasetoInsert.add(caseObj);
            }
     	
     List<Opportunity> opp10 = new List<Opportunity>();   
     	opp10= [select Id,Onboarding_Session_1_Complete__c , AccountId,days_After_Closed_Date__c , CloseDate, Susbcription_Status__c from opportunity where StageName = 'Closed Won' and Susbcription_Status__c in ('Active','Expired') and Onboarding_Session_1_Complete__c =true and (Storefront_Marketplace__c ='' OR Product_Stage__c < 11) ];
            for(Opportunity o10 : opp10)
            {  
               	Case caseObj =CreateCase('Open Onboarding Risk Case','RISK: Store / QB Not Connected', o10.Id, o10.AccountId);
              	lstCasetoInsert.add(caseObj);
            }
        try {
            	   if(!lstCasetoInsert.IsEmpty()){
            			 caseSet.addAll(lstCasetoInsert);
						caseListToUpdate.addAll(caseSet);
            			system.debug('Kamran3');
       		 			insert caseListToUpdate;
                       	
                   }      
    		} catch (system.dmlexception e) {
        		System.debug('Case not inserted: ' + e);
    		}
    
        
    }
    
    global Case CreateCase(String subject, String Casetype, Id oppId,Id accId){
    Case caseObj = new Case(
    Opportunity__c = oppId,
    AccountId = accId,
    Status = 'New',
    Type = Casetype,
    Subject = subject    
    );
    return caseObj;     
}
    
    
    global void finish(Database.BatchableContext BC)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 
        mail.setToAddresses(new String[] {'ahmeds@example.com'});
        mail.setReplyTo('ahmeds@examle.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Case Created Completed');
        mail.setPlainTextBody('CSM case Batch Process has Completed');
 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}
schedulable apex
 
Id batchJobId = Database.executeBatch(new CSMCaseCreation(), 1);
System.schedule('Scheduled Job 1', '0 0 * * * ?', new ScheduleCSMCaseCreation());
Execution Log
User-added image

Can you guys please help me as soon as possible.

Thanks in advance.

 

Hi All,

I need a Batchable class that will update the lead Status as 'Open' when no actvities logged under Lead Object

Step1: We have 2 lead status 'Contacted Attempt Made' and 'Discovery'. When these status set, I update the stage date (Custom field Stage_date__c). 
Step2: If stage date is more than 30 days and no actvity logged under lead object from stage date then we need to update the Lead status as 'Open'

Can you please provide the class to update the stage 

Thanks in advanced
 

.

 

 

Hello Guys,

I have created a trigger on contact that insert a new opportunity. It is working properly but when we perform bulk operation then it's giving the error CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: OpportunityCreatorOnContact: System.LimitException: Too many SOQL queries: 101 

See the trigger below and please provide me the solution for it

trigger OpportunityCreatorOnContact on Contact (before update) {
   
    if(OpportunityCreatorOnContactHandler.isFirstTime){
        OpportunityCreatorOnContactHandler.isFirstTime=false;
  
       List<Contact> ContList = new List<Contact>([SELECT Name,Contact.Account.Id,Contact.Account.Name, Most_recent_Opportunity_Stage__c, Contact.Account.OwnerId,Quarantine__c,mkto71_Lead_Score__c from Contact where id IN :Trigger.newMap.keySet()]); 
                for(Contact c : trigger.new)
                {   
                    for(Contact c1: ContList){  

                      if(c.Most_recent_Opportunity_Stage__c=='Closed Lost' && trigger.oldMap.get(c.Id).Create_New_Opp__c==false && c.Create_New_Opp__c==true  && c.mkto71_Lead_Score__c>=100 ) {   
                        
			Opportunity opp = new Opportunity(Name=c1.Account.Name, AccountID=c.AccountId, StageName='Open', CloseDate=Date.Today().addDays(+30),ownerID = c1.Account.OwnerId);
                        insert opp;
                      	
			opportunityCOntactRole oppCOn = new opportunityCOntactRole(OpportunityId=opp.id, contactId= c.Id, isPrimary=true);
                      	insert oppCon;

                      }    
                  }    
                }     

                        
          }    
}
Thanks

 

 

 

 

Hi Guys,

I want to display only those contacts that are related to the selected account. I have 2 custome lookup field on opportunity object, one is the referrer account and another one is referrer contact. When we select the lookup account and save it then need to display only related contacts. I have created a lookup filter but its not display contacts by default when click on the contact lookup, see the lookup filter as below

 

 

 

 

 

User-added image

Please help on it

Thanks


 

I want to display external website on one of the salefoce object detail page via visual force page. But iframe is not working after release 15, so how can use it. Pleae let me know
I have created a batch class that fetch records from opportunity objects and based on it creating a task. It is executing successfully but task not creating. It is working for few records but not woking for more records. 
I have getting th​e task id in the debug mode but when we are put these task id in the URL, its showing as deteted. 

Class:
global class CSportfoliosTask implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        datetime next30days = date.today().addDays(30);
        string next30daysformat = next30days.format('yyyy-MM-dd');
        String query = 'SELECT Id, Credit_Card_Expiration__c, Next_Billed_Date__c,Opportunity.Account.OwnerId  FROM opportunity WHERE  StageName = \'Closed Won\' and Susbcription_Status__c =\'Active\' and Next_Billed_Date__c='+next30daysformat;
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope)
    {
            for(Opportunity o : scope)
            {
                if(o.Credit_Card_Expiration__c!=NULL){
                    String ccs = o.Credit_Card_Expiration__c;
                    String[] ccsplitted = ccs.split('-'); 
                    String ccmonth =  ccsplitted[0];
                    String ccyear =  ccsplitted[1];
                    String nexts = string.valueOfGmt(o.Next_Billed_Date__c);
                    String[] nextSplitted = nexts.split('-');
                    String nextYear = nextSplitted[0];
                    String nextMonth = nextSplitted[1];
                    if(ccyear<=nextYear){
                        if(Integer.ValueOf(ccmonth)<=Integer.ValueOf(nextMonth)){
                             CreaeTask('Alert - Subscription payment at risk - Expired Card on '+o.Credit_Card_Expiration__c, o.Id , o.Account.OwnerId);
                        }
                    }
                }   
            }
            
        List<Opportunity> opp2 = new List<Opportunity>();
        datetime next30days = date.today().addDays(30);
        string next30daysformat = next30days.format('MM/dd/YYYY');
        date next30daysdate = date.parse(next30daysformat);
        
        opp2= [SELECT Id, Next_Billed_Date__c, Opportunity.Account.OwnerId FROM opportunity WHERE  StageName = 'Closed Won' and Susbcription_Status__c ='Active' and Next_Billed_Date__c=:next30daysdate];
            for(Opportunity o2 : opp2)
            {  
               CreaeTask('Alert - Secure Subscription Renewal on '+o2.Next_Billed_Date__c, o2.Id, o2.Account.OwnerId);
            }
    }
    
    global void CreaeTask(String Subject,String Id, String OwnerId){
        Task t = new Task();
        t.Subject = Subject;
        t.Type = 'Outbound Call';
        t.Status = 'Open';
        t.Priority = 'Normal';
        t.ActivityDate= date.today();
        t.WhatId =Id;
        t.OwnerId = OwnerId;
        insert t;     
       } 
    
    global void finish(Database.BatchableContext BC)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 
        mail.setToAddresses(new String[] {'ahmeds@example.com'});
        mail.setReplyTo('ahmeds@example.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Early Warning System for CS portfolios create task Completed');
        mail.setPlainTextBody('Early Warning System for CS portfolios create task Batch Process has Completed');
 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}
Scheduler Class
 
global class ScheduleCSportfoliosTask implements Schedulable
{
       global void execute(SchedulableContext sc) 
        {
        CSportfoliosTask d1 = new CSportfoliosTask();
        ID batchprocessid = Database.executeBatch(d1,200);           
        }
}
User-added image

I have aslo execute batch with 10 as well. i.e  ID batchprocessid = Database.executeBatch(d1,10); but its not the solution.

Also getting the too many sql query

User-added image

Can you guys please help me how to resolve this issue.

Thansk in advance. 
 
Can anybody let me know how to make 'Email Domain' checked by default?

User-added image

Thanks in advance
 
Hi All,

I want to update the few fields of converted leads. So can you guys please help me and let me know how can update it. 

Thanks in advance
I have an issue when converting a lead using API on sandbox. It gives a error INVALID_ACCESS_LEVEL. I am unabe to understand whats the issue. It was working fine from last 2 years but yesterday suddenly occured the error INVALID_ACCESS_LEVEL when converting the lead. I have already update the password and security tocken on sandbox.

I am using convertLead function to convert the lead.

Can anybody please help me on it.

Thanks in advance
I am unable to convert leads via API. Today, I have update the password. Its was working after update the password but suddently its not converting lead and giving the error 'INVALID_ACCESS_LEVEL' . This issue is occuring at my sandbox environment. Can anyone please help me whats the issue.

Thanks in advance 
Hello Guys,

When I validate the trigger with test class on LIVE, getting error for Too many SQL Quries 101. Can you please help me to update the trigger.

Trigger: UpdateContactOwnerForTrial that wants to validate on LIVE.
trigger UpdateContactOwnerForTrial on Opportunity (after insert, after Update) {
    
     List<Contact> conList = new List<Contact>([select Id,ownerId from Contact where Id In (select ContactId from OpportunityContactRole where OpportunityId IN :Trigger.newMap.keySet())]); 
  	 List<Contact> contactsToUpdate = new List<Contact>{};
    
    for(Opportunity opp : trigger.new)
    {   
          for(Contact c: conList){
              c.ownerId = opp.ownerId;
              contactsToUpdate.add(c);
        }    
    }
   update contactsToUpdate; 

}

Test class
@isTest
public class TestUpdateContactOwnerForTrial {
	static testMethod void TestUpdateContactOwnerForTrialTest()
	{    
		Account a = new Account(Name = 'TestUpdateContactOwnerForTrial');
		a.Type = 'Customer';
		insert a;

		Contact newContact = new Contact(Lastname='testLastName', AccountId = a.Id );
		insert newContact;
	
        String opportunityName = 'TestUpdateContactOwnerForTrial';
        Opportunity o1 = new Opportunity(AccountId=a.Id, name=opportunityName, StageName='Closed Won', Accounting_Platform__c='QuickBooks Online (US)', CloseDate = Date.today() );
        insert o1;
        
		OpportunityContactRole ocr = new OpportunityContactRole(OpportunityId = o1.Id, ContactId = newContact.Id, Role='Decision Maker',Isprimary=true );
		insert ocr;
        
    }	
		
}

Error: 

User-added image
trigger billingSubscriptionEmail on Opportunity (before update) {


List<Addon_Opportunity__c> addOppList = new List<Addon_Opportunity__c>([SELECT Name,Amount__c,Quantity__c FROM Addon_Opportunity__c where Id__c IN :Trigger.newMap.keySet()]); 

List<Contact> conList = new List<Contact>([select Email from Contact where Id In (select ContactId from OpportunityContactRole where OpportunityId IN :Trigger.newMap.keySet())]); 

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     Decimal planPrice=0 ;
    String[] toAddresses;
    if(addOppList!=null){
        for(Addon_Opportunity__c addon :addOppList){
                planPrice= planPrice+ addon.Amount__c;
            }    
  }
    for(Opportunity opp : trigger.new){
    
            if(opp.StageName=='Closed Won' && Trigger.oldMap.get(opp.Id).StageName!='Closed Won'){
                
                for(Contact c:conList){
                        if(c.Email.contains('webgility.com')){
                            toAddresses = new String[] {'test3@test.com','test1@test.com'};
                        }else{
                                 toAddresses = new String[] {'test4@test.com','test2@test.com'};
                        }     
                     String billingCycle;
                     String promo='';
                       
                        mail.setToAddresses(toAddresses );   
                        mail.setSubject('New Subscription - '+opp.Accounting_Platform__c+' - '+c.Email);   
                       if(opp.Billing_Cycle__c=='Monthly'){
                         billingCycle = 'Monthly';
                       }else{
                          billingCycle = 'Annual';  
                       }
                       
                      if(opp.promo_code__c!=null){
                          promo = opp.promo_code__c;
                      }else{
                          promo = 'None';
                      } 
                         Decimal P;
                       
                         if(opp.Recurring_Revenue__c==null) opp.Recurring_Revenue__c=0;
                         if(opp.One_Time_Fee__c==null) opp.One_Time_Fee__c=0;
                         P = (integer)opp.Recurring_Revenue__c +(integer)opp.One_Time_Fee__c-(integer)planPrice;
                         String template = 'Billing & Subscription Info:\n';
                         template+= '----------------------------------\n';
                       template+= 'Account Email: '+c.Email+'\n';
                         template+= 'Total Upfront Payment: $'+ opp.One_Time_Fee__c+'\n';  
                         template+= billingCycle+' Recurring Amount: $'+opp.Recurring_Revenue__c+'\n';
                         template+= 'Plan: '+opp.Plan__c+' ($'+P+')\n';
                         template+= 'Plan Tier: '+opp.Plan_Tier__c+'\n';
                         template+= '----------------------------------\n';
                         for(Addon_Opportunity__c addon :addOppList){
                             String qty='';
                             if(addon.Name=='Installation'){
                                addon.Name = 'Installation ,setup and traning';
                             }
                             if(addon.Name=='Add-on Users' || addon.Name=='Add-on Profile')
                             {
                                qty =  String.valueOf(addon.Quantity__c.format())+' ';
                             } 
                             template+= qty+addon.Name+': $'+addon.Amount__c;
                             template+= '\n';
                        }
                        template+= '\n';
                        template+= '----------------------------------\n';
                        template+= 'Recurring billing start date :'+opp.Purchase_Date__c+'\n';
                        template+= 'Promo Code :'+promo+'\n';
                        template+= 'SF Opportunity: '+'https://webgility.my.salesforce.com/'+Trigger.oldMap.get(opp.Id).Id;
                        List<String> args = new List<String>();
                   String formattedHtml = String.format(template, args);
                   
                    mail.setPlainTextBody(formattedHtml);
                         
                    } 
                   if(BillingEmailTriggerHandler.isFirstTime)
                        {
                          BillingEmailTriggerHandler.isFirstTime = false;  
                          Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});  
                       }  
            }

    }

}
Issue is getting on the line no. 6
List<Contact> conList = new List<Contact>([select Email from Contact where Id In (select ContactId from OpportunityContactRole where OpportunityId IN :Trigger.newMap.keySet())]); 

Thanks 








 
Hi Guys,

Need code coverage for apex scheduler class. I am getting only 47% coverage. Can anyone please give me the test class for more than 75% code coverage. 

Batchable Class:
global class TrialExpiredAlertTask implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
       String query = 'SELECT Id,ownerId,Accounting_Platform__c,StageName FROM opportunity WHERE CloseDate =NEXT_N_DAYS:1 and StageName=\'Trial\' and Accounting_Platform__c IN (\'QuickBooks Enterprise (US)\',\'QuickBooks POS (US)\')';
        
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope)
    { 	
        for(opportunity o : scope){ 
            Task t = new Task();
            t.Subject = 'Trial will expired after one day';
            t.Status = 'Open';
            t.ActivityDate= date.today();   
            t.Priority = 'High';
            t.Type= 'Call';
            t.Description = 'Please call to customer. Trial will expired by tomorrow.';
            t.WhatId =o.Id;
            t.ownerId = o.ownerId;
            insert t;        
        }
        
    }
    global void finish(Database.BatchableContext BC)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 
        mail.setToAddresses(new String[] {'kamrantest@gmail.com'});
        mail.setReplyTo('kamrantest@gmail.com');
        mail.setSenderDisplayName('Trial Expired Task alert Batch Processing');
        mail.setSubject('Trial Expired Task alert Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}
Code Coverage: 

User-added image

Test Class:
@isTest
public class TestScheduleTaskExpirationTaskAlert {

     public static testMethod void TestScheduleTaskExpirationTaskAlertTest()
    { Test.startTest();
        List<Opportunity> oplist = new List<Opportunity>{};
        SchedulableContext SC3;
       
        Account a1 = new Account(Name = 'TestScheduleTaskExpirationTaskAlert');
        insert a1;

        Opportunity opp1 = new Opportunity (Name='TestScheduleTaskExpirationTaskAlert',CloseDate = date.today(), Accountid = a1.id,stageName = 'Trial');
        oplist.add(opp1);
     
        ScheduleTaskExpirationTaskAlert wsch3 = new ScheduleTaskExpirationTaskAlert();
        wsch3.execute(SC3);
        string schedule = '0 5 1-23 * * ?';
     	system.schedule('Process Trans 123', schedule, wsch3);
        
    }

    public static testMethod void testBatchClass()
    {   Test.startTest();
        Database.BatchableContext BC;
       
        TrialExpiredAlertTask b = new TrialExpiredAlertTask();
        ID myBatchJobIDTask = database.executebatch(b);
        Test.stopTest();
    }

}

 
Hi, 
Getting Apex governor limit warning when we active on task trigger. Can you guys please help on it.
Thanks in advance.
Operation: insert.Name

By user/organization: 005160000064dkR/00DG0000000k8tZ

Caused the following Apex resource warnings:

Number of query rows: 25477 out of 50000
Unable to uderstands whats the issue with the trigger.
trigger activityCountUpdate on Task (after insert,after update) {
Set<String> whatIDs = new Set<String>();
    for (Task t : Trigger.new) {
          if(t.whatId != NULL)
            whatIDs.add(t.whatID);
    }
    Date dt;
    List<aggregateResult> resultsOutbound =[select count(Id) TotalOutbound from Task where WhatId IN :whatIDs and Type in ('Email', 'Email - AM', 'Voicemail', 'Outbound Call', 'Demo', 'CS Call', 'Marketing Email', 'Call')];
    List<aggregateResult> resultsInbound =[select count(Id) TotalInbound from Task where WhatId IN :whatIDs and Type in ('Inbound Call','Save Call')];
    List<aggregateResult> resultsOther =[select count(Id) TotalOther from Task where WhatId IN :whatIDs and Type in ('Other','Assisted Sale','Bad Number','Billing','Live Chat','Meeting','Implementation','')];
    List<aggregateResult> resultsTotal =[select count(Id) Total from Task where WhatId IN :whatIDs];
    
    List<Task> taskData = [select LastModifiedDate from Task where WhatId IN :whatIDs order by LastModifiedDate desc limit 1];
    String d,outbound,inbound,other,total;
    for(Task t : taskData){
        dt = date.parse(t.LastModifiedDate.format('MM/dd/yyyy'));
    }
    for(AggregateResult ar : resultsOutbound){ 
            outbound = String.valueOf(ar.get('TotalOutbound'));
    }
    for(AggregateResult ar1 : resultsInbound){ 
             inbound = String.valueOf(ar1.get('TotalInbound'));
    }
    for(AggregateResult ar2 : resultsOther){ 
             other = String.valueOf(ar2.get('TotalOther'));
    }
    for(AggregateResult ar3 : resultsTotal){ 
            total = String.valueOf(ar3.get('Total'));
    }
    
    List<Opportunity> oppResult = [select Id,Accounting_Platform__c,Activity_Count_Inbound__c,Activity_Count_Outbound__c,Activity_Count_By_Type__c, Total_Activity_Count__c,Date_of_last_contact__c  from Opportunity where Id IN: whatIDs];
  
    for(Opportunity opp : oppResult){
         opp.Activity_Count_Inbound__c =inbound; 
         opp.Activity_Count_Outbound__c = outbound;
         opp.Activity_Count_By_Type__c = other;
         opp.Total_Activity_Count__c = total;
         opp.Date_of_last_contact__c = dt;
        if(opp.Accounting_Platform__c!=''){
            update opp;
        }
        
    }
    
  
   
}



 
I need test class for the trigger.
trigger billingSubscriptionEmail on Opportunity (before update) {
if(BillingEmailTriggerHandler.isFirstTime)
{
BillingEmailTriggerHandler.isFirstTime = false;

List<Addon_Opportunity__c> addOppList = new List<Addon_Opportunity__c>([SELECT Name,Amount__c,Quantity__c FROM Addon_Opportunity__c where Id__c IN :Trigger.newMap.keySet()]); 

List<Contact> conList = new List<Contact>([select Email from Contact where Id In (select ContactId from OpportunityContactRole where OpportunityId IN :Trigger.newMap.keySet())]); 

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  
    for(Opportunity opp : trigger.new){
    
            if(opp.StageName=='Closed Won' && Trigger.oldMap.get(opp.Id).StageName!='Closed Won'){
                
                for(Contact c:conList){
               
                 String[] toAddresses = new String[] {'ahmeds@webgility.com'};
                 String billingCycle;
                 String promo='';
                   
                    mail.setToAddresses(toAddresses );   
                    mail.setSubject('New Subscription - '+opp.Accounting_Platform__c+' - '+c.Email);   
                   if(opp.Billing_Cycle__c=='Monthly'){
                     billingCycle = 'Monthly';
                   }else{
                      billingCycle = 'Annual';  
                   }
                   
                  if(opp.promo_code__c!=null){
                      promo = opp.promo_code__c;
                  }else{
                      promo = 'None';
                  }
                    String template = 'Billing & Subscription Info:\n\n';
                     template+= '----------------------------------\n';
                     template+= billingCycle+' Recurring Amount: $'+opp.Recurring_Revenue__c+'\n';
                     template+= 'Plan: '+opp.Plan__c+'\n';
                     template+= 'Account Email: '+c.Email+'\n';
                     template+= 'Total Upfront Payment: $'+ opp.One_Time_Fee__c+'\n'; 
                     template+= '----------------------------------\n';
                     for(Addon_Opportunity__c addon :addOppList){
                        
                         template+= addon.Quantity__c+' '+addon.Name+' : $'+addon.Amount__c;
                         template+= '\n';
                         
                    }
                    template+= '\n';
                    template+= 'One Time Fee: $'+opp.One_Time_Fee__c+'\n';
                    template+= '----------------------------------\n';
                    template+= 'Recurring billing start date :'+opp.Purchase_Date__c+'\n';
                    template+= 'Promo Code :'+promo;
                    List<String> args = new List<String>();
               String formattedHtml = String.format(template, args);
               
                mail.setPlainTextBody(formattedHtml);
                
              }
              Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});  
           }   

    }

 }
}
I have a opportuity trigger that sent an email before update the opporunity. Email sent properly but it send twice. I have also tried to update customer field and checked it in the condition but not solved. We have mulitiple triggers on opportunities, so may be possible it executes same time. Please help me on it.
trigger billingSubscriptionEmail on Opportunity (before update) {

List<Addon_Opportunity__c> addOppList = new List<Addon_Opportunity__c>([SELECT Name,Amount__c,Quantity__c FROM Addon_Opportunity__c where Id__c IN :Trigger.newMap.keySet()]); 

List<Contact> conList = new List<Contact>([select Email from Contact where Id In (select ContactId from OpportunityContactRole where OpportunityId IN :Trigger.newMap.keySet())]); 

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  
    for(Opportunity opp : trigger.new){
    
            if(opp.StageName=='Closed Won' && Trigger.oldMap.get(opp.Id).StageName!='Closed Won'){
                
                for(Contact c:conList){
               
                 String[] toAddresses = new String[] {'ahmeds@webgility.com'};
                 String billingCycle;
                 String promo='';
                   
                    mail.setToAddresses(toAddresses );   
                    mail.setSubject('New Subscription - '+opp.Accounting_Platform__c+' - '+c.Email);   
                   if(opp.Billing_Cycle__c=='Monthly'){
                     billingCycle = 'Monthly';
                   }else{
                      billingCycle = 'Annual';  
                   }
                   
                  if(opp.promo_code__c!=null){
                      promo = opp.promo_code__c;
                  }else{
                      promo = 'None';
                  }
                    String template = 'Billing & Subscription Info:\n\n';
                     template+= '----------------------------------\n';
                     template+= billingCycle+' Recurring Amount: $'+opp.Recurring_Revenue__c+'\n';
                     template+= 'Plan: '+opp.Plan__c+'\n';
                     template+= 'Account Email: '+c.Email+'\n';
                     template+= 'Total Upfront Payment: $'+ opp.One_Time_Fee__c+'\n'; 
                     template+= '----------------------------------\n';
                     for(Addon_Opportunity__c addon :addOppList){
                        
                         template+= addon.Quantity__c+' '+addon.Name+' : $'+addon.Amount__c;
                         template+= '\n';
                         
                    }
                    template+= '\n';
                    template+= 'One Time Fee: $'+opp.One_Time_Fee__c+'\n';
                    template+= '----------------------------------\n';
                    template+= 'Recurring billing start date :'+opp.Purchase_Date__c+'\n';
                    template+= 'Promo Code :'+promo;
                    List<String> args = new List<String>();
               String formattedHtml = String.format(template, args);
               
                mail.setPlainTextBody(formattedHtml);
                
              
                Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
              
                
              }  
           }   

    }


}



Thanks in advance
Hi, I have a task trigger that updates the opportunity fields but i got the error email:

"Developer script exception from Webgility : activityCountUpdate : Apex trigger activityCountUpdate caused an unexpected exception, contact your administrator: activityCountUpdate: System.LimitException: Too many query rows: 50001"

Can anyone help me to sort out this issue and update the trigger as well if any thing wrong in it.
Thanks
trigger activityCountUpdate on Task (after insert,after update) {
Set<String> whatIDs = new Set<String>();
    for (Task t : Trigger.new) {
            whatIDs.add(t.whatID);
    }
    Date dt;
    List<aggregateResult> resultsOutbound =[select count(Id) TotalOutbound from Task where WhatId IN :whatIDs and Type in ('Email', 'Email - AM', 'Voicemail', 'Outbound Call', 'Demo', 'CS Call', 'Marketing Email', 'Call')];
	List<aggregateResult> resultsInbound =[select count(Id) TotalInbound from Task where WhatId IN :whatIDs and Type in ('Inbound Call','Save Call')];
    List<aggregateResult> resultsOther =[select count(Id) TotalOther from Task where WhatId IN :whatIDs and Type in ('Other','Assisted Sale','Bad Number','Billing','Live Chat','Meeting','Implementation','')];
    List<aggregateResult> resultsTotal =[select count(Id) Total from Task where WhatId IN :whatIDs];
    
    List<Task> taskData = [select LastModifiedDate from Task where WhatId IN :whatIDs order by LastModifiedDate desc limit 1];
    String d,outbound,inbound,other,total;
    for(Task t : taskData){
        dt = date.parse(t.LastModifiedDate.format('MM/dd/yyyy'));
    }
    for(AggregateResult ar : resultsOutbound){ 
            outbound = String.valueOf(ar.get('TotalOutbound'));
    }
    for(AggregateResult ar1 : resultsInbound){ 
             inbound = String.valueOf(ar1.get('TotalInbound'));
    }
    for(AggregateResult ar2 : resultsOther){ 
             other = String.valueOf(ar2.get('TotalOther'));
    }
	for(AggregateResult ar3 : resultsTotal){ 
            total = String.valueOf(ar3.get('Total'));
    }
    
    List<Opportunity> oppResult = [select Id,Activity_Count_Inbound__c,Activity_Count_Outbound__c,Activity_Count_By_Type__c, Total_Activity_Count__c,Date_of_last_contact__c  from Opportunity where Id =: whatIDs];
  
    for(Opportunity opp : oppResult){
         opp.Activity_Count_Inbound__c =inbound; 
         opp.Activity_Count_Outbound__c = outbound;
         opp.Activity_Count_By_Type__c = other;
         opp.Total_Activity_Count__c = total;
         opp.Date_of_last_contact__c = dt;
    }
    update oppResult;
   
    

}




 
Hi,

I have created a trigger on task for after insert and after update. That updates the opporutnity custom fields based on task 'type'  counts. It is working but i have also reciving Apex governor limit warnig. This waring is coming after push this trigger on production SF. Can anybody please correct my trigger to avoid these waring issue.

Thanks in advance.
trigger activityCountUpdate on Task (after insert,after update) {
Set<String> whatIDs = new Set<String>();
    for (Task t : Trigger.new) {
            whatIDs.add(t.whatID);
    }
    Date dt;
    List<aggregateResult> resultsOutbound =[select count(Id) TotalOutbound from Task where WhatId IN :whatIDs and Type in ('Email', 'Email - AM', 'Voicemail', 'Outbound Call', 'Demo', 'CS Call', 'Marketing Email', 'Call')];
	List<aggregateResult> resultsInbound =[select count(Id) TotalInbound from Task where WhatId IN :whatIDs and Type in ('Inbound Call','Save Call')];
    List<aggregateResult> resultsOther =[select count(Id) TotalOther from Task where WhatId IN :whatIDs and Type in ('Other','Assisted Sale','Bad Number','Billing','Live Chat','Meeting','Implementation','')];
    List<aggregateResult> resultsTotal =[select count(Id) Total from Task where WhatId IN :whatIDs];
    
    List<Task> taskData = [select LastModifiedDate from Task where WhatId IN :whatIDs order by LastModifiedDate desc limit 1];
    String d,outbound,inbound,other,total;
    for(Task t : taskData){
        dt = date.parse(t.LastModifiedDate.format('MM/dd/yyyy'));
    }
    for(AggregateResult ar : resultsOutbound){ 
            outbound = String.valueOf(ar.get('TotalOutbound'));
    }
    for(AggregateResult ar1 : resultsInbound){ 
             inbound = String.valueOf(ar1.get('TotalInbound'));
    }
    for(AggregateResult ar2 : resultsOther){ 
             other = String.valueOf(ar2.get('TotalOther'));
    }
	for(AggregateResult ar3 : resultsTotal){ 
            total = String.valueOf(ar3.get('Total'));
    }
    
    List<Opportunity> oppResult = [select Id from Opportunity where Id =: whatIDs];
  
    for(Opportunity opp : oppResult){
         opp.Activity_Count_Inbound__c =inbound; 
         opp.Activity_Count_Outbound__c = outbound;
         opp.Activity_Count_By_Type__c = other;
         opp.Total_Activity_Count__c = total;
         opp.Date_of_last_contact__c = dt;
         update opp;
    }
   
    

}

 
Hi All,

I want to update the few fields of converted leads. So can you guys please help me and let me know how can update it. 

Thanks in advance

I need to get Opportunity Owner name In the  opp trigger. Can anyone help on this ?

here is my trigger code :

 

trigger PortalCallout on Opportunity (after insert,after update) {

    if(Trigger.IsInsert){
       for (Opportunity o : Trigger.new) {
           // make the asynchronous web service callout
           HttpResponse r= new Httpresponse();
           SendDataToPortal s = new SendDataToPortal();
           if(o.Subscriber_ID__c!=null && o.Client_ID__c!=null ){
               r = s.sendNotification(o.Subscriber_ID__c, o.Id, o.AccountId,o.Client_ID__c,'','','','','','','',o.Name,'','','','insert');
           } 
           //system.debug('r');
      }
    }
    if(Trigger.IsUpdate){
       for (Opportunity o : Trigger.new) {
                    // make the asynchronous web service callout
        HttpResponse r= new Httpresponse();
        SendDataToPortal s = new SendDataToPortal();
        String cdate = NULL;
        String isOppNameUpdated = 'false';
        String isCancelFldUpdated = 'false';
        String isOtherFldUpdated = 'false';
        //system.debug('r');
    
        /******************************** REPLACE SALESFORCE ADMIN UserID ON PRODUCTION ***********************************/
           if(userinfo.getUserId()!='005160000064dkRAAQ' &&  o.Subscriber_ID__c!=null && Trigger.OldMap.get(o.Id).Name!= o.Name){
               
               isOppNameUpdated = 'true';
           }
           
           if(userinfo.getUserId()!='005160000064dkRAAQ' &&  o.Subscriber_ID__c!=null && (Trigger.OldMap.get(o.Id).Cancellation_Reason__c!= o.Cancellation_Reason__c || Trigger.OldMap.get(o.Id).Cancellation_Date__c!=o.Cancellation_Date__c || Trigger.OldMap.get(o.Id).Cancellation_Feedback__c!=o.Cancellation_Feedback__c)){
               
               isCancelFldUpdated = 'true';
               cdate = string.valueof(o.Cancellation_Date__c);
           }
    
           if(userinfo.getUserId()!='005160000064dkRAAQ' && o.Subscriber_ID__c!=null && (Trigger.OldMap.get(o.Id).Accounting_Platform__c!= o.Accounting_Platform__c || Trigger.OldMap.get(o.Id).Order_Volume__c!= o.Order_Volume__c || Trigger.OldMap.get(o.Id).promo_code__c!= o.promo_code__c)) {
               isOtherFldUpdated='true';
               
           }
           if(isOppNameUpdated=='true' || isCancelFldUpdated=='true' || isOtherFldUpdated=='true'){
               r = s.sendNotification(o.Subscriber_ID__c, o.Id, o.AccountId,o.Client_ID__c, o.Cancellation_Reason__c,o.Order_Volume__c,o.Accounting_Platform__c,cdate,o.promo_code__c,o.Cancellation_Feedback__c,o.Susbcription_Status__c,o.Name,isOppNameUpdated,isCancelFldUpdated,isOtherFldUpdated,'update'); 
           }
    
        system.debug('r');
    
    }
  }

}

I have implemnted a trigger on custom object which hold the opportunity Id and Opportunity Name. I need to access  a custom field from oportunity object for which I used a SOQL query but not able to get coverage for that . so need help on this .

My Apex  Trigger :

trigger SendImplementaionStageOnPortal on Implementation__c (after update) { // TEST CLASS TestSendImplementationStageOnPortal
    if(Trigger.IsUpdate){
         for (Implementation__c imp : Trigger.new) {
                // make the asynchronous web service callout
                HttpResponse r= new Httpresponse();
                 SendDataToPortal s = new SendDataToPortal();
                 String ImpStage = NULL;

             /******************************** REPLACE SALESFORCE ADMIN UserID ON PRODUCTION ***********************************/
               
             if(imp.Opportunity_ID__c!=null && Trigger.OldMap.get(imp.Id).Stage__c!= imp.Stage__c && imp.Stage__c=='Complete'){
                   
                 //Query Opportunity
                List<Opportunity>lstOppts = [select Subscriber_id__c From Opportunity WHERE  Id=:imp.Opportunity_ID__c limit 1];
                if(lstOppts.size()>0){
                
                        System.debug('Subscriber_id__c-MY: '+ lstOppts[0].Subscriber_id__c);
                      // List<Account>lstAccounts = [select id,Name,(select id,FirstName,LastName FROM Contacts ) From Account WHERE Id =:lstOppts[0].id];
               
                 
                 ImpStage = string.valueof(imp.Stage__c);
                  //r = s.sendImplementaionData(lstOppts[0].Subscriber_id__c,imp.Stage__c); 
                   r = s.sendImplementaionData(lstOppts[0].Subscriber_id__c,'complete'); 
             }
             
               
            }
    }
}
}

 

My Apex Test Class :

@isTest
public class TestSendImplementationStageOnPortal {
    static testMethod void sendImplementaionDataTest() {  
        
        Account a = new Account(Name = 'SDToPortalImpTest',Type = 'Customer',TypeCustomerDate__c=Date.today());
        insert a;
        Contact newContact = new Contact(Lastname='testLastName', AccountId = a.Id ,Email='mayanks+test@webgility.com',phone ='56465464' , LeadSource='Inbound', Lead_Source_Detail__c = 'Website');
        insert newContact;
           String opportunityName = 'SDToPortalImpTest';
       
        Opportunity o1 = new Opportunity(AccountId=a.Id, name='OPP test1',Type ='New Business',Susbcription_Status__c = 'Active', Subscriber_ID__c =3651,Client_ID__c=1258, StageName='Closed Won',CloseDate = Date.today() );
        insert o1;
        OpportunityContactRole ocr1 = new OpportunityContactRole(OpportunityId = o1.Id, ContactId = newContact.Id, Role='Decision Maker',Isprimary=true );
        insert ocr1;
      
    
         Implementation__c imp = new Implementation__c(name='IMP test1',Opportunity_Name__c=o1.Id,Stage__c='New');
         insert imp;
          
        List<Opportunity> myList = new List<Opportunity>(); // Define a new list
          Opportunity opp = new Opportunity(Subscriber_id__c=3651,Id= imp.Opportunity_ID__c);
          myList.add(opp);
        
       //List<Opportunity>lstOppts = [select Subscriber_id__c From Opportunity WHERE  Id='0061F00000AOBTkQAP'];
       

        Test.StartTest(); 
        imp.Stage__c ='Complete';
        imp.Id='a1s1F0000017sCqQAI';
        imp.Opportunity_Name__c='0061F00000AOBTkQAP';
        update imp;
        
       List<Opportunity>lstOppts = [select Subscriber_id__c From Opportunity WHERE  Id=:imp.Opportunity_ID__c limit 1];
         System.assert(lstOppts != null);

         Test.StopTest();  
    }
}

Hello everyone,
I have created a trigger which will update Contact Object field(Most_recent_Opportunity_Stage__c) whenever opportunity status gets changed.
My trigger is working fine but associated Test class is not making 75% code coverage of Trigger. I am new to salesforce and not having much experince to build test class so please help me.

Here is my Trigger and associated test class :

Trigger :

trigger UpdateMostRecentOpportunityStageOfContact on Opportunity (after update) {
  Set<String> ContactIds = new Set<String>();
     Set<String> oppIds = new Set<String>();
     if(UpdateStageOnContactHandler.isFirstTime){
             UpdateStageOnContactHandler.isFirstTime=false;
    List<OpportunityContactRole> conList = new List<OpportunityContactRole>([select ContactId from OpportunityContactRole where IsPrimary = true and OpportunityId IN :Trigger.newMap.keySet() limit 1]);
     for(OpportunityContactRole c :conList)
       {
           ContactIds.add(c.ContactId);
       }    
    List<OpportunityContactRole> oppList =  new List<OpportunityContactRole>([select ContactId,opportunityId,CreatedDate from OpportunityContactRole where IsPrimary = true and ContactId =: ContactIds order by CreatedDate desc  limit 1]);
    for(OpportunityContactRole cr :oppList)
       {
           oppIds.add(cr.opportunityId);
       } 
    if(!oppIds.isEmpty()){
    Opportunity op = [select StageName from opportunity where Id =:oppIds limit 1]; 
    List<Contact> contactToUpdate = new List<Contact>();
    for(Opportunity opp : trigger.new){
           for(OpportunityContactRole c :oppList){ 
                if(opp.AccountId != null){
                 contactToUpdate.add(new Contact(Id = c.ContactId, Most_recent_Opportunity_Stage__c=op.StageName)); 
               }
           }    
       }
       if (contactToUpdate != null && !contactToUpdate.isEmpty())
        {
            Update contactToUpdate;
        } 
     }
   }      
 }


TEST Class :

@isTest
public class TestUpdateMostRecentopportunityStage {
   static testMethod void TestUpdateStageOnContactTest()
    {   
        Account a = new Account(Name = 'TestUpdateStageOnContactTest');
        a.Type = 'Prospect';
        insert a;

        Contact newContact1 = new Contact(Lastname='TestUpdateStageOnContactTest1', AccountId = a.Id ,Email='mayanks+test1@webgility.com' );
        insert newContact1;
        
        Contact newContact2 = new Contact(Lastname='TestUpdateStageOnContactTest2', AccountId = a.Id ,Email='mayanks+test2@webgility.com' );
        insert newContact2;
    
      
        Opportunity o1 = new Opportunity(AccountId=a.Id, name='OPP test1', StageName='Demo', CloseDate = Date.today() );
       insert o1;
        OpportunityContactRole ocr1 = new OpportunityContactRole(OpportunityId = o1.Id, ContactId = newContact1.Id, Role='Decision Maker',Isprimary=true );
        insert ocr1;
        
          Opportunity o2 = new Opportunity(AccountId=a.Id, name='OPP test2', StageName='Open', CloseDate = Date.today() );
       insert o2;
        OpportunityContactRole ocr2 = new OpportunityContactRole(OpportunityId = o2.Id, ContactId = newContact2.Id, Role='Decision Maker',Isprimary=true );
        insert ocr2;
        
          Test.StartTest();
        o1.stageName='Demo';
        update o1;
        newContact1.Most_recent_Opportunity_Stage__c='Demo';
        update newContact1;
        
         o2.stageName='Open';
        update o2;
        newContact2.Most_recent_Opportunity_Stage__c='Open';
        update newContact2;
        
        Test.StopTest();
         
      }   
}


Thanks,
Mayank

Hi All,

I need a Batchable class that will update the lead Status as 'Open' when no actvities logged under Lead Object

Step1: We have 2 lead status 'Contacted Attempt Made' and 'Discovery'. When these status set, I update the stage date (Custom field Stage_date__c). 
Step2: If stage date is more than 30 days and no actvity logged under lead object from stage date then we need to update the Lead status as 'Open'

Can you please provide the class to update the stage 

Thanks in advanced
 

.

 

 

Hello Guys,

I have created a trigger on contact that insert a new opportunity. It is working properly but when we perform bulk operation then it's giving the error CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: OpportunityCreatorOnContact: System.LimitException: Too many SOQL queries: 101 

See the trigger below and please provide me the solution for it

trigger OpportunityCreatorOnContact on Contact (before update) {
   
    if(OpportunityCreatorOnContactHandler.isFirstTime){
        OpportunityCreatorOnContactHandler.isFirstTime=false;
  
       List<Contact> ContList = new List<Contact>([SELECT Name,Contact.Account.Id,Contact.Account.Name, Most_recent_Opportunity_Stage__c, Contact.Account.OwnerId,Quarantine__c,mkto71_Lead_Score__c from Contact where id IN :Trigger.newMap.keySet()]); 
                for(Contact c : trigger.new)
                {   
                    for(Contact c1: ContList){  

                      if(c.Most_recent_Opportunity_Stage__c=='Closed Lost' && trigger.oldMap.get(c.Id).Create_New_Opp__c==false && c.Create_New_Opp__c==true  && c.mkto71_Lead_Score__c>=100 ) {   
                        
			Opportunity opp = new Opportunity(Name=c1.Account.Name, AccountID=c.AccountId, StageName='Open', CloseDate=Date.Today().addDays(+30),ownerID = c1.Account.OwnerId);
                        insert opp;
                      	
			opportunityCOntactRole oppCOn = new opportunityCOntactRole(OpportunityId=opp.id, contactId= c.Id, isPrimary=true);
                      	insert oppCon;

                      }    
                  }    
                }     

                        
          }    
}
Thanks

 

 

 

 

Hi Guys,

I want to display only those contacts that are related to the selected account. I have 2 custome lookup field on opportunity object, one is the referrer account and another one is referrer contact. When we select the lookup account and save it then need to display only related contacts. I have created a lookup filter but its not display contacts by default when click on the contact lookup, see the lookup filter as below

 

 

 

 

 

User-added image

Please help on it

Thanks


 

Hi All,

I want to update the few fields of converted leads. So can you guys please help me and let me know how can update it. 

Thanks in advance