• Sahil Yadav
  • NEWBIE
  • 75 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 41
    Questions
  • 25
    Replies
Hello Community Developers ,
I am working on one rest api service class which  will accept  payload from external system and send it to our salesforce and will created data in Salesforce.

 I am getting this issue while running my test classes.
Apex Class :-


@RestResource (urlMapping = '/createContact/*')
global with sharing class communityUsersWebService {
 @HttpPost
    global static ResponseWrapper createContacts(){
        Boolean success = false;
        String message = '';
        Set<Id> accountIds = new Set<Id>();
        List<Contact> newContactRecords = new List<Contact>();
        RestRequest request = RestContext.request;
        RestResponse response = RestContext.response;
        if(request != null){
            System.debug('request is not equal to null');
            Blob body = request.requestBody;
            String requestBody = body.toString();
            if(requestBody != null){
                try{
                    Map<String, Object> deserializeRequestBody = (Map<String , Object>)JSON.deserializeUntyped(requestBody);
                    System.debug(' deserializeRequestBody Map :-' +deserializeRequestBody);
                    Map<String , Object> storedeserializeRequestBody = new Map< String , Object>();
                    for(String s : deserializeRequestBody.keySet()){
                        storedeserializeRequestBody.put(s , deserializeRequestBody.get(s));
                        System.debug(' storedeserializeRequestBody Map :-' +storedeserializeRequestBody);
                    }
                    if(!storedeserializeRequestBody.isEmpty()){
                        String DDI_Industry_c = String.valueOf(storedeserializeRequestBody.get('DDI_Industry__c'));
                        String RecordTypeId =  String.valueOf(storedeserializeRequestBody.get('RecordTypeId'));
                        String Firstname =  String.valueOf(storedeserializeRequestBody.get('Firstname'));
                        String LastName = String.valueOf(storedeserializeRequestBody.get('Lastname'));
                        String Email = String.valueOf(storedeserializeRequestBody.get('Email'));
                        String DDI_Contact_Role_c =  String.valueOf(storedeserializeRequestBody.get('DDI_Contact_Role__c'));
                        String DDI_Decision_role_c =  String.valueOf(storedeserializeRequestBody.get('DDI_Decision_role__c'));
                        String Contact_Type_c =  String.valueOf(storedeserializeRequestBody.get('Contact_Type__c'));
                        String Account_Name_c  = String.valueOf(storedeserializeRequestBody.get('Account_Name__c'));
                        
                        List<Contact> getContacts = [Select id , FirstName , LastName , Email , RecordTypeId from Contact 
                                                     Where RecordTypeId =: RecordTypeId
                                                     AND FirstName =: Firstname
                                                     AND LastName =: LastName];
                        if(getContacts != null && getContacts.size() > 0){
                            System.debug('You Cannot Create Contacts due to Duplicacy !!!');
                            success = true;
                            message  = 'Contact creation is not Proceesed Succesfully since Duplicates Contacts in Salesforce ';
         
                               
                            
                        }
                        else{
                            List<Account> getAccounts = [Select id ,  Name   from Account Where Name=: Account_Name_c Limit 1];
                            if(getAccounts != null && getAccounts.size() > 0){
                                for(Account account : getAccounts){
                                    accountIds.add(account.Id);
                                    
                                }
                                
                            }
                            if(accountIds != null && accountIds.size() == 1 ){
                                Id mapToAccountId ;
                                for(Id id : accountIds){
                                    mapToAccountId = id;
                                }
                                Contact newContact = new Contact();
                                newContact.DDI_Industry__c = DDI_Industry_c;
                                newContact.RecordTypeId = RecordTypeId;
                                newContact.FirstName = Firstname;
                                newContact.LastName = Lastname;
                                newContact.Email = Email;
                                newContact.DDI_Contact_Role__c = DDI_Contact_Role_c;
                                newContact.DDI_Decision_role__c = DDI_Decision_role_c;
                                newContact.Contact_Type__c = Contact_Type_c;
                                newContact.AccountId = mapToAccountId;
                                //newContact.Account_Name__c = Account_Name_c;
                                newContactRecords.add(newContact);
                                
                            }
                            if(newContactRecords != null && newContactRecords.size() > 0){
                                insert newContactRecords;
                                success = true;
                                message =  'Contact creation request is processed Succcessfully !!!!';
                               
                            }
                            
                            
                        }
                        
                        
                        
                        
                    }
                    
                    
                }
                Catch(Exception ex){
                    System.debug('The Exception is : '+ex.getMessage());
                    success = true;
                    message = ex.getMessage();
                    
                }
            }
        }
        
        ResponseWrapper responseWrapper = new ResponseWrapper();
        responseWrapper.message = message ;
        responseWrapper.success = success;
        return responseWrapper;
        
    }
    
    
    global class ResponseWrapper{
           global String message ; 
           global Boolean success;
    }


}
 
Test Class :-


@isTest
public with sharing class communityUsersWebServiceTest {
    
    @isTest
    public static void testContactCreation(){
        Account account = new Account();
        account.name = 'Test Account';
        Id RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('DDI').getRecordTypeId();
        account.RecordTypeId = RecordTypeId;
        insert account;
        Contact contact = new Contact();
        contact.FirstName = 'Raghav';
        contact.LastName = 'Thakur';
        contact.Email = 'raghav.thakue+33@gmail.com';
        Id contactRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('DDI').getRecordTypeId();
        contact.RecordTypeId = contactRecordTypeId;
        contact.AccountId = account.Id;
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        req.requestURI = '/services/apexrest/subscriptionUpdate/';
        String jsonMessage = '{"DDI_Industry": "Other", "RecordTypeId": "0123g000000kDbrAAE", "Firstname": "Raghav", "Lastname": "Thakur", "Email": "raghav.thakue+33@gmail.com","DDI_Contact_Role__c": "Point of Contact","DDI_Decision_role__c": "Other", "Contact_Type__c": "Partner", "Account_Name__c": "'+account.Name+'" }';
        if(jsonMessage != null){
            req.requestBody = Blob.valueOf(jsonMessage);
            req.httpMethod = 'POST';
            RestContext.request = req;
            RestContext.response = res;
           
            
        }
        
         communityUsersWebService.createContacts();
        
        
        
    }

}

In my test class the line which i made as bold showing an issue !!

Any Help really thankfull !!!!
 
Hello Folks, I am trying to write the test class for one the apex class where I am getting the code coverage very less.
 
Apex Class :- 
@RestResource(urlMapping='/subscriptionUpdate/*')
global with sharing class subscriptionUpdate {    
    @HttpPost
    global static void doPost() {
        Map<String, Object> requestBody= (Map<String, Object>)JSON.deserializeUntyped(RestContext.request.requestBody.toString()); 
        Map<String, Object> requestBody1 = new Map<String, Object>();
        for(String s: requestBody.keySet()){
            requestBody1.put(s.toLowerCase(),requestBody.get(s));
        }
        system.debug('requestBody' +requestBody);
        system.debug('requestBody1===' +requestBody1);
        String oppId = String.valueOf(requestBody1.get('opportunityid'));
        String buyerId = String.valueOf(requestBody1.get('buyerid'));
        String subStatus = String.valueOf(requestBody1.get('subscriptionstatus'));
        String subsId = String.valueOf(requestBody1.get('subscriptionid'));
        if(oppId != null && oppId != ''){
            Opportunity opp = [SELECT ID, Name, Buy_ID__c, Subscription_Status__c FROM Opportunity WHERE Id = :oppId LIMIT 1];
            opp.Subscription_Status__c = subStatus;
            update opp;
        }
        
        if(buyerId != null  && oppId == null){
            System.debug('buyerId  ' +buyerId);
            Account acc = [SELECT ID,Name,API_Buyer_Id__c FROM Account WHERE API_Buyer_Id__c =:buyerId LIMIT 1];
            System.debug('Acc' +acc);
            Id rtId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Buyer Development Opportunity').getRecordTypeId();
            Opportunity opp =new Opportunity();
            opp.name = acc.Name;
            opp.AccountId = acc.Id;
            opp.StageName = 'Closed Won';
            opp.Subscription_Status__c = subStatus;
            opp.CloseDate = System.today();
            opp.RecordTypeId = rtId;
            opp.Subscription_ID__c  = subsId;
            opp.LeadSource= '';
            insert opp;
            Product2 prd = new Product2();
            if(subsId == '1'){               
                prd = [SELECT ID,Name FROM Product2 WHERE Name = 'Vehicle Score' LIMIT 1];
                Opportunity opp1 = [Select id, name , Subscription_Name__c from Opportunity where id =: opp.Id ];
                
                opp1.Subscription_Name__c = prd.Name;
                opp1.Name = acc.Name+'-'+opp1.Subscription_Name__c+'-'+opp1.id;
                update opp1;
                
            }
            else if(subsId == '2'){
                prd = [SELECT ID,Name FROM Product2 WHERE Name = 'Custom Bid' LIMIT 1];
                Opportunity opp1 = [Select id, name , Subscription_Name__c from Opportunity where id =: opp.Id ];
                opp1.Subscription_Name__c = prd.Name;
                opp1.Name = acc.Name+'-'+opp1.Subscription_Name__c+'-'+opp1.id;
                update opp1;
               
            }
            
        }
    }
}
 
