Saturday, September 19, 2015

Sharing Rule Throw Batch Apex for Account Object


global class AccountPlanSharing_Batch implements Schedulable, Database.Batchable<sObject> {

    global static void scheduleJob() {
        // 1st digit = seconds
        // 2nd digit = minutes
        // 3rd digit = hours (24 hours)
        // 4th digit = day of month (? = no value, * = all, 1 - 31)
        // 5th digit = month (? = no value, * = all, 1=January, etc.)
        // 6th digit = day of week (? = no value, * = all, 1=Sunday, etc.)

        String sch_1stDayofMonth_1am = '0 0 2 * * ?'; // 2am every day
        System.schedule('AccountPlanSharing_Batch' + (Test.isRunningTest() ? 'TEST' : ''),
            sch_1stDayofMonth_1am, new AccountPlanSharing_Batch());    
    }

    public String qrystr = 'SELECT Id, Name, RecordType.Name, Account__r.Name, Account__r.CP_Hierarchy_Level_Type__c '+
            ' From Account_Plan__c '+
            ' WHERE RecordType.Name = \'EMEA Account Plan\' '+
            ' AND Account__r.CP_Hierarchy_Level_Type__c = \'RP\' ';
           
    public void setQrystr(String instr) {
        qrystr = instr;
    }
       
    /**
     * Constructor
     * - Does nothing because nothing to do for scheduled job
     */
    global AccountPlanSharing_Batch(){
    }
   
    /**
     * Schedule Interface Method
     * Responsible for starting the job (not batched though)
     */
    global void execute(SchedulableContext sc) {
        Database.executeBatch(new AccountPlanSharing_Batch(), 100);
    }

    global void finish(Database.BatchableContext BC){ }

    global Database.QueryLocator start(Database.BatchableContext BC){
        // Select all Accounts and process
        return Database.getQueryLocator(qrystr);
    }

    global void execute(Database.BatchableContext BC, list<sObject> scope){
        runJob(scope);
    }
   
    /*
      main method...
    */
    public static void runJob(list<sObject> scope) {
        System.Debug('    #### runJob...');
        // set of RP Account Ids for the AccountPlans in scope
        Set<Id> rpAccountIdSet = new Set<Id>();
        for (sObject sobj : scope) {
            Account_Plan__c acctplan = (Account_Plan__c) sobj;
            rpAccountIdSet.add(acctplan.Account__r.Id);
        }
       
        // now query all child MP Account records
        List<Account> acctList = [SELECT Id, Name, OwnerId, Owner.Name, ParentId
                  FROM Account WHERE ParentId IN :rpAccountIdSet AND CP_Hierarchy_Level_Type__c = 'MP'];
       
        // build a Map of RP Account Id to List<MP Account>
        Map<Id, List<Account>> acctRPMPMap = new Map<Id, List<Account>>();
        for (Account acct : acctList) {
          List<Account> tmpacctList = new List<Account>();
          if (acctRPMPMap.containsKey(acct.ParentId)) {
            tmpacctList = acctRPMPMap.get(acct.ParentId);
          }
          tmpacctList.add(acct);
          acctRPMPMap.put(acct.ParentId, tmpacctList);
        }
       
        // now for each AP, grab cooresponding MP Accounts and build sharing record
        List<Account_Plan__Share> apshareInsertList = new List<Account_Plan__Share>();
        for (sObject sobj : scope) {
            Account_Plan__c acctplan = (Account_Plan__c) sobj;
            List<Account> mpList = acctRPMPMap.get(acctplan.Account__c);
            if (mpList != null) {
        for (Account acct : mpList) {
          String acctOwner = acct.OwnerId;
          if (acctOwner.startsWith('005')) {
            Account_Plan__Share apshare = new Account_Plan__Share();// sharing object of account
            apshare.ParentId = acctplan.Id;// parent id
            apshare.UserOrGroupId = acct.OwnerId;
            apshare.AccessLevel = 'Read';
            apshareInsertList.add(apshare);
            System.Debug('    #### creating apshare for '+acct.Owner.Name+' for '+acctplan.Name);
          }
        }
            }
        }
       
        Database.insert(apshareInsertList, false);
   
    }

   

}

No comments:

Post a Comment