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
SurenderSurender 

System.LimitException: Too many script statements for the Apex Code:

Hi,

 

I'm getting System.LimitException: Too many script statements for the below Apex Code:

 

Apex Code:

public class OpportunitySalesTeamSwarmHelper {

public static void evaluateOpptySalesTeamRules() {

// Get list of Opptys with opp, acc, owner details
List<Opportunity> opptys = [SELECT o.Id, o.Name, o.Type, o.AccountId, Account.Name,Account.OwnerId, Account.JDA_Industry__c,
Account.Named_Account__c,Account.Target_Rating__c, o.StageName, o.Amount,o.CurrencyIsoCode, o.Local_Region_Override__c,o.CloseDate, o.Business_Unit__c,
o.OwnerId, o.Owner.Name, o.Owner.Reports_To__c FROM Opportunity o WHERE o.StageName like 'open'];

// Get list of all rules
List<Opportunity_Swarm_Rule__c> rules = [select Name,type__c, Opportunity_amount__c, Opportunity_stage__c,
Opportunity_type__c, Opportunity_Local__c,Opportunity_Business_Unit__c,JDA_Industry__c, user__c,
ownerId, Notify_on_Swarm__c from Opportunity_Swarm_Rule__c WHERE user__r.IsActive = true];

// Get all subscriptions and put in string concatenating subscriber + object ID
List<EntitySubscription> existingOpptySubs = [select SubscriberId, ParentId from EntitySubscription where ParentId in :opptys];

Set<String> existingOpptySubsIds = new Set<String>();
for (EntitySubscription es:existingOpptySubs) {
existingOpptySubsIds.add((String)es.SubscriberId + es.ParentId);
}//for

List<OpportunityTeamMember> opptySalesTeams = [SELECT UserId from OpportunityTeamMember where OpportunityId in :opptys];

// Create a list of subscripions and chatter feeds and insert them later outside the loop
List<EntitySubscription> subs = new List<EntitySubscription>();
List<FeedItem> feedNotifications = new List<FeedItem>();

// For each oppty check all rules.
// If criteria is satisfied, make the user of rule to follow the opportunity
Integer count = 0;
for (Opportunity thisOppty : opptys) {
count++;
System.debug('The value of Count is'+count);
for (Opportunity_Swarm_Rule__c rule : rules) {

if(rule.Type__c.contains('Opptys where I am an Account Team Member')) {

boolean salesTeamFlag = false;
boolean condition = false;
for (OpportunityTeamMember opptySalesTeam : opptySalesTeams) {
if(rule.User__c == opptySalesTeam.UserId ){
salesTeamFlag=true;
}
if(salesTeamFlag)
break;
}

condition= salesTeamFlag;
System.debug('The value of Condition - Opptys where I am Sales Team Member is : '+condition);

if(condition) {
if (existingOpptySubsIds.contains((string)rule.User__c + thisOppty.Id) == FALSE) {
subs.add(new EntitySubscription(parentId = thisOppty.id, SubscriberId = rule.User__c));
existingOpptySubsIds.add((String)rule.User__c + thisOppty.id);

// Add swarming notification to user's feed
if (rule.Notify_on_Swarm__c == true) {
//displaying close datetime as only date string
Datetime dateTimetemp = thisOppty.CloseDate;
Date dateTemp = Date.newInstance(dateTimetemp.year(),dateTimetemp.month(),dateTimetemp.day());
String dateStr = dateTemp.format();

string msg = 'You have automatically swarmed an Opportunity.'+ '\n' +
'Opportunity Name : ' + thisOppty.Name+ '\n' +
'Account : ' + thisOppty.Account.Name + '\n' +
'Type : ' + thisOppty.Type + '\n' +
'Close Date : ' + dateStr + '\n' +
'Owner : ' + thisOppty.Owner.Name;

FeedItem swarmNotification = new FeedItem();
swarmNotification.Type = 'LinkPost';
swarmNotification.ParentId = rule.User__c;
swarmNotification.Title = 'Link to Opportunity Record '+thisOppty.Name+' Swarmed';
swarmNotification.Body = msg;
swarmNotification.LinkUrl = URL.getSalesforceBaseUrl().toExternalForm() + '/' + thisOppty.Id;
feedNotifications.add(swarmNotification);
}// if 3
}//if 2
}//if 1
}

}//for 2

}//for 1 oppty's

try {
System.Debug('Subscription count : ' + subs.size());
insert subs;
insert feedNotifications;
} catch (DMLException e) {
system.debug('Oppty Swarm subscriptions were not all inserted successfully. Error: '+e);
}//catch
}//evaluateOpptyRules

}//class

 

Below is debug log info:

01:42:46.811|LIMIT_USAGE_FOR_NS|(default)|

Number of SOQL queries: 4 out of 100
Number of query rows: 6698 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 0 out of 150
Number of DML rows: 0 out of 10000
Number of script statements: 200002 out of 200000 ******* CLOSE TO LIMIT
Maximum heap size: 0 out of 6000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10

 

Can someone look at the code and please share your thoughts to overcome the above exception..

 

Thanks in advance..

 

CholericCholeric

Hi,

 

your problem is caused by 3 interlaced for-loops (Opportunity, Opportunity_Swarm_Rule__c, OpportunityTeamMember).

As each data-pool for the loops has no relation to another in your code you get #Opps*#Swarm_rules* #TeamMembers script statements.

 

Try not to loop through all date each time.

e.g. loop through Team-Members of the actual Opportunity (same goes for those swarm rules if they got a relation to Opportunities (as I believe) - that could be achieved using maps with opp.id as key and data-rows as values (map<Id, list<OpportunityTeamMember>)).

 

You maybe could query that data in a single SOQL statement using sub-queries ([select id, (select id from OpportunityTeamMembers) from Opportunity]) and loop through data like that:

 

for (Opportunity opp : <opp-select>) {

for (OpportunityTeamMember otm : opp.OpportunityTeamMembers) {

....

}

}

 

If you still create too many Statements or if my suggestion doesn't work in your context (you might want to give some background then)... let it run as a batch-job with your Opportunity-Query as input and reduce Batchsize to a number that doesn't throws errors.

 

cheers,

Stefan