Test Class :-

@isTest
public class subscriptionUpdateTest {
    
    @isTest static void testPostMethod(){
        Test.startTest();
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.API_Buyer_Id__c = '123456';
        insert acc;
        Opportunity TestOpp = new Opportunity();
        date mydate = date.parse('12/27/2022');
        TestOpp.name = 'TestOpp1';
        TestOpp.StageName = '0. Qualifying';
        TestOpp.CloseDate = mydate;
        TestOpp.AccountId = acc.Id;
        TestOpp.Subscription_Status__c = 'Subscribed';
        insert TestOpp;
        Opportunity opp = [SELECT ID,Buy_ID__c,AccountId,Account.API_Buyer_Id__c FROM Opportunity WHERE id = :TestOpp.Id];
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        
        req.requestURI = '/services/apexrest/subscriptionUpdate/';
       String JSONMsg = '{"opportunityid" : "'+opp.Id+'", "buyerId" : "'+opp.Account.API_Buyer_Id__c+'","Subscription Status":"Subscribed", "SubscriptionId" : "1"}';
        //String JSONMsg = '{"opportunityid" : "null", "Subscription Status":"Subscribed", "SubscriptionId" : "1"}';
        req.requestBody = Blob.valueof(JSONMsg);
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response= res;
        subscriptionUpdate.doPost();
        
        Test.stopTest();
        
    }
}

Any Suggestion would be really appreciated !!! for leting me know where I am doing wrong due to which its show very less coverage.
 
Hello Folks , I will be working on writting the test classes but facing an issue exactly could able to figure those 
Rest API Class
:-

@RestResource(urlMapping='/subscriptionUpdate/*')
global with sharing class subscriptionUpdate {    
    @HttpPost
    global static void doPost() {
        Map<String, Object> requestBody= (Map<String, Object>)JSON.deserializeUntyped(RestContext.request.requestBody.toString()); 
        Map<String, Object> requestBody1 = new Map<String, Object>();
        for(String s: requestBody.keySet()){
            requestBody1.put(s.toLowerCase(),requestBody.get(s));
        }
        system.debug('requestBody' +requestBody);
        system.debug('requestBody1===' +requestBody1);
        String oppId = String.valueOf(requestBody1.get('opportunityid'));
        String buyerId = String.valueOf(requestBody1.get('buyerid'));
        String subStatus = String.valueOf(requestBody1.get('subscriptionstatus'));
        String subsId = String.valueOf(requestBody1.get('subscriptionid'));
        if(oppId != null && oppId != ''){
            Opportunity opp = [SELECT ID, Name, Buy_ID__c, Subscription_Status__c FROM Opportunity WHERE Id = :oppId LIMIT 1];
            opp.Subscription_Status__c = subStatus;
            update opp;
        }
        
        if(buyerId != null && buyerId != ''){
            Account acc = [SELECT ID,Name,API_Buyer_Id__c FROM Account WHERE API_Buyer_Id__c =:buyerId LIMIT 1];
            Id rtId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Buyer Development Opportunity').getRecordTypeId();
            Opportunity opp =new Opportunity();
            opp.name = acc.Name;
            opp.AccountId = acc.Id;
            opp.StageName = 'Closed Won';
            opp.Subscription_Status__c = subStatus;
            opp.CloseDate = System.today();
            opp.RecordTypeId = rtId;
            opp.Subscription_ID__c  = subsId; 
            insert opp;
            Product2 prd = new Product2();
            if(subsId == '1'){               
                prd = [SELECT ID,Name FROM Product2 WHERE Name = 'Vehicle Score' LIMIT 1];
                Opportunity opp1 = [Select id, name , Subscription_Name__c from Opportunity where id =: opp.Id ];
                opp1.Subscription_Name__c = prd.Name;
                update opp1;
                Integration_logs__c ilog = new Integration_logs__c();
                ilog.Request_Body__c = RestContext.request.requestBody.toString();
                ilog.Response_Body__c = 'Opportunity Subscription Name is been Updated !!';
                ilog.Status__c = 'Success';
                insert ilog;
            }
            else if(subsId == '2'){
                prd = [SELECT ID,Name FROM Product2 WHERE Name = 'Custom Bid' LIMIT 1];
                Opportunity opp1 = [Select id, name , Subscription_Name__c from Opportunity where id =: opp.Id ];
                opp1.Subscription_Name__c = prd.Name;
                update opp1;
                Integration_logs__c ilog = new Integration_logs__c();
                ilog.Request_Body__c = RestContext.request.requestBody.toString();
                ilog.Response_Body__c = 'Opportunity Subscription Name is been Updated !!';
                ilog.Status__c = 'Success';
                insert ilog;
            }
 }
    }
}
 
Test Class :-

@isTest
public class subscriptionUpdateTest {
    @isTest static void testPostMethod(){
        Test.startTest();
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.API_Buyer_Id__c = '123456';
        insert acc;
        Opportunity TestOpp = new Opportunity();
        date mydate = date.parse('12/27/2022');
        TestOpp.name = 'TestOpp1';
        TestOpp.StageName = '0. Qualifying';
        TestOpp.CloseDate = mydate;
        TestOpp.AccountId = acc.Id;
        insert TestOpp;
        Id pricebookId = Test.getStandardPricebookId();
        Product2 prod = new Product2(
            Name = 'Custom Bid',
            ProductCode = 'Custom Bid',
            isActive = true
        );
        insert prod;
        PricebookEntry pbEntry = new PricebookEntry(
            Pricebook2Id = pricebookId,
            Product2Id = prod.Id,
            UnitPrice = 1,
            IsActive = true
        );
        insert pbEntry;
        
        Opportunity opp = [SELECT ID,Buy_ID__c,AccountId,Account.API_Buyer_Id__c FROM Opportunity WHERE id = :TestOpp.Id];
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        
        req.requestURI = '/services/apexrest/subscriptionUpdate/';
        String JSONMsg = '{"buyerId" : "'+opp.Account.API_Buyer_Id__c+'","Subscription Status":"Subscribed","subscription Id":"2"}';
        req.requestBody = Blob.valueof(JSONMsg);
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response= res;
        subscriptionUpdate.doPost();
        Test.stopTest();
        
    }
}


Issue :- 

Methods defined as TestMethod do not support Web service callouts
 
Payload Coming from External System to Salesforce as a Post request :-
{ 

    "OpportunityID": null, 

    "buyerId":"3456", 

    "SubscriptionStatus":"ReSubscribed", 

    "SubscriptionID": "1" 

 

}

Any Help will highly be appreciated needs to complete on an urent basis ...
Thank You 
Hello Folks, I will be working on Integration Part and I would have come accross the scenario where external system will send some payload to salesforce and based on payload we need to update that specific record in salesforce.
Payload Send from External System


{

  "Model": {

    "$type": "BuyerPortal.Profile.Shared.SalesforceModel, BuyerPortal.Profile.Shared",

    "BuyerId": null,

    "EventName": "BuyerMarketExpansionUpdate",

    "When": "2022-09-27T20:39:41.6733477+00:00",

    "SegmentationInfo": null,

    "MarketExpansionInfo": {

      "AuthUserKey": "1a396649-0d4e-4206-b93e-168a59ca816a",

      "LegalFirstName": "RMMMMMM",

      "LegalLastName": "MoMMMroMt",

      "Email": "",

      "BuyerId": null,

      "PrimaryMarket": 3,

     "ExpansionMarket": 2,

      "UserAcceptanceHistory": {

        "AcceptAuctionRules": true,

        "AcceptAuctionRulesDateTime": "2022-09-27T20:38:58.7321995+00:00",

        "AcceptPrivacyPolicy": true,

        "AcceptPrivacyPolicyDateTime": "2022-09-27T20:38:58.7322046+00:00",

        "IPAddress": "::1",

        "DeviceSource": 0,

        "AcceptPromotionalOffers": false,

        "AcceptPromotionalOffersDateTime": null,

        "AcceptNonDealerDeclaration": false,

        "AcceptNonDealerDeclarationDateTime": null

      }

    },

    "AuctionAccessCompanyMismatch": null,

    "AuthUserKey": "1a396649-0d4e-4206-b93e-168a59ca816a",

    "RegistrationModel": null

  },

  "CorrelationId": null,

  "Roles": null,

  "SessionId": null,

  "From": null,

  "DomainName": null,

  "RetryOnFailure": false,

  "DeliverAfterEpoch": {

    "$type": "IAAI.Base.Epoch, IAAI.Base",

    "Seconds": 0

  },

  "Token": null,

  "MaxRetryCount": 0

}

