+ Start a Discussion
akashakash 

Lead Status (Open - Not Contacted)

If the lead is still in the same condition (Open - Not Contacted) after 4 hours of lead creation, an email has to be sent to the owner of the lead and the manager of the owner in CC.

The below code works for sending emails to lead owner if he is an individual owner (sending Cc mail to Manager), same like that if lead owner is queue it is sending only to user mail not user's Cc manager.
 
should now send emails to individual owners, CC their managers, and all users in queues, including the CC to queue user managers.

Plz Provide solution.

public class LeadClass implements Database.Batchable<SObject> {

    // Start method for the batch job
    public Database.QueryLocator start(Database.BatchableContext context) {
        // Calculate the datetime four hours ago
        DateTime fourHoursAgo = DateTime.now().addHours(-4);

        // Retrieve the leads that meet the criteria
        return Database.getQueryLocator([
            SELECT Id, OwnerId, Owner.Email, Owner.Type, CreatedDate
            FROM Lead
            WHERE Status = 'Open - Not Contacted' AND CreatedDate >= :fourHoursAgo
        ]);
    }

    // Execute method for processing the batch
    public void execute(Database.BatchableContext context, List<Lead> scope) {
        // Create a map to store email messages
        Map<Id, Messaging.SingleEmailMessage> emailMap = new Map<Id, Messaging.SingleEmailMessage>();

        // Create a set to store owner IDs
        Set<Id> ownerIds = new Set<Id>();

        // Create a set to store queue IDs
        Set<Id> queueIds = new Set<Id>();

        // Iterate over the leads in the current batch
        for (Lead lead : scope) {
            if (lead.Owner.Type == 'User') {
                // Add the lead's owner ID to the set of owner IDs
                ownerIds.add(lead.OwnerId);
            } else if (lead.Owner.Type == 'Queue') {
                // Add the lead's owner ID to the set of queue IDs
                queueIds.add(lead.OwnerId);
            }
        }

        // Query the owners and their details using the owner IDs
        Map<Id, User> ownerMap = new Map<Id, User>([
            SELECT Id, Name, Email, ManagerId
            FROM User
            WHERE Id IN :ownerIds
        ]);

        // Create a set to store manager IDs
        Set<Id> managerIds = new Set<Id>();

        // Iterate over the owner records to collect manager IDs
        for (User owner : ownerMap.values()) {
            if (owner.ManagerId != null) {
                // Add the owner's manager ID to the set of manager IDs
                managerIds.add(owner.ManagerId);
            }
        }

        // Query the managers and their details using the manager IDs
        Map<Id, User> managerMap = new Map<Id, User>([
            SELECT Id, Name, Email
            FROM User
            WHERE Id IN :managerIds
        ]);

        // Iterate over the leads in the current batch
        for (Lead lead : scope) {
            if (lead.Owner.Type == 'User') {
                // Retrieve the lead's owner from the ownerMap
                User owner = ownerMap.get(lead.OwnerId);

                // Create an email message
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                // Set the recipient (owner's email address)
                email.setToAddresses(new List<String>{ owner.Email });

                // Add owner's manager's email to cc recipients if available
                if (owner.ManagerId != null && managerMap.containsKey(owner.ManagerId)) {
                    User manager = managerMap.get(owner.ManagerId);
                    if (manager != null && !String.isBlank(manager.Email)) {
                        email.setCcAddresses(new List<String>{ manager.Email });
                    }
                }

                // Set the email subject and body
                email.setSubject('Lead Still not actioned upon');
                email.setPlainTextBody('Dear ' + owner.Name + ',\n\n' +
                                       'This is a notification regarding the lead with the status "Open - Not Contacted" that was created within the last 4 hours.\n\n' +
                                       'Lead Record: ' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + lead.Id + '\n\n' +
                                       'Thank you.\n\n' +
                                       'Best Regards,\n' +
                                       'Your Company');

                // Add the email message to the map using the lead's owner ID as the key
                emailMap.put(lead.OwnerId, email);
            } else if (lead.Owner.Type == 'Queue') {
                // Retrieve the queue users associated with the lead's queue
                List<User> queueUsers = [SELECT Id, Name, Email, ManagerId
                                         FROM User
                                         WHERE Id IN (SELECT UserOrGroupId
                                                      FROM GroupMember
                                                      WHERE GroupId = :lead.OwnerId)];

                // Iterate over the queue users
                for (User queueUser : queueUsers) {
                    // Create an email message
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                    // Set the recipient (queue user's email address)
                    email.setToAddresses(new List<String>{ queueUser.Email });

                    // Add queue user's manager's email to cc recipients if available
                    if (queueUser.ManagerId != null && managerMap.containsKey(queueUser.ManagerId)) {
                        User manager = managerMap.get(queueUser.ManagerId);
                        if (manager != null && !String.isBlank(manager.Email)) {
                            email.setCcAddresses(new List<String>{ manager.Email });
                        }
                    }

                    // Set the email subject and body
                    email.setSubject('Lead Still not actioned upon');
                    email.setPlainTextBody('Dear ' + queueUser.Name + ',\n\n' +
                                           'This is a notification regarding the lead with the status "Open - Not Contacted" that was created within the last 4 hours.\n\n' +
                                           'Lead Record: ' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + lead.Id + '\n\n' +
                                           'Thank you.\n\n' +
                                           'Best Regards,\n' +
                                           'Your Company');

                    // Add the email message to the map using the queue user's ID as the key
                    emailMap.put(queueUser.Id, email);

                    // CC the manager of the queue user if available
                    if (queueUser.ManagerId != null && managerMap.containsKey(queueUser.ManagerId)) {
                        User manager = managerMap.get(queueUser.ManagerId);
                        if (manager != null && !String.isBlank(manager.Email)) {
                            emailMap.get(queueUser.Id).setCcAddresses(new List<String>{ manager.Email });
                        }
                    }
                }
            }
        }

        // Send the email messages
        Messaging.sendEmail(emailMap.values());
    }

