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
Sudeep SinghSudeep Singh 

When order is created using batch at that time Order Status should be "Order Placed" instead Draft

I have written a batch which is creating order and order item when contract status activated.
When the order is created the status field is showing "Draft" which is giving default value as we cannot change anything while creating order.

So, I need to set that Status to "Order Placed" instead of "Draft".

Here is the Batch :- 

/* Class Type :- Batch
* Date :- 
* Description :- Creates a new order if Contract Status is Activated after one month and update Next Order Date
* Author :- 
*/ 
global class AutoSubscriptionForOrderCreation implements Database.Batchable<sObject>,schedulable {
    Public void execute(SchedulableContext sc) 
    { 
        database.executebatch(new AutoSubscriptionForOrderCreation());
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date orderCreationDate = system.today().addDays(3);
        //system.debug('output'+[SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,ShippingAddress,BillingAddress,Insurance__c From Contract Where Status = 'Activated' And Next_Order_Date__c = TODAY]);
        if(Test.isRunningTest()){
            return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,account.PersonContactId,ShippingAddress,BillingAddress,Insurance__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract]);
        }else{
           return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,account.PersonContactId,ShippingAddress,BillingAddress,Insurance__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract Where Status = 'Activated' And Next_Order_Date__c =: orderCreationDate]); 
        }
    }
    
    global void execute(Database.BatchableContext bc, List<Contract> contractlst) {
        List<Order> orderlsttoinsert = new List<Order>();
        List<OrderItem> orderItemsToInsert = new List<OrderItem>();
        List<Contract> contractupdatelst = new List<Contract>();
        map<Id, Id> contractProdMap = New map<Id, Id>();
        if(contractlst.size() > 0){
            
            Pricebook2 priceBook = [select id, name from Pricebook2 where isStandard = true limit 1];
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2.Id, Product2.Name, UnitPrice FROM PriceBookEntry WHERE Pricebook2Id =:priceBook.id];            
            //Set <Id> accid  = new set <Id>();
            //List
            for(Contract con: contractlst){
                //Insert Orders
                Order orderObj = new Order();
                orderObj.AccountId = con.AccountId;
                orderObj.Status = 'Draft';
                orderObj.ContractId = con.Id;
                orderObj.EffectiveDate = System.today();
                orderObj.Pricebook2Id =  priceBook.id;
                orderObj.Insurance__c =  con.Insurance__c;
                orderObj.Type = 'Subscription Order';
                orderObj.BillingStreet = con.BillingStreet;
                orderObj.BillingState = con.BillingState;
                orderObj.BillingCity = con.BillingCity;
                orderObj.BillingCountry = con.BillingCountry;
                orderObj.BillingPostalCode = con.BillingPostalCode;
                orderObj.BillingLatitude = con.BillingLatitude;
                orderObj.BillingLongitude = con.BillingLongitude;
                orderObj.ShippingStreet = con.ShippingStreet;
                orderObj.ShippingState = con.ShippingState;
                orderObj.ShippingCity = con.ShippingCity;
                orderObj.ShippingCountry = con.ShippingCountry;
                orderObj.ShippingPostalCode = con.ShippingPostalCode;
                orderObj.ShippingLatitude = con.ShippingLatitude;
                orderObj.ShippingLongitude = con.ShippingLongitude;
                orderObj.ShipToContactId =con.account.PersonContactId; 
                orderObj.BillToContactId = con.account.PersonContactId;
                orderObj.EffectiveDate = con.Next_Order_Date__c;
                orderlsttoinsert.add(orderObj);
                
                //Create Contract and Product Map
                for(PriceBookEntry pBookEntry : priceBookEntryList){
                    if(pBookEntry.Product2.Id == con.Service__r.Id){
                        contractProdMap.put(con.Id, pBookEntry.Id);
                    }
                }
                
                // Update order date to next month's nearest Wednesday
                Date nextOrderDate = ((System.today().addMonths(1)).toStartOfWeek().addDays(3));
                con.Next_Order_Date__c = nextOrderDate;
                contractupdatelst.add(con);
                
            }
            if(orderlsttoinsert.size() > 0){
                insert orderlsttoinsert;               
                for(Order O: orderlsttoinsert){
                    //Insert Order Items
                    OrderItem oi = new OrderItem();
                    oi.OrderId = O.id;
                    oi.Quantity = 1;
                    oi.UnitPrice = 1;
                    oi.Product2id = O.Contract.Service__c;
                    oi.PricebookEntryId = contractProdMap.get(O.ContractId);
                    oi.sstation__Currency_Type__c = 'USD';
                    orderItemsToInsert.add(oi);
                }    
            }
            if(orderItemsToInsert.size() > 0){
                insert orderItemsToInsert;
            }
            if(contractupdatelst.size() > 0){
                update contractupdatelst;
            }
        }
    }    
    global void finish(Database.BatchableContext bc) {
        
    }
}
Best Answer chosen by Sudeep Singh
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sudeep,