Now authuser key is common on both the system and based on that that authuserkey we need to fetch that specific lead record .
When ASAP sends over the following enumerations for 'Primary Market' and/or Expansion Market then we should display the respective text: 
When we receive a '1' for 'Primary Market or Expansion Market we would expect to see 'US' in the User Interface 
When we receive a '2' for 'Primary Market or Expansion Market we would expect to see 'CA' in the User Interface 
When we receive a '3' for 'Primary Market or Expansion Market we would expect to see 'UK' in the User Interface

Rest Apex Code :-
@RestResource (urlMapping = '/createBuyerLead/')
global with sharing class LeadClass {
@HttpPatch
    global static String updatePrimaryAndExpansionMarket(){
        
        //String leadFirstName, leadLastName, leadAuthUserKey , leadPrimaryMarket , leadExpansionMarket;
        
        RestRequest request = RestContext.request;
        
        RestResponse response = RestContext.response;
        
        Blob blobrequestBody = request.requestBody;
        
        String requestBody = blobrequestBody.toString();
        
        Map<String, Object> requestBody1 = (Map<String,Object>)JSON.deserializeUntyped(requestBody);
        
        System.debug('requestBody1 : '+ requestBody1);
        
        Map<String, Object> requestBody2 = new Map<String , Object>();
        
        for(String s : requestBody1.keySet()){
            
            requestBody2.put(s.toLowerCase(), requestBody1.get(s));
            
            
            
        }
        System.debug('requestBody2'+requestBody2);
        
        String leadAuthUserKey = String.valueOf(requestBody2.get('AuthUserKey'));
        
        System.debug('leadAuthUserKey'+leadAuthUserKey);
        
        String leadFirstName = String.valueOf(requestBody2.get('LegalFirstName'));
        
        String leadLastName = String.valueOf(requestBody2.get('LegalLastName'));
        
        String leadPrimaryMarket = String.valueOf(requestBody2.get('PrimaryMarket'));
        
        String leadExpansionMarket = String.valueOf(requestBody2.get('ExpansionMarket'));
        
        Lead leadRecord = [Select id, name, Primary_Market__c, Expansion_Market__c, authuserkey__c from lead where authuserkey__c =:leadAuthUserKey LIMIT 1  ];
        
        System.debug('Lead Name - '+leadRecord.Name);
        
        if(leadPrimaryMarket == '1'){
            leadRecord.Primary_Market__c = 'US';
        }
        else if(leadPrimaryMarket == '2'){
            leadRecord.Primary_Market__c = 'CA';
        }
        else if(leadPrimaryMarket == '3'){
            leadRecord.Primary_Market__c = 'UK';
        }
        
        if(leadExpansionMarket == '1'){
            leadRecord.Expansion_Market__c = 'US';
        }
        else if(leadExpansionMarket == '2'){
            leadRecord.Expansion_Market__c = 'CA';
        }
        else if(leadExpansionMarket == '3'){
            leadRecord.Expansion_Market__c = 'UK';
        }
        
        update leadRecord;
        String leadId = leadRecord.id;
        return leadId;
        
        
    }
   
}

But its not updating an appropriate lead record  .
User-added image

Authuser key is showing as null where as in payload we are sending the values

Any Suggestion or Help would be highly Appreciated !!!!
Hello Folks, I will be writing one rest apex class based on my business requirement but wanted to know a better way of how can we make our code much better.
{

  "Model": {

    "$type": "BuyerPortal.Profile.Shared.SalesforceModel, BuyerPortal.Profile.Shared",

    "BuyerId": null,

    "EventName": "BuyerMarketExpansionUpdate",

    "When": "2022-09-27T20:39:41.6733477+00:00",

    "SegmentationInfo": null,

    "MarketExpansionInfo": {

      "AuthUserKey": "1a396649-0d4e-4206-b93e-168a59ca816a",

      "LegalFirstName": "RMMMMMM",

      "LegalLastName": "MoMMMroMt",

      "Email": "",

      "BuyerId": null,

      "PrimaryMarket": 3,

     "ExpansionMarket": 2,

      "UserAcceptanceHistory": {

        "AcceptAuctionRules": true,

        "AcceptAuctionRulesDateTime": "2022-09-27T20:38:58.7321995+00:00",

        "AcceptPrivacyPolicy": true,

        "AcceptPrivacyPolicyDateTime": "2022-09-27T20:38:58.7322046+00:00",

        "IPAddress": "::1",

        "DeviceSource": 0,

        "AcceptPromotionalOffers": false,

        "AcceptPromotionalOffersDateTime": null,

        "AcceptNonDealerDeclaration": false,

        "AcceptNonDealerDeclarationDateTime": null

      }

    },

    "AuctionAccessCompanyMismatch": null,

    "AuthUserKey": "1a396649-0d4e-4206-b93e-168a59ca816a",

    "RegistrationModel": null

  },

  "CorrelationId": null,

  "Roles": null,

  "SessionId": null,

  "From": null,

  "DomainName": null,

  "RetryOnFailure": false,

  "DeliverAfterEpoch": {

    "$type": "IAAI.Base.Epoch, IAAI.Base",

    "Seconds": 0

  },

  "Token": null,

  "MaxRetryCount": 0

}

This above is the payload which salesforce willl consume and perform an updation on that particular lead record.
Authuserkey is the common token in between of salesforce and external system .
so i need to fetch those lead record   which matches an authuser key and also two attribute is been passing in payload and based on that i need to update the salesforce records.
I have wrote an rest apex class but wanted to make sure i am on the correct way or not.

When we receive a '1' for 'Primary Market or Expansion Market we would expect to see 'US' in the User Interface 
When we receive a '2' for 'Primary Market or Expansion Market we would expect to see 'CA' in the User Interface 
When we receive a '3' for 'Primary Market or Expansion Market we would expect to see 'UK' in the User Interface

 
@RestResource (urlMapping = '/createBuyerLead/')
global with sharing class LeadClass {
      @httpPatch
    global static void updatePrimaryAndExpansionMarket(){
          String fname ,lname, authuserkey, company, primarymarket, expansionmarket;
        RestRequest request = RestContext.request;
        RestResponse response = restContext.response;
        String requestbody = request.requestBody.tostring();
        JSONParser parser = JSON.createParser(requestbody);
         //List<Lead> leadList = [Select id, name ,AuthUserKey__c, Primary_Market__c ,Expansion_Market__c  from lead where AuthUserKey__c =:authuserkey Limit 1 ];
        //System.debug('@@'+leadList);
        //System.debug('@@'+parser.readValueAs(JSONParser));
        while(parser.nextToken() != null){
            if(parser.getCurrentToken() != JSONToken.END_OBJECT){
                String fieldname = parser.getCurrentName();
                System.debug('@fieldname@'+fieldname);
                
                String fieldvalue = parser.getText();
                System.debug('@fieldvalue@'+fieldvalue);
                if(fieldname == 'AuthUserKey'){
                    authuserkey = fieldvalue; 
                }
                List<Lead> leadList = [Select id, name ,AuthUserKey__c, Primary_Market__c ,Expansion_Market__c  from lead where AuthUserKey__c =:authuserkey Limit 1 ];
                if(fieldname == 'PrimaryMarket'){
                     primarymarket = fieldvalue;
                    if(primarymarket == '1'){
                   leadList[0].Primary_Market__c = 'US';
                    }
                    else if(primarymarket == '2'){
                   leadList[0].Primary_Market__c = 'CA';
                    }
                    else if(primarymarket == '3'){
                   leadList[0].Primary_Market__c = 'UK';
                    }
                    
                }
                
                 else if(fieldname == 'ExpansionMarket'){
                     expansionmarket = fieldvalue;
                    if(expansionmarket == '1'){
                   leadList[0].Expansion_Market__c = 'US';
                    }
                    else if(expansionmarket == '2'){
                   leadList[0].Expansion_Market__c = 'CA';
                    }
                    else if(expansionmarket == '3'){
                   leadList[0].Expansion_Market__c = 'UK';
                    }
                }
                
               
                try{
                   update leadList[0];
                    System.debug('Leadlist'+leadList[0]);
                 
                }
                catch(Exception ex){
                    
                }
                
            }
        }
        
        
    }
       

}

Any Suggestion or improvement highly appreciated !!!
Hello folks,
while inserting data from data loader into the object lead .
closedate is a datetime field whose date is getting changed 
Any Suggestion how can we correct this close date so that its get mapped correctly an expected date as per csv??
 
Hello Folks, 
    I will be facing some test coverage related issue which I tried in multiple ways but still stuck on this Hopefully our community will help me to make understand where I did something wrong 
 
Apex Class :- GetTeamsMeetingURL 

