• Ankita L
  • NEWBIE
  • 20 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 5
    Questions
  • 0
    Replies
Hi guys,
need to write apex class to update billing Account field on order object. then it should update the Billing account field on orderproduct. 
Need solution. New to it.

Thanks in advance
 
Need to create the component when checkbox is unchecked then the three three text field should be disabled. 
when checkbox is checked then three text field should be enabled.
Thanks in advance
Create APP, 2 create component with record edit form and hard coded Booking ID 3. add button "Create Project" and 4. It should update booking record with some value in project number field without touching on ui.
Hi everyone,
my i am stuck in test class need my code coverage is not improving.
Can u please help to to achive. 
my apex code:
public class MindbodySubscriberService
{
    //when testing in dev you need to generate a new token via postman and put it in the devToken variable below. auth.mbodev.me is NOT available from salesforce!
    static final String devToken = null; //auth.mbodev.me is not available externally this should be generated via postman and put here for testing
    static final String authUser = 'SfEventClientUser'; //in dev/sanbox we have to fake the auth using the devToken above so these values are for production
    static final String authPass = 'dTr58@1GvUlob!';
    static String authToken = null;
    static datetime authExpiry = datetime.now().addMinutes(-10);
    
    @future(callout=true)
    public static void sendNotification(String oldEmail, String newEmail, String AccountNumber) 
    {
        System.debug('MBSubscriberService.sendNotification ' + AccountNumber);
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        string token = MindbodyAuthCallout();
        if (token == null)
        {
            System.debug('Failed to authenticate to Mindbody');
            return;
        }
        req.setHeader('Authorization','Bearer ' + token);
        req.setEndpoint(SubscriberUrl());
        req.setMethod('PUT');
        req.setHeader('Content-Type', 'application/json');
        
        EmailAccountObject upData = new EmailAccountObject();
        upData.OldEmail = oldEmail;
        upData.NewEmail = newEmail;
        upData.AccountNumber = AccountNumber;
        req.setBody(JSON.serialize(upData));
        System.debug(upData);
        try 
        {
            res = http.send(req);
            System.debug(res.getBody());
            System.debug(res.getStatus());
        } 
        catch(System.CalloutException e) 
        {
            System.debug('MB Callout error: '+ e);
            System.debug(res.toString());
        }
    }

public static string MindbodyAuthCallout ()
{
    if(Test.isRunningTest()){
         return null;   
    }
     if (isSandbox())
     {
        MindbodySubscriberService.authExpiry = datetime.now().addSeconds(7000); //just assume it's valid for dev environments 
        return MindbodySubscriberService.devToken;
     }
     if (MindbodySubscriberService.authToken != null && MindbodySubscriberService.authExpiry > datetime.now().addMinutes(-5))
     {
        return MindbodySubscriberService.authToken;
     }
     MBAuthObject auth = new MBAuthObject();
     auth.username = MindbodySubscriberService.authUser;
     auth.password = MindbodySubscriberService.authPass;
     auth.grant_type = 'password';
     auth.scope = 'urn:mboframeworkapi';
     HttpRequest req = new HttpRequest();
     req.setEndpoint('https://auth.mindbodyonline.com/issue/oauth2/token');
     req.setMethod('POST');
     req.setHeader('Authorization', 'Basic U2ZFdmVudENsaWVudDppaEF5bm9hR2xaZko4dzFieU9yU3pCZ3doUjR1cURLaTUvdE9LYlgyc1FBPQ==');
     req.setHeader('Content-Type', 'application/json');
     req.setBody(JSON.serialize(auth));
   
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HttpResponse res = http.send(req);

     JSONParser parser = JSON.createParser(res.getBody());
     while (parser.nextToken() != null) 
     {
        if (parser.getCurrentToken() == JSONToken.FIELD_NAME)
        {
            if (parser.getText() == 'access_token')
            {
                        parser.nextToken();
                        MindbodySubscriberService.authToken = parser.getText();
            }
            if (parser.getText() == 'expires_in')
            {
                        parser.nextToken();
                        MindbodySubscriberService.authExpiry = datetime.now().addSeconds(parser.getIntegerValue());
            }
        }
        if (MindbodySubscriberService.authExpiry > datetime.now())
        {
            return MindbodySubscriberService.authToken;
        }
     }
     System.debug ('Failed to get response token:' + res.getBody());
     return null;
}

public class MBAuthObject
{
    public String username;
    public String password;
    public String grant_type;
    public String scope;
}

public class EmailAccountObject
{
    public string AccountNumber;
    public string OldEmail;
    public string NewEmail;
}

