Tuesday, 2 October 2012

Using Batch Apex to Change the Account Owners


global class AccountOwnerReassignment implements 
             Database.Batchable<SObject>, Database.Stateful{
    
    User fromUser{get; set;}
    User toUser{get; set;}
    Double failedUpdates{get; set;}
    //Parameter Construcotr
    global AccountOwnerReassignment(User fromUser, User toUser){
        this.fromUser = fromUser;
        this.toUser = toUser;
        failedUpdates = 0;
    }
    
    global Database.queryLocator 
                    start(Database.BatchableContext ctx){
        return Database.getQueryLocator([SELECT id, name, ownerId 
                        FROM Account WHERE ownerId = :fromUser.id]);
    }
    
    global void execute(Database.BatchableContext ctx, List<Sobject> scope){
        List<Account> accs = (List<Account>)scope;
        
        for(Integer i = 0; i < accs.size(); i++){
            accs[i].ownerId = toUser.id;
        }
        
        List<Database.SaveResult> dsrs = Database.update(accs, false);
        for(Database.SaveResult dsr : dsrs){
            if(!dsr.isSuccess()){
                failedUpdates++;
            }
            
        } 
    }
    
    global void finish(Database.BatchableContext ctx){
    
        AsyncApexJob a = [SELECT id, ApexClassId, 
                       JobItemsProcessed, TotalJobItems, 
                       NumberOfErrors, CreatedBy.Email 
                       FROM AsyncApexJob 
                       WHERE id = :ctx.getJobId()];
        
        String emailMessage = 'Your batch job '
             + 'AccountOwnerReassignment '
             + 'has finished.  It executed ' 
             + a.totalJobItems 
             + ' batches.  Of which, ' + a.jobitemsprocessed 
             + ' processed without any exceptions thrown and ' 
             + a.numberOfErrors +
             ' batches threw unhandled exceptions.'
             + '  Of the batches that executed without error, ' 
             + failedUpdates 
             + ' records were not updated successfully.';
        
        Messaging.SingleEmailMessage mail = 
              new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.createdBy.email};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('noreply@salesforce.com');
        mail.setSenderDisplayName('Batch Job Summary');
        mail.setSubject('Batch job completed');
        mail.setPlainTextBody(emailMessage);
        mail.setHtmlBody(emailMessage);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] 
                           { mail });
    }    
}
In Developer Console Paste below code:

User fromUser = [select id,firstname from user where firstname = 'name of the user'];
User toUser = [select id,firstname from user where firstname = 'name of the user'];                 
Database.executeBatch(new AccountOwnerReassignment(fromUser,toUser));
Note: Name of the user means, Goto Managed Users>Click on particuar user> At the top below the User one name will display that name we should give in place of 'name of the user'

Calling Batch Apex from Trigger:
* Goto App Setup> Customize> Account> Triggers

Trigger AccountOwnerReassignment on Account (before insert) {
    List<Account> al = Trigger.new;
    for(Account a:al) {
        User fromUser = [select id,firstname from user where alias = 'alias name'];
        User toUser = [select id,firstname from user where alias = 'alias name'];                 
        try {
            Database.executeBatch(new AccountOwnerReassignment(fromUser,toUser));
        }
        Catch(Exception E) {
        }
    }
}
Note: In case, no rows queried from the SOQL Queries below error will arise.
Error: Invalid Data. Review all error messages below to correct your data.Apex trigger AccountOwnerReassignment caused an unexpected exception, contact your administrator: AccountOwnerReassignment: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.AccountOwnerReassignment: line 4, column 1

Refer:
http://developer.force.com/cookbook/recipe/using-batch-apex-to-reassign-account-owners

No comments:

Post a Comment

Labels