global class GetTeamsMeetingURL {
    @InvocableMethod(label='Get MS Teams Meeting URL' description='Returns a meeting URL For MS Teams')
    //global static List<String> makeApiCallout(List<List<String>> inputTeamsParms) 
     global static List<String> makeApiCallout()
    {
        // Setup the HTTP Initial Request
        HttpRequest req = new HttpRequest();
        Http http = new Http();
               
        //Setup the Headers, format the body, and call the MS Graph API
        req.setEndpoint('callout:MS_Azure_OnlineMeeting');
        req.setMethod('POST');
        req.setHeader('Content-Type','application/json');
        req.setHeader('Accept','*/*');
        req.setHeader('Accept-Encoding','gzip, deflate, br');
        
        /* Setup the Parameters for Meetings, subject, etc. */
        // Note: The initial demo only utilized title, further development can use other inputs. 
       /* system.debug('Array size  =' + inputTeamsParms.get(0).size());  
        String inTitle = '"' + inputTeamsParms.get(0).get(0) + '"';
        system.debug('inTitle =' + inTitle);    
        String inAgenda = '"' + inputTeamsParms.get(0).get(0) + '"';
        system.debug('inAgenda =' + inAgenda);               
        String inPwd = '"' + inputTeamsParms.get(0).get(1) + '"';
        system.debug('inPwd =' + inPwd);                
        String inStart = '"' + inputTeamsParms.get(0).get(2) + '"';
        system.debug('inStart =' + inStart);                
        String inEnd = '"' + inputTeamsParms.get(0).get(3) + '"';
        system.debug('inEnd =' + inEnd);*/
        
        // Setup the Body
        String reqHTTPString  =  '';
        //reqHTTPString = '{"subject":' + inTitle +'}';
        //reqHTTPString = '{"Subject":' + "DDI Training Registration"}'
         reqHTTPString =  '{"Subject":"DDI Training Registration"}';
        req.setBody(reqHTTPString);
        System.debug('The Request Body' +reqHTTPString);
        
        /* Send request to MS Teams Server */
        HTTPResponse res = http.send(req);
        System.debug('The Response' +res);
        System.debug('The Response Body Is : '+res.getBody());
        /* Parse Response from MS Team Server */
        JSONParser parser = JSON.createParser(res.getBody());
        String webLink;
        webLink = 'MSTeamsNotSetup';
        System.debug(weblink);
        System.debug('The Parser :'+parser);
            
        while (parser.nextToken() != null) {
        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'joinWebUrl')) {
            parser.nextToken();
            System.debug('@@ParserNextToken' +parser.nextToken());
            System.debug('@@' +parser.getText());
            webLink = parser.getText();
            System.debug('Weblink' +webLink);
            System.debug('joinWebUrl= ' + webLink);
           
            }
        }
    
    // Apex Actions Return. The method signature for invocable method requires a List of Strings to be returned. 
    // 
     System.debug('Weblink: '+webLink);
    return new List<String>{webLink};
    }
}

HttpMockClass :- HttpMockFactory

@isTest
global  class HttpMockFactory implements HttpCalloutMock{
    protected Integer Code;
    protected String Status;
    protected String Body;
    public HttpMockFactory(Integer Code, String Status,  String Body){
        this.Code = Code;
        this.Status = Status;
        this.Body = Body;
    }
    
    public HttpResponse respond(HttpRequest req){
        HttpResponse response = new HttpResponse();
        response.setStatusCode(this.Code);
        response.setStatus(this.Status);
        response.setBody(this.Body);
        return response;
        
    }
    

}


 
Test Class :- TestAzure

@istest
 public class TestAzure {
    
    
    /* Test Method for Unit Testing Connection */
     @istest
    public static String getMeetingUrl()
    {
        HttpMockFactory mock = new HttpMockFactory(200 ,'OK','Result Found');
        Test.setMock(HttpCalloutMock.class, mock);
          GetTeamsMeetingURL.makeApiCallout();
       // System.assertEquals(result, 'Result Found');
        
        HttpRequest req = new HttpRequest();
        Http http = new Http();
               
        //Setup the Endpoint and append the name of the file
        req.setEndpoint('callout:MS_Azure_OnlineMeeting');
        //req.setEndpoint('https://graph.microsoft.com/v1.0/me/onlineMeetings');
        req.setMethod('POST');
        req.setHeader('Content-Type','application/json');
        req.setHeader('Accept','*/*');
        req.setHeader('Accept-Encoding','gzip, deflate, br');
        
        //Setup the JSON Body - in the test just set a subject, can add more through Postman or other tests
        req.setBody('{"subject":"Delegated User Test Meeting"}');        
        //req.setBody('{}');
        
        System.debug('Body: ' + req.getBody());
        System.debug('Endpoint Value: '+ req.getEndpoint());
        System.debug('Request: ' + req);
        
        HTTPResponse res = http.send(req);
        System.debug('Response Body: '+res.getBody());

        /* Parse Response */
        JSONParser parser = JSON.createParser(res.getBody());
        String webLink;
        webLink = 'MSTeamsNotSetup';
        while (parser.nextToken() != null) {
        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
        (parser.getText() == 'joinWebUrl')) {
            parser.nextToken();
            webLink = parser.getText();
            System.debug('joinWebUrl= ' + webLink);
            }
        }
    
    return webLink;
        
        
    }
}
Code Coverage which I will be getting is 80% but the test class is still failing .
User-added image
This is the error which i am getting exactly but not able to relate what exactly its means to say

User-added image

on the second image this piece of line is not been getting covered 
any help would be highl appreciated
Whenever a case owner is changed to other user of profile(new user profile name : 'AST ENTERPRISE' )in case record.
Then i want to get a confirmation dailog before saving with ok and cancel button.
On Click of ok button i want to change the case owner and return to the same page and
On Click of cancel do not change case owner and return to the same page. How can we do this? Is there a way to achieve this? Please guide me out in this.
Thank You.
Hello Folks, I had one apex class which is getting triggered from flow through actions and that flow create a case records since create record element in flow holds the id of the created record and that id I am pushing it into one collection variable while will pass List<List<Id>> from Flow to an apex class through invocable annotation.
 
public class createChildCase {
    
    public static String caseType = 'ELT';
    
    
    @InvocableMethod
    public static void createChildCase( List<List<Id>> newCaseIds){
        
        
        
        
        if(newCaseIds != Null & newCaseIds.size() > 0){
            
            for( integer i = 0; i < newCaseIds.size() ; i++){
                Case  getCase = [SELECT Id, ParentId, Type,Reason_for_Case__c, DDI_City__c, DDI_State__c , DDI_Multi_State__c,DDI_Requester_Company__c, SuppliedEmail, RecordTypeId, Subject  FROM Case WHere Id =: newCaseIds[i] AND ParentId = Null];
                
                 getCases( getCase);
                
                
            }
            
            
            
            
        }
        
        
    }
    
    public static void getCases(Case getCase){
        List<Case> providerSwitchCasesList = new List <Case>();
        
        List<Case> contractCasesList = new List<Case>();
        

                    

                        
                        if (getCase.RecordTypeId == System.Label.DDI_Provider_Switch_State_Record_Type_Id && getCase.Type == caseType ){
                            
                            providerSwitchCasesList.add( getCase);
                            
                            providerSwitch( providerSwitchCasesList);
                            
                            
                            
                        }
                        
                        else if (getCase.RecordTypeId == System.Label.DDI_Contract_Case_Record_Type_Id && getCase.Type == caseType){
                            
                            contractCasesList.add(getCase);
                        }
                    
                  
                    
                    
                
        
    }
    
    
    public static void providerSwitch(List<Case> providerSwitchCasesList){
          
                    if(providerSwitchCasesList != Null && providerSwitchCasesList.size() > 0){
                        
                        for (Case providerSwitchCase : providerSwitchCasesList){
                            checkProviderSwitchCaseStateBlankOrNot(providerSwitchCase);
                           
                        }
                        
                    }
        
        
    }
    
    public static void checkProviderSwitchCaseStateBlankOrNot( Case providerSwitchCase){
        
         if (providerSwitchCase.DDI_Multi_State__c != Null){
                                
                                List<String> selectedStates = providerSwitchCase.DDI_Multi_State__c.split(';'); 
                                
                                System.debug('Selected States for ProviderSwitchCase is :' +selectedStates);
                                
                                if(selectedStates != Null && selectedStates.size()>0){
                                    
                                  childProviderSwitch(selectedStates, providerSwitchCase);
                                    
                                }
                            }
        
    }
    
    public static void childProviderSwitch( List<String > selectedStates, Case providerSwitchCase){
          List<Case> childProviderSwitchCaseList = new List<Case> ();
                                    
                                    for (Integer s = 0; s < selectedStates.size(); s++){
                                        
                                        String singleState = selectedStates[s];
                                        
                                        Case childProviderSwitchCase = new Case();
                                        
                                        childProviderSwitchCase.ParentId = providerSwitchCase.Id;
                                        
                                        childProviderSwitchCase.RecordTypeId =  System.Label.DDI_Provider_Switch_State_Record_Type_Id;
                                        
                                        childProviderSwitchCase.DDI_State__c = singleState;
                                        
                                        childProviderSwitchCase.Subject = 'Child Case of Provider Switch Case';
                                        
                                        childProviderSwitchCaseList.add(childProviderSwitchCase);
                                        
                                    }
                                    insert childProviderSwitchCaseList;
                                    
        
    }
    
    
}
 
