• SalesforceCrm AccountCRM
  • NEWBIE
  • 35 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 40
    Questions
  • 60
    Replies
Can any one help me on this ...
We are using the standard functionality of Task "Send Email" Button for the cases to reply to the customer.When the customers sends a email ,keeping in cc to service team a ticket is raised .when we click on the "Send Email Button" the cc is not getting copied . Any idea or suggestion what may be the issue.
PFA Screen Shot :
User-added image
Can any one help me out . How to send an email to Account Owner from contract object in Batch Class.Im using templateid ,in target object im giving the contact id ,in whatid im sending the Account owner email ,but the Account owner is not getting any email.What im doing is correct .Any help very much appreciated.
Portion of the Code :
global void execute(Database.BatchableContext bc, List < Contract >
     recs) {
            List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
             for (Contract c: recs) {
                if (c.Contact_Email__c != null) {
                    List < String > toAddresses = new List < String > ();
                     List < String > CcAddresses = new List < String > ();
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    //toAddresses.add(c.Contact_Email__c);
                     ccAddresses.add(c.Account.Owner.Email);
                    //toAddresses.add(c.Account.Owner.Manager.Email);
                    // mail.setToAddresses(toAddresses);
                     mail.setCcAddresses(CcAddresses);
            mail.setTargetObjectId('c.contact__r.Id)');
                     mail.setWhatId(c.Account.Owner.Manager.Email));
                     mail.setTemplateId('00X4B000000M3go');
                     mail.setSaveAsActivity(false);
                mailList.add(mail);
                 }
            }
             Messaging.sendEmail(mailList);
         }

 
I have a Batch class and written a test class where the code coverage is displaying as 50% only.How to cover the single message email in the test class .
Batch Class :
global class NinetyDaysNotificationEmail implements Database.Batchable < sObject >, Schedulable, Database.Stateful {
    global List<String> errorMessages = new List<String>();
    global Database.QueryLocator start(Database.BatchableContext bc) {

        Date ed = Date.today().addDays(1);
        System.debug(Date.today().addDays(1));

        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'Subscription Administrator' AND Contract__r.EndDate =: ed]) {
            setContractIds.add(objContract.Contract__c);
        }

         return Database.getQueryLocator([Select  id, Contract_Name__c , EndDate ,Contact_Email__c,  Account.Owner.Email ,Account.Owner.Manager.Email,Contact__r.ID FROM Contract  WHERE Id IN: setContractIds ]);
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               ccAddresses.add(c.Account.Owner.Email);
                 mail.setCcAddresses(CcAddresses);
                  mail.setTargetObjectId(c.Contact__r.ID);
                  mail.setWhatId(c.Id);
                  mail.setTemplateId('00X4B000000M08W');
                  mail.setSaveAsActivity(false);
                mailList.add(mail);
            }
        }

      Messaging.sendEmail(mailList);

    }

    global void finish(Database.BatchableContext bc) {
        AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];

        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce NotificationEmailtoCustomer Finished: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

    global void execute(SchedulableContext SC) {
        NotificationEmailtoAccountExecutive batchable = new NotificationEmailtoAccountExecutive();
        database.executebatch(batchable);
    }
}
Test Class :
@isTest
public class TestNinetyDaysNotificationEmail{
static testMethod void TestNinetyDays()
{
Account acc90 = new Account(Name='Testing NinetyDaysNotificationEmail', BillingStreet='Banjara hills', Industry = 'Banking' );
        insert acc90 ;

        contact cc90 = new contact(FirstName ='Test Contact', LastName ='NinetyDaysNotificationEmail', Role__c='Subscription Administrator',Email='xyz@edb.com',AccountId=acc90.Id);
        insert cc90;

        Opportunity opty90 = new Opportunity(Name = 'Test Oppty NinetyDaysNotificationEmail', StageName ='Proposal/Price Quote', CloseDate = System.Today(),  AccountId = acc90.Id,);
        insert opty90;

        list<OpportunityContactRole> opptyConRolelist90 =  new list<OpportunityContactRole>{
            new OpportunityContactRole(ContactId = cc90.Id, OpportunityId = opty90.Id, IsPrimary = false, Role = 'Subscription Administrator')
        };   
        insert opptyConRolelist90;

product2 p90 = new product2(Name='PostgresPlus',Product_Name1__C='Product - Subscription',IsActive = true, Renewable__c=True);
        insert p90;

        PricebookEntry pbey90 = new PricebookEntry(Product2ID=p90.id, Pricebook2ID= test.getStandardPricebookId(), UnitPrice=50, isActive=true);
        insert pbey90;

        Opportunitylineitem ooli9 = new Opportunitylineitem(OpportunityId = opty90.Id, PricebookEntryId = pbey90.Id, Quantity =4, Start_Date__c = System.today(), End_Date__c =  System.today() + 90); 
  insert ooli9;

        Opportunitylineitem ooli90 = new Opportunitylineitem(OpportunityId = opty90.Id, PricebookEntryId = pbey90.Id, Quantity =4, Start_Date__c = System.today(), End_Date__c =  System.today() + 100,  Parent_Opportunity_Product_Id__c=ooli9.Id);
        insert ooli90;

         Contract contr90 = new Contract(CurrencyIsoCode='USD',   Opportunity_Product_Id__c=ooli9.Id,AccountId=acc90.Id,StartDate=System.today() ,EndDate=System.today());
        insert contr90;

Contract_Role__c contrRole90 = new Contract_Role__c(Role__c='Subscription Administrator' ,Contract__c=contr90.Id);
        insert contrRole90;

        Test.StartTest();
        NinetyDaysNotificationEmail Ninetydays = new NinetyDaysNotificationEmail();
        Database.executebatch(Ninetydays);
        Test.StopTest();
    }   
     Static testMethod void TestNinetyDays90()
    { 
        Test.StartTest();
        NinetyDaysNotificationEmail AE = new  NinetyDaysNotificationEmail();
        String sch = '0 0 23 * * ?'; 
        system.schedule('Test Notification email to Customer', sch, AE); 
        //Database.executebatch(b);
        Test.StopTest();
    }
    }
The portion which is not getting covered in DC :
global void execute(Database.BatchableContext bc, List < Contract > recs) {
            List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
            for (Contract c: recs) {
                if (c.Contact_Email__c != null) {
                    List < String > toAddresses = new List < String > ();
                    List < String > CcAddresses = new List < String > ();
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                   ccAddresses.add(c.Account.Owner.Email);
                     mail.setCcAddresses(CcAddresses);
                      mail.setTargetObjectId(c.Contact__r.ID);
                      mail.setWhatId(c.Id);
                      mail.setTemplateId('00X4B000000M08W');
                      mail.setSaveAsActivity(false);
                    mailList.add(mail);
                }
            }

          Messaging.sendEmail(mailList);

        }
Any help very much appreciated.


 
Can any one help me out with this error .
1)When im using mail.setTargetObjectId(c.CustomerSignedId); the system start throwing a error .
SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing targetObjectId with template:
2)When im using mail.setTargetObjectId('00538000004bjrA'); the system start throwing a error .
SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.: [whatId, 8004B000000Qmzi]
3)When i use mail.setTargetObjectId(c.OwnerId); ,
i get the email but the merge fields value are not getting displayed
Here is the Code which im using the Batch Class :
global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
                ccAddresses.add(c.Account.Owner.Email);
               // toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setCcAddresses(CcAddresses);
                mail.setTargetObjectId(c.CustomerSignedId);
                //mail.setTargetObjectId('00538000004bjrA');
                mail.setWhatId(c.Id);
                mail.setTemplateId('00X4B000000M3go');
                mail.setSaveAsActivity(false);
           mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }
Any Suggestion very much appreciated.
 
Hello ,
I had a requirement where i need to send an email notification 100 days before the contract end date based on the condition.So i have created the workflow rule with the condition and time based workflow ,email alert.Which worked fine.
Now once the 100 days email is sent to the opportunity owner,then their is a field on contract object "SRR" (picklist field - as yes/no).Now the opportunity owner will update the field "SRR" value .
1)If the owners updates the field "SRR" value as "Yes" then an email needs to send to the customer for 45 /30 /15 days before the contract end date.
2)If the owners updates the field "SRR" value as "No" then stop sending  email needs to  the customer .
3)If the owners does not updates the field "SRR" value  within 90 days before the contract end date,then an email needs to be sent to the owner  and superior.
How can i get this filter in WFR .Any help or example very much appreciated.
Hello ,
I have a requirement ,where the system should automatically  calculate 100 days before the contract end date and send an alert to the customer.How can we formulate the formulae ,
 
