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
sf sf usersf sf user 

apex code to check if there is open opportunity on the account

Hi all,

Is there any way where I can check if there is any open opportunity with the close date is in past and if it is there tehn I want to close it before i create a new opportunity on the same account.
Here I am creating the new opportunity using the batch job and my job will run on first day of every month.
Thanks in advance........
Uttpal_ChandraUttpal_Chandra
Yes you can do it easily by using trigger.
sf sf usersf sf user
Hi Cahndra,

List<Account> accs =new List<Account>([SELECT Id,Name, 
                (SELECT Id,CloseDate,Name,IsClosed FROM Opportunities WHERE IsClosed = False AND CloseDate < Today) FROM Account]);
      public static List<Opportunity> opps (Opportunity openOpp) { 
      //Close the open Opportunity 
          openOpp.StageName = 'Closed Lost';
          openOpp.Close_Reason__c = 'Mass_Closure_Lacking_Follow_Up';  
         Database.update(openOpp);
        return opps;
}

I have written something like this. But, it is hitting the limit. Cn you help me in modifying it so that it will not hit the limits anymore
SarvaniSarvani
Hi,

The trigger below will check for a new Opportunity if there are any opportunities on the same Account which are not closed but having closedate before today and updates all the related opportunity records StageName and Close_Reason__c.

Please try below code:
trigger CloseOpps on Opportunity (before insert) {
   set<id> RelatedAccountId=new Set<id>();
    list<opportunity> OppsCloselist=new list<Opportunity>();
     list<Opportunity> OppRecs=new  list<Opportunity>();
    //Fetch New Opportunity records Account Id if exists
    for(Opportunity opp:Trigger.new){
        if(opp.AccountId!=NULL){
            RelatedAccountId.add(opp.AccountId);
        }
    }
    //Fetching All opps of the Account
    if(RelatedAccountId.size()>0){
    OppRecs =[Select id,AccountId,StageName,Closedate,IsClosed,Close_Reason__c from Opportunity where Accountid in :RelatedAccountId];
    }
    // Check the opps stage and closed date and update accordingly
    if(OppRecs.size()>0){
        for(opportunity Opp:OppRecs){
            if(Opp.IsClosed ==False && Opp.CloseDate < System.Today()){
                Opp.StageName='Closed Lost';
                Opp.Close_Reason__c = 'Mass_Closure_Lacking_Follow_Up';
            }
            OppsCloselist.add(Opp);
        }
        if(OppsCloselist.size()>0){
            update OppsCloselist;
        }
        
    }

}
Hope this helps! Please mark as best if it does

Thanks