    // Finish method for post-processing after the batch job finishes
    public void finish(Database.BatchableContext context) {
        // Do any post-processing after the batch job finishes
    }
}
Best Answer chosen by akash
Abdul KhatriAbdul Khatri
Hi Akash,

I have made changes to your code, tried simplifying it, and followed the best practice.

In your code, there is SOQL in the loop which is against the best practice. I have commented on the code

Here is the code
public class LeadClass implements Database.Batchable<SObject> {

    // Start method for the batch job
    public Database.QueryLocator start(Database.BatchableContext context) {
        // Calculate the datetime four hours ago
        DateTime fourHoursAgo = DateTime.now().addHours(-4);

        // Retrieve the leads that meet the criteria
        return Database.getQueryLocator([
            SELECT Id, OwnerId, Owner.Email, Owner.Type, CreatedDate
            FROM Lead
            WHERE Status = 'Open - Not Contacted' AND CreatedDate >= :fourHoursAgo
        ]);
    }

    // Execute method for processing the batch
    public void execute(Database.BatchableContext context, List<Lead> scope) {
        // Create a map to store email messages
        Map<Id, Messaging.SingleEmailMessage> emailMap = new Map<Id, Messaging.SingleEmailMessage>();

        // Create a set to store owner IDs
        Set<Id> ownerIds = new Set<Id>();

        // Create a set to store queue IDs
        Set<Id> queueIds = new Set<Id>();

        // Create a map to store List of Owner for every lead
        Map<Id, List<Id>> idLeadidUsersMap = new Map<Id, List<Id>>();
        
        // Iterate over the leads in the current batch
        for (Lead lead : scope) {
            if (lead.Owner.Type == 'User') {
                // Add the lead's owner ID to the set of owner IDs
                ownerIds.add(lead.OwnerId);
                idLeadidUsersMap.put(lead.Id, new List<Id>{lead.OwnerId});
            } else if (lead.Owner.Type == 'Queue') {
                // Add the lead's owner ID to the set of queue IDs
                queueIds.add(lead.OwnerId);
            }
        }
        
        // create map to store list of Queue users by Queue Id
        Map<Id, List<Id>> idMap = new Map<Id, List<Id>>();
        
        // create map of Group Member of the Queue Id 
        Map<Id, GroupMember> memberMap = new Map<Id, GroupMember>([SELECT UserOrGroupId, GroupId FROM GroupMember WHERE GroupId = :queueIds]);
        
        // iterate over Group Member to create Map list of Users in Queue
		for(GroupMember member : memberMap.values())
        {
            ownerIds.add(member.UserOrGroupId);
            List<Id> tempList = new List<Id>{member.UserOrGroupId};
            if(idMap.containsKey(member.GroupId))
            {
                tempList = idMap.get(member.GroupId);
                tempList.add(member.UserOrGroupId);
            }
            idMap.put(member.GroupId, tempList);
        }
        
		// iterate over lead records collect list of users per lead
        for (Lead lead : scope) {            
            if(lead.Owner.Type == 'Queue' && idMap != null && idMap.get(lead.OwnerId) != null) {               
                idLeadidUsersMap.put(lead.Id, idMap.get(lead.OwnerId));
            }
        }
        
        // Query the owners and their details using the owner IDs
        Map<Id, User> ownerMap = new Map<Id, User>([
            SELECT Id, Name, Email, ManagerId
            FROM User
            WHERE Id IN :ownerIds
        ]);

        // Create a set to store manager IDs
        Set<Id> managerIds = new Set<Id>();

        // Iterate over the owner records to collect manager IDs
        for (User owner : ownerMap.values()) {
            system.debug('User : ' + owner.ManagerId);
            if (owner.ManagerId != null) {
                // Add the owner's manager ID to the set of manager IDs
                managerIds.add(owner.ManagerId);
            }
        }

        // Query the managers and their details using the manager IDs
        Map<Id, User> managerMap = new Map<Id, User>([
            SELECT Id, Name, Email
            FROM User
            WHERE Id IN :managerIds
        ]);
        
        
        for(Lead lead : scope)
        {    
            for(Id iduser : idLeadidUsersMap.get(lead.Id))
            {
                
                // Retrieve the lead's owner from the ownerMap                
                User owner = ownerMap.get(idUser);
                system.debug('lead Id : ' + lead.Id + ' --  owner : ' + owner.Id + ' -- Manage : ' + owner.ManagerId);                
                // Create an email message
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                // Set the recipient (owner's email address)
                email.setToAddresses(new List<String>{ owner.Email });

                // Add owner's manager's email to cc recipients if available
                if (owner.ManagerId != null && managerMap.containsKey(owner.ManagerId)) {
                    User manager = managerMap.get(owner.ManagerId);
                    if (manager != null && !String.isBlank(manager.Email)) {
                        email.setCcAddresses(new List<String>{ manager.Email });
                        system.debug('email.setCcAddresses');
                    }
                }

                // Set the email subject and body
                email.setSubject('Lead Still not actioned upon');
                email.setPlainTextBody('Dear ' + owner.Name + ',\n\n' +
                                       'This is a notification regarding the lead with the status "Open - Not Contacted" that was created within the last 4 hours.\n\n' +
                                       'Lead Record: ' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + lead.Id + '\n\n' +
                                       'Thank you.\n\n' +
                                       'Best Regards,\n' +
                                       'Your Company');

                // Add the email message to the map using the lead's owner ID as the key
                emailMap.put(lead.OwnerId, email);                
                
            }
            
        }       
        

        // Iterate over the leads in the current batch
        /*
        for (Lead lead : scope) {
            if (lead.Owner.Type == 'User') {
                // Retrieve the lead's owner from the ownerMap
                User owner = ownerMap.get(lead.OwnerId);

                // Create an email message
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                // Set the recipient (owner's email address)
                email.setToAddresses(new List<String>{ owner.Email });

                // Add owner's manager's email to cc recipients if available
                if (owner.ManagerId != null && managerMap.containsKey(owner.ManagerId)) {
                    User manager = managerMap.get(owner.ManagerId);
                    if (manager != null && !String.isBlank(manager.Email)) {
                        email.setCcAddresses(new List<String>{ manager.Email });
                    }
                }

                // Set the email subject and body
                email.setSubject('Lead Still not actioned upon');
                email.setPlainTextBody('Dear ' + owner.Name + ',\n\n' +
                                       'This is a notification regarding the lead with the status "Open - Not Contacted" that was created within the last 4 hours.\n\n' +
                                       'Lead Record: ' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + lead.Id + '\n\n' +
                                       'Thank you.\n\n' +
                                       'Best Regards,\n' +
                                       'Your Company');

                // Add the email message to the map using the lead's owner ID as the key
                emailMap.put(lead.OwnerId, email);
            } else if (lead.Owner.Type == 'Queue') {
                // Retrieve the queue users associated with the lead's queue
                List<User> queueUsers = [SELECT Id, Name, Email, ManagerId
                                         FROM User
                                         WHERE Id IN (SELECT UserOrGroupId
                                                      FROM GroupMember
                                                      WHERE GroupId = :lead.OwnerId)];

                // Iterate over the queue users
                for (User queueUser : queueUsers) {
                    // Create an email message
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                    // Set the recipient (queue user's email address)
                    email.setToAddresses(new List<String>{ queueUser.Email });

                    // Add queue user's manager's email to cc recipients if available
                    if (queueUser.ManagerId != null && managerMap.containsKey(queueUser.ManagerId)) {
                        User manager = managerMap.get(queueUser.ManagerId);
                        if (manager != null && !String.isBlank(manager.Email)) {
                            email.setCcAddresses(new List<String>{ manager.Email });
                        }
                    }

                    // Set the email subject and body
                    email.setSubject('Lead Still not actioned upon');
                    email.setPlainTextBody('Dear ' + queueUser.Name + ',\n\n' +
                                           'This is a notification regarding the lead with the status "Open - Not Contacted" that was created within the last 4 hours.\n\n' +
                                           'Lead Record: ' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + lead.Id + '\n\n' +
                                           'Thank you.\n\n' +
                                           'Best Regards,\n' +
                                           'Your Company');

                    // Add the email message to the map using the queue user's ID as the key
                    emailMap.put(queueUser.Id, email);

                    // CC the manager of the queue user if available
                    if (queueUser.ManagerId != null && managerMap.containsKey(queueUser.ManagerId)) {
                        User manager = managerMap.get(queueUser.ManagerId);
                        if (manager != null && !String.isBlank(manager.Email)) {
                            emailMap.get(queueUser.Id).setCcAddresses(new List<String>{ manager.Email });
                        }
                    }
                }
            }
        }
		*/

        // Send the email messages
        Messaging.sendEmail(emailMap.values());
    }