1)Date dt = Today()+100 and then assign it to contract end date =:dt in a query
2) Date ed = Date.today().addDays(100);
3)contract end date >=Today+100days
4)Date=(today+100 - contractend date)
or how can we calculate..Im in dilemma  which one should work to calculate.Any thoughts or ideas or example very much appreciated.
Can any one help me on this or give Suggestion .I have a requirement where i need to send an email notification to the owner before the contract end date.Their few conditions to be satisfied and then the email notification is sent.
1)I need to send an email notification to the opportunity owner,keeping in cc to the contract owner 4months before the contract end date.
Their are few conditions which needs to get satisfied ,
Condition is when the 
a)"Status Renewal" is equal to pipeline ,next renewal status And 
b)when the "Status Renewed next year" is not equal to renewed ,renewed lost.
Here "Status Renewal" and "Status Renewed next year" are picklist field.
Once the condition is satisfied , then the email notification is sent to the opportunity owner ,keeping in cc to the contract owner.
Now  if we get the response from the customer for the renewal ,then an update is done .
We have a picklist field as ''send renewal reminder" with yes or no values.Now here , the update is done by the owner of the record.Their few more condition now.
Condition 1:

If the "Send renewal reminder" is "YES" then an email notification mail is to be sent to the customer for 45,30 and 15 days .
If this  condition is satisfied .i.e If the a)"Status Renewal" is equal to pipeline ,next renewal status And
b)when the "Status Renewed next year" is not equal to renewed ,renewed lost And
c)"Send renewal reminder" is "YES".

Condition 2:

If the "Send renewal reminder" is "No" ,then stop sending the email notification .
Condition 3 :

If the "Send renewal reminder" is not updated ,then an email notification needs to be sent to the opportunity owner and the superior for 3months.

Any Suggestion or ideas very much appreciated.

 
Hello,
I have a written a Batch Class to send an notification email 60 days before the contract end date.I have created the email template and used in the code.But the system throws an error as :
Batch Class Error as System.StringException: Invalid id at line #29 
mail.setTargetObjectId(c.Owner.Email);
global class SixtyDaysNotificationEmail implements Database.Batchable < sObject >, Schedulable, Database.Stateful {
    global List<String> errorMessages = new List<String>();
    global Database.QueryLocator start(Database.BatchableContext bc) {
        
        Date ed = Date.today().addDays(60);
        System.debug(Date.today().addDays(60));
        
        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'Subscription Administrator' AND Contract__r.EndDate =: ed]) {
            setContractIds.add(objContract.Contract__c);
        }
        
        return Database.getQueryLocator('Select  id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c,  Account.Owner.Email ,Account.Owner.Manager.Email,Owner.Email FROM Contract  WHERE Id IN: setContractIds');
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
                ccAddresses.add(c.Account.Owner.Email);
               // toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setCcAddresses(CcAddresses);
                mail.setTargetObjectId(c.Owner.Email);
                mail.setTemplateId('00X4B000000M3zx');
                mail.setSaveAsActivity(false);
               // mail.setSubject('Notification Before 100 Days of Contract End Date to Account Executive and Manager');
               // String messageBody = '<html><body>Hi ,The Contract Named ' + c.Contract_Name__c  + ',<br>Will get Expired within 60 Days . <br>Kindly take approriate action to inform the Customer.<br><br><b>Regards,</b><br>CAB</body></html>';
               // mail.setHtmlBody(messageBody);
                mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }

    global void finish(Database.BatchableContext bc) {
        AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce NotificationEmailtoAccountExecutive Finished: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
    global void execute(SchedulableContext SC) {
        NotificationEmailtoAccountExecutive batchable = new NotificationEmailtoAccountExecutive();
        database.executebatch(batchable);
    }
}
The targetobjectid should be for the contact.But when i use mail.setTargetObjectId(c.Contact_Email__c); the system throws the same error .
Any help very much appreciated.
 
 
Hello ,
Do we have an option to send an email alter format in a Send email message .
As in Email Alert ..we have
Subject Line
To ,From nd CC
Body
In body we give the detailed description etc.
For example :I would like to send an email to the customer regarding an product .
So how can i get it formatted in an sendemail message .
Any example very much appreciated.

 
Hello ,
The System throws an Error as :
Compile Error: expecting a right parentheses, found ',' at line 22 column 298
When i use this query
 
Database.getQueryLocator([Select id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c, Owner.Email, Owner.Manager.Email ,Account.Owner.Email,Account.Owner.Manager.Email  FROM Contract  WHERE Id IN: setContractIds AND Renewal_Status__c IN :('Pushed Forward To Next Quarter','In Pipe') AND Next_Quarter_Renewal_Status__c IN :('Renewed','Renewal lost’)]);
Any help very much appreciated.




 
Hello All,
I had a requirement where i need to send an email notification 100 days before the contract end date.So based on this we had a batch and schedule class written.Now we would like to add few more condition in the code.
We have two picklist value as 'Status Renewed' and "Status Renewed next Year".This picklist field has some values  as Status renewed for nxt quarter , pipeline etc the other picklist has renewed and renewed lost.
Condition is when the "Status Renewed" is equal to "Status renewed for next quarter " or "Pipeline" AND when "Status Renewed next Year" is not equal to "Renewed" or"Renewed lost".
So how do i give this condition in an execute method.When this condition is satisfied ,then the email notification should be sent to the owner before 100 days.

Batch and Schedule Class:
global class NotificationEmailtoAccountExecutive implements Database.Batchable < sObject >, Schedulable, Database.Stateful {
	global List<String> errorMessages = new List<String>();
    global Database.QueryLocator start(Database.BatchableContext bc) {
     
        Date ed = Date.today().addDays(100);
        System.debug(Date.today().addDays(100));
        
        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'Subscription Administrator' AND Contract__r.EndDate =: ed]) {
			setContractIds.add(objContract.Contract__c);
        }
        
        return Database.getQueryLocator('Select  id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c, Owner.Email, Owner.Manager.Email ,Account.Owner.Email,Account.Owner.Manager.Email  FROM Contract  WHERE Id IN: setContractIds');
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
	        toAddresses.add(c.Owner.Email);
                toAddresses.add(c.Account.Owner.Email);
                toAddresses.add(c.Owner.Manager.Email);
                toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Notification Before 100 Days of Contract End Date');
                String messageBody = '<html><body>Hi ' + c.Contract_Name__c  + ',<br>Your  Contract Expires within 100 Days . <br>Kindly take  action.<br><br><b>Regards,</b><br>ADP</body></html>';
                mail.setHtmlBody(messageBody);
                mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }

    global void finish(Database.BatchableContext bc) {
		AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce NotificationEmailtoAccountExecutive Finished: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
	}
	
	global void execute(SchedulableContext SC) {
        NotificationEmailtoAccountExecutive batchable = new NotificationEmailtoAccountExecutive();
		database.executebatch(batchable);
    }
}
Any help very much appreciated.

 
We had a requirement where we need to send an notification email to owner and manager .Based on it we have written some code etc.
Small concern is ---
1)Untill their is a Manager field vaue  populated in the user record,the code gets triggered.
2)If the Manager field is blank ,then the value does not get displayed .The code doesnot get triggered throws error.
3)If the Manager gets changed in between ,then how  the notification email  will go to the related owners- manager ,because the manager field in the  user record is filled manually.
4)Its Manadatory to have a Manager field value populated in the user record ,if the scenario is that the notification email to be sent to the owner and manager of the record.
Any Suggestion or Ideas very much appreciated.
 
Based on the requirement i have written a batch class.The Scenarios is i need to send an email notification 90 days before the contract end date to the contract owner.Where the contract role should be of 'SA'.But the email is not going to the contract owner.Correct me if the code written is correct or wrong.Any help very much appreciated.

