• Shiraz Hoda
  • NEWBIE
  • 190 Points
  • Member since 2017
  • Senior Consultant
  • Deloitte

  • Chatter
    Feed
  • 6
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 44
    Replies
I have a requirement to check if Case Owner ID is any Queue Id then change the Flag value to True.

I am strucked here how to compare Case Owner Id with List of Queue Id's.

Thanks!!
  • September 05, 2022
  • Like
  • 0
Hello, I have this class that is excecuted by a Batchable

And I getting the following error on the log: FATAL_ERROR System.LimitException: Too many queueable jobs added to the queue: 2

According to some posts that I've read, the issue is because I have system.enqueueJob(dvssService) inside a for loop.
 
public without sharing class OpportunityUpdate_WithDVSSCaseHelper {
    
    public static void UpdateOpptyStatusForOpptyWithDVSSCases_OnPegaSide(List<Opportunity> newOppty,Map<Id,Opportunity> oldOppty){
      
        Map<String,String> DvssCaseTypes = new Map<String,String>();
        DvssCaseTypes.put('DVSS AM', 'DVSSAM'); 
        DvssCaseTypes.put('DVSS CPE','DVSSCPE');
        DvssCaseTypes.put('DVSS DR','DVSSDR');
        DvssCaseTypes.put('DVSS RFP','DVSSRFP');
    
        List<Id> opptyIds = new List<Id>();
        List<Opportunity> opptiesToUpdateOnPega;       
        for(Opportunity oppty:newOppty){
            
            Opportunity oldOp = oldOppty.get(oppty.Id);
            if(oppty.StageName != oldOp.StageName && (oppty.StageName =='5 Closed Lost' || oppty.StageName =='5 Closed Disqualified' ) ){
                opptyIds.add(oppty.Id);
            }
            
        }   
        
        
        if(opptyIds.size() > 0){
            
            
            opptiesToUpdateOnPega = [select Id,StageName,(SELECT Case_Type__c,SWAP_Case_ID__c FROM SWAPS_Tracker__r where case_type__c in ('DVSS AM','DVSS CPE','DVSS DR','DVSS RFP')) 
                                     from Opportunity where Id in:opptyIds and Id in(select Opportunity_Name__c from SWAP_Tracker__c
                                                                                     where Opportunity_Name__c in:opptyIds and case_type__c in ('DVSS AM','DVSS CPE','DVSS DR','DVSS RFP')) ];

            
            if(opptiesToUpdateOnPega.size() > 0){
             
                               
                
                for(Opportunity opp:opptiesToUpdateOnPega){
                    
                    List<SWAP_Tracker__c> swTrack = opp.SWAPS_Tracker__r;
                    
                    system.debug('Oppt info LP>> ' + opp);
                    DateTime dtvar = null;
                    String Casetype='' ;
                    String CaseId='';
            
                    string OpptyStatus = opp.StageName;
                    
                    
                        for(SWAP_Tracker__c swt:swTrack){
                            
                            Casetype =  (DvssCaseTypes.get(swt.Case_Type__c) == null)?'':DvssCaseTypes.get(swt.Case_Type__c);
                            CaseId = (swt.SWAP_Case_ID__c ==null)?'':swt.SWAP_Case_ID__c;
     
                           
                DVSSOpptyStageUpdateService dvssService = new DVSSOpptyStageUpdateService();
                dvssService.Casetype = Casetype;
                dvssService.CaseId = CaseId;
                dvssService.OpptyStatus = OpptyStatus;
                
                system.enqueueJob(dvssService);                
                
            }  

            
            
        }


        
        
     }


   }

}
        
    public class DVSSOpptyStageUpdateService implements Queueable, Database.AllowsCallouts {
        

        public string Casetype{get;set;}
        public string CaseId{get;set;}
        public string OpptyStatus{get;set;}
        
        
        
        public void execute(QueueableContext context){
            
            

            
            system.debug('LL- Calling to update oppty stage');
            
            try{
                
            
                        Pega_CaseMiddleware.PegaCaseResult pagecaserslt = Pega_CaseMiddleware.UpdateDVSSCases_OpptyStatus(Casetype,CaseId,OpptyStatus);
                        
                        If(pagecaserslt.Error.size()>0){                
                            
                            system.debug('LL- error Message>>> ' + pagecaserslt.Error);
                            
                            
                            
                        }
                        else{
                            
                            system.debug('LL- Success Message>>> ' + pagecaserslt.CaseID);
                            
                        } 
                        
                
                
                
            }
            catch(Exception ex){
                
                system.debug('LL-Errrrror: ' + ex.getMessage()+ ' -- ' + ex.getStackTraceString() + '-- ' + ex.getLineNumber());
                insertLog('outbound', '-1', ex.getMessage()+ ex.getStackTraceString() + ex.getLineNumber(), 'DVSSOpptyStageUpdateService');    
                
            }
            
            
        }
        
        
    }
    
    public static void insertLog(String inboundOutbound, string requestID, string message, string method){
        
        try {
            
            Event_Log__c log = new Event_Log__c();
            
            log.Record_Id__c = requestID;
            log.Operation__c = inboundOutbound;
            log.sObject_Type__c ='SWAP Case';
            log.Message__c = 'pega_salesforce_inbound_outbound';
            log.Line_Number__c = method;
            log.Notes__c = message;
            
            insert log;
            
            
        } catch (Exception ex) {
            System.debug(ex.getMessage());
        }
        
        
    }
    
}
Is there any way to refactor this code?
I tried to create a list and then use it as an argument for the enqueueJob like this:
if(opptiesToUpdateOnPega.size() > 0){
             
                //List to collect the dvssService that are going to be enqueable-.
                List<DVSSOpptyStageUpdateService> dvssServiceLst = new List<DVSSOpptyStageUpdateService>();
                
                for(Opportunity opp:opptiesToUpdateOnPega){
                    
                    List<SWAP_Tracker__c> swTrack = opp.SWAPS_Tracker__r;
                    
                    system.debug('Oppt info LP>> ' + opp);
                    DateTime dtvar = null;
                    String Casetype='' ;
                    String CaseId='';
            
                    string OpptyStatus = opp.StageName;
                    
                    
                        for(SWAP_Tracker__c swt:swTrack){
                            
                            Casetype =  (DvssCaseTypes.get(swt.Case_Type__c) == null)?'':DvssCaseTypes.get(swt.Case_Type__c);
                            CaseId = (swt.SWAP_Case_ID__c ==null)?'':swt.SWAP_Case_ID__c;
     
                           
                DVSSOpptyStageUpdateService dvssService = new DVSSOpptyStageUpdateService();
                dvssService.Casetype = Casetype;
                dvssService.CaseId = CaseId;
                dvssService.OpptyStatus = OpptyStatus;
                
                dvssServiceLst.add(dvssService);
                
            }  

            
        }
        
        //Taking the enqueueJob out of the for loop-.
        system.enqueueJob(dvssServiceLst);


     }

