• Alex Calder 10
  • NEWBIE
  • 20 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 5
    Replies
I am struggleing understanding how to write test units for this class. 
 
//@RestResource(urlMapping='/Google/*') is used to tell the class that it is a REST resource used for POST GET etc
@RestResource(urlMapping='/Google/*')
global with sharing class GoogleWebHookListener {
    //HttpPost tells the method that it will be a POST method
    @HttpPost
    global static void handlePost() {
        
        //set up varibles for the Lead
        String name;
        String phone;
        String email;
        String postCode;
        String firstName;
        String lastName;
        
        //try to do the JSON deserialization and Lead Creation
        //******EXAMPLE JSON AT BOTTOM*****
        try
        {
            // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString'
            String jsonString = RestContext.request.requestBody.toString();
            //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample
            GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class);
            
            //This tests the JSON to see if it is legit.
            if(g.google_key == ''){
                
                //This loops through the JSON array set up in the Class GoogleJsonLeadExample
                
               for(GoogleJsonLeadExample.userData d : g.user_column_data)
               {
                   if(d.column_name == 'Full Name')
                   {
                       //The JSON has Full Name, this breaks Full Name into First and Last Names
                        name = d.string_value;
                        List<String> names = name.split(' ');
                       	firstName = names[0];
                        lastName = names[1];
                           
                   }
                   if(d.column_name == 'User Phone')
                   {
                        phone = d.string_value;
                   }
                   if(d.column_name == 'User Email')
                   {
                        email = d.string_value;
                   }
                   if(d.column_name == 'Postal Code')
                   {
                       postCode = d.string_value;
                   }
               }
              
                //This creates the Lead                 
            Lead detail = new Lead();
            detail.LastName = lastName;
            detail.FirstName = firstName;
            detail.Phone = phone;
            detail.Company = name;
            detail.Email = email;
            detail.OwnerId = '0051Q00000GrANL'; // This Id is the user Hubspot.
            insert detail;
           
            }
                                        
        }
        catch (DMLException e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }

}

 
public class DriveCode{
 
     @future (callout=true)  // future method needed to run callouts from Triggers
      public static void getDistance(){
        // gather account info
        Property__c [] a = [SELECT  Street_Address__c, 
                                  City__c, 
                                  State__c,
                                  Zip__c, 
                                  Service_Center__c,
                                  NeedDistance__c 
                                  FROM Property__c 
                                  WHERE Id ='a031Q00001wPRnYQAW'];
                            
        
        if(a[1].NeedDistance__c == true){  
            // build callout
            String dstreet = ' ';
            String dcity = ' ';
            String dstate = ' ';
            String dzip = ' ';
            String saddress = ' ';
            if(a[1].Street_Address__c != null){dstreet = a[1].Street_Address__c;}
            if(a[1].City__c != null){dcity = a[1].City__c;}
            if(a[1].State__c != null){dstate = a[1].State__c;}
            if(a[1].Zip__c != null){dzip = a[1].Zip__c;}
            if(a[1].Service_Center__c != null){saddress = a[1].Service_Center__c;}
            String destaddress = EncodingUtil.urlEncode(dstreet + ' ' + dcity + ' ' + dstate + ' ' + dzip, 'UTF-8');
            String serveaddress = EncodingUtil.urlEncode(saddress, 'UTF-8');
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            //req.setEndpoint('http://maps.googleapis.com/maps/api/distancematrix/json?origins=' + a[1].Origin_Zip__c + '&destinations=' + a[1].Destination_Zip__c + '&mode=driving&units=imperial&sensor=false');
            req.setEndpoint('http://maps.googleapis.com/maps/api/distancematrix/json?origins=' + destaddress +'&destinations=' + serveaddress + '&key=AIzaSyDgO1iTw2QWJMBbgn73ODqgryrZ6sLtWTw');
            //req.setEndpoint(EncodingUtil.urlEncode('http://maps.googleapis.com/maps/api/distancematrix/json?origins=' + a[1].Origin_Street__c + '+' + a[1].Origin_City__c + '+' + a[1].Origin_State__c + '+' + a[1].Origin_Zip__c + '&destinations=' + a[1].Destination_Street__c + '+' + a[1].Destination_City__c + '+' + a[1].Destination_State__c + '+' + a[1].Destination_Zip__c + '&mode=driving&units=imperial&sensor=false', 'UTF-8'));
            //req.setEndpoint(GEOCODING_URI_BASE + EncodingUtil.urlEncode(address, 'UTF-8'));
            req.setMethod('GET');
            req.setTimeout(60000);
            integer distance = null;
            string tdistance = null;
            //HttpResponse res = h.send(req);
            // callout
            HttpResponse res = h.send(req);
            System.debug(res.getBody());
            // parse coordinates from response
            JSONParser parser = JSON.createParser(res.getBody());
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
                    (parser.getText() == 'distance')){
                       parser.nextToken(); // object start
                       while (parser.nextToken() != JSONToken.END_OBJECT){
                           String txt = parser.getText();
                           parser.nextToken();
                           if (txt == 'text')
                               tdistance = parser.getText();
                           else if (txt == 'value')
                               distance = parser.getIntegerValue();
                       }
                }
            }
 