Test Class Code:-

@IsTest
public class createChildCaseTest{
	@isTest
    public Static void unitTest(){
          Case cases = new Case();
        cases.SuppliedEmail= 'yadavsahil463@gmail.com';
        cases.DDI_Multi_State__c  = 'Arizona;Colorado; California';
        cases.Subject = 'Case is been getting created';
      cases.DDI_City__c = 'Mumbai';
        cases.DDI_State__c = 'Maharashtra';
        cases.Type= ' ELT ' ;
       cases.Reason_for_Case__c = ' ELT Provider Switch ';
        cases.recordTypeId = System.label.DDI_Provider_Switch_State_Record_Type_Id	;
        insert cases;
       
        List<Case> caseList = [Select Id, subject,CaseEmail__c from Case where id =: cases.Id ];
        createChildCase.createChildCase(new list<list<Id>>{Cases.Id});
        System.assertEquals('yadavsahil463@gmail.com',Cases.SuppliedEmail );
    }
    
    
    
    
}

I am facing issue on how we can pass the list of case<Ids > in test class 
Any Suggestion would be really appreciable!!!!
Hello Folks , 
    I will be working on one scenario where a case is been get created from one screen flow where there is one multiselect picklist fields  with the label state where end user can select multiple state value during the case creation . Now I need to create a child cases of the cases which is been created bu the screen flow.
So ideally one parent case is get created through screen flow where suppose state an end user selected is  AK, AL, CZ then the three child cases must be get created because  3 states is been selected  AK, AL, CZ

So 
Parent Case get created from screen flow and passing the case id from flow to apex class to create a no of child cases depend upon the number of state field values.
Code for creating a child Case 



public class createChildCase {
      @InvocableMethod
    public static void createChild(List<Id> caseIds){
        System.debug('createChildCaseInvoked');
        Case parentCase = [Select id, subject , description, DDI_States_Of_Interests__c from Case where id = : caseIds[0]];
         List<String> States = parentCase.DDI_States_Of_Interests__c.split(';');
        System.debug('States Size' +States.size() );
         List<Case> childCase = new List<Case>();
        for(integer i = 0; i< States.size(); i++ ){
            String state = States[i];
            System.debug('State :' +state);
             Case caseAL = new Case();
                         System.debug('@@');
                         caseAL.Subject = 'Sub Case for Different States';
                         System.debug('@@');
                         caseAL.ParentId = parentCase.Id;
                         System.debug('@@');
                         caseAL.RecordTypeId = '01223000000NZDEAA4';
                         System.debug('@@');
                         caseAl.DDI_States_Of_Interests__c = state;
                         //insert caseAK;
                         childCase.add(caseAL);
            
        }
         
       
                          
                          System.debug('@@' +childCase.size());
                         //System.debug('@@' +caseAL.Id);
          insert childCase;
                         //return childCase;
                         
        
    }

}
 
Test Class


@isTest
public class createChildCaseTest {
    
    @isTest
    public static void createChild(){
        Case cases = new Case();
        cases.CaseEmail__c= 'yadavsahil46623@gmail.com';
        cases.MultiSelect_State__c = 'AZ, AR, CA';
        cases.Subject = 'Case is been getting created';
        insert cases;
       
        List<Case> caseList = [Select Id, subject,CaseEmail__c, MultiSelect_State__c from Case where id =: cases.Id ];
        System.assertEquals('yadavsahil46623@gmail.com',cases.CaseEmail__c );
        
    }

}

Now how may i proceed futher not geting an idea please let me know if any comments 
How should i wrote a test class for this scenarios?
Hello Developers,
           I had came accross one business requirement where i needed to send the opportunity line item record from source org to an external org using Rest API.
WHile sending a request a method i kept is POST and at that moment only i will be sending the data of opportunity Line Item in Json format and at the target org the request which is been sent is also coming but after deserializing the request in target org the data is becooming null and while insertion of record in target org throuwing error.
Sending the Request to Target Org======


Global class IntegrationClass {
    /*
    @HttpGet
    global static List<opportunity> doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String BuyerId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone,Bi_Id__c, Website FROM Account WHERE Bi_Id__c = :BuyerId];
        
            
                String acc = result.Id;
                List<Opportunity> opp = [Select id, name, accountId from Opportunity where accountId =:acc ];
                 return opp;
            
           
        
        
    }*/
    public static void sendData(){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://capge56-dev-ed.my.salesforce.com/services/apexrest/v1/opportunityLineItem/*');
        request.setMethod('POST');
        OpportunityLineItem opp = [Select id, name,ListPrice,UnitPrice, Opportunity.Id,Opportunity.CloseDate, Opportunity.Account.BI_ID__c from OpportunityLineItem  Limit 1];
        //OpportunityLineItem opp = [Select id, name,ListPrice,UnitPrice from OpportunityLineItem  Limit 1];
         String jsonString  =  JSON.serialize(opp);
        System.debug(jsonString);
        String name = opp.name;
        System.debug('!!!' +name);
        Decimal listPrice = opp.ListPrice;
        System.debug('!!!' +listPrice);
        Decimal unitPrice = opp.UnitPrice;
        System.debug('!!!' +unitPrice);
        Date closeDate = opp.Opportunity.CloseDate;
        System.debug('!!!' +closeDate);
        
        request.setBody(jsonString);
       // request.setBodyAsBlob(OpportunityLineItem);
        //request.setBody('{"Name":"any--JUL 2022 Mobile", "ListPrice" : "123.00", "UnitPrice" : "123.00" , "CloseDate" : "2022-07-01 00:00:00"}');
        request.setHeader('Content-Type', 'Application/Json; charset = UTF-8');
        System.debug('!!!'+request);
        HttpResponse response = http.send(request);
        System.debug('!!!'+response);
    }
        

}
 
Exposing an Apex class as Rest Web Service Class


@RestResource(urlMapping = '/v1/opportunityLineItem/*')
Global class createOpportunityLineItem {
    
    @HttpPost
    Global static opportunityLineItemWrapper insertOpportunityLineItem( /*opportunityLineItemWrapper oLIW*/){
        
        RestRequest req = RestContext.request;
        
        RestResponse response = RestContext.response;
        System.debug('@@@@' +req.requestBody);
        
       String  result = req.requestBody.toString();
       //String result = JSON.Stringify(req.requestBody);
        System.debug('@@@'+result);
        
        opportunityLineItemWrapper oLIW = (opportunityLineItemWrapper)JSON.deserialize(result, opportunityLineItemWrapper.class );
        System.debug('@@@'+oLIW);
         
        /*
        for(OpportunityLineItem o : oLIW ){
            o.Id = null;
            insert o;
        }*/
        
        OpportunityLineItem oLIRecord =  new OpportunityLineItem();
        // oLIRecord = oLIW.opportunityLineItemRecord;
       // oLIRecord.Name = oLIW.Name;
        //oLIRecord.ListPrice = oLIW.ListPrice;
        oLIRecord.UnitPrice = oLIW.UnitPrice;
        oLIRecord.OpportunityId = oLIW.OpportunityId;
        oLIRecord.Quantity = oLIW.Quantity;
       // insert oLIRecord;
        //System.debug('@@@'+oLIRecord);
        //insert oLIRecord;
              
        
        
        //Opportunity oppRecord = oLIW.opportunityRecord;
        //insert oppRecord;
        
        //Product2 prodRecord = oLIW.productRecord;
        //insert prodRecord;
        
                
        //OpportunityLineItem oLIRecord = oLIW.opportunityLineItemRecord;
        //oLIRecord.Product2Id = prodRecord.Id;
        //oLIRecord.OpportunityId = oppRecord.Id;
        //Insert oLIRecord;
        
        return oLIW;
        
       
        
    }
    
    
    
    

}
 
Wrapper class for Opportunity Line Item



Global class opportunityLineItemWrapper{
    // Global Opportunity opportunityRecord {get; set;}
    //Global Product2 productRecord {get; set;}
    //Global OpportunityLineItem opportunityLineItemRecord {get; set;}
    // Global class opportunityLineItem{
    public string name;
    public integer ListPrice;
    public integer UnitPrice;
    public string OpportunityId;
    public integer Quantity;
    
    // }
    // 
    
    public static opportunityLineItemWrapper parse(String json) {
        return (opportunityLineItemWrapper) System.JSON.deserialize(json, opportunityLineItemWrapper.class);
    }
    public class opportunityLineItemWrappers
    {
    public List<opportunityLineItemWrapper> opportunityLineItemWrapper { get; set; }
    }
    
    
}
 
Sending Request Through PostMan
/*
{
  "OpportunityLineItem": {
    
    "UnitPrice": "123",
    "OpportunityId" : "0065j00000TSPdFAAX",
    "Quantity" : "4",
    "Product2Id" : "01t5j0000049jQsAAI"
  }
}
*/
Hello Folks, 
               I am still exploring on Integration part in salesforce but for now i had come accroseed a requirement that from salesforce i needed to send the opportunitylineitem record from salesforce to external system So here is my code 
