Skip to main content

Manufacturing Cloud | Rebate Management - Order Record Activation using Apex Batch Class - Streamlining Data Processing

In the dynamic landscape of Salesforce development, where data processing and manipulation are at the heart of business operations, efficient handling of large datasets becomes imperative. Salesforce Batch Apex classes emerge as a powerful solution to tackle these challenges by allowing developers to process records in smaller chunks, optimizing resource utilization and maintaining system performance. In this article, we will delve into the world of Salesforce Batch Apex classes, understand its various methods, explore its advantages and disadvantages, and learn how to schedule batch jobs using the Cron scheduler.

Understanding Batch Apex

Batch Apex is a specialized form of Apex code that allows for the processing of large volumes of data in a more manageable and resource-efficient manner. Unlike traditional Apex code that operates on all records at once, Batch Apex divides the data into smaller batches or chunks, processing them sequentially. This approach not only helps in preventing memory issues but also ensures that system resources are utilized efficiently.

Three Batch Apex Methods

start() Method: This method is used to initiate the batch job and define the scope of records to be processed. It returns an iterable that represents the records to be processed in the current batch.

execute() Method: The core processing logic is implemented in this method. It accepts a batch of records as input and performs required operations on them. Developers can design this method to handle data manipulation, calculations, and updates.

finish() Method: This method is executed once all batches are processed. It provides an opportunity to perform any post-processing tasks, such as sending notifications or updating status fields.

Key Points about Batch Apex

Governor Limits: Batch Apex operates within Salesforce's governor limits, ensuring that resource usage remains under control.

Record Processing: Batch Apex processes records in chunks, reducing the risk of hitting memory limits and enhancing performance.

Asynchronous Execution: Batch jobs run asynchronously, allowing other tasks to be executed in parallel.

Database Transactions: Each batch is treated as a separate transaction, offering better control over data integrity.

Advantages of Batch Apex

Efficiency: Batch Apex enables the processing of large datasets without causing memory issues or performance degradation.

Governor Limit Management: Salesforce governor limits are better managed as batch processing adheres to these limits.

Scalability: Batch Apex is highly scalable, making it suitable for data-intensive operations in both small and large organizations.

Disadvantages of Batch Apex

Complexity: Designing and implementing Batch Apex classes can be more complex than traditional Apex due to the need to manage batch state and execution flow.

Learning Curve: Developers need to understand the intricacies of the batch processing framework, which might have a learning curve.

Data Consistency: Ensuring data consistency across batches might require extra attention, especially in scenarios with interdependent records.

Scheduling Batch Apex with Cron

Batch Apex jobs can be scheduled using the Salesforce Cron scheduler, which allows for automated execution at specific intervals. To schedule a batch job:

Create a Batch Class: Develop a Batch Apex class that implements the start(), execute(), and finish() methods.

Schedule the Job: Navigate to "Setup" > "Apex Jobs" > "Scheduled Jobs" and click "Schedule Apex". Select your batch class, set the preferred frequency (daily, weekly, etc.), and define the time of execution using a Cron expression.

Monitor Execution: You can monitor the execution of scheduled batch jobs through the Apex Jobs page, which provides insights into job status and execution history.

Conclusion

Salesforce Batch Apex classes offer an efficient and scalable solution for processing large volumes of data within Salesforce applications. By breaking down data into manageable chunks, Batch Apex optimizes resource utilization and ensures smoother execution. While it comes with certain complexities and considerations, mastering Batch Apex opens the door to enhanced data processing capabilities, empowering organizations to harness the full potential of their Salesforce environments.

Manufacturing Cloud | Rebate Management - Order Record Activation Apex Batch Class

The salesforce rebate managemnt system helps customers to automate the review and payout process . The use of software also ensures timely, transparent payouts and frees up finance team members to do more complex tasks. Also, with Rebate Management, a company can customize the rebate program parameters to fit their needs.

The input to rebate management system is sales cloud Orders data . To process the orders data into rebate application is done via salesforce standard DPE engine ' Insert Orders Into Members Journal' . WHen DPE is executed on timely basis the Orders data with Order Line items are transfered from sales cloud order object with order products into rebate application staging object called ' Transactional Journal' .

The data from Transactional Journal is moved into rebate application product aggregate object for rebate  incentive processing in parallel execution with Rebate orchestration flows . 

Here we will delve into orders record automation on moving Order record with status 'Draft' into Activated status . The rebate engine only process Order record which are activated with Order Line items . The orders status could be Activated or Invoiced based on your system setup. 

We will discuss how to setup batch apex to process large datasets of Order records and change Order status from Draft to Activated . 

Apex Batch Class

Create an apex class which implements Database.Batchable interface and the class must be global

global class batchExample implements Database.Batchable<sObject> {}

Describe all batchable class method



The order records before the batch class execution . The order status are in DRAFT status . 



Here is the Batch class to update the Order Status from Draft to Activated.

    /**

        * Navneet Kamat .

        * Copyright (c) https://navneetkamat.blogspot.com/

    */

global class AutoActivatedOrdersBatch implements Database.Batchable<sObject>

{

    global Database.QueryLocator start(Database.BatchableContext BC) {

        // Get collection of records

        String query = 'SELECT Id,Name,status FROM Order';

        return Database.getQueryLocator(query);

    }

    global void execute(Database.BatchableContext BC, List<Order> ordList) { 

        // To do the required processing for each chunk of data, use the execute method

        List<Order> ordToUpdate = new List<Order>();

        for(Order ord : ordList)

        if(ord.status=='Draft')

        {        

               // Update the Order status to Activated if the current status id Draft only. 

            ord.Status = 'Activated';

            ordToUpdate.add(ord);

        }

        try {

            // Update the Order Record

            update ordToUpdate;

        } catch(Exception e) {

            System.debug(e);

        }

    }   

    global void finish(Database.BatchableContext BC) {

        // execute any post-processing operations

  }

}

 





Execute the BATCHABLE Class in Developer Console.

To invoke a batch class, we need to  instantiate it and then call Database.executeBatch with the instance as shown below .

 AutoActivatedOrdersBatch Ord= new AutoActivatedOrdersBatch();
database.executeBatch(Ord);   

The batch will be executed and can be seen in Apex Jobs . 



The order records after the batch class execution . The order status are in Activated status . 





batchExample be = new batchExample();
database.executeBatch(be);
 global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
    }

    global void execute(Database.BatchableContext bc, List<P> records){
        // process each batch of records
    }    

    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }    
 global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
    }

    global void execute(Database.BatchableContext bc, List<P> records){
        // process each batch of records
    }    

    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }    

Comments