0

My requirement is I need to block the creation of Account records based on apex future callout response

TriggerCode

trigger AccountTrigger on Account (before insert) {

    Set<Id> accLst = new Set<Id>();
    
    if(Trigger.isInsert && Trigger.isBefore){
    for(Account accNew: Trigger.New) {
        system.debug('CC ID' + accNew);
        accLst.add(accNew.Id);
       
    }
        System.debug('testing@@' + accNew);
     SAPIntegration.Integrationsap(accLst);
    }

}

ApexCallout class

global class SAPIntegration{

  @future(callout = true)
  global static void Integrationsap(Set<Id> acclst) {
      
    List<Account> DelAccLst= [select id, IsPersonAccount,Business_Partner_Grouping__c,Business_Partner_Role__c,FirstName,
                              LastName,BillingAddress,BillingPostalCode,BillingCity, Phone, Preferred_Contact_Method__c,
                              Registration_No__c,Trade_License_No__c,Preferred_Language__pc,TRN__c, Salutation,Nationality__pc,
                              PersonMobilePhone, PersonEmail, Preferred_Contact_Method__pc,Emirates_ID_Number__pc,Passport_No__pc,
                              Passport_No__c,
                              Preferred_Language__c,Search_Term__c,Nationality__c,BillingStreet  from account where id in : acclst];

    HttpRequest req = new HttpRequest();
    req.setHeader('X-API-Key', 'xxxxx');
    req.setHeader('Content-Type', 'application/json');
    String endpoint = 'https://apiservices.qpropertie.xxx/api/qh-xxx/xxxx';
    req.setMethod('POST');
    req.setEndpoint(endpoint); 
    req.setTimeout(120000);
    map<String,String> mapOfCountryNameToCountrycode = new map<String, String>(); 
    map<String,String> mapOfLanguageNameToLanguagecode = new map<String, String>();
   

    // retrieve metadata values to get Country code of the respective country names 
    Map<String, Account_Nationality_Code__mdt> countryName = Account_Nationality_Code__mdt.getAll();
    for(Account_Nationality_Code__mdt country : countryName.values()){
        
       mapOfCountryNameToCountrycode.put(country.MasterLabel, country.DeveloperName);
       
    }
        Map<String, Account_Language_Code__mdt> languageName = Account_Language_Code__mdt.getAll();
    for(Account_Language_Code__mdt language : languageName.values()){
        
       mapOfLanguageNameToLanguagecode.put(language.MasterLabel, language.DeveloperName);
       
    }
     List<Account> accntLst = new List<Account>();
     String jsonData = '';
     if(!DelAccLst.isEmpty()){
            JSONGenerator jsonGen = JSON.createGenerator(true);
            for(Account con : DelAccLst){
                jsonGen.writeStartObject();
            
                if(!con.IsPersonAccount) {
                jsonGen.writeObjectField('BusinessPartnerCategory','1');
                    if(con.Business_Partner_Grouping__c != null) {
                   jsonGen.writeObjectField('BusinessPartnerGrouping',con.Business_Partner_Grouping__c);
                    }
                    else {
                     jsonGen.writeObjectField('BusinessPartnerGrouping','Z051');   
                    }
                jsonGen.writeFieldName('to_BusinessPartnerRole');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                    if(con.Business_Partner_Role__c != null) {
                  jsonGen.writeObjectField('BusinessPartnerRole',con.Business_Partner_Role__c);
                    }
                    else {
                     jsonGen.writeObjectField('BusinessPartnerRole','ZTR601');   
                    }
                
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                    if(con.FirstName != null) {
                 jsonGen.writeObjectField('FirstName',con.FirstName);
                    }
                    else {
                     jsonGen.writeObjectField('FirstName','BP Odata Service');   
                    }
                    if(con.LastName != null) {
                    jsonGen.writeObjectField('LastName',con.LastName);
                    }
                    else {
                     jsonGen.writeObjectField('LastName','SFDC');   
                    }
                    
                     if(con.Preferred_Language__c != null) {
                    jsonGen.writeObjectField('CorrespondenceLanguage',mapOfLanguageNameToLanguagecode.get(con.Preferred_Language__c));
                    jsonGen.writeObjectField('Language',mapOfLanguageNameToLanguagecode.get(con.Preferred_Language__c));
                    }
                    else {
                     jsonGen.writeObjectField('CorrespondenceLanguage','EN');  
                     jsonGen.writeObjectField('Language','EN');
                    }
                    
                     if(con.Search_Term__c != null) {
                   jsonGen.writeObjectField('SearchTerm1',con.Search_Term__c);
                    }
                    else {
                     jsonGen.writeObjectField('SearchTerm1','Test');
                    }
                    
                     jsonGen.writeObjectField('FormOfAddress','0003');
                    if(con.Nationality__c != null) {
                    jsonGen.writeObjectField('NameCountry',mapOfCountryNameToCountrycode.get(con.Nationality__c));
                    }
                    else {
                     jsonGen.writeObjectField('NameCountry','AE');
                    }
                   
                jsonGen.writeFieldName('to_BusinessPartnerAddress');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                 if(con.BillingStreet != null) {
                    jsonGen.writeObjectField('StreetName',con.BillingStreet);
                    }
                    else {
                     jsonGen.writeObjectField('StreetName','Park Street');
                    } 
                    
                    if(con.BillingAddress != null) {
                    jsonGen.writeObjectField('HouseNumber','hno');
                    }
                    else {
                    jsonGen.writeObjectField('HouseNumber','H.No.');
                    } 
                    
                    if(con.BillingPostalCode != null) {
                    jsonGen.writeObjectField('PostalCode',con.BillingPostalCode);
                    }
                    else {
                    jsonGen.writeObjectField('PostalCode','12456');
                    } 
                    
                     
                    if(con.BillingCity != null) {
                   jsonGen.writeObjectField('CityName',con.BillingCity);
                    }
                    else {
                    jsonGen.writeObjectField('CityName','Abu Dhabi');
                    } 
                    
                     if(con.Nationality__c != null) {
                    jsonGen.writeObjectField('Country',mapOfCountryNameToCountrycode.get(con.Nationality__c));
                    }
                    else {
                    jsonGen.writeObjectField('Country','AE');
                    } 
                    
                     if(con.BillingPostalCode != null) {
                    jsonGen.writeObjectField('POBox',con.BillingPostalCode);
                    }
                    else {
                    jsonGen.writeObjectField('POBox','392934');
                    } 
                jsonGen.writeFieldName('to_MobilePhoneNumber');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                     if(con.Phone != null) {
                    jsonGen.writeObjectField('PhoneNumber',con.Phone);
                    jsonGen.writeObjectField('IsDefaultPhoneNumber',true);
                    }
                    else {
                    jsonGen.writeObjectField('PhoneNumber','12040939');
                    jsonGen.writeObjectField('IsDefaultPhoneNumber',false);
                    } 
               
              
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                jsonGen.writeFieldName('to_PhoneNumber');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                     if(con.Phone != null) {
                     jsonGen.writeObjectField('PhoneNumber',con.Phone);
                     jsonGen.writeObjectField('IsDefaultPhoneNumber',true);
                    }
                    else {
                    jsonGen.writeObjectField('PhoneNumber','12040939');
                    jsonGen.writeObjectField('IsDefaultPhoneNumber',false);
                    } 
               
                
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                jsonGen.writeFieldName('to_EmailAddress');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                Contact cont = [Select Id, Email, Passport_No__c from Contact where AccountId=:con.Id];
                    if(cont != null) {
                        jsonGen.writeObjectField('EmailAddress',cont.Email);
                        jsonGen.writeObjectField('IsDefaultEmailAddress',true);
                    }
                    else{
                        jsonGen.writeObjectField('EmailAddress','[email protected]');
                        jsonGen.writeObjectField('IsDefaultEmailAddress',false);
                    }
                
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                    if(con.Preferred_Contact_Method__c != null) {
                      //jsonGen.writeObjectField('PrfrdCommMediumType',con.Preferred_Contact_Method__c);
                         jsonGen.writeObjectField('PrfrdCommMediumType','INT');
                    }
                    else {
                    jsonGen.writeObjectField('PrfrdCommMediumType','INT');
                    } 
               
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                jsonGen.writeFieldName('to_BuPaIdentification');
                jsonGen.writeStartArray();
                      if(cont != null) {
                jsonGen.writeStartObject();
                jsonGen.writeObjectField('BPIdentificationType','FS0002');
                jsonGen.writeObjectField('BPIdentificationNumber',cont.Passport_No__c);
                     if(con.Nationality__c != null) {
                      jsonGen.writeObjectField('Country',mapOfCountryNameToCountrycode.get(con.Nationality__c));
                    }
                    else {
                    jsonGen.writeObjectField('Country','AE');
                    } 
                jsonGen.writeEndObject();  
                }
                if(con.TRN__c != null) {
                jsonGen.writeStartObject();
                jsonGen.writeObjectField('BPIdentificationType','FS0003');
                jsonGen.writeObjectField('BPIdentificationNumber',con.TRN__c);
                     if(con.Nationality__c != null) {
                      jsonGen.writeObjectField('Country',mapOfCountryNameToCountrycode.get(con.Nationality__c));
                    }
                    else {
                    jsonGen.writeObjectField('Country','AE');
                    } 
               
                jsonGen.writeEndObject();
                }
                if(con.Trade_License_No__c != null) {
                jsonGen.writeStartObject();
                jsonGen.writeObjectField('BPIdentificationType','FS0004');
                jsonGen.writeObjectField('BPIdentificationNumber',con.Trade_License_No__c);
                     if(con.Nationality__c != null) {
                      jsonGen.writeObjectField('Country',mapOfCountryNameToCountrycode.get(con.Nationality__c));
                    }
                    else {
                    jsonGen.writeObjectField('Country','AE');
                    } 
                jsonGen.writeEndObject();  
                }
              
                
                jsonGen.writeEndArray();
            }
                
                else {
                  jsonGen.writeObjectField('BusinessPartnerCategory','1');
                jsonGen.writeObjectField('BusinessPartnerGrouping','Z051');

                jsonGen.writeFieldName('to_BusinessPartnerRole');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                jsonGen.writeObjectField('BusinessPartnerRole','ZTR601');
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                    if(con.FirstName != null) {
                 jsonGen.writeObjectField('FirstName',con.FirstName);
                    }
                    else {
                     jsonGen.writeObjectField('FirstName','BP Odata Service');   
                    }
                    if(con.LastName != null) {
                    jsonGen.writeObjectField('LastName',con.LastName);
                    }
                    else {
                     jsonGen.writeObjectField('LastName','SFDC');   
                    }
                    
                     if(con.Preferred_Language__pc != null) {
                    jsonGen.writeObjectField('CorrespondenceLanguage',mapOfLanguageNameToLanguagecode.get(con.Preferred_Language__pc));
                    jsonGen.writeObjectField('Language',mapOfLanguageNameToLanguagecode.get(con.Preferred_Language__pc));
                    }
                    else {
                     jsonGen.writeObjectField('CorrespondenceLanguage','EN');  
                     jsonGen.writeObjectField('Language','EN');
                    }
                    
                     if(con.Search_Term__c != null) {
                   jsonGen.writeObjectField('SearchTerm1',con.Search_Term__c);
                    }
                    else {
                     jsonGen.writeObjectField('SearchTerm1','Test');
                    }
                    
                    if(con.Salutation == 'Mr.'){
                jsonGen.writeObjectField('FormOfAddress','0002');
                    }
                    else if(con.Salutation == 'Ms.' || con.Salutation == 'Mrs.'){
                jsonGen.writeObjectField('FormOfAddress','0001');
                    }
                     else{
                jsonGen.writeObjectField('FormOfAddress','0001');
                    }

                    if(con.Nationality__pc != null) {
                    jsonGen.writeObjectField('NameCountry',mapOfCountryNameToCountrycode.get(con.Nationality__pc));
                    }
                    else {
                     jsonGen.writeObjectField('NameCountry','AE');
                    }
                   
                jsonGen.writeFieldName('to_BusinessPartnerAddress');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                 if(con.BillingStreet != null) {
                    jsonGen.writeObjectField('StreetName',con.BillingStreet);
                    }
                    else {
                     jsonGen.writeObjectField('StreetName','Park Street');
                    } 
                    
                    if(con.BillingAddress != null) {
                    jsonGen.writeObjectField('HouseNumber','hno');
                    }
                    else {
                    jsonGen.writeObjectField('HouseNumber','H.No.');
                    } 
                    
                    if(con.BillingPostalCode != null) {
                    jsonGen.writeObjectField('PostalCode',con.BillingPostalCode);
                    }
                    else {
                    jsonGen.writeObjectField('PostalCode','12456');
                    } 
                    
                    if(con.BillingCity != null) {
                   jsonGen.writeObjectField('CityName',con.BillingCity);
                    }
                    else {
                    jsonGen.writeObjectField('CityName','Abu Dhabi');
                    } 
                    
                     if(con.Nationality__pc != null) {
                    jsonGen.writeObjectField('Country',mapOfCountryNameToCountrycode.get(con.Nationality__pc));
                    }
                    else {
                    jsonGen.writeObjectField('Country','AE');
                    } 
                    
                     if(con.BillingPostalCode != null) {
                    jsonGen.writeObjectField('POBox',con.BillingPostalCode);
                    }
                    else {
                    jsonGen.writeObjectField('POBox','392934');
                    } 
                jsonGen.writeFieldName('to_MobilePhoneNumber');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                     if(con.PersonMobilePhone != null) {
                    jsonGen.writeObjectField('PhoneNumber',con.PersonMobilePhone);
                    jsonGen.writeObjectField('IsDefaultPhoneNumber',true);
                    }
                    else {
                    jsonGen.writeObjectField('PhoneNumber','12040939');
                    jsonGen.writeObjectField('IsDefaultPhoneNumber',false);
                    } 
               
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                jsonGen.writeFieldName('to_PhoneNumber');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                     if(con.PersonMobilePhone != null) {
                     jsonGen.writeObjectField('PhoneNumber',con.PersonMobilePhone);
                     jsonGen.writeObjectField('IsDefaultPhoneNumber',true);
                    }
                    else {
                    jsonGen.writeObjectField('PhoneNumber','12040939');
                    jsonGen.writeObjectField('IsDefaultPhoneNumber',false);
                    } 
               
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                jsonGen.writeFieldName('to_EmailAddress');
                jsonGen.writeStartArray();
                jsonGen.writeStartObject();
                     if(con.PersonEmail != null) {
                     jsonGen.writeObjectField('EmailAddress',con.PersonEmail);
                     jsonGen.writeObjectField('IsDefaultEmailAddress',true);
                    }
                    else {
                    jsonGen.writeObjectField('EmailAddress','[email protected]');
                    jsonGen.writeObjectField('IsDefaultEmailAddress',false);
                    } 
               
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                    if(con.Preferred_Contact_Method__pc != null) {
                      jsonGen.writeObjectField('PrfrdCommMediumType','INT');
                    }
                    else {
                    jsonGen.writeObjectField('PrfrdCommMediumType','INT');
                    } 
               
                jsonGen.writeEndObject();
                jsonGen.writeEndArray();
                jsonGen.writeFieldName('to_BuPaIdentification');
                jsonGen.writeStartArray();
                if(con.Emirates_ID_Number__pc != null) {
                    System.debug('PASSPORT NTTEE ' + con.Passport_No__c );
                jsonGen.writeStartObject();
                jsonGen.writeObjectField('BPIdentificationType','FS0001');
                jsonGen.writeObjectField('BPIdentificationNumber',con.Emirates_ID_Number__pc);
                     if(con.Nationality__pc != null) {
                      jsonGen.writeObjectField('Country',mapOfCountryNameToCountrycode.get(con.Nationality__pc));
                    }
                    else {
                    jsonGen.writeObjectField('Country','AE');
                    } 
               
                jsonGen.writeEndObject();
                }
                if(con.Passport_No__c != null) {
                    System.debug('PASSPORT NTT' );
                jsonGen.writeStartObject();
                jsonGen.writeObjectField('BPIdentificationType','FS0002');
                jsonGen.writeObjectField('BPIdentificationNumber',con.Passport_No__c);
                     if(con.Nationality__pc != null) {
                      jsonGen.writeObjectField('Country',mapOfCountryNameToCountrycode.get(con.Nationality__pc));
                    }
                    else {
                    jsonGen.writeObjectField('Country','AE');
                    } 
                jsonGen.writeEndObject();  
                }
                
                jsonGen.writeEndArray();
                }
                 jsonGen.writeEndObject();
                
                 jsonData = jsonGen.getAsString();
                 System.debug('Json Data - ' + jsonData);
                 req.setBody(jsonData);
                 system.debug('CC ID');
                 Http http = new Http();
                 HttpResponse response = http.send(req);
                 sYSTEM.debug('SENDING ' + response.getStatusCode());
                 sYSTEM.debug('RESUT22' + response.getBody());
                 String jsonString = response.getBody().replaceAll('\n','').replaceAll('\r','');    
                 sYSTEM.debug('RESUT333' + jsonString);
                 Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(jsonString);  
                    
                 if (response.getStatusCode() == 200) {
                    System.debug('test' + response.getBody());
                    String partnerid = (String)results.get('id');
                    con.Partner_Id__c = partnerid;
                    accntLst.add(con);
                 }
                 else {
                    con.SAP_Error_Response__c = jsonString;
                    accntLst.add(con);
                     
                }
            }
         
          update accntLst;
            
           
           
        }
   
     
     
     

  }
}

