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
Amanda Bruce 11Amanda Bruce 11 

Help with APEX Code to update a field

Hi There, I need some help to write some APEX, my developer skills are very limited.  We have a field called Total_Recurring__c . When a new order is created we want to take the Total_Recurring__c and update Previous_Months_Total__c . The end goal is to see the current total and the previous month's total 
RajeshPunjabiRajeshPunjabi
Hi Amanda,

So you like to get Previous_Months_Total__c from previous order or from somewhere else? Where is that value resides?

Please provide more details and you may not have to write any code.

Thanks.



 
Amanda Bruce 11Amanda Bruce 11
We have apex code that looks at contracts and if a contract is active each month a new order is created. When the new order is created we would like to know what the previous month's total was on the current months order so we can compare the previous total to the current total
Amanda Bruce 11Amanda Bruce 11
I tried to work with Salesforce Support on this but they could not find a way to make this possible without using some code. 
RajeshPunjabiRajeshPunjabi
Hi Amanda,

Allow me sometime, I will send you code.

If you can provide me following:

Table name for Contract and Order
Field:
Order Id
Order Number
Contact Id field on Order
Status (list of values/picklist)
any date field being used.

Regards,
Raj



 
Amanda Bruce 11Amanda Bruce 11
Thank you so much! Here is the information below: 
Table Name Contract: Contract
Table Name Order:  Opportunity

Field Names on Order: 
Opportunity type (formula): Order 
Order Number: Order_Number__c
Contact (Lookup): Field Name: Contract
Date Fields(lookup): CreatedBy
Account ID: ia_crm__SFDC_Account_Id__c
ContractID: ia_crm__SFDC_Contract_Id__c
OpportunityID: ia_crm__SFDC_Opportunity_Id__c
Total Quantity: Total_Quantity__c  - this field should populate the (Previous_Month_s_Quantity__c) when a new order is created
Total Reoccouring: Total_Recurring__c - this field should populate the (Previous_Month_s_Revenue__c) when a new order is created

Field Names on Contract
Next Bill Cycle Date: Next_Bill_Cycle_Date__c
Last Order Created Date: Last_Order_Created_Date__c

Here are the fields we need to get populated via the Apex Code
Previous_Month_s_Quantity__c
Previous_Month_s_Revenue__c

Let me know if you need anything else. 

I appreciate your help so much 
RajeshPunjabiRajeshPunjabi
Hi Amanda,

A quick confirmation, Order creation is manual?

Regards,
Raj
Amanda Bruce 11Amanda Bruce 11
Hi Raj,

The order is created via a trigger in our Salesforce Instance, on the 1st of every month. Hope that helps. 
RajeshPunjabiRajeshPunjabi
Hi Amanda,

Can you please share Trigger, will add the logic into it. Will send you by today.

Regards,
Raj
Amanda Bruce 11Amanda Bruce 11
Hi Raj,

Thank you so much for your help! This is our trigger logic to batch create orders. 