Can you try code as below.
 
/* Class Type :- Batch
* Date :- 
* Description :- Creates a new order if Contract Status is Activated after one month and update Next Order Date
* Author :- 
*/ 
global class AutoSubscriptionForOrderCreation implements Database.Batchable<sObject>,schedulable {
    Public void execute(SchedulableContext sc) 
    { 
        database.executebatch(new AutoSubscriptionForOrderCreation());
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date orderCreationDate = system.today().addDays(3);
        //system.debug('output'+[SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,ShippingAddress,BillingAddress,Insurance__c From Contract Where Status = 'Activated' And Next_Order_Date__c = TODAY]);
        if(Test.isRunningTest()){
            return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,account.PersonContactId,ShippingAddress,BillingAddress,Insurance__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract]);
        }else{
           return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,account.PersonContactId,ShippingAddress,BillingAddress,Insurance__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract Where Status = 'Activated' And Next_Order_Date__c =: orderCreationDate]); 
        }
    }
    
    global void execute(Database.BatchableContext bc, List<Contract> contractlst) {
        List<Order> orderlsttoinsert = new List<Order>();
        List<OrderItem> orderItemsToInsert = new List<OrderItem>();
        List<Contract> contractupdatelst = new List<Contract>();
        List<Order> ordertoupdate= new List<Order>();
        map<Id, Id> contractProdMap = New map<Id, Id>();
        if(contractlst.size() > 0){
            
            Pricebook2 priceBook = [select id, name from Pricebook2 where isStandard = true limit 1];
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2.Id, Product2.Name, UnitPrice FROM PriceBookEntry WHERE Pricebook2Id =:priceBook.id];            
            //Set <Id> accid  = new set <Id>();
            //List
            for(Contract con: contractlst){
                //Insert Orders
                Order orderObj = new Order();
                orderObj.AccountId = con.AccountId;
                orderObj.Status = 'Draft';
                orderObj.ContractId = con.Id;
                orderObj.EffectiveDate = System.today();
                orderObj.Pricebook2Id =  priceBook.id;
                orderObj.Insurance__c =  con.Insurance__c;
                orderObj.Type = 'Subscription Order';
                orderObj.BillingStreet = con.BillingStreet;
                orderObj.BillingState = con.BillingState;
                orderObj.BillingCity = con.BillingCity;
                orderObj.BillingCountry = con.BillingCountry;
                orderObj.BillingPostalCode = con.BillingPostalCode;
                orderObj.BillingLatitude = con.BillingLatitude;
                orderObj.BillingLongitude = con.BillingLongitude;
                orderObj.ShippingStreet = con.ShippingStreet;
                orderObj.ShippingState = con.ShippingState;
                orderObj.ShippingCity = con.ShippingCity;
                orderObj.ShippingCountry = con.ShippingCountry;
                orderObj.ShippingPostalCode = con.ShippingPostalCode;
                orderObj.ShippingLatitude = con.ShippingLatitude;
                orderObj.ShippingLongitude = con.ShippingLongitude;
                orderObj.ShipToContactId =con.account.PersonContactId; 
                orderObj.BillToContactId = con.account.PersonContactId;
                orderObj.EffectiveDate = con.Next_Order_Date__c;
                orderlsttoinsert.add(orderObj);
                
                //Create Contract and Product Map
                for(PriceBookEntry pBookEntry : priceBookEntryList){
                    if(pBookEntry.Product2.Id == con.Service__r.Id){
                        contractProdMap.put(con.Id, pBookEntry.Id);
                    }
                }
                
                // Update order date to next month's nearest Wednesday
                Date nextOrderDate = ((System.today().addMonths(1)).toStartOfWeek().addDays(3));
                con.Next_Order_Date__c = nextOrderDate;
                contractupdatelst.add(con);
                
            }
            if(orderlsttoinsert.size() > 0){
                insert orderlsttoinsert;  
                           
                for(Order O: orderlsttoinsert){
                    //Insert Order Items
                    OrderItem oi = new OrderItem();
                    oi.OrderId = O.id;
                    oi.Quantity = 1;
                    oi.UnitPrice = 1;
                    oi.Product2id = O.Contract.Service__c;
                    oi.PricebookEntryId = contractProdMap.get(O.ContractId);
                    oi.sstation__Currency_Type__c = 'USD';
                    orderItemsToInsert.add(oi);
                }    
            }
            if(orderItemsToInsert.size() > 0){
                insert orderItemsToInsert;
            }
            if(contractupdatelst.size() > 0){
                update contractupdatelst;
            }
            if(orderlsttoinsert.size() > 0){
            for(Order Or: orderlsttoinsert){
                Or.Status='Order Placed';
                ordertoupdate.add(Or);
            } 
            update ordertoupdate; 
        }   
        }
    }    
    global void finish(Database.BatchableContext bc) {
        
    }
}

