• trailhead solutions 10
  • NEWBIE
  • 10 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 3
    Replies
Hello

Please someone help how to cover the test class and code coverage for the below rest api class?

Thanks in Advance
TH

public class callIwiseAPI {

    //To capture getOauthToken response
    public class tokenResponse{
        public string access_token;
    }
  
  public class OpptyInput{
    String SalesForceId;
        string OpportunityType;
    String Lob;
    String Product;
    String Region;
        String SubRegion;
    String BOTitle;
  //  String BType;
    String DealNature;
  //  String BOCurrency;
    Decimal ContractValue;
    Date EffectiveDate;
    Decimal ContractDuration;
    String ContractDurationUnitOfMesurement;
  //  String AccountCode;
    String Description;
    String SalesPerson1;
    String CreatedBy;
        string ProspectName;
        String ContactPerson;
        String ContactNumber;
        String Competitors;
        String ContactEmail;
        String JobTitle;
        String AccountName;

  }
/******************************************************************************************************************
Method      : getOauthToken
Parameters  : # 
ReturnType  : object
Description : Calling iWise API to get oAuth Token and pass the same token get the BO data
*******************************************************************************************************************/
    public  String getOauthToken(){
        String oAuthToken;
        tokenResponse atResponse = new tokenResponse();
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:iWise_Credentials/token');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=utf-8');
        request.setHeader('username', '{!$Credential.Username}');
        request.setHeader('password', '{!$Credential.Password}');
        request.setHeader('grant_type', 'password');
    
        System.debug('Request to get oAuth Token:'+request);
        
    
        HttpResponse response = http.send(request);
        system.debug('Response from iWise for OAUTH Token:::'+response.toString());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 201 || response.getStatusCode() == 200) {
            // Deserialize the JSON string into collections of primitive data types.
            //Map<String, object> results = (Map<String, object>) JSON.deserializeUntyped(response.getBody());
            system.debug(':::: Response::::'+response.getBody());
            atResponse = (tokenResponse)json.deserialize(response.getBody(),tokenResponse.class);
            // get the oAuth tken from the response
            
            oAuthToken = atResponse.access_token;//(String) results.get('access_token');
            System.debug('OAuth Acces Token from response:'+oAuthToken);
            return oAuthToken;
            
        }
        else{
            System.debug('The status code returned was not expected: ' +
            response.getStatusCode() + ' ' + response.getStatus());
            return oAuthToken;
        }
        
    }
    