Batch Class :
global class NotificationEmailtoOwner implements Database.Batchable < sObject > 
{
    global Database.QueryLocator start(Database.BatchableContext bc) 
    {
        Date ed = Date.today().addDays(90);
        System.debug(Date.today().addDays(90));

        set<Id> setContractIds = new set<Id>();
        set<Id> OwnerIds = new set<Id>();
        //Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :ownerIds]);

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'Subscription Administrator' AND Contract__r.EndDate =: ed])
        {
          setContractIds.add(objContract.Contract__c);
        }
 return Database.getQueryLocator('Select  id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c FROM Contract  WHERE Id IN: setContractIds');
        return Database.getQueryLocator('select id, Name, Email from User where Id IN:OwnerIds');
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) 
    {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        User u = [select Id from User where Profile.Name = 'System Administrator' Limit :1];
        for (Contract c: recs) 
        {
             c.OwnerId = u.Id;   

            if (c.Contact_Email__c!= null) 
            {
                List < String > toAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Notification Before 90 Days of Contract End Date for the Contract Owner');
                String messageBody = '<html><body>Hi ' + c.Contract_Name__c  + ',<br>Your  Contract Expires within 90 Days . <br>Kindly take approriate action.<br><br><b>Regards,</b><br>EDBPSQL</body></html>';
                mail.setHtmlBody(messageBody);
                mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }

    global void finish(Database.BatchableContext bc) {}
}
Schedule Class :
global class scheduleNotificationEmailtoOwner implements Schedulable {
    global void execute(SchedulableContext sc) {
        NotificationEmailtoOwner neo = new  NotificationEmailtoOwner();
        Database.executeBatch(neo);
    }
}


 
Hello All,
I have a requirement where i need to send an email notification to the contract owner 30 days before the contract end date , when the contract role is 'SA/EB?TA' etc.Any suggestion  with an example very much appreciated.
Hi ,
I had a requirement where i need to send an notification email before the 90 days from the contract end day.So we have created a batch class and it worked fine .But now their is a change in the requirement.So how can i achieve this with the combination of workflow ,trigger or batch classes.Any Suggestion very much appreciated.
1)When Contract End Date is exactly 4months days from now, send email notification to Sales Representative giving  a condition .
2)When Contract End Date is exactly 3months days from now, send email notification to Sales Representative  + Supervisior giving a condition .
a)When Customer says Yes ,then an email notification to be sent before the contract days prior to 3mnths/2mnths /1mnth.
b)when customer say no ,then stop sending an email notification.
This all should be sent when a contract role =SA/EB/TA etc.
When i run the test class .The system throws an error  for the TestStatusUpdates method
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MergeLeadTrigger: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: [] Trigger.MergeLeadTrigger: line 430, column 1: []
Trigger :
trigger CampaignMemberSyncStatus on CampaignMember (after update) {
    // Sync response status on Campaign Member to lead or contact

    // Look for status changes
    List<Id> relatedIDs = new List<ID>();
    List<Id> modifiedIDs = new List<ID>();
 
    // Get the list of IDs for campaignmembers whose status changed
    for(CampaignMember cm : Trigger.new) {
        if(cm.Response_Status__c != trigger.oldMap.get(cm.Id).Response_Status__c)
        {
            modifiedIDs.add(cm.Id);
            if(cm.ContactId != null) {
                relatedIDs.add(cm.ContactId);
            } else {
                relatedIDs.add(cm.LeadId);
            }
        }
    }
    if(modifiedIds.size() == 0) return;     /// No modified responses
    
    // Now pull the list of related leads and contacts
    Map<id,Lead> RelatedLeads;
    Map<id,Contact> RelatedContacts;
    RelatedLeads = new Map<ID,Lead>([Select id, Disqaulified_Reason__c, Status from Lead where Id in :relatedIDs]);
    RelatedContacts = new Map<ID,Contact>(
        [Select id, Status__c, Lead_Score__c, Campaign_Score__c, Account.Customer_Status__c, Admin_Nurture_Timeout__c from Contact where Id in :relatedIDs]);
    
    // Build lists of leads or contacts to update
    Map<ID,Lead> ModifiedLeads = new Map<ID,Lead>();
    Map<ID,Contact> ModifiedContacts = new Map<ID,Contact>();
    
    Map<String, CMStatusSettings__c> statusmapping = CMStatusSettings__c.getall();
    
    // Now update the stautus
    for(id cmid : modifiedIDs) {
        CampaignMember cm = trigger.newMap.get(cmid);
        Boolean wasupdated;
        if(cm.ContactId != null) {
            wasupdated = CampaignMemberFunctions.SyncStatus(cm, null, RelatedContacts.get(cm.ContactId), statusmapping);
            if(wasupdated) ModifiedContacts.put(cm.ContactID,RelatedContacts.get(cm.ContactId));
        } else {
            wasupdated = CampaignMemberFunctions.SyncStatus(cm, RelatedLeads.get(cm.LeadId), null, statusmapping);
            if(wasupdated) ModifiedLeads.put(cm.LeadId,RelatedLeads.get(cm.LeadId));
        }
    }
    if(ModifiedLeads.size()>0) update ModifiedLeads.values();
    if(ModifiedContacts.size()>0) update ModifiedContacts.values();
    
    
}
Test Class :
@isTest
public class TestCampaignMemberSync 
{

    static testMethod void TestStatusUpdates() 
    {
    //Test.StartTest();
    
    Account genericaccount = new Account(Name = 'someaccount');
    insert genericaccount;
    
       /* Lead ld1 = new Lead(Company='colead1',LastName='colead1');*/
        Lead ld2 = new Lead(Company='colead2',LastName='colead2');
        Contact ct1 = new Contact(LastName='cocontact1', AccountID = genericaccount.Id);
        Contact ct2 = new Contact(LastName='cocontact2', AccountID = genericaccount.Id);
       /* Campaign cam = new Campaign(Name='campname');
        insert cam;*/
   /* insert ld1;*/
    insert ld2;
    insert ct1;
    insert ct2;
    
     Profile p = [SELECT id ,Name FROM Profile WHERE Name='Custom Partner Community user'];

        User u = new User(
            FirstName = 'test', 
            LastName= 'last_test', 
            Email='test323232@test.com', 
            Phone='111-111-1111', 
            //True_Market_Unit__c='1111', 
            alias = 'test', 
            EmailEncodingKey='UTF-8',
            ProfileId = p.Id,
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US', 
            TimeZoneSidKey='America/Los_Angeles',
            UserName = 'test323232@test.com'
            );
         u.ContactId=ct1.Id;
        insert u;
         Campaign cam = new Campaign(Name='campname');
             insert cam;
       System.runAs(u) {
             test.startTest();
             Lead ld1 = new Lead(Company='colead1',LastName='colead1',country='USA');
             insert ld1;
             /*Campaign cam = new Campaign(Name='campname');
             insert cam;*/
             
    
        CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id, LeadId=ld1.Id, Buyer__c='a', user__c='b');
        CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id, Buyer__c='a', user__c='b');
        CampaignMember mc3 = new CampaignMember(CampaignId = cam.Id, ContactId=ct1.Id, Buyer__c='a', user__c='b');
        CampaignMember mc4 = new CampaignMember(CampaignId = cam.Id, ContactId=ct2.Id, Buyer__c='a', user__c='b');
    List<CampaignMember> cms = new List<CampaignMember>();
    cms.add(mc1);cms.add(mc2);cms.add(mc3);cms.add(mc4);
    
    
        insert cms;
        List<Id> cmids = new List<id>();
    for(CampaignMember thiscm: cms)
    {
      cmids.add(thiscm.id);
    }
    
    ld1.admin_CMSourceId__c = mc1.id;
    update ld1;  // Needed later to simulate the button click on conversion
    ld2.admin_CMSourceId__c = mc2.id;
    update ld2; // Needed later to simulate the button click on conversion
    
    
    
    // Initialize the opp for later creation from CampaignMember
    Opportunity Opp = new Opportunity(CloseDate = Date.Today().addDays(30), AccountId = genericaccount.Id,
        Name='someopp', StageName='Selected' );
        
       // Test.StartTest();
        mc1.Response_Status__c = 'Working';
        mc2.Response_Status__c = 'Disqualified';
        mc2.Disqualified_Reason__c = 'no budget';
        mc3.Response_Status__c = 'Working';
        mc4.Response_Status__c = 'Disqualified';
        mc4.Disqualified_Reason__c = 'no budget';
        mc4.Do_not_reassign_to_Landings__c = true;
        
        update cms;
       Test.StopTest();    
        
        List<CampaignMember> mcres = [Select Id, Response_Status__c, Contact.Admin_Nurture_Timeout__c , Contact.Status__c, Lead.Status, Do_not_reassign_to_Landings__c 
          from CampaignMember where Id = :cmids ];
        for(CampaignMember cm: mcres) {
          System.debug('Response ' + cm.Response_Status__c + ' lead status:' + cm.Lead.Status + ' contact status:' + cm.Contact.Status__c );
          System.debug('Nurture date:' + mcres[3].Contact.Admin_Nurture_Timeout__c);
        }
    //System.assertEquals(mcres[3].Do_not_reassign_to_Landings__c, mcres[3].Contact.Do_not_reassign_to_Landings__c);
 
     }
    }
