+ Start a Discussion
EQ AdminEQ Admin 

Need help in Nested Loop Optimization . Hw can i implement this by map

for(Apttus_Billing__Invoice__c invoice:invoiceObjectList1) // loop over invoices
              {
                  List<InvoiceLineItems> listToStoreLineItems = new List<InvoiceLineItems>();
                  APTS_InvoiceJournalWrapper invoiceJournWrapper= new APTS_InvoiceJournalWrapper();
                   countHeader=0;
                   
                   count=count+1;
                  Decimal Sum=0;
                   
                                    invoiceJournWrapper.id=String.valueof(invoice.id);
                                    invoiceJournWrapper.HeaderKey=String.valueof(count);
                                    invoiceJournWrapper.ZCurrency=(invoice.CurrencyIsoCode!=null?invoice.CurrencyIsoCode:'USD');
                                    //invoiceJournWrapper.AccountingJournal='null';
                                    invoiceJournWrapper.AccountingJournalID=String.valueOf(invoice.Name + '_' +myDate);
                                    invoiceJournWrapper.JournalNumber=String.valueOf(invoice.Name + '_' +myDate);
                                    invoiceJournWrapper.ExternalReferenceID=String.valueOf(invoice.Name);                  
                                    invoiceJournWrapper.AccountingDate=String.valueof(Date.valueof(invoice.Apttus_Billing__InvoiceDate__c));
                  //-------------------
                  list<Apttus_Billing__InvoiceLineItem__c> invlineitems=[Select id,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode,Apttus_Billing__InvoiceId__r.Name,Apttus_Billing__ProductId__r.Name,Apttus_Billing__InvoiceId__r.CurrencyIsoCode,
                                                                      Apttus_Billing__Type__c,Apttus_Billing__InvoiceId__c,Name,Apttus_Billing__Amount__c,Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c,Apttus_Billing__LocationId__c,
                                                                      Apttus_Billing__ProductId__r.EQ_FeeCode__c,Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c,Apttus_Billing__ProductId__r.ProductCode,Apttus_Billing__InvoiceId__r.EQ_TotalInvoiceAmount__c 
                                                             from Apttus_Billing__InvoiceLineItem__c where Apttus_Billing__InvoiceId__c=:invoice.id and Apttus_Billing__Type__c='Contracted' and Apttus_Billing__Amount__c!=0];
                  //----
                  //
                  //-------------
                   InvoiceLineItems FirstInvItems= new InvoiceLineItems();
                            countHeader=countHeader+1;
                            FirstInvItems.LineKey=string.valueof(countHeader);

 
Best Answer chosen by EQ Admin
paul diracpaul dirac
I find some errors and the code does not compile (i mocked all of your custom object but anyway there might be some sintax errors).
Consider to split some "iterative tasks" in an helper (static) class, since your Rest service might grows in future, developers (you too ofc) may encounter difficulties to maintain that. For example, that part in which lineItems are collected and then modified can be delegated to the helper class to enhance code readability.
Further little optization can be done storing fixed numbers/strings in costants but I guess that there are not any improvements that significately reduce the execution time, I mean the optimization I will want to see here is in code readability first. Hope I helped you to solve your cancerns!

All Answers

paul diracpaul dirac
The problem here is that query inside the loop (there is a missing bracket so it's not 100% clear where the loop ends).
I modifyed the query for readability, please check if it's correct before run the code.
First of all keep your filter in a String/Id list in order to minimize the records access. To keep track of your record use a second list of type Apttus_Billing_Invoice__c  and wrap them in a map:
 
Map<String,Apttus_Billing_Invoice__c > idMap = new Map<String.Apttus_Billing_Invoice__c >();
for(Apttus_Billing_Invoice__c i : invoiceObjectList){
idList.put(i.id,Apttus_Billing_Invoice__c),//the keyset String list is your query filter at the end of the loop
}
Then you will able to do a consistent filter in the WHERE clause:
 
list<Apttus_Billing__InvoiceLineItem__c> invlineitems=[SELECT id,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode,Apttus_Billing__InvoiceId__r.Name,Apttus_Billing__ProductId__r.Name,Apttus_Billing__InvoiceId__r.CurrencyIsoCode,
Apttus_Billing__Type__c,Apttus_Billing__InvoiceId__c,Name,Apttus_Billing__Amount__c,Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c,Apttus_Billing__LocationId__c,

Apttus_Billing__ProductId__r.EQ_FeeCode__c,Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c,Apttus_Billing__ProductId__r.ProductCode,Apttus_Billing__InvoiceId__r.EQ_TotalInvoiceAmount__c

FROM Apttus_Billing__InvoiceLineItem__c 
WHERE (Apttus_Billing__InvoiceId__c IN: idMap.keyset() and Apttus_Billing__Type__c='Contracted' and Apttus_Billing__Amount__c!=0]);

So even if your loop scans 10000 records the number of query performed during the script execution is always one. This is the simplest "optimization" you can do, but actually your code does not respect salesforce best practices.
Tell me if you need further help


Paul
EQ AdminEQ Admin
Thanks Paul.

I have already tried this one. Please see my code:

Expected output should be: 

But I am not getting the line items in correct order. It should be like : Invoice1 - All ites line items, Invoice2- All its line items .....
 
Expected :

    "Invoices"
        {
            "Id"
            "HeaderKey"
            "AddOnly"
            "CreateJournalWithErros"
            "AccountingJournal"
            "AutoComplete"
            "AccountingJournalID"
            "Submit"
            "JournalNumber"
            "Company"
            "Currency"
            "LedgerType"
            "BookCode"
           "AccountingDate"
            "JournalSource"
            "JournalEntryMemo"
            "ExternalReferenceID"
            "CreateReversal"
            "ReversalDate"
            "CurrencyRateType"
            "LineItems"
                {
                    "HeaderKey"
                    "LineKey"
                    "LineCompany"
                    "LedgerAccount"
                    "AccountSet"
                    "DebitAmount"
                    "CreditAmount"
                    "Currency"
                    "Memo"
                    "ExternalReferenceID"
                    "CostCenter"
                    "RevenueCategory"
                    "Product"
                    "SpendCategory"
                    "Project"
                    "Customer"
                    "Location"
                    "IssueNumber"
                    "InterCompanyAffiliate"
                    "IssueProductType"
                    "Supplier"
                    "TaxAmount"
                },
                {
                    "HeaderKey"
                    "LineKey"
                    "LineCompany"
                    "LedgerAccount"
                    "AccountSet"
                    "DebitAmount"
                    "CreditAmount"
                    "Currency"
                    "Memo"
                    "ExternalReferenceID"
                    "CostCenter"
                    "RevenueCategory"
                    "Product"
                    "SpendCategory"
                    "Project"
                    "Customer"
                    "Location"
                    "IssueNumber"
                    "InterCompanyAffiliate"
                    "IssueProductType"
                    "Supplier"
                    "TaxAmount"
                },


 
/**
 ─────────────────────────────────────────────────────────────────────────────────────────────────┐
* Webservice to return invoice details to workday.
* ──────────────────────────────────────────────────────────────────────────────────────────────────
* @author         surinder singh   <susingh@apttus.com>
* @modifiedBy     -
* @version        1.0
* @created        2019-12-22
* @modified Date  -
**/

        
    if(off<=MaximumNoOfPages_Invoice)
      {
   // ***************************OFFSET calculation with input "off"*******************************
       
          Integer varOff=0;
          If(off==1)
          {
              varOff =0;
          }
          else
          {
              varOff=varOff+lim*(off-1);
          }
   //*****************************************Closed************************************************      
       
         invoiceObjectList1=[Select id,Name,EQ_TotalInvoiceAmount__c,EQ_InvoiceApprovedDate__c,Apttus_Billing__TotalDueAmount__c,Apttus_billing__status__c,CurrencyIsoCode,Apttus_Billing__ShipToAccountId__r.EQ_ClientRef__c,Apttus_Billing__ShipToAccountId__r.EQ_ShippingState__c,Apttus_Billing__InvoiceDate__c,EQ_DueDateCustom__c,EQ_TotalTaxAmount__c from Apttus_Billing__Invoice__c where EQ_InvoiceApprovedDate__c>=:startDate and EQ_InvoiceApprovedDate__c<=:endDate and EQ_TotalInvoiceAmount__c > 0 and Apttus_billing__status__c='Approved' ORDER BY Name limit:lim offset:varOff]; 
         Integer count;
        count=0;
        system.debug('list of rec%%'+ invoiceObjectList1.size());
        map<ID,Apttus_Billing__Invoice__c> invmap= new map<ID,Apttus_Billing__Invoice__c>();
        map<ID,String> header= new map<ID,String>();
        map<ID,APTS_InvoiceJournalWrapper> mapInv= new map<ID,APTS_InvoiceJournalWrapper>();
         list<APTS_InvoiceJournalWrapper> invoiceJournWrapper1= new list<APTS_InvoiceJournalWrapper>();
          list<Apttus_Billing__Invoice__c> listInvoices= new list<Apttus_Billing__Invoice__c>();
          APTS_InvoiceJournalWrapper invoiceJournWrapper= new APTS_InvoiceJournalWrapper();
         for(Apttus_Billing__Invoice__c invoice:invoiceObjectList1) // loop over invoices
              {
                  
                  count=count+1;
                  Decimal Sum=0;
                   
                                    invoiceJournWrapper.id=String.valueof(invoice.id);
                                    invoiceJournWrapper.HeaderKey=String.valueof(count);
                                    invoiceJournWrapper.ZCurrency=(invoice.CurrencyIsoCode!=null?invoice.CurrencyIsoCode:'USD');
                                    //invoiceJournWrapper.AccountingJournal='null';
                                    invoiceJournWrapper.AccountingJournalID=String.valueOf(invoice.Name + '_' +myDate);
                                    invoiceJournWrapper.JournalNumber=String.valueOf(invoice.Name + '_' +myDate);
                                    invoiceJournWrapper.ExternalReferenceID=String.valueOf(invoice.Name);                  
                                    invoiceJournWrapper.AccountingDate=String.valueof(Date.valueof(invoice.Apttus_Billing__InvoiceDate__c));
                                    invmap.put(invoice.id,invoice);
                                    header.put(invoice.id,invoiceJournWrapper.HeaderKey);
                                    mapInv.put(invoice.id,invoiceJournWrapper);
                                    listInvoices.add(invoice);
                                    //invoiceObjectList1.add(invoiceJournWrapper);
                                    system.debug('@@@'+mapInv);
              }
 
            
             counterHeader=1;
            
            
              List<InvoiceLineItems> listToStoreLineItems = new List<InvoiceLineItems>();
            for(Apttus_Billing__InvoiceLineItem__c invlineitems:[Select id,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode,Apttus_Billing__InvoiceId__r.Name,Apttus_Billing__ProductId__r.Name,Apttus_Billing__InvoiceId__r.CurrencyIsoCode,
                                                                       Apttus_Billing__Type__c,Apttus_Billing__InvoiceId__c,Name,Apttus_Billing__Amount__c,Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c,Apttus_Billing__LocationId__c,
                                                                      Apttus_Billing__ProductId__r.EQ_FeeCode__c,Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c,Apttus_Billing__ProductId__r.ProductCode,Apttus_Billing__InvoiceId__r.EQ_TotalInvoiceAmount__c 
                                                             from Apttus_Billing__InvoiceLineItem__c where Apttus_Billing__InvoiceId__c IN:invmap.keyset() and Apttus_Billing__Type__c='Contracted' and Apttus_Billing__Amount__c!=0])
                 {
                     
                   
                    system.debug('^^^^6+ :entered');
                     if(counterHeader==1)
                     {
                          
                            InvoiceLineItems FirstInvItems= new InvoiceLineItems(); 
                            FirstInvItems.LineKey=string.valueof(counterHeader);
                            FirstInvItems.HeaderKey=String.valueof(mapInv.get(invlineitems.Apttus_Billing__InvoiceId__c).HeaderKey);
                            FirstInvItems.LedgerAccount='10106';
                            //FirstInvItems.DebitAmount=String.valueof((Sum*-1).setScale(2,RoundingMode.HALF_UP));
                            FirstInvItems.CreditAmount='';
                            FirstInvItems.RevenueCategory='RC900';
                            FirstInvItems.ZCurrency=invmap.get(invlineitems.Apttus_Billing__InvoiceId__c).CurrencyIsoCode;
                             FirstInvItems.ExternalReferenceID=invmap.get(invlineitems.Apttus_Billing__InvoiceId__c).Name;
                           if(invlineitems.Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c!=null)
                            {
                            FirstInvItems.Customer=invlineitems.Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c!=null?invlineitems.Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c:'';
                            }
                            else
                            {
                                FirstInvItems.Customer='';
                            }
                          listToStoreLineItems.add(FirstInvItems);
                          counterHeader=counterHeader+1;
                         system.debug('***********listToStoreLineItems'+listToStoreLineItems);
                     }
                     
                     else
                     {
                         
                            InvoiceLineItems InvItems= new InvoiceLineItems();
                            InvItems.LineKey=string.valueof(counterHeader);
                            InvItems.HeaderKey=String.valueof(header.get(invlineitems.Apttus_Billing__InvoiceId__c));
                            InvItems.LedgerAccount='40050';
                            InvItems.DebitAmount=('');
                            InvItems.CreditAmount=invlineitems.Apttus_Billing__Amount__c!=null?String.valueof((invlineitems.Apttus_Billing__Amount__c).setScale(2,RoundingMode.HALF_UP)):'';
                            // Sum=  invlineitems.Apttus_Billing__Amount__c+Sum;
                           InvItems.RevenueCategory='RC022';
                            InvItems.ZCurrency=(invlineitems.Apttus_Billing__InvoiceId__r.CurrencyIsoCode!=null?invlineitems.Apttus_Billing__InvoiceId__r.CurrencyIsoCode:'USD');
                            InvItems.Memo=invlineitems.Name;
                            InvItems.ExternalReferenceID= invmap.get(invlineitems.Apttus_Billing__InvoiceId__c).Name;
                            if(invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__c!=null)
                            {
                            InvItems.Product= (invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode!=null?invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode:'');
                            }
                           else
                            {
                            InvItems.Product= (invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode!=null?invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode:'');
                            }
                           // InvItems.Project='';
                            InvItems.Customer=(invlineitems.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c!=null?invlineitems.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c:'');
                           // InvItems.Location='';
                           // InvItems.InterCompanyAffiliate='';
                            //InvItems.IssueProductType='';
                            //InvItems.Supplier='';
                           // InvItems.TaxAmount='';
                           // InvItems.IssueNumber='';
                           counterHeader=counterHeader+1;
                            listToStoreLineItems.add(InvItems);
                            mapInv.get(invlineitems.Apttus_Billing__InvoiceId__c).InvoiceLineItems=listToStoreLineItems;
                            invoiceJournWrapper1.add(mapInv.get(invlineitems.Apttus_Billing__InvoiceId__c));
                             listToStoreJournInvoices=invoiceJournWrapper1;
                             system.debug('****************8listToStoreJournInvoices'+listToStoreJournInvoices);
                       }
                 }
                
           
        
         intWrap.Invoices =listToStoreJournInvoices;
         intWrap.TotalNumberOfInvoices=invoiceObjectList1.SIZE();  
         
          if((invoiceObjectList1.size()<=lim))
          {
              if(CMObjectListCount.size()>0)
              {
                 intWrap.MoreRecords='true'; 
              }
          }
          else
          {
                intWrap.MoreRecords='false';   
          }
         if (res == null) {
            res = new RestResponse();
            RestContext.response = res;
        }
        res.responseBody = Blob.valueOf(JSON.serialize(intWrap).replace('"ZCurrency":','"Currency":'));
       // res.responseBody = Blob.valueOf(JSON.serialize(intWrap));
          res.statusCode = 200;
   }    
        
    
     
 
 //------------------------------------------------------------------------------------------------------------------   


  //--------------------------------------------------------------GetJournals--------------------------------------------

 
paul diracpaul dirac
Hi EQ,
I suspect that the bahavior of the keyset() method (returning a Set<> and not a List, that means the elements belonging the container are not ordered, check this here : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_map.htm#apex_System_Map_keySet ) could change the order of your records.
What you can do is, before using keys in keyset(), to put your records from the keyset() to a List, that means you can obtain an ordered data structured since the List class do it for you.
The easiest way to fill the list is made using tha .addAll() method.
Let me know if this solve the issue.
 
EQ AdminEQ Admin
I tried with below approach:
Could you please review this code and let me know if  more optimization can be done. This is working correctly.
@RestResource(urlMapping='/WorkdayIntegration/GetJournalDetails/') 
global with sharing class APTS_GetJournalDetailsWS 
{
      
 @HttpPost
 global static void GetJournalDetails()
    { 
         "off"*******************************
       
          Integer varOff=0;
          If(off==1)
          {
              varOff =0;
          }
          else
          {
              varOff=varOff+lim*(off-1);
          }
   //*****************************************Closed************************************************      
       
         invoiceObjectList1=[Select id,Name,EQ_TotalInvoiceAmount__c,EQ_InvoiceApprovedDate__c,Apttus_Billing__TotalDueAmount__c,Apttus_billing__status__c,CurrencyIsoCode,Apttus_Billing__ShipToAccountId__r.EQ_ClientRef__c,Apttus_Billing__ShipToAccountId__r.EQ_ShippingState__c,Apttus_Billing__InvoiceDate__c,EQ_DueDateCustom__c,EQ_TotalTaxAmount__c from Apttus_Billing__Invoice__c where EQ_InvoiceApprovedDate__c>=:startDate and EQ_InvoiceApprovedDate__c<=:endDate and EQ_TotalInvoiceAmount__c > 0 and Apttus_billing__status__c='Approved' ORDER BY Name limit:lim offset:varOff]; 
         Integer count;
        count=0;
        
        map<ID,Apttus_Billing__Invoice__c> invmap= new map<ID,Apttus_Billing__Invoice__c>();
        map<ID,String> header= new map<ID,String>();
        map<ID,APTS_InvoiceJournalWrapper> mapInv= new map<ID,APTS_InvoiceJournalWrapper>();
         list<APTS_InvoiceJournalWrapper> invoiceJournWrapper1= new list<APTS_InvoiceJournalWrapper>();
          list<Apttus_Billing__Invoice__c> listInvoices= new list<Apttus_Billing__Invoice__c>();
          map<ID,Apttus_Billing__Invoice__c> map1= new map<ID,Apttus_Billing__Invoice__c>();
          map<ID,list<Apttus_Billing__InvoiceLineItem__c>> map2= new map<ID,list<Apttus_Billing__InvoiceLineItem__c>>();
          list<Apttus_Billing__InvoiceLineItem__c> list1= new list<Apttus_Billing__InvoiceLineItem__c>();
          //-------------------------------------------------------------------------------
          for(Apttus_Billing__Invoice__c invoice:invoiceObjectList1) // loop over invoices
          {
              map1.put(invoice.id,invoice);
              
          }
          
          
           for(Apttus_Billing__InvoiceLineItem__c invlineitems:[Select id,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode,
                                                               Apttus_Billing__InvoiceId__r.Name,Apttus_Billing__ProductId__r.Name,Apttus_Billing__InvoiceId__r.CurrencyIsoCode,
                                                                       Apttus_Billing__Type__c,Apttus_Billing__InvoiceId__c,Name,Apttus_Billing__Amount__c,
                                                                       Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c,Apttus_Billing__LocationId__c,
                                                                      Apttus_Billing__ProductId__r.EQ_FeeCode__c,Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c,
                                                                      Apttus_Billing__ProductId__r.ProductCode,Apttus_Billing__InvoiceId__r.EQ_TotalInvoiceAmount__c 
                                                                      from Apttus_Billing__InvoiceLineItem__c where Apttus_Billing__InvoiceId__c IN:map1.keyset()])
                 {
                   if((invlineitems.Apttus_Billing__Type__c=='Contracted') && (invlineitems.Apttus_Billing__Amount__c!=0))
                    {
                     
                            list1=map2.get(invlineitems.Apttus_Billing__InvoiceId__c);
                            
                            if(list1==null)
                            {
                            list1=new list<Apttus_Billing__InvoiceLineItem__c>();
                            map2.put(invlineitems.Apttus_Billing__InvoiceId__c,list1);
                            }
                            list1.add(invlineitems);
                            
                            map2.put(invlineitems.Apttus_Billing__InvoiceId__c,list1);
                    
                    }
                 }
          
         for(Apttus_Billing__Invoice__c invoice:invoiceObjectList1) // loop over invoices
              {
                  
                  count=count+1;
                  Decimal Sum=0;
                                    APTS_InvoiceJournalWrapper invoiceJournWrapper= new APTS_InvoiceJournalWrapper();
                                     List<InvoiceLineItems> listToStoreLineItems = new List<InvoiceLineItems>();
                                    List<InvoiceLineItems> listToStoreLineItems1 = new List<InvoiceLineItems>();
                                    invoiceJournWrapper.id=String.valueof(invoice.id);
                                    invoiceJournWrapper.HeaderKey=String.valueof(count);
                                    invoiceJournWrapper.ZCurrency=(invoice.CurrencyIsoCode!=null?invoice.CurrencyIsoCode:'USD');
                                    //invoiceJournWrapper.AccountingJournal='null';
                                    invoiceJournWrapper.AccountingJournalID=String.valueOf(invoice.Name + '_' +myDate);
                                    invoiceJournWrapper.JournalNumber=String.valueOf(invoice.Name + '_' +myDate);
                                    invoiceJournWrapper.ExternalReferenceID=String.valueOf(invoice.Name);                  
                                    invoiceJournWrapper.AccountingDate=String.valueof(Date.valueof(invoice.Apttus_Billing__InvoiceDate__c));
                                    
            counterHeader=1;
          if(map2.get(invoice.ID)!=null)
              
          {  
            
            for(Apttus_Billing__InvoiceLineItem__c invlineitems:map2.get(invoice.ID))
                 {
                     
                     
                    if(counterHeader==1)
                     {
                          
                            InvoiceLineItems FirstInvItems= new InvoiceLineItems(); 
                            FirstInvItems.LineKey=string.valueof(counterHeader);
                            FirstInvItems.HeaderKey=String.valueof(invoiceJournWrapper.HeaderKey);
                            FirstInvItems.LedgerAccount='10106';
                            //FirstInvItems.DebitAmount=String.valueof((Sum*-1).setScale(2,RoundingMode.HALF_UP));
                            FirstInvItems.CreditAmount='';
                            FirstInvItems.RevenueCategory='RC900';
                            FirstInvItems.ZCurrency=invoice.CurrencyIsoCode!=null?invoice.CurrencyIsoCode:'';
                             FirstInvItems.ExternalReferenceID=invoice.Name;
                           if(invlineitems.Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c!=null)
                            {
                            FirstInvItems.Customer=invlineitems.Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c!=null?invlineitems.Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c:'';
                            }
                            else
                            {
                                FirstInvItems.Customer='';
                            }
                          listToStoreLineItems.add(FirstInvItems);
                          counterHeader=counterHeader+1;
                          //---
                           InvoiceLineItems InvItems= new InvoiceLineItems();
                            InvItems.LineKey=string.valueof(counterHeader);
                            InvItems.HeaderKey=String.valueof(invoiceJournWrapper.HeaderKey);
                            InvItems.LedgerAccount='40050';
                            InvItems.DebitAmount=('');
                            InvItems.CreditAmount=invlineitems.Apttus_Billing__Amount__c!=null?String.valueof((invlineitems.Apttus_Billing__Amount__c).setScale(2,RoundingMode.HALF_UP)):'';
                            // Sum=  invlineitems.Apttus_Billing__Amount__c+Sum;
                           InvItems.RevenueCategory='RC022';
                            InvItems.ZCurrency=(invlineitems.Apttus_Billing__InvoiceId__r.CurrencyIsoCode!=null?invlineitems.Apttus_Billing__InvoiceId__r.CurrencyIsoCode:'USD');
                            InvItems.Memo=invlineitems.Name;
                            InvItems.ExternalReferenceID= invoice.Name;
                            if(invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__c!=null)
                            {
                            InvItems.Product= (invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode!=null?invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode:'');
                            }
                           else
                            {
                            InvItems.Product= (invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode!=null?invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode:'');
                            }
                           
                            InvItems.Customer=(invlineitems.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c!=null?invlineitems.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c:'');
                             listToStoreLineItems.add(InvItems);
                            invoiceJournWrapper.LineItems=listToStoreLineItems;
                            counterHeader=counterHeader+1;
                         //--
                     }
                     
                     else
                     {
                         
                            InvoiceLineItems InvItems= new InvoiceLineItems();
                            InvItems.LineKey=string.valueof(counterHeader);
                            InvItems.HeaderKey=String.valueof(invoiceJournWrapper.HeaderKey);
                            InvItems.LedgerAccount='40050';
                            InvItems.DebitAmount=('');
                            InvItems.CreditAmount=invlineitems.Apttus_Billing__Amount__c!=null?String.valueof((invlineitems.Apttus_Billing__Amount__c).setScale(2,RoundingMode.HALF_UP)):'';
                            // Sum=  invlineitems.Apttus_Billing__Amount__c+Sum;
                           InvItems.RevenueCategory='RC022';
                            InvItems.ZCurrency=(invlineitems.Apttus_Billing__InvoiceId__r.CurrencyIsoCode!=null?invlineitems.Apttus_Billing__InvoiceId__r.CurrencyIsoCode:'USD');
                            InvItems.Memo=invlineitems.Name;
                            InvItems.ExternalReferenceID= invoice.Name;
                            if(invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__c!=null)
                            {
                            InvItems.Product= (invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode!=null?invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode:'');
                            }
                           else
                            {
                            InvItems.Product= (invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode!=null?invlineitems.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode:'');
                            }
                           
                            InvItems.Customer=(invlineitems.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c!=null?invlineitems.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c:'');
                            counterHeader=counterHeader+1;
                            listToStoreLineItems.add(InvItems);//listToStoreLineItems2
                           invoiceJournWrapper.LineItems=listToStoreLineItems;
                       }
                      
                 }
               listToStoreJournInvoices.add(invoiceJournWrapper); 
            }
         }
            
            
        
         intWrap.Invoices =listToStoreJournInvoices;
         intWrap.TotalNumberOfInvoices=invoiceObjectList1.SIZE();  
         
          if((invoiceObjectList1.size()<=lim))
          {
              if(CMObjectListCount.size()>0)
              {
                 intWrap.MoreRecords='true'; 
              }
          }
          else
          {
                intWrap.MoreRecords='false';   
          }
         if (res == null) {
            res = new RestResponse();
            RestContext.response = res;
        }
        res.responseBody = Blob.valueOf(JSON.serialize(intWrap).replace('"ZCurrency":','"Currency":'));
       // res.responseBody = Blob.valueOf(JSON.serialize(intWrap));
          res.statusCode = 200;
   }    
        
    
     
 if(off>MaximumNoOfPages_Invoice)
  {
        off= off-MaximumNoOfPages_Invoice;     
        Integer count;
        
        count=0;
        Integer varOff=0;
        If(off==1)
          {
           varOff =0;
                  }
          else
          {
              varOff=varOff+lim*(off-1);
          }
        List<Apttus_Billing__CreditMemo__c> CMObjectList=[Select id,Apttus_Billing__CreditAmount__c,Name,CurrencyIsoCode,EQ_TotalCreditAmount__c,Apttus_Billing__CreditMemoDate__c,Apttus_Billing__InvoiceID__c  from Apttus_Billing__CreditMemo__c where Apttus_Billing__CreditMemoDate__c>=:startDate and Apttus_Billing__CreditMemoDate__c<=:endDate  and Apttus_Billing__Status__c=:approved ORDER BY Name limit:lim Offset:varOff]; 
        List<APTS_InvoiceJournalWrapper> listToStoreJournCM = new List<APTS_InvoiceJournalWrapper>();
        APTS_WorkdayIntegrationJournalWrapper intWrapCM= new APTS_WorkdayIntegrationJournalWrapper();
         map<ID,Apttus_Billing__CreditMemo__c> CMmap= new map<ID,Apttus_Billing__CreditMemo__c>();
        
         list<APTS_InvoiceJournalWrapper> invoiceJournWrapper2= new list<APTS_InvoiceJournalWrapper>();
          
          map<ID,String> CMheader= new map<ID,String>();
          map<ID,APTS_InvoiceJournalWrapper> mapCM= new map<ID,APTS_InvoiceJournalWrapper>();
      //---------------------------\
          map<ID,Apttus_Billing__CreditMemo__c> map3= new map<ID,Apttus_Billing__CreditMemo__c>();
          map<ID,list<Apttus_Billing__CreditMemoLineItem__c>> map4= new map<ID,list<Apttus_Billing__CreditMemoLineItem__c>>();
          list<Apttus_Billing__CreditMemoLineItem__c> list2= new list<Apttus_Billing__CreditMemoLineItem__c>();
          //-------------------------------------------------------------------------------
          for(Apttus_Billing__CreditMemo__c CM:CMObjectList) // loop over invoices
          {
              map3.put(CM.id,CM);
          }
          
          for(Apttus_Billing__CreditMemoLineItem__c inLines:[Select id,Apttus_Billing__Amount__c,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__c,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode,Name,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__c,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode,Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c,EQ_Amount__c,Apttus_Billing__ProductId__r.Name,CurrencyIsoCode,Apttus_Billing__CreditMemoId__r.CurrencyIsoCode,Apttus_Billing__AssetLineItemId__r.Apttus_Config2__PriceListItemId__r.Apttus_Config2__PriceType__c,
                                                                                Apttus_Billing__CreditMemoId__c,Apttus_Billing__CreditMemoId__r.Name,Apttus_Billing__BillToAccountId__r.EQ_ClientRef__c,Apttus_Billing__InvoiceLineItemId__r.Apttus_Billing__ProductId__r.EQ_FeeCode__c
                                                                               from Apttus_Billing__CreditMemoLineItem__c where Apttus_Billing__CreditMemoId__c IN:map3.keyset()])
                 {
                    
                            list2=map4.get(inLines.Apttus_Billing__CreditMemoId__c);
                            if(list2==null)
                            {
                               list2=new list<Apttus_Billing__CreditMemoLineItem__c>();
                               map4.put(inLines.Apttus_Billing__CreditMemoId__c,list2);
                            }
                            list2.add(inLines);
                            map4.put(inLines.Apttus_Billing__CreditMemoId__c,list2);
                    
                 }
         
        for(Apttus_Billing__CreditMemo__c CM:CMObjectList) // loop over invoices
              {
                   count=count+1; 
                                    APTS_InvoiceJournalWrapper invoiceJournWrapper= new APTS_InvoiceJournalWrapper();
                                   List<InvoiceLineItems> listToStoreCMLineItems = new List<InvoiceLineItems>();
                                   invoiceJournWrapper.HeaderKey=String.valueof(count);
                                   invoiceJournWrapper.id=String.valueof(CM.id);
                                   invoiceJournWrapper.ZCurrency=(CM.CurrencyIsoCode!=null?CM.CurrencyIsoCode:'');
                                   // invoiceJournWrapper.AccountingJournal='null';
                                    invoiceJournWrapper.AccountingJournalID=String.valueOf(CM.Name + '_' + myDate);
                                    invoiceJournWrapper.JournalNumber=String.valueOf(CM.Name + '_' + myDate);
                                    invoiceJournWrapper.AccountingDate=String.valueof(Date.valueof(CM.Apttus_Billing__CreditMemoDate__c));
                                    invoiceJournWrapper.ExternalReferenceID=String.valueOf(CM.Name);
           counterHeader=1;
          if(map4.get(CM.id)!=null)
          {
                  
              for(Apttus_Billing__CreditMemoLineItem__c inLines:map4.get(CM.id))
                  {
                   if(counterHeader==1)
                   {
                       InvoiceLineItems firstcmItem= new InvoiceLineItems();
                            firstcmItem.LineKey='1';
                            firstcmItem.HeaderKey=String.valueof(invoiceJournWrapper.HeaderKey);
                            firstcmItem.LedgerAccount=('10106');
                            firstcmItem.CreditAmount=('');
                           // firstcmItem.DebitAmount=(String.valueof((CM.Apttus_Billing__CreditAmount__c*-1).setScale(2,RoundingMode.HALF_UP)));
                            firstcmItem.RevenueCategory=('RC900');
                            firstcmItem.ZCurrency=string.valueof((inLines.Apttus_Billing__CreditMemoId__r.CurrencyIsoCode!=null?inLines.Apttus_Billing__CreditMemoId__r.CurrencyIsoCode:''));
                            firstcmItem.ExternalReferenceID= CM.Name;
                            firstcmItem.Customer=inLines.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c!=null?inLines.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c:'';
                             counterHeader=counterHeader+1;
                            listToStoreCMLineItems.add(firstcmItem);
                          //---
                          InvoiceLineItems cmItems= new InvoiceLineItems();
                            
                            cmItems.LineKey=String.valueof(counterHeader);
                            cmItems.HeaderKey=String.valueof(invoiceJournWrapper.HeaderKey);
                            cmItems.LedgerAccount='40050';
                            cmItems.CreditAmount=(inLines.Apttus_Billing__Amount__c!=null?String.valueof((inLines.Apttus_Billing__Amount__c*-1).setScale(2,RoundingMode.HALF_UP)):'');
                            cmItems.DebitAmount=('');
                            cmItems.RevenueCategory='RC022';
                            cmItems.ZCurrency=(inLines.Apttus_Billing__CreditMemoId__r.CurrencyIsoCode!=null?inLines.Apttus_Billing__CreditMemoId__r.CurrencyIsoCode:'');
                            cmItems.Memo=inLines.Name;
                            cmItems.ExternalReferenceID= CM.Name;
                           if(inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__c!=null)
                            {
                            cmItems.Product= (inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode!=null?inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode:'');
                            }
                           else
                            {
                            cmItems.Product= (inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode!=null?inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode:'');
                            }
                            cmItems.Project='';
                            cmItems.Customer=(inLines.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c==null?'':inLines.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c);
                            cmItems.Location='';
                           // cmItems.InterCompanyAffiliate='';
                           // cmItems.IssueProductType='';
                           // cmItems.Supplier='';
                           // cmItems.TaxAmount='';
                           // cmItems.IssueNumber='';
                            counterHeader=counterHeader+1;
                            listToStoreCMLineItems.add(cmItems);
                            invoiceJournWrapper.LineItems=listToStoreCMLineItems;
                   }
                   else
                   {
                    // creation of CM line items wrapper records
                            InvoiceLineItems cmItems= new InvoiceLineItems();
                            counterHeader=counterHeader+1;
                            cmItems.LineKey=String.valueof(counterHeader);
                            cmItems.HeaderKey=String.valueof(invoiceJournWrapper.HeaderKey);
                            cmItems.LedgerAccount='40050';
                            cmItems.CreditAmount=(inLines.Apttus_Billing__Amount__c!=null?String.valueof((inLines.Apttus_Billing__Amount__c*-1).setScale(2,RoundingMode.HALF_UP)):'');
                            cmItems.DebitAmount=('');
                            cmItems.RevenueCategory='RC022';
                            cmItems.ZCurrency=(inLines.Apttus_Billing__CreditMemoId__r.CurrencyIsoCode!=null?inLines.Apttus_Billing__CreditMemoId__r.CurrencyIsoCode:'');
                            cmItems.Memo=inLines.Name;
                            cmItems.ExternalReferenceID= CM.Name;
                           if(inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__c!=null)
                            {
                            cmItems.Product= (inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode!=null?inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__OptionId__r.ProductCode:'');
                            }
                           else
                            {
                            cmItems.Product= (inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode!=null?inLines.Apttus_Billing__AssetLineItemId__r.Apttus_Config2__ProductId__r.ProductCode:'');
                            }
                            cmItems.Project='';
                            cmItems.Customer=(inLines.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c==null?'':inLines.Apttus_Billing__SoldToAccountId__r.EQ_ClientRef__c);
                            cmItems.Location='';
                           // cmItems.InterCompanyAffiliate='';
                           // cmItems.IssueProductType='';
                           // cmItems.Supplier='';
                           // cmItems.TaxAmount='';
                           // cmItems.IssueNumber='';
                           
                            listToStoreCMLineItems.add(cmItems);
                            invoiceJournWrapper.LineItems=listToStoreCMLineItems;
                       }
                               
                  } 
                  listToStoreJournCM.add(invoiceJournWrapper);   
                  
              }
         }
              
         intWrapCM.Invoices = listToStoreJournCM;
         intWrapCM.TotalNumberOfInvoices=count; 
         if(CMObjectList.size()<lim)
             {
               intWrapCM.MoreRecords='false';  
             }
         else
         {
             intWrapCM.MoreRecords='true';
         }
         if (res == null) {
            res = new RestResponse();
            RestContext.response = res;
        }
        res.responseBody = Blob.valueOf(JSON.serialize(intWrapCM).replaceAll('"ZCurrency":','"Currency":'));
        res.statusCode = 200;
        system.debug('response body**************'+res.responseBody);
      
  }
    }    
 //------------------------------------------------------------------------------------------------------------------   

-----------------

 
paul diracpaul dirac
I find some errors and the code does not compile (i mocked all of your custom object but anyway there might be some sintax errors).
Consider to split some "iterative tasks" in an helper (static) class, since your Rest service might grows in future, developers (you too ofc) may encounter difficulties to maintain that. For example, that part in which lineItems are collected and then modified can be delegated to the helper class to enhance code readability.
Further little optization can be done storing fixed numbers/strings in costants but I guess that there are not any improvements that significately reduce the execution time, I mean the optimization I will want to see here is in code readability first. Hope I helped you to solve your cancerns!
This was selected as the best answer
EQ AdminEQ Admin
thanks paul. Agreed, I will use some custom lables instead of hardcoding and create helper class for readability purpose.
satish090satish090
devin cafedevin cafe
Here the customers can provide feedback related to their latest dining experience. If you have recently visited Wawa Restaurant. then you can give your feedback at Wawa Survey 
http://online-surveys.info/wawa-survey-www-mywawavisit-com/