    // Finish method for post-processing after the batch job finishes
    public void finish(Database.BatchableContext context) {
        // Do any post-processing after the batch job finishes
    }
}

I hope this also fixes your issue.

Regards,
Abdul Aziz Khatri
Travis Lee 1Travis Lee 1 
When checking this challenge, I get an error stating that the quickContact Lightning Component could not be found. Including screenshots of the steps I took thus far. Any advice would be appreciated!

1. The Lightning component must be named quickContact (this comes as part of the package, confirmed in picture below)
User-added image

2. Create a new action with Label Quick Contact and Name Quick_Contact on the Account object that invokes the quickContact component. (confirmed in picture below)
User-added image
3. Add the appropriate interfaces to the quickContact component. (Hint: there are two.) (used the implements force:lightningquickaction AND the force:hasrecordid on line 1, confirmed in picture below)
User-added image

4. Add the action to the Account Layout page layout. (added in picture below)
User-added image
Best Answer chosen by Travis Lee 1
SandhyaSandhya (Salesforce Developers) 
Hi,

Please check if you have connected to same DE org where you have done  your work in the trailhead.To do this click on" launch your hands on  org" and select the DE org or trailhead playground where you have your work and then check challenge.

 OR

Go to Trailhead Profile -- settings -- make the DE org which you have worked as default then check the challenge.