static testMethod void TestConversionsNoOpp() 
    {
        Test.StartTest();
        Account genericaccount = new Account(Name = 'someaccount');
        insert genericaccount;

            Lead ld1 = new Lead(Company='colead1',LastName='colead1');
            Lead ld2 = new Lead(Company='colead2',LastName='colead2');
            ld2.OwnerId = UserInfo.getUserId();
            Campaign cam = new Campaign(Name='campname');
            insert cam;
            insert ld1;
            insert ld2;
            CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id, LeadId=ld1.Id, Buyer__c='a', user__c='b');
            CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id, Buyer__c='a', user__c='b');
            List<CampaignMember> cms = new List<CampaignMember>();
            cms.add(mc1);
            cms.add(mc2);
        
            insert cms;
            List<Id> cmids = new List<id>();
            /*for(CampaignMember thiscm: cms)
            {
              cmids.add(thiscm.id);
            }*/
        
        ld1.admin_CMSourceId__c = mc1.id;
        update ld1;  // Needed later to simulate the button click on conversion
        ld2.admin_CMSourceId__c = mc2.id;
        update ld2; // Needed later to simulate the button click on conversion
        
        // Initialize the opp for later creation from CampaignMember
        Opportunity Opp = new Opportunity(CloseDate = Date.Today().addDays(30), AccountId = genericaccount.Id,
            Name='someopp', StageName='Selected' );
            
            mc1.Response_Status__c = 'Working';
            mc2.Response_Status__c = 'Disqualified';
            mc2.Disqualified_Reason__c = 'no budget';
             
            
            update cms;
            
            // We're checking CampaignMemberOpportunityInsertTrigger here
            Opp.admin_CMSourceId__c = mc2.Id;  // Set the source ID
            insert Opp;

           // Test.StartTest();

            
            // Now let's do a lead convert
         Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(ld2.Id);
        lc.setConvertedStatus('Converted - Existing Opportunity');
        lc.setDoNotCreateOpportunity(true);
        lc.setOwnerId(UserInfo.getUserId());
        Database.LeadConvertResult lcr2 = Database.convertLead(lc);
            
              Test.StopTest();    
            try
            {
             }
            catch(Exception ex)
            {
              System.Debug('Exception during TestConversionsNoOpp StopTest (async error)' + ex.getMessage());
            }
     
         System.assert(lcr2.isSuccess());
            CampaignMember mc2b = [Select Id,Response_Status__c, Opportunity_Create_Date__c, Opportunity_Name__c, Buyer__c, User__c from CampaignMember where Id = :mc2.id];
        Lead convertedleadinfo = [Select Id, isConverted, Status from Lead where id = :ld2.Id];
        System.Debug('original leadid:' + ld2.Id + ' leadid result id:' + lcr2.getLeadId());
        System.Debug('Converted lead isconverted:' + convertedleadinfo.IsConverted + ' status:' + convertedleadinfo.Status);
           system.assertEquals('Converted - Existing Opportunity', mc2b.Response_Status__c);
    

     }
     }

The other error is for the  TestConversionsNoOpp() as
System.LimitException: Too many SOQL queries: 101
Trigger.MergeLeadTrigger: line 276, column 1
The line #276 is
conrecords=[select id , Rep_Managing_Partner_del__c from Contact where id in: getconid1 and Rep_Managing_Partner_del__c !=null];
Any help very much appreciated.



 
When i run a test class the system throws an error as
if i uncomment the line ,the system throws an error :
System.AssertException: Assertion Failed

System.assert(mc1res.New_to_EnterpriseDB__c);
If comment the above line ,then the method gets passed .
Trigger :
 
public class CampaignMemberFunctions {

    // Sets the CampaignMember New_to_Enterprise_Db field if lead was created in lsat 6 hours
    // Call during CampaignMember before create trigger 
    public static void UpdateNewToEnterpriseDB(CampaignMember cm, Lead ld)
    {
         if(ld.CreatedDate.addHours(6) > DateTime.Now()) cm.New_to_EnterpriseDB__c = true;
    }
    
     
    // Updates the lead or contact status based on sync logic. Returns True if update occurred
    // ld or ct must be valid. If ct is valid, ct.Account.Customer_Status__c must be valid.
    // Note for developers - yes, it's not the most efficient possible code, but is clear, and leaves flexibility
    // for more complex mappings later.
    public static Boolean SyncStatus(CampaignMember cm, Lead ld, Contact ct, Map<String, CMStatusSettings__c> statusmap)
    {
        Boolean result = true;
        String newvalue;
        
        if(ct!= null)
        {
            if(statusmap.containsKey(cm.Response_Status__c))
            {
                newvalue = statusmap.get(cm.Response_Status__c).StatusMapping__c;
                if(newvalue == ct.Status__c)
                {
                    result = false;
                }
                else
                {
                    ct.Status__c = newvalue;
                }
            } else if(cm.Response_Status__c == 'Disqualified' || 
                        cm.Response_Status__c == 'Qualified - New Opportunity' ||
                        cm.Response_Status__c == 'Closed - Converted' )
            {
                newvalue = 'Closed - ' + ct.Account.Customer_Status__c + ' Account';
                if(ct.Status__c == newvalue)
                {
                    result = false;
                }
                else
                {
                    ct.Status__c = newvalue;
                }
                if(cm.Response_Status__c == 'Disqualified')
                {   // Set nuture time on disqualified status
                    Date newtimeout = Date.today().addDays((CMScoreEngine__c.getInstance('Default').NurtureTimeoutDays__c).intValue());
                    if(ct.Admin_Nurture_Timeout__c != newtimeout || ct.Lead_Score__c !=0 || ct.Campaign_Score__c !=0) result = true;
                    ct.Admin_Nurture_Timeout__c = newtimeout;
                    ct.Lead_Score__c = 0; 
                    ct.Campaign_Score__c = 0;   // Probably aren't using this one
                }
            } else
            {
                result = false;
            }       
            /*if(cm.Response_Status__c=='Contacted-Warm' && cm.Do_not_reassign_to_Landings__c) 
            {
                ct.Do_not_reassign_to_Landings__c = true;
                result = true;
            }*/
            
            
        }
        
        else if(ld!=null)
        {
            if(statusmap.containsKey(cm.Response_Status__c))
            {
                newvalue = statusmap.get(cm.Response_Status__c).StatusMapping__c;
                if(newvalue==ld.Status)
                {
                    result = false;
                }
                else
                {
                    ld.Status = newvalue;
                }
            } else if(cm.Response_Status__c == 'Disqualified')
            {
                if(ld.Status=='Disqualified' && ld.Disqaulified_Reason__c == cm.Disqualified_Reason__c)
                {
                    result = false;
                }
                else
                {
                    ld.Status = 'Disqualified';
                    ld.Disqaulified_Reason__c = cm.Disqualified_Reason__c;
                    System.Debug('Disqualified reason being set to: ' + cm.Disqualified_Reason__c);
                }
            } else
            {
                result = false;
            }
            /*if(cm.Response_Status__c=='Contacted-Warm' && cm.Do_not_reassign_to_Landings__c) 
            {
                ld.Do_not_reassign_to_Landings__c = true;
                result = true;
            }*/
        } 
        return(result);
    
    }
    
    // Search through the converted leads, opportunities and campaignmembers to sync if necessary
    public static void SyncAfterConversion(Map<Id,Lead> convertedleads, Map<Id, Opportunity>convertedops, Map<Id, CampaignMember> possiblecms) 
    {
        for(Lead ld: convertedleads.values())
        {
            // Grab the campaign member - this must be correct by original query
             CampaignMember cm = new CampaignMember();
             
             System.debug('@@@@@possiblecms.get(ld.admin_CMSourceId__c)'+possiblecms.get(ld.admin_CMSourceId__c));
             cm = possiblecms.get(ld.admin_CMSourceId__c);
             System.debug('@@@@@cm '+cm );
           if(cm!=null)
           {  
            // We know this lead is converted. Let's get the opportunity.             
            if(ld.ConvertedOpportunityId != null)
            {
                Opportunity opp = convertedops.get(ld.ConvertedOpportunityId);
                opp.PMM_stage__c = cm.PMM_Stage__c;
                opp.Product_Interest__c = cm.Product_Interest__c;
                opp.Buyer__c = cm.Buyer__c;
                opp.New_to_EnterpriseDB__c = cm.New_to_EnterpriseDB__c;
                opp.Problem_to_Solve__c = cm.Problem_to_Solve__c;
                opp.Any_OSS_in_current_stack__c = cm.Any_OSS_in_current_stack__c;
                opp.Total_of_Databases_in_your_Org__c = cm.Total_of_Databases_in_your_Org__c;
                opp.Primary_Database__c = cm.Primary_Database__c;
                opp.of_Postgres_Database_Servers__c = cm.of_Postgres_Database_Servers__c;
                opp.Just_learning_about_EnterpriseDB__c = cm.Just_learning_about_EnterpriseDB__c;
                opp.Project_Requires_a_Net_New_DB__c = cm.Project_Requires_a_Net_New_DB__c;
                opp.Timeframe_To_Production__c = cm.Timeframe_To_Production__c;
                opp.Budget__c = cm.Budget__c;
                opp.User__c = cm.User__c;
                opp.Champion__c = cm.Champion__c;
                opp.Decision_Maker__c = cm.Decision_Maker__c;
                cm.Response_Status__c = 'Qualified - New Opportunity';
                cm.Opportunity_Name__c = opp.Id;
                cm.Opportunity_Create_Date__c = Date.Today();
            }
            
            else
            {                          
                if(cm.lead.status!=null)
                 {
                    cm.Response_Status__c = cm.lead.status;
                 }
            }
            cm.admin_IsConverted__c = true; 
          }           
        }   
    
    }
    
