Skip to main content

#BatchClass토론 중인 항목 0개

I wrote trigger on Account object, When I test the Trigger it was working fine when I entered the the record manually., But Trigger is not fired when the data is coming through integration even it passing all the criteria. Please help me why the trigger is not firing

. #BatchClass, #Batchapex, #Triggers,@developers

답변 7개
  1. 2025년 7월 22일 오전 10:57

    Hi Naveen, 

     

    Check the following things, 

     

    API User Permissions: Verify that the integration user has the necessary permissions to trigger the logic. 

    Integration Method: Ensure the API method used (like create, update) aligns with your trigger logic. 

     

    please mark this answer helpful if it solved your query.

     

     

     

     

     

    Arun Goel

    Oct 1, 2024, 7:40 PM

     

     

     

    Hi Naveen, 

      

    Check the following things, 

      

    API User Permissions: Verify that the integration user has the necessary permissions to trigger the logic. 

    Integration Method: Ensure the API method used (like create, update) aligns with your trigger logic. 

      

    please mark this answer helpful if it solved your query.

     

     

     

     

     

    Arun Goel

    Oct 1, 2024, 7:40 PM

     

     

     

    Hi Naveen, 

      

    Check the following things, 

      

    API User Permissions: Verify that the integration user has the necessary permissions to trigger the logic. 

    Integration Method: Ensure the API method used (like create, update) aligns with your trigger logic. 

      

    please mark this answer helpful if it solved your query.

0/9000
shubham kakade (UNCC) 님이 #Apex에 질문했습니다

In salesforce doc it's mentioned that for async we can fetch upto 10k records using querylocator. But in batch apex trail the statement says that "With the QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed and you can query up to 50 million records.".

Can some one explain me how is this possible.

 

#Apex  #Governerlimts  #Salesforce  #BatchClass

답변 3개
  1. Sushil Kumar (UKG) Forum Ambassador
    2024년 2월 26일 오후 1:27

    As i mentioned above, in Batch apex, there are two contexts, One is start method(Here i believe it should be able to fetch upto 50 million records). Execute Context - Here it should only be able to fetch upto 10k as you mentioned. 

0/9000

Hello Community,

 

What do you thing about the best naming conventions for batch jobs ?

 

#Salesforce Developer  #BatchClass  #Jobs

0/9000

global class GoogleRatingBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {

    

    private Map<Id, Double> accountIdToRatingMap = new Map<Id, Double>();

 

    global Database.QueryLocator start(Database.BatchableContext BC) {

        // Adjust this query to match your criteria for selecting accounts

        String query = 'SELECT Id, Name, inflooens__Google_Rating__c, inflooens__Review_Count__c FROM Account WHERE RecordType.Name = \'Business Account\'';

        return Database.getQueryLocator(query);

    }

 

    global void execute(Database.BatchableContext BC, List<Account> scope) {

        List<String> companyNames = new List<String>();

        List<Account> accountsToUpdate = new List<Account>();

 

        for (Account acc : scope) {

            companyNames.add(acc.Name);

        }

 

        Map<String, String> companyNameToPlaceIdMap = getPlaceIds(companyNames);

Double rating;

    integer reviewcount;

        for (Account acc : scope) {

            String companyName = acc.Name;

            String placeId = companyNameToPlaceIdMap.get(companyName);

 

            if (placeId != null) {

                accountIdToRatingMap.put(acc.Id, getGoogleRating(placeId));

            }

            rating = getGoogleRating(placeId);

            if (rating != null) {

                accountIdToRatingMap.put(acc.Id, rating);

            }

            

        }

 

        for (Account acc : scope) {

            if (accountIdToRatingMap.containsKey(acc.Id)) {

                acc.inflooens__Google_Rating__c  = String.valueOf(accountIdToRatingMap.get(acc.Id));

                acc.inflooens__Review_Count__c = rating.intValue(); // Convert to integer as needed

                accountsToUpdate.add(acc);

            }

        }

 

        // Update all modified accounts in a single DML operation

        if (!accountsToUpdate.isEmpty()) {

            update accountsToUpdate;

        }

    }

 

    global void finish(Database.BatchableContext BC) {

        // Execute any post-processing logic here

    }

 

    // Method to get Google Place IDs using Google Places API

  // Method to get Google Place IDs using Google Places API

private Map<String, String> getPlaceIds(List<String> companyNames) {

    Map<String, String> companyNameToPlaceIdMap = new Map<String, String>();

    String apiKey = getKey();//'AIzaSyCVUVkHPEjSJOpIu1lbirhvJRaqJ4hArr0';

 

    HttpRequest req = new HttpRequest();

    req.setMethod('GET');

    req.setEndpoint('https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=' + EncodingUtil.urlEncode(String.join(companyNames, ','), 'UTF-8') + '&inputtype=textquery&key=' + apiKey);

 

    Http http = new Http();

    HttpResponse res = http.send(req);

 

    if (res.getStatusCode() == 200) {

        String responseBody = res.getBody();

        Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(responseBody);

 

        if (jsonMap.containsKey('status') && jsonMap.get('status').equals('OK')) {

            List<Object> candidates = (List<Object>) jsonMap.get('candidates');

            for (Integer i = 0; i < Math.min(candidates.size(), companyNames.size()); i++) {

                Map<String, Object> candidate = (Map<String, Object>) candidates[i];

                String placeId = (String) candidate.get('place_id');

                companyNameToPlaceIdMap.put(companyNames[i], placeId);

            }

        } else {

            System.debug('Error in the response. Status: ' + jsonMap.get('status'));

        }

    } else {

        System.debug('Error: ' + res.getStatusCode() + ' ' + res.getStatus());

    }

 

    return companyNameToPlaceIdMap;

}

 

    // Method to get Google ratings using Google Places API

    private Double getGoogleRating(String placeId) {

        String apiKey = getKey();//'AIzaSyCVUVkHPEjSJOpIu1lbirhvJRaqJ4hArr0';

 

        HttpRequest req = new HttpRequest();

        req.setMethod('GET');

        req.setEndpoint('https://maps.googleapis.com/maps/api/place/details/json?placeid=' + placeId + '&fields=name,rating,reviewcount&key=' + apiKey);

 

        Http http = new Http();

        HttpResponse res = http.send(req);

 

        if (res.getStatusCode() == 200) {

            String responseBody = res.getBody();

            Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(responseBody);

 

            if (jsonMap.containsKey('status') && jsonMap.get('status').equals('OK')) {

                Map<String, Object> result = (Map<String, Object>) jsonMap.get('result');

                if (result != null && result.containsKey('rating')) {

                    return (Double) result.get('rating');

                }

                if(result!=null && result.containsKey('reviewcount')){

                    return (integer) result.get('reviewcount');

                }

            }

        }

 

        return null;

    }

   public static string getKey(){

        ApexTriggerSettings__c setting = ApexTriggerSettings__c.getValues('Inflooens Trigger Settings');

       

        String apiKey;// = 'AIzaSyCVUVkHPEjSJOpIu1lbirhvJRaqJ4hArr0';

        if(setting != NULL && setting.inflooens__Google_API_Key__c != NULL)

            apiKey=setting.inflooens__Google_API_Key__c;

        return apiKey;

    }

}

 

