Write a trigger and it's Test class on Account when Account is update check all opportunity inside the account.

Update all Opportunities Stage to close lost if an opportunity created date is greater than 30 days from today and stage not equal to close won.

....Trigger....

trigger UpdateOpportunities on Account (after update) {
    
    Set<Id> accountIds = new Set<Id>();
    for(Account a:Trigger.new){
        accountIds.add(a.Id);
    }
    
    DateTime day30=system.now()-30;
    List<Opportunity> oppListToUpdate=new List<Opportunity>();
    
    List<Opportunity> oppList = [Select Id, AccountId, StageName, CreatedDate, CloseDate from Opportunity where AccountId in :accountIds];
    if(oppList.size()>0) 
    {
        for(Opportunity opp : oppList)
        {  
            if(opp.CreatedDate < day30 && opp.StageName!='Closed Won')
            {
                opp.CloseDate = system.today();
                opp.StageName = 'Closed Lost';
                oppListToUpdate.add(opp);
                update opp;
            }
        }
    }
    if(oppListToUpdate.size()>0){
        update oppListToUpdate;
    }
}
....Test Class....
@istest
public class UpdateOpportunities1Test {
    @istest
    public static  void  triggerTest() {
        Account testAcct = new Account (Name = 'My Test Account');
        insert testAcct;
        Opportunity oppt = new Opportunity();
        oppt.Name ='New mAWS Deal';
        oppt.AccountID = testAcct.ID;
        oppt.StageName = 'Closed Lost';
        oppt.Amount = 3000;
        oppt.CloseDate = System.today();
        insert oppt;
        testAcct.AccountNumber='1234';
        update testAcct;
        update oppt;
        
        Opportunity oppList = [Select Id, AccountId, StageName, CreatedDate, CloseDate from Opportunity where id =: oppt.Id];
        System.assertEquals(oppList.StageName,'Closed Lost');   
    }
}

Comments