Salesforce APEX method not bulkified - salesforce

I have written an APEX Class that sends an email when a client is released. There is a method that I thought I had bulkified but I was told it does not. This is because this method calls another function which actually does the actual email creation and that is not bulkified. Can someone guide me as to how the SOQL queries can be taken out of the method?
global class LM_ChangeAccountRT {
private static final Profile sysAdmin = [select id from profile where name='System Administrator'];
#AuraEnabled
public static String resendEmails(List<String> accountIdList) {
String response = null;
try {
//Only send emails if user is either an ARMS Administor or System Administrator
if (System.label.ARMS_Administrator_Profile_Id == userinfo.getProfileId() ||
sysAdmin.Id == userinfo.getProfileId()) {
List<Account> accList = [SELECT Id,Client_Released__c, RecordTypeId,Client_Number__c, Client_Released__c, Email_Sent__c FROM Account WHERE Id IN:accountIdList];
for(Account acc: accList){
if (acc.Client_Number__c != null && acc.Client_Released__c && acc.Email_Sent__c == true) {
sendpdfgenerationEmails(acc); //this is the method thats not bulkified.
acc.Email_Sent__c = false;
response = 'Email Sent';
}else {
response= 'Access Denied';
}
}
update accList;
}
}catch(Exception e) {
System.debug(e.getMessage());
response = 'Error sending emails';
}
return response;
}
public static void sendpdfgenerationEmails(Account acc){
system.debug('start of confirmation card and pdf generation');
//Logic to find which VF template is used to send an email.
list<EmailTemplate> templateId = new list<EmailTemplate>();
string temppartner;
String partner_opt_in_attachment;
boolean sendFCAmail;
List<Dealership_PDF_Generation__c> custsettingdata = Dealership_PDF_Generation__c.getall().values();
System.debug('custom setting size = ' + custsettingdata.size());
// Fetch State
if(acc.Dealership_State__c!=null && acc.Dealership_Partner__c!=null)
{
for(Dealership_PDF_Generation__c tempcustsetting :custsettingdata)
{
if(acc.Dealership_Partner__c == tempcustsetting.Dealership_Partner__c && acc.Dealership_State__c==tempcustsetting.State__c && tempcustsetting.State__c=='WA' && acc.Dealership_State__c=='WA'){
//For WA State
// temppartner= '%' + tempcustsetting.TEMPLATE_Unique_name__c + '%';
temppartner= tempcustsetting.TEMPLATE_Unique_name__c;
if(acc.Dealership_Spiff_Payment__c == '% premium'){
partner_opt_in_attachment=tempcustsetting.opt_in_form_premium__c;
}else{
partner_opt_in_attachment=tempcustsetting.opt_in_form_nonpremium__c;
}
}
else if(acc.Dealership_Partner__c == tempcustsetting.Dealership_Partner__c && acc.Dealership_State__c==tempcustsetting.State__c && tempcustsetting.State__c=='TX' && acc.Dealership_State__c=='TX'){
//For TX State
//temppartner= '%' + tempcustsetting.TEMPLATE_Unique_name__c + '%';
temppartner= tempcustsetting.TEMPLATE_Unique_name__c;
if(acc.Dealership_Spiff_Payment__c == '% premium'){
partner_opt_in_attachment=tempcustsetting.opt_in_form_premium__c;
}else{
partner_opt_in_attachment=tempcustsetting.opt_in_form_nonpremium__c;
}
}
else if(acc.Dealership_Partner__c == tempcustsetting.Dealership_Partner__c && acc.Dealership_State__c!=tempcustsetting.State__c && tempcustsetting.State__c!='TX' && acc.Dealership_State__c!='TX' && acc.Dealership_State__c!='WA' &&tempcustsetting.State__c!='WA' ){
//For Non TX State
//temppartner= '%' + tempcustsetting.TEMPLATE_Unique_name__c + '%';
temppartner= tempcustsetting.TEMPLATE_Unique_name__c;
if(acc.Dealership_Spiff_Payment__c == '% premium'){
partner_opt_in_attachment=tempcustsetting.opt_in_form_premium__c;
}else{
partner_opt_in_attachment=tempcustsetting.opt_in_form_nonpremium__c;
}
system.debug('grabbed template: ' + temppartner);
}
if(acc.Dealership_Partner__c != null && temppartner!=null ){
templateId.add([Select id,DeveloperName from EmailTemplate where DeveloperName = :temppartner]); //This will probably cause governor limit issues. First problem
}
if (partner_opt_in_attachment != null) {
StaticResource sr = [Select s.Name, s.Id, s.Body From StaticResource s where s.Name =: partner_opt_in_attachment]; //'static_resource' is the name of the static resource PDF. This is another SOQL query that will cause problems
Blob tempBlob = sr.Body;
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setBody(tempBlob);
efa.setFileName('Opt-in.pdf');
List<Messaging.EmailFileAttachment> attachments = new List<Messaging.EmailFileAttachment>();
attachments.add(efa);
// add attachment to each email
for (Messaging.SingleEmailMessage email : emails) {
email.setFileAttachments(attachments);
}
}
system.debug('email sent: ' + emails.size());
Messaging.sendEmail(emails);
}
}
}
The reason why I am trying to bulkify this is because I have written a APEX scheduler that calls the resendemails method everyday at 7am to check which records need to have an email sent. I am afraid that if there are more than a 100 clients then it will cause problems and not send the emails. Any suggestions on how I can optimize the sendpdfemailgeenration() method?
Thank you

Yes, you are right - your's resendEmails() method is not bulkified.
Firstly, let me explain you why is that:
SOQL to get Accounts
Loop 1 on List of Account records
Call sendpdfgenerationEmails() method
Retrieve list of Dealership_PDF_Generation__c records
Loop 2 on List of Dealership_PDF_Generation__c records
SOQL to get StaticResources - Very bad! It's inside double loop!
Call Messaging.sendEmail() method - Very bad! It's inside double loop!
Update on List of Account records
You need to remember that:
1. You should never do SOQLs in loops! - Limit 100 SOQLs per transaction
2. You should never call Messaging.sendEmail() in loops! - Limit 10 calls per transaction
Now let me guide you how to refactor this method:
#AuraEnabled
public static String resendEmails(List<String> accountIdList) {
// 1. SOQL for List of Account records
// 2. Retrieve list of Dealership_PDF_Generation__c records
// 3. SOQL for List of StaticResources for all Names from Dealership_PDF_Generation__c records
// 4. Declaration of new List variable for Messaging.SingleEmailMessage objects
// 5. Loop 1 on List of Account records
// 6. Call new "prepareEmailsForAccount()" method, which prepares and returns list of Messaging.SingleEmailMessage objects
// 7. Add returned Messaging.SingleEmailMessage objects to list from point 4
// 8. End of loop 1
// 9. Call "Messaging.sendEmail()" method with list from point 4
// 10. Update on List of Account records
}
With this you will avoid SOQLs and calling Messaging.sendEmail() method in loops.

Related

Receiving errors on Apex class to match fields for two different custom objects

I've been stuck for 18 hours on this apex class. I would really appreciate some help to figure out what's wrong. Basically this code should match the fields between two objects and I don't know why I'm receiving the following errors:
Missing return statement required return type: String - Line 2
Expecting '}' but was: 'for' - Line 26
The output should show that when location and position title from Candidate object matches location and title from Position object then it will just show those values that match on a data table in a lightning web component I made on Visual Studio.
I'd like some help improving this code so I can run it on the dev console.
public class Matchposition {
public static String matchPositionsWithCandidate() {
Set<String> statuses = new Set<String> {'New', 'Open'};
List<Position__c> openPositions = [SELECT Id, Name, Location__c, Status__c FROM Position__c WHERE Status__c IN :statuses];
//system.debug(openPositions);
Set<String> openPositionAndLocation = new Set<String>();
Map<String, Position__c> openPositionMap = new Map<String, Position__c>();
for (Position__c position : openPositions) {
openPositionMap.put(position.Name + '-' + position.Location__c, position);
openPositionAndLocation.add(position.Name + '-' + position.Location__c);
}
}
//for(String key : openPositionMap.keySet()) {
// system.debug('*** Start ***');
// system.debug('key :' + key);
// system.debug('value :' + openPositionMap.get(key));
// system.debug('*** End ***');
//}
Map<String, List<Candidate__c>> candidatesMap = new Map<String, List<Candidate__c>>();
List<Candidate__c> candidates = [SELECT Position__c, Location__c, Mobile__c, First_Name__c, Last_Name__c, Email__c FROM Candidate__c];
for (Candidate__c candidate : candidates) {
if(candidatesMap.containsKey(candidate.Position__c + '-' + candidate.Location__c)) {
candidatesMap.get(candidate.Position__c + '-' + candidate.Location__c).add(candidate);
} else {
candidatesMap.put(candidate.Position__c + '-' + candidate.Location__c, new List<Candidate__c> {candidate});
}
}
system.debug('*************** OPEN POSITIONS ***************');
for (String key : openPositionAndLocation) {
system.debug('====> ' + openPositionMap.get(key).Name);
if(candidatesMap.containsKey(key)) {
system.debug('***** Candidates *****');
for(Candidate__c candidate : candidatesMap.get(key)) {
system.debug('------- Name : ' + candidate.First_Name__c + ' ' + candidate.Last_Name__c);
system.debug('------- Email : ' + candidate.Email__c);
system.debug('------- Mobile : ' + candidate.Mobile__c);
}
} else {
system.debug('********* No Candidates');
}
}
One issue you certainly have, apropos of nothing else, is overall structure. Removing the actual lines of code, here's how your class is laid out now:
public class Matchposition {
public static String matchPositionsWithCandidate() {
// Code here
}
// more code here - problem!
}
You have much of your logic loose in the body of your class, which is not valid in Apex. Additionally, the code in the class body references variables declared inside the method matchPositionsWithCandidate(), which are scoped (visible) to that method.
matchPositionsWithCandidate() is also declared to return a string, but in fact returns nothing at all.
Since you're not returning any data anywhere, one step you can take to try to get this code running is to ensure that all of your logic is inside the scope (the curly braces) of the method matchPositionsWithCandidate(), and declare that method to return void, not String.
You may also have unbalanced braces - it looks like there is one missing after the final else - if it wasn't simply omitted in the copy and paste.
I'm not sure why this code exists. While much of the logic is correct, it makes far more sense to model your data with a relationship between Candidate__c and Position__c, rather than just storing a name in both positions. Then, you don't need any "matching" code at all - just a simple SOQL relationship query.

Apex, SOQL, add results from database to the List, error

I would like to add results from database to the List. But there is a bug.
String str = '\'AOC\',\'BPD\',\'CRE\'';
List<String> lstString = str.split(',');
List<Shop_Product__c> productList = new List<Shop_Product__c>();
Integer i = 0;
for (String record: lstString) {
System.debug('record[' + i + ']: ' + record);
if ((record != null) && (productList != null)) {
productList.add([SELECT Id, Brand__c
FROM Shop_Product__c
WHERE Brand__c = :record
LIMIT 10]);
System.debug('productList[' + i + ']: ' + productList);
System.debug('Here in for ----------------------------------------');
}
++i;
}
Error is System.QueryException: List has no rows for assignment to SObject.
Here is it the explain, but I don't understand what I should do.
The List method add() takes a single sObject. That's why you get the QueryException, just like in the examples you link to.
You can use the addAll() method to create a List<sObject> context, which avoids the exception if there are no responsive records.

how to delete all records excluding 0th record in array index

As per the code I don't want to delete 0th record and delete rest of the record. But it is deleting all the records!
Kindly assist where I am making the mistake.
Here is the code:
list<account> scope = [Select Id,(Select id,CreatedDate,ebMobile__FileType__c,ebMobile__Account__c from Files__r order by CreatedDate DESC) from account where id in ('0016D00000444','0016D000000ugO')];
Set<Id>OldIds = new Set<Id>();
Set<Id>newIds = new Set<Id>();
Set<Id> rIds = new Set<Id>();
Set<Id> rrIds = new Set<Id>();
list<File__c> listmemb = new list<File__c>();
List<File__c> listmemb3 = new List<File__c>();
List<File__c> listmemb4 = new List<File__c>();
for(Account Acc : scope)
{
for(File__c fi : Acc.ebMobile__Files__r)
{
listmemb = [select id,CreatedDate,ebMobile__FileType__c from File__c where id =: fi.id];
if(fi.ebMobile__Account__c != Null)
{
for(Integer i=0; i<listmemb.size(); i++)
{
if(fi.ebMobile__FileType__c == 'Signature' && i==0)
{
rIds.add(listmemb[0].id); // Exclude 0th record
}
if(i>0 && listmemb[i].ebMobile__FileType__c == 'Signature' || i > 0 && listmemb[i].ebMobile__FileType__c != 'signature')
{
rrIds.add(listmemb[i].id); // Delete all record excluding 0th record
}
if(fi.ebMobile__FileType__c != 'Signature')
{
OldIds.add(fi.id);
}
}
}
}
}
listmemb3 = [Select id,CreatedDate,ebMobile__FileType__c from File__c where id in : OldIds];
listmemb4 = [Select id,CreatedDate,ebMobile__FileType__c from ebMobile__File__c where id in : rrIds];
if(listmemb3.size() > 0 && listmemb4.size()>0)
{
delete listmemb3;
delete listmemb4;
}
}
There are some many unnecessary checks and lists in the code
Let us simplify the stuff:
list scope = [Select Id,(Select id,CreatedDate,ebMobile__FileType__c,ebMobile__Account__c from Files__r order by CreatedDate DESC) from account where id in ('XXXXXXXXXXXXXXXX','XXXXXXXXXXXXXXXX')];//Always keep Ids encrypted while posting on public platform
SetOldIds = new Set();
SetnewIds = new Set();
Set rIds = new Set();
Set rrIds = new Set();
list listmemb = new list();
List listmemb3 = new List();
List listmemb4 = new List();
for(Account Acc : scope)
{
Integer i= 0; //This will be used to exclue the first element
for(File__c fi : Acc.ebMobile__Files__r)
{
//listmemb = [select id,CreatedDate,ebMobile__FileType__c from File__c where id =: fi.id];//You don't need this as you already have fi
//if(fi.ebMobile__Account__c != Null)We are getting fi from Acc so it won't be having ebMobile__Account__c as null, assuming it as lookup
//{
//for(Integer i=0; i {This is syntactically wrong
/* This whole section is not needed as rIds is not being used anywhere
if(fi.ebMobile__FileType__c == 'Signature' && i==0)
{
rIds.add(listmemb[0].id); // Exclude 0th record
}
*/
//if(i>0 && listmemb[i].ebMobile__FileType__c == 'Signature' || i > 0 && listmemb[i].ebMobile__FileType__c != 'signature')
if( i > 0 ) //Just put the check you need
{
rrIds.add(listmemb[i].id); // Delete all record excluding 0th record
}
if(fi.ebMobile__FileType__c != 'Signature')
{
OldIds.add(fi.id);
}
i++;
//}
//}
}
}
listmemb3 = [Select id,CreatedDate,ebMobile__FileType__c from File__c where id in : OldIds];
listmemb4 = [Select id,CreatedDate,ebMobile__FileType__c from ebMobile__File__c where id in : rrIds];
if(listmemb3.size() > 0 && listmemb4.size()>0)
{
delete listmemb3;
delete listmemb4;
}
}
Hope this helps.
#Vishal there are a couple things I'm not really sure of based on your code and context:
What defines 'the first file'? In your second (duplicate) query you don't seem to apply any ordering, so Salesforce might return you the same records in different order based on their database structuring. In your first sub-select query there is.
Is there a specific reason you use if, if, if, instead of if, else if, else if? With this approach you prevent the second and third item to run, even when the first one applied. This will simplify your code as you don't need all duplicate check (i == 0, i > 0 and such)
How is it possible that a different Salesforce record (File vs. ebMobile__File__c) can have the same Salesforce ID? (in your query for listMembers)
Couple suggestions:
Only query the records you really want to delete using Offset (shift starting record)
Please try to avoid doing queries and DML actions in loops, since this is bad for performance, but also might cause running into governor limits
Apply usage of variableBinding, this will ensure no SOQL Injection can be applied (when the account IDs are e.g. fetched from the front-end)
Simplify your logic to do what you really want; if you query only those to delete (see 1.) then you can simply loop ones to determine the Signature condition and then just delete the list of Files per Account. In my perspective, there is no need to query the files again, since you already have their IDs and records, so you can simply specify to delete the retrieved records, right?
Set<Id> accountIds = new Set<Id>{ 'xxxx', 'xxxx' };
List<Account> scope = [SELECT Id,
( SELECT Id, ...
FROM Files__r
ORDER BY CreatedDate DESC
OFFSET 1 )
FROM Account
WHERE Id IN :accountIds];
List<File> filesToDelete = new List<File>();
List<ebMobile__File__c> ebMobileFileToDelete = new List<File>();
for( Integer i = 0, j = scope.size(); i < j; i++ ){
Account acc = scope[ i ];
if( acc.Files__r != null & !acc.Files__r.isEmpty() ){
for( Integer k = 0, l = acc.Files__r.size(); k < l; k++ ){
File f = acc.Files__r[ k ];
if( f.ebMobile__FileType__c != 'Signature' ){
// When not signature, delete the original file
filesToDelete.add( f );
} else{
// Don't delete the File, but delete the EB MobileFile
ebMobileFileToDelete.add( new ebMobile__File__c( Id = f.Id ) );
}
}
}
}
if( !filesToDelete.isEmpty() ){ delete filesToDelete; }
if( !ebMobileFileToDelete.isEmpty() ){ delete ebMobileFileToDelete; }
Please note, I haven't run this code, so it might require some tweaking, but I hope you'll be able to get it all working.
Good luck and enjoy! Reinier