Thanks,
 

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sudeep ,

In the above code just replace "orderObj.Status = 'Draft';" with  orderObj.status='Order Placed'; .

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
Sudeep SinghSudeep Singh
I tried but it is not happening
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sudeep,

What do you meant by not happening. Is the record not getting created or are you facing any issue?

Thanks,
 
Sudeep SinghSudeep Singh

It is throwing error 13:31:02:039 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FAILED_ACTIVATION, Choose a valid status and save your changes. For a new or cloned order, choose Draft. An Activated order's status can't be edited.: [Status]

 

Thanks

Sai PraveenSai Praveen (Salesforce Developers) 
Hi sudeep,

In this scenerio you have to create order with Draft status and update them in the same batch to "Order Placed" status.
Can you  try it.

Thanks,
 
Sudeep SinghSudeep Singh
Where shall I modfy with code not getting

Thanks
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sudeep,

Can you try as below.
/* Class Type :- Batch
* Date :- 
* Description :- Creates a new order if Contract Status is Activated after one month and update Next Order Date
* Author :- 
*/ 
global class AutoSubscriptionForOrderCreation implements Database.Batchable<sObject>,schedulable {
    Public void execute(SchedulableContext sc) 
    { 
        database.executebatch(new AutoSubscriptionForOrderCreation());
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date orderCreationDate = system.today().addDays(3);
        //system.debug('output'+[SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,ShippingAddress,BillingAddress,Insurance__c From Contract Where Status = 'Activated' And Next_Order_Date__c = TODAY]);
        if(Test.isRunningTest()){
            return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,account.PersonContactId,ShippingAddress,BillingAddress,Insurance__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract]);
        }else{
           return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,account.PersonContactId,ShippingAddress,BillingAddress,Insurance__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract Where Status = 'Activated' And Next_Order_Date__c =: orderCreationDate]); 
        }
    }
    
    global void execute(Database.BatchableContext bc, List<Contract> contractlst) {
        List<Order> orderlsttoinsert = new List<Order>();
        List<OrderItem> orderItemsToInsert = new List<OrderItem>();
        List<Contract> contractupdatelst = new List<Contract>();
        List<Order> ordertoupdate= new List<Order>();
        map<Id, Id> contractProdMap = New map<Id, Id>();
        if(contractlst.size() > 0){
            
            Pricebook2 priceBook = [select id, name from Pricebook2 where isStandard = true limit 1];
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2.Id, Product2.Name, UnitPrice FROM PriceBookEntry WHERE Pricebook2Id =:priceBook.id];            
            //Set <Id> accid  = new set <Id>();
            //List
            for(Contract con: contractlst){
                //Insert Orders
                Order orderObj = new Order();
                orderObj.AccountId = con.AccountId;
                orderObj.Status = 'Draft';
                orderObj.ContractId = con.Id;
                orderObj.EffectiveDate = System.today();
                orderObj.Pricebook2Id =  priceBook.id;
                orderObj.Insurance__c =  con.Insurance__c;
                orderObj.Type = 'Subscription Order';
                orderObj.BillingStreet = con.BillingStreet;
                orderObj.BillingState = con.BillingState;
                orderObj.BillingCity = con.BillingCity;
                orderObj.BillingCountry = con.BillingCountry;
                orderObj.BillingPostalCode = con.BillingPostalCode;
                orderObj.BillingLatitude = con.BillingLatitude;
                orderObj.BillingLongitude = con.BillingLongitude;
                orderObj.ShippingStreet = con.ShippingStreet;
                orderObj.ShippingState = con.ShippingState;
                orderObj.ShippingCity = con.ShippingCity;
                orderObj.ShippingCountry = con.ShippingCountry;
                orderObj.ShippingPostalCode = con.ShippingPostalCode;
                orderObj.ShippingLatitude = con.ShippingLatitude;
                orderObj.ShippingLongitude = con.ShippingLongitude;
                orderObj.ShipToContactId =con.account.PersonContactId; 
                orderObj.BillToContactId = con.account.PersonContactId;
                orderObj.EffectiveDate = con.Next_Order_Date__c;
                orderlsttoinsert.add(orderObj);
                
                //Create Contract and Product Map
                for(PriceBookEntry pBookEntry : priceBookEntryList){
                    if(pBookEntry.Product2.Id == con.Service__r.Id){
                        contractProdMap.put(con.Id, pBookEntry.Id);
                    }
                }
                
                // Update order date to next month's nearest Wednesday
                Date nextOrderDate = ((System.today().addMonths(1)).toStartOfWeek().addDays(3));
                con.Next_Order_Date__c = nextOrderDate;
                contractupdatelst.add(con);
                
            }
            if(orderlsttoinsert.size() > 0){
                insert orderlsttoinsert;  
                for(Order Or: orderlsttoinsert){
                    Or.Status='Order Placed';
                    ordertoupdate.add(Or);
                } 
                update ordertoupdate;                
                for(Order O: orderlsttoinsert){
                    //Insert Order Items
                    OrderItem oi = new OrderItem();
                    oi.OrderId = O.id;
                    oi.Quantity = 1;
                    oi.UnitPrice = 1;
                    oi.Product2id = O.Contract.Service__c;
                    oi.PricebookEntryId = contractProdMap.get(O.ContractId);
                    oi.sstation__Currency_Type__c = 'USD';
                    orderItemsToInsert.add(oi);
                }    
            }
            if(orderItemsToInsert.size() > 0){
                insert orderItemsToInsert;
            }
            if(contractupdatelst.size() > 0){
                update contractupdatelst;
            }
        }
    }    
    global void finish(Database.BatchableContext bc) {
        
    }
}


Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
Sudeep SinghSudeep Singh
No Its not working as expected