But then I got an error (I can't remember the error exactly and my dev console is acting up so I can't replicate it) that said something like class List<DVSSOpptyStageUpdateService> needs to implemet queueable (I can't remember the error exactly and my dev console is acting up so I can't replicate it)

Any help with this, thank you very much.
 

I have created an Apex Trigger for a contact created using flow builder. I am creating it using Peson Account which creates a contact. My trigger is not working for this contact but it is working when i create a contact manually. 

User-added imageI have verifed the Flow and it is working fine, i can see the converted contacts in CRM. But the trigger doesn't work when the contact is created.

Only reason i can think of is Contact created from Person Account is not able to invoke the trigger but i am not sure.

Please Help

 

Hello - I have a for loop that adds a string and Id to a map. This field in the map Field_Agent__r. is a lookup field. The Id keeps coming back as null.

Any idea why? I verified that the Field_Agent__c and User__c is populated. 

Map<String, Id> fieldAgentUserIdMap = new Map<String, Id>(); //Hold Field Agent Username

for(Lead newLead : newlyCreateLeads){
           
                fieldAgentUserIdMap.put(newLead.Field_Agent_SOB__c, newLead.Field_Agent__r.User__c);

        }
        
        System.debug('Field agent in map '+fieldAgentUserIdMap);

DEBUG|Field agent in map {1234567=null}
Delete those Accounts who have more than 2 opportunities

If anyone Can write query for it.....
I got problem  While deleting Account...\
I have written code like below---
but when i  want to delete account at the end then it will not get deleted it is saying that account have cases...what to do now...how to process it forward from here in code for deleting these account records who has opportunities grater than 2 with them.....

  List<Account> aList = [Select Name,(Select Name from Opportunities) from Account];
         List<Account> delAcc = new List<Account>();
         for(Account a:alist)
         {
           if(a.Opportunities.size()>2)
           {
               system.debug(a.Opportunities.size());
               delacc.add(a);
           }
         }
         system.debug(delacc);
         delete delacc;
    } 
I have LOP__c field in Leaverequest__c object .
I need to  count this field in  records.

Thanks in advance
 
