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

How to add conditions in a Batch class when their are n no of clause

I  would like to add few condition in the query,how to add them.Any Suggestion please.

1) Add more roles (such as EB ,TA ,RA etc where role is a picklist field) in this query .
SELECT Contract__c FROM Contract_role__c WHERE Role__c = 'SA'
2)In getquerylocator , add few condition such as
When "Renewed" is Checked AND 
When "SRR" is YES AND 
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"
i have the query as
return Database.getQueryLocator('Select id, Contract_Name__c , EndDate ,ownerId FROM Contract WHERE Id IN: setContractIds');
When i try in developer console , it executes and gives the output ,but when i use in getquery locator the output does not comes ...
Select  id, Contract_Name__c , EndDate ,Renewal_Status__c FROM Contract where Status Renewed IN ('Status renewed for next quarter','Pipeline') OR Status Renewed next Year IN ('Renewed','Renewed lost')
Any help very much appreciated.

 
bob_buzzardbob_buzzard
1.  Select Contract__c from Contract_role__c where Role__c in ('SA', 'EB', 'TA', 'RA)

2. You can just add these clauses to the query. 

What are you expecting to receive fromt he getQueryLocator() call? This will return a QueryLocator class that you can then iterate at a later point in time. 
computing cloudcomputing cloud
@bob_buzzard :Thanks for your response.
I tried adding the clause to the query but no luck .Basically i have a batch class ,which sends an email notification 100 days before the contract end date  to customer.Which was working fine when we were using this query .
return Database.getQueryLocator('Select id, Contract_Name__c , EndDate ,ownerId FROM Contract WHERE Id IN: setContractIds');
Now we have few changes in the requirement ,to add few conditions so when i started adding the condition ,the code got saved but the email notification is not going to the customer.
return Database.getQueryLocator([Select id, Contract_Name__c , EndDate ,Renewal_Status__c FROM Contract where Status Renewed IN ('Status renewed for next quarter','Pipeline') OR Status Renewed next Year IN ('Renewed','Renewed lost')])
Batch 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.


 
bob_buzzardbob_buzzard
Is you querylocator a verbatim copy - I can't see how a query containing ' OR Status Renewed next Year IN' would do anything other than throw an exception. as 'Status renewed next Year' isn't valid SOQL.
computing cloudcomputing cloud
@bob_buzzard :Status_Renewed__c and Status_Renewed_next_Year__c are the custom picklist value.I tried using this query
return Database.getQueryLocator([Select id, Contract_Name__c , EndDate ,Status_Renewed__c FROM Contract where Status_Renewed__c IN ('Status renewed for next quarter','Pipeline') AND Status_Renewed_next_Year__c NOT  IN ('Renewed','Renewed lost')]);
i worked ,but how can i make a formula field as checked.how can i use in the query .Any suggestion please.
 
bob_buzzardbob_buzzard
Are you looking to make a formula field that covers the Status_Renewed__c and Status_Renewed_next_Year__c checks? If so it should be something like:
 
IF (
  AND(
    OR(Status_Renewed__c = 'Status renewed for next quarter',            
           Status_Renewed__c='Pipeline'
          ), 
    AND(Status_Renewed_next_Year__c!='Renewed',
            Status_Renewed_next_Year__c!=''Renewed lost'
           ),
    true,
    false
)

 
computing cloudcomputing cloud
@bob_buzzard :I have a formual field as "Renewable" on contract object and this field is used only for the products which gets renewed.Now how can i query this formula field and make it checked in the record.

For Example : The Scenario is when the renewable product is checked ,then only the email notification is to be sent before 100 days of the contract end date.When i create an record i dont find the field on the edit page (as we know its an read only field) but how to make it checked .Do i need to do some field update or any formula where the value gets updated.

Any suggestion please.