  // Updates Subscriber Information in MINDBODY SAAS subscriber database as needed for the principal owner
  // Reach out to MB PT & E before modifying or disabling this trigger.  Primary use is STRIPE payout notifications
  // Author: A.J. Brann June 2018

  public static void UpdateMindbodySubscriberWhenPrincipalOwner(List<Contact> listContacts, Map<Id, Contact> oldMap, Boolean isInsert, Boolean isUpdate)
  {
      /*
    if(Test.isRunningTest())  //too many test failures in production, mocking the auth doesn't seem to help so we're just going to jump ship and not do anything from a test.
    {
           return;
    }
*/
    for(contact c: listContacts)
    {
        String contact_account;
        /*Update SAAS Platform for payout notifications to the principal owner upon change of email*/
        if(c.Role__c == 'Principal Owner' && isUpdate  && c.Email != oldMap.get(c.ID).Email)
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification(oldMap.get(c.ID).Email, c.Email, contact_account);
            }

        }
        if (c.Role__c != 'Principal Owner' && isUpdate && oldMap.get(c.ID).Role__c == 'Principal Owner') //role changed from principal owner
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification(oldMap.get(c.ID).Email, '', contact_account);
            }
        }
        if (c.Role__c == 'Principal Owner' && isInsert) //possible new owner
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification('', c.Email, contact_account);
            }
        }
    }
  }
  
 @testVisible
    private Static Boolean isSandbox(){
        String host = URL.getSalesforceBaseUrl().getHost();
        String server = host.substring(0,host.indexOf('.'));
 
        // It's easiest to check for 'my domain' sandboxes first 
        // even though that will be rare
        if(server.contains('--'))
            return true;
 
        // tapp0 is a unique "non-cs" server so we check it now
        if(server == 'tapp0')
            return true;
 
        // If server is 'cs' followed by a number it's a sandbox
        if(server.length()>2){
            if(server.substring(0,2)=='cs'){
                try{
                    Integer.valueOf(server.substring(2,server.length()));
                }
                catch(exception e){
                    //started with cs, but not followed by a number
                    return false;
                }
 
                //cs followed by a number, that's a hit
                return true;
            }
        }
        // If we made it here it's a production box
        return false;
    }
@TestVisible
    private Static String SubscriberUrl ()
    {
        String devSubscriber = 'https://subscriber.mbodev.me/Subscriber/Settings';
        String prodSubscriber = 'https://subscriber.mindbodyonline.com/Subscriber/Settings';
        if (isSandbox())
        {
            return devSubscriber;
        } 
        return prodSubscriber;
    }
 }

================================
my test class
=================================
public class MindbodySubscriberService
{
    //when testing in dev you need to generate a new token via postman and put it in the devToken variable below. auth.mbodev.me is NOT available from salesforce!
    static final String devToken = null; //auth.mbodev.me is not available externally this should be generated via postman and put here for testing
    static final String authUser = 'SfEventClientUser'; //in dev/sanbox we have to fake the auth using the devToken above so these values are for production
    static final String authPass = 'dTr58@1GvUlob!';
    static String authToken = null;
    static datetime authExpiry = datetime.now().addMinutes(-10);
    