Global class IntegrationClass {
    /*
    @HttpGet
    global static List<opportunity> doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String BuyerId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone,Bi_Id__c, Website FROM Account WHERE Bi_Id__c = :BuyerId];
        
            
                String acc = result.Id;
                List<Opportunity> opp = [Select id, name, accountId from Opportunity where accountId =:acc ];
                 return opp;
            
           
        
        
    }*/
    public static void sendData(){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://hookb.in/6JqjXyjp2RsoO0ro3nP7');
        request.setMethod('POST');
        OpportunityLineItem opp = [Select id, name,ListPrice,UnitPrice, Opportunity.Id,Opportunity.CloseDate, Opportunity.Account.BI_ID__c from OpportunityLineItem  Limit 1];
        System.debug(JSON.serialize(opp));
        String name = opp.name;
        System.debug('!!!' +name);
        Decimal listPrice = opp.ListPrice;
        System.debug('!!!' +listPrice);
        Decimal unitPrice = opp.UnitPrice;
        System.debug('!!!' +unitPrice);
        Date closeDate = opp.Opportunity.CloseDate;
        System.debug('!!!' +closeDate);
        
        request.setBody('{OpportunityLineItem opp}');
        request.setBody('{"Name":"any--JUL 2022 Mobile", "ListPrice" : "123.00", "UnitPrice" : "123.00" , "CloseDate" : "2022-07-01 00:00:00"}');
        request.setHeader('Content-Type', 'Application/Json; charset = UTF-8');
        System.debug('!!!'+request);
        HttpResponse response = http.send(request);
        System.debug('!!!'+response);
    }
        

}

 So I will be getting opportunity line item record which is been needed
to sent and serializing it so the way I sent that seriallized record is the correct way to pass under request body or there is some other way around. 
Please let me know or any suggestion
Hello Developers, 
         I needed to pass an opportunitylineitem from salesforce to external application through Rest Api where in terms of http request the daya willl be passed from salesforce to other end .
But facing System.limit Exception while send the records and suggestion or improvisation needed in the code let me know.
Global class IntegrationClass {
    /*
    @HttpGet
    global static List<opportunity> doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String BuyerId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone,Bi_Id__c, Website FROM Account WHERE Bi_Id__c = :BuyerId];
        
            
                String acc = result.Id;
                List<Opportunity> opp = [Select id, name, accountId from Opportunity where accountId =:acc ];
                 return opp;
            
           
        
        
    }*/
    public static void sendData(){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://www.google.com');
        request.setMethod('POST');
        List<OpportunityLineItem> opp = [Select id, name,ListPrice,UnitPrice, Opportunity.Id,Opportunity.CloseDate, Opportunity.Account.BI_ID__c from OpportunityLineItem where OpportunityId = '' AND Opportunity.Account.BI_ID__c = 'buy-7765'];
        String name = opp[0].name;
        Decimal listPrice = opp[0].ListPrice;
        Decimal unitPrice = opp[0].UnitPrice;
        Date closeDate = opp[0].Opportunity.CloseDate;
        
        
        request.setBody('{"Name":"name", "ListPrice" : "listPrice", "UnitPrice" : "unitPrice" , "CloseDate" : "closeDate"}');
        request.setHeader('Content-Type', 'Application/Json; charset = UTF-8');
        System.debug('!!!'+request);
        HttpResponse response = http.send(request);
        System.debug('!!!'+response);
    }
        

}



====================================================================


Calling Integration Class Method:-

IntegrationClass.sendData();


User-added image


For a Time being End Point Url i keep dummy and created a remote site setting as well 
Hello Developers,
      I have one global action with name "High Touch Activity" and i made it available in publisher layout as well but i needed this action under lightning record page under activities standard component 

User-added imageIn publisher layout i placed a global actions under lightning experience.

User-added image

but in lightning record page under activities component only three global action are only available but along with I also needed high touch activity under activities 
Any suggestion why it is not coming

 
Hello Developers and Community Leaders, 
                                  I have got a scenario but not getting any path how may i could proceed on this and suggestion or thought would be apprechiable.
trigger ddi_Account_Trigger on Account (before insert) {
    switch on Trigger.operationType {
        when  Before_Insert{
             //List<Account> accountList =[SELECT Id, Name, MultiSelect_State__c,Account_Email__c, createddate FROM Account Order By createddate Desc Limit 1];
            ddiAccountTriggerHandler.getDDIAccount( trigger.new );
        }
    }
}



===========================================================================


public class ddiAccountTriggerHandler {
    
    public static void getDDIAccount(List<Account> accountList){
        //List<Account> accountList =[SELECT Id, Name, MultiSelect_State__c,Account_Email__c, createddate FROM Account Order By createddate Desc Limit 1];
        if (accountList != Null && accountList.size()>0){
            System.debug('@@@' +accountList);
            for(Account ac : accountList){
                System.debug('@@@'+ac.MultiSelect_State__c);
                List<String> States = ac.MultiSelect_State__c.split(';');
                System.debug('@@@' +States);
                System.debug('@@@'+States.size());
                for(integer i = 0; i < states.size(); i++){
                    String state = states[i];
                    String email = ac.Account_Email__c;
                    //Url u = https://iaaicsr--parvathy.my.salesforce.com/sfc/p/2i0000000rP7/a/2i0000009JVE/vIRIVQqXM1Ib31jKcU6kFD1qWryC2jPP7yNTfYwErYs;
                    
                    switch on state{
                        when 'Maharashtra'{
                           // Blob b = https://iaaicsr--sahil.my.salesforce.com/one/one.app#/alohaRedirect/08123000000BN09?isdtp=p1;
                           
                            System.debug('@@@Hurray Maharashtra' );
                            ddiAccountEmailSend.sendEmail(state, email);
                            
                        }
                        when 'Gujarat'{
                            System.debug('@@@Hurray Gujarat');
                            ddiAccountEmailSend.sendEmail(state, email);
                            
                        }
                        when 'Tamil Nadu'{
                            System.debug('@@@Hurray Tamil Nadu');
                            ddiAccountEmailSend.sendEmail(state, email);
                            
                        }
                        when 'Himachal'{
                            System.debug('@@@Hurray Himachal');
                            ddiAccountEmailSend.sendEmail(state, email);
                            
                        }
                        
                    }
                    
                }
                
                
            }
            
        }
        
    }
}


=================================================================


public class ddiAccountEmailSend {
    public static void sendEmail(String state, String email, String u){
        // creating an instance of SingleEmailMessage
        Messaging.SingleEmailMessage objEmail = new Messaging.SingleEmailMessage();
        
        // Setting the body for the email
        objEmail.setPlainTextBody('This is a Plain Text');
        
        // Setting the Subject for the email
        objEmail.setSubject('Interested States Related Pdf');
        //
        // Setting up the Address to whom we needed to send an Email
        objEmail.setToAddresses(new String[] {email});
        
        Messaging.EmailFileAttachment[] attachments  = new Messaging.EmailFileAttachment[1];
        
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        
        //Getting an Attachments from the Static Resource
        List<StaticResource> objPDF = [Select body, name from StaticResource where Name =: state];
        
        // setting the body of an attachment
        attachment.setBody(objPDF[0].body); 
        
        // setting up the file name of an attachment
        attachment.setFileName(objPDF[0].name +'.pdf');
        
        //Assinging the single attachment to a list  
        attachments[0] = attachment;
        
        objEmail.setFileAttachments( attachments);
        
        
        // Finally Send the Email
        
        List<Messaging.Sendemailresult> objER = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {objEmail});
        
        if (!objER[0].isSuccess()){
            // Error handling;
        }
        
        
        
        
    }
    
    
}

So this code basically sending the sending the email in which some respective pdf is been get attached depending on the state multiselect picklist value selected while creating an account .. 
Any suggestion on how could we place the url for thr document and that url only must be sent to that account email
 
Hello,
I had a scenario where When user creates a Lead we need to first check that Is this an Existing Lead or not.Based on the data on New Lead record page.
If that data matches with the existing record then just update the record based on the field values that are provided and DO NOT CREATE THE NEW LEAD.
If that data does not matches with the existing records then just CREATE NEW LEAD
 
trigger LeadTrigg on Lead (before insert){
    switch on Trigger.operationType {
        when  Before_Insert{
            Set<String> leadFname = new Set<String>();
            for(Lead l : trigger.new){
                leadFname.add(l.firstname);
            }
            if(leadFname.size()>0 && leadFname != null){
                List<Lead> leadList = [Select id, firstname,email from Lead where firstname IN:leadFname];
                Map<String ,Lead> mapNameWiseAccount = new Map<String,Lead>();
                For(Lead le: leadList)
                {
                    mapNameWiseAccount.put(le.firstname ,le);
                }
                
                For(Lead le : trigger.new)
                {
                    if(mapNameWiseAccount.containsKey(le.firstname))
                    {
                        if(le.email != null){
                            leadList[0].email = le.email;
                            le.Id = leadList[0].id ;
                            update leadList;
                            
                        }
                    }
                }
                
            }
            
            
            
        }
        
    }
}