Please refer below link how to take challenges in trailhead.

https://force.desk.com/customer/portal/articles/2643793-trailhead-profile-signup-login-faq?b_id=13478

Hope this helps you!

Please mark it as Best Answer if my reply was helpful. It will make it available for other as the proper solution.
 
Thanks and Regards
Sandhya

 
EtienneCoutantEtienneCoutant 

Hi,

 

Can someone help, I keep getting the error:

System.DmlException: Insert failed. First exception on row 0 with id 00oS0000000AOgYIAW; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 

But I am pretty sure that there is no Id specified in my insert call.

Here is my code:

 

 

public PageReference save() { List<OpportunityLineItemSchedule> revenueSchedulesToUpdate = new List<OpportunityLineItemSchedule>(); List<OpportunityLineItemSchedule> revenueSchedulesToInsert = new List<OpportunityLineItemSchedule>(); for(revenueSchedulesDate revenueSchedulesDate:revenueSchedulesDates){ for(OpportunityLineItemSchedule revenueSchedule:revenueSchedulesDate.getRevenueSchedules()){ if(revenueSchedule.get('Id') == null) revenueSchedulesToInsert.add(revenueSchedule); else revenueSchedulesToUpdate.add(revenueSchedule); } if(revenueSchedulesToUpdate.size() > 0) update revenueSchedulesToUpdate; if(revenueSchedulesToInsert.size() > 0) insert revenueSchedulesToInsert; } return Page.revenueScheduleView2; }

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
wesnoltewesnolte