/******************************************************************************************************************
Method      : sendBoToIwise
Parameters  : oAuthToken 
ReturnType  : object
Description : Calling iWise API to send the BO
*******************************************************************************************************************/
  @future(callout = true)
    public static void sendBoToIwise(set<id> oppIds){
//    system.debug('this');
    list<Opportunity> opty = new list<Opportunity>();
       String oAuthToken;
        
    
    opty = [select Id,Name,TCV__c,IBS_Lob__c,Contract_Type__c,Competitors_Names__c,Products__c,CloseDate,Type_of_Deal__c,Tenure_Unit_of_Measure__c,Tenure__c,Description,Owner.Name,Owner.Email,Account__r.Account_Code__c,Response_from_iWise_System__c,Account.Name,
                ( SELECT contact.firstName,contact.phone,contact.Email,contact.Title,contact.IBS_Region__c,contact.IBS_Sub_Region__c FROM OpportunityContactRoles ),
                (select Name,TeamMemberRole,User.Name,User.Email   from OpportunityTeamMembers where  TeamMemberRole = 'Sales Rep')
                                                from Opportunity where Id IN : oppIds];
            system.debug(opty);
       list<OpptyInput> inputRequest = new list<OpptyInput>();
        callIwiseAPI obj = new callIwiseAPI();
        oAuthToken = obj.getOauthToken();
    if(!opty.isEmpty()){
      for(Opportunity op : opty){
        OpptyInput reqInput  = new OpptyInput();
        reqInput.BOTitle=op.Name;
        reqInput.SalesForceId=op.Id;
                reqInput.OpportunityType=op.Type_of_Deal__c;
        reqInput.Lob = op.IBS_Lob__c;
        reqInput.Product=op.Products__c;
        reqInput.Region=op.OpportunityContactRoles[0].contact.IBS_Region__c;
        reqInput.SubRegion=op.OpportunityContactRoles[0].contact.IBS_Sub_Region__c;
      //  reqInput.BType = 'New BO';
        reqInput.DealNature = op.Contract_Type__c;
      //  reqInput.BOCurrency = 'USD';
        reqInput.ContractValue = op.TCV__c;
                reqInput.EffectiveDate = op.CloseDate;
        reqInput.ContractDuration = op.Tenure__c;
        reqInput.ContractDurationUnitOfMesurement = op.Tenure_Unit_of_Measure__c ;
      //  reqInput.AccountCode= op.Account__r.Account_Code__c;
      //  reqInput.Description= op.Description;
        reqInput.SalesPerson1 =op.OpportunityTeamMembers[0].User.Email;
        reqInput.CreatedBy=op.Owner.Email;
                reqInput.ProspectName= op.Account.Name;
                reqInput.ContactPerson=op.OpportunityContactRoles[0].contact.firstName;
                reqInput.ContactNumber=op.OpportunityContactRoles[0].contact.phone;
                reqInput.Competitors=op.Competitors_Names__c;
                reqInput.ContactEmail = op.OpportunityContactRoles[0].contact.Email;
                reqInput.JobTitle=op.OpportunityContactRoles[0].contact.Title;
                reqInput.AccountName=op.Account.Name;

      inputRequest.add(reqInput);
      
      } 
    }
    String OpportunityInput = Json.serialize(inputRequest);
    System.debug('Input request to send Opportunity to iWise::'+OpportunityInput); 
    Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('Actual Endpoint to service');// also add this endpoint in remote site settings
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=utf-8');
        request.setHeader('Authorization', oAuthToken);
    request.setBody(OpportunityInput);
    
    System.debug('Request to send Opportunity:'+request);
    System.debug('Request body send Opportunity:'+request.getBody());
    
    HttpResponse response = http.send(request);
        system.debug('Response from iWise for Get Opportunity request:::'+response.toString());
    system.debug('Response from iWise for Get Opportunity request:::'+response.getBody());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
      System.debug('Success Response from iWise::'+response.getStatus());
        opty[0].Response_from_iWise_System__c=response.getStatusCode()+' - '+response.getStatus()+' - '+ response.getBody();
    }
    else{
      System.debug('Error Response from iWise::'+response.getStatus());
      opty[0].Response_from_iWise_System__c=response.getStatusCode()+' - '+response.getStatus()+' - '+ response.getBody();
    }
    if(!opty.isEmpty())
      Update opty;  
  }
}
Hello

I have my Salesforce.com Certified Administrator and Certified PD 1credential, and would like to gain more experience in the field.

I am having 1 Yr Exp in Salesforce Admin and Development.

I am located in Hyderabad, India. I am ready to contribute my time in delivering the Salesforce Project in my free time for free.

Appreciate any leads or any direction you can give.

Sincerely,
Nalini
srinalini.ch@gmail.com
Hello

I have added apex class and VF Page to override standard convert button to Accept Button. The mentioned below code is working fine. But it is getting converted in Classic Version. But need the lead Conversion Page in Lightning Version. Anyone Please suggest.

public class AutoConvertLeads {
    
    private final Lead lead; //variable for the standard Lead object
    
    public AutoConvertLeads(ApexPages.StandardController standardPageController) {
        this.lead = (Lead)standardPageController.getRecord(); //initialize the standard controller
    }
    
    public PageReference redirectToConvertionPage() {
        PageReference nextPage = new PageReference('/lead/leadconvert.jsp'); //set the starting point for the page reference to which the User will be sent
        nextPage = encodeAndSetParam(nextPage, 'retURL', lead.Id); //set the retURL parameter in order to allow for returning to Lead if User cancels from page
        nextPage = encodeAndSetParam(nextPage, 'id', lead.Id); //set the id parameter so that the conversion page knows the proper record
        nextPage = encodeAndSetParam(nextPage, 'nooppti', '1'); //set the nooppti parameter to pre-populate the "Do not create a new opportunity upon conversion." checkbox
        nextPage = encodeAndSetParam(nextPage, 'nooverride', '1'); //set the nooverride parameter in order to prevent looping in the user interface
        nextPage.setRedirect(true); //indicate that the redirect should be performed on the client side
        return nextPage; //send the User to the Lead conversion page
    }
    