Thanks
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sudeep,

Are you getting any error. Can you share it.

Thanks,
 
Sudeep SinghSudeep Singh

13:54:23:057 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FAILED_ACTIVATION, Choose a valid status and save your changes. For a new or cloned order, choose Draft. An Activated order's status can't be edited.: [Status]

 

That same only

Sudeep SinghSudeep Singh
Hi Sai

Any Solution for this

Thanks
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sudeep,

The solution above should work. Please find the similar solution (https://salesforce.stackexchange.com/questions/218186/how-to-set-the-status-on-order-to-activated-in-test-code) for this.

Thanks,
 
Sudeep SinghSudeep Singh
Except highlighted text is there anything else that u added in the above code
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sudeep,

Yes I have updated the code now. Can you check. You can copy paste tne entire code. I just added the code needed to your code.

Thanks,

 
Sudeep SinghSudeep Singh

14:33:38:088 FATAL_ERROR System.DmlException: Update failed. First exception on row 0 with id 8018L000000JoSPQA0; first error: FAILED_ACTIVATION, An order must have at least one product.: []

 

After pasting your whole code this error is coming

Thanks

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sudeep,

Can you try code as below.
 
/* Class Type :- Batch
* Date :- 
* Description :- Creates a new order if Contract Status is Activated after one month and update Next Order Date
* Author :- 
*/ 
global class AutoSubscriptionForOrderCreation implements Database.Batchable<sObject>,schedulable {
    Public void execute(SchedulableContext sc) 
    { 
        database.executebatch(new AutoSubscriptionForOrderCreation());
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date orderCreationDate = system.today().addDays(3);
        //system.debug('output'+[SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,ShippingAddress,BillingAddress,Insurance__c From Contract Where Status = 'Activated' And Next_Order_Date__c = TODAY]);
        if(Test.isRunningTest()){
            return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,account.PersonContactId,ShippingAddress,BillingAddress,Insurance__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract]);
        }else{
           return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,account.PersonContactId,ShippingAddress,BillingAddress,Insurance__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract Where Status = 'Activated' And Next_Order_Date__c =: orderCreationDate]); 
        }
    }
    
    global void execute(Database.BatchableContext bc, List<Contract> contractlst) {
        List<Order> orderlsttoinsert = new List<Order>();
        List<OrderItem> orderItemsToInsert = new List<OrderItem>();
        List<Contract> contractupdatelst = new List<Contract>();
        List<Order> ordertoupdate= new List<Order>();
        map<Id, Id> contractProdMap = New map<Id, Id>();
        if(contractlst.size() > 0){
            
            Pricebook2 priceBook = [select id, name from Pricebook2 where isStandard = true limit 1];
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2.Id, Product2.Name, UnitPrice FROM PriceBookEntry WHERE Pricebook2Id =:priceBook.id];            
            //Set <Id> accid  = new set <Id>();
            //List
            for(Contract con: contractlst){
                //Insert Orders
                Order orderObj = new Order();
                orderObj.AccountId = con.AccountId;
                orderObj.Status = 'Draft';
                orderObj.ContractId = con.Id;
                orderObj.EffectiveDate = System.today();
                orderObj.Pricebook2Id =  priceBook.id;
                orderObj.Insurance__c =  con.Insurance__c;
                orderObj.Type = 'Subscription Order';
                orderObj.BillingStreet = con.BillingStreet;
                orderObj.BillingState = con.BillingState;
                orderObj.BillingCity = con.BillingCity;
                orderObj.BillingCountry = con.BillingCountry;
                orderObj.BillingPostalCode = con.BillingPostalCode;
                orderObj.BillingLatitude = con.BillingLatitude;
                orderObj.BillingLongitude = con.BillingLongitude;
                orderObj.ShippingStreet = con.ShippingStreet;
                orderObj.ShippingState = con.ShippingState;
                orderObj.ShippingCity = con.ShippingCity;
                orderObj.ShippingCountry = con.ShippingCountry;
                orderObj.ShippingPostalCode = con.ShippingPostalCode;
                orderObj.ShippingLatitude = con.ShippingLatitude;
                orderObj.ShippingLongitude = con.ShippingLongitude;
                orderObj.ShipToContactId =con.account.PersonContactId; 
                orderObj.BillToContactId = con.account.PersonContactId;
                orderObj.EffectiveDate = con.Next_Order_Date__c;
                orderlsttoinsert.add(orderObj);
                
                //Create Contract and Product Map
                for(PriceBookEntry pBookEntry : priceBookEntryList){
                    if(pBookEntry.Product2.Id == con.Service__r.Id){
                        contractProdMap.put(con.Id, pBookEntry.Id);
                    }
                }
                
                // Update order date to next month's nearest Wednesday
                Date nextOrderDate = ((System.today().addMonths(1)).toStartOfWeek().addDays(3));
                con.Next_Order_Date__c = nextOrderDate;
                contractupdatelst.add(con);
                
            }
            if(orderlsttoinsert.size() > 0){
                insert orderlsttoinsert;  
                           
                for(Order O: orderlsttoinsert){
                    //Insert Order Items
                    OrderItem oi = new OrderItem();
                    oi.OrderId = O.id;
                    oi.Quantity = 1;
                    oi.UnitPrice = 1;
                    oi.Product2id = O.Contract.Service__c;
                    oi.PricebookEntryId = contractProdMap.get(O.ContractId);
                    oi.sstation__Currency_Type__c = 'USD';
                    orderItemsToInsert.add(oi);
                }    
            }
            if(orderItemsToInsert.size() > 0){
                insert orderItemsToInsert;
            }
            if(contractupdatelst.size() > 0){
                update contractupdatelst;
            }
            if(orderlsttoinsert.size() > 0){
            for(Order Or: orderlsttoinsert){
                Or.Status='Order Placed';
                ordertoupdate.add(Or);
            } 
            update ordertoupdate; 
        }   
        }
    }    
    global void finish(Database.BatchableContext bc) {
        
    }
}

Thanks,
 
This was selected as the best answer
Sudeep SinghSudeep Singh

Hi Sai,
Now its working fine but when am running the test class for the code coverage this error is coming :- 

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [PricebookEntryId]: [PricebookEntryId]
Class.AutoSubscriptionForOrderCreation.execute: line 91, column 1

Thanks

Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

If the above solution helps please mark it as best answer. For test class can you share apex class and test class as new question so I can check and let you know. Also share the error with the line number as well.

Thanks
 
Sudeep SinghSudeep Singh
Test Class is failing but giving code coverage ,,, How its possible ?
 
Sudeep SinghSudeep Singh
I had added an question can u please revert
Sudeep SinghSudeep Singh
Hi Sai,

Please revert in my another que