    public static void EmailErrorMessage(String message)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {'edbnotify@bearcavern.com', 'roanbear@gmail.com'});
        mail.setSenderDisplayName('APEX notifier');
        mail.setSubject('SFDC/Eloqua Data Creation Error');
        mail.setPlainTextBody(message);
        List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        for(Messaging.SendEmailResult r: results)
        {
            System.debug('Result of Email sent ' + r.isSuccess());
            if(!r.isSuccess())
            {
                for(Messaging.SendEmailError sme: r.getErrors())
                {
                    for(String s: sme.getFields())  System.Debug('Error for field ' + s );      
                    System.Debug('Error message ' + sme.getMessage());
                    System.Debug('StatusCode ' + sme.getStatusCode());
                }
            }
        }
        
    }

}
Part of Test Class Written :
@isTest
Public class TestCampaignMemberFunctions {

   //Checking for if Condition value Response_Status__c= Disqualified 
    Public static testMethod void TestCreationDate() {
      
       Test.StartTest();
        
        Lead ld2 = [select ID, CreatedDate, IsConverted from LEAD where CreatedDate < :DateTime.Now().addHours(-7) and IsConverted=False  LIMIT 1];
        Campaign cam = new Campaign(Name='campname');      
        insert cam;       
        Account a = new Account();
        a.Name ='My Company';
        Insert a;                   
        
        Lead ld = new Lead();
        ld.Company='colead1';  
        ld.LastName ='colead1_'+String.valueOf(System.now());
        ld.status= 'Disqualified';        
        ld.admin_CMSourceId__c= cam.Id;
        ld.Disqaulified_Reason__c='Disqualified';              
        insert ld;
        
        Contact con = new Contact(LastName ='Test');        
        Insert con;               
       // Test.StartTest();
        CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id,Product_Interest__c='Services',Response_Status__c='Disqualified',status= 'Disqualified',PMM_Stage__c='Learns of Postgres', LeadId=ld.Id);
        CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id);
        insert mc1;
        insert mc2; 
        Opportunity opp =new Opportunity();
        opp.Product_Interest__c='Services';
       
        opp.PMM_stage__c ='Deployment';
        opp.Buyer__c = 'xyz';
        opp.New_to_EnterpriseDB__c =True;
        opp.Problem_to_Solve__c ='Performance' ;
        opp.Any_OSS_in_current_stack__c ='OS' ;
        opp.Total_of_Databases_in_your_Org__c ='500';
        opp.Primary_Database__c =mc1.Primary_Database__c;
        opp.of_Postgres_Database_Servers__c = mc1.of_Postgres_Database_Servers__c;
        opp.Just_learning_about_EnterpriseDB__c = mc1.Just_learning_about_EnterpriseDB__c;
        opp.Project_Requires_a_Net_New_DB__c = mc1.Project_Requires_a_Net_New_DB__c;
        opp.Timeframe_To_Production__c = mc1.Timeframe_To_Production__c;
        opp.Budget__c = mc1.Budget__c;
        opp.User__c = mc1.User__c;
        opp.Champion__c = mc1.Champion__c;
        opp.Decision_Maker__c =mc1.Decision_Maker__c;
                
        opp.Name='Testing';
        opp.StageName='Closed Lost';
        opp.CloseDate=System.today(); 
        Insert opp;       
        CampaignMember mc1res = [Select Id, New_to_EnterpriseDB__c,Response_Status__c from CampaignMember where Id = :mc1.id ];
        CampaignMember mc2res = [Select Id, New_to_EnterpriseDB__c from CampaignMember where Id = :mc2.id ];        
        System.assert(mc1res.New_to_EnterpriseDB__c);
        System.assert(! mc2res.New_to_EnterpriseDB__c);
        
        Map<String, CMStatusSettings__c> statusmap = new Map<String, CMStatusSettings__c>();
       // statusmap.put(mc1res.Response_Status__c, custSetting);
                  
        Map<Id,Lead> convertedleads = new Map<Id,Lead>();                   
        convertedleads.put(ld.Id,ld);
        
        Map<Id, Opportunity> convertedops= new Map<Id, Opportunity>();        
        convertedops.put(opp.Id,opp);
          
        Map<Id, CampaignMember> possiblecms= new Map<Id, CampaignMember>();        
        possiblecms.put(mc1.Id,mc1);                                 
        CampaignMemberFunctions  cmf = new CampaignMemberFunctions();
        CampaignMemberFunctions.SyncStatus( mc1res,ld,con,statusmap);
        System.debug('@@@@@convertedleads'+convertedleads);
        System.debug('@@@@@possiblecms'+possiblecms);
        System.debug('@@@@@convertedops'+convertedops);
                
        CampaignMemberFunctions.SyncAfterConversion(convertedleads,convertedops,possiblecms);
        CampaignMemberFunctions.EmailErrorMessage('testmessage');     
        Test.StopTest();    
        }
}
Any help very much appreciated.


 
Can any one help me out with this error:
System.LimitException: Too many SOQL queries: 101
I'm running a test class for a trigger  and the test class methods gets failed and the system throws an error for the other triggers 
System.LimitException: Too many SOQL queries: 101
Trigger.MergeLeadTrigger: line 276, column 1

The error line is :
conrecords=[select id , Rep_Managing_Partner_del__c from Contact where id in: getconid1 and Rep_Managing_Partner_del__c !=null];
        

System.LimitException: Too many SOQL queries: 101
Trigger.Accountduplicate: line 6, column 1
The error line is :
  lstusr  =[SELECT Id,Name,Profile.Name FROM User WHERE Id=:UserInfo.getuserId()];
Trigger which i run :
trigger CampaignMemberSyncStatus on CampaignMember (after update) {
    // Sync response status on Campaign Member to lead or contact

    // Look for status changes
    List<Id> relatedIDs = new List<ID>();
    List<Id> modifiedIDs = new List<ID>();
 
    // Get the list of IDs for campaignmembers whose status changed
    for(CampaignMember cm : Trigger.new) {
        if(cm.Response_Status__c != trigger.oldMap.get(cm.Id).Response_Status__c)
        {
            modifiedIDs.add(cm.Id);
            if(cm.ContactId != null) {
                relatedIDs.add(cm.ContactId);
            } else {
                relatedIDs.add(cm.LeadId);
            }
        }
    }
    if(modifiedIds.size() == 0) return;     /// No modified responses
    
    // Now pull the list of related leads and contacts
    Map<id,Lead> RelatedLeads;
    Map<id,Contact> RelatedContacts;
    RelatedLeads = new Map<ID,Lead>([Select id, Disqaulified_Reason__c, Status from Lead where Id in :relatedIDs]);
    RelatedContacts = new Map<ID,Contact>(
        [Select id, Status__c, Lead_Score__c, Campaign_Score__c, Account.Customer_Status__c, Admin_Nurture_Timeout__c from Contact where Id in :relatedIDs]);
    
    // Build lists of leads or contacts to update
    Map<ID,Lead> ModifiedLeads = new Map<ID,Lead>();
    Map<ID,Contact> ModifiedContacts = new Map<ID,Contact>();
    
    Map<String, CMStatusSettings__c> statusmapping = CMStatusSettings__c.getall();
    
    // Now update the stautus
    for(id cmid : modifiedIDs) {
        CampaignMember cm = trigger.newMap.get(cmid);
        Boolean wasupdated;
        if(cm.ContactId != null) {
            wasupdated = CampaignMemberFunctions.SyncStatus(cm, null, RelatedContacts.get(cm.ContactId), statusmapping);
            if(wasupdated) ModifiedContacts.put(cm.ContactID,RelatedContacts.get(cm.ContactId));
        } else {
            wasupdated = CampaignMemberFunctions.SyncStatus(cm, RelatedLeads.get(cm.LeadId), null, statusmapping);
            if(wasupdated) ModifiedLeads.put(cm.LeadId,RelatedLeads.get(cm.LeadId));
        }
    }
    if(ModifiedLeads.size()>0) update ModifiedLeads.values();
    if(ModifiedContacts.size()>0) update ModifiedContacts.values();
    }
Test Class :
@isTest
public class TestCampaignMemberSync 
{