I would ike to establish a relationship where each role can be related to a single account but I can't find a way to do it.  Any suggestions would be greatly appreciated.  
Hi,
I can't create a quick action to run a flow from an Individual
Is this standard or am I missing something:
Flow mission from picklist
I am trying to create a JSON in the specified format below but i am not able to create the exact JSON format. i am using an apex class here to create the JSON format.

JSON Format --
{
  "records": [
    {
      "attributes": {
        "type": "Product2",
        "referenceId": "pref1"
      },
      "name": "Product 2",
      "SBQQ__Features__r": {
        "records": [
          {
            "attributes": {
              "type": "SBQQ__ProductFeature__c",
              "referenceId": "ref1"
            },
            "Name": "Feature1",
            "SBQQ__Number__c": 1,
            "SBQQ__MinOptionCount__c": 1
          }
        ]
      }
    },
    {
      "attributes": {
        "type": "Product2",
        "referenceId": "pref2"
      },
      "name": "Product 2",
      "SBQQ__Features__r": {
        "records": [
          {
            "attributes": {
              "type": "SBQQ__ProductFeature__c",
              "referenceId": "ref2"
            },
            "Name": "Feature1",
            "SBQQ__Number__c": 1,
            "SBQQ__MinOptionCount__c": 1
          }
        ]
      }
    }
  ]
}
Apex Class - 
public class JSonCLassForParent_Child {
    
    public List<Records_Z> records;

    public class SBQQ_Features_r {
        public List<Records> records;
    }

    public class Records_Z {
        public Attributes attributes;
        public String name;
        public SBQQ_Features_r SBQQ_Features_r;
    }

    public class Attributes {
        public String type;
        public String referenceId;
        
         public Attributes(String type,String referenceId){
            
            this.type = type;
            this.referenceId = referenceId;
        }
    }

    public class Records {
        public Attributes attributes;
        public String Name;
        public Decimal SBQQ_Number_c;
        public Decimal SBQQ_MinOptionCount_c;
    }


    public static String createJSONforParent_Child(List <Id> pIds){
        List<Product2> pList = [Select Id,Name from Product2 where Id = :pIds];
        System.debug(pList);
       List<Records> rec = new List<Records>();
       List<Records_Z> rz = new List<Records_Z>();
       Map<Id,Product2> aMap = new Map<Id,Product2>([Select Id,Name from Product2 where Id = :pIds]);
       System.debug('map is ' +aMap);
        List<SBQQ__ProductFeature__c> fList = [Select Id,Name,SBQQ__Number__c,SBQQ__MinOptionCount__c,SBQQ__ConfiguredSKU__c from SBQQ__ProductFeature__c where SBQQ__ConfiguredSKU__c In : aMap.keySet()];
        System.debug('feature is'+fList);
        
       // Map<Id,SBQQ__ProductFeature__c> productFeatureMap = new Map<Id,SBQQ__ProductFeature__c>();
        
        Integer count = 0;
        for(SBQQ__ProductFeature__c f : fList){
                        count++;
            if(aMap.containsKey(f.SBQQ__ConfiguredSKU__c)){
                
            Records r = new Records ();
            r.attributes = new Attributes('SBQQ_ProductFeature_c','ref'+count);
            r.Name = f.Name;
            r.SBQQ_Number_c = f.SBQQ__Number__c;
            r.SBQQ_MinOptionCount_c = f.SBQQ__MinOptionCount__c;
            rec.add(r);
           // productFeatureMap.put(f.SBQQ__ConfiguredSKU__c,f);
            }        
            
        }
        
        SBQQ_Features_r sbf = new SBQQ_Features_r();
        sbf.records = rec;
            
          Integer count2 = 0;
      for(Product2 a : pList){
            count2++;
            Records_Z r = new Records_Z();
             r.attributes = new Attributes('Product2','pref'+count2);
            r.name = a.Name;
            r.SBQQ_Features_r = sbf;
            //r.SBQQ_Features_r = productFeatureMap.get(a.Id);
            rz.add(r);
        }
        
        System.debug(rz);
        
         Map <String,Object> parentMap = new Map <String,Object> ();
         parentMap.put('records',rz);
         System.debug(JSON.serialize(parentMap));
        String jsonString = JSON.serialize(parentMap);
         String    finalJsonString = jsonString.replaceAll('_','__');
         System.debug(finalJsonString);
        return finalJsonString;
      
    }
}


 
Hi Folks,
 
Recently, we got a requirement of improving the performance of out future methods. There were few future methods which were taking around 22448 ms. 
I have implemented the solution for this below:
 
Whenever future methods are being called, publish a platform event. The platform event is subscribed by a flow which in turn calls that same future method, now converted as InvocableMethod.So, the callout which was occurring in the future method is now happening in the invocable method.
 