    public PageReference encodeAndSetParam(PageReference passedPageReference, String passedParameterId, String passedParameterValue){
        if (passedParameterValue != null) { //if the passedParameterValue is not null
            String encodedParameterValue = EncodingUtil.urlEncode(passedParameterValue, 'UTF-8'); //encode the value that was passed to eliminate conflicts with unsafe characters
            passedPageReference.getParameters().put(passedParameterId, EncodingUtil.urlDecode(encodedParameterValue, 'UTF-8')); //add the parameter to the page reference
        }
        return passedPageReference;
    }

}

Visual Force Page:

<apex:page action="{!redirectToConvertionPage}" extensions="AutoConvertLeads" standardController="Lead">
    <apex:sectionHeader title="Accept" subtitle="{!Lead.Name}" help="/htviewhelpdoc?id=leads_convert.htm&siteLang=en_US"></apex:sectionHeader>
    <apex:pageMessages ></apex:pageMessages>
</apex:page>


Thanks
TS

 
Hello

I have a custom button. On clicking on that, a field update with checkbox true has to be done. How this can be done with Apex and VF. Any code, Please suggest.

Thanks
TS
Hello

I have added apex class and VF Page to override standard convert button to Accept Button. The mentioned below code is working fine. But it is getting converted in Classic Version. But need the lead Conversion Page in Lightning Version. Anyone Please suggest.

public class AutoConvertLeads {
    
    private final Lead lead; //variable for the standard Lead object
    
    public AutoConvertLeads(ApexPages.StandardController standardPageController) {
        this.lead = (Lead)standardPageController.getRecord(); //initialize the standard controller
    }
    
    public PageReference redirectToConvertionPage() {
        PageReference nextPage = new PageReference('/lead/leadconvert.jsp'); //set the starting point for the page reference to which the User will be sent
        nextPage = encodeAndSetParam(nextPage, 'retURL', lead.Id); //set the retURL parameter in order to allow for returning to Lead if User cancels from page
        nextPage = encodeAndSetParam(nextPage, 'id', lead.Id); //set the id parameter so that the conversion page knows the proper record
        nextPage = encodeAndSetParam(nextPage, 'nooppti', '1'); //set the nooppti parameter to pre-populate the "Do not create a new opportunity upon conversion." checkbox
        nextPage = encodeAndSetParam(nextPage, 'nooverride', '1'); //set the nooverride parameter in order to prevent looping in the user interface
        nextPage.setRedirect(true); //indicate that the redirect should be performed on the client side
        return nextPage; //send the User to the Lead conversion page
    }
    
    public PageReference encodeAndSetParam(PageReference passedPageReference, String passedParameterId, String passedParameterValue){
        if (passedParameterValue != null) { //if the passedParameterValue is not null
            String encodedParameterValue = EncodingUtil.urlEncode(passedParameterValue, 'UTF-8'); //encode the value that was passed to eliminate conflicts with unsafe characters
            passedPageReference.getParameters().put(passedParameterId, EncodingUtil.urlDecode(encodedParameterValue, 'UTF-8')); //add the parameter to the page reference
        }
        return passedPageReference;
    }

}

Visual Force Page:

<apex:page action="{!redirectToConvertionPage}" extensions="AutoConvertLeads" standardController="Lead">
    <apex:sectionHeader title="Accept" subtitle="{!Lead.Name}" help="/htviewhelpdoc?id=leads_convert.htm&siteLang=en_US"></apex:sectionHeader>
    <apex:pageMessages ></apex:pageMessages>
</apex:page>


Thanks
TS

 
Hello

I have a custom button. On clicking on that, a field update with checkbox true has to be done. How this can be done with Apex and VF. Any code, Please suggest.

Thanks
TS
Hi there, I am trying to emulate the "convert lead" action on a custom object of mine which I've made a path for (see below)User-added image

When I click on the final stage in my Path, I would like it to generate a pop-up that will then let me create new records in related objects.  Is this possible?  Here is a picture of what im talking about.

User-added image

If anyone could should me how to do this I would really appreciate it!