What does the oldmap actually do here? Can someone explain

This is a code to create a new task when stage is inserted or updated to Closed Won
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
List<Task> tl = new List<Task>();
for(Opportunity op : Trigger.new) {
if(Trigger.isInsert) {
if(Op.StageName == 'Closed Won') {
tl.add(new Task(Subject = 'Follow Up Test Task', WhatId = op.Id));
}
}
if(Trigger.isUpdate) {
if(Op.StageName == 'Closed Won'
&& Op.StageName != Trigger.oldMap.get(op.Id).StageName) {
tl.add(new Task(Subject = 'Follow Up Test Task', WhatId = op.Id));
}
}
}
if(tl.size()>0) {
insert tl;
}
}
Here, what does && Op.StageName != Trigger.oldMap.get(op.Id).StageName) do? Why do we use oldMap here?
Trigger.newMap is the map of IDs of new object values. Available in insert, update, and undelete triggers, and 'new' records can only be modified in before triggers.
Trigger.oldMap is the map of IDs of old object values. Available in update and delete triggers only.
if (Trigger.isUpdate) {
// Iterate updated opportunities
for (Opportunity o : Trigger.new) {
// Get the opportunity before update
Opportunity oldOpp = Trigger.oldMap.get(o.Id);
// Check if a value changed
if (o.Some_Value__c == oldOpp.Some_Value__c) {
System.debug('Value did not change.');
} else {
System.debug('Value changed!');
}
}
}
Note: I could have used Trigger.newMap instead of Trigger.new but I'd be looping through Trigger.newMap.values() instead - with the same end result. newMap is just a convenient way of getting the bulkified data in map form instead of a list.
We use old map to compare with the new value of the Some_Value__c custom field. If the two values differ then the field value has changed. Of course, if you read the code in the two if branches, this is obvious.

