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
RahulRahul 

hello friends, can you help me with test class of this class. As its integration its difficult for me to write it. Thanks in advance

//To get all the leads from housing
public class HousingHelper
{  
    public static void searchLead()
    {   
        //to check if lead is already created for today
        Set<String> setOfMobiles = new Set<String>();
        Set<String> setOfEmails = new Set<String>();
        //for error mail
        String errorBody = '';
        Boolean hasError = false ;
        //start date
        Date todayDate = System.today();
        DateTime startDateToday=Datetime.newInstance(todaydate.year(), todaydate.month(), todaydate.day(), 00, 00, 00);
        Long epochStartDate = (startDateToday.getTime()/1000);
        DateTime endDateToday=Datetime.newInstance(todaydate.year(), todaydate.month(), todaydate.day(), 23, 59, 59);
        Long epochEndDate = (endDateToday.getTime()/1000);
        String salt = String.valueOf((datetime.now().getTime()/1000));
        String key = 'b13cad2be5dde31ebca4c6f451e02abe';
        Blob mac = Crypto.generateMac('HmacSHA256', Blob.valueOf(salt), Blob.valueOf(key));
        String encripted = EncodingUtil.convertToHex(mac);
        String idValue = '171726';
        Http h = new Http();
        HttpRequest request = new HttpRequest();
        request.setMethod('GET');
        request.setEndPoint('https://leads.housing.com/api/v0/get-builder-leads?start_date='+epochStartDate+'&end_date='+epochEndDate+'&current_time='+salt+'&hash='+encripted+'&id='+idValue);
        HttpResponse response = new HttpResponse(); 
        response = h.send(request);
        system.debug('status code:'+response.getStatuscode());
        system.debug('code: '+response.getBody());
        try
        {
            List<HousingHelper.wrapperLeadsHousing> wrapResponse = new List<HousingHelper.wrapperLeadsHousing>();//wrapper for consuming response from the API
            wrapResponse = (List<HousingHelper.wrapperLeadsHousing>)System.JSON.deserialize(response.getBody(),List<HousingHelper.wrapperLeadsHousing>.class);//converting response into object in salesforce
            if(wrapResponse.size()>0){
                Id queueId = [Select id, Name from Group where type='Queue' AND Name='Unassigned Leads' limit 1].Id;
                Id freshSales= [select id from recordtype where name='Fresh Sales' AND sObjectType='Lead'].id;
                List<Lead> newLeads = new List<Lead>();
                /*========== To check if leads with same mobile or email are created today ===================================
for(HousingHelper.wrapperLeadsHousing tempResponse : wrapResponse){
if(tempResponse.lead_Email != null)    setOfEmails.add(tempResponse.lead_Email);
if(tempResponse.lead_phone != null)    setOfMobiles.add(tempResponse.lead_phone);
}
Date filterDate= system.today();
List<Lead> listOfLeads = new List<Lead>();
listOfLeads = [Select Id, Name, MobilePhone, Email, Project__c,createdDate from Lead where (Email in : setOfEmails Or MobilePhone in : setOfMobiles) AND DAY_ONLY(convertTimezone(CreatedDate))=:filterDate];
======= Ends here ========================================================================================== */
                //New lead creation
                for(HousingHelper.wrapperLeadsHousing tempResponse : wrapResponse){
                    Lead tempLead = new Lead();
                    //lead name mapping
                    /* if((!setOfEmails.contains(tempResponse.lead_phone)) && (!setOfMobiles.contains(tempResponse.lead_Email)))
{    */                     
                    if(tempResponse.lead_name!=null){
                        String[] splitName = tempResponse.lead_name.split(' ');
                        if(splitName.size()>0){
                            //split the name into first name and last name
                            if(splitName.size()==1){
                                //tempLead.FirstName = splitName[0];
                                tempLead.LastName = splitName[0];
                            }
                            else{
                                tempLead.FirstName = splitName[0];
                                integer sizeArr = 1;
                                String tempLastName = '';
                                while(sizeArr<splitName.size()){
                                    tempLastName+=splitName[sizeArr]+' ';
                                    sizeArr++;
                                }
                                tempLead.lastName = tempLastName;
                            }
                        }
                    }
                    else
                        tempLead.lastName = 'Not provided';
                    
                    tempLead.LeadSource = 'Online';
                    tempLead.Lead_Medium__c='Housing';
                    string mobile;
                    if(tempResponse.lead_phone != null)
                        mobile=tempResponse.lead_phone;
                    if(mobile != null) {                      
                        mobile= mobile.deleteWhitespace();
                        mobile= mobile.remove(',');
                        if(mobile.length()==10)
                            tempLead.MobilePhone = mobile;
                        else
                            tempLead.Alt_Mobile__c = mobile;
                    }
                    string email=tempResponse.lead_Email;
                    if(email != null){
                        email= email.deleteWhitespace();
                        email= email.remove(',');
                    }
                    tempLead.Email = email;
                    tempLead.Primary_Customer_Status__c = 'Unattended';
                    tempLead.Company = 'Company name not provided';
                    tempLead.RecordTypeId = freshSales;
                    if(tempResponse.project_name == 'Ashiana Town B')
                        tempLead.ProjectName__c = 'Ashiana Town';
                    else
                        tempLead.ProjectName__c = tempResponse.project_name;
                    tempLead.Country_Code__c = tempResponse.country_code ;
                    //tempLead.Address_line_1__c = tempResponse.locality_name ;
                    if(queueId!=null){
                        tempLead.OwnerId = queueId;    
                    }
                    newLeads.add(tempLead);
                    //}
                }//End of For loop Housing Loop
                try{
                    
                    Database.SaveResult[] srList = Database.insert(newLeads,False);
                    String errorMsg = '<table border="1" align="center" style="width:100%;border-collapse: collapse;"><caption>Housing Lead Error Table</caption><tr style="background-color:#87CEFA !important;"><th>Lead Name</th><th>Mobile</th><th>Email Id</th><th>Project</th><th>Field</th><th>Error message</th></tr>';
                    // Iterate through each returned result
                    for (Integer i=0;i<srList.size();i++) {
                        if (srList[i].isSuccess()) {
                            // Operation was successful, so get the ID of the record that was processed
                            System.debug('Successfully inserted lead. Lead ID: ' + srList[i].getId());
                        }
                        else {
                            
                            hasError = true;
                            String error = '';
                            String fields='';
                            // Get all errors                
                            for(Database.Error err : srList[i].getErrors()) {
                                System.debug('The following error has occurred.');                    
                                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                                System.debug('Lead fields that affected this error: ' + err.getFields());
                                error+=err.getMessage();
                                fields+=err.getFields();
                            }
                            errorMsg+='<tr><td style="width:13%;"><center>'+newLeads[i].FirstName+' '+newLeads[i].LastName+'<center></td><td style="width:13%;"><center>'+newLeads[i].MobilePhone+'<center></td><td style="width:13%;"><center>'+newLeads[i].Email+'<center></td><td style="width:10%;"><center>'+newLeads[i].ProjectName__c+'<center></td><td style="width:10%;"><center>'+fields+'<center></td><td style="width:20%;"><center>'+error+'<center></td></tr>' ;
                        }
                    }
                    if(hasError){
                        errorMsg += '</table>';
                        errorBody = '<html><body>Dear Admin,<br/><br/>Error in following leads : <br/><br/>'+errorMsg;
                    }
                }
                catch(DMLException e){
                    //hasError = true;
                    //errorBody = '<html><body>Dear Admin,<br/><br/>Error due to '+e.getMessage();
                    System.debug('Error in inserting leads from housing due to '+e.getMessage());
                }
            }            
        }
        Catch(Exception e)
        { 
            //hasError = true;
            //errorBody = '<html><body>Dear Admin,<br/><br/>Error due to '+e.getMessage();
            system.debug('error'+e.getMessage());
        }
        if(hasError){
            list<Email_for_integration_error_mail__mdt> tempEmailIds = [Select Email__c from Email_for_integration_error_mail__mdt];
            
            system.debug('tempEmailIds:'+tempEmailIds);
            List<String> emailIds = new List<String>();
            for(Email_for_integration_error_mail__mdt email : tempEmailIds){
                emailIds.add(email.Email__c);
            }
            system.debug('emailIds:'+emailIds);
            errorBody +='<br/><br/><br/>Thanks & Regards</body></html>';
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.toAddresses =  emailIds;
            message.subject = 'Error in Housing Lead Integrations || Date : '+(System.today()).format();
            message.setHtmlBody(errorBody);
            message.setsaveAsActivity(false);
            Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            if (results[0].success) {
                System.debug('The email was sent successfully.');
            } else {
                System.debug('The email failed to send: ' + results[0].errors[0].message);
            } 
        }
        
        
        
    }
    
    public class wrapperLeadsHousing { // Convert API response to object in salesforce to save leads
        public Integer lead_date;
        public String lead_name;
        public String lead_email;
        public String lead_phone;
        public String country_code;
        public Integer project_id;
        public String project_name;
        public String locality_name;
        
    }
}