SO from the code its updating the email field values for an existing recoord but at the same time its creating a new record as well and i needed to restrict the creation of a new record .
Any Suggestion would be helpfull!!!
Hello Developers, 
my task is whenever an account is created with the specific recordtype then I needed to create a task for that but exactly after the 30 mins of account creation time.



User-added image

In debug mode it seems like task is been created but when i will be searching for the task record its shows me specific error any suggestion would be apprechiable right now i will be debugging flow as System Admin only


User-added image
@AuraEnabled(cacheable=true)
    public static Account getAccRec(String accId){
        Account AccObj = new Account();
        AccObj = [select id,Floor_Plan_Providers__c	,Name,BillingStreet,BillingState,BillingCity,BillingCountry,BillingPostalCode from Account where id=:accId Limit 1];
        return AccObj;
        
    }
===================================================================


<template>
    <lightning-quick-action-panel header="Edit Fields Action">
        <lightning-record-edit-form record-id={recordId}
                                    object-api-name={objectApiName}
                                    onsuccess={handleSuccess}>
            <!--<lightning-input-field field-name="Name"></lightning-input-field>
            <lightning-input-field field-name="Phone"></lightning-input-field>-->
            <!--<lightning-output-field field-name="Floor_Plan_Providers__c"></lightning-output-field>
            <lightning-input-field field-name="Floor_Plan_Providers__c"> {toEmail}</lightning-input-field>-->
             
            <lightning-input type="text" label="Email" value = {toEmail}></lightning-input>
            
            <lightning-input type="text" label="Subject" value="FP_Lead_Email_Notification" ></lightning-input>
          

            <lightning-input-field  label = "CC"></lightning-input-field>

=================================================================

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import getAccRecord  from '@salesforce/apex/emailController.getAccRec';
export default class sendEmail extends LightningElement {
    @api recordId;
    accounts;
    toEmail;

    @wire (getRecord, {accId: '$recordId'})
    getAccRecs({error, data}){
        console.log(data);
        if(data){
            this.accounts = data;
            this.error = undefined;
            toEmail = accounts.Floor_Plan_Providers__c;


        }
        else if(error){
            this.accounts = undefined;
            this.error = error;
        }
        

    }

 
Hello developers ,
I had a controller class in which there is one method which fetcjh an account and return it . I had an action which invoke lwc component placed on lightning record page in which its open a pop up after clicking on action multiple fields appear where one imput  field in email in which it need to map the picklist fields value of a specific account.on that account there is picklist floor plan provider its value should be get mapped to an email input field 

User-added image






User-added image



Any help would be appreciated
Hello Developer, 
i had a usecase where on I needed to create a lightning button which should be present over account lightning record page and on click of button it should open modal where it sends an email but there should be one flield account name in the modal where it should fetch the current id account name should be populated. 
Since new to lwc needed support 
Hello Community Developers ,
I am working on one rest api service class which  will accept  payload from external system and send it to our salesforce and will created data in Salesforce.

 I am getting this issue while running my test classes.
Apex Class :-


@RestResource (urlMapping = '/createContact/*')
global with sharing class communityUsersWebService {
 @HttpPost
    global static ResponseWrapper createContacts(){
        Boolean success = false;
        String message = '';
        Set<Id> accountIds = new Set<Id>();
        List<Contact> newContactRecords = new List<Contact>();
        RestRequest request = RestContext.request;
        RestResponse response = RestContext.response;
        if(request != null){
            System.debug('request is not equal to null');
            Blob body = request.requestBody;
            String requestBody = body.toString();
            if(requestBody != null){
                try{
                    Map<String, Object> deserializeRequestBody = (Map<String , Object>)JSON.deserializeUntyped(requestBody);
                    System.debug(' deserializeRequestBody Map :-' +deserializeRequestBody);
                    Map<String , Object> storedeserializeRequestBody = new Map< String , Object>();
                    for(String s : deserializeRequestBody.keySet()){
                        storedeserializeRequestBody.put(s , deserializeRequestBody.get(s));
                        System.debug(' storedeserializeRequestBody Map :-' +storedeserializeRequestBody);
                    }
                    if(!storedeserializeRequestBody.isEmpty()){
                        String DDI_Industry_c = String.valueOf(storedeserializeRequestBody.get('DDI_Industry__c'));
                        String RecordTypeId =  String.valueOf(storedeserializeRequestBody.get('RecordTypeId'));
                        String Firstname =  String.valueOf(storedeserializeRequestBody.get('Firstname'));
                        String LastName = String.valueOf(storedeserializeRequestBody.get('Lastname'));
                        String Email = String.valueOf(storedeserializeRequestBody.get('Email'));
                        String DDI_Contact_Role_c =  String.valueOf(storedeserializeRequestBody.get('DDI_Contact_Role__c'));
                        String DDI_Decision_role_c =  String.valueOf(storedeserializeRequestBody.get('DDI_Decision_role__c'));
                        String Contact_Type_c =  String.valueOf(storedeserializeRequestBody.get('Contact_Type__c'));
                        String Account_Name_c  = String.valueOf(storedeserializeRequestBody.get('Account_Name__c'));
                        
                        List<Contact> getContacts = [Select id , FirstName , LastName , Email , RecordTypeId from Contact 
                                                     Where RecordTypeId =: RecordTypeId
                                                     AND FirstName =: Firstname
                                                     AND LastName =: LastName];
                        if(getContacts != null && getContacts.size() > 0){
                            System.debug('You Cannot Create Contacts due to Duplicacy !!!');
                            success = true;
                            message  = 'Contact creation is not Proceesed Succesfully since Duplicates Contacts in Salesforce ';
         
                               
                            
                        }
                        else{
                            List<Account> getAccounts = [Select id ,  Name   from Account Where Name=: Account_Name_c Limit 1];
                            if(getAccounts != null && getAccounts.size() > 0){
                                for(Account account : getAccounts){
                                    accountIds.add(account.Id);
                                    
                                }
                                
                            }
                            if(accountIds != null && accountIds.size() == 1 ){
                                Id mapToAccountId ;
                                for(Id id : accountIds){
                                    mapToAccountId = id;
                                }
                                Contact newContact = new Contact();
                                newContact.DDI_Industry__c = DDI_Industry_c;
                                newContact.RecordTypeId = RecordTypeId;
                                newContact.FirstName = Firstname;
                                newContact.LastName = Lastname;
                                newContact.Email = Email;
                                newContact.DDI_Contact_Role__c = DDI_Contact_Role_c;
                                newContact.DDI_Decision_role__c = DDI_Decision_role_c;
                                newContact.Contact_Type__c = Contact_Type_c;
                                newContact.AccountId = mapToAccountId;
                                //newContact.Account_Name__c = Account_Name_c;
                                newContactRecords.add(newContact);
                                
                            }
                            if(newContactRecords != null && newContactRecords.size() > 0){
                                insert newContactRecords;
                                success = true;
                                message =  'Contact creation request is processed Succcessfully !!!!';
                               
                            }
                            
                            
                        }
                        
                        
                        
                        
                    }
                    
                    
                }
                Catch(Exception ex){
                    System.debug('The Exception is : '+ex.getMessage());
                    success = true;
                    message = ex.getMessage();
                    
                }
            }
        }
        
        ResponseWrapper responseWrapper = new ResponseWrapper();
        responseWrapper.message = message ;
        responseWrapper.success = success;
        return responseWrapper;
        
    }
    
    
    global class ResponseWrapper{
           global String message ; 
           global Boolean success;
    }


}
 
Test Class :-


@isTest
public with sharing class communityUsersWebServiceTest {
    
    @isTest
    public static void testContactCreation(){
        Account account = new Account();
        account.name = 'Test Account';
        Id RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('DDI').getRecordTypeId();
        account.RecordTypeId = RecordTypeId;
        insert account;
        Contact contact = new Contact();
        contact.FirstName = 'Raghav';
        contact.LastName = 'Thakur';
        contact.Email = 'raghav.thakue+33@gmail.com';
        Id contactRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('DDI').getRecordTypeId();
        contact.RecordTypeId = contactRecordTypeId;
        contact.AccountId = account.Id;
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        req.requestURI = '/services/apexrest/subscriptionUpdate/';
        String jsonMessage = '{"DDI_Industry": "Other", "RecordTypeId": "0123g000000kDbrAAE", "Firstname": "Raghav", "Lastname": "Thakur", "Email": "raghav.thakue+33@gmail.com","DDI_Contact_Role__c": "Point of Contact","DDI_Decision_role__c": "Other", "Contact_Type__c": "Partner", "Account_Name__c": "'+account.Name+'" }';
        if(jsonMessage != null){
            req.requestBody = Blob.valueOf(jsonMessage);
            req.httpMethod = 'POST';
            RestContext.request = req;
            RestContext.response = res;
           
            
        }
        
         communityUsersWebService.createContacts();
        
        
        
    }

}

In my test class the line which i made as bold showing an issue !!

Any Help really thankfull !!!!
 
Hello Folks , 
    I will be working on one scenario where a case is been get created from one screen flow where there is one multiselect picklist fields  with the label state where end user can select multiple state value during the case creation . Now I need to create a child cases of the cases which is been created bu the screen flow.
So ideally one parent case is get created through screen flow where suppose state an end user selected is  AK, AL, CZ then the three child cases must be get created because  3 states is been selected  AK, AL, CZ

So 
Parent Case get created from screen flow and passing the case id from flow to apex class to create a no of child cases depend upon the number of state field values.
Code for creating a child Case 



public class createChildCase {
      @InvocableMethod
    public static void createChild(List<Id> caseIds){
        System.debug('createChildCaseInvoked');
        Case parentCase = [Select id, subject , description, DDI_States_Of_Interests__c from Case where id = : caseIds[0]];
         List<String> States = parentCase.DDI_States_Of_Interests__c.split(';');
        System.debug('States Size' +States.size() );
         List<Case> childCase = new List<Case>();
        for(integer i = 0; i< States.size(); i++ ){
            String state = States[i];
            System.debug('State :' +state);
             Case caseAL = new Case();
                         System.debug('@@');
                         caseAL.Subject = 'Sub Case for Different States';
                         System.debug('@@');
                         caseAL.ParentId = parentCase.Id;
                         System.debug('@@');
                         caseAL.RecordTypeId = '01223000000NZDEAA4';
                         System.debug('@@');
                         caseAl.DDI_States_Of_Interests__c = state;
                         //insert caseAK;
                         childCase.add(caseAL);
            
        }
         
       
                          
                          System.debug('@@' +childCase.size());
                         //System.debug('@@' +caseAL.Id);
          insert childCase;
                         //return childCase;
                         
        
    }

}
 
Test Class


@isTest
public class createChildCaseTest {
    