Hey

 

You're getting this error becuase you're adding items to list; inserting the list; adding more items to the list; and then trying to insert all the items you've already inserted and the new ones.

 

You shouldn't be performing DML inside a loop, although isn't directly causing your issue. Try this instead:

 

    public PageReference save() {
        List<OpportunityLineItemSchedule> revenueSchedulesToUpdate = new List<OpportunityLineItemSchedule>();
        List<OpportunityLineItemSchedule> revenueSchedulesToInsert = new List<OpportunityLineItemSchedule>();
       
        for(revenueSchedulesDate revenueSchedulesDate:revenueSchedulesDates){
            for(OpportunityLineItemSchedule revenueSchedule:revenueSchedulesDate.getRevenueSchedules()){
                if(revenueSchedule.get('Id') == null)
                    revenueSchedulesToInsert.add(revenueSchedule);
                else
                    revenueSchedulesToUpdate.add(revenueSchedule);
            }
        }
       
        update revenueSchedulesToUpdate;
        insert revenueSchedulesToInsert;       
       
        return Page.revenueScheduleView2;
    }

 

This will help with governor limits(although this still depends on the amoutn of data you work with), and will avoid your other issue.

 

Wes

 

 

daniela tobardaniela tobar 
Hi, good morning, I get the following error in the logs "Error message: List index out of bounds: 0" on line 52 of the code. 
This is the code of line 52, how can I validate or how can I fix the error?
 
new CampaignMembersService_SV().constructRegistrantCampaignMember(regData.optIn, newCon,ProfHubEmailSendSelector_SV.newInstance().selectByMasterLabel(new Set<String> {countryMap.get(regData.country)})[0].Communication_Optin__c, uow);