#BatchClass

답변 2개
  1. Eric Burté (DEVOTEAM) Forum Ambassador
    2024년 2월 22일 오전 6:49

    Hello @kaustubh chandratre, do you manage to get both calls done ? Does your second call's pass the good place id in parameter, and does the response body looks correct with rating inside ? Eric

0/9000

While executing it is showing no but none of debug log is visible in logs, In sandbox it is same but atlease contact is recieving an email but in production same code is executed but none of contact is getting an mail .

public class BirthDayNotificationBatchClass implements Database.Batchable<SObject>, Schedulable {

 

    // Add a class variable to store the OrgWideEmailAddressId

    private Id orgWideEmailAddressId;

 

    public BirthDayNotificationBatchClass() {

        // Initialize the OrgWideEmailAddressId in the constructor

        OrgWideEmailAddress[] owea = [SELECT Id FROM OrgWideEmailAddress WHERE Address = 'contact@appstrail.ae'];

        if (owea.size() > 0) {

            orgWideEmailAddressId = owea[0].Id;

        }

    }

 

    public Database.QueryLocator start(Database.BatchableContext BC) {

        System.debug('Inside Start');

        Integer currentMonth = Date.today().month(); // Get current month

        Integer nextMonth = (currentMonth == 12) ? 1 : currentMonth + 1; // Calculate next month

        Integer currentYear = Date.today().year();

        System.debug('Next Month: ' + nextMonth);

        String query = 'SELECT Id, Name, Email, Birthdate, Voucher_Code__c FROM Contact WHERE CALENDAR_MONTH(Birthdate) = :nextMonth';

        System.debug('Query: ' + query);

        return Database.getQueryLocator(query);

    }

 

    public void execute(Database.BatchableContext BC, List<Contact> scope) {

        // Id templateId =  [select id, name from EmailTemplate where developername = 'Dusoul_Monthly_Birthday_Greetings'].id;

        // Move the above line outside the loop to avoid unnecessary queries

 

        for (Contact c : scope) {

            Id templateId = [select id, name from EmailTemplate where developername = 'Dusoul_Monthly_Birthday_Greetings'].id;

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

            // Set the OrgWideEmailAddressId directly

            if (orgWideEmailAddressId != null) {

                mail.setOrgWideEmailAddressId(orgWideEmailAddressId);

            }

            mail.setToAddresses(new List<String>{c.Email});

            mail.setTargetObjectId(c.Id);

            mail.setTemplateId(templateId);

           

            Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

        }

    }

 

    public void finish(Database.BatchableContext BC) {

        System.debug('Batch execution finished.');

        // Optional: Add any cleanup or post-processing logic here

    }

 

    public void execute(SchedulableContext sc) {

        System.debug('Scheduled job started.');

        Database.executeBatch(this);

        System.debug('Scheduled job finished.');

    }

} #BatchClass #Send Email #Apex Class

답변 3개
0/9000