Pagination in Google cloud endpoints + Datastore + Objectify

I want to return a List of "Posts" from an endpoint with optional pagination.
I need 100 results per query.
The Code i have written is as follows, it doesn't seem to work.
I am referring to an example at Objectify Wiki
Another option i know of is using query.offset(100);
But i read somewhere that this just loads the entire table and then ignores the first 100 entries which is not optimal.
I guess this must be a common use case and an optimal solution will be available.
public CollectionResponse<Post> getPosts(#Nullable #Named("cursor") String cursor,User auth) throws OAuthRequestException {
if (auth!=null){
Query<Post> query = ofy().load().type(Post.class).filter("isReviewed", true).order("-timeStamp").limit(100);
if (cursor!=null){
query.startAt(Cursor.fromWebSafeString(cursor));
log.info("Cursor received :" + Cursor.fromWebSafeString(cursor));
} else {
log.info("Cursor received : null");
}
QueryResultIterator<Post> iterator = query.iterator();
for (int i = 1 ; i <=100 ; i++){
if (iterator.hasNext()) iterator.next();
else break;
}
log.info("Cursor generated :" + iterator.getCursor());
return CollectionResponse.<Post>builder().setItems(query.list()).setNextPageToken(iterator.getCursor().toWebSafeString()).build();
} else throw new OAuthRequestException("Login please.");
}
This is a code using Offsets which seems to work fine.
#ApiMethod(
name = "getPosts",
httpMethod = ApiMethod.HttpMethod.GET
)
public CollectionResponse<Post> getPosts(#Nullable #Named("offset") Integer offset,User auth) throws OAuthRequestException {
if (auth!=null){
if (offset==null) offset = 0;
Query<Post> query = ofy().load().type(Post.class).filter("isReviewed", true).order("-timeStamp").offset(offset).limit(LIMIT);
log.info("Offset received :" + offset);
log.info("Offset generated :" + (LIMIT+offset));
return CollectionResponse.<Post>builder().setItems(query.list()).setNextPageToken(String.valueOf(LIMIT + offset)).build();
} else throw new OAuthRequestException("Login please.");
}
Be sure to assign the query:
query = query.startAt(cursor);
Objectify's API uses a functional style. startAt() does not mutate the object.
Try the following:
Remove your for loop -- not sure why it is there. But just iterate through your list and build out the list of items that you want to send back. You should stick to the iterator and not force it for 100 items in a loop.
Next, once you have iterated through it, use the iterator.getStartCursor() as the value of the cursor.

Resources