global class BatchCreateOrders implements Database.Batchable<sObject>, Database.Stateful, Schedulable {
    
    global Map<Id, User> activeUsers;

    global BatchCreateOrders(){
        activeUsers = new Map<Id, User>([SELECT Id FROM User WHERE IsActive = true]);
    }

    public static void scheduleMe() {

        BatchCreateOrders sch = new BatchCreateOrders();
        String cron = '0 0 1 1 * ?';
        String title = 'Create Orders';
        if(Test.isRunningTest()) title = 'Test Create Orders Test';
        System.schedule(title, cron, sch);    
    }
    
    public void execute(SchedulableContext sc){
        BatchCreateOrders sch = new BatchCreateOrders();
        Database.executeBatch(sch, 200);
    }
  
    public Database.QueryLocator start(Database.BatchableContext BC) {
    
    return Database.getQueryLocator([SELECT Id, 
                                            Status, 
                                            EndDate,
                                            AccountId,
                                            Account.Name,
                                            OwnerId,
                                            OverrideBill__c,
                                            Next_Bill_Cycle_Date__c,
                                            Pricebook2Id,
                                            Pricebook2.Default_Opportunity_Owner__c,
                                            Pricebook2.Approval_Process__c,
                                            Bill_to_Contact__c,
                                            Contract_Contact__c, 
                                            Bill_To__c,
                                            Bill_to_Account__c,
                                         ad_campaign_id__c,
                                         campaign_name__c,
                                         Po_reference_number__c
                                    FROM Contract 
                                    WHERE Next_Bill_Cycle_Date__c = :System.today()
                                    OR OverrideBill__c = true]);
    }

    public void execute(Database.BatchableContext BC, List<Contract> scope) {

        Map<Id, List<OpportunityLineItem>> contToAllActiveItems = new Map<Id, List<OpportunityLineItem>>();
        for(OpportunityLineItem oli : [SELECT Id, OpportunityId, Opportunity.Created_Contract__c, UnitPrice, Discount, Quantity, PricebookEntryId, description, multiplier__c, OppLineItemID__c FROM OpportunityLineItem WHERE Active__c = true AND Opportunity.IsWon = true AND Opportunity.Created_Contract__c IN :scope]){
            OpportunityLineItem[] activeItemsUnderThisCont = new OpportunityLineItem[]{oli};
            if(contToAllActiveItems.containsKey(oli.Opportunity.Created_Contract__c)) activeItemsUnderThisCont.addAll(contToAllActiveItems.get(oli.Opportunity.Created_Contract__c));
            contToAllActiveItems.put(oli.Opportunity.Created_Contract__c, activeItemsUnderThisCont);
        }

        Map<Id, Opportunity> contToNewOpp = new Map<Id, Opportunity>();
        Map<Id, List<OpportunityLineItem>> contToNewItems = new Map<Id, List<OpportunityLineItem>>();
        for(Contract c : scope){
            if(contToAllActiveItems.containsKey(c.Id)){
                contToNewOpp.put(c.Id, new Opportunity(Name = 'Order - ' + System.today().month() + '/' + System.today().day() + '/' + System.today().year() + ' - ' + c.Account.Name, RecordTypeId = '0124A000001NT0xQAG', StageName = 'Pending', CloseDate = System.today(), AccountId = c.AccountId, Contract__c = c.Id, Pricebook2Id = c.Pricebook2Id, OwnerId = activeUsers.containsKey(c.OwnerId) ? c.OwnerId : c.Pricebook2.Default_Opportunity_Owner__c, ia_crm__Bill_to__c = c.Bill_to_Contact__c, ia_crm__Ship_to__c = c.Contract_Contact__c, Bill_To__c = c.Bill_To__c, ia_crm__Intacct_Entity__c= 'a3Z4A000000RKoF', ia_crm__Bill_to_Account__c = c.Bill_To_Account__c, ad_campaign_ID__c =c.ad_campaign_id__c, campaign_name__c=c.campaign_name__c, PO_reference_number__c = c.po_reference_number__c));
                OpportunityLineItem[] newItemsForThisOpp = new OpportunityLineItem[]{};
                for(OpportunityLineItem oli : contToAllActiveItems.get(c.Id)){
                    newItemsForThisOpp.add(new OpportunityLineItem(PricebookEntryId = oli.PricebookEntryId, UnitPrice = oli.UnitPrice, Quantity = oli.Quantity*oli.Multiplier__c, Discount = oli.Discount, Description = oli.Description, lineUUID__c = oli.OppLineItemID__c));
                }
                contToNewItems.put(c.Id, newItemsForThisOpp);
            }
        }

        if(!contToNewOpp.isEmpty()){
            insert contToNewOpp.values();
            OpportunityLineItem[] allNewLineItems = new OpportunityLineItem[]{};
            for(Id cId : contToNewOpp.keySet()){
                if(contToNewItems.containsKey(cId)){
                    for(OpportunityLineItem oli : contToNewItems.get(cId)){
                        oli.OpportunityId = contToNewOpp.get(cId).Id;
                        allNewLineItems.add(oli);
                    }
                }
            }
            if(!allNewLineItems.isEmpty()) insert allNewLineItems;

            Approval.ProcessRequest[] allRequests = new Approval.ProcessRequest[]{};
            for(Contract c : scope){
                if(contToNewOpp.containsKey(c.Id)){
                    if(c.Pricebook2.Approval_Process__c != null){
                        Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
                        req.setObjectId(contToNewOpp.get(c.Id).Id);
                        req.setProcessDefinitionNameOrId(c.Pricebook2.Approval_Process__c);
                        req.setSkipEntryCriteria(true);
                        req.setSubmitterId(contToNewOpp.get(c.Id).OwnerId);
                        allRequests.add(req);
                    }
                }
            }

            if(!allRequests.isEmpty()){
                Approval.ProcessResult[] results = Approval.process(allRequests,false);
                for(Approval.ProcessResult r : results){
                    if(!r.isSuccess()) System.debug(r.getErrors());
                }
            }
        }
        
        for(Contract c : scope){
            c.OverrideBill__c = false;
            c.Last_Order_Created_Date__c = System.today();
        }
        if(!scope.isEmpty()) update scope;

    }
  
    public void finish(Database.BatchableContext BC){}  

}
Amanda Bruce 11Amanda Bruce 11
Let me know if you need any more information 
Amanda Bruce 11Amanda Bruce 11
Hi Raj, Just wondering if you needed anything further from me on this? Thank you so much for your help. 
Amanda Bruce 11Amanda Bruce 11
Hi Raj,

Just wondering if you were still able to help me with this?