    @future(callout=true)
    public static void sendNotification(String oldEmail, String newEmail, String AccountNumber) 
    {
        System.debug('MBSubscriberService.sendNotification ' + AccountNumber);
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        string token = MindbodyAuthCallout();
        if (token == null)
        {
            System.debug('Failed to authenticate to Mindbody');
            return;
        }
        req.setHeader('Authorization','Bearer ' + token);
        req.setEndpoint(SubscriberUrl());
        req.setMethod('PUT');
        req.setHeader('Content-Type', 'application/json');
        
        EmailAccountObject upData = new EmailAccountObject();
        upData.OldEmail = oldEmail;
        upData.NewEmail = newEmail;
        upData.AccountNumber = AccountNumber;
        req.setBody(JSON.serialize(upData));
        System.debug(upData);
        try 
        {
            res = http.send(req);
            System.debug(res.getBody());
            System.debug(res.getStatus());
        } 
        catch(System.CalloutException e) 
        {
            System.debug('MB Callout error: '+ e);
            System.debug(res.toString());
        }
    }

public static string MindbodyAuthCallout ()
{
    if(Test.isRunningTest()){
         return null;   
    }
     if (isSandbox())
     {
        MindbodySubscriberService.authExpiry = datetime.now().addSeconds(7000); //just assume it's valid for dev environments 
        return MindbodySubscriberService.devToken;
     }
     if (MindbodySubscriberService.authToken != null && MindbodySubscriberService.authExpiry > datetime.now().addMinutes(-5))
     {
        return MindbodySubscriberService.authToken;
     }
     MBAuthObject auth = new MBAuthObject();
     auth.username = MindbodySubscriberService.authUser;
     auth.password = MindbodySubscriberService.authPass;
     auth.grant_type = 'password';
     auth.scope = 'urn:mboframeworkapi';
     HttpRequest req = new HttpRequest();
     req.setEndpoint('https://auth.mindbodyonline.com/issue/oauth2/token');
     req.setMethod('POST');
     req.setHeader('Authorization', 'Basic U2ZFdmVudENsaWVudDppaEF5bm9hR2xaZko4dzFieU9yU3pCZ3doUjR1cURLaTUvdE9LYlgyc1FBPQ==');
     req.setHeader('Content-Type', 'application/json');
     req.setBody(JSON.serialize(auth));
   
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HttpResponse res = http.send(req);

     JSONParser parser = JSON.createParser(res.getBody());
     while (parser.nextToken() != null) 
     {
        if (parser.getCurrentToken() == JSONToken.FIELD_NAME)
        {
            if (parser.getText() == 'access_token')
            {
                        parser.nextToken();
                        MindbodySubscriberService.authToken = parser.getText();
            }
            if (parser.getText() == 'expires_in')
            {
                        parser.nextToken();
                        MindbodySubscriberService.authExpiry = datetime.now().addSeconds(parser.getIntegerValue());
            }
        }
        if (MindbodySubscriberService.authExpiry > datetime.now())
        {
            return MindbodySubscriberService.authToken;
        }
     }
     System.debug ('Failed to get response token:' + res.getBody());
     return null;
}

public class MBAuthObject
{
    public String username;
    public String password;
    public String grant_type;
    public String scope;
}

public class EmailAccountObject
{
    public string AccountNumber;
    public string OldEmail;
    public string NewEmail;
}

  // Updates Subscriber Information in MINDBODY SAAS subscriber database as needed for the principal owner
  // Reach out to MB PT & E before modifying or disabling this trigger.  Primary use is STRIPE payout notifications
  // Author: A.J. Brann June 2018

