• Harshit Kumar 27
  • NEWBIE
  • 3 Points
  • Member since 2022
  • Software Engineer
  • Trantor

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 3
    Likes Given
  • 6
    Questions
  • 9
    Replies
I'm using a dynamic process to consume API and return the list which can be used in batch class to process all the records and insert them.
I've used custom settings and custom metadata types.
Endpoint: https://gorest.co.in/public/v1/users
Please find below my code and help me write its test class.

// ContactAPIController
public with sharing class ContactAPIController {
    public static HttpResponse getContact(String var,Integer page){
        CTdata__c ct = CTdata__c.getOrgDefaults();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(ct.Endpoint__c+var+'?page='+page);
        request.setMethod('GET');
        request.setTimeout(120000);
        try {
            Http http = new Http();
            HttpResponse res = http.send(request);
            System.debug('Status Code:: '+res.getStatusCode());
            System.debug('Body:: '+res.getBody());
            return res;
        }catch(System.CalloutException ex) {
            System.debug('ex:: '+ex.getMessage());
            return null;
        }
    }
    
    // Dynamic method to consume API and return List<SObject>
    public static List<SObject> contactAPIProcessor(String objAPIName, String var, Map<String,Account> mapContactNumberToAcc) {                        
        List<Object> objRecords = new List<Object>();
        HttpResponse resObj = ContactAPIController.getContact(var,1);
        Map<String,Object> jsonObjMap = (Map<String,Object>)JSON.deserializeUntyped(resObj.getBody());
        objRecords = (List<Object>) jsonObjMap.get('data');

        if(resObj.getStatusCode() == 200 && (Integer)jsonObjMap.get('total') > 1) {
            Double pages = Math.ceil((Double) jsonObjMap.get('total')/10);
            System.debug('pages---'+pages);
            for(Integer i=2; i<=pages; i++) {
                jsonObjMap = null;
                HttpResponse resObjects = ContactAPIController.getContact(var,i);
                jsonObjMap = (Map<String,Object>)JSON.deserializeUntyped(resObjects.getBody());
                objRecords.addAll((List<Object>) jsonObjMap.get('data'));
            }
        }
        System.debug('objRecords---'+objRecords);
        List<SObject> objList = new List<SObject>();
        Map<String, Schema.SObjectType> gdMap = Schema.getGlobalDescribe();
        Map<String, Contact__mdt> contactData = Contact__mdt.getAll();
        Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(objAPIName).getDescribe().fields.getMap(); 
        Schema.SObjectType st = gdMap.get(objAPIName);
        for(Object obj: objRecords){ 
            Sobject objName = st.newSobject();
            Map<String,Object> rMap = (Map<String,Object>)obj;                        
            String Id = String.valueOf(rMap.get('id'));         
            if(mapContactNumberToAcc.containsKey(Id) && Id == mapContactNumberToAcc.get(Id).Contact_Number__c){
                objName.put('AccountId', mapContactNumberToAcc.get(Id).Id);                                
                for(String fieldName : rMap.keySet()){                                         
                    if(contactData.containsKey(fieldName) || contactData.containsKey(fieldName.toLowerCase())){                        
                        String fieldAPIName;
                        if(contactData.containsKey(fieldName.toLowerCase())){
                            fieldAPIName = fieldMap.get(contactData.get(fieldName.toLowerCase()).API_Name__c).getDescribe().getName(); 
                        }else{
                            fieldAPIName = fieldMap.get(contactData.get(fieldName).API_Name__c).getDescribe().getName(); 
                        }                     
                        if(fieldName == 'id'){                            
                            objName.put(fieldAPIName, String.valueOf(rMap.get(fieldName)));
                        }else{
                            objName.put(fieldAPIName, rMap.get(fieldName));
                        }                    
                    }                                                                                                   
                }     
                objList.add(objName);
            }
        }
        return objList;
	}
}