            // update coordinates if we get back
            if (distance != null){
                a[1].Distance_Miles__c = distance;
                //a[1].tdistance__c = tdistance;
                a[1].NeedDistance__c = False;
                //a[1].Description1__c = req.getEndpoint();
                //a[1].Description2__c = res.getBody();
                //String originaddress = a[1].Origin_Street__c != null ? a[1].Origin_Street__c + ' ' : '' +
                //a[1].Origin_City__c != null ? a[1].Origin_City__c + ' ' : '' +
                //a[1].Origin_State__c != null ? a[1].Origin_State__c + ' ' : '' +
                //a[1].Origin_Zip__c != null ? a[1].Origin_Zip__c : '';
                //String originaddress = EncodingUtil.urlEncode(a[1].Origin_Street__c + ' ' + a[1].Origin_City__c + ' ' + a[1].Origin_State__c + ' ' + a[1].Origin_Zip__c, 'UTF-8');
                a[1].LinkToDirections__c = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=' + destaddress +'&destinations=' + serveaddress + '&key=AIzaSyDgO1iTw2QWJMBbgn73ODqgryrZ6sLtWTw';
                //a[1].Description1__c = EncodingUtil.urlEncode(originaddress, 'UTF-8') + '---' + originaddress;
                update a;
            }
        } 
          Else {
              a[1].LinkToDirections__c = 'test';
              a[1].NeedDistance__c = True;
              update a;
          }
      }
      
}
@isTest
private class DrivefutureTest {
    @isTest static void test1() {
            // startTest/stopTest block to run future method synchronously
            Test.startTest();        
            DriveCode.getDistance();
            Test.stopTest();
        }
        
    
}

I am not a coder, but I am pretty ok at finding code and making it work.  Can someone please help with with this.  Why is it not finding the record.
trigger opportunity_contact_required on Opportunity (after insert, after update) {

    //map to keep track of the contact_required = 1
    Map<String, Opportunity> oppy_contact = new Map<String, Opportunity>();

    //Trigger.new is an array of opportunities 
    //and adds any that have Contact_Required = 1 to the oppy_contact Map
    for (Integer i = 0; i < Trigger.new.size(); i++) {
        System.debug('*****Required? ' + Trigger.new[i].contact_required__c);
        if  (Trigger.new[i].contact_required__c == 1) {
            oppy_contact.put(Trigger.new[i].id,Trigger.new[i]);
        }
    }

    //map to keep track of the opportunity contact roles
    map<Id, OpportunityContactRole> oppycontactroles = new map<Id, OpportunityContactRole>();

    //select OpportunityContactRoles for the opportunities with contact role required 

    List<OpportunityContactRole> roles = [select OpportunityId, IsPrimary from OpportunityContactRole
        where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId
        in :oppy_contact.keySet())];


    for (OpportunityContactRole ocr : roles) {
        //puts the contact roles in the map with the Opportunity ID as the key
        oppycontactroles.put(ocr.OpportunityId,ocr);
    }

    // Loop through the opportunities and check if they exists in the contact roles map or contact role isn't required    
    for (Opportunity oppy : system.trigger.new) {
        //system.debug('List oppy Id - '+oppy.id);
        if  (oppy.contact_required__c ==1 && !oppycontactroles.containsKey(oppy.id))
        {
            oppy.addError('No Primary Contact Exists. Please go to the Contact Roles and select a primary contact.  Insure that all contacts related to this Opportunity are properly added in the Contact Roles with respective roles assigned.');       
        }
    } 
 }
In classic, if the user starts with with a contact the map oppycontactroles is populated.  In Lightning the map oppycontactroles is not populated. 
 
Is there a way to tell a trigger that it was started from a certain page?  For example, if a new opportunity is created from the Contact page then do something, if created from Account page do something, if created from a custom object then do something, so on and so forth.
I am struggleing understanding how to write test units for this class. 
 