    static testMethod void TestStatusUpdates() 
    {
    Account genericaccount = new Account(Name = 'someaccount');
    insert genericaccount;

        Lead ld1 = new Lead(Company='colead1',LastName='colead1');
        Lead ld2 = new Lead(Company='colead2',LastName='colead2');
        Contact ct1 = new Contact(LastName='cocontact1', AccountID = genericaccount.Id);
        Contact ct2 = new Contact(LastName='cocontact2', AccountID = genericaccount.Id);
        Campaign cam = new Campaign(Name='campname');
        insert cam;
    insert ld1;
    insert ld2;
    insert ct1;
    insert ct2;
        CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id, LeadId=ld1.Id, Buyer__c='a', user__c='b');
        CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id, Buyer__c='a', user__c='b');
        CampaignMember mc3 = new CampaignMember(CampaignId = cam.Id, ContactId=ct1.Id, Buyer__c='a', user__c='b');
        CampaignMember mc4 = new CampaignMember(CampaignId = cam.Id, ContactId=ct2.Id, Buyer__c='a', user__c='b');
    List<CampaignMember> cms = new List<CampaignMember>();
    cms.add(mc1);cms.add(mc2);cms.add(mc3);cms.add(mc4);
    
    
        insert cms;
        List<Id> cmids = new List<id>();
    for(CampaignMember thiscm: cms)
    {
      cmids.add(thiscm.id);
    }
    
    ld1.admin_CMSourceId__c = mc1.id;
    update ld1;  // Needed later to simulate the button click on conversion
    ld2.admin_CMSourceId__c = mc2.id;
    update ld2; // Needed later to simulate the button click on conversion
    
    // Initialize the opp for later creation from CampaignMember
    Opportunity Opp = new Opportunity(CloseDate = Date.Today().addDays(30), AccountId = genericaccount.Id,
        Name='someopp', StageName='Selected' );
        
        Test.StartTest();
        mc1.Response_Status__c = 'Working';
        mc2.Response_Status__c = 'Disqualified';
        mc2.Disqualified_Reason__c = 'no budget';
        mc3.Response_Status__c = 'Working';
        mc4.Response_Status__c = 'Disqualified';
        mc4.Disqualified_Reason__c = 'no budget';
        mc4.Do_not_reassign_to_Landings__c = true;
        
        update cms;
       Test.StopTest();    
        
        List<CampaignMember> mcres = [Select Id, Response_Status__c, Contact.Admin_Nurture_Timeout__c , Contact.Status__c, Lead.Status, Do_not_reassign_to_Landings__c 
          from CampaignMember where Id = :cmids ];
        for(CampaignMember cm: mcres) {
          System.debug('Response ' + cm.Response_Status__c + ' lead status:' + cm.Lead.Status + ' contact status:' + cm.Contact.Status__c );
          System.debug('Nurture date:' + mcres[3].Contact.Admin_Nurture_Timeout__c);
        }
    //System.assertEquals(mcres[3].Do_not_reassign_to_Landings__c, mcres[3].Contact.Do_not_reassign_to_Landings__c);
 
     }
   static testMethod void TestConversionsNoOpp() 
    {
        Account genericaccount = new Account(Name = 'someaccount');
        insert genericaccount;

            Lead ld1 = new Lead(Company='colead1',LastName='colead1');
            Lead ld2 = new Lead(Company='colead2',LastName='colead2');
            ld2.OwnerId = UserInfo.getUserId();
            Campaign cam = new Campaign(Name='campname');
            insert cam;
            insert ld1;
            insert ld2;
            CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id, LeadId=ld1.Id, Buyer__c='a', user__c='b');
            CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id, Buyer__c='a', user__c='b');
            List<CampaignMember> cms = new List<CampaignMember>();
            cms.add(mc1);
            cms.add(mc2);
        
            insert cms;
            List<Id> cmids = new List<id>();
            /*for(CampaignMember thiscm: cms)
            {
              cmids.add(thiscm.id);
            }*/
        
        ld1.admin_CMSourceId__c = mc1.id;
        update ld1;  // Needed later to simulate the button click on conversion
        ld2.admin_CMSourceId__c = mc2.id;
        update ld2; // Needed later to simulate the button click on conversion
        
        // Initialize the opp for later creation from CampaignMember
        Opportunity Opp = new Opportunity(CloseDate = Date.Today().addDays(30), AccountId = genericaccount.Id,
            Name='someopp', StageName='Selected' );
            
            mc1.Response_Status__c = 'Working';
            mc2.Response_Status__c = 'Disqualified';
            mc2.Disqualified_Reason__c = 'no budget';
             
            
            update cms;
            
            // We're checking CampaignMemberOpportunityInsertTrigger here
            Opp.admin_CMSourceId__c = mc2.Id;  // Set the source ID
            insert Opp;

            Test.StartTest();

            
            // Now let's do a lead convert
         Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(ld2.Id);
        lc.setConvertedStatus('Converted - Existing Opportunity');
        lc.setDoNotCreateOpportunity(true);
        lc.setOwnerId(UserInfo.getUserId());
        Database.LeadConvertResult lcr2 = Database.convertLead(lc);
            
              Test.StopTest();    
            try
            {
             }
            catch(Exception ex)
            {
              System.Debug('Exception during TestConversionsNoOpp StopTest (async error)' + ex.getMessage());
            }
     
         System.assert(lcr2.isSuccess());
            CampaignMember mc2b = [Select Id,Response_Status__c, Opportunity_Create_Date__c, Opportunity_Name__c, Buyer__c, User__c from CampaignMember where Id = :mc2.id];
        Lead convertedleadinfo = [Select Id, isConverted, Status from Lead where id = :ld2.Id];
        System.Debug('original leadid:' + ld2.Id + ' leadid result id:' + lcr2.getLeadId());
        System.Debug('Converted lead isconverted:' + convertedleadinfo.IsConverted + ' status:' + convertedleadinfo.Status);
           system.assertEquals('Converted - Existing Opportunity', mc2b.Response_Status__c);
     }
 }
Any help very much appreciated.



 
Can any one help me out with this error .When i compile all the classes , the system throws an error as :
Compilation Errors found:
DeleteDownloadHitOlderAYearSchedular: line 4, column 67: Constructor not defined: [DeleteDownloadHitCountBatch].<Constructor>(String)
Schedular Class is :
global class DeleteDownloadHitOlderAYearSchedular Implements Schedulable
{    
    global void execute(SchedulableContext sc) {
        DeleteDownloadHitCountBatch deleteDownloadHitCountBatch = new DeleteDownloadHitCountBatch('SELECT Id,Name FROM Download_Hit_Count__c WHERE CreatedDate < LAST_n_DAYS:365');
        Database.executeBatch(deleteDownloadHitCountBatch,100);           
    }
    
    
}
Batch Class :
global class DeleteDownloadHitCountBatch implements Database.Batchable<sObject>,Schedulable {
    
    global String query;
    
   /* global DeleteDownloadHitCountBatch(String q) {
        query = q;
    }*/
    
    global DeleteDownloadHitCountBatch() {
        query = 'SELECT Id,Name FROM Download_Hit_Count__c WHERE CreatedDate < LAST_n_DAYS:365';
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        delete scope;
        //Database.emptyRecycleBin(scope);
    }
    
    global void finish(Database.BatchableContext BC){
    }
    
    //execute methode for scheduler
    global void execute(SchedulableContext sc) {
        DeleteDownloadHitCountBatch delDownloadHitCount = new DeleteDownloadHitCountBatch();
        Database.executeBatch(delDownloadHitCount ,200);           
    }
}
Any help very much appreciated.


 
When I run the test class for the one trigger ,the system throws an as :
System.LimitException: Too many SOQL queries: 101

Trigger.MergeLeadTrigger: line 276, column 1

Trigger.Accountduplicate: line 6, column 1

The Trigger which im running :
trigger CampaignMemberSyncStatus on CampaignMember (after update) {
    // Sync response status on Campaign Member to lead or contact

    // Look for status changes
    List<Id> relatedIDs = new List<ID>();
    List<Id> modifiedIDs = new List<ID>();
 
    // Get the list of IDs for campaignmembers whose status changed
    for(CampaignMember cm : Trigger.new) {
        if(cm.Response_Status__c != trigger.oldMap.get(cm.Id).Response_Status__c)
        {
            modifiedIDs.add(cm.Id);
            if(cm.ContactId != null) {
                relatedIDs.add(cm.ContactId);
            } else {
                relatedIDs.add(cm.LeadId);
            }
        }
    }
    if(modifiedIds.size() == 0) return;     /// No modified responses
    
    // Now pull the list of related leads and contacts
    Map<id,Lead> RelatedLeads;
    Map<id,Contact> RelatedContacts;
    RelatedLeads = new Map<ID,Lead>([Select id, Disqaulified_Reason__c, Status from Lead where Id in :relatedIDs]);
    RelatedContacts = new Map<ID,Contact>(
        [Select id, Status__c, Lead_Score__c, Campaign_Score__c, Account.Customer_Status__c, Admin_Nurture_Timeout__c from Contact where Id in :relatedIDs]);
    
    // Build lists of leads or contacts to update
    Map<ID,Lead> ModifiedLeads = new Map<ID,Lead>();
    Map<ID,Contact> ModifiedContacts = new Map<ID,Contact>();
    
    Map<String, CMStatusSettings__c> statusmapping = CMStatusSettings__c.getall();
    
    // Now update the stautus
    for(id cmid : modifiedIDs) {
        CampaignMember cm = trigger.newMap.get(cmid);
        Boolean wasupdated;
        if(cm.ContactId != null) {
            wasupdated = CampaignMemberFunctions.SyncStatus(cm, null, RelatedContacts.get(cm.ContactId), statusmapping);
            if(wasupdated) ModifiedContacts.put(cm.ContactID,RelatedContacts.get(cm.ContactId));
        } else {
            wasupdated = CampaignMemberFunctions.SyncStatus(cm, RelatedLeads.get(cm.LeadId), null, statusmapping);
            if(wasupdated) ModifiedLeads.put(cm.LeadId,RelatedLeads.get(cm.LeadId));
        }
    }
    if(ModifiedLeads.size()>0) update ModifiedLeads.values();
    if(ModifiedContacts.size()>0) update ModifiedContacts.values();
    
    
}
Test Class :
@isTest
public class TestCampaignMemberSync 
{