Thanks!
Best Answer chosen by daniela tobar
Prateek Prasoon 25Prateek Prasoon 25
The error message "List index out of bounds: 0" typically occurs when you try to access an element in a list using an index that is out of range. In this case, it seems like the error is happening on line 52 of your code.
To fix this error, you need to ensure that the list you're trying to access has at least one element before accessing it. Here's an updated version of your code that includes a check to validate the list before accessing its first element:
List<String> communicationOptinList = ProfHubEmailSendSelector_SV.newInstance().selectByMasterLabel(new Set<String>{countryMap.get(regData.country)});
if (communicationOptinList.size() > 0) {
  new CampaignMembersService_SV().constructRegistrantCampaignMember(regData.optIn, newCon, communicationOptinList[0].Communication_Optin__c, uow);
} else {
  // Handle the case when the list is empty, possibly by providing a default value or throwing an exception.
}

If you find this answer helpful,Please mark it as the best answer.
svidyansvidyan 

Hi,

 

I am following the book "Developement with the Force.com platform" by JasonOuelette.

When creating the Custom Objects, I did not check the box to be visible in a tab, and so I could not add this object to the Custom App I was creating. Now I have a created fields and relationships in the custom object. How do I add this Object to the Custom App?

 

thanks

Svidya

Best Answer chosen by Admin (Salesforce Developers) 
b-Forceb-Force

It looks you havent create custom Tabs while defining custom objects first you need to create custom Tab for new objects Creating Tab Setup -->App Set up---> Create---> Tabs Click on new Tab [drop down shows all untabed objects ] select your object, set Tab style , click Next select profiles Save Adding To App Setup -->App Set up---> Create---> Apps Click on edit, edit available tab section Save Done Thanks, Bala

rima khanrima khan 
Hi!
I registered with trailhead.
I’m an SDR looking to expand my Salesforce skill set. Let’s pretend I have none. Particularly looking for the basics around reporting, and any other trails that may be beneficial to spend some time with.
My goal is to have a competent understanding of SF to build my sales as I enter a closing role and the relevant tools in SF that will help me gain an advantage.
Thanks in advance!
Best Answer chosen by rima khan
manasa udupimanasa udupi
Hi Rima,

Below are few trailhead links, hope it helps:)

https://trailhead.salesforce.com/en/content/learn/modules/sales_admin_sales_reports_for_lex
https://trailhead.salesforce.com/en/content/learn/modules/sales-activity-analysis
UserSFDXUserSFDX 
Getting error while completing a trialhead challenge 
Error -> Challenge not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Contact_must_be_in_Account_ZIP_Code: [] 

Please help 
Best Answer chosen by UserSFDX
SubratSubrat (Salesforce Developers) 
Hello ,
Please note that Questions about how to pass Trailhead challenges are not on topic, because these challenges are intended to be independent demonstrations of your abilities.