Here in my trigger code, I need to pass Account record data to future callout method Issues facing:-

  1. Since I doesn't have Account Id on before insert, But future methods only accept primitive data type
  2. if there is error response from endpoint, need to block the creation of Account record

How should I modify the code to acheive this reqrmnt?

1 Answer 1

2

As written, this is not possible. You cannot use @future, or any other async approach (batch, schedulable, queueable) to prevent a trigger from doing work. This extends beyond triggers though. Any code that is run, which causes other code to be run async, cannot be controlled by or wait for the async portion to complete.

The main points of running async code are:

  • It's separated from the main transaction
  • You get a new (and expanded) set of governor limits
  • The originating transaction doesn't wait for the async code to finish (or even to start)

You have several options here to move forward.

If you're only working with data being entered from the web UI

You can look into Continuations. That link is for LWC, but continuations are also available for legacy VisualForce pages too.

You would create your account "in memory", but not insert it.
Then, you send the data off to your external system.
Finally, in the callback, you would perform the DML in Salesforce (if your callout was successful)

If you are generating these records elsewhere in code

Then simply perform the callout before attempting to insert your Accounts in Salesforce. You'll still create the Account records in memory, just not perform DML until after your callout.

If you can't change the order of operations

The previous two approaches assume that you don't need to send the Salesforce Ids for your Accounts to this external systetm you're working with.

If you do need the Id, then your only option is to perform the DML, and then make your callout async. You cannot prevent the record from being created here, but if your callout returns an error you could delete the Account from Salesforce (or make some other change to the record that limits its visibility or ability to be edited).

It's a similar end result, and most users would probably not be able to tell the difference.

Other notes

  • Don't use the global modifier if you don't absolutely know that you'll need it. public is just fine (unless you're developing managed packages)
  • Don't use JSONGenerator unless you know that you need to. Creating a Map<String, Object>, List<Object>, or making an Apex class to store the information you need and then passing that to JSON.serialize() is generally a much better experience (less typing, less error-prone)
  • If you do need Ids for records that are being inserted, that information is only available after insert (and obviously in any update/delete context)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .