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
Tirumala Kuppani 10Tirumala Kuppani 10 

Deep clone opportunity(Quote, Quotlineitem and opportunity products) with synced quotes

Hi All,

 I need help on synced quote cloned opportunities. I have done customisation(Visualforce page, Apex class, custom button) for synced quote clone opportunities through custom button(clone with product). I got an error while create new cloned opportunity with synced quotes. 
 
My Requirement: Need clone opportunity with quote,quote line item and opportunity line item with sync quote. 

Error:

An internal server error has occurred
An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support. Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information. We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 1780655579-104329 (-1460871158)



Please check the below code.

visualforce page:

<apex:page standardController="Opportunity" extensions="cloneExtension" action="{!cloneRecord}">
</apex:page>


Apex class:

 public with sharing class cloneExtension 
{
    //Variable to hold current record
    private Opportunity currentRecord {get;set;}
    
    //public ID newRecordId {get;set;}
    //Standard constructor method
    public cloneExtension(ApexPages.StandardController controller) 
    {
        currentRecord = (Opportunity)controller.getRecord();
        system.debug('CurrentRecord=== '+currentRecord);
    }
    
    public PageReference cloneRecord()
    {
        //Variable to hold the new record
        Opportunity newRecord;
        Savepoint sp = Database.setSavepoint();
        try
       {
            currentRecord = [Select Id, IsDeleted, AccountId, RecordTypeId, IsPrivate, Name,Description, StageName, Amount, Probability, ExpectedRevenue, TotalOpportunityQuantity, CloseDate, Type, NextStep, LeadSource, IsClosed, IsWon, ForecastCategory, 
            ForecastCategoryName, CampaignId, HasOpportunityLineItem, Pricebook2Id, OwnerId, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, LastActivityDate, FiscalQuarter, FiscalYear, Fiscal, LastViewedDate,
             LastReferencedDate, PartnerAccountId, SyncedQuoteId, ContractId, HasOpenActivity, HasOverdueTask, Distributor__c, Location__c, Competitors__c, Push_Counter__c, Reseller__c, Won_Lost_Reason__c, Budget__c, Stage_of_Initiative__c, 
             ISR_Managed__c,Other_AIM_Partner__c,Trial_Start_Date__c, Trial_End_Date__c, Trial_Type__c, Timeframe__c, Legacy_Notes__c, Key_Risk_Summary__c, Keys_to_Win_Deal__c, Is_Primary_UC_Partner_the_Deal_Source__c, Opportunity_Sales_Region__c, PO_Number__c,
              PO_Date__c, Environment_Info_Warning__c, Total_Value_of_Wi_Fi_Products__c, Service_Stage__c, Total_Number_Installation_Products__c, Comments__c, Winning_Incentive_Number__c, Currency_Code__c, Currency_Exchange_rate__c, 
              Currency_last_updated__c, SourceID__c, SFID_18__c, Amount_USD__c, Legacy_Type__c, Legacy_ISR_Managed__c, Legacy_Primary_Direct_Channel_ACC__c, Legacy_Direct_Channel__c, Legacy_2nd_Tier_Reseller__c, Legacy_Campaign__c, 
              Legacy_Alliance_Partner__c, Legacy_Primary_UC_Partner_Influence_Deal__c, Legacy_Opportunity_Sales_Region__c, Legacy_Vertical_Industry__c, Win_Loss_Comments__c, Legacy_Owner__c, Industry__c, Sales_In_Sales_Thru__c, 
              Total_Amount_MSRP__c, Account_Sales_Region__c, LID__LinkedIn_Company_Id__c, Lead_Source_Most_Recent__c, Buying_service_with_discounted_product__c, Referred_By_Oppty__c, Reseller_Type__c, Top_Opportunity__c, POS_Revenue_Won__c,
               Opportunity_Platform__c, Installed_Base_Revenue__c, Eloqua_Lead_Rating__c, Quota__c, Reseller_Certification__c, Reseller_Quota_TY__c, Service_Contract_Start_Date__c, Service_Contract_End_Date__c, Deal_Registration_Discount_dr__c, 
               Reseller_Address_dr__c, Reseller_Sales_Rep_Phone_dr__c, Reseller_Sales_Rep_Email_dr__c, Key_Contact__c, Call_Platform__c, Estimated_Footage__c, Estimated_Opportunity_Value_dr__c, Estimated_Close_Date__c, Does_Opty_Site_have_WiFi_dr__c, 
               Expected_Revenue_USD__c, AmPsh__c, ACLostDt__c, NST__c, NST_Approval_Date__c, xNST_End_Date__c, Reseller_Account_ID__c, Deal_Registration_Status__c, NST_RD_Approval__c, NST_VP_Approval__c, AIMS_Partner__c,
               Maintenance_Needed__c, Reseller_Company_Name_dr__c, Reseller_Sales_Rep_First_Name_dr__c, NST_Justificaiton_of_proposed_terms__c, Solutions_Architect__c, BMXR__Assets_Created__c, Stand_by_Reason__c, 
               Product_Relevance__c, Next_Step_Action_Plan__c, Power_of_1__c, Opp_Disty_for_Discount__c, Big_Deal_Notification_Sent__c, Partner_Opportunity__c, Stage_Duration__c, Offered_discount_in_the_past__c, Reseller_s_contribution_to_discount__c, 
               Synced_Quote__c, What_is_our_install_base_revenue__c, Business_Case_Percent_Completeness__c, Distributor_Account_ID__c, Deal_Registration_Number__c, Non_Service_Amount__c, Month_Created__c, Distributor_Discount_Product_Temp__c,
               Month_Closed__c, PIVOT_Non_Service_Amount__c, Current_Year__c, Distributor_Discount_Service_Temp__c, Quarter_Close__c, Previous_Quarter_Close__c, Non_Service_Opps__c, Actual_Month_Closed__c, Won_Lost_Date_Abbreviated__c,
               PIVOT_Non_Service_Opp__c, Actual_Close_Date__c, Won_Lost_Date__c, Won_Lost_Year__c, Won_Lost_Previous_Quarter_Close__c, NST_End_Date__c, Trial_Approval_Status__c, Trial_Key_Contact__c, Trial_Products__c, Deal_Distributor_dr__c, 
               Spectralink_Associate_dr__c, Deal_Decline_Reason_dr__c, Deal_Registration_Description__c, Deal_Registration_Expiration__c, Dates_of_Customer_Meetings_dr__c, Will_this_be_a_phased_deployment__c, Number_of_Handsets_dr__c, 
               Reseller_Country_dr__c, Reseller_Level_dr__c, Handsets_dr__c, Accessories_dr__c, Services_dr__c, Level_of_Engagement_dr__c, Other_dr__c, Reseller_City_dr__c, Reseller_State_dr__c, Reseller_Zip_Postal_Code_dr__c, 
               Reseller_Sales_Rep_Last_Name_dr__c FROM Opportunity where id=:currentRecord.id];
                   
            newRecord = currentRecord.clone(false);
            insert newRecord;
            system.debug('newRecord.id '+newRecord.id);
             
            List<Quote>Quotelist=[Select Id, IsDeleted, Name, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, LastViewedDate, LastReferencedDate, OpportunityId, Pricebook2Id, ContactId, QuoteNumber, IsSyncing, ShippingHandling, 
            Tax, Status, ExpirationDate, Description, Subtotal, TotalPrice, LineItemCount, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry, BillingLatitude, BillingLongitude, BillingGeocodeAccuracy, BillingAddress, ShippingStreet, 
            ShippingCity, ShippingState, ShippingPostalCode, ShippingCountry, ShippingLatitude, ShippingLongitude, ShippingGeocodeAccuracy, ShippingAddress, QuoteToStreet, QuoteToCity, QuoteToState, QuoteToPostalCode, QuoteToCountry, QuoteToLatitude, QuoteToLongitude, 
            QuoteToGeocodeAccuracy, QuoteToAddress, AdditionalStreet, AdditionalCity, AdditionalState, AdditionalPostalCode, AdditionalCountry, AdditionalLatitude, AdditionalLongitude, AdditionalGeocodeAccuracy, AdditionalAddress, BillingName, ShippingName, 
            QuoteToName, AdditionalName, Email, Phone, Fax, ContractId, AccountId, Discount, GrandTotal, Maximum_Discount__c, Distributor_Product_Discount_Temp__c, Distributor_Product_Discount__c, Expiration_Date_90_Days_Out__c, Legacy_Pricebook_Name__c, 
            Legacy_Currency_Code__c, Distributor_Service_Discount__c, Max_Incremental_Discounts__c, Winning_Incentive_Number__c, Winning_Incentive_No_Display__c, Total_Price_MSRP_Currency__c, Total_Contract_Value__c, Currency__c, Total_Price_MSRP_Number__c, 
            BMXB__Annual_Recurring_Total__c, Disclaimer__c, BMXB__Contract_Term_Months__c, BMXB__Daily_Price__c, BMXB__End_Date2__c, BMXB__End_Date__c, BMXB__First_Year_Contract_Value__c, BMXB__Monthly_Recurring_Total__c, BMXB__One_time_Total__c, 
            BMXB__Quote_Approved__c, BMXB__Start_Date__c, BMXB__Submitted_for_Approval__c, BMXB__Total_Contract_Value__c, BMXB__Number_of_Line_Items_Needing_Approval__c, BMXP__Primary_Quote__c, BMXR__Is_Addon__c, BMXR__Is_Renewal__c, Service_Disclaimer__c, 
            Contract_Term_In_Months__c, Approval_Required__c, Approval_Date__c, Business_Case_Percent_Complete__c, Currency_Exchange_Rate__c, Currency_last_updated__c, Distributor_Incentive_Discount__c, Distributor__c, Total_Gross_Margin_Percent__c, 
            Total_Extended_Net_After_Disti_Incentive__c, Total_Extended_Net__c, Total_Extended_Std_Cost__c, Distributor_Service_Discount_Temp__c, Quote_contact_name2__c, Total_Extended_Non_Standard_Cost__c, Total_Gross_Margin__c, BMXB__Step_Number__c, 
            Invalid_Expiration_Date__c FROM Quote WHERE Opportunityid =:currentRecord.id];
            
            List<Quote> test_Case_User = new List<Quote>();
            List<id>Quoteid=new list<id>();
            list<Quote> NewQuotes = new list<Quote>();
            map<id,Quote> oldQuotes=new map<id,Quote>();
  
            for (Quote qo :Quotelist ) {
                  Quoteid.add(qo.id);
                  oldQuotes.put(qo.id,qo);
                  Quote newquote = qo.clone(false);
                  if(newquote.IsSyncing==true || newquote.IsSyncing==false ){
                  newquote.Opportunityid = newRecord.id;
                  NewQuotes.add(newquote);
                  }
             }
             insert NewQuotes;
             system.debug('New Quote values'+NewQuotes);
              List<QuoteLineItem> Qlitems=new List<QuoteLineItem>();
                  Qlitems=[Select Id, IsDeleted, LineNumber, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, QuoteId, PricebookEntryId, Quantity, UnitPrice, Discount, HasRevenueSchedule, HasQuantitySchedule, 
            Description, ServiceDate, Product2Id, SortOrder, HasSchedule, ListPrice, Subtotal, TotalPrice, Distributor_Discount__c, Incremental_Discount__c, Product_Description__c, Active__c, Total_Discount__c, End_Price__c, Sales_Price_1__c, 
            Total_Price_MSRP__c, Total_Price_MSRP_HIDDEN__c, MSRP__c, Distributor_Discount_Incentive__c, Distributor__c, Currency__c, MSRP_Number__c, Distributor_Discount_1__c, Opp_Product__c, Extended_Net_After_Disti_Incentive_CALC__c, 
            Extended_Net_After_Disti_Incentive__c, Extended_Net_CALC__c, BMXB__Annual_Fee__c, BMXB__Approval_threshold__c, BMXB__Calculated_Discount__c, BMXB__Contract_Term_Months__c, BMXB__Monthly_Fees__c, BMXB__Net_Discount__c, BMXB__Net_Price__c, 
            BMXB__Product_Code__c, BMXB__Product_Description__c, BMXB__Product_Family__c, BMXB__Recurrence__c, BMXB__Requires_Approval__c, BMXB__Total_Contract_Value_TCV__c, QConfig__Model_Name__c, QConfig__Model__c, QConfig__Product_Key__c, 
            QConfig__Requirement_Type__c, BMXP__Account_Specific_Price__c, BMXP__Associated_Product_Price__c, BMXP__Bundle_Number__c, BMXP__Price_Source__c, BMXP__Primary_Quote__c, BMXP__Tiered_Price__c, BMXP__Volume_Price__c, Extended_Net__c, 
            Extended_Non_Standard_COG_Percent__c, Extended_Non_Standard_Cost_CALC__c, Extended_Non_Standard_Cost__c, Extended_Std_Cost_CALC__c, Extended_Std_Cost__c, Gross_Margin_Amount_CALC__c, Gross_Margin_Amount__c, Gross_Margin_Percent__c, 
            Include_Disti_Incentive_Discount__c, Initial_MSRP_Hidden__c, Product_Category__c, Product_Group__c, Total_Discount_CALC__c, Distributor_Discount_HIDDEN__c, Unit_Std_Cost_CALC__c, Unit_Std_Cost__c, Testing_notes__c, Opportunity_Info__c, 
            Product_Series__c, ProdFam__c FROM QuoteLineItem WHERE QuoteId in :Quoteid];
            
             system.debug('Quotelineitemslist'+Qlitems);
       
            List<QuoteLineItem>NewQlitems=new list<QuoteLineItem>();
            
            for(Quote quotess:NewQuotes){
                    for(QuoteLineItem qlies:Qlitems){
                        
                              
                          QuoteLineItem qlm=qlies.clone(false);
                          
                         

                     if(qlies.QuoteId!=null && (oldQuotes.get(qlies.QuoteId).id == qlies.QuoteId)){
                         system.debug('oldquotes '+oldQuotes.get(qlies.QuoteId).id );
                          system.debug('oldquotelineiems'+qlies.QuoteId);
                         if(oldQuotes.get(qlies.QuoteId).Name==quotess.Name){
                         qlm.QuoteId= quotess.id;
                         NewQlitems.add(qlm);
                        }
                      
                         }
                    }
                   }
            
               insert NewQlitems;
               
         
                system.debug('Quotelineitemslist'+NewQlitems);
               //Copy the related list - Test (this is a sample related list I created) 
               List<OpportunityLineItem> opplineItems = new List<OpportunityLineItem>();
             List<OpportunityLineItem> oldopplitms = [Select Id, OpportunityId, SortOrder, PricebookEntryId, Product2Id, ProductCode, Name, Quantity, Discount, TotalPrice, ListPrice,ServiceDate, HasRevenueSchedule, HasQuantitySchedule, Description,
                HasSchedule, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, IsDeleted, Legacy_Currency_Code__c, Product_Family__c, Product_Type__c, Legacy_Pricebook_Name__c, Class__c, Legacy_Contractual_Discount_Per__c, 
                Legacy_Contractual_Discount_Value__c, Legacy_Gross_Margin_Value__c, Legacy_Incremental_Discount_Per__c, Legacy_Incremental_Discount_Value__c, Legacy_Total_Discount_Percent__c, Legacy_Total_Discount_Value__c, SourceID__c, Legacy_Gross_Margin__c,
                 Legacy_PricebookEntryID__c, Legacy_List_Price__c, Product_Description__c, Distributor_Discount__c, Incremental_Discount__c, Total_Price_MSRP__c, Total_Price_MSRP_HIDDEN__c, Sales_Price_Disti__c, Incremental_Discount_1__c, Active__c, MSRP__c,
                  Product_Family_Value__c, Cloned__c, Distributor_Discount_1__c, Clone_Timer__c, Solution_Type__c, Series__c, QConfig__Model_Name__c, QConfig__Model__c, QConfig__Product_Key__c, Total_Price_USD__c, Apply_Discount__c, Distributor_Discount_Product_HIDDEN__c, 
                  Distributor_Discount_Service_HIDDEN__c FROM OpportunityLineItem where Opportunityid =:currentRecord.id];
                 for( OpportunityLineItem  testStep : oldopplitms)
                 
            {
            system.debug('OpportunityLineItemOLD records'+testStep);
            for(Quote qq :Quotelist){
            for(QuoteLineItem qlitm: Qlitems){
            if(qq.IsSyncing==false){
            OpportunityLineItem opplitems = testStep.clone(false);
           
            {
                 
                 opplitems .opportunityid = newRecord.id;
                 opplineItems .add(opplitems);
                //system.debug('OpLI '+opplitems.size());
                  system.debug('OpLI initial');
               
            }
              system.debug('OpLI before');
            insert opplineItems ;
            system.debug('OpLI added');  
           }
                }
       }
       }
      } 
        catch(Exception e)
        {
           Database.rollback(sp);
            ApexPages.addMessages(e);
            return null;
       } 
        
return new PageReference('/'+newRecord.id+'/e?retURL=%2F'+newRecord.id);

    }

}


Any one let us know the solution on syncing quotes in cloned opportunities. 

I have created ticket to salesforce team also, But they suggested we have support only standard functionlaity(standard clone button). My requirement is custon button. 

Regards
Tirumala K