  public static void UpdateMindbodySubscriberWhenPrincipalOwner(List<Contact> listContacts, Map<Id, Contact> oldMap, Boolean isInsert, Boolean isUpdate)
  {
      /*
    if(Test.isRunningTest())  //too many test failures in production, mocking the auth doesn't seem to help so we're just going to jump ship and not do anything from a test.
    {
           return;
    }
*/
    for(contact c: listContacts)
    {
        String contact_account;
        /*Update SAAS Platform for payout notifications to the principal owner upon change of email*/
        if(c.Role__c == 'Principal Owner' && isUpdate  && c.Email != oldMap.get(c.ID).Email)
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification(oldMap.get(c.ID).Email, c.Email, contact_account);
            }

        }
        if (c.Role__c != 'Principal Owner' && isUpdate && oldMap.get(c.ID).Role__c == 'Principal Owner') //role changed from principal owner
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification(oldMap.get(c.ID).Email, '', contact_account);
            }
        }
        if (c.Role__c == 'Principal Owner' && isInsert) //possible new owner
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification('', c.Email, contact_account);
            }
        }
    }
  }
  
 @testVisible
    private Static Boolean isSandbox(){
        String host = URL.getSalesforceBaseUrl().getHost();
        String server = host.substring(0,host.indexOf('.'));
 
        // It's easiest to check for 'my domain' sandboxes first 
        // even though that will be rare
        if(server.contains('--'))
            return true;
 
        // tapp0 is a unique "non-cs" server so we check it now
        if(server == 'tapp0')
            return true;
 
        // If server is 'cs' followed by a number it's a sandbox
        if(server.length()>2){
            if(server.substring(0,2)=='cs'){
                try{
                    Integer.valueOf(server.substring(2,server.length()));
                }
                catch(exception e){
                    //started with cs, but not followed by a number
                    return false;
                }
 
                //cs followed by a number, that's a hit
                return true;
            }
        }
        // If we made it here it's a production box
        return false;
    }
@TestVisible
    private Static String SubscriberUrl ()
    {
        String devSubscriber = 'https://subscriber.mbodev.me/Subscriber/Settings';
        String prodSubscriber = 'https://subscriber.mindbodyonline.com/Subscriber/Settings';
        if (isSandbox())
        {
            return devSubscriber;
        } 
        return prodSubscriber;
    }
 }
Hi,

I am in Lightning and I am currently using Salesforce's standard functionality of adding products on an opportunity.

As we have different types of products, when the users are selecting the products from the Add Products page and click the button Next, I want to be able to hide a Lookup field to a custom object I have created on the OLI - depending on the type of product selected. 

Also, when the Lookup field is showing on the OLI for some of the products, I want to prepoluate another two fields from the OLI with the values of the records from the Lookup field.

Is it possible to achieve this only by creating an Apex code? Without having to create a Visualforce page?


Thanks a lot.
Test Class :-

@IsTest
public class OpportunityHandlerTest 
{
   //public static String VAR_EXP = '0 0 0 15 3 ? 2022'; 
   