    @isTest
    public static void createChild(){
        Case cases = new Case();
        cases.CaseEmail__c= 'yadavsahil46623@gmail.com';
        cases.MultiSelect_State__c = 'AZ, AR, CA';
        cases.Subject = 'Case is been getting created';
        insert cases;
       
        List<Case> caseList = [Select Id, subject,CaseEmail__c, MultiSelect_State__c from Case where id =: cases.Id ];
        System.assertEquals('yadavsahil46623@gmail.com',cases.CaseEmail__c );
        
    }

}

Now how may i proceed futher not geting an idea please let me know if any comments 
How should i wrote a test class for this scenarios?
Hello Developers, 
my task is whenever an account is created with the specific recordtype then I needed to create a task for that but exactly after the 30 mins of account creation time.



User-added image

In debug mode it seems like task is been created but when i will be searching for the task record its shows me specific error any suggestion would be apprechiable right now i will be debugging flow as System Admin only


User-added image
Hello folks,
On Account object i have a object specific action with action type flow which basically invoke a scrreen flow at the backend.
I needed to make the action visible for 2 profile System Admin, Buyer Development for the account record whose recordtype is Buyer Account recordtype.

System Admin ----> Buyer Account RecordType ---> Buyer Account Page Layout WHere i placed an actions inside mobile and lightning experience.


Similarly,
Buyer Development Profile ----> Buyer Account RecordType ---> Buyer Development Page Layout WHere i placed an actions inside mobile and lightning experience.

Apart from that Lightning recod page in account object for both above profiles is Buyer Development Record Page where also I included the action.

So basically as an admin that action is visible but if i logged in a buyer development profile user i couldnt able to see the action which i created .
Any suggestion or solution would be very helpful !!!!
 
I have a scenario where i need a button on task record which should directly create a opportunity based on whoid of a task where whoid is Contact .
How could we achieve this, basically  I tried this using flows but i couldn't able to achieve at the moment if any help would be apprechiable.
 
As a buyer development member I want to bypass the account and contact creation screen to automated opportunity creation for leads with record type buyer development lead.

Acceptance Criteria:
If Campaign member is already a contact go right to opportunity.
Following information should be included in opportunity

Opportunity naming convention
Account Name - Campaign Name - Month

here basically while after creating a lead reords we have standard buttons covert it into acc, con, opp
but here buyer development is one of the profile .
If as a user i click on covert on leads record then it opens a standard page with acc, con, opp sections ,
but i wanted to custumize  any suggestions or help would be appreciable !!!
There is dicription field in case obj
where it contains 
Customer Name: Smith Ng Customer Email: smith.ng@.com
now my task is basically to get the get the name from yhe description field and populate to some other field in case obj
Just name that is Smith Ng 
any suggestions !!!!
String casedesc = caserec.Description;
                                String SuppliedName = casedesc.substringAfter('Name:');
                                System.debug('@@'+SuppliedName);
                                String sn = SuppliedName.substringBefore(' Custumer Email:');
                                
                                
                                 System.debug('@@'+sn);
                                //caserec.SuppliedName = SuppliedName;

 

Custumer Name:Abc Xyz
here i wanted basically to write the regex for validating the first name and last name 
Regex ('[Custumer Name]+[A-Za-z]+[]+[A-Za-z]+')
Here basically i wanted to know as there is a space in between of first name and lastname so how we can write the regex expression for space ?
Here I have a screen flow which basically creates a case records  whose owner is basically a queue suppose Support team queue now my task is to escalate the when the status field of the case object is havent been change from new to other status value after an hour it should be get escalated to other queue.
Now here my question is case escallation rule will help me on this scenario or is there any other way to escalate a case created from a flow ????

Also i created an ecalation rule but the case has not been escalated to other queue for the record created through flow as well i also tried to create a case record from case object then also escalation doesn't executed ... Any Suggestion or any other way please do let me know it would be more helpful.....
I have a flow in Sandbox but the issue is for one of the profile the flow is executing as expected but for other profile that flow does not executing flow user permisssion is also given for all the user lying under this 2 different profile and the error is "An unhandled fault has occurred in this flow An unhandled fault has occurred while processing the flow. Please contact your system administrator for more information." 

So any body could help me out what could be the best way to solve this error
So basiically i had a one outlook id specific to company account and i had a scenario in which suppose if any one mail is comming to this outlook id its should automatically converted as a records in salesforce .
with respect to gmail is seems to be fine but i want to do the same setup for outlook so ??..
Verify Email to Case Routing via Company mail .
But identify the steps needed to route the cases when we use a company account
 
The problem is in my dev Sandbox I have a lightning flows whose flows api version is 54.0 because its been recently created by me but I need to deploy that flows in QA enviroment  for testing purpose but faving the error while deployment that is The field apiVersion can't be "54" how could we overcome that? 
public class integrationLogBatchClass implements Database.Batchable <sObject> {
    /*
     * the start methods basically queried out a list of records on which futher
     * DML operations is been get executed
     */
    public Database.QueryLocator start(Database.BatchableContext bc){
        
        return Database.getQueryLocator([SELECT Id, Name, OwnerId, IsDeleted, CreatedDate, RecordTypeId, CreatedById, SystemModstamp, LastReferencedDate, Response_Body__c, Status__c, Transection_Id__c, CRC_Response_Body__c, IntegrationType__c, Endpoint_URL__c, Transaction_Type__c, Sent_To__c, Sent_From__c, Request_Body__c, LastViewedDate, LastModifiedById, LastModifiedDate FROM Integration_logs__c where CreatedDate = Today  ]);
        
    }
    
    /*
     * The execute method is entry point of execution for performing
     * DML operation in a batches or a small chunks of records
     * */
    public void execute(Database.BatchableContext bc, List<Integration_logs__c> scope){
        
        delete scope;
        
        /*
       for(Integration_logs__c il : scope){

             delete il;

           }
         */
    }
    
  
    /*
     * This is is the exit point for Batch Class Execution 
     * which is been executed onle once
     * */
    public void finish(Database.BatchableContext bc){
        System.debug('the finish method of integration Log object is invoked !!!');
    }

}

 
Batch Class

public class personBatch implements Database.Batchable<sObject>{
    
    public Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator([SELECT Id, CreatedDate, Name, Phone_No__c FROM Person__c Where CreatedDate = Today]);
        
    }
    
    public void execute(Database.BatchableContext bc, List<sObject> scope){
        for (sObject sc : Scope){
            delete sc;
        }
        
    }
    public void finish(Database.BatchableContext bc){
        System.debug('Finish method is get executed');
    }

}
====================================================================

Schedulable Class


public class personSchedule implements Schedulable {
    
    public void execute(SchedulableContext sc){
        personBatch pB = new personBatch();
        Database.executeBatch(pB,200 );
        
    }

}


=================================================================
Log Code


personSchedule pS = new personSchedule();
String cronExp = '00 00 5 * * ?';
String jobPerson= System.schedule('personScheduleJobs',cronExp,pS);
System.debug(+jobPerson);