// BatchToProcessContactAPIResponse
global class BatchToProcessContactAPIResponse implements Database.Batchable<SObject>, Database.Stateful, Database.AllowsCallouts {
	global final String query;
    global BatchToProcessContactAPIResponse(String query) {
        this.query = query;
    }
    global BatchToProcessContactAPIResponse() {
        query = 'SELECT Id, Name, Contact_Number__c FROM Account WHERE Contact_Number__c != null';
    }
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope) {
        //System.debug(scope);
        Map<String,Account> mapContactNumberToAcc = new Map<String,Account>();
        for(Account acc : scope) {
            mapContactNumberToAcc.put(acc.Contact_Number__c,acc);
        }
        
        List<Contact> conList = (List<Contact>) ContactAPIController.contactAPIProcessor('Contact', 'users', mapContactNumberToAcc);
        System.debug('conList:: '+conList);
       	
        if(conList.size() > 0) insert conList;
    }
    
    global void finish(Database.BatchableContext BC) {
    }
}

 
Scenario:

Trigger to update the most recent opportunity stagename on contact. Now the most recent opportunity can be associated with multiple contacts through Opportunity Contact Roles.
If it is the most recent one for all the contacts then update the stagename on the respective contact.
This is what I've tried but it does not seem to be working. 
Please help me with this.
Map<Id,String> conIdVsStageMap = new Map<Id,String>();
        for(Opportunity opp : oppList) {
            conIdSet.add(opp.ContactId);
        }
        List<OpportunityContactRole> ocrList = [SELECT ContactId, Contact.Name, OpportunityId, Opportunity.Name FROM OpportunityContactRole];
        List<Contact> conList = [SELECT Id, Most_Recent_Opportunity_Stage__c FROM Contact WHERE Id IN :conIdSet];
        
        for(Opportunity opp : oppList) {
            conIdVsStageMap.put(opp.ContactId, opp.StageName);
        }
        
        for(Contact con : conList) {
            if(conIdVsStageMap.containsKey(con.Id)) {
                con.Most_Recent_Opportunity_Stage__c = conIdVsStageMap.get(con.Id);
            }
        }

 
Suppose we have a contact which is having three opportunities related to it. Now I've created a new field on contact named recent_opp_stage__c. I want to display the stage name of the most recently created opportunity associated with the contact.
Please help me write an Apex trigger or create a flow for this.
I'm writing a batch class to send notification to only the latest contact that exist on an account.
 
global class ContactProcessor implements Database.Batchable<sObject>() {
gloal final String query;
global ContactProcessor(){  
        query = ' SELECT Id, Name, CreatedDate FROM Contact ORDER BY CreatedDate DESC';
}

global Database.QueryLocator start(Database.BatchableContext BC){
    return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Contact> scope) {
  // how to fetch only the latest created contact record from the records that are coming through the query.
  // LIMIT 1 cannot be used.
}

global void finish(Database.BatchableContext BC) {

}

}
Ex - On Account i have two contacts (C1 and C2). I want to fetch the latest created contact record and send notification to the latest one only.
There is a picklist field called Role on Contact object with values
Manager, Lead, Developer and create one field called Higher Role on Account object.
Write a trigger to update account Higher role field.
Ex : We have 3 contacts to one account with roles as manager, lead, developer.
Manager will be populated as Manager is higher role
Suppose if we have contacts with roles lead and developer only then lead will be populated as Lead is higher role
Priority: Manager > Lead > Developer.
Both Role and Account can be changed.
Create following fields on Opportunity sObject -
Coupon 1 (Boolean)
Coupon 2 (Boolean)
Coupon 3 (Boolean)
Write a trigger on opportunity if the amount is greater than 10% of expected revenue then check coupon 1 and if 20% then check coupon 2 and if 30% then check coupon 3.
Suppose we have a contact which is having three opportunities related to it. Now I've created a new field on contact named recent_opp_stage__c. I want to display the stage name of the most recently created opportunity associated with the contact.
Please help me write an Apex trigger or create a flow for this.
In the Visit__c object, if more than 2 visit are made in the name of the same owner, then the error is given that you can't create more than 2 visit  by the same owner ????by trigger
Create the opportunity whose state is closewon & account is !null then update closedate__c on account as todat date by trigger handler ??