//@RestResource(urlMapping='/Google/*') is used to tell the class that it is a REST resource used for POST GET etc
@RestResource(urlMapping='/Google/*')
global with sharing class GoogleWebHookListener {
    //HttpPost tells the method that it will be a POST method
    @HttpPost
    global static void handlePost() {
        
        //set up varibles for the Lead
        String name;
        String phone;
        String email;
        String postCode;
        String firstName;
        String lastName;
        
        //try to do the JSON deserialization and Lead Creation
        //******EXAMPLE JSON AT BOTTOM*****
        try
        {
            // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString'
            String jsonString = RestContext.request.requestBody.toString();
            //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample
            GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class);
            
            //This tests the JSON to see if it is legit.
            if(g.google_key == ''){
                
                //This loops through the JSON array set up in the Class GoogleJsonLeadExample
                
               for(GoogleJsonLeadExample.userData d : g.user_column_data)
               {
                   if(d.column_name == 'Full Name')
                   {
                       //The JSON has Full Name, this breaks Full Name into First and Last Names
                        name = d.string_value;
                        List<String> names = name.split(' ');
                       	firstName = names[0];
                        lastName = names[1];
                           
                   }
                   if(d.column_name == 'User Phone')
                   {
                        phone = d.string_value;
                   }
                   if(d.column_name == 'User Email')
                   {
                        email = d.string_value;
                   }
                   if(d.column_name == 'Postal Code')
                   {
                       postCode = d.string_value;
                   }
               }
              
                //This creates the Lead                 
            Lead detail = new Lead();
            detail.LastName = lastName;
            detail.FirstName = firstName;
            detail.Phone = phone;
            detail.Company = name;
            detail.Email = email;
            detail.OwnerId = '0051Q00000GrANL'; // This Id is the user Hubspot.
            insert detail;
           
            }
                                        
        }
        catch (DMLException e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }

}

 
I am struggleing understanding how to write test units for this class. 
 
//@RestResource(urlMapping='/Google/*') is used to tell the class that it is a REST resource used for POST GET etc
@RestResource(urlMapping='/Google/*')
global with sharing class GoogleWebHookListener {
    //HttpPost tells the method that it will be a POST method
    @HttpPost
    global static void handlePost() {
        
        //set up varibles for the Lead
        String name;
        String phone;
        String email;
        String postCode;
        String firstName;
        String lastName;
        
        //try to do the JSON deserialization and Lead Creation
        //******EXAMPLE JSON AT BOTTOM*****
        try
        {
            // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString'
            String jsonString = RestContext.request.requestBody.toString();
            //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample
            GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class);
            
            //This tests the JSON to see if it is legit.
            if(g.google_key == ''){
                
                //This loops through the JSON array set up in the Class GoogleJsonLeadExample
                
               for(GoogleJsonLeadExample.userData d : g.user_column_data)
               {
                   if(d.column_name == 'Full Name')
                   {
                       //The JSON has Full Name, this breaks Full Name into First and Last Names
                        name = d.string_value;
                        List<String> names = name.split(' ');
                       	firstName = names[0];
                        lastName = names[1];
                           
                   }
                   if(d.column_name == 'User Phone')
                   {
                        phone = d.string_value;
                   }
                   if(d.column_name == 'User Email')
                   {
                        email = d.string_value;
                   }
                   if(d.column_name == 'Postal Code')
                   {
                       postCode = d.string_value;
                   }
               }
              
                //This creates the Lead                 
            Lead detail = new Lead();
            detail.LastName = lastName;
            detail.FirstName = firstName;
            detail.Phone = phone;
            detail.Company = name;
            detail.Email = email;
            detail.OwnerId = '0051Q00000GrANL'; // This Id is the user Hubspot.
            insert detail;
           
            }
                                        
        }
        catch (DMLException e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }

}

 
Is there a way to tell a trigger that it was started from a certain page?  For example, if a new opportunity is created from the Contact page then do something, if created from Account page do something, if created from a custom object then do something, so on and so forth.
Hello, We have had random disruptions and issues with our Google Maps API call this week. Does anyone know of issues with this call and wether or not this could be a Winter 16 release issue. Our org was updated over the weekend and the issues began on Monday. What we have is an object in SFDC built to collect Origin Zip Code and Destination Zip Code and the call goes to GMDM and returns the distance in meters. It has returned too many zeros this week ocasionally returning results with a refresh or clone and working some hours of the day, some hours not.... Help please!