   private static testmethod void MyUnitTest()
   {  
       Integer MAX_QUERY = Limits.getLimitQueries();
       Integer NUM_QUERY = MAX_QUERY - 1; 
      //Create accunt
      Account acc = new account();
      acc.name='test';
      try
      {
          insert acc;
          system.debug('this is acc' +acc); 
      }
      catch(DMLException de)
      {
           system.debug('a is failed' +de.getMessage());
      }
      
       //Create contact 1
       Contact c=new Contact();
       c.lastname='nunes';
       c.Accountid=acc.id;
       c.LeadSource='Inbound';
       c.Contact_Status__c='Open';
       c.New_Lead_Source__c='Inbound';
       c.Pre_Demo_Notes__c='from pre contact';
       c.Post_Demo_Notes__c='from post contact';
       c.Created_in_admin_panel__c=true;
       insert c;
       system.assert(c.id != null);
       
       //Create contact 2
       Contact c2=new Contact();
       c2.lastname='nunes';
       c2.Accountid=acc.id;
       c2.LeadSource='Inbound';
       c2.Contact_Status__c='Open';
       c2.New_Lead_Source__c='Inbound';
       c2.Pre_Demo_Notes__c='from pre contact';
       c2.Post_Demo_Notes__c='from post contact';
       c2.Created_in_admin_panel__c=true;
       insert c2;
       system.assert(c2.id != null);
       
       
        Opportunity opp1 = new Opportunity(AccountId=acc.id,Upsell_Potential__c='No', Name='o2',contact_name__c=c.id, CloseDate=System.today(), StageName='Prospecting',Product_Specialist__c='Nicolas Carreras');
        insert opp1;

        Opportunity opp=[Select id,Contact_Name__c from Opportunity where contact_name__c != null ];
        opp.name='Start';
        opp.Contact_Name__c=c2.id;
        update opp;

        Opportunity opp2 = new Opportunity(AccountId=acc.id,Upsell_Potential__c='No', Name='o2', CloseDate=System.today(), StageName='Prospecting',Product_Specialist__c='Nicolas Carreras');
        insert opp2;

        Opportunity opp3 = new Opportunity
        (AccountId=acc.id,
        Upsell_Potential__c='SDR Target', 
        Name='o3', 
        CloseDate=System.today(), 
        StageName='Closed Won',
        Product_Specialist__c='Nicolas Carreras',
        Catalyst__c='Greenfield'
        //RenewalDate__c=system.today()
        );
        insert opp3;
        
        opp3.StageName = 'Prospecting';
        update opp3;
        
        opp3.StageName = 'Closed Won';
        update opp3; 
        
         OpportunityContactRole opcr=new OpportunityContactRole();
         opcr.OpportunityId = opp3.id;
         opcr.ContactId = c2.id;
         opcr.IsPrimary = true;
         opcr.Role='End-User';
         insert opcr;
        system.assert(opcr.id != null); 
        
        Id stdpricebook = System.Test.getStandardPricebookId();
        system.debug('this is stdpricebook : ' +stdpricebook);
        system.assert(stdpricebook != null);
        
        List<SBQQ__Quote__c> qlist=new List<SBQQ__Quote__c>();
        SBQQ__Quote__c thisquote=new SBQQ__Quote__c();
        thisquote.SBQQ__SubscriptionTerm__c=12;
        thisquote.SBQQ__StartDate__c=system.today();
        thisquote.SBQQ__PriceBook__c=stdpricebook;
        thisquote.SBQQ__Primary__c=true;
        thisquote.SBQQ__Opportunity2__c=opp3.id;
        qlist.add(thisquote);
        //try{
        Test.startTest();
        insert qlist;
        Test.stopTest();
        //}
        ////catch(exception e)
        //{
        //system.debug(e);
        //}
        System.assert(thisquote.id != null);
        
        set<id> setid = new set<id>();
        
        for(SBQQ__Quote__c a : qlist){
        
        setid.add(a.id);
        }
        
       // list<SBQQ__Quote__c> insrtdQ = 
        list<SBQQ__QuoteLine__c> qq = [select id from SBQQ__QuoteLine__c where id=:setid];
        List<SBQQ__QuoteLine__c> newQlils = new List<SBQQ__QuoteLine__c>();   
          
       for(SBQQ__QuoteLine__c qq1 :qq ){
       
       if(qq1.id != null){
       SBQQ__QuoteLine__c QL = new SBQQ__QuoteLine__c();
     //  QL.SBQQ__Quote__c = setid;
       
       }
       }
       
     }  
                 
}

Apex Class:-

public class OpportunityHandler_cpq{

public integer enddate;