Please share your thoughts, if this solution is good and efficient?
I am new to SFDC writing SOQL, I need to build a query that will search for all the accounts that are prospects and have bene modified in the last x amount of time

Is there any Examples or place I can look as I know this is a simple process but have limited time and need to fix a issue ASAP and will be going back to do training 

Thank you
For Admin the field names are showing on upper side of the input boxes
User-added image

And for different users,  the field names are showing on the side of the input boxes.
User-added image
Please can anyone help me to find the root cause of this issue? Thanks in advance
I have built simple bar chart with ChartJS version v2.8.0, so now I am trying to display the data values on each bars using chartjs-plugin-datalabels v1.0.0 (https://github.com/chartjs/chartjs-plugin-datalabels/tags) plugins chartjs-plugin-datalabels I have loaded this plugin as below in the code and registered the plugin as specified in the plugin documentation (https://v1_0_0--chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#registration) but however the data values are not showing up on each bars.
Can anyone point out what am I missing here? that would be helpful
Here is the LwC code:
import { LightningElement,api, wire, track } from 'lwc';
import chartjs from '@salesforce/resourceUrl/chartjs_v280';
import ChartDataLabels from '@salesforce/resourceUrl/ChartjsPluginDataLabels';
import { loadScript } from 'lightning/platformResourceLoader';

export default class ChartDemocmp extends LightningElement {
    isChartJsInitialized;
    chartConfiguration;

    connectedCallback(){
        this.setData();
    }

    setData(){
        this.chartConfiguration = {
            type: 'bar',
    data: {
     labels: ["data1","data2","data3","data4","data5","data6","data7"],
     datasets: [
      {
       label: 'dataset',
       barPercentage: 0.5,
       barThickness: 6,
       maxBarThickness: 8,
       minBarLength: 2,
       backgroundColor: "blue",
       data: [65, 59, 80, 81, 56, 55, 40],
      },
     ],
    },
    plugins: [ChartDataLabels], //plugin register
    options: {
        resposive:true,
    },
   };
   console.log('chart data---> '+JSON.stringify(this.chartConfiguration));
}
    

    renderedCallback() {
        /*if (this.isChartJsInitialized) {
            return;
        }*/
        // load chartjs from the static resource
        Promise.all([
            loadScript(this, chartjs)
        ])
        .then(()=>{
            //load ChartDataLabels from the static resource
        Promise.all([
            loadScript(this, ChartDataLabels )
        ])
        .then(() => {
            console.log('Loaded');
            this.isChartJsInitialized = true;
            
            if(this.chart!= null || this.chart!=undefined){
                this.chart.destroy();//destory the chart once data is updated to show the new chart
                }
        const ctx = this.template.querySelector("canvas.barChart").getContext('2d');
       Chart.plugins.register(ChartDataLabels);
        this.chart = new window.Chart(ctx,JSON.parse(JSON.stringify(this.chartConfiguration)));
        //console.log('data chart');
        });
    })
        .catch(error => {
           console.error('error chart--> '+JSON.stringify(error))
            
        });
    
    }

    
    }
Here is the screen shot of bar chart below where the values are not getting displayed on each bars:
Here is the screen shot of bar chart where the values are not getting displayed on each bars:
when i am running my test method i am geting the below error:

System.DmlException: Process failed. First exception on row 0; first error: MANAGER_NOT_DEFINED, This approval request requires the next approver to be determined by the Manager field. This value is empty. Please contact your administrator for more information.: []

Apex class:
-------------
Public static void IncentiveCompAutoSubmitApproval(List<Case> tickets)
   {
       try{
       Map<ID, RecordType> recordTypeMap = New Map<ID, RecordType>([Select ID, Name From RecordType Where sObjectType = 'Case']);
       set<Id> ticketId = new set<Id>();
       Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
       for(Case cs : tickets)
       {  if(recordTypeMap.get(cs.recordTypeID).name.containsIgnoreCase('Incentive Compensation Request')&& cs.Status =='open'&& cs.managerid__c != null)
          {
              req1.setComments('Submitting request for approval.');
              req1.setObjectId(cs.Id);
              req1.setSubmitterId(UserInfo.getUserId());
              req1.setProcessDefinitionNameOrId('Incentive_Compensation_Tier_1_Approvals');
              req1.setSkipEntryCriteria(true);
                  system.debug('test111 ' + cs.managerid__c);
             Approval.ProcessResult result = Approval.process(req1);
              system.debug('test222 ' + cs.managerid__c);
          }    
       }
       }catch(QueryException qe){
            system.debug('QueryException: '+qe);
        }
            catch(Exception e){
                System.debug('Exception caught: ' + e.getMessage());
            }
   }

Test Method
------------------
@isTest static void IncentiveCompAutoSubmitApprovalTest()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
      Userrole objr = [SELECT Id FROM UserRole WHERE Name = 'Global Administrator' LIMIT 1];
       User thisUser = new User(Alias = 'standt', Email='contractdesk@testorg.com', 
                                 EmailEncodingKey='UTF-8', LastName='contractdesk', LanguageLocaleKey='en_US', 
                                 LocaleSidKey='en_US', ProfileId = p.Id,UserRoleId = objr.Id,
                                 TimeZoneSidKey='America/Los_Angeles', UserName='contractdesk@testorg.com');
        TestDataBuilder testBuilder = new TestDataBuilder();
        //insert manager
        User usrManager             = new User();
        usrManager          = testBuilder.dummyUser(0);
        usrManager.UserRoleId = objr.Id;
        insert usrManager; 
        //Insert User
        User usr                = new User();
        usr             = testBuilder.dummyUser(1);
        usr.ManagerId   = usrManager.Id;
        usr.UserRoleId = objr.Id;
        
        insert usr;
      
      System.runAs(thisUser){
      List<case> caseList = new List<case>();
        //insert Case
        Case cse                    = new Case();
        cse.RecordTypeId    = eUiteroRecordTypeId1;
        cse.Status='Open';
        cse.Type_of_Credit__c='Internal';
        cse.Reason_for_Credit__c='Staff Discount Coupon';
        cse.Order_Type__c='invisalign';
        cse.Subject='Testing';
        cse.Invoice_Number__c='1234567891';
        cse.Amount_of_credit__c=10;
        cse.Order_type__c='webstore';
        cse.Sales_Order_Number__c='123456';
        //cse.managerid__c = usr.ManagerId;
      insert cse;
       Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
          req1.setComments('Submitting request for approval.');
              req1.setObjectId(cse.Id);
              req1.setSubmitterId(UserInfo.getUserId());
              req1.setProcessDefinitionNameOrId('Incentive_Compensation_Tier_1_Approvals');
                req1.setNextApproverIds(new Id[] {usr.ManagerId});
              req1.setSkipEntryCriteria(true);
          
          Approval.ProcessResult result1 = Approval.process(req1);
    }
    }