    static testMethod void TestStatusUpdates() 
    {
    Account genericaccount = new Account(Name = 'someaccount');
    insert genericaccount;

        Lead ld1 = new Lead(Company='colead1',LastName='colead1');
        Lead ld2 = new Lead(Company='colead2',LastName='colead2');
        Contact ct1 = new Contact(LastName='cocontact1', AccountID = genericaccount.Id);
        Contact ct2 = new Contact(LastName='cocontact2', AccountID = genericaccount.Id);
        Campaign cam = new Campaign(Name='campname');
        insert cam;
    insert ld1;
    insert ld2;
    insert ct1;
    insert ct2;
        CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id, LeadId=ld1.Id, Buyer__c='a', user__c='b');
        CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id, Buyer__c='a', user__c='b');
        CampaignMember mc3 = new CampaignMember(CampaignId = cam.Id, ContactId=ct1.Id, Buyer__c='a', user__c='b');
        CampaignMember mc4 = new CampaignMember(CampaignId = cam.Id, ContactId=ct2.Id, Buyer__c='a', user__c='b');
    List<CampaignMember> cms = new List<CampaignMember>();
    cms.add(mc1);cms.add(mc2);cms.add(mc3);cms.add(mc4);
    
    
        insert cms;
        List<Id> cmids = new List<id>();
    for(CampaignMember thiscm: cms)
    {
      cmids.add(thiscm.id);
    }
    
    ld1.admin_CMSourceId__c = mc1.id;
    update ld1;  // Needed later to simulate the button click on conversion
    ld2.admin_CMSourceId__c = mc2.id;
    update ld2; // Needed later to simulate the button click on conversion
    
    // Initialize the opp for later creation from CampaignMember
    Opportunity Opp = new Opportunity(CloseDate = Date.Today().addDays(30), AccountId = genericaccount.Id,
        Name='someopp', StageName='Selected' );
        
        Test.StartTest();
        mc1.Response_Status__c = 'Working';
        mc2.Response_Status__c = 'Disqualified';
        mc2.Disqualified_Reason__c = 'no budget';
        mc3.Response_Status__c = 'Working';
        mc4.Response_Status__c = 'Disqualified';
        mc4.Disqualified_Reason__c = 'no budget';
        mc4.Do_not_reassign_to_Landings__c = true;
        
        update cms;
       Test.StopTest();    
        
        List<CampaignMember> mcres = [Select Id, Response_Status__c, Contact.Admin_Nurture_Timeout__c , Contact.Status__c, Lead.Status, Do_not_reassign_to_Landings__c 
          from CampaignMember where Id = :cmids ];
        for(CampaignMember cm: mcres) {
          System.debug('Response ' + cm.Response_Status__c + ' lead status:' + cm.Lead.Status + ' contact status:' + cm.Contact.Status__c );
          System.debug('Nurture date:' + mcres[3].Contact.Admin_Nurture_Timeout__c);
        }
    //System.assertEquals(mcres[3].Do_not_reassign_to_Landings__c, mcres[3].Contact.Do_not_reassign_to_Landings__c);
 
     }
     
     
    static testMethod void TestConversionsNoOpp() 
    {
        Account genericaccount = new Account(Name = 'someaccount');
        insert genericaccount;

            Lead ld1 = new Lead(Company='colead1',LastName='colead1');
            Lead ld2 = new Lead(Company='colead2',LastName='colead2');
            ld2.OwnerId = UserInfo.getUserId();
            Campaign cam = new Campaign(Name='campname');
            insert cam;
            insert ld1;
            insert ld2;
            CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id, LeadId=ld1.Id, Buyer__c='a', user__c='b');
            CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id, Buyer__c='a', user__c='b');
            List<CampaignMember> cms = new List<CampaignMember>();
            cms.add(mc1);
            cms.add(mc2);
        
            insert cms;
            List<Id> cmids = new List<id>();
       
        
        ld1.admin_CMSourceId__c = mc1.id;
        update ld1;  // Needed later to simulate the button click on conversion
        ld2.admin_CMSourceId__c = mc2.id;
        update ld2; // Needed later to simulate the button click on conversion
        
        // Initialize the opp for later creation from CampaignMember
        Opportunity Opp = new Opportunity(CloseDate = Date.Today().addDays(30), AccountId = genericaccount.Id,
            Name='someopp', StageName='Selected' );
            
            mc1.Response_Status__c = 'Working';
            mc2.Response_Status__c = 'Disqualified';
            mc2.Disqualified_Reason__c = 'no budget';
             
            
            update cms;
            
            // We're checking CampaignMemberOpportunityInsertTrigger here
            Opp.admin_CMSourceId__c = mc2.Id;  // Set the source ID
            insert Opp;

            Test.StartTest();

            
            // Now let's do a lead convert
         Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(ld2.Id);
        lc.setConvertedStatus('Converted - Existing Opportunity');
        lc.setDoNotCreateOpportunity(true);
        lc.setOwnerId(UserInfo.getUserId());
        Database.LeadConvertResult lcr2 = Database.convertLead(lc);
            
              Test.StopTest();    
            try
            {
             }
            catch(Exception ex)
            {
              System.Debug('Exception during TestConversionsNoOpp StopTest (async error)' + ex.getMessage());
            }
     
         System.assert(lcr2.isSuccess());
            CampaignMember mc2b = [Select Id,Response_Status__c, Opportunity_Create_Date__c, Opportunity_Name__c, Buyer__c, User__c from CampaignMember where Id = :mc2.id];
        Lead convertedleadinfo = [Select Id, isConverted, Status from Lead where id = :ld2.Id];
        System.Debug('original leadid:' + ld2.Id + ' leadid result id:' + lcr2.getLeadId());
        System.Debug('Converted lead isconverted:' + convertedleadinfo.IsConverted + ' status:' + convertedleadinfo.Status);
           system.assertEquals('Converted - Existing Opportunity', mc2b.Response_Status__c);
     }
 }
The Error Lines Of other Triggers are
Error line  for MergeLead Trigger :

conrecords=[select id , Rep_Managing_Partner_del__c from Contact where id in: getconid1 and Rep_Managing_Partner_del__c !=null];

Error line  for AccountDuplicateTrigger :

  lstusr  =[SELECT Id,Name,Profile.Name FROM User WHERE Id=:UserInfo.getuserId()];
Any help very much appreciated.



 
Can any one help me out . How to send an email to Account Owner from contract object in Batch Class.Im using templateid ,in target object im giving the contact id ,in whatid im sending the Account owner email ,but the Account owner is not getting any email.What im doing is correct .Any help very much appreciated.
Portion of the Code :
global void execute(Database.BatchableContext bc, List < Contract >
     recs) {
            List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
             for (Contract c: recs) {
                if (c.Contact_Email__c != null) {
                    List < String > toAddresses = new List < String > ();
                     List < String > CcAddresses = new List < String > ();
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    //toAddresses.add(c.Contact_Email__c);
                     ccAddresses.add(c.Account.Owner.Email);
                    //toAddresses.add(c.Account.Owner.Manager.Email);
                    // mail.setToAddresses(toAddresses);
                     mail.setCcAddresses(CcAddresses);
            mail.setTargetObjectId('c.contact__r.Id)');
                     mail.setWhatId(c.Account.Owner.Manager.Email));
                     mail.setTemplateId('00X4B000000M3go');
                     mail.setSaveAsActivity(false);
                mailList.add(mail);
                 }
            }
             Messaging.sendEmail(mailList);
         }

 
Can any one help me out with this error .
1)When im using mail.setTargetObjectId(c.CustomerSignedId); the system start throwing a error .
SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing targetObjectId with template:
2)When im using mail.setTargetObjectId('00538000004bjrA'); the system start throwing a error .
SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.: [whatId, 8004B000000Qmzi]
3)When i use mail.setTargetObjectId(c.OwnerId); ,
i get the email but the merge fields value are not getting displayed
Here is the Code which im using the Batch Class :
global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
                ccAddresses.add(c.Account.Owner.Email);
               // toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setCcAddresses(CcAddresses);
                mail.setTargetObjectId(c.CustomerSignedId);
                //mail.setTargetObjectId('00538000004bjrA');
                mail.setWhatId(c.Id);
                mail.setTemplateId('00X4B000000M3go');
                mail.setSaveAsActivity(false);
           mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }
Any Suggestion very much appreciated.
 