    Public void CpqQuoteInsert( list<opportunity> listopp){
        
        set<id> oppids = new set<id>();
      
        for(opportunity op :listopp ) {
      
            if(op.SBQQ__Renewal__c == True &&  op.SBQQ__RenewedContract__c != null ){

              oppids.add(op.id);
              system.debug('First op id'+op.id);
            }
        }
        system.debug('oppids::'+oppids);  
        List<Opportunity> oppls = [select id,Renewal_Contract_Term__c,SBQQ__RenewedContract__c, formulapreviousopp__c, SBQQ__RenewedContract__r.SBQQ__Opportunity__c from opportunity where id IN : oppids];
        system.debug('oppls::'+oppls);  
        Map<Id, Id> oldVSnewOpp = new Map<Id, Id>();
   
        for(Opportunity opp: oppls) {
            system.debug('opp.SBQQ__RenewedContract__c::'+opp.SBQQ__RenewedContract__c);
            system.debug('opp.SBQQ__RenewedContract__r.SBQQ__Opportunity__c::'+opp.SBQQ__RenewedContract__r.SBQQ__Opportunity__c);
            system.debug('opp.formulapreviousopp__::'+opp.formulapreviousopp__c);
            
            if(opp.SBQQ__RenewedContract__c != null && opp.SBQQ__RenewedContract__r.SBQQ__Opportunity__c != null)
                oldVSnewOpp.put(opp.SBQQ__RenewedContract__r.SBQQ__Opportunity__c, opp.Id);
     
        }
        system.debug('oldVSnewOpp:'+oldVSnewOpp);
        List<Opportunity> oldOppls = [select id, name,
                                                (Select ACV_Auto_Renew_Increment_Amount__c, ACV__c, Account_Name__c, Auto_Renew__c, Contract_End_Date__c, CreatedById, CreatedDate, Document_Template__c, 
Id, IsDeleted, LastActivityDate, LastModifiedById, LastModifiedDate, LastReferencedDate, LastViewedDate, Name, Number_of_Licences__c, 
Opp_Closed__c, Original_Quote_id__c, OwnerId, Payment__c, Primary_Contact_First_Name__c, Product_Family__c, SBQQ__Account__c, 
SBQQ__AdditionalDiscountAmount__c, SBQQ__AverageCustomerDiscount__c, SBQQ__AveragePartnerDiscount__c, SBQQ__BillingCity__c, SBQQ__BillingCountry__c, 
SBQQ__BillingFrequency__c, SBQQ__BillingName__c, SBQQ__BillingPostalCode__c, SBQQ__BillingState__c, SBQQ__BillingStreet__c, SBQQ__ContractingMethod__c,
 SBQQ__CustomerAmount__c, SBQQ__CustomerDiscount__c, SBQQ__DaysQuoteOpen__c, SBQQ__DefaultTemplate__c, SBQQ__DeliveryMethod__c, SBQQ__DistributorDiscount__c,
 SBQQ__Distributor__c, SBQQ__DocumentStatus__c, SBQQ__EmailTemplateId__c, SBQQ__EndDate__c, SBQQ__ExpirationDate__c, SBQQ__FirstSegmentTermEndDate__c,
 SBQQ__GenerateContractedPrice__c, SBQQ__Introduction__c, SBQQ__Key__c, SBQQ__LineItemCount__c, SBQQ__LineItemsGrouped__c, SBQQ__LineItemsPrinted__c, 
 SBQQ__ListAmount__c, SBQQ__MarkupRate__c, SBQQ__MasterContract__c, SBQQ__NetAmount__c, SBQQ__Notes__c, SBQQ__Opportunity2__c, SBQQ__Ordered__c, 
 SBQQ__OriginalQuote__c, SBQQ__PartnerDiscount__c, SBQQ__Partner__c, SBQQ__PaymentTerms__c, SBQQ__PriceBook__c, SBQQ__PricebookId__c,
 SBQQ__PrimaryContact__c, SBQQ__Primary__c, SBQQ__QuoteProcessId__c, SBQQ__QuoteTemplateId__c, SBQQ__RegularAmount__c, SBQQ__SalesRep__c, 
 SBQQ__ShippingCity__c, SBQQ__ShippingCountry__c, SBQQ__ShippingName__c, SBQQ__ShippingPostalCode__c, SBQQ__ShippingState__c, SBQQ__ShippingStreet__c, 
 SBQQ__Source__c, SBQQ__StartDate__c, SBQQ__Status__c, SBQQ__SubscriptionTerm__c, SBQQ__TargetCustomerAmount__c, SBQQ__TotalCustomerDiscountAmount__c,
 SBQQ__Type__c, SBQQ__WatermarkShown__c, SystemModstamp
                                                from SBQQ__Quotes2__r where SBQQ__Primary__c =  true) 
                                    from opportunity where id IN :oldVSnewOpp.keySet()];
         system.debug('oldOppls:'+oldOppls);
     
        List<SBQQ__Quote__c>  quotels = new  List<SBQQ__Quote__c>();
        for(Opportunity oldOpp :oldOppls) {
            if(oldOpp.SBQQ__Quotes2__r.size() >0 ) {
                system.debug('oldOpp.SBQQ__Quotes2__r::'+oldOpp.SBQQ__Quotes2__r);
                system.debug('oldVSnewOpp.containsKey(oldOpp.id)::'+oldVSnewOpp.containsKey(oldOpp.id));
                if(oldVSnewOpp.containsKey(oldOpp.id)) {
                    system.debug('here!!!!!!');
                    SBQQ__Quote__c  quote1 =  oldOpp.SBQQ__Quotes2__r[0].clone();
                    quote1.Original_Quote_id__c=oldOpp.SBQQ__Quotes2__r[0].id;
                    quote1.SBQQ__StartDate__c = system.today();
                    
                 //  Integer enddate= Integer.valueOf(String.valueOf(Math.roundToLong(oldOpp.SBQQ__Quotes2__r[0].SBQQ__SubscriptionTerm__c)));
                    
              //   quote1.SBQQ__EndDate__c =system.today().addmonths(enddate);

                    system.debug('quote1.Original_Quote_id__c::'+quote1.Original_Quote_id__c);
                    quote1.SBQQ__Opportunity2__c = oldVSnewOpp.get(oldOpp.id);
                    system.debug('quote1::'+quote1);
                    quotels.add(quote1);
                } 
         
            }
     
        }
        system.debug('quotels::'+quotels);
        
        if(quotels.size()>0) {
            insert quotels;
        }
        
       
        
         set<id> Quoteid = new set<id>();
         Map<id, id> oldQuoteVSNewQuoteIds = new Map<id, id>();
         for(SBQQ__Quote__c qt : quotels){
            if(qt.Original_Quote_id__c != null){
                oldQuoteVSNewQuoteIds.put(qt.Original_Quote_id__c, qt.id);
            }
        }
        system.debug('oldQuoteVSNewQuoteIds:::'+oldQuoteVSNewQuoteIds);
        
        list<SBQQ__Quote__c> oldquotelist = [Select ACV_Auto_Renew_Increment_Amount__c, ACV__c, Account_Name__c, Auto_Renew__c, Contract_End_Date__c, CreatedById, CreatedDate, Document_Template__c, 
Id, IsDeleted, LastActivityDate, LastModifiedById, LastModifiedDate, LastReferencedDate, LastViewedDate, Name, Number_of_Licences__c, 
Opp_Closed__c, Original_Quote_id__c, OwnerId, Payment__c, Primary_Contact_First_Name__c, Product_Family__c, SBQQ__Account__c, 
SBQQ__AdditionalDiscountAmount__c, SBQQ__AverageCustomerDiscount__c, SBQQ__AveragePartnerDiscount__c, SBQQ__BillingCity__c, SBQQ__BillingCountry__c, 
tartDate__c, SBQQ__Status__c, SBQQ__SubscriptionTerm__c, SBQQ__TargetCustomerAmount__c, SBQQ__TotalCustomerDiscountAmount__c,
 SBQQ__Type__c, SBQQ__WatermarkShown__c, SystemModstamp,
                                              (Select CreatedById, CreatedDate, Id, IsDeleted, LastModifiedById, LastModifiedDate, Name, Opportunity__c, Product_Description__c, Product_Family__c, 
SBQQ__AdditionalDiscountAmount__c, SBQQ__AdditionalDiscount__c, SBQQ__AdditionalQuantity__c, SBQQ__AllowAssetRefund__c, SBQQ__BatchQuantity__c, 
SBQQ__BillingFrequency__c, SBQQ__BillingType__c, SBQQ__BlockPrice__c, SBQQ__Bundle__c, SBQQ__BundledQuantity__c, SBQQ__Bundled__c, SBQQ__CarryoverLine__c,
 SBQQ__ChargeType__c, SBQQ__ComponentCost__c, SBQQ__ComponentDiscountedByPackage__c, SBQQ__ComponentListTotal__c, SBQQ__ComponentSubscriptionScope__c, 
 
 
 SBQQ__TotalDiscountRate__c, SBQQ__UnitCost__c, SBQQ__UnproratedNetPrice__c, SBQQ__UpgradedAsset__c, SBQQ__UpgradedQuantity__c, 
 SBQQ__UpgradedSubscription__c, SBQQ__UpliftAmount__c, SBQQ__Uplift__c, SBQQ__VolumeDiscount__c, SystemModstamp  FROM SBQQ__Lineitems__r) FROM SBQQ__Quote__c 
                                                   where id IN :oldQuoteVSNewQuoteIds.keySet()];
                                              
        List<SBQQ__QuoteLine__c> newQlils = new List<SBQQ__QuoteLine__c>();                                           
        for(SBQQ__Quote__c q1 :oldquotelist){
            for(SBQQ__QuoteLine__c qli : q1.SBQQ__Lineitems__r){
                SBQQ__QuoteLine__c newQli = qli.clone();
                newQli.SBQQ__Quote__c = oldQuoteVSNewQuoteIds.get(q1.id);
                newQli.SBQQ__Product__c= qli.SBQQ__Product__c;
                
                system.debug('qli:::'+qli.SBQQ__ProductFamily__c+ '::'+qli);
                system.debug('newQli:::'+newQli.SBQQ__ProductFamily__c+ '::'+newQli);

                newQlils.add(newQli);  
            } 
        }
        
        system.debug('newQlils::'+newQlils.size() + '::' +newQlils);
        if(newQlils.size() > 0) {
            insert newQlils;
        
        }
      /*  set<Id> newIds = new Set<Id>();
        for(SBQQ__QuoteLine__c qliNew1 :newQlils) {
            newIds.add(qliNew1.id);
        }
        
    
    List<SBQQ__QuoteLine__c>  updatedValue = [select id, name, SBQQ__CustomerPrice__c,SBQQ__ProductFamily__c  from SBQQ__QuoteLine__c where id IN :newIds];                                      
    system.debug('updatedValue::'+updatedValue);
    for(SBQQ__QuoteLine__c a1  :updatedValue) {
        system.debug('a1::'+a1);
    
    }
        */
        
        set<id> newQuoteid = new set<id>();
       
       for(SBQQ__Quote__c qt2 :quotels){
       newQuoteid.add(qt2.id);
       
       }
       
     //  list<string> updateTerm = new list<string>();
        
        list<SBQQ__Quote__c> newQuote =[select SBQQ__SubscriptionTerm__c, Renewal_Contract_Term_from_Renewal_opp__c, SBQQ__EndDate__c from  SBQQ__Quote__c where id=:newQuoteid];

        for(SBQQ__Quote__c updateEnddate: newQuote){
        
           Integer enddate= Integer.valueOf(String.valueOf(Math.roundToLong(updateEnddate.Renewal_Contract_Term_from_Renewal_opp__c)));

        
        updateEnddate.SBQQ__EndDate__c = system.today().addMonths(enddate);
        
        updateEnddate.SBQQ__SubscriptionTerm__c =updateEnddate.Renewal_Contract_Term_from_Renewal_opp__c;
        
        update updateEnddate;
        }

    } 
        
}
  • June 18, 2019
  • Like
  • 1