Thanks!!
  • September 12, 2022
  • Like
  • 0
Hell all,
I am trying to figure out how to share a map between my main Class and a utility Class.

Main Class
global void Update( SObject oldSo, SObject newSo ){ 

public static Map<Id, SObject> updateMap = new Map<Id, SObject>();

record__c newRecord= ( record__c ) newSo;
newAccount = newRecord.Account

utilClass.updateRecord(newRecord, newAccount)
}

if( !updateMap.isEmpty() && Trigger.isUpdate && Trigger.isAfter ){
       List<SObject> updateList = updateMap.values();
       updateList.sort();
       List<Database.SaveResult> results = Database.update( updateList, false);
}


Util Class
public void updateRecord(record__c  newRecord, Account newAccount){
        if(newAccount != null && newRecord != null){
            newAccount.isAcount =  true;
            updateMap.put(newAccount.Id, newAccount);
        }
        return updateMap;
    }

What is the best option for passing the updateMap from the util class back to the main class?  Any help is appreciated.

Cheers,
P
  • September 08, 2022
  • Like
  • 0
Whenever trying to execute the below code I am getting the error:


global class batchclass implements Database.Batchable<sObject>,Database.Stateful{
    global integer countopp;
    global Decimal sumamount;
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query='Select id, Customer_segment__c ,(select accountid,amount,Stagename,Createddate from Opportunities) from Account Limit 500';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> lstacc)
    {
         AggregateResult[] gr= [SELECT Accountid,SUM(Amount) optyamt,Count(Id) cid FROM Opportunity Where Accountid IN:lstacc Group by Accountid];
    
    for(AggregateResult ag:gr){
        sumamount = (Decimal)ag.get('optyamt');
        countopp=(integer)ag.get('cid');
    }

        for(account acc:lstacc){
            if(sumamount<50000 && countopp>1){
                        acc.Customer_segment__c = 'Hot';
            }
            else if(sumamount>=50000 && countopp>1){
                        acc.Customer_segment__c = 'Medium';
            }
             else{
            acc.Customer_segment__c = 'Low';
        }
        update lstacc;
    }
    }
    global void finish(Database.BatchableContext BC){
        system.debug('finish'); 
    }
}

We have a lightning component and we are trying to render this to a specific user using the user's profile section in salesforce org.

Is there a possible way, so we can provide the access to a specific user?