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
brozinickrbrozinickr 

Help with Trigger on Account

Hello.  In our org we have a trigger on the Account so that if the Account changes ownership, that open opportunities do not switch to the new account owner.  When manually testing , it seems to work for those opportunitites that are Closed/Won, but it still switches the owners if they are Protected. (Protected is a checkbox on the opportunity.  I want it so if the opportunity is protected, the opportunity owner will NOT change).

 

Here's my code:

 

public class AlOpportunity {
    
    public static Opportunity GetOpportunity(string Id){
        Opportunity opp = null;
        for (Opportunity oppr: [SELECT Id, Name, AccountId from Opportunity WHERE Opportunity.Id=: Id]){
            System.debug('Testing_Code');
            opp = oppr;
            break;
        }
        return opp;
    }
    
    //unit test TestGetOpportunity
    public static testMethod void TestGetOpportunity(){
        
        Opportunity o = new Opportunity();
        o.Name = 'test opp';
        o.StageName = 'test stage';
        o.CloseDate = Date.today();
        insert o;
        
        Opportunity o1 = GetOpportunity(o.id);
        
        System.assertEquals(o1.id == o.id, true);
    }
    
    public static List<Opportunity> ChangeOpportynityOwners(Map<Id,Account> accounts){
        List<Opportunity> opps = [Select o.Id, o.OwnerId, o.AccountId From Opportunity o WHERE accountid in: accounts.KeySet() AND Protected__c = false AND StageName <> 'Closed/Won' AND StageName <> 'Closed Lost'];
        if (opps == null)
            opps = new List<Opportunity>();
        for (Opportunity opp: opps){
            opp.OwnerId = accounts.get(opp.AccountId).OwnerId;
        }
        return opps;
    }
    
    //unit test TestChangeOpportynityOwners
    public static testMethod void TestChangeOpportynityOwners(){
        
        Account acc = new Account();
        acc.Name = 'Unit test account';
        insert acc;
        
        Opportunity o = new Opportunity();
        o.Name = 'test opp';
        o.StageName = 'Quote';
        o.AccountId = acc.id;
        o.CloseDate = date.today();
        insert o;
                
        Map<Id,Account> accs = new Map<Id,Account>();
        accs.Put(acc.id,acc);
        AlOpportunity.ChangeOpportynityOwners(accs);
    }

}

 

and the trigger:

 

trigger Account_UpdateOpportunityAndTaskOwners on Account (after update) {
  
  Map<id,Account> accountsToProcess = new Map<id,Account>();
  
  //filter accounts with changed owner
  for (Account acc : trigger.new){
    if (acc.OwnerId != trigger.oldMap.get(acc.id).OwnerId){
      accountsToProcess.put(acc.id,acc);
    }
  }
  
  try{
  if (accountsToProcess.size() > 0) {
    System.Debug('Processing the accounts tasks and opprs');
    List<Task> tasksToUpdate = AlAccount.ChangeTaskOwners(accountsToProcess);
    List<Opportunity> oppsToUpdate = AlOpportunity.ChangeOpportynityOwners(accountsToProcess);
    
    if (tasksToUpdate.size() > 0)
    {
      System.debug('updating the tasks');
      update tasksToUpdate;
    }
    if (oppsToUpdate.size() > 0)
      update oppsToUpdate;
  }
  }
  catch( Exception ex)
  {
    //String subject;
    System.Debug('Exception occured in deleting tasks...' + ex.getMessage()+ '\r\n' + 
    'Stack Trace ...' + ex.getStackTraceString() + '\r\n');
    /*subject += 'Exception occured in deleting tasks...' + ex.getMessage() + '\r\n';
      subject += 'Stack Trace ...' + ex.getStackTraceString() + '\r\n';  
      if (AL_Settings__c.getInstance('MaxProtectedAccounts').Territory_Process_Error_Email__c != null){
        List<string> toAddresses = new List<string>();
        toAddresses.add(AL_Settings__c.getInstance('MaxProtectedAccounts').Territory_Process_Error_Email__c);  
        if (toAddresses.size() > 0)
        {
              Messaging.SingleEmailMessage statusMail = new Messaging.SingleEmailMessage();
              List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
              statusMail.setToAddresses(toAddresses);
              statusMail.setReplyTo('padma.ramkumar@revelanttech.com');
              statusMail.setSubject(subject + ' ' + String.valueOf(Datetime.now()) );
              statusMail.setPlainTextBody('Account_DefineRelatedTerritory:Account Bulk Load');
              mails.add(statusMail);
              Messaging.sendEmail(mails);
        }
      }  */        
  }
  
}

 

 

 

 

 

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
brozinickrbrozinickr

The trigger is supposed to change only open non-protected opportunities.

 

I did some testing via data loader and I have found that my trigger works when I change account ownership there.

 

From what I can tell, if you change ownership literally through salesforce using the UI, then it will automatically change the open opportunities when the account owner and opportunity owner are the same.

 

When you use the API to change the Account Owners (ex. using the Data Loader or DBAmp), then it doesn't not change ownership of ANY opportunities unless you write some type of automation for it to do so.

 

Since we only change account ownership via the data loader, what I have works, so my issue is resolved.

 

Thanks for your suggestions, Jia Hu! :)

All Answers

Jia HuJia Hu
Based on my understanding, when StageName is 'Closed/Won' or 'Closed Lost', the Ownership can change with Account. Is it right?

If this is the case, then when Protected is true, but StageName is 'Closed/Won' or 'Closed Lost', the Ownership still can change.
brozinickrbrozinickr

The trigger is supposed to change only open non-protected opportunities.

 

I did some testing via data loader and I have found that my trigger works when I change account ownership there.

 

From what I can tell, if you change ownership literally through salesforce using the UI, then it will automatically change the open opportunities when the account owner and opportunity owner are the same.

 

When you use the API to change the Account Owners (ex. using the Data Loader or DBAmp), then it doesn't not change ownership of ANY opportunities unless you write some type of automation for it to do so.

 

Since we only change account ownership via the data loader, what I have works, so my issue is resolved.

 

Thanks for your suggestions, Jia Hu! :)

This was selected as the best answer