Hello ,
Based on the requirement i have created few html email templates with the merge fields .When i use the templateid in the batch class and execute the batch class,the email which i get doesnot display the merge fields value .What may be issue .Any help very much appreciated.
Here is the code used to send an email notification for the 30 days .
Batch Class and Schedule Class :
global class ThirtyDaysNotificationEmail implements Database.Batchable < sObject >, Schedulable, Database.Stateful {
    global List<String> errorMessages = new List<String>();
    global Database.QueryLocator start(Database.BatchableContext bc) {
        
        Date ed = Date.today().addDays(30);
        System.debug(Date.today().addDays(30));
        
        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'SA' AND Contract__r.EndDate =: ed]) {
            setContractIds.add(objContract.Contract__c);
        }
        
         return Database.getQueryLocator([Select  id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c,  Account.Owner.Email ,Account.Owner.Manager.Email,Owner.Email,CustomerSignedId,OwnerId FROM Contract  WHERE Id IN: setContractIds AND SRR__c ='YES' AND Status__c IN('In Pipe','Pushed Forward ') AND Renewal_Status__c NOT IN ('Renewed','Renewed Lost')]);
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
                ccAddresses.add(c.Account.Owner.Email);
               // toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setCcAddresses(CcAddresses);
               // mail.setTargetObjectId(c.CustomerSignedId);
                mail.setTargetObjectId(c.OwnerId);
               // mail.setWhatId(c.Id);
                mail.setTemplateId('00X4B000000M3g7');
                mail.setSaveAsActivity(false);
               // mail.setSubject('Notification Before 100 Days of Contract End Date to Account Executive and Manager');
               // String messageBody = '<html><body>Hi ,The Contract Named ' + c.Contract_Name__c  + ',<br>Will get Expired within 100 Days . <br>Kindly take approriate action to inform the Customer.<br><br><b>Regards,</b><br>ADP</body></html>';
               // mail.setHtmlBody(messageBody);
                mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }

    global void finish(Database.BatchableContext bc) {
        AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce Thirty Days NotificationEmailtoCustomer Finished: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
    global void execute(SchedulableContext SC) {
        NotificationEmailtoAccountExecutive batchable = new NotificationEmailtoAccountExecutive();
        database.executebatch(batchable);
    }
}
HTML Email template Created :
User-added image

The output which i get without the merge fields is :
User-added image
Any help very much appreciated.
Hello ,
I had a requirement where i need to send an email notification 100 days before the contract end date based on the condition.So i have created the workflow rule with the condition and time based workflow ,email alert.Which worked fine.
Now once the 100 days email is sent to the opportunity owner,then their is a field on contract object "SRR" (picklist field - as yes/no).Now the opportunity owner will update the field "SRR" value .
1)If the owners updates the field "SRR" value as "Yes" then an email needs to send to the customer for 45 /30 /15 days before the contract end date.
2)If the owners updates the field "SRR" value as "No" then stop sending  email needs to  the customer .
3)If the owners does not updates the field "SRR" value  within 90 days before the contract end date,then an email needs to be sent to the owner  and superior.
How can i get this filter in WFR .Any help or example very much appreciated.
Hello ,
I have a requirement ,where the system should automatically  calculate 100 days before the contract end date and send an alert to the customer.How can we formulate the formulae ,
 
1)Date dt = Today()+100 and then assign it to contract end date =:dt in a query
2) Date ed = Date.today().addDays(100);
3)contract end date >=Today+100days
4)Date=(today+100 - contractend date)
or how can we calculate..Im in dilemma  which one should work to calculate.Any thoughts or ideas or example very much appreciated.
Can any one help me on this or give Suggestion .I have a requirement where i need to send an email notification to the owner before the contract end date.Their few conditions to be satisfied and then the email notification is sent.
1)I need to send an email notification to the opportunity owner,keeping in cc to the contract owner 4months before the contract end date.
Their are few conditions which needs to get satisfied ,
Condition is when the 
a)"Status Renewal" is equal to pipeline ,next renewal status And 
b)when the "Status Renewed next year" is not equal to renewed ,renewed lost.
Here "Status Renewal" and "Status Renewed next year" are picklist field.
Once the condition is satisfied , then the email notification is sent to the opportunity owner ,keeping in cc to the contract owner.
Now  if we get the response from the customer for the renewal ,then an update is done .
We have a picklist field as ''send renewal reminder" with yes or no values.Now here , the update is done by the owner of the record.Their few more condition now.
Condition 1:

If the "Send renewal reminder" is "YES" then an email notification mail is to be sent to the customer for 45,30 and 15 days .
If this  condition is satisfied .i.e If the a)"Status Renewal" is equal to pipeline ,next renewal status And
b)when the "Status Renewed next year" is not equal to renewed ,renewed lost And
c)"Send renewal reminder" is "YES".

Condition 2:

If the "Send renewal reminder" is "No" ,then stop sending the email notification .
Condition 3 :

If the "Send renewal reminder" is not updated ,then an email notification needs to be sent to the opportunity owner and the superior for 3months.

Any Suggestion or ideas very much appreciated.

 
Hello,
I have a written a Batch Class to send an notification email 60 days before the contract end date.I have created the email template and used in the code.But the system throws an error as :
Batch Class Error as System.StringException: Invalid id at line #29 
mail.setTargetObjectId(c.Owner.Email);
global class SixtyDaysNotificationEmail implements Database.Batchable < sObject >, Schedulable, Database.Stateful {
    global List<String> errorMessages = new List<String>();
    global Database.QueryLocator start(Database.BatchableContext bc) {
        
        Date ed = Date.today().addDays(60);
        System.debug(Date.today().addDays(60));
        
        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'Subscription Administrator' AND Contract__r.EndDate =: ed]) {
            setContractIds.add(objContract.Contract__c);
        }
        
        return Database.getQueryLocator('Select  id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c,  Account.Owner.Email ,Account.Owner.Manager.Email,Owner.Email FROM Contract  WHERE Id IN: setContractIds');
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
                ccAddresses.add(c.Account.Owner.Email);
               // toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setCcAddresses(CcAddresses);
                mail.setTargetObjectId(c.Owner.Email);
                mail.setTemplateId('00X4B000000M3zx');
                mail.setSaveAsActivity(false);
               // mail.setSubject('Notification Before 100 Days of Contract End Date to Account Executive and Manager');
               // String messageBody = '<html><body>Hi ,The Contract Named ' + c.Contract_Name__c  + ',<br>Will get Expired within 60 Days . <br>Kindly take approriate action to inform the Customer.<br><br><b>Regards,</b><br>CAB</body></html>';
               // mail.setHtmlBody(messageBody);
                mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }

    global void finish(Database.BatchableContext bc) {
        AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce NotificationEmailtoAccountExecutive Finished: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
    global void execute(SchedulableContext SC) {
        NotificationEmailtoAccountExecutive batchable = new NotificationEmailtoAccountExecutive();
        database.executebatch(batchable);
    }
}
The targetobjectid should be for the contact.But when i use mail.setTargetObjectId(c.Contact_Email__c); the system throws the same error .
Any help very much appreciated.
 
 
Hello ,
The System throws an Error as :
Compile Error: expecting a right parentheses, found ',' at line 22 column 298
When i use this query
 
Database.getQueryLocator([Select id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c, Owner.Email, Owner.Manager.Email ,Account.Owner.Email,Account.Owner.Manager.Email  FROM Contract  WHERE Id IN: setContractIds AND Renewal_Status__c IN :('Pushed Forward To Next Quarter','In Pipe') AND Next_Quarter_Renewal_Status__c IN :('Renewed','Renewal lost’)]);
Any help very much appreciated.




 
Hello All,
I had a requirement where i need to send an email notification 100 days before the contract end date.So based on this we had a batch and schedule class written.Now we would like to add few more condition in the code.
We have two picklist value as 'Status Renewed' and "Status Renewed next Year".This picklist field has some values  as Status renewed for nxt quarter , pipeline etc the other picklist has renewed and renewed lost.
Condition is when the "Status Renewed" is equal to "Status renewed for next quarter " or "Pipeline" AND when "Status Renewed next Year" is not equal to "Renewed" or"Renewed lost".
So how do i give this condition in an execute method.When this condition is satisfied ,then the email notification should be sent to the owner before 100 days.

Batch and Schedule Class:
global class NotificationEmailtoAccountExecutive implements Database.Batchable < sObject >, Schedulable, Database.Stateful {
	global List<String> errorMessages = new List<String>();
    global Database.QueryLocator start(Database.BatchableContext bc) {
     
        Date ed = Date.today().addDays(100);
        System.debug(Date.today().addDays(100));
        
        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'Subscription Administrator' AND Contract__r.EndDate =: ed]) {
			setContractIds.add(objContract.Contract__c);
        }
        
        return Database.getQueryLocator('Select  id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c, Owner.Email, Owner.Manager.Email ,Account.Owner.Email,Account.Owner.Manager.Email  FROM Contract  WHERE Id IN: setContractIds');
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
	        toAddresses.add(c.Owner.Email);
                toAddresses.add(c.Account.Owner.Email);
                toAddresses.add(c.Owner.Manager.Email);
                toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Notification Before 100 Days of Contract End Date');
                String messageBody = '<html><body>Hi ' + c.Contract_Name__c  + ',<br>Your  Contract Expires within 100 Days . <br>Kindly take  action.<br><br><b>Regards,</b><br>ADP</body></html>';
                mail.setHtmlBody(messageBody);
                mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }

    global void finish(Database.BatchableContext bc) {
		AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce NotificationEmailtoAccountExecutive Finished: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
	}
	
	global void execute(SchedulableContext SC) {
        NotificationEmailtoAccountExecutive batchable = new NotificationEmailtoAccountExecutive();
		database.executebatch(batchable);
    }
}
Any help very much appreciated.

 
Hello All,
I have a requirement where i need to send an email notification to the contract owner 30 days before the contract end date , when the contract role is 'SA/EB?TA' etc.Any suggestion  with an example very much appreciated.