Trailhead Help (https://trailhead.salesforce.com/en/help?support=home)can provide assistance for situations where Trailhead does not appear to be functioning correctly. You can reach out to them if this is the case.

Please close the thread by selecting as best answer so that we can keep our community clean.

Thank you
Eddie Grissett 11Eddie Grissett 11 
Is there a way to set up discussion forums on our salesforce community?
We would like our customers to be able to have discussions based on our own products?
Best Answer chosen by Eddie Grissett 11
SwethaSwetha (Salesforce Developers) 
HI Eddie,
 
You can enable "Allow discussion threads" as mentioned in  
https://help.salesforce.com/s/articleView?id=sf.networks_chatter_threaded_discussions_enable.htm&type=5

Also see https://salesforce.stackexchange.com/questions/375093/adding-a-forum-to-an-existing-experience-cloud-site

https://salesforce.stackexchange.com/questions/107645/is-it-possible-to-create-a-user-forum-in-communities


If this information helps, please mark the answer as best. Thank you
kavya mareedukavya mareedu 
Ans:  Text, Text Area, Text Area Long, Rich Text Area, URL. Is this is the right answer or is there something else????

13. Can we change the data type from Text to Auto Number for the Name when we already have?

Ans: I feel the answer is yes. If yes, please do let me know the explanation . If no, let me know the reason as well. Thanks guys. 

 
Best Answer chosen by kavya mareedu
sairam akella 11sairam akella 11
Yes.. We change the Data field type from name to autonumber . But the changes only apply to the new record not for the existing record.

As name is one of the default field that is created while creating object and also internally it is used for indexing Salesforce has given this permissiong to edit the data type of this field.
 
MasahiroYMasahiroY 
I've successfully plotted the accounts on Google Map with Lightning Component and it works in Sandbox...but don't know how to write a test code for the ApexClass.

I describe the codes below and hope anyone can help with the test code part. Thank you!

Component (MapNearbyAccount.cmp)
<aura:component controller="MapNearbyAccountController" implements="flexipage:availableForAllPageTypes,force:hasRecordId">
    <aura:attribute name="mapMarkers" type="Object"/>
    <aura:attribute name="selectedMarkerValue" type="String" />
    
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
    
    <div class="slds-box slds-theme--default">
        <lightning:map 
                       mapMarkers="{! v.mapMarkers }"
                       selectedMarkerValue="{!v.selectedMarkerValue}"
                       markersTitle="accounts nearby"
                       listView="auto"
                       showFooter="false"
                       onmarkerselect="{!c.handlerMarkerSelect}" />
    </div>
</aura:component>
Controller (MapNearbyAccount.js)
({
    init: function (cmp, event, helper) {
        var recordId = cmp.get("v.recordId");     
        var action = cmp.get("c.getAccounts");
        action.setParams({recordId :recordId});
        cmp.set('v.mapMarkers', [{location: {}}]);

        action.setCallback(this, function(response){
            
            var accounts = response.getReturnValue();
            var markers = [];
            for(var i = 0; i < accounts.length; i++){
                var acc = accounts[i];
                markers.push({
                    location: {
                        Country : acc.BillingCountry,
                        State : acc.BillingState,
                        City: acc.BillingCity,
                        Street: acc.BillingStreet
                    },
    
                    icon : "standard:account",
                    value: acc.Id,
                    title: acc.Name,
                    description:acc.Description
                });
            }
            
            if(markers.length != 0){
                cmp.set('v.mapMarkers', markers);
            }
        });

        $A.enqueueAction(action);
    },

    handlerMarkerSelect: function (cmp, event, helper) {
        console.log(event.getParam("selectedMarkerValue"));
    }
});
ApexClass (MapNearbyAccountController)
public class MapNearbyAccountController {
    @AuraEnabled
    public static List<Account> getAccounts(String BillingCity, String BillingState, String recordId){
        Account acct = [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet, Industry FROM Account WHERE Id =:recordId];
        
        return [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet,Description
                FROM Account 
                WHERE BillingState = :acct.BillingState AND BillingCity LIKE :('%' + acct.BillingCity + '%') AND Industry = :acct.Industry LIMIT 10];
    }
}
TestClass
@isTest
public class MapNearbyAccountControllerTest {
@isTest
    static void testMapNearbyAccountController() {
        Account acc1 = new Account();
        acc1.Name='acc1';
        acc1.BillingCity='Shibuya';
        acc1.BillingState='Tokyo';
        insert acc1;
        
        MapNearbyAccountController ctrl = new MapNearbyAccountController();
        
        Test.startTest();
            List<Account> getAccounts = ctrl.getAccounts();
            System.assertEquals(false,getAccounts.isEmpty());
        Test.stopTest();
    }
    
}
Best Answer chosen by MasahiroY
Maharajan CMaharajan C
Hi  Masahiro,

Please use the below test class:
 
@isTest
public class MapNearbyAccountControllerTest {
    @isTest
    static void testMapNearbyAccountController() {
        Account acc1 = new Account();
        acc1.Name='acc1';
        acc1.BillingCity='Shibuya';
        acc1.BillingState='Tokyo';
        insert acc1;
                
        Test.startTest();
        List<Account> getAccounts = MapNearbyAccountController.getAccounts('Shibuya','Tokyo',acc1.Id);
        System.assertEquals(false,getAccounts.isEmpty());
        Test.stopTest();
    }